[7695] Fixed typo & -> &&
[AHbot.git] / src / game / Unit.cpp
blobdbf482bbb5bbf1df90a1903c7d49a4de88ee6427
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(pVictim->GetTypeId() == TYPEID_PLAYER && GetTypeId() == TYPEID_PLAYER)
501 if(((Player*)pVictim)->InBattleGround())
503 Player *killer = ((Player*)this);
504 if(killer != ((Player*)pVictim))
505 if(BattleGround *bg = killer->GetBattleGround())
506 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
510 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
511 ((Creature*)pVictim)->SetLootRecipient(this);
513 if (health <= damage)
515 DEBUG_LOG("DealDamage: victim just died");
517 // find player: owner of controlled `this` or `this` itself maybe
518 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
520 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
521 player = ((Creature*)pVictim)->GetLootRecipient();
522 // Reward player, his pets, and group/raid members
523 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
524 if(player && player!=pVictim)
526 player->RewardPlayerAndGroupAtKill(pVictim);
527 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
530 DEBUG_LOG("DealDamageAttackStop");
532 // stop combat
533 pVictim->CombatStop();
534 pVictim->getHostilRefManager().deleteReferences();
536 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
538 // if talent known but not triggered (check priest class for speedup check)
539 Aura* spiritOfRedemtionTalentReady = NULL;
540 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
541 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
543 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
544 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
546 if((*itr)->GetSpellProto()->SpellIconID==1654)
548 spiritOfRedemtionTalentReady = *itr;
549 break;
554 DEBUG_LOG("SET JUST_DIED");
555 if(!spiritOfRedemtionTalentReady)
556 pVictim->setDeathState(JUST_DIED);
558 DEBUG_LOG("DealDamageHealth1");
560 if(spiritOfRedemtionTalentReady)
562 // save value before aura remove
563 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
564 if(!ressSpellId)
565 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
567 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
568 pVictim->RemoveAllAurasOnDeath();
570 // restore for use at real death
571 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
573 // FORM_SPIRITOFREDEMPTION and related auras
574 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
576 else
577 pVictim->SetHealth(0);
579 // remember victim PvP death for corpse type and corpse reclaim delay
580 // at original death (not at SpiritOfRedemtionTalent timeout)
581 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
582 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
584 // Call KilledUnit for creatures
585 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
586 ((Creature*)this)->AI()->KilledUnit(pVictim);
588 // achievement stuff
589 if (pVictim->GetTypeId() == TYPEID_PLAYER)
591 if (GetTypeId() == TYPEID_UNIT)
592 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
593 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
594 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
597 // 10% durability loss on death
598 // clean InHateListOf
599 if (pVictim->GetTypeId() == TYPEID_PLAYER)
601 // only if not player and not controlled by player pet. And not at BG
602 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
604 DEBUG_LOG("We are dead, loosing 10 percents durability");
605 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
606 // durability lost message
607 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
608 ((Player*)pVictim)->GetSession()->SendPacket(&data);
611 else // creature died
613 DEBUG_LOG("DealDamageNotPlayer");
614 Creature *cVictim = (Creature*)pVictim;
616 if(!cVictim->isPet())
618 cVictim->DeleteThreatList();
619 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
621 // Call creature just died function
622 if (cVictim->AI())
623 cVictim->AI()->JustDied(this);
625 // Dungeon specific stuff, only applies to players killing creatures
626 if(cVictim->GetInstanceId())
628 Map *m = cVictim->GetMap();
629 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
630 // TODO: do instance binding anyway if the charmer/owner is offline
632 if(m->IsDungeon() && creditedPlayer)
634 if(m->IsRaid() || m->IsHeroic())
636 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
637 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
639 else
641 // the reset time is set but not added to the scheduler
642 // until the players leave the instance
643 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
644 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
645 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
651 // last damage from non duel opponent or opponent controlled creature
652 if(duel_hasEnded)
654 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
655 Player *he = (Player*)pVictim;
657 assert(he->duel);
659 he->duel->opponent->CombatStopWithPets(true);
660 he->CombatStopWithPets(true);
662 he->DuelComplete(DUEL_INTERUPTED);
665 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
666 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
668 Player *killed = ((Player*)pVictim);
669 if(BattleGround *bg = killed->GetBattleGround())
670 if(player)
671 bg->HandleKillPlayer(killed, player);
672 //later we can add support for creature->player kills here i'm
673 //not sure, but i guess those kills also get counted in av
674 //else if(GetTypeId() == TYPEID_UNIT)
675 // bg->HandleKillPlayer(killed,(Creature*)this);
678 else // if (health <= damage)
680 DEBUG_LOG("DealDamageAlive");
682 pVictim->ModifyHealth(- (int32)damage);
684 if(damagetype != DOT)
686 if(!getVictim())
688 // if not have main target then attack state with target (including AI call)
689 //start melee attacks only after melee hit
690 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
693 // if damage pVictim call AI reaction
694 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
695 ((Creature*)pVictim)->AI()->AttackedBy(this);
698 // polymorphed and other negative transformed cases
699 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
700 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
702 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
704 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
705 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
707 if (pVictim->GetTypeId() != TYPEID_PLAYER)
709 if(spellProto && IsDamageToThreatSpell(spellProto))
710 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
711 else
712 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
714 else // victim is a player
716 // Rage from damage received
717 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
719 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
720 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
723 // random durability for items (HIT TAKEN)
724 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
726 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
727 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
731 if(GetTypeId()==TYPEID_PLAYER)
733 // random durability for items (HIT DONE)
734 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
736 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
737 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
741 // TODO: Store auras by interrupt flag to speed this up.
742 AuraMap& vAuras = pVictim->GetAuras();
743 for (AuraMap::iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
745 const SpellEntry *se = i->second->GetSpellProto();
746 next = i; ++next;
747 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
748 continue;
749 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
751 bool remove = true;
752 if (se->procFlags & (1<<3))
754 if (!roll_chance_i(se->procChance))
755 remove = false;
757 if (remove)
759 pVictim->RemoveAurasDueToSpell(i->second->GetId());
760 // FIXME: this may cause the auras with proc chance to be rerolled several times
761 next = vAuras.begin();
766 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
768 if( damagetype != DOT )
770 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
772 // skip channeled spell (processed differently below)
773 if (i == CURRENT_CHANNELED_SPELL)
774 continue;
776 if(Spell* spell = pVictim->m_currentSpells[i])
777 if(spell->getState() == SPELL_STATE_PREPARING)
779 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
780 pVictim->InterruptSpell(i);
781 else
782 spell->Delayed();
787 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
789 if (spell->getState() == SPELL_STATE_CASTING)
791 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
792 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
794 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
795 spell->DelayedChannel();
797 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
799 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
800 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
803 else if (spell->getState() == SPELL_STATE_DELAYED)
804 // break channeled spell in delayed state on damage
806 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
807 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
812 // last damage from duel opponent
813 if(duel_hasEnded)
815 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
816 Player *he = (Player*)pVictim;
818 assert(he->duel);
820 he->SetHealth(1);
822 he->duel->opponent->CombatStopWithPets(true);
823 he->CombatStopWithPets(true);
825 he->CastSpell(he, 7267, true); // beg
826 he->DuelComplete(DUEL_WON);
830 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
832 return damage;
835 void Unit::CastStop(uint32 except_spellid)
837 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
838 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
839 InterruptSpell(i,false);
842 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
844 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
846 if(!spellInfo)
848 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
849 return;
852 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
855 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
857 if(!spellInfo)
859 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
860 return;
863 if (castItem)
864 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
866 if(!originalCaster && triggeredByAura)
867 originalCaster = triggeredByAura->GetCasterGUID();
869 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
871 SpellCastTargets targets;
872 targets.setUnitTarget( Victim );
873 spell->m_CastItem = castItem;
874 spell->prepare(&targets, triggeredByAura);
877 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
879 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
881 if(!spellInfo)
883 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
884 return;
887 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
890 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)
892 if(!spellInfo)
894 sLog.outError("CastCustomSpell: unknown spell");
895 return;
898 if (castItem)
899 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
901 if(!originalCaster && triggeredByAura)
902 originalCaster = triggeredByAura->GetCasterGUID();
904 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
906 if(bp0)
907 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
909 if(bp1)
910 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
912 if(bp2)
913 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
915 SpellCastTargets targets;
916 targets.setUnitTarget( Victim );
917 spell->m_CastItem = castItem;
918 spell->prepare(&targets, triggeredByAura);
921 // used for scripting
922 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
924 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
926 if(!spellInfo)
928 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()));
929 return;
932 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
935 // used for scripting
936 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
938 if(!spellInfo)
940 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
941 return;
944 if (castItem)
945 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
947 if(!originalCaster && triggeredByAura)
948 originalCaster = triggeredByAura->GetCasterGUID();
950 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
952 SpellCastTargets targets;
953 targets.setDestination(x, y, z);
954 spell->m_CastItem = castItem;
955 spell->prepare(&targets, triggeredByAura);
958 // Obsolete func need remove, here only for comotability vs another patches
959 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
961 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
962 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
963 CalculateSpellDamage(&damageInfo, damage, spellInfo);
964 SendSpellNonMeleeDamageLog(&damageInfo);
965 DealSpellDamage(&damageInfo, true);
966 return damageInfo.damage;
969 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
971 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
972 Unit *pVictim = damageInfo->target;
974 if (damage < 0)
975 return;
977 if(!this || !pVictim)
978 return;
979 if(!this->isAlive() || !pVictim->isAlive())
980 return;
982 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
983 // Check spell crit chance
984 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
985 bool blocked = false;
986 // Per-school calc
987 switch (spellInfo->DmgClass)
989 // Melee and Ranged Spells
990 case SPELL_DAMAGE_CLASS_RANGED:
991 case SPELL_DAMAGE_CLASS_MELEE:
993 // Physical Damage
994 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
996 //Calculate armor mitigation
997 damage = CalcArmorReducedDamage(pVictim, damage);
998 // Get blocked status
999 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1001 // Magical Damage
1002 else
1004 // Calculate damage bonus
1005 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1007 if (crit)
1009 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1011 // Calculate crit bonus
1012 uint32 crit_bonus = damage;
1013 // Apply crit_damage bonus for melee spells
1014 if(Player* modOwner = GetSpellModOwner())
1015 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1016 damage += crit_bonus;
1018 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1019 int32 critPctDamageMod=0;
1020 if(attackType == RANGED_ATTACK)
1021 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1022 else
1024 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1025 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1027 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1028 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1030 if (critPctDamageMod!=0)
1031 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1033 // Resilience - reduce crit damage
1034 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1035 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1037 // Spell weapon based damage CAN BE crit & blocked at same time
1038 if (blocked)
1040 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1041 if (damage < damageInfo->blocked)
1042 damageInfo->blocked = damage;
1043 damage-=damageInfo->blocked;
1046 break;
1047 // Magical Attacks
1048 case SPELL_DAMAGE_CLASS_NONE:
1049 case SPELL_DAMAGE_CLASS_MAGIC:
1051 // Calculate damage bonus
1052 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1053 // If crit add critical bonus
1054 if (crit)
1056 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1057 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1058 // Resilience - reduce crit damage
1059 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1060 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1063 break;
1066 // Calculate absorb resist
1067 if(damage > 0)
1069 // lookup absorb/resist ignore auras on caster for spell
1070 bool ignore = false;
1071 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1072 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1073 if ((*i)->isAffectedOnSpell(spellInfo))
1075 ignore = true;
1076 break;
1079 if (!ignore)
1081 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1082 damage-= damageInfo->absorb + damageInfo->resist;
1085 else
1086 damage = 0;
1087 damageInfo->damage = damage;
1090 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1092 if (damageInfo==0)
1093 return;
1095 Unit *pVictim = damageInfo->target;
1097 if(!this || !pVictim)
1098 return;
1100 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1101 return;
1103 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1104 if (spellProto == NULL)
1106 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1107 return;
1110 //You don't lose health from damage taken from another player while in a sanctuary
1111 //You still see it in the combat log though
1112 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1114 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1115 if(area && area->flags & 0x800) //sanctuary
1116 return;
1119 // Call default DealDamage
1120 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1121 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1124 //TODO for melee need create structure as in
1125 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1127 damageInfo->attacker = this;
1128 damageInfo->target = pVictim;
1129 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1130 damageInfo->attackType = attackType;
1131 damageInfo->damage = 0;
1132 damageInfo->cleanDamage = 0;
1133 damageInfo->absorb = 0;
1134 damageInfo->resist = 0;
1135 damageInfo->blocked_amount = 0;
1137 damageInfo->TargetState = 0;
1138 damageInfo->HitInfo = 0;
1139 damageInfo->procAttacker = PROC_FLAG_NONE;
1140 damageInfo->procVictim = PROC_FLAG_NONE;
1141 damageInfo->procEx = PROC_EX_NONE;
1142 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1144 if(!this || !pVictim)
1145 return;
1146 if(!this->isAlive() || !pVictim->isAlive())
1147 return;
1149 // Select HitInfo/procAttacker/procVictim flag based on attack type
1150 switch (attackType)
1152 case BASE_ATTACK:
1153 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1154 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1155 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1156 break;
1157 case OFF_ATTACK:
1158 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1159 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1160 damageInfo->HitInfo = HITINFO_LEFTSWING;
1161 break;
1162 case RANGED_ATTACK:
1163 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1164 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1165 damageInfo->HitInfo = 0x08;// test
1166 break;
1167 default:
1168 break;
1171 // Physical Immune check
1172 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1174 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1175 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1177 damageInfo->procEx |=PROC_EX_IMMUNE;
1178 damageInfo->damage = 0;
1179 damageInfo->cleanDamage = 0;
1180 return;
1182 damage += CalculateDamage (damageInfo->attackType, false);
1183 // Add melee damage bonus
1184 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1185 // Calculate armor reduction
1186 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1187 damageInfo->cleanDamage += damage - damageInfo->damage;
1189 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1191 // Disable parry or dodge for ranged attack
1192 if(damageInfo->attackType == RANGED_ATTACK)
1194 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1195 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1198 switch(damageInfo->hitOutCome)
1200 case MELEE_HIT_EVADE:
1202 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1203 damageInfo->TargetState = VICTIMSTATE_EVADES;
1205 damageInfo->procEx|=PROC_EX_EVADE;
1206 damageInfo->damage = 0;
1207 damageInfo->cleanDamage = 0;
1208 return;
1210 case MELEE_HIT_MISS:
1212 damageInfo->HitInfo |= HITINFO_MISS;
1213 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1215 damageInfo->procEx|=PROC_EX_MISS;
1216 damageInfo->damage = 0;
1217 damageInfo->cleanDamage = 0;
1218 break;
1220 case MELEE_HIT_NORMAL:
1221 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1222 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1223 break;
1224 case MELEE_HIT_CRIT:
1226 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1227 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1229 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1230 // Crit bonus calc
1231 damageInfo->damage += damageInfo->damage;
1232 int32 mod=0;
1233 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1234 if(damageInfo->attackType == RANGED_ATTACK)
1235 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1236 else
1238 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1239 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1242 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1244 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1245 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1246 if (mod!=0)
1247 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1249 // Resilience - reduce crit damage
1250 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1252 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1253 damageInfo->damage -= resilienceReduction;
1254 damageInfo->cleanDamage += resilienceReduction;
1256 break;
1258 case MELEE_HIT_PARRY:
1259 damageInfo->TargetState = VICTIMSTATE_PARRY;
1260 damageInfo->procEx|=PROC_EX_PARRY;
1261 damageInfo->cleanDamage += damageInfo->damage;
1262 damageInfo->damage = 0;
1263 break;
1265 case MELEE_HIT_DODGE:
1266 damageInfo->TargetState = VICTIMSTATE_DODGE;
1267 damageInfo->procEx|=PROC_EX_DODGE;
1268 damageInfo->cleanDamage += damageInfo->damage;
1269 damageInfo->damage = 0;
1270 break;
1271 case MELEE_HIT_BLOCK:
1273 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1274 damageInfo->HitInfo |= HITINFO_BLOCK;
1275 damageInfo->procEx|=PROC_EX_BLOCK;
1276 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1277 if (damageInfo->blocked_amount >= damageInfo->damage)
1279 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1280 damageInfo->blocked_amount = damageInfo->damage;
1282 damageInfo->damage -= damageInfo->blocked_amount;
1283 damageInfo->cleanDamage += damageInfo->blocked_amount;
1284 break;
1286 case MELEE_HIT_GLANCING:
1288 damageInfo->HitInfo |= HITINFO_GLANCING;
1289 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1290 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1291 float reducePercent = 1.0f; //damage factor
1292 // calculate base values and mods
1293 float baseLowEnd = 1.3;
1294 float baseHighEnd = 1.2;
1295 switch(getClass()) // lowering base values for casters
1297 case CLASS_SHAMAN:
1298 case CLASS_PRIEST:
1299 case CLASS_MAGE:
1300 case CLASS_WARLOCK:
1301 case CLASS_DRUID:
1302 baseLowEnd -= 0.7;
1303 baseHighEnd -= 0.3;
1304 break;
1307 float maxLowEnd = 0.6;
1308 switch(getClass()) // upper for melee classes
1310 case CLASS_WARRIOR:
1311 case CLASS_ROGUE:
1312 maxLowEnd = 0.91; //If the attacker is a melee class then instead the lower value of 0.91
1315 // calculate values
1316 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1317 float lowEnd = baseLowEnd - ( 0.05f * diff );
1318 float highEnd = baseHighEnd - ( 0.03f * diff );
1320 // apply max/min bounds
1321 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1322 lowEnd = 0.01f;
1323 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1324 lowEnd = maxLowEnd;
1326 if ( highEnd < 0.2f ) //high end limits
1327 highEnd = 0.2f;
1328 if ( highEnd > 0.99f )
1329 highEnd = 0.99f;
1331 if(lowEnd > highEnd) // prevent negative range size
1332 lowEnd = highEnd;
1334 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1336 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1337 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1338 break;
1340 case MELEE_HIT_CRUSHING:
1342 damageInfo->HitInfo |= HITINFO_CRUSHING;
1343 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1344 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1345 // 150% normal damage
1346 damageInfo->damage += (damageInfo->damage / 2);
1347 break;
1349 default:
1351 break;
1354 // Calculate absorb resist
1355 if(int32(damageInfo->damage) > 0)
1357 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1358 // Calculate absorb & resists
1359 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1360 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1361 if (damageInfo->absorb)
1363 damageInfo->HitInfo|=HITINFO_ABSORB;
1364 damageInfo->procEx|=PROC_EX_ABSORB;
1366 if (damageInfo->resist)
1367 damageInfo->HitInfo|=HITINFO_RESIST;
1370 else // Umpossible get negative result but....
1371 damageInfo->damage = 0;
1374 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1376 if (damageInfo==0) return;
1377 Unit *pVictim = damageInfo->target;
1379 if(!this || !pVictim)
1380 return;
1382 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1383 return;
1385 //You don't lose health from damage taken from another player while in a sanctuary
1386 //You still see it in the combat log though
1387 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1389 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1390 if(area && area->flags & 0x800) //sanctuary
1391 return;
1394 // Hmmmm dont like this emotes cloent must by self do all animations
1395 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1396 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1397 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1398 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1400 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1402 // Get attack timers
1403 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1404 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1405 // Reduce attack time
1406 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1408 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20;
1409 float percent60 = 3 * percent20;
1410 if(offtime > percent20 && offtime <= percent60)
1412 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1414 else if(offtime > percent60)
1416 offtime -= 2 * percent20;
1417 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1420 else
1422 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1423 float percent60 = 3 * percent20;
1424 if(basetime > percent20 && basetime <= percent60)
1426 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1428 else if(basetime > percent60)
1430 basetime -= 2 * percent20;
1431 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1436 // Call default DealDamage
1437 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1438 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1440 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1441 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1442 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1444 // -probability is between 0% and 40%
1445 // 20% base chance
1446 float Probability = 20;
1448 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1449 if( pVictim->getLevel() < 30 )
1450 Probability = 0.65f*pVictim->getLevel()+0.5;
1452 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1453 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1455 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1457 if(Probability > 40)
1458 Probability = 40;
1460 if(roll_chance_f(Probability))
1461 CastSpell(pVictim, 1604, true);
1464 // If not miss
1465 if (!(damageInfo->HitInfo & HITINFO_MISS))
1467 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1469 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1470 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1473 // victim's damage shield
1474 std::set<Aura*> alreadyDone;
1475 uint32 removedAuras = pVictim->m_removedAuras;
1476 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1477 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1479 next++;
1480 if (alreadyDone.find(*i) == alreadyDone.end())
1482 alreadyDone.insert(*i);
1483 uint32 damage=(*i)->GetModifier()->m_amount;
1484 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1485 if(!spellProto)
1486 continue;
1487 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1488 //uint32 absorb;
1489 //uint32 resist;
1490 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1491 //damage-=absorb + resist;
1493 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1494 data << uint64(pVictim->GetGUID());
1495 data << uint64(GetGUID());
1496 data << uint32(spellProto->Id);
1497 data << uint32(damage); // Damage
1498 data << uint32(0); // Overkill
1499 data << uint32(spellProto->SchoolMask);
1500 pVictim->SendMessageToSet(&data, true );
1502 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1504 if (pVictim->m_removedAuras > removedAuras)
1506 removedAuras = pVictim->m_removedAuras;
1507 next = vDamageShields.begin();
1515 void Unit::HandleEmoteCommand(uint32 anim_id)
1517 WorldPacket data( SMSG_EMOTE, 12 );
1518 data << uint32(anim_id);
1519 data << uint64(GetGUID());
1520 SendMessageToSet(&data, true);
1523 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1525 uint32 newdamage = 0;
1526 float armor = pVictim->GetArmor();
1527 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1528 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1530 // Apply Player CR_ARMOR_PENETRATION rating
1531 if (GetTypeId()==TYPEID_PLAYER)
1532 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1534 if (armor < 0.0f) armor=0.0f;
1536 float levelModifier = getLevel();
1537 if ( levelModifier > 59 )
1538 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1540 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1541 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1543 if(tmpvalue < 0.0f)
1544 tmpvalue = 0.0f;
1545 if(tmpvalue > 0.75f)
1546 tmpvalue = 0.75f;
1547 newdamage = uint32(damage - (damage * tmpvalue));
1549 return (newdamage > 1) ? newdamage : 1;
1552 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1554 if(!pVictim || !pVictim->isAlive() || !damage)
1555 return;
1557 // Magic damage, check for resists
1558 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1560 // Get base victim resistance for school
1561 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1562 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1563 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1565 tmpvalue2 *= (float)(0.15f / getLevel());
1566 if (tmpvalue2 < 0.0f)
1567 tmpvalue2 = 0.0f;
1568 if (tmpvalue2 > 0.75f)
1569 tmpvalue2 = 0.75f;
1570 uint32 ran = urand(0, 100);
1571 uint32 faq[4] = {24,6,4,6};
1572 uint8 m = 0;
1573 float Binom = 0.0f;
1574 for (uint8 i = 0; i < 4; i++)
1576 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1577 if (ran > Binom )
1578 ++m;
1579 else
1580 break;
1582 if (damagetype == DOT && m == 4)
1583 *resist += uint32(damage - 1);
1584 else
1585 *resist += uint32(damage * m / 4);
1586 if(*resist > damage)
1587 *resist = damage;
1589 else
1590 *resist = 0;
1592 int32 RemainingDamage = damage - *resist;
1594 // Get unit state (need for some absorb check)
1595 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1596 // Reflect damage spells (not cast any damage spell in aura lookup)
1597 uint32 reflectSpell = 0;
1598 int32 reflectDamage = 0;
1599 // Need remove expired auras after
1600 bool existExpired = false;
1601 // absorb without mana cost
1602 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1603 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1605 Modifier* mod = (*i)->GetModifier();
1606 if (!(mod->m_miscvalue & schoolMask))
1607 continue;
1609 SpellEntry const* spellProto = (*i)->GetSpellProto();
1611 // Max Amount can be absorbed by this aura
1612 int32 currentAbsorb = mod->m_amount;
1614 // Found empty aura (umpossible but..)
1615 if (currentAbsorb <=0)
1617 existExpired = true;
1618 continue;
1620 // Handle custom absorb auras
1621 // TODO: try find better way
1622 switch(spellProto->SpellFamilyName)
1624 case SPELLFAMILY_GENERIC:
1626 // Astral Shift
1627 if (spellProto->SpellIconID == 3066)
1629 //reduces all damage taken while stun, fear or silence
1630 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1631 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1632 continue;
1634 // Nerves of Steel
1635 if (spellProto->SpellIconID == 2115)
1637 // while affected by Stun and Fear
1638 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1639 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1640 continue;
1642 // Spell Deflection
1643 if (spellProto->SpellIconID == 3006)
1645 // You have a chance equal to your Parry chance
1646 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1647 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1648 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1649 continue;
1651 // Reflective Shield (Lady Malande boss)
1652 if (spellProto->Id == 41475)
1654 if(RemainingDamage < currentAbsorb)
1655 reflectDamage = RemainingDamage / 2;
1656 else
1657 reflectDamage = currentAbsorb / 2;
1658 reflectSpell = 33619;
1659 break;
1661 if (spellProto->Id == 39228 || // Argussian Compass
1662 spellProto->Id == 60218) // Essence of Gossamer
1664 // Max absorb stored in 1 dummy effect
1665 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1666 currentAbsorb = spellProto->EffectBasePoints[1];
1667 break;
1669 break;
1671 case SPELLFAMILY_DRUID:
1673 // Primal Tenacity
1674 if (spellProto->SpellIconID == 2253)
1676 //reduces all damage taken while Stunned
1677 if (unitflag & UNIT_FLAG_STUNNED)
1678 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1679 continue;
1681 break;
1683 case SPELLFAMILY_ROGUE:
1685 // Cheat Death
1686 if(spellProto->SpellIconID == 2109)
1688 if (pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1689 pVictim->GetHealth() <= RemainingDamage && // Only if damage kill
1690 !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
1691 roll_chance_i(currentAbsorb)) // Only if roll
1693 pVictim->CastSpell(pVictim,31231,true);
1694 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1695 // with health > 10% lost health until health==10%, in other case no losses
1696 uint32 health10 = pVictim->GetMaxHealth()/10;
1697 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1699 continue;
1701 break;
1703 case SPELLFAMILY_PRIEST:
1705 // Reflective Shield
1706 if (spellProto->SpellFamilyFlags == 0x1)
1708 if (pVictim == this)
1709 break;
1710 Unit* caster = (*i)->GetCaster();
1711 if (!caster)
1712 break;
1713 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1714 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1716 switch((*k)->GetModifier()->m_miscvalue)
1718 case 5065: // Rank 1
1719 case 5064: // Rank 2
1720 case 5063: // Rank 3
1722 if(RemainingDamage >= currentAbsorb)
1723 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1724 else
1725 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1726 reflectSpell = 33619;
1727 } break;
1728 default: break;
1731 break;
1733 break;
1735 case SPELLFAMILY_SHAMAN:
1737 // Astral Shift
1738 if (spellProto->SpellIconID == 3066)
1740 //reduces all damage taken while stun, fear or silence
1741 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1742 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1743 continue;
1745 break;
1747 case SPELLFAMILY_DEATHKNIGHT:
1749 // Shadow of Death
1750 if (spellProto->SpellIconID == 1958)
1752 // TODO: absorb only while transform
1753 continue;
1755 // Anti-Magic Shell (on self)
1756 if (spellProto->Id == 48707)
1758 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1759 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1760 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1761 int32 regen = absorbed * 2 / 10;
1762 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1763 RemainingDamage -= absorbed;
1764 continue;
1766 // Anti-Magic Shell (on single party/raid member)
1767 if (spellProto->Id == 50462)
1769 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1770 continue;
1772 // Anti-Magic Zone
1773 if (spellProto->Id == 50461)
1775 Unit* caster = (*i)->GetCaster();
1776 if (!caster)
1777 continue;
1778 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1779 int32 canabsorb = caster->GetHealth();
1780 if (canabsorb < absorbed)
1781 absorbed = canabsorb;
1782 DealDamage(caster, absorbed, NULL, damagetype, schoolMask, 0, false);
1783 RemainingDamage -= absorbed;
1784 continue;
1786 break;
1788 default:
1789 break;
1792 // currentAbsorb - damage can be absorbed by shield
1793 // If need absorb less damage
1794 if (RemainingDamage < currentAbsorb)
1795 currentAbsorb = RemainingDamage;
1797 RemainingDamage -= currentAbsorb;
1799 // Reduce shield amount
1800 mod->m_amount-=currentAbsorb;
1801 // Need remove it later
1802 if (mod->m_amount<=0)
1803 existExpired = true;
1806 // Remove all expired absorb auras
1807 if (existExpired)
1809 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1811 if ((*i)->GetModifier()->m_amount<=0)
1813 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1814 i = vSchoolAbsorb.begin();
1816 else
1817 ++i;
1820 // Cast back reflect damage spell
1821 if (reflectSpell)
1822 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true);
1824 // absorb by mana cost
1825 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1826 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1828 next = i; ++next;
1830 // check damage school mask
1831 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1832 continue;
1834 int32 currentAbsorb;
1835 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1836 currentAbsorb = (*i)->GetModifier()->m_amount;
1837 else
1838 currentAbsorb = RemainingDamage;
1840 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1841 if(Player *modOwner = pVictim->GetSpellModOwner())
1842 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1844 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1845 if (currentAbsorb > maxAbsorb)
1846 currentAbsorb = maxAbsorb;
1848 (*i)->GetModifier()->m_amount -= currentAbsorb;
1849 if((*i)->GetModifier()->m_amount <= 0)
1851 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1852 next = vManaShield.begin();
1855 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1856 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1858 RemainingDamage -= currentAbsorb;
1861 // only split damage if not damaging yourself
1862 if(pVictim != this)
1864 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1865 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1867 next = i; ++next;
1869 // check damage school mask
1870 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1871 continue;
1873 // Damage can be splitted only if aura has an alive caster
1874 Unit *caster = (*i)->GetCaster();
1875 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1876 continue;
1878 int32 currentAbsorb;
1879 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1880 currentAbsorb = (*i)->GetModifier()->m_amount;
1881 else
1882 currentAbsorb = RemainingDamage;
1884 RemainingDamage -= currentAbsorb;
1886 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1888 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1889 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1892 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1893 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1895 next = i; ++next;
1897 // check damage school mask
1898 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1899 continue;
1901 // Damage can be splitted only if aura has an alive caster
1902 Unit *caster = (*i)->GetCaster();
1903 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1904 continue;
1906 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1908 RemainingDamage -= splitted;
1910 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1912 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1913 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1917 *absorb = damage - RemainingDamage - *resist;
1920 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1922 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1923 return;
1925 if (!pVictim->isAlive())
1926 return;
1928 if(IsNonMeleeSpellCasted(false))
1929 return;
1931 uint32 hitInfo;
1932 if (attType == BASE_ATTACK)
1933 hitInfo = HITINFO_NORMALSWING2;
1934 else if (attType == OFF_ATTACK)
1935 hitInfo = HITINFO_LEFTSWING;
1936 else
1937 return; // ignore ranged case
1939 uint32 extraAttacks = m_extraAttacks;
1941 // melee attack spell casted at main hand attack only
1942 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1944 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1946 // not recent extra attack only at any non extra attack (melee spell case)
1947 if(!extra && extraAttacks)
1949 while(m_extraAttacks)
1951 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1952 if(m_extraAttacks > 0)
1953 --m_extraAttacks;
1957 // if damage pVictim call AI reaction
1958 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
1959 ((Creature*)pVictim)->AI()->AttackedBy(this);
1961 return;
1964 // attack can be redirected to another target
1965 pVictim = SelectMagnetTarget(pVictim);
1967 CalcDamageInfo damageInfo;
1968 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1969 // Send log damage message to client
1970 SendAttackStateUpdate(&damageInfo);
1971 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1972 DealMeleeDamage(&damageInfo,true);
1974 if (GetTypeId() == TYPEID_PLAYER)
1975 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1976 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1977 else
1978 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1979 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1981 // extra attack only at any non extra attack (normal case)
1982 if(!extra && extraAttacks)
1984 while(m_extraAttacks)
1986 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1987 if(m_extraAttacks > 0)
1988 --m_extraAttacks;
1992 // if damage pVictim call AI reaction
1993 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
1994 ((Creature*)pVictim)->AI()->AttackedBy(this);
1997 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
1999 // This is only wrapper
2001 // Miss chance based on melee
2002 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2004 // Critical hit chance
2005 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2007 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2008 float dodge_chance = pVictim->GetUnitDodgeChance();
2009 float block_chance = pVictim->GetUnitBlockChance();
2010 float parry_chance = pVictim->GetUnitParryChance();
2012 // Useful if want to specify crit & miss chances for melee, else it could be removed
2013 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2015 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2018 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2020 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2021 return MELEE_HIT_EVADE;
2023 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2024 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2026 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2027 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2029 // bonus from skills is 0.04%
2030 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2031 int32 sum = 0, tmp = 0;
2032 int32 roll = urand (0, 10000);
2034 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2035 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2036 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2038 tmp = miss_chance;
2040 if (tmp > 0 && roll < (sum += tmp ))
2042 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2043 return MELEE_HIT_MISS;
2046 // always crit against a sitting target (except 0 crit chance)
2047 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2049 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2050 return MELEE_HIT_CRIT;
2053 // Dodge chance
2055 // only players can't dodge if attacker is behind
2056 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2058 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2060 else
2062 // Reduce dodge chance by attacker expertise rating
2063 if (GetTypeId() == TYPEID_PLAYER)
2064 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2066 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2067 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2069 tmp = dodge_chance;
2070 if ( (tmp > 0) // check if unit _can_ dodge
2071 && ((tmp -= skillBonus) > 0)
2072 && roll < (sum += tmp))
2074 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2075 return MELEE_HIT_DODGE;
2079 // parry & block chances
2081 // check if attack comes from behind, nobody can parry or block if attacker is behind
2082 if (!pVictim->HasInArc(M_PI,this))
2084 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2086 else
2088 // Reduce parry chance by attacker expertise rating
2089 if (GetTypeId() == TYPEID_PLAYER)
2090 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2092 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2094 int32 tmp = int32(parry_chance);
2095 if ( (tmp > 0) // check if unit _can_ parry
2096 && ((tmp -= skillBonus) > 0)
2097 && (roll < (sum += tmp)))
2099 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
2100 return MELEE_HIT_PARRY;
2104 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2106 tmp = block_chance;
2107 if ( (tmp > 0) // check if unit _can_ block
2108 && ((tmp -= skillBonus) > 0)
2109 && (roll < (sum += tmp)))
2111 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2112 return MELEE_HIT_BLOCK;
2117 // Critical chance
2118 tmp = crit_chance;
2120 if (tmp > 0 && roll < (sum += tmp))
2122 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2123 return MELEE_HIT_CRIT;
2126 // 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)
2127 if( attType != RANGED_ATTACK &&
2128 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2129 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2130 getLevel() < pVictim->getLevelForTarget(this) )
2132 // cap possible value (with bonuses > max skill)
2133 int32 skill = attackerWeaponSkill;
2134 int32 maxskill = attackerMaxSkillValueForLevel;
2135 skill = (skill > maxskill) ? maxskill : skill;
2137 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2138 tmp = tmp > 4000 ? 4000 : tmp;
2139 if (roll < (sum += tmp))
2141 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2142 return MELEE_HIT_GLANCING;
2146 // mobs can score crushing blows if they're 4 or more levels above victim
2147 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2148 // can be from by creature (if can) or from controlled player that considered as creature
2149 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2150 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2151 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2153 // when their weapon skill is 15 or more above victim's defense skill
2154 tmp = victimDefenseSkill;
2155 int32 tmpmax = victimMaxSkillValueForLevel;
2156 // having defense above your maximum (from items, talents etc.) has no effect
2157 tmp = tmp > tmpmax ? tmpmax : tmp;
2158 // tmp = mob's level * 5 - player's current defense skill
2159 tmp = attackerMaxSkillValueForLevel - tmp;
2160 if(tmp >= 15)
2162 // add 2% chance per lacking skill point, min. is 15%
2163 tmp = tmp * 200 - 1500;
2164 if (roll < (sum += tmp))
2166 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2167 return MELEE_HIT_CRUSHING;
2172 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2173 return MELEE_HIT_NORMAL;
2176 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2178 float min_damage, max_damage;
2180 if (normalized && GetTypeId()==TYPEID_PLAYER)
2181 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2182 else
2184 switch (attType)
2186 case RANGED_ATTACK:
2187 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2188 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2189 break;
2190 case BASE_ATTACK:
2191 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2192 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2193 break;
2194 case OFF_ATTACK:
2195 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2196 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2197 break;
2198 // Just for good manner
2199 default:
2200 min_damage = 0.0f;
2201 max_damage = 0.0f;
2202 break;
2206 if (min_damage > max_damage)
2208 std::swap(min_damage,max_damage);
2211 if(max_damage == 0.0f)
2212 max_damage = 5.0f;
2214 return urand((uint32)min_damage, (uint32)max_damage);
2217 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2219 if(spellProto->spellLevel <= 0)
2220 return 1.0f;
2222 float LvlPenalty = 0.0f;
2224 if(spellProto->spellLevel < 20)
2225 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2226 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2227 if(LvlFactor > 1.0f)
2228 LvlFactor = 1.0f;
2230 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2233 void Unit::SendAttackStart(Unit* pVictim)
2235 WorldPacket data( SMSG_ATTACKSTART, 16 );
2236 data << uint64(GetGUID());
2237 data << uint64(pVictim->GetGUID());
2239 SendMessageToSet(&data, true);
2240 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2243 void Unit::SendAttackStop(Unit* victim)
2245 if(!victim)
2246 return;
2248 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2249 data.append(GetPackGUID());
2250 data.append(victim->GetPackGUID()); // can be 0x00...
2251 data << uint32(0); // can be 0x1
2252 SendMessageToSet(&data, true);
2253 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2255 /*if(victim->GetTypeId() == TYPEID_UNIT)
2256 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2259 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2261 if (pVictim->HasInArc(M_PI,this))
2263 /* Currently not exist spells with ignore block
2264 // Ignore combat result aura (parry/dodge check on prepare)
2265 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2266 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2268 if (!(*i)->isAffectedOnSpell(spellProto))
2269 continue;
2270 if ((*i)->GetModifier()->m_miscvalue == )
2271 return false;
2275 // Check creatures flags_extra for disable block
2276 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2277 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2278 return false;
2280 float blockChance = pVictim->GetUnitBlockChance();
2281 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2282 if (roll_chance_f(blockChance))
2283 return true;
2285 return false;
2288 // Melee based spells can be miss, parry or dodge on this step
2289 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2290 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2292 // Calculate hit chance (more correct for chance mod)
2293 int32 HitChance;
2295 // PvP - PvE melee chances
2296 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2297 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2298 if(leveldif < 3)
2299 HitChance = 95 - leveldif;
2300 else
2301 HitChance = 93 - (leveldif - 2) * lchance;
2303 // Hit chance depends from victim auras
2304 if(attType == RANGED_ATTACK)
2305 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2306 else
2307 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2309 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2310 if(Player *modOwner = GetSpellModOwner())
2311 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2313 // Miss = 100 - hit
2314 float miss_chance= 100.0f - HitChance;
2316 // Bonuses from attacker aura and ratings
2317 if (attType == RANGED_ATTACK)
2318 miss_chance -= m_modRangedHitChance;
2319 else
2320 miss_chance -= m_modMeleeHitChance;
2322 // bonus from skills is 0.04%
2323 miss_chance -= skillDiff * 0.04f;
2325 // Limit miss chance from 0 to 60%
2326 if (miss_chance < 0.0f)
2327 return 0.0f;
2328 if (miss_chance > 60.0f)
2329 return 60.0f;
2330 return miss_chance;
2333 // Melee based spells hit result calculations
2334 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2336 WeaponAttackType attType = BASE_ATTACK;
2338 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2339 attType = RANGED_ATTACK;
2341 // bonus from skills is 0.04% per skill Diff
2342 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2343 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2344 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2346 uint32 roll = urand (0, 10000);
2348 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2349 // Roll miss
2350 uint32 tmp = missChance;
2351 if (roll < tmp)
2352 return SPELL_MISS_MISS;
2354 // Chance resist mechanic (select max value from every mechanic spell effect)
2355 int32 resist_mech = 0;
2356 // Get effects mechanic and chance
2357 for(int eff = 0; eff < 3; ++eff)
2359 int32 effect_mech = GetEffectMechanic(spell, eff);
2360 if (effect_mech)
2362 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2363 if (resist_mech < temp*100)
2364 resist_mech = temp*100;
2367 // Roll chance
2368 tmp += resist_mech;
2369 if (roll < tmp)
2370 return SPELL_MISS_RESIST;
2372 bool canDodge = true;
2373 bool canParry = true;
2375 // Same spells cannot be parry/dodge
2376 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2377 return SPELL_MISS_NONE;
2379 // Ranged attack cannot be parry/dodge only deflect
2380 if (attType == RANGED_ATTACK)
2382 // only if in front
2383 if (pVictim->HasInArc(M_PI,this))
2385 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2386 tmp+=deflect_chance;
2387 if (roll < tmp)
2388 return SPELL_MISS_DEFLECT;
2390 return SPELL_MISS_NONE;
2393 // Check for attack from behind
2394 if (!pVictim->HasInArc(M_PI,this))
2396 // Can`t dodge from behind in PvP (but its possible in PvE)
2397 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2398 canDodge = false;
2399 // Can`t parry
2400 canParry = false;
2402 // Check creatures flags_extra for disable parry
2403 if(pVictim->GetTypeId()==TYPEID_UNIT)
2405 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2406 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2407 canParry = false;
2409 // Ignore combat result aura
2410 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2411 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2413 if (!(*i)->isAffectedOnSpell(spell))
2414 continue;
2415 switch((*i)->GetModifier()->m_miscvalue)
2417 case MELEE_HIT_DODGE: canDodge = false; break;
2418 case MELEE_HIT_BLOCK: break; // Block check in hit step
2419 case MELEE_HIT_PARRY: canParry = false; break;
2420 default:
2421 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2422 break;
2426 if (canDodge)
2428 // Roll dodge
2429 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2430 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2431 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2432 // Reduce dodge chance by attacker expertise rating
2433 if (GetTypeId() == TYPEID_PLAYER)
2434 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2435 if (dodgeChance < 0)
2436 dodgeChance = 0;
2438 tmp += dodgeChance;
2439 if (roll < tmp)
2440 return SPELL_MISS_DODGE;
2443 if (canParry)
2445 // Roll parry
2446 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2447 // Reduce parry chance by attacker expertise rating
2448 if (GetTypeId() == TYPEID_PLAYER)
2449 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2450 if (parryChance < 0)
2451 parryChance = 0;
2453 tmp += parryChance;
2454 if (roll < tmp)
2455 return SPELL_MISS_PARRY;
2458 return SPELL_MISS_NONE;
2461 // TODO need use unit spell resistances in calculations
2462 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2464 // Can`t miss on dead target (on skinning for example)
2465 if (!pVictim->isAlive())
2466 return SPELL_MISS_NONE;
2468 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2469 // PvP - PvE spell misschances per leveldif > 2
2470 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2471 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2473 // Base hit chance from attacker and victim levels
2474 int32 modHitChance;
2475 if(leveldif < 3)
2476 modHitChance = 96 - leveldif;
2477 else
2478 modHitChance = 94 - (leveldif - 2) * lchance;
2480 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2481 if(Player *modOwner = GetSpellModOwner())
2482 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2483 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2484 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2485 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2486 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2487 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2488 if (IsAreaOfEffectSpell(spell))
2489 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2490 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2491 if (IsDispelSpell(spell))
2492 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2493 // Chance resist mechanic (select max value from every mechanic spell effect)
2494 int32 resist_mech = 0;
2495 // Get effects mechanic and chance
2496 for(int eff = 0; eff < 3; ++eff)
2498 int32 effect_mech = GetEffectMechanic(spell, eff);
2499 if (effect_mech)
2501 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2502 if (resist_mech < temp)
2503 resist_mech = temp;
2506 // Apply mod
2507 modHitChance-=resist_mech;
2509 // Chance resist debuff
2510 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2512 int32 HitChance = modHitChance * 100;
2513 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2514 HitChance += int32(m_modSpellHitChance*100.0f);
2516 // Decrease hit chance from victim rating bonus
2517 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2518 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2520 if (HitChance < 100) HitChance = 100;
2521 if (HitChance > 10000) HitChance = 10000;
2523 int32 tmp = 10000 - HitChance;
2525 uint32 rand = urand(0,10000);
2527 if (rand < tmp)
2528 return SPELL_MISS_RESIST;
2530 // cast by caster in front of victim
2531 if (pVictim->HasInArc(M_PI,this))
2533 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2534 tmp+=deflect_chance;
2535 if (rand < tmp)
2536 return SPELL_MISS_DEFLECT;
2539 return SPELL_MISS_NONE;
2542 // Calculate spell hit result can be:
2543 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2544 // For melee based spells:
2545 // Miss
2546 // Dodge
2547 // Parry
2548 // For spells
2549 // Resist
2550 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2552 // Return evade for units in evade mode
2553 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2554 return SPELL_MISS_EVADE;
2556 // Check for immune
2557 if (pVictim->IsImmunedToSpell(spell))
2558 return SPELL_MISS_IMMUNE;
2560 // All positive spells can`t miss
2561 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2562 if (IsPositiveSpell(spell->Id))
2563 return SPELL_MISS_NONE;
2565 // Check for immune
2566 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2567 return SPELL_MISS_IMMUNE;
2569 // Try victim reflect spell
2570 if (CanReflect)
2572 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2573 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2574 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2575 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2576 reflectchance += (*i)->GetModifier()->m_amount;
2577 if (reflectchance > 0 && roll_chance_i(reflectchance))
2579 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2580 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2581 return SPELL_MISS_REFLECT;
2585 switch (spell->DmgClass)
2587 case SPELL_DAMAGE_CLASS_RANGED:
2588 case SPELL_DAMAGE_CLASS_MELEE:
2589 return MeleeSpellHitResult(pVictim, spell);
2590 case SPELL_DAMAGE_CLASS_NONE:
2591 case SPELL_DAMAGE_CLASS_MAGIC:
2592 return MagicSpellHitResult(pVictim, spell);
2594 return SPELL_MISS_NONE;
2597 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2599 if(!pVictim)
2600 return 0.0f;
2602 // Base misschance 5%
2603 float misschance = 5.0f;
2605 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2606 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2608 bool isNormal = false;
2609 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2611 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2613 isNormal = true;
2614 break;
2617 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2619 misschance = 5.0f;
2621 else
2623 misschance = 24.0f;
2627 // PvP : PvE melee misschances per leveldif > 2
2628 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2630 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2631 if(leveldif < 0)
2632 leveldif = 0;
2634 // Hit chance from attacker based on ratings and auras
2635 float m_modHitChance;
2636 if (attType == RANGED_ATTACK)
2637 m_modHitChance = m_modRangedHitChance;
2638 else
2639 m_modHitChance = m_modMeleeHitChance;
2641 if(leveldif < 3)
2642 misschance += (leveldif - m_modHitChance);
2643 else
2644 misschance += ((leveldif - 2) * chance - m_modHitChance);
2646 // Hit chance for victim based on ratings
2647 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2649 if (attType == RANGED_ATTACK)
2650 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2651 else
2652 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2655 // Modify miss chance by victim auras
2656 if(attType == RANGED_ATTACK)
2657 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2658 else
2659 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2661 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2662 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2663 misschance -= skillBonus * 0.04f;
2665 // Limit miss chance from 0 to 60%
2666 if ( misschance < 0.0f)
2667 return 0.0f;
2668 if ( misschance > 60.0f)
2669 return 60.0f;
2671 return misschance;
2674 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2676 if(GetTypeId() == TYPEID_PLAYER)
2678 // in PvP use full skill instead current skill value
2679 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2680 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2681 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2682 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2683 return value;
2685 else
2686 return GetUnitMeleeSkill(target);
2689 float Unit::GetUnitDodgeChance() const
2691 if(hasUnitState(UNIT_STAT_STUNNED))
2692 return 0.0f;
2693 if( GetTypeId() == TYPEID_PLAYER )
2694 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2695 else
2697 if(((Creature const*)this)->isTotem())
2698 return 0.0f;
2699 else
2701 float dodge = 5.0f;
2702 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2703 return dodge > 0.0f ? dodge : 0.0f;
2708 float Unit::GetUnitParryChance() const
2710 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2711 return 0.0f;
2713 float chance = 0.0f;
2715 if(GetTypeId() == TYPEID_PLAYER)
2717 Player const* player = (Player const*)this;
2718 if(player->CanParry() )
2720 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2721 if(!tmpitem)
2722 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2724 if(tmpitem)
2725 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2728 else if(GetTypeId() == TYPEID_UNIT)
2730 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2732 chance = 5.0f;
2733 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2737 return chance > 0.0f ? chance : 0.0f;
2740 float Unit::GetUnitBlockChance() const
2742 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2743 return 0.0f;
2745 if(GetTypeId() == TYPEID_PLAYER)
2747 Player const* player = (Player const*)this;
2748 if(player->CanBlock() )
2750 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2751 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2752 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2754 // is player but has no block ability or no not broken shield equipped
2755 return 0.0f;
2757 else
2759 if(((Creature const*)this)->isTotem())
2760 return 0.0f;
2761 else
2763 float block = 5.0f;
2764 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2765 return block > 0.0f ? block : 0.0f;
2770 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2772 float crit;
2774 if(GetTypeId() == TYPEID_PLAYER)
2776 switch(attackType)
2778 case BASE_ATTACK:
2779 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2780 break;
2781 case OFF_ATTACK:
2782 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2783 break;
2784 case RANGED_ATTACK:
2785 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2786 break;
2787 // Just for good manner
2788 default:
2789 crit = 0.0f;
2790 break;
2793 else
2795 crit = 5.0f;
2796 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2799 // flat aura mods
2800 if(attackType == RANGED_ATTACK)
2801 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2802 else
2803 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2805 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2807 // reduce crit chance from Rating for players
2808 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2810 if (attackType==RANGED_ATTACK)
2811 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2812 else
2813 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2816 // Apply crit chance from defence skill
2817 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2819 if (crit < 0.0f)
2820 crit = 0.0f;
2821 return crit;
2824 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2826 uint32 value = 0;
2827 if(GetTypeId() == TYPEID_PLAYER)
2829 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2831 // feral or unarmed skill only for base attack
2832 if(attType != BASE_ATTACK && !item )
2833 return 0;
2835 if(IsInFeralForm())
2836 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2838 // weapon skill or (unarmed for base attack)
2839 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2841 // in PvP use full skill instead current skill value
2842 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2843 ? ((Player*)this)->GetMaxSkillValue(skill)
2844 : ((Player*)this)->GetSkillValue(skill);
2845 // Modify value from ratings
2846 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2847 switch (attType)
2849 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2850 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2851 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2854 else
2855 value = GetUnitMeleeSkill(target);
2856 return value;
2859 void Unit::_UpdateSpells( uint32 time )
2861 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2862 _UpdateAutoRepeatSpell();
2864 // remove finished spells from current pointers
2865 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2867 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2869 m_currentSpells[i]->SetReferencedFromCurrent(false);
2870 m_currentSpells[i] = NULL; // remove pointer
2874 // TODO: Find a better way to prevent crash when multiple auras are removed.
2875 m_removedAuras = 0;
2876 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2877 if ((*i).second)
2878 (*i).second->SetUpdated(false);
2880 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2882 next = i;
2883 ++next;
2884 if ((*i).second)
2886 // prevent double update
2887 if ((*i).second->IsUpdated())
2888 continue;
2889 (*i).second->SetUpdated(true);
2890 (*i).second->Update( time );
2891 // several auras can be deleted due to update
2892 if (m_removedAuras)
2894 if (m_Auras.empty()) break;
2895 next = m_Auras.begin();
2896 m_removedAuras = 0;
2901 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2903 if ((*i).second)
2905 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2907 RemoveAura(i);
2909 else
2911 ++i;
2914 else
2916 ++i;
2920 if(!m_gameObj.empty())
2922 GameObjectList::iterator ite1, dnext1;
2923 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2925 dnext1 = ite1;
2926 //(*i)->Update( difftime );
2927 if( !(*ite1)->isSpawned() )
2929 (*ite1)->SetOwnerGUID(0);
2930 (*ite1)->SetRespawnTime(0);
2931 (*ite1)->Delete();
2932 dnext1 = m_gameObj.erase(ite1);
2934 else
2935 ++dnext1;
2940 void Unit::_UpdateAutoRepeatSpell()
2942 //check "realtime" interrupts
2943 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2945 // cancel wand shoot
2946 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2947 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2948 m_AutoRepeatFirstCast = true;
2949 return;
2952 //apply delay
2953 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2954 setAttackTimer(RANGED_ATTACK,500);
2955 m_AutoRepeatFirstCast = false;
2957 //castroutine
2958 if (isAttackReady(RANGED_ATTACK))
2960 // Check if able to cast
2961 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
2963 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2964 return;
2967 // we want to shoot
2968 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2969 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2971 // all went good, reset attack
2972 resetAttackTimer(RANGED_ATTACK);
2976 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2978 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2980 uint32 CSpellType = pSpell->GetCurrentContainer();
2982 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2984 // break same type spell if it is not delayed
2985 InterruptSpell(CSpellType,false);
2987 // special breakage effects:
2988 switch (CSpellType)
2990 case CURRENT_GENERIC_SPELL:
2992 // generic spells always break channeled not delayed spells
2993 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
2995 // autorepeat breaking
2996 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
2998 // break autorepeat if not Auto Shot
2999 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3000 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3001 m_AutoRepeatFirstCast = true;
3003 } break;
3005 case CURRENT_CHANNELED_SPELL:
3007 // channel spells always break generic non-delayed and any channeled spells
3008 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3009 InterruptSpell(CURRENT_CHANNELED_SPELL);
3011 // it also does break autorepeat if not Auto Shot
3012 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3013 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3014 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3015 } break;
3017 case CURRENT_AUTOREPEAT_SPELL:
3019 // only Auto Shoot does not break anything
3020 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3022 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3023 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3024 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3026 // special action: set first cast flag
3027 m_AutoRepeatFirstCast = true;
3028 } break;
3030 default:
3032 // other spell types don't break anything now
3033 } break;
3036 // current spell (if it is still here) may be safely deleted now
3037 if (m_currentSpells[CSpellType])
3038 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3040 // set new current spell
3041 m_currentSpells[CSpellType] = pSpell;
3042 pSpell->SetReferencedFromCurrent(true);
3045 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3047 assert(spellType < CURRENT_MAX_SPELL);
3049 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3051 // send autorepeat cancel message for autorepeat spells
3052 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3054 if(GetTypeId()==TYPEID_PLAYER)
3055 ((Player*)this)->SendAutoRepeatCancel();
3058 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3059 m_currentSpells[spellType]->cancel();
3061 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3062 if (m_currentSpells[spellType])
3064 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3065 m_currentSpells[spellType] = NULL;
3070 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3072 // We don't do loop here to explicitly show that melee spell is excluded.
3073 // Maybe later some special spells will be excluded too.
3075 // generic spells are casted when they are not finished and not delayed
3076 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3077 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3078 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3079 return(true);
3081 // channeled spells may be delayed, but they are still considered casted
3082 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3083 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3084 return(true);
3086 // autorepeat spells may be finished or delayed, but they are still considered casted
3087 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3088 return(true);
3090 return(false);
3093 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3095 // generic spells are interrupted if they are not finished or delayed
3096 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3097 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3099 // autorepeat spells are interrupted if they are not finished or delayed
3100 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3101 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3103 // channeled spells are interrupted if they are not finished, even if they are delayed
3104 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3105 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3108 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3110 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
3111 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3112 return m_currentSpells[i];
3113 return NULL;
3116 bool Unit::isInFront(Unit const* target, float distance, float arc) const
3118 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3121 void Unit::SetInFront(Unit const* target)
3123 SetOrientation(GetAngle(target));
3126 bool Unit::isInBack(Unit const* target, float distance, float arc) const
3128 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3131 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3133 if(IsInWater())
3134 return c->canSwim();
3135 else
3136 return c->canWalk() || c->canFly();
3139 bool Unit::IsInWater() const
3141 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3144 bool Unit::IsUnderWater() const
3146 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3149 void Unit::DeMorph()
3151 SetDisplayId(GetNativeDisplayId());
3154 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3156 int32 modifier = 0;
3158 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3159 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3160 modifier += (*i)->GetModifier()->m_amount;
3162 return modifier;
3165 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3167 float multiplier = 1.0f;
3169 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3170 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3171 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3173 return multiplier;
3176 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3178 int32 modifier = 0;
3180 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3181 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3182 if ((*i)->GetModifier()->m_amount > modifier)
3183 modifier = (*i)->GetModifier()->m_amount;
3185 return modifier;
3188 int32 Unit::GetMaxNegativeAuraModifier(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::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3202 int32 modifier = 0;
3204 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3205 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3207 Modifier* mod = (*i)->GetModifier();
3208 if (mod->m_miscvalue & misc_mask)
3209 modifier += mod->m_amount;
3211 return modifier;
3214 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3216 float multiplier = 1.0f;
3218 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3219 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3221 Modifier* mod = (*i)->GetModifier();
3222 if (mod->m_miscvalue & misc_mask)
3223 multiplier *= (100.0f + mod->m_amount)/100.0f;
3225 return multiplier;
3228 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3230 int32 modifier = 0;
3232 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3233 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3235 Modifier* mod = (*i)->GetModifier();
3236 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3237 modifier = mod->m_amount;
3240 return modifier;
3243 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3245 int32 modifier = 0;
3247 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3248 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3250 Modifier* mod = (*i)->GetModifier();
3251 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3252 modifier = mod->m_amount;
3255 return modifier;
3258 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3260 int32 modifier = 0;
3262 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3263 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3265 Modifier* mod = (*i)->GetModifier();
3266 if (mod->m_miscvalue == misc_value)
3267 modifier += mod->m_amount;
3269 return modifier;
3272 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3274 float multiplier = 1.0f;
3276 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3277 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3279 Modifier* mod = (*i)->GetModifier();
3280 if (mod->m_miscvalue == misc_value)
3281 multiplier *= (100.0f + mod->m_amount)/100.0f;
3283 return multiplier;
3286 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3288 int32 modifier = 0;
3290 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3291 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3293 Modifier* mod = (*i)->GetModifier();
3294 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3295 modifier = mod->m_amount;
3298 return modifier;
3301 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3303 int32 modifier = 0;
3305 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3306 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3308 Modifier* mod = (*i)->GetModifier();
3309 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3310 modifier = mod->m_amount;
3313 return modifier;
3316 bool Unit::AddAura(Aura *Aur)
3318 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3319 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3320 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3322 delete Aur;
3323 return false;
3326 if(Aur->GetTarget() != this)
3328 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3329 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3330 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3331 delete Aur;
3332 return false;
3335 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3337 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3338 AuraMap::iterator i = m_Auras.find( spair );
3340 // take out same spell
3341 if (i != m_Auras.end())
3343 // passive and persistent auras can stack with themselves any number of times
3344 if (!Aur->IsPassive() && !Aur->IsPersistent())
3346 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3348 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3350 // Aura can stack on self -> Stack it;
3351 if(aurSpellInfo->StackAmount)
3353 i2->second->modStackAmount(1);
3354 delete Aur;
3355 return false;
3357 // can be only single (this check done at _each_ aura add
3358 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3359 break;
3362 bool stop = false;
3363 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3365 // DoT/HoT/etc
3366 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3367 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3368 case SPELL_AURA_PERIODIC_LEECH:
3369 case SPELL_AURA_PERIODIC_HEAL:
3370 case SPELL_AURA_OBS_MOD_HEALTH:
3371 case SPELL_AURA_PERIODIC_MANA_LEECH:
3372 case SPELL_AURA_PERIODIC_ENERGIZE:
3373 case SPELL_AURA_OBS_MOD_MANA:
3374 case SPELL_AURA_POWER_BURN_MANA:
3375 break;
3376 default: // not allow
3377 // can be only single (this check done at _each_ aura add
3378 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3379 stop = true;
3380 break;
3383 if(stop)
3384 break;
3389 // passive auras not stacable with other ranks
3390 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3392 if (!RemoveNoStackAurasDueToAura(Aur))
3394 delete Aur;
3395 return false; // couldn't remove conflicting aura with higher rank
3399 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3400 if (Aur->IsSingleTarget() && Aur->GetTarget())
3402 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3403 for(;;)
3405 Unit* caster = Aur->GetCaster();
3406 if(!caster) // caster deleted and not required adding scAura
3407 break;
3409 bool restart = false;
3410 AuraList& scAuras = caster->GetSingleCastAuras();
3411 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3413 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3414 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3416 if ((*itr)->IsInUse())
3418 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());
3419 continue;
3421 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3422 restart = true;
3423 break;
3427 if(!restart)
3429 // done
3430 scAuras.push_back(Aur);
3431 break;
3436 // add aura, register in lists and arrays
3437 Aur->_AddAura();
3438 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3439 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3441 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3444 Aur->ApplyModifier(true,true);
3445 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3446 return true;
3449 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3451 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3452 if(!spellInfo)
3453 return;
3454 AuraMap::iterator i,next;
3455 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3457 next = i;
3458 ++next;
3459 uint32 i_spellId = (*i).second->GetId();
3460 if((*i).second && i_spellId && i_spellId != spellId)
3462 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3464 RemoveAurasDueToSpell(i_spellId);
3466 if( m_Auras.empty() )
3467 break;
3468 else
3469 next = m_Auras.begin();
3475 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3477 if (!Aur)
3478 return false;
3480 SpellEntry const* spellProto = Aur->GetSpellProto();
3481 if (!spellProto)
3482 return false;
3484 uint32 spellId = Aur->GetId();
3485 uint32 effIndex = Aur->GetEffIndex();
3487 // passive spell special case (only non stackable with ranks)
3488 if(IsPassiveSpell(spellId))
3490 if(IsPassiveSpellStackableWithRanks(spellProto))
3491 return true;
3494 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3496 AuraMap::iterator i,next;
3497 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3499 next = i;
3500 ++next;
3501 if (!(*i).second) continue;
3503 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3505 if (!i_spellProto)
3506 continue;
3508 uint32 i_spellId = i_spellProto->Id;
3510 // early checks that spellId is passive non stackable spell
3511 if(IsPassiveSpell(i_spellId))
3513 // passive non-stackable spells not stackable only for same caster
3514 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3515 continue;
3517 // passive non-stackable spells not stackable only with another rank of same spell
3518 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3519 continue;
3522 uint32 i_effIndex = (*i).second->GetEffIndex();
3524 if(i_spellId == spellId) continue;
3526 bool is_triggered_by_spell = false;
3527 // prevent triggered aura of removing aura that triggered it
3528 for(int j = 0; j < 3; ++j)
3529 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3530 is_triggered_by_spell = true;
3532 if (is_triggered_by_spell)
3533 continue;
3535 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3537 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3538 bool is_sspt = IsSingleFromSpellSpecificRanksPerTarget(spellId_spec,i_spellId_spec);
3540 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3542 // cannot remove higher rank
3543 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3544 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3545 return false;
3547 // Its a parent aura (create this aura in ApplyModifier)
3548 if ((*i).second->IsInUse())
3550 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());
3551 continue;
3553 RemoveAurasDueToSpell(i_spellId);
3555 if( m_Auras.empty() )
3556 break;
3557 else
3558 next = m_Auras.begin();
3560 else if( is_sspt && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId) )
3562 // cannot remove higher rank
3563 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3564 return false;
3566 // Its a parent aura (create this aura in ApplyModifier)
3567 if ((*i).second->IsInUse())
3569 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());
3570 continue;
3572 RemoveAurasDueToSpell(i_spellId);
3574 if( m_Auras.empty() )
3575 break;
3576 else
3577 next = m_Auras.begin();
3579 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3581 // Its a parent aura (create this aura in ApplyModifier)
3582 if ((*i).second->IsInUse())
3584 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());
3585 continue;
3587 RemoveAurasDueToSpell(i_spellId);
3589 if( m_Auras.empty() )
3590 break;
3591 else
3592 next = m_Auras.begin();
3594 // Potions stack aura by aura (elixirs/flask already checked)
3595 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3597 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3599 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3600 return false; // cannot remove higher rank
3602 // Its a parent aura (create this aura in ApplyModifier)
3603 if ((*i).second->IsInUse())
3605 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());
3606 continue;
3608 RemoveAura(i);
3609 next = i;
3613 return true;
3616 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3618 spellEffectPair spair = spellEffectPair(spellId, effindex);
3619 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3621 if(iter->second!=except)
3623 RemoveAura(iter);
3624 iter = m_Auras.lower_bound(spair);
3626 else
3627 ++iter;
3631 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3633 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3635 Aura *aur = iter->second;
3636 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3637 RemoveAura(iter);
3638 else
3639 ++iter;
3643 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
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)
3650 // Custom dispel case
3651 // Unstable Affliction
3652 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3654 int32 damage = aur->GetModifier()->m_amount*9;
3655 uint64 caster_guid = aur->GetCasterGUID();
3657 // Remove aura
3658 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3660 // backfire damage and silence
3661 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3663 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3665 else
3666 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3668 else
3669 ++iter;
3673 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3675 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3677 Aura *aur = iter->second;
3678 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3680 int32 basePoints = aur->GetBasePoints();
3681 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3682 // some different constructors
3683 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3685 // set its duration and maximum duration
3686 // max duration 2 minutes (in msecs)
3687 int32 dur = aur->GetAuraDuration();
3688 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3689 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3690 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3692 // Unregister _before_ adding to stealer
3693 aur->UnregisterSingleCastAura();
3695 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3696 new_aur->SetIsSingleTarget(false);
3698 // add the new aura to stealer
3699 stealer->AddAura(new_aur);
3701 // Remove aura as dispel
3702 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3704 else
3705 ++iter;
3709 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3711 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3713 if (iter->second->GetId() == spellId)
3714 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3715 else
3716 ++iter;
3720 void Unit::RemoveAurasWithDispelType( DispelType type )
3722 // Create dispel mask by dispel type
3723 uint32 dispelMask = GetDispellMask(type);
3724 // Dispel all existing auras vs current dispel type
3725 AuraMap& auras = GetAuras();
3726 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3728 SpellEntry const* spell = itr->second->GetSpellProto();
3729 if( (1<<spell->Dispel) & dispelMask )
3731 // Dispel aura
3732 RemoveAurasDueToSpell(spell->Id);
3733 itr = auras.begin();
3735 else
3736 ++itr;
3740 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3742 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3743 if(iter != m_Auras.end())
3745 if (iter->second->modStackAmount(-1))
3746 RemoveAura(iter);
3750 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3752 for (int i=0; i<3; ++i)
3753 RemoveSingleAuraFromStack(spellId, i);
3756 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3758 for (int i = 0; i < 3; ++i)
3759 RemoveAura(spellId,i,except);
3762 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3764 for (int k=0; k < 3; ++k)
3766 spellEffectPair spair = spellEffectPair(spellId, k);
3767 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3769 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3771 RemoveAura(iter);
3772 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3774 else
3775 ++iter;
3780 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3782 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3784 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3785 RemoveAura(iter);
3786 else
3787 ++iter;
3791 void Unit::RemoveNotOwnSingleTargetAuras()
3793 // single target auras from other casters
3794 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3796 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3797 RemoveAura(iter);
3798 else
3799 ++iter;
3802 // single target auras at other targets
3803 AuraList& scAuras = GetSingleCastAuras();
3804 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3806 Aura* aura = *iter;
3807 if (aura->GetTarget()!=this)
3809 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3810 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3811 iter = scAuras.begin();
3813 else
3814 ++iter;
3819 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3821 Aura* Aur = i->second;
3822 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3824 Aur->UnregisterSingleCastAura();
3826 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3827 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3829 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3832 // Set remove mode
3833 Aur->SetRemoveMode(mode);
3834 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3835 // remove aura from list before to prevent deleting it before
3836 m_Auras.erase(i);
3837 ++m_removedAuras; // internal count used by unit update
3839 // Statue unsummoned at aura remove
3840 Totem* statue = NULL;
3841 bool caster_channeled = false;
3842 if(IsChanneledSpell(AurSpellInfo))
3844 Unit* caster = Aur->GetCaster();
3846 if(caster)
3848 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3849 statue = ((Totem*)caster);
3850 else
3851 caster_channeled = caster==this;
3855 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3856 Aur->ApplyModifier(false,true);
3857 Aur->_RemoveAura();
3858 delete Aur;
3860 if(caster_channeled)
3861 RemoveAurasAtChanneledTarget (AurSpellInfo);
3863 if(statue)
3864 statue->UnSummon();
3866 // only way correctly remove all auras from list
3867 if( m_Auras.empty() )
3868 i = m_Auras.end();
3869 else
3870 i = m_Auras.begin();
3873 void Unit::RemoveAllAuras()
3875 while (!m_Auras.empty())
3877 AuraMap::iterator iter = m_Auras.begin();
3878 RemoveAura(iter);
3882 void Unit::RemoveArenaAuras(bool onleave)
3884 // in join, remove positive buffs, on end, remove negative
3885 // used to remove positive visible auras in arenas
3886 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3888 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3889 && !iter->second->IsPassive() // don't remove passive auras
3890 && (!(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)
3891 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3892 RemoveAura(iter);
3893 else
3894 ++iter;
3898 void Unit::RemoveAllAurasOnDeath()
3900 // used just after dieing to remove all visible auras
3901 // and disable the mods for the passive ones
3902 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3904 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3905 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3906 else
3907 ++iter;
3911 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3913 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3914 if (iter != m_Auras.end())
3916 if (iter->second->GetAuraDuration() < delaytime)
3917 iter->second->SetAuraDuration(0);
3918 else
3919 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3920 iter->second->SendAuraUpdate(false);
3921 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3925 void Unit::_RemoveAllAuraMods()
3927 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3929 (*i).second->ApplyModifier(false);
3933 void Unit::_ApplyAllAuraMods()
3935 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3937 (*i).second->ApplyModifier(true);
3941 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3943 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3944 if (iter != m_Auras.end())
3945 return iter->second;
3946 return NULL;
3949 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
3951 AuraList const& auras = GetAurasByType(type);
3952 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
3954 SpellEntry const *spell = (*i)->GetSpellProto();
3955 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
3957 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
3958 continue;
3959 return (*i);
3962 return NULL;
3965 bool Unit::HasAura(uint32 spellId) const
3967 for (int i = 0; i < 3 ; ++i)
3969 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3970 if (iter != m_Auras.end())
3971 return true;
3973 return false;
3976 void Unit::AddDynObject(DynamicObject* dynObj)
3978 m_dynObjGUIDs.push_back(dynObj->GetGUID());
3981 void Unit::RemoveDynObject(uint32 spellid)
3983 if(m_dynObjGUIDs.empty())
3984 return;
3985 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3987 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
3988 if(!dynObj)
3990 i = m_dynObjGUIDs.erase(i);
3992 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
3994 dynObj->Delete();
3995 i = m_dynObjGUIDs.erase(i);
3997 else
3998 ++i;
4002 void Unit::RemoveAllDynObjects()
4004 while(!m_dynObjGUIDs.empty())
4006 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4007 if(dynObj)
4008 dynObj->Delete();
4009 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4013 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4015 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4017 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4018 if(!dynObj)
4020 i = m_dynObjGUIDs.erase(i);
4021 continue;
4024 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4025 return dynObj;
4026 ++i;
4028 return NULL;
4031 DynamicObject * Unit::GetDynObject(uint32 spellId)
4033 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4035 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4036 if(!dynObj)
4038 i = m_dynObjGUIDs.erase(i);
4039 continue;
4042 if (dynObj->GetSpellId() == spellId)
4043 return dynObj;
4044 ++i;
4046 return NULL;
4049 GameObject* Unit::GetGameObject(uint32 spellId) const
4051 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4052 if ((*i)->GetSpellId() == spellId)
4053 return *i;
4055 return NULL;
4058 void Unit::AddGameObject(GameObject* gameObj)
4060 assert(gameObj && gameObj->GetOwnerGUID()==0);
4061 m_gameObj.push_back(gameObj);
4062 gameObj->SetOwnerGUID(GetGUID());
4064 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4066 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4067 // Need disable spell use for owner
4068 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4069 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4070 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4074 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4076 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4078 gameObj->SetOwnerGUID(0);
4080 // GO created by some spell
4081 if (uint32 spellid = gameObj->GetSpellId())
4083 RemoveAurasDueToSpell(spellid);
4085 if (GetTypeId()==TYPEID_PLAYER)
4087 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4088 // Need activate spell use for owner
4089 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4090 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4091 ((Player*)this)->SendCooldownEvent(createBySpell);
4095 m_gameObj.remove(gameObj);
4097 if(del)
4099 gameObj->SetRespawnTime(0);
4100 gameObj->Delete();
4104 void Unit::RemoveGameObject(uint32 spellid, bool del)
4106 if(m_gameObj.empty())
4107 return;
4108 GameObjectList::iterator i, next;
4109 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4111 next = i;
4112 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4114 (*i)->SetOwnerGUID(0);
4115 if(del)
4117 (*i)->SetRespawnTime(0);
4118 (*i)->Delete();
4121 next = m_gameObj.erase(i);
4123 else
4124 ++next;
4128 void Unit::RemoveAllGameObjects()
4130 // remove references to unit
4131 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4133 (*i)->SetOwnerGUID(0);
4134 (*i)->SetRespawnTime(0);
4135 (*i)->Delete();
4136 i = m_gameObj.erase(i);
4140 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4142 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4143 data.append(log->target->GetPackGUID());
4144 data.append(log->attacker->GetPackGUID());
4145 data << uint32(log->SpellID);
4146 data << uint32(log->damage); //damage amount
4147 data << uint32(0);
4148 data << uint8 (log->schoolMask); //damage school
4149 data << uint32(log->absorb); //AbsorbedDamage
4150 data << uint32(log->resist); //resist
4151 data << uint8 (log->phusicalLog); // damsge type? flag
4152 data << uint8 (log->unused); //unused
4153 data << uint32(log->blocked); //blocked
4154 data << uint32(log->HitInfo);
4155 data << uint8 (0); // flag to use extend data
4156 SendMessageToSet( &data, true );
4159 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4161 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
4162 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4163 data.append(target->GetPackGUID());
4164 data.append(GetPackGUID());
4165 data << uint32(SpellID);
4166 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
4167 data << uint32(0); // wotlk
4168 data << uint8(damageSchoolMask); // spell school
4169 data << uint32(AbsorbedDamage); // AbsorbedDamage
4170 data << uint32(Resist); // resist
4171 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
4172 data << uint8(0); // unk isFromAura
4173 data << uint32(Blocked); // blocked
4174 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
4175 data << uint8(0); // isDebug?
4176 SendMessageToSet( &data, true );
4179 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4181 // Not much to do if no flags are set.
4182 if (procAttacker)
4183 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4184 // Now go on with a victim's events'n'auras
4185 // Not much to do if no flags are set or there is no victim
4186 if(pVictim && pVictim->isAlive() && procVictim)
4187 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4190 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4192 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4193 data << uint32(spellID);
4194 data << uint64(GetGUID());
4195 data << uint8(0); // can be 0 or 1
4196 data << uint32(1); // target count
4197 // for(i = 0; i < target count; ++i)
4198 data << uint64(target->GetGUID()); // target GUID
4199 data << uint8(missInfo);
4200 // end loop
4201 SendMessageToSet(&data, true);
4204 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4206 uint32 count = 1;
4207 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4208 data << (uint32)damageInfo->HitInfo;
4209 data.append(GetPackGUID());
4210 data.append(damageInfo->target->GetPackGUID());
4211 data << (uint32)(damageInfo->damage); // Full damage
4212 data << uint32(0); // overkill value
4214 data << (uint8)count; // Sub damage count
4216 for(int i = 0; i < count; ++i)
4218 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4219 data << (float)damageInfo->damage; // sub damage
4220 data << (uint32)damageInfo->damage; // Sub Damage
4223 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4225 for(int i = 0; i < count; ++i)
4226 data << (uint32)damageInfo->absorb; // Absorb
4229 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4231 for(int i = 0; i < count; ++i)
4232 data << (uint32)damageInfo->resist; // Resist
4235 data << (uint8)damageInfo->TargetState;
4236 data << (uint32)0;
4237 data << (uint32)0;
4239 if(damageInfo->HitInfo & HITINFO_BLOCK)
4240 data << (uint32)damageInfo->blocked_amount;
4242 if(damageInfo->HitInfo & HITINFO_UNK3)
4243 data << uint32(0);
4245 if(damageInfo->HitInfo & HITINFO_UNK1)
4247 data << uint32(0);
4248 data << float(0);
4249 data << float(0);
4250 data << float(0);
4251 data << float(0);
4252 data << float(0);
4253 data << float(0);
4254 data << float(0);
4255 data << float(0);
4256 for(uint8 i = 0; i < 5; ++i)
4258 data << float(0);
4259 data << float(0);
4261 data << uint32(0);
4264 SendMessageToSet( &data, true );
4267 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4269 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4271 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4272 data << uint32(HitInfo); // flags
4273 data.append(GetPackGUID());
4274 data.append(target->GetPackGUID());
4275 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4276 data << uint32(0); // overkill value
4278 data << (uint8)SwingType; // count?
4280 // for(i = 0; i < SwingType; ++i)
4281 data << (uint32)damageSchoolMask;
4282 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4283 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4284 // end loop
4286 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4288 // for(i = 0; i < SwingType; ++i)
4289 data << uint32(AbsorbDamage);
4290 // end loop
4293 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4295 // for(i = 0; i < SwingType; ++i)
4296 data << uint32(Resist);
4297 // end loop
4300 data << (uint8)TargetState;
4301 data << (uint32)0;
4302 data << (uint32)0;
4304 if(HitInfo & HITINFO_BLOCK)
4306 data << uint32(BlockedAmount);
4309 if(HitInfo & HITINFO_UNK3)
4311 data << uint32(0);
4314 if(HitInfo & HITINFO_UNK1)
4316 data << uint32(0);
4317 data << float(0);
4318 data << float(0);
4319 data << float(0);
4320 data << float(0);
4321 data << float(0);
4322 data << float(0);
4323 data << float(0);
4324 data << float(0);
4325 for(uint8 i = 0; i < 5; ++i)
4327 data << float(0);
4328 data << float(0);
4330 data << uint32(0);
4333 SendMessageToSet( &data, true );
4336 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4338 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4340 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4341 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4343 uint32 triggered_spell_id = 0;
4344 Unit* target = pVictim;
4345 int32 basepoints0 = 0;
4347 switch(hasteSpell->SpellFamilyName)
4349 case SPELLFAMILY_ROGUE:
4351 switch(hasteSpell->Id)
4353 // Blade Flurry
4354 case 13877:
4355 case 33735:
4357 target = SelectNearbyTarget();
4358 if(!target)
4359 return false;
4360 basepoints0 = damage;
4361 triggered_spell_id = 22482;
4362 break;
4365 break;
4369 // processed charge only counting case
4370 if(!triggered_spell_id)
4371 return true;
4373 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4375 if(!triggerEntry)
4377 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4378 return false;
4381 // default case
4382 if(!target || target!=this && !target->isAlive())
4383 return false;
4385 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4386 return false;
4388 if(basepoints0)
4389 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4390 else
4391 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4393 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4394 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4396 return true;
4399 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4401 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4402 uint32 effIndex = triggeredByAura->GetEffIndex();
4403 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4405 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4406 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4408 uint32 triggered_spell_id = 0;
4409 Unit* target = pVictim;
4410 int32 basepoints0 = 0;
4412 switch(dummySpell->SpellFamilyName)
4414 case SPELLFAMILY_GENERIC:
4416 switch (dummySpell->Id)
4418 // Eye for an Eye
4419 case 9799:
4420 case 25988:
4422 // return damage % to attacker but < 50% own total health
4423 basepoints0 = triggerAmount*int32(damage)/100;
4424 if(basepoints0 > GetMaxHealth()/2)
4425 basepoints0 = GetMaxHealth()/2;
4427 triggered_spell_id = 25997;
4428 break;
4430 // Sweeping Strikes
4431 case 12328:
4432 case 18765:
4433 case 35429:
4435 // prevent chain of triggered spell from same triggered spell
4436 if(procSpell && procSpell->Id==26654)
4437 return false;
4439 target = SelectNearbyTarget();
4440 if(!target)
4441 return false;
4443 triggered_spell_id = 26654;
4444 break;
4446 // Unstable Power
4447 case 24658:
4449 if (!procSpell || procSpell->Id == 24659)
4450 return false;
4451 // Need remove one 24659 aura
4452 RemoveSingleSpellAurasFromStack(24659);
4453 return true;
4455 // Restless Strength
4456 case 24661:
4458 // Need remove one 24662 aura
4459 RemoveSingleSpellAurasFromStack(24662);
4460 return true;
4462 // Adaptive Warding (Frostfire Regalia set)
4463 case 28764:
4465 if(!procSpell)
4466 return false;
4468 // find Mage Armor
4469 bool found = false;
4470 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4471 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4473 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4475 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4477 found=true;
4478 break;
4482 if(!found)
4483 return false;
4485 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4487 case SPELL_SCHOOL_NORMAL:
4488 case SPELL_SCHOOL_HOLY:
4489 return false; // ignored
4490 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4491 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4492 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4493 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4494 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4495 default:
4496 return false;
4499 target = this;
4500 break;
4502 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4503 case 27539:
4505 if(!procSpell)
4506 return false;
4508 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4510 case SPELL_SCHOOL_NORMAL:
4511 return false; // ignore
4512 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4513 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4514 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4515 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4516 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4517 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4518 default:
4519 return false;
4522 target = this;
4523 break;
4525 // Mana Leech (Passive) (Priest Pet Aura)
4526 case 28305:
4528 // Cast on owner
4529 target = GetOwner();
4530 if(!target)
4531 return false;
4533 triggered_spell_id = 34650;
4534 break;
4536 // Mark of Malice
4537 case 33493:
4539 // Cast finish spell at last charge
4540 if (triggeredByAura->GetAuraCharges() > 1)
4541 return false;
4543 target = this;
4544 triggered_spell_id = 33494;
4545 break;
4547 // Twisted Reflection (boss spell)
4548 case 21063:
4549 triggered_spell_id = 21064;
4550 break;
4551 // Vampiric Aura (boss spell)
4552 case 38196:
4554 basepoints0 = 3 * damage; // 300%
4555 if (basepoints0 < 0)
4556 return false;
4558 triggered_spell_id = 31285;
4559 target = this;
4560 break;
4562 // Aura of Madness (Darkmoon Card: Madness trinket)
4563 //=====================================================
4564 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4565 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4566 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4567 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4568 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4569 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4570 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4571 // 41011 Martyr Complex: +35 stamina (All classes)
4572 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4573 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4574 case 39446:
4576 if(GetTypeId() != TYPEID_PLAYER)
4577 return false;
4579 // Select class defined buff
4580 switch (getClass())
4582 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4583 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4585 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4586 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4587 break;
4589 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4590 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4592 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4593 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4594 break;
4596 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4597 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4598 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4599 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4601 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4602 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4603 break;
4605 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4607 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4608 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4609 break;
4611 default:
4612 return false;
4615 target = this;
4616 if (roll_chance_i(10))
4617 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4618 break;
4621 // TODO: need find item for aura and triggered spells
4622 // Sunwell Exalted Caster Neck (??? neck)
4623 // cast ??? Light's Wrath if Exalted by Aldor
4624 // cast ??? Arcane Bolt if Exalted by Scryers*/
4625 case 46569:
4626 return false; // disable for while
4629 if(GetTypeId() != TYPEID_PLAYER)
4630 return false;
4632 // Get Aldor reputation rank
4633 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4635 target = this;
4636 triggered_spell_id = ???
4637 break;
4639 // Get Scryers reputation rank
4640 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4642 triggered_spell_id = ???
4643 break;
4645 return false;
4646 }/**/
4647 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4648 // cast 45479 Light's Wrath if Exalted by Aldor
4649 // cast 45429 Arcane Bolt if Exalted by Scryers
4650 case 45481:
4652 if(GetTypeId() != TYPEID_PLAYER)
4653 return false;
4655 // Get Aldor reputation rank
4656 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4658 target = this;
4659 triggered_spell_id = 45479;
4660 break;
4662 // Get Scryers reputation rank
4663 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4665 triggered_spell_id = 45429;
4666 break;
4668 return false;
4670 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4671 // cast 45480 Light's Strength if Exalted by Aldor
4672 // cast 45428 Arcane Strike if Exalted by Scryers
4673 case 45482:
4675 if(GetTypeId() != TYPEID_PLAYER)
4676 return false;
4678 // Get Aldor reputation rank
4679 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4681 target = this;
4682 triggered_spell_id = 45480;
4683 break;
4685 // Get Scryers reputation rank
4686 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4688 triggered_spell_id = 45428;
4689 break;
4691 return false;
4693 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4694 // cast 45431 Arcane Insight if Exalted by Aldor
4695 // cast 45432 Light's Ward if Exalted by Scryers
4696 case 45483:
4698 if(GetTypeId() != TYPEID_PLAYER)
4699 return false;
4701 // Get Aldor reputation rank
4702 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4704 target = this;
4705 triggered_spell_id = 45432;
4706 break;
4708 // Get Scryers reputation rank
4709 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4711 target = this;
4712 triggered_spell_id = 45431;
4713 break;
4715 return false;
4717 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4718 // cast 45478 Light's Salvation if Exalted by Aldor
4719 // cast 45430 Arcane Surge if Exalted by Scryers
4720 case 45484:
4722 if(GetTypeId() != TYPEID_PLAYER)
4723 return false;
4725 // Get Aldor reputation rank
4726 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4728 target = this;
4729 triggered_spell_id = 45478;
4730 break;
4732 // Get Scryers reputation rank
4733 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4735 triggered_spell_id = 45430;
4736 break;
4738 return false;
4740 // Living Seed
4741 case 48504:
4743 triggered_spell_id = 48503;
4744 basepoints0 = triggerAmount;
4745 target = this;
4746 break;
4748 // Vampiric Touch (generic, used by some boss)
4749 case 52723:
4750 case 60501:
4752 triggered_spell_id = 52724;
4753 basepoints0 = damage / 2;
4754 target = this;
4755 break;
4757 // Divine purpose
4758 case 31871:
4759 case 31872:
4761 // Roll chane
4762 if (!roll_chance_i(triggerAmount))
4763 return false;
4765 // Remove any stun effect on target
4766 AuraMap& Auras = pVictim->GetAuras();
4767 for(AuraMap::iterator iter = Auras.begin(); iter != Auras.end();)
4769 SpellEntry const *spell = iter->second->GetSpellProto();
4770 if( spell->Mechanic == MECHANIC_STUN ||
4771 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4773 pVictim->RemoveAurasDueToSpell(spell->Id);
4774 iter = Auras.begin();
4776 else
4777 ++iter;
4779 return true;
4782 break;
4784 case SPELLFAMILY_MAGE:
4786 // Magic Absorption
4787 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4789 if (getPowerType() != POWER_MANA)
4790 return false;
4792 // mana reward
4793 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
4794 target = this;
4795 triggered_spell_id = 29442;
4796 break;
4798 // Master of Elements
4799 if (dummySpell->SpellIconID == 1920)
4801 if(!procSpell)
4802 return false;
4804 // mana cost save
4805 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4806 basepoints0 = cost * triggerAmount/100;
4807 if( basepoints0 <=0 )
4808 return false;
4810 target = this;
4811 triggered_spell_id = 29077;
4812 break;
4814 // Hot Streak
4815 if (dummySpell->SpellIconID == 2999)
4817 if (effIndex!=0)
4818 return true;
4819 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4820 if (!counter)
4821 return true;
4823 // Count spell criticals in a row in second aura
4824 Modifier *mod = counter->GetModifier();
4825 if (procEx & PROC_EX_CRITICAL_HIT)
4827 mod->m_amount *=2;
4828 if (mod->m_amount < 100) // not enough
4829 return true;
4830 // Crititcal counted -> roll chance
4831 if (roll_chance_i(triggerAmount))
4832 CastSpell(this, 48108, true, castItem, triggeredByAura);
4834 mod->m_amount = 25;
4835 return true;
4837 // Burnout
4838 if (dummySpell->SpellIconID == 2998)
4840 if(!procSpell)
4841 return false;
4843 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4844 basepoints0 = cost * triggerAmount/100;
4845 if( basepoints0 <=0 )
4846 return false;
4847 triggered_spell_id = 44450;
4848 target = this;
4849 break;
4851 // Incanter's Regalia set (add trigger chance to Mana Shield)
4852 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4854 if(GetTypeId() != TYPEID_PLAYER)
4855 return false;
4857 target = this;
4858 triggered_spell_id = 37436;
4859 break;
4861 switch(dummySpell->Id)
4863 // Ignite
4864 case 11119:
4865 case 11120:
4866 case 12846:
4867 case 12847:
4868 case 12848:
4870 switch (dummySpell->Id)
4872 case 11119: basepoints0 = int32(0.04f*damage); break;
4873 case 11120: basepoints0 = int32(0.08f*damage); break;
4874 case 12846: basepoints0 = int32(0.12f*damage); break;
4875 case 12847: basepoints0 = int32(0.16f*damage); break;
4876 case 12848: basepoints0 = int32(0.20f*damage); break;
4877 default:
4878 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4879 return false;
4882 triggered_spell_id = 12654;
4883 break;
4885 // Combustion
4886 case 11129:
4888 //last charge and crit
4889 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4891 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4892 return true; // charge counting (will removed)
4895 CastSpell(this, 28682, true, castItem, triggeredByAura);
4896 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4899 break;
4901 case SPELLFAMILY_WARRIOR:
4903 // Retaliation
4904 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4906 // check attack comes not from behind
4907 if (!HasInArc(M_PI, pVictim))
4908 return false;
4910 triggered_spell_id = 22858;
4911 break;
4913 // Second Wind
4914 if (dummySpell->SpellIconID == 1697)
4916 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4917 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4918 return false;
4919 // Need stun or root mechanic
4920 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
4921 return false;
4923 switch (dummySpell->Id)
4925 case 29838: triggered_spell_id=29842; break;
4926 case 29834: triggered_spell_id=29841; break;
4927 case 42770: triggered_spell_id=42771; break;
4928 default:
4929 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4930 return false;
4933 target = this;
4934 break;
4936 // Damage Shield
4937 if (dummySpell->SpellIconID == 3214)
4939 triggered_spell_id = 59653;
4940 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
4941 break;
4943 break;
4945 case SPELLFAMILY_WARLOCK:
4947 // Seed of Corruption
4948 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4950 Modifier* mod = triggeredByAura->GetModifier();
4951 // if damage is more than need or target die from damage deal finish spell
4952 if( mod->m_amount <= damage || GetHealth() <= damage )
4954 // remember guid before aura delete
4955 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4957 // Remove aura (before cast for prevent infinite loop handlers)
4958 RemoveAurasDueToSpell(triggeredByAura->GetId());
4960 // Cast finish spell (triggeredByAura already not exist!)
4961 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4962 return true; // no hidden cooldown
4965 // Damage counting
4966 mod->m_amount-=damage;
4967 return true;
4969 // Seed of Corruption (Mobs cast) - no die req
4970 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4972 Modifier* mod = triggeredByAura->GetModifier();
4973 // if damage is more than need deal finish spell
4974 if( mod->m_amount <= damage )
4976 // remember guid before aura delete
4977 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4979 // Remove aura (before cast for prevent infinite loop handlers)
4980 RemoveAurasDueToSpell(triggeredByAura->GetId());
4982 // Cast finish spell (triggeredByAura already not exist!)
4983 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
4984 return true; // no hidden cooldown
4986 // Damage counting
4987 mod->m_amount-=damage;
4988 return true;
4990 // Fel Synergy
4991 if (dummySpell->SpellIconID == 3222)
4993 target = GetPet();
4994 if (!target)
4995 return false;
4996 triggered_spell_id = 54181;
4997 basepoints0 = damage * triggerAmount / 100;
4998 break;
5000 switch(dummySpell->Id)
5002 // Nightfall
5003 case 18094:
5004 case 18095:
5006 target = this;
5007 triggered_spell_id = 17941;
5008 break;
5010 //Soul Leech
5011 case 30293:
5012 case 30295:
5013 case 30296:
5015 // health
5016 basepoints0 = int32(damage*triggerAmount/100);
5017 target = this;
5018 triggered_spell_id = 30294;
5019 break;
5021 // Shadowflame (Voidheart Raiment set bonus)
5022 case 37377:
5024 triggered_spell_id = 37379;
5025 break;
5027 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5028 case 37381:
5030 target = GetPet();
5031 if(!target)
5032 return false;
5034 // heal amount
5035 basepoints0 = damage * triggerAmount/100;
5036 triggered_spell_id = 37382;
5037 break;
5039 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5040 case 39437:
5042 triggered_spell_id = 37378;
5043 break;
5046 break;
5048 case SPELLFAMILY_PRIEST:
5050 // Vampiric Touch
5051 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
5053 if(!pVictim || !pVictim->isAlive())
5054 return false;
5056 // pVictim is caster of aura
5057 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5058 return false;
5060 // energize amount
5061 basepoints0 = triggerAmount*damage/100;
5062 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5063 return true; // no hidden cooldown
5065 // Divine Aegis
5066 if (dummySpell->SpellIconID == 2820)
5068 basepoints0 = damage * triggerAmount/100;
5069 triggered_spell_id = 47753;
5070 break;
5072 switch(dummySpell->Id)
5074 // Vampiric Embrace
5075 case 15286:
5077 if(!pVictim || !pVictim->isAlive())
5078 return false;
5080 // pVictim is caster of aura
5081 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5082 return false;
5084 // heal amount
5085 int32 team = triggerAmount*damage/500;
5086 int32 self = triggerAmount*damage/100 - team;
5087 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5088 return true; // no hidden cooldown
5090 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5091 case 40438:
5093 // Shadow Word: Pain
5094 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5095 triggered_spell_id = 40441;
5096 // Renew
5097 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5098 triggered_spell_id = 40440;
5099 else
5100 return false;
5102 target = this;
5103 break;
5105 // Oracle Healing Bonus ("Garments of the Oracle" set)
5106 case 26169:
5108 // heal amount
5109 basepoints0 = int32(damage * 10/100);
5110 target = this;
5111 triggered_spell_id = 26170;
5112 break;
5114 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5115 case 39372:
5117 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5118 return false;
5120 // heal amount
5121 basepoints0 = damage * triggerAmount/100;
5122 target = this;
5123 triggered_spell_id = 39373;
5124 break;
5126 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5127 case 28809:
5129 triggered_spell_id = 28810;
5130 break;
5132 // Glyph of Dispel Magic
5133 case 55677:
5135 if(!target->IsFriendlyTo(this))
5136 return false;
5138 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5139 triggered_spell_id = 56131;
5140 break;
5143 break;
5145 case SPELLFAMILY_DRUID:
5147 switch(dummySpell->Id)
5149 // Healing Touch (Dreamwalker Raiment set)
5150 case 28719:
5152 // mana back
5153 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5154 target = this;
5155 triggered_spell_id = 28742;
5156 break;
5158 // Healing Touch Refund (Idol of Longevity trinket)
5159 case 28847:
5161 target = this;
5162 triggered_spell_id = 28848;
5163 break;
5165 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5166 case 37288:
5167 case 37295:
5169 target = this;
5170 triggered_spell_id = 37238;
5171 break;
5173 // Druid Tier 6 Trinket
5174 case 40442:
5176 float chance;
5178 // Starfire
5179 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5181 triggered_spell_id = 40445;
5182 chance = 25.f;
5184 // Rejuvenation
5185 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5187 triggered_spell_id = 40446;
5188 chance = 25.f;
5190 // Mangle (cat/bear)
5191 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5193 triggered_spell_id = 40452;
5194 chance = 40.f;
5196 else
5197 return false;
5199 if (!roll_chance_f(chance))
5200 return false;
5202 target = this;
5203 break;
5205 // Maim Interrupt
5206 case 44835:
5208 // Deadly Interrupt Effect
5209 triggered_spell_id = 32747;
5210 break;
5213 // Eclipse
5214 if (dummySpell->SpellIconID == 2856)
5216 if (!procSpell)
5217 return false;
5218 // Only 0 aura can proc
5219 if (effIndex!=0)
5220 return true;
5221 // Wrath crit
5222 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5224 if (!roll_chance_i(60))
5225 return false;
5226 triggered_spell_id = 48518;
5227 target = this;
5228 break;
5230 // Starfire crit
5231 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5233 triggered_spell_id = 48517;
5234 target = this;
5235 break;
5237 return false;
5239 // Living Seed
5240 else if (dummySpell->SpellIconID == 2860)
5242 triggered_spell_id = 48504;
5243 basepoints0 = triggerAmount * damage / 100;
5244 break;
5246 break;
5248 case SPELLFAMILY_ROGUE:
5250 switch(dummySpell->Id)
5252 // Deadly Throw Interrupt
5253 case 32748:
5255 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5256 if(this == pVictim)
5257 return false;
5259 triggered_spell_id = 32747;
5260 break;
5263 // Cut to the Chase
5264 if( dummySpell->SpellIconID == 2909 )
5266 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5267 // lookup Slice and Dice
5268 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5269 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5271 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5272 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5273 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5275 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5276 (*itr)->RefreshAura();
5277 return true;
5280 return false;
5282 // Deadly Brew
5283 if( dummySpell->SpellIconID == 2963 )
5285 triggered_spell_id = 25809;
5286 break;
5288 // Quick Recovery
5289 if( dummySpell->SpellIconID == 2116 )
5291 if(!procSpell)
5292 return false;
5294 // energy cost save
5295 basepoints0 = procSpell->manaCost * triggerAmount/100;
5296 if(basepoints0 <= 0)
5297 return false;
5299 target = this;
5300 triggered_spell_id = 31663;
5301 break;
5303 break;
5305 case SPELLFAMILY_HUNTER:
5307 // Thrill of the Hunt
5308 if ( dummySpell->SpellIconID == 2236 )
5310 if(!procSpell)
5311 return false;
5313 // mana cost save
5314 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5315 basepoints0 = mana * 40/100;
5316 if(basepoints0 <= 0)
5317 return false;
5319 target = this;
5320 triggered_spell_id = 34720;
5321 break;
5323 // Hunting Party
5324 if ( dummySpell->SpellIconID == 3406 )
5326 triggered_spell_id = 57669;
5327 target = this;
5328 break;
5330 // Lock and Load
5331 if ( dummySpell->SpellIconID == 3579 )
5333 // Proc only from periodic (from trap activation proc another aura of this spell)
5334 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5335 return false;
5336 triggered_spell_id = 56453;
5337 target = this;
5338 break;
5340 // Rapid Recuperation
5341 if ( dummySpell->SpellIconID == 3560 )
5343 // This effect only from Rapid Killing (mana regen)
5344 if (!(procSpell->SpellFamilyFlags & 0x0100000000000000LL))
5345 return false;
5346 triggered_spell_id = 56654;
5347 target = this;
5348 break;
5350 break;
5352 case SPELLFAMILY_PALADIN:
5354 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5355 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && effIndex==0)
5357 triggered_spell_id = 25742;
5358 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5359 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5360 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5361 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5362 break;
5364 // Sacred Shield
5365 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5367 triggered_spell_id = 58597;
5368 target = this;
5369 break;
5371 // Righteous Vengeance
5372 if (dummySpell->SpellIconID == 3025)
5374 // 4 damage tick
5375 basepoints0 = triggerAmount*damage/400;
5376 triggered_spell_id = 61840;
5377 break;
5379 // Sheath of Light
5380 if (dummySpell->SpellIconID == 3030)
5382 // 4 healing tick
5383 basepoints0 = triggerAmount*damage/400;
5384 triggered_spell_id = 54203;
5385 break;
5387 switch(dummySpell->Id)
5389 // Judgement of Light
5390 case 20185:
5392 // Get judgement caster
5393 Unit *caster = triggeredByAura->GetCaster();
5394 if (!caster)
5395 return false;
5396 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5397 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5398 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5399 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5400 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5401 return true;
5403 // Judgement of Wisdom
5404 case 20186:
5406 if (pVictim->getPowerType() == POWER_MANA)
5407 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5408 return true;
5410 // Holy Power (Redemption Armor set)
5411 case 28789:
5413 if(!pVictim)
5414 return false;
5416 // Set class defined buff
5417 switch (pVictim->getClass())
5419 case CLASS_PALADIN:
5420 case CLASS_PRIEST:
5421 case CLASS_SHAMAN:
5422 case CLASS_DRUID:
5423 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5424 break;
5425 case CLASS_MAGE:
5426 case CLASS_WARLOCK:
5427 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5428 break;
5429 case CLASS_HUNTER:
5430 case CLASS_ROGUE:
5431 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5432 break;
5433 case CLASS_WARRIOR:
5434 triggered_spell_id = 28790; // Increases the friendly target's armor
5435 break;
5436 default:
5437 return false;
5439 break;
5441 // Seal of Vengeance (damage calc on apply aura)
5442 case 31801:
5444 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5445 return false;
5447 triggered_spell_id = 31803;
5448 break;
5450 // Spiritual Attunement
5451 case 31785:
5452 case 33776:
5454 // if healed by another unit (pVictim)
5455 if(this == pVictim)
5456 return false;
5458 // heal amount
5459 basepoints0 = triggerAmount*damage/100;
5460 target = this;
5461 triggered_spell_id = 31786;
5462 break;
5464 // Seal of Blood do damage trigger
5465 case 31892:
5467 if (effIndex == 0) // 0 effect - is proc on enemy
5468 triggered_spell_id = 31893;
5469 else if (effIndex == 1) // 1 effect - is proc on self
5471 // add spell damage from prev effect (27%)
5472 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5473 basepoints0 = triggerAmount * damage / 100;
5474 target = this;
5475 triggered_spell_id = 32221;
5477 else
5478 return true;
5479 break;
5481 // Seal of the Martyr do damage trigger
5482 case 53720:
5484 if (effIndex == 0) // 0 effect - is proc on enemy
5485 triggered_spell_id = 53719;
5486 else if (effIndex == 1) // 1 effect - is proc on self
5488 // add spell damage from prev effect (27%)
5489 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5490 basepoints0 = triggerAmount * damage / 100;
5491 target = this;
5492 triggered_spell_id = 53718;
5494 else
5495 return true;
5496 break;
5498 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5499 case 40470:
5501 if( !procSpell )
5502 return false;
5504 float chance;
5506 // Flash of light/Holy light
5507 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5509 triggered_spell_id = 40471;
5510 chance = 15.f;
5512 // Judgement
5513 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5515 triggered_spell_id = 40472;
5516 chance = 50.f;
5518 else
5519 return false;
5521 if (!roll_chance_f(chance))
5522 return false;
5524 break;
5526 // Glyph of Divinity
5527 case 54939:
5529 // Lookup base amount mana restore
5530 for (int i=0; i<3;i++)
5531 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5533 int32 mana = procSpell->EffectBasePoints[i];
5534 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5535 break;
5537 return true;
5539 // Glyph of Flash of Light
5540 case 54936:
5542 triggered_spell_id = 54957;
5543 basepoints0 = triggerAmount*damage/100;
5544 break;
5546 // Glyph of Holy Light
5547 case 54937:
5549 triggered_spell_id = 54968;
5550 basepoints0 = triggerAmount*damage/100;
5551 break;
5554 break;
5556 case SPELLFAMILY_SHAMAN:
5558 switch(dummySpell->Id)
5560 // Totemic Power (The Earthshatterer set)
5561 case 28823:
5563 if( !pVictim )
5564 return false;
5566 // Set class defined buff
5567 switch (pVictim->getClass())
5569 case CLASS_PALADIN:
5570 case CLASS_PRIEST:
5571 case CLASS_SHAMAN:
5572 case CLASS_DRUID:
5573 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5574 break;
5575 case CLASS_MAGE:
5576 case CLASS_WARLOCK:
5577 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5578 break;
5579 case CLASS_HUNTER:
5580 case CLASS_ROGUE:
5581 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5582 break;
5583 case CLASS_WARRIOR:
5584 triggered_spell_id = 28827; // Increases the friendly target's armor
5585 break;
5586 default:
5587 return false;
5589 break;
5591 // Lesser Healing Wave (Totem of Flowing Water Relic)
5592 case 28849:
5594 target = this;
5595 triggered_spell_id = 28850;
5596 break;
5598 // Windfury Weapon (Passive) 1-5 Ranks
5599 case 33757:
5601 if(GetTypeId()!=TYPEID_PLAYER)
5602 return false;
5604 if(!castItem || !castItem->IsEquipped())
5605 return false;
5607 // custom cooldown processing case
5608 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5609 return false;
5611 // Now amount of extra power stored in 1 effect of Enchant spell
5612 // Get it by item enchant id
5613 uint32 spellId;
5614 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5616 case 283: spellId = 8232; break; // 1 Rank
5617 case 284: spellId = 8235; break; // 2 Rank
5618 case 525: spellId = 10486; break; // 3 Rank
5619 case 1669:spellId = 16362; break; // 4 Rank
5620 case 2636:spellId = 25505; break; // 5 Rank
5621 case 3785:spellId = 58801; break; // 6 Rank
5622 case 3786:spellId = 58803; break; // 7 Rank
5623 case 3787:spellId = 58804; break; // 8 Rank
5624 default:
5626 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5627 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5628 return false;
5632 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5633 if(!windfurySpellEntry)
5635 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5636 return false;
5639 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5641 // Off-Hand case
5642 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5644 // Value gained from additional AP
5645 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5646 triggered_spell_id = 33750;
5648 // Main-Hand case
5649 else
5651 // Value gained from additional AP
5652 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5653 triggered_spell_id = 25504;
5656 // apply cooldown before cast to prevent processing itself
5657 if( cooldown )
5658 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5660 // Attack Twice
5661 for ( uint32 i = 0; i<2; ++i )
5662 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5664 return true;
5666 // Shaman Tier 6 Trinket
5667 case 40463:
5669 if( !procSpell )
5670 return false;
5672 float chance;
5673 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5675 triggered_spell_id = 40465; // Lightning Bolt
5676 chance = 15.f;
5678 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5680 triggered_spell_id = 40465; // Lesser Healing Wave
5681 chance = 10.f;
5683 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5685 triggered_spell_id = 40466; // Stormstrike
5686 chance = 50.f;
5688 else
5689 return false;
5691 if (!roll_chance_f(chance))
5692 return false;
5694 target = this;
5695 break;
5697 // Glyph of Healing Wave
5698 case 55440:
5700 // Not proc from self heals
5701 if (this==pVictim)
5702 return false;
5703 basepoints0 = triggerAmount * damage / 100;
5704 target = this;
5705 triggered_spell_id = 55533;
5706 break;
5708 // Spirit Hunt
5709 case 58877:
5711 // Cast on owner
5712 target = GetOwner();
5713 if(!target)
5714 return false;
5715 basepoints0 = triggerAmount * damage / 100;
5716 triggered_spell_id = 58879;
5717 break;
5720 // Ancestral Awakening
5721 if (dummySpell->SpellIconID == 3065)
5723 // TODO: frite dummy fot triggered spell
5724 triggered_spell_id = 52759;
5725 basepoints0 = triggerAmount * damage / 100;
5726 target = this;
5727 break;
5729 // Earth Shield
5730 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5732 basepoints0 = triggerAmount;
5733 target = this;
5734 triggered_spell_id = 379;
5735 break;
5737 // Improved Water Shield
5738 if (dummySpell->SpellIconID == 2287)
5740 // Lesser Healing Wave need aditional 60% roll
5741 if (procSpell->SpellFamilyFlags & 0x0000000000000080LL && !roll_chance_i(60))
5742 return false;
5743 // lookup water shield
5744 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5745 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5747 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5748 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5750 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5751 CastSpell(this, spell, true, castItem, triggeredByAura);
5752 if ((*itr)->DropAuraCharge())
5753 RemoveAurasDueToSpell((*itr)->GetId());
5754 return true;
5757 return false;
5758 break;
5760 // Lightning Overload
5761 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5763 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5764 return false;
5766 // custom cooldown processing case
5767 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5768 return false;
5770 uint32 spellId = 0;
5771 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5772 switch (procSpell->Id)
5774 // Lightning Bolt
5775 case 403: spellId = 45284; break; // Rank 1
5776 case 529: spellId = 45286; break; // Rank 2
5777 case 548: spellId = 45287; break; // Rank 3
5778 case 915: spellId = 45288; break; // Rank 4
5779 case 943: spellId = 45289; break; // Rank 5
5780 case 6041: spellId = 45290; break; // Rank 6
5781 case 10391: spellId = 45291; break; // Rank 7
5782 case 10392: spellId = 45292; break; // Rank 8
5783 case 15207: spellId = 45293; break; // Rank 9
5784 case 15208: spellId = 45294; break; // Rank 10
5785 case 25448: spellId = 45295; break; // Rank 11
5786 case 25449: spellId = 45296; break; // Rank 12
5787 case 49237: spellId = 49239; break; // Rank 13
5788 case 49238: spellId = 49240; break; // Rank 14
5789 // Chain Lightning
5790 case 421: spellId = 45297; break; // Rank 1
5791 case 930: spellId = 45298; break; // Rank 2
5792 case 2860: spellId = 45299; break; // Rank 3
5793 case 10605: spellId = 45300; break; // Rank 4
5794 case 25439: spellId = 45301; break; // Rank 5
5795 case 25442: spellId = 45302; break; // Rank 6
5796 case 49268: spellId = 49270; break; // Rank 7
5797 case 49269: spellId = 49271; break; // Rank 8
5798 default:
5799 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5800 return false;
5802 // No thread generated mod
5803 // TODO: exist special flag in spell attributes for this, need found and use!
5804 SpellModifier *mod = new SpellModifier;
5805 mod->op = SPELLMOD_THREAT;
5806 mod->value = -100;
5807 mod->type = SPELLMOD_PCT;
5808 mod->spellId = dummySpell->Id;
5809 mod->mask = 0x0000000000000003LL;
5810 mod->mask2= 0LL;
5811 ((Player*)this)->AddSpellMod(mod, true);
5813 // Remove cooldown (Chain Lightning - have Category Recovery time)
5814 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5815 ((Player*)this)->RemoveSpellCooldown(spellId);
5817 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5819 ((Player*)this)->AddSpellMod(mod, false);
5821 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5822 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5824 return true;
5826 // Static Shock
5827 if(dummySpell->SpellIconID == 3059)
5829 // lookup Lightning Shield
5830 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5831 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5833 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5834 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5836 uint32 spell = 0;
5837 switch ((*itr)->GetId())
5839 case 324: spell = 26364; break;
5840 case 325: spell = 26365; break;
5841 case 905: spell = 26366; break;
5842 case 945: spell = 26367; break;
5843 case 8134: spell = 26369; break;
5844 case 10431: spell = 26370; break;
5845 case 10432: spell = 26363; break;
5846 case 25469: spell = 26371; break;
5847 case 25472: spell = 26372; break;
5848 case 49280: spell = 49278; break;
5849 case 49281: spell = 49279; break;
5850 default:
5851 return false;
5853 CastSpell(this, spell, true, castItem, triggeredByAura);
5854 if ((*itr)->DropAuraCharge())
5855 RemoveAurasDueToSpell((*itr)->GetId());
5856 return true;
5859 return false;
5860 break;
5862 break;
5864 case SPELLFAMILY_DEATHKNIGHT:
5866 // Blood Aura
5867 if (dummySpell->SpellIconID == 2636)
5869 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5870 return false;
5871 basepoints0 = triggerAmount * damage / 100;
5872 triggered_spell_id = 53168;
5873 break;
5875 // Butchery
5876 if (dummySpell->SpellIconID == 2664)
5878 basepoints0 = triggerAmount;
5879 triggered_spell_id = 50163;
5880 target = this;
5881 break;
5883 // Dancing Rune Weapon
5884 if (dummySpell->Id == 49028)
5886 // 1 dummy aura for dismiss rune blade
5887 if (effIndex!=2)
5888 return false;
5889 // TODO: wite script for this "fights on its own, doing the same attacks"
5890 // NOTE: Trigger here on every attack and spell cast
5891 return false;
5893 // Mark of Blood
5894 if (dummySpell->Id == 49005)
5896 // TODO: need more info (cooldowns/PPM)
5897 triggered_spell_id = 50424;
5898 break;
5900 // Vendetta
5901 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5903 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5904 triggered_spell_id = 50181;
5905 target = this;
5906 break;
5908 // Necrosis
5909 if (dummySpell->SpellIconID == 2709)
5911 basepoints0 = triggerAmount * damage / 100;
5912 triggered_spell_id = 51460;
5913 break;
5915 // Runic Power Back on Snare/Root
5916 if (dummySpell->Id == 61257)
5918 // only for spells and hit/crit (trigger start always) and not start from self casted spells
5919 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5920 return false;
5921 // Need snare or root mechanic
5922 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
5923 return false;
5924 triggered_spell_id = 61258;
5925 target = this;
5926 break;
5928 // Wandering Plague
5929 if (dummySpell->SpellIconID == 1614)
5931 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
5932 return false;
5933 basepoints0 = triggerAmount * damage / 100;
5934 triggered_spell_id = 50526;
5935 break;
5937 break;
5939 default:
5940 break;
5943 // processed charge only counting case
5944 if(!triggered_spell_id)
5945 return true;
5947 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5949 if(!triggerEntry)
5951 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5952 return false;
5955 // default case
5956 if(!target || target!=this && !target->isAlive())
5957 return false;
5959 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5960 return false;
5962 if(basepoints0)
5963 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5964 else
5965 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5967 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5968 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5970 return true;
5973 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5975 // Get triggered aura spell info
5976 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5978 // Basepoints of trigger aura
5979 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5981 // Set trigger spell id, target, custom basepoints
5982 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5983 Unit* target = NULL;
5984 int32 basepoints0 = 0;
5986 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
5987 basepoints0 = triggerAmount;
5989 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5990 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5992 // Try handle uncnown trigger spells
5993 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
5995 switch (auraSpellInfo->SpellFamilyName)
5997 case SPELLFAMILY_GENERIC:
5998 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
5999 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6000 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6001 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6002 trigger_spell_id = 23781;
6003 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6004 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6006 // trigger_spell_id = 48877;
6008 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6010 // trigger_spell_id = 59233;
6012 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6014 // trigger_spell_id = 29471; // gain mana
6015 // 27526; // drain mana if possible
6017 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6018 //else if (auraSpellInfo->Id==54476) // Blood Presence
6019 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6020 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6021 //else if (auraSpellInfo->Id==52856) // Charge
6022 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6024 // Pct value stored in dummy
6025 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6026 target = pVictim;
6027 break;
6029 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6030 // trigger_spell_id = 41249;
6031 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6032 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6033 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6034 // trigger_spell_id = 41055;
6035 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6036 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6037 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6039 float stat = 0.0f;
6040 // strength
6041 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6042 // agility
6043 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6044 // intellect
6045 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6046 // spirit
6047 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6049 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6050 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6051 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6052 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6053 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6054 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6055 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6056 trigger_spell_id = 33898;
6057 //else if (auraSpellInfo->Id==18943) // Double Attack
6058 //else if (auraSpellInfo->Id==19194) // Double Attack
6059 //else if (auraSpellInfo->Id==19817) // Double Attack
6060 //else if (auraSpellInfo->Id==19818) // Double Attack
6061 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6062 // trigger_spell_id = 14822;
6064 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6066 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6068 case 34191:
6069 case 34329:
6070 case 34524:
6071 case 34582:
6072 case 36733:
6073 break;
6074 default:
6075 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6076 return false;
6078 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6079 switch (procSpell->School)
6081 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6082 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6083 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6084 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6085 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6086 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6087 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6088 default:
6089 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6090 return false;
6094 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6095 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6096 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6097 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6098 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6099 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6100 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6101 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6102 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6103 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6104 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6105 //else if (auraSpellInfo->Id==40250) // Improved Duration
6106 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6107 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6108 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6109 // Mana Drain Trigger
6111 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6112 if (this && this->isAlive())
6113 CastSpell(this, 29471, true, castItem, triggeredByAura);
6114 if (pVictim && pVictim->isAlive())
6115 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6116 return true;
6118 //else if (auraSpellInfo->Id==55580) // Mana Link
6119 //else if (auraSpellInfo->Id==45903) // Offensive State
6120 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6121 //else if (auraSpellInfo->Id==43453) // Rune Ward
6122 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6123 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6124 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6125 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6126 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6127 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6128 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6129 //else if (auraSpellInfo->Id==35205) // Vanish
6130 //else if (auraSpellInfo->Id==42730) // Woe Strike
6131 //else if (auraSpellInfo->Id==59735) // Woe Strike
6132 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6133 break;
6134 case SPELLFAMILY_MAGE:
6135 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6137 switch (auraSpellInfo->Id)
6139 case 31641: // Rank 1
6140 case 31642: // Rank 2
6141 trigger_spell_id = 31643;
6142 break;
6143 default:
6144 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6145 return false;
6148 break;
6149 case SPELLFAMILY_WARRIOR:
6150 if (auraSpellInfo->Id == 50421) // Scent of Blood
6151 trigger_spell_id = 50422;
6152 break;
6153 case SPELLFAMILY_WARLOCK:
6155 // Pyroclasm
6156 if (auraSpellInfo->SpellIconID == 1137)
6158 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6159 return false;
6160 // Calculate spell tick count for spells
6161 uint32 tick = 1; // Default tick = 1
6163 // Hellfire have 15 tick
6164 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6165 tick = 15;
6166 // Rain of Fire have 4 tick
6167 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6168 tick = 4;
6169 else
6170 return false;
6172 // Calculate chance = baseChance / tick
6173 float chance = 0;
6174 switch (auraSpellInfo->Id)
6176 case 18096: chance = 13.0f / tick; break;
6177 case 18073: chance = 26.0f / tick; break;
6179 // Roll chance
6180 if (!roll_chance_f(chance))
6181 return false;
6183 trigger_spell_id = 18093;
6185 // Drain Soul
6186 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6188 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6189 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6191 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6193 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6194 // Drain Soul
6195 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6196 break;
6199 // Not remove charge (aura removed on death in any cases)
6200 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6201 return false;
6203 // Nether Protection
6204 else if (auraSpellInfo->SpellIconID == 1985)
6206 if (!procSpell)
6207 return false;
6208 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6210 case SPELL_SCHOOL_NORMAL:
6211 case SPELL_SCHOOL_HOLY:
6212 return false; // ignore
6213 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6214 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6215 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6216 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6217 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6218 default:
6219 return false;
6222 break;
6224 case SPELLFAMILY_PRIEST:
6226 // Greater Heal Refund
6227 if (auraSpellInfo->Id==37594)
6228 trigger_spell_id = 37595;
6229 // Blessed Recovery
6230 else if (auraSpellInfo->SpellIconID == 1875)
6232 switch (auraSpellInfo->Id)
6234 case 27811: trigger_spell_id = 27813; break;
6235 case 27815: trigger_spell_id = 27817; break;
6236 case 27816: trigger_spell_id = 27818; break;
6237 default:
6238 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6239 return false;
6241 basepoints0 = damage * triggerAmount / 100 / 3;
6242 target = this;
6244 break;
6246 case SPELLFAMILY_DRUID:
6248 // Druid Forms Trinket
6249 if (auraSpellInfo->Id==37336)
6251 switch(m_form)
6253 case FORM_NONE: trigger_spell_id = 37344;break;
6254 case FORM_CAT: trigger_spell_id = 37341;break;
6255 case FORM_BEAR:
6256 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6257 case FORM_TREE: trigger_spell_id = 37342;break;
6258 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6259 default:
6260 return false;
6263 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6264 // trigger_spell_id = ????;
6265 // Leader of the Pack
6266 else if (auraSpellInfo->Id == 24932)
6268 if (triggerAmount == 0)
6269 return false;
6270 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6271 trigger_spell_id = 34299;
6273 break;
6275 case SPELLFAMILY_HUNTER:
6276 break;
6277 case SPELLFAMILY_PALADIN:
6280 // Blessed Life
6281 if (auraSpellInfo->SpellIconID == 2137)
6283 switch (auraSpellInfo->Id)
6285 case 31828: // Rank 1
6286 case 31829: // Rank 2
6287 case 31830: // Rank 3
6288 break;
6289 default:
6290 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6291 return false;
6295 // Healing Discount
6296 if (auraSpellInfo->Id==37705)
6298 trigger_spell_id = 37706;
6299 target = this;
6301 // Soul Preserver
6302 if (auraSpellInfo->Id==60510)
6304 trigger_spell_id = 60515;
6305 target = this;
6307 // Illumination
6308 else if (auraSpellInfo->SpellIconID==241)
6310 if(!procSpell)
6311 return false;
6312 // procspell is triggered spell but we need mana cost of original casted spell
6313 uint32 originalSpellId = procSpell->Id;
6314 // Holy Shock heal
6315 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6317 switch(procSpell->Id)
6319 case 25914: originalSpellId = 20473; break;
6320 case 25913: originalSpellId = 20929; break;
6321 case 25903: originalSpellId = 20930; break;
6322 case 27175: originalSpellId = 27174; break;
6323 case 33074: originalSpellId = 33072; break;
6324 case 48820: originalSpellId = 48824; break;
6325 case 48821: originalSpellId = 48825; break;
6326 default:
6327 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6328 return false;
6331 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6332 if(!originalSpell)
6334 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6335 return false;
6337 // percent stored in effect 1 (class scripts) base points
6338 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6339 basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6340 trigger_spell_id = 20272;
6341 target = this;
6343 // Lightning Capacitor
6344 else if (auraSpellInfo->Id==37657)
6346 if(!pVictim || !pVictim->isAlive())
6347 return false;
6348 // stacking
6349 CastSpell(this, 37658, true, NULL, triggeredByAura);
6351 Aura * dummy = GetDummyAura(37658);
6352 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6353 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6354 return false;
6356 RemoveAurasDueToSpell(37658);
6357 trigger_spell_id = 37661;
6358 target = pVictim;
6360 // Thunder Capacitor
6361 else if (auraSpellInfo->Id == 54841)
6363 if(!pVictim || !pVictim->isAlive())
6364 return false;
6365 // stacking
6366 CastSpell(this, 54842, true, NULL, triggeredByAura);
6368 // counting
6369 Aura * dummy = GetDummyAura(54842);
6370 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6371 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6372 return false;
6374 RemoveAurasDueToSpell(54842);
6375 trigger_spell_id = 54843;
6376 target = pVictim;
6378 break;
6380 case SPELLFAMILY_SHAMAN:
6382 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6383 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6385 switch(auraSpellInfo->Id)
6387 case 324: // Rank 1
6388 trigger_spell_id = 26364; break;
6389 case 325: // Rank 2
6390 trigger_spell_id = 26365; break;
6391 case 905: // Rank 3
6392 trigger_spell_id = 26366; break;
6393 case 945: // Rank 4
6394 trigger_spell_id = 26367; break;
6395 case 8134: // Rank 5
6396 trigger_spell_id = 26369; break;
6397 case 10431: // Rank 6
6398 trigger_spell_id = 26370; break;
6399 case 10432: // Rank 7
6400 trigger_spell_id = 26363; break;
6401 case 25469: // Rank 8
6402 trigger_spell_id = 26371; break;
6403 case 25472: // Rank 9
6404 trigger_spell_id = 26372; break;
6405 case 49280: // Rank 10
6406 trigger_spell_id = 49278; break;
6407 case 49281: // Rank 11
6408 trigger_spell_id = 49279; break;
6409 default:
6410 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6411 return false;
6414 // Lightning Shield (The Ten Storms set)
6415 else if (auraSpellInfo->Id == 23551)
6417 trigger_spell_id = 23552;
6418 target = pVictim;
6420 // Damage from Lightning Shield (The Ten Storms set)
6421 else if (auraSpellInfo->Id == 23552)
6422 trigger_spell_id = 27635;
6423 // Mana Surge (The Earthfury set)
6424 else if (auraSpellInfo->Id == 23572)
6426 if(!procSpell)
6427 return false;
6428 basepoints0 = procSpell->manaCost * 35 / 100;
6429 trigger_spell_id = 23571;
6430 target = this;
6432 // Nature's Guardian
6433 else if (auraSpellInfo->SpellIconID == 2013)
6435 // Check health condition - should drop to less 30% (damage deal after this!)
6436 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6437 return false;
6439 if(pVictim && pVictim->isAlive())
6440 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6442 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6443 trigger_spell_id = 31616;
6444 target = this;
6446 break;
6448 case SPELLFAMILY_DEATHKNIGHT:
6450 // Acclimation
6451 if (auraSpellInfo->SpellIconID == 1930)
6453 if (!procSpell)
6454 return false;
6455 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6457 case SPELL_SCHOOL_NORMAL:
6458 return false; // ignore
6459 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6460 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6461 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6462 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6463 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6464 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6465 default:
6466 return false;
6469 // Blood Presence
6470 else if (auraSpellInfo->Id == 48266)
6472 if (GetTypeId() != TYPEID_PLAYER)
6473 return false;
6474 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6475 return false;
6476 trigger_spell_id = 50475;
6477 basepoints0 = damage * triggerAmount / 100;
6479 break;
6481 default:
6482 break;
6486 // All ok. Check current trigger spell
6487 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6488 if ( triggerEntry == NULL )
6490 // Not cast unknown spell
6491 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6492 return false;
6495 // not allow proc extra attack spell at extra attack
6496 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6497 return false;
6499 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6500 // Custom triggered spells
6501 switch (auraSpellInfo->Id)
6503 // Persistent Shield (Scarab Brooch trinket)
6504 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6505 case 26467:
6507 basepoints0 = damage * 15 / 100;
6508 target = pVictim;
6509 trigger_spell_id = 26470;
6510 break;
6512 // Cheat Death
6513 case 28845:
6515 // When your health drops below 20% ....
6516 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6517 return false;
6518 break;
6520 // Deadly Swiftness (Rank 1)
6521 case 31255:
6523 // whenever you deal damage to a target who is below 20% health.
6524 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6525 return false;
6527 target = this;
6528 trigger_spell_id = 22588;
6530 // Greater Heal Refund (Avatar Raiment set)
6531 case 37594:
6533 // Not give if target alredy have full health
6534 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6535 return false;
6536 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6537 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6538 return false;
6539 break;
6541 // Bonus Healing (Crystal Spire of Karabor mace)
6542 case 40971:
6544 // If your target is below $s1% health
6545 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6546 return false;
6547 break;
6549 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6550 case 45057:
6552 // reduce you below $s1% health
6553 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6554 return false;
6555 break;
6557 // Rapid Recuperation
6558 case 53228:
6559 case 53232:
6561 // This effect only from Rapid Fire (ability cast)
6562 if (!(procSpell->SpellFamilyFlags & 0x0000000000000020LL))
6563 return false;
6564 break;
6568 // Costum basepoints/target for exist spell
6569 // dummy basepoints or other customs
6570 switch(trigger_spell_id)
6572 // Cast positive spell on enemy target
6573 case 7099: // Curse of Mending
6574 case 39647: // Curse of Mending
6575 case 29494: // Temptation
6576 case 20233: // Improved Lay on Hands (cast on target)
6578 target = pVictim;
6579 break;
6581 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6582 case 15250: // Rogue Setup
6584 if(!pVictim || pVictim != getVictim()) // applied only for main target
6585 return false;
6586 break; // continue normal case
6588 // Finish movies that add combo
6589 case 14189: // Seal Fate (Netherblade set)
6590 case 14157: // Ruthlessness
6592 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6593 break;
6595 // Bloodthirst (($m/100)% of max health)
6596 case 23880:
6598 basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
6599 break;
6601 // Shamanistic Rage triggered spell
6602 case 30824:
6604 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6605 break;
6607 // Enlightenment (trigger only from mana cost spells)
6608 case 35095:
6610 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6611 return false;
6612 break;
6614 // Brain Freeze
6615 case 57761:
6617 if(!procSpell)
6618 return false;
6619 // For trigger from Blizzard need exist Improved Blizzard
6620 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080LL)
6622 bool found = false;
6623 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6624 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6626 int32 script = (*i)->GetModifier()->m_miscvalue;
6627 if(script==836 || script==988 || script==989)
6629 found=true;
6630 break;
6633 if(!found)
6634 return false;
6636 break;
6638 // Astral Shift
6639 case 52179:
6641 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6642 return false;
6644 // Need stun, fear or silence mechanic
6645 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6646 return false;
6647 break;
6649 // Burning Determination
6650 case 54748:
6652 if(!procSpell)
6653 return false;
6654 // Need Interrupt or Silenced mechanic
6655 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6656 return false;
6657 break;
6659 // Lock and Load
6660 case 56453:
6662 // Proc only from trap activation (from periodic proc another aura of this spell)
6663 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
6664 return false;
6665 break;
6669 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6670 return false;
6672 // try detect target manually if not set
6673 if ( target == NULL )
6674 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6676 // default case
6677 if(!target || target!=this && !target->isAlive())
6678 return false;
6680 if(basepoints0)
6681 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6682 else
6683 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6685 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6686 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6688 return true;
6691 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6693 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6695 if(!pVictim || !pVictim->isAlive())
6696 return false;
6698 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6699 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6701 uint32 triggered_spell_id = 0;
6703 switch(scriptId)
6705 case 836: // Improved Blizzard (Rank 1)
6707 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6708 return false;
6709 triggered_spell_id = 12484;
6710 break;
6712 case 988: // Improved Blizzard (Rank 2)
6714 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6715 return false;
6716 triggered_spell_id = 12485;
6717 break;
6719 case 989: // Improved Blizzard (Rank 3)
6721 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6722 return false;
6723 triggered_spell_id = 12486;
6724 break;
6726 case 4086: // Improved Mend Pet (Rank 1)
6727 case 4087: // Improved Mend Pet (Rank 2)
6729 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6730 if(!roll_chance_i(chance))
6731 return false;
6733 triggered_spell_id = 24406;
6734 break;
6736 case 4533: // Dreamwalker Raiment 2 pieces bonus
6738 // Chance 50%
6739 if (!roll_chance_i(50))
6740 return false;
6742 switch (pVictim->getPowerType())
6744 case POWER_MANA: triggered_spell_id = 28722; break;
6745 case POWER_RAGE: triggered_spell_id = 28723; break;
6746 case POWER_ENERGY: triggered_spell_id = 28724; break;
6747 default:
6748 return false;
6750 break;
6752 case 4537: // Dreamwalker Raiment 6 pieces bonus
6753 triggered_spell_id = 28750; // Blessing of the Claw
6754 break;
6755 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6756 triggered_spell_id = 37445; // Mana Surge
6757 break;
6758 case 8152: // Serendipity
6760 // if heal your target over maximum health
6761 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6762 return false;
6763 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6764 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6765 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6766 return true;
6770 // not processed
6771 if(!triggered_spell_id)
6772 return false;
6774 // standard non-dummy case
6775 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6777 if(!triggerEntry)
6779 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6780 return false;
6783 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6784 return false;
6786 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6788 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6789 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6791 return true;
6794 void Unit::setPowerType(Powers new_powertype)
6796 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6798 if(GetTypeId() == TYPEID_PLAYER)
6800 if(((Player*)this)->GetGroup())
6801 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6803 else if(((Creature*)this)->isPet())
6805 Pet *pet = ((Pet*)this);
6806 if(pet->isControlled())
6808 Unit *owner = GetOwner();
6809 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6810 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6814 switch(new_powertype)
6816 default:
6817 case POWER_MANA:
6818 break;
6819 case POWER_RAGE:
6820 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6821 SetPower( POWER_RAGE,0);
6822 break;
6823 case POWER_FOCUS:
6824 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6825 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6826 break;
6827 case POWER_ENERGY:
6828 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6829 SetPower( POWER_ENERGY,0);
6830 break;
6831 case POWER_HAPPINESS:
6832 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6833 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6834 break;
6838 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6840 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6841 if(!entry)
6843 static uint64 guid = 0; // prevent repeating spam same faction problem
6845 if(GetGUID() != guid)
6847 if(GetTypeId() == TYPEID_PLAYER)
6848 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6849 else
6850 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6851 guid = GetGUID();
6854 return entry;
6857 bool Unit::IsHostileTo(Unit const* unit) const
6859 // always non-hostile to self
6860 if(unit==this)
6861 return false;
6863 // always non-hostile to GM in GM mode
6864 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6865 return false;
6867 // always hostile to enemy
6868 if(getVictim()==unit || unit->getVictim()==this)
6869 return true;
6871 // test pet/charm masters instead pers/charmeds
6872 Unit const* testerOwner = GetCharmerOrOwner();
6873 Unit const* targetOwner = unit->GetCharmerOrOwner();
6875 // always hostile to owner's enemy
6876 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6877 return true;
6879 // always hostile to enemy owner
6880 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6881 return true;
6883 // always hostile to owner of owner's enemy
6884 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6885 return true;
6887 Unit const* tester = testerOwner ? testerOwner : this;
6888 Unit const* target = targetOwner ? targetOwner : unit;
6890 // always non-hostile to target with common owner, or to owner/pet
6891 if(tester==target)
6892 return false;
6894 // special cases (Duel, etc)
6895 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6897 Player const* pTester = (Player const*)tester;
6898 Player const* pTarget = (Player const*)target;
6900 // Duel
6901 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6902 return true;
6904 // Group
6905 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6906 return false;
6908 // Sanctuary
6909 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6910 return false;
6912 // PvP FFA state
6913 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))
6914 return true;
6916 //= PvP states
6917 // Green/Blue (can't attack)
6918 if(pTester->GetTeam()==pTarget->GetTeam())
6919 return false;
6921 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6922 return pTester->IsPvP() && pTarget->IsPvP();
6925 // faction base cases
6926 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6927 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6928 if(!tester_faction || !target_faction)
6929 return false;
6931 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6932 return true;
6934 // PvC forced reaction and reputation case
6935 if(tester->GetTypeId()==TYPEID_PLAYER)
6937 // forced reaction
6938 if(target_faction->faction)
6940 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
6941 return *force <= REP_HOSTILE;
6943 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6944 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6945 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
6946 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6949 // CvP forced reaction and reputation case
6950 else if(target->GetTypeId()==TYPEID_PLAYER)
6952 // forced reaction
6953 if(tester_faction->faction)
6955 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
6956 return *force <= REP_HOSTILE;
6958 // apply reputation state
6959 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6960 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6961 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
6965 // common faction based case (CvC,PvC,CvP)
6966 return tester_faction->IsHostileTo(*target_faction);
6969 bool Unit::IsFriendlyTo(Unit const* unit) const
6971 // always friendly to self
6972 if(unit==this)
6973 return true;
6975 // always friendly to GM in GM mode
6976 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6977 return true;
6979 // always non-friendly to enemy
6980 if(getVictim()==unit || unit->getVictim()==this)
6981 return false;
6983 // test pet/charm masters instead pers/charmeds
6984 Unit const* testerOwner = GetCharmerOrOwner();
6985 Unit const* targetOwner = unit->GetCharmerOrOwner();
6987 // always non-friendly to owner's enemy
6988 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6989 return false;
6991 // always non-friendly to enemy owner
6992 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6993 return false;
6995 // always non-friendly to owner of owner's enemy
6996 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6997 return false;
6999 Unit const* tester = testerOwner ? testerOwner : this;
7000 Unit const* target = targetOwner ? targetOwner : unit;
7002 // always friendly to target with common owner, or to owner/pet
7003 if(tester==target)
7004 return true;
7006 // special cases (Duel)
7007 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7009 Player const* pTester = (Player const*)tester;
7010 Player const* pTarget = (Player const*)target;
7012 // Duel
7013 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7014 return false;
7016 // Group
7017 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7018 return true;
7020 // Sanctuary
7021 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7022 return true;
7024 // PvP FFA state
7025 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))
7026 return false;
7028 //= PvP states
7029 // Green/Blue (non-attackable)
7030 if(pTester->GetTeam()==pTarget->GetTeam())
7031 return true;
7033 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7034 return !pTarget->IsPvP();
7037 // faction base cases
7038 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7039 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7040 if(!tester_faction || !target_faction)
7041 return false;
7043 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7044 return false;
7046 // PvC forced reaction and reputation case
7047 if(tester->GetTypeId()==TYPEID_PLAYER)
7049 // forced reaction
7050 if(target_faction->faction)
7052 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7053 return *force >= REP_FRIENDLY;
7055 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7056 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7057 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7058 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7061 // CvP forced reaction and reputation case
7062 else if(target->GetTypeId()==TYPEID_PLAYER)
7064 // forced reaction
7065 if(tester_faction->faction)
7067 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7068 return *force >= REP_FRIENDLY;
7070 // apply reputation state
7071 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7072 if(raw_tester_faction->reputationListID >=0 )
7073 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7077 // common faction based case (CvC,PvC,CvP)
7078 return tester_faction->IsFriendlyTo(*target_faction);
7081 bool Unit::IsHostileToPlayers() const
7083 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7084 if(!my_faction || !my_faction->faction)
7085 return false;
7087 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7088 if(raw_faction && raw_faction->reputationListID >=0 )
7089 return false;
7091 return my_faction->IsHostileToPlayers();
7094 bool Unit::IsNeutralToAll() const
7096 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7097 if(!my_faction || !my_faction->faction)
7098 return true;
7100 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7101 if(raw_faction && raw_faction->reputationListID >=0 )
7102 return false;
7104 return my_faction->IsNeutralToAll();
7107 bool Unit::Attack(Unit *victim, bool meleeAttack)
7109 if(!victim || victim == this)
7110 return false;
7112 // dead units can neither attack nor be attacked
7113 if(!isAlive() || !victim->isAlive())
7114 return false;
7116 // player cannot attack in mount state
7117 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7118 return false;
7120 // nobody can attack GM in GM-mode
7121 if(victim->GetTypeId()==TYPEID_PLAYER)
7123 if(((Player*)victim)->isGameMaster())
7124 return false;
7126 else
7128 if(((Creature*)victim)->IsInEvadeMode())
7129 return false;
7132 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7133 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7134 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7136 // in fighting already
7137 if (m_attacking)
7139 if (m_attacking == victim)
7141 // switch to melee attack from ranged/magic
7142 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7144 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7145 SendAttackStart(victim);
7146 return true;
7148 return false;
7151 // remove old target data
7152 AttackStop(true);
7154 // new battle
7155 else
7157 // set position before any AI calls/assistance
7158 if(GetTypeId()==TYPEID_UNIT)
7159 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7162 //Set our target
7163 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7165 if(meleeAttack)
7166 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7168 m_attacking = victim;
7169 m_attacking->_addAttacker(this);
7171 if(GetTypeId()==TYPEID_UNIT)
7173 WorldPacket data(SMSG_AI_REACTION, 12);
7174 data << uint64(GetGUID());
7175 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7176 ((WorldObject*)this)->SendMessageToSet(&data, true);
7178 ((Creature*)this)->CallAssistance();
7181 // delay offhand weapon attack to next attack time
7182 if(haveOffhandWeapon())
7183 resetAttackTimer(OFF_ATTACK);
7185 if(meleeAttack)
7186 SendAttackStart(victim);
7188 return true;
7191 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7193 if (!m_attacking)
7194 return false;
7196 Unit* victim = m_attacking;
7198 m_attacking->_removeAttacker(this);
7199 m_attacking = NULL;
7201 //Clear our target
7202 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7204 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7206 InterruptSpell(CURRENT_MELEE_SPELL);
7208 // reset only at real combat stop
7209 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7210 ((Creature*)this)->SetNoCallAssistance(false);
7212 SendAttackStop(victim);
7214 return true;
7217 void Unit::CombatStop(bool cast)
7219 if (cast && IsNonMeleeSpellCasted(false))
7220 InterruptNonMeleeSpells(false);
7222 AttackStop();
7223 RemoveAllAttackers();
7224 if( GetTypeId()==TYPEID_PLAYER )
7225 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7226 ClearInCombat();
7229 void Unit::CombatStopWithPets(bool cast)
7231 CombatStop(cast);
7232 if(Pet* pet = GetPet())
7233 pet->CombatStop(cast);
7234 if(Unit* charm = GetCharm())
7235 charm->CombatStop(cast);
7236 if(GetTypeId()==TYPEID_PLAYER)
7238 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7239 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7240 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7241 guardian->CombatStop(cast);
7245 bool Unit::isAttackingPlayer() const
7247 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7248 return true;
7250 Pet* pet = GetPet();
7251 if(pet && pet->isAttackingPlayer())
7252 return true;
7254 Unit* charmed = GetCharm();
7255 if(charmed && charmed->isAttackingPlayer())
7256 return true;
7258 for (int8 i = 0; i < MAX_TOTEM; i++)
7260 if(m_TotemSlot[i])
7262 Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]);
7263 if(totem && totem->isAttackingPlayer())
7264 return true;
7268 return false;
7271 void Unit::RemoveAllAttackers()
7273 while (!m_attackers.empty())
7275 AttackerSet::iterator iter = m_attackers.begin();
7276 if(!(*iter)->AttackStop())
7278 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7279 m_attackers.erase(iter);
7284 void Unit::ModifyAuraState(AuraState flag, bool apply)
7286 if (apply)
7288 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7290 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7291 if(GetTypeId() == TYPEID_PLAYER)
7293 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7294 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
7296 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
7297 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
7298 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
7299 if (spellInfo->CasterAuraState == flag)
7300 CastSpell(this, itr->first, true, NULL);
7305 else
7307 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
7309 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7310 Unit::AuraMap& tAuras = GetAuras();
7311 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
7313 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
7314 if (spellProto->CasterAuraState == flag)
7316 // exceptions (applied at state but not removed at state change)
7317 // Rampage
7318 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
7320 ++itr;
7321 continue;
7324 RemoveAura(itr);
7326 else
7327 ++itr;
7333 Unit *Unit::GetOwner() const
7335 uint64 ownerid = GetOwnerGUID();
7336 if(!ownerid)
7337 return NULL;
7338 return ObjectAccessor::GetUnit(*this, ownerid);
7341 Unit *Unit::GetCharmer() const
7343 if(uint64 charmerid = GetCharmerGUID())
7344 return ObjectAccessor::GetUnit(*this, charmerid);
7345 return NULL;
7348 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7350 uint64 guid = GetCharmerOrOwnerGUID();
7351 if(IS_PLAYER_GUID(guid))
7352 return ObjectAccessor::GetPlayer(*this, guid);
7354 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7357 Pet* Unit::GetPet() const
7359 if(uint64 pet_guid = GetPetGUID())
7361 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7362 return pet;
7364 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7365 const_cast<Unit*>(this)->SetPet(0);
7368 return NULL;
7371 Unit* Unit::GetCharm() const
7373 if(uint64 charm_guid = GetCharmGUID())
7375 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7376 return pet;
7378 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7379 const_cast<Unit*>(this)->SetCharm(NULL);
7382 return NULL;
7385 float Unit::GetCombatDistance( const Unit* target ) const
7387 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
7388 float dx = GetPositionX() - target->GetPositionX();
7389 float dy = GetPositionY() - target->GetPositionY();
7390 float dz = GetPositionZ() - target->GetPositionZ();
7391 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
7392 return ( dist > 0 ? dist : 0);
7395 void Unit::SetPet(Pet* pet)
7397 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7399 // FIXME: hack, speed must be set only at follow
7400 if(pet)
7401 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7402 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7405 void Unit::SetCharm(Unit* pet)
7407 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7409 if(GetTypeId() == TYPEID_PLAYER)
7410 ((Player*)this)->m_mover = pet ? pet : this;
7413 void Unit::UnsummonAllTotems()
7415 for (int8 i = 0; i < MAX_TOTEM; ++i)
7417 if(!m_TotemSlot[i])
7418 continue;
7420 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
7421 if (OldTotem && OldTotem->isTotem())
7422 ((Totem*)OldTotem)->UnSummon();
7426 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
7428 if(!victim)
7429 return NULL;
7431 // Magic case
7432 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
7434 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
7435 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
7436 if(Unit* magnet = (*itr)->GetCaster())
7437 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
7438 return magnet;
7440 // Melee && ranged case
7441 else
7443 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
7444 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
7445 if(Unit* magnet = (*i)->GetCaster())
7446 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
7447 if(roll_chance_i((*i)->GetModifier()->m_amount))
7448 return magnet;
7451 return victim;
7454 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7456 // we guess size
7457 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7458 data.append(pVictim->GetPackGUID());
7459 data.append(GetPackGUID());
7460 data << uint32(SpellID);
7461 data << uint32(Damage);
7462 data << uint32(0); // over healing?
7463 data << uint8(critical ? 1 : 0);
7464 data << uint8(0); // unused in client?
7465 SendMessageToSet(&data, true);
7468 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7470 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7471 data.append(pVictim->GetPackGUID());
7472 data.append(GetPackGUID());
7473 data << uint32(SpellID);
7474 data << uint32(powertype);
7475 data << uint32(Damage);
7476 SendMessageToSet(&data, true);
7479 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
7481 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7482 return pdamage;
7484 // For totems get damage bonus from owner (statue isn't totem in fact)
7485 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7487 if(Unit* owner = GetOwner())
7488 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7491 // Taken/Done total percent damage auras
7492 float DoneTotalMod = 1.0f;
7493 float TakenTotalMod = 1.0f;
7494 int32 DoneTotal = 0;
7495 int32 TakenTotal = 0;
7497 // ..done
7498 // Pet damage
7499 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7500 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7502 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7503 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7505 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7506 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7507 // -1 == any item class (not wand then)
7508 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7509 // 0 == any inventory type (not wand then)
7511 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7515 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7516 // Add flat bonus from spell damage versus
7517 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7518 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7519 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7520 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7521 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7523 // done scripted mod (take it from owner)
7524 Unit *owner = GetOwner();
7525 if (!owner) owner = this;
7526 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7527 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7529 if (!(*i)->isAffectedOnSpell(spellProto))
7530 continue;
7531 switch((*i)->GetModifier()->m_miscvalue)
7533 case 4920: // Molten Fury
7534 case 4919:
7535 case 6917: // Death's Embrace
7536 case 6926:
7537 case 6928:
7539 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7540 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7541 break;
7543 // Soul Siphon
7544 case 4992:
7545 case 4993:
7547 // effect 1 m_amount
7548 int32 maxPercent = (*i)->GetModifier()->m_amount;
7549 // effect 0 m_amount
7550 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
7551 // count affliction effects and calc additional damage in percentage
7552 int32 modPercent = 0;
7553 AuraMap const& victimAuras = pVictim->GetAuras();
7554 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7556 SpellEntry const* m_spell = itr->second->GetSpellProto();
7557 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & 0x0004071B8044C402LL))
7558 continue;
7559 modPercent += stepPercent * itr->second->GetStackAmount();
7560 if (modPercent >= maxPercent)
7562 modPercent = maxPercent;
7563 break;
7566 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7567 break;
7569 case 6916: // Death's Embrace
7570 case 6925:
7571 case 6927:
7572 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
7573 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7574 break;
7575 case 5481: // Starfire Bonus
7577 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x0000000000200002LL))
7578 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7579 break;
7581 case 4418: // Increased Shock Damage
7582 case 4554: // Increased Lightning Damage
7583 case 4555: // Improved Moonfire
7584 case 5142: // Increased Lightning Damage
7585 case 5147: // Improved Consecration / Libram of Resurgence
7586 case 5148: // Idol of the Shooting Star
7587 case 6008: // Increased Lightning Damage / Totem of Hex
7589 DoneTotal+=(*i)->GetModifier()->m_amount;
7590 break;
7592 // Tundra Stalker
7593 // Merciless Combat
7594 case 7277:
7596 // Merciless Combat
7597 if ((*i)->GetSpellProto()->SpellIconID == 2656)
7599 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7600 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7602 else // Tundra Stalker
7604 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_DEATHKNIGHT, 0x0400000000000000LL))
7605 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7606 break;
7608 break;
7610 case 7293: // Rage of Rivendare
7612 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0x0200000000000000LL))
7613 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7614 break;
7616 // Twisted Faith
7617 case 7377:
7619 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x0000000000008000LL, 0, GetGUID()))
7620 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7621 break;
7623 // Marked for Death
7624 case 7598:
7625 case 7599:
7626 case 7600:
7627 case 7601:
7628 case 7602:
7630 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x0000000000000400LL))
7631 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7632 break;
7637 // Custom scripted damage
7638 // Ice Lance
7639 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 186)
7641 if (pVictim->isFrozen())
7642 DoneTotalMod *= 3.0f;
7645 // ..taken
7646 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7647 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7648 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7649 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7651 // .. taken pct: dummy auras
7652 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7654 //Cheat Death
7655 if (Aura *dummy = pVictim->GetDummyAura(45182))
7657 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7658 if (mod < dummy->GetModifier()->m_amount)
7659 mod = dummy->GetModifier()->m_amount;
7660 TakenTotalMod *= (mod+100.0f)/100.0f;
7664 // From caster spells
7665 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
7666 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
7667 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
7668 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7670 // Mod damage from spell mechanic
7671 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
7672 if (mechanicMask)
7674 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
7675 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
7676 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
7677 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7680 // Taken/Done fixed damage bonus auras
7681 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
7682 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7684 // Pets just add their bonus damage to their spell damage
7685 // note that their spell damage is just gain of their own auras
7686 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
7687 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
7689 float LvlPenalty = CalculateLevelPenalty(spellProto);
7690 // Spellmod SpellDamage
7691 float SpellModSpellDamage = 100.0f;
7692 if(Player* modOwner = GetSpellModOwner())
7693 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7694 SpellModSpellDamage /= 100.0f;
7696 // Check for table values
7697 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
7698 if (bonus)
7700 float coeff;
7701 if (damagetype == DOT)
7702 coeff = bonus->dot_damage * LvlPenalty * stack;
7703 else
7704 coeff = bonus->direct_damage * LvlPenalty * stack;
7706 if (bonus->ap_bonus)
7707 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
7709 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
7710 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
7712 // Default calculation
7713 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
7715 // Damage Done from spell damage bonus
7716 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7717 // Damage over Time spells bonus calculation
7718 float DotFactor = 1.0f;
7719 if(damagetype == DOT)
7721 int32 DotDuration = GetSpellDuration(spellProto);
7722 // 200% limit
7723 if(DotDuration > 0)
7725 if(DotDuration > 30000) DotDuration = 30000;
7726 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7727 int x = 0;
7728 for(int j = 0; j < 3; j++)
7730 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7731 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7732 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7734 x = j;
7735 break;
7738 int32 DotTicks = 6;
7739 if(spellProto->EffectAmplitude[x] != 0)
7740 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7741 if(DotTicks)
7743 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
7744 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
7748 // Distribute Damage over multiple effects, reduce by AoE
7749 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7750 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7751 for(int j = 0; j < 3; ++j)
7753 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7754 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7756 CastingTime /= 2;
7757 break;
7760 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
7761 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
7764 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
7765 // apply spellmod to Done damage (flat and pct)
7766 if(Player* modOwner = GetSpellModOwner())
7767 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7769 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
7771 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7774 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7776 int32 DoneAdvertisedBenefit = 0;
7778 // ..done
7779 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7780 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7781 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7782 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7783 // -1 == any item class (not wand then)
7784 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7785 // 0 == any inventory type (not wand then)
7786 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7788 if (GetTypeId() == TYPEID_PLAYER)
7790 // Base value
7791 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7793 // Damage bonus from stats
7794 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7795 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7797 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7799 // stat used stored in miscValueB for this aura
7800 Stats usedStat = Stats((*i)->GetMiscBValue());
7801 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7804 // ... and attack power
7805 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7806 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7807 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7808 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7811 return DoneAdvertisedBenefit;
7814 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7816 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7818 int32 TakenAdvertisedBenefit = 0;
7819 // ..done (for creature type by mask) in taken
7820 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7821 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7822 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7823 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7825 // ..taken
7826 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7827 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7828 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7829 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7831 return TakenAdvertisedBenefit;
7834 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7836 // not critting spell
7837 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7838 return false;
7840 float crit_chance = 0.0f;
7841 switch(spellProto->DmgClass)
7843 case SPELL_DAMAGE_CLASS_NONE:
7844 return false;
7845 case SPELL_DAMAGE_CLASS_MAGIC:
7847 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7848 crit_chance = 0.0f;
7849 // For other schools
7850 else if (GetTypeId() == TYPEID_PLAYER)
7851 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7852 else
7854 crit_chance = m_baseSpellCritChance;
7855 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7857 // taken
7858 if (pVictim)
7860 if (!IsPositiveSpell(spellProto->Id))
7862 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7863 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7864 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7865 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7866 // Modify by player victim resilience
7867 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7868 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7871 // scripted (increase crit chance ... against ... target by x%
7872 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7873 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7875 if (!((*i)->isAffectedOnSpell(spellProto)))
7876 continue;
7877 switch((*i)->GetModifier()->m_miscvalue)
7879 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
7880 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
7881 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
7882 case 7917: // Glyph of Shadowburn
7883 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7884 crit_chance+=(*i)->GetModifier()->m_amount;
7885 break;
7886 case 7997: // Renewed Hope
7887 case 7998:
7888 if (pVictim->HasAura(6788))
7889 crit_chance+=(*i)->GetModifier()->m_amount;
7890 break;
7891 case 21: // Test of Faith
7892 case 6935:
7893 case 6918:
7894 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
7895 crit_chance+=(*i)->GetModifier()->m_amount;
7896 break;
7897 default:
7898 break;
7901 // Custom crit by class
7902 switch(spellProto->SpellFamilyName)
7904 case SPELLFAMILY_PALADIN:
7905 // Sacred Shield
7906 if (spellProto->SpellFamilyFlags & 0x0000000040000000LL)
7908 Aura *aura = pVictim->GetDummyAura(58597);
7909 if (aura && aura->GetCasterGUID() == GetGUID())
7910 crit_chance+=aura->GetModifier()->m_amount;
7911 break;
7913 break;
7914 case SPELLFAMILY_SHAMAN:
7915 // Lava Burst
7916 if (spellProto->SpellFamilyFlags & 0x0000100000000000LL)
7918 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x0000000010000000LL, 0, GetGUID()))
7920 // Consume shock aura if not have Glyph of Flame Shock
7921 if (!GetAura(55447, 0))
7922 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
7923 return true;
7925 break;
7927 break;
7931 break;
7933 case SPELL_DAMAGE_CLASS_MELEE:
7934 case SPELL_DAMAGE_CLASS_RANGED:
7936 if (pVictim)
7938 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7939 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7941 break;
7943 default:
7944 return false;
7946 // percent done
7947 // only players use intelligence for critical chance computations
7948 if(Player* modOwner = GetSpellModOwner())
7949 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7951 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7952 if (roll_chance_f(crit_chance))
7953 return true;
7954 return false;
7957 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7959 // Calculate critical bonus
7960 int32 crit_bonus;
7961 switch(spellProto->DmgClass)
7963 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7964 case SPELL_DAMAGE_CLASS_RANGED:
7965 // TODO: write here full calculation for melee/ranged spells
7966 crit_bonus = damage;
7967 break;
7968 default:
7969 crit_bonus = damage / 2; // for spells is 50%
7970 break;
7973 // adds additional damage to crit_bonus (from talents)
7974 if(Player* modOwner = GetSpellModOwner())
7975 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
7977 if(pVictim)
7979 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7980 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7983 if(crit_bonus > 0)
7984 damage += crit_bonus;
7986 return damage;
7989 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7991 // Calculate critical bonus
7992 int32 crit_bonus;
7993 switch(spellProto->DmgClass)
7995 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7996 case SPELL_DAMAGE_CLASS_RANGED:
7997 // TODO: write here full calculation for melee/ranged spells
7998 crit_bonus = damage;
7999 break;
8000 default:
8001 crit_bonus = damage / 2; // for spells is 50%
8002 break;
8005 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_BONUS));
8007 if(pVictim)
8009 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8010 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8013 if(crit_bonus > 0)
8014 damage += crit_bonus;
8016 return damage;
8019 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
8021 // No heal amount for this class spells
8022 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
8023 return healamount;
8025 // For totems get healing bonus from owner (statue isn't totem in fact)
8026 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8027 if(Unit* owner = GetOwner())
8028 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
8030 // Healing Done
8031 // Taken/Done total percent damage auras
8032 float DoneTotalMod = 1.0f;
8033 float TakenTotalMod = 1.0f;
8034 int32 DoneTotal = 0;
8035 int32 TakenTotal = 0;
8037 // Healing done percent
8038 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8039 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8040 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8042 // done scripted mod (take it from owner)
8043 Unit *owner = GetOwner();
8044 if (!owner) owner = this;
8045 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8046 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8048 if (!(*i)->isAffectedOnSpell(spellProto))
8049 continue;
8050 switch((*i)->GetModifier()->m_miscvalue)
8052 case 4415: // Increased Rejuvenation Healing
8053 case 4953:
8054 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
8055 DoneTotal+=(*i)->GetModifier()->m_amount;
8056 break;
8057 case 7997: // Renewed Hope
8058 case 7998:
8059 if (pVictim->HasAura(6788))
8060 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8061 break;
8062 case 21: // Test of Faith
8063 case 6935:
8064 case 6918:
8065 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8066 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8067 break;
8068 case 7798: // Glyph of Regrowth
8070 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x0000000000000040LL))
8071 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8072 break;
8074 case 8477: // Nourish Heal Boost
8076 int32 stepPercent = (*i)->GetModifier()->m_amount;
8077 int32 modPercent = 0;
8078 AuraMap const& victimAuras = pVictim->GetAuras();
8079 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8081 if (itr->second->GetCasterGUID()!=GetGUID())
8082 continue;
8083 SpellEntry const* m_spell = itr->second->GetSpellProto();
8084 if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8085 !(m_spell->SpellFamilyFlags & 0x0000001000000050LL))
8086 continue;
8087 modPercent += stepPercent * itr->second->GetStackAmount();
8089 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8090 break;
8092 case 7871: // Glyph of Lesser Healing Wave
8094 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x0000040000000000LL, 0, GetGUID()))
8095 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8096 break;
8098 default:
8099 break;
8103 // Taken/Done fixed damage bonus auras
8104 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8105 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8107 float LvlPenalty = CalculateLevelPenalty(spellProto);
8108 // Spellmod SpellDamage
8109 float SpellModSpellDamage = 100.0f;
8110 if(Player* modOwner = GetSpellModOwner())
8111 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8112 SpellModSpellDamage /= 100.0f;
8114 // Check for table values
8115 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8116 if (bonus)
8118 float coeff;
8119 if (damagetype == DOT)
8120 coeff = bonus->dot_damage * LvlPenalty * stack;
8121 else
8122 coeff = bonus->direct_damage * LvlPenalty * stack;
8124 if (bonus->ap_bonus)
8125 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8127 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8128 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8130 // Default calculation
8131 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8133 // Damage Done from spell damage bonus
8134 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8135 // Damage over Time spells bonus calculation
8136 float DotFactor = 1.0f;
8137 if(damagetype == DOT)
8139 int32 DotDuration = GetSpellDuration(spellProto);
8140 // 200% limit
8141 if(DotDuration > 0)
8143 if(DotDuration > 30000) DotDuration = 30000;
8144 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8145 int x = 0;
8146 for(int j = 0; j < 3; j++)
8148 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8149 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8150 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8152 x = j;
8153 break;
8156 int32 DotTicks = 6;
8157 if(spellProto->EffectAmplitude[x] != 0)
8158 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8159 if(DotTicks)
8161 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8162 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8166 // Distribute Damage over multiple effects, reduce by AoE
8167 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8168 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8169 for(int j = 0; j < 3; ++j)
8171 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8172 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8174 CastingTime /= 2;
8175 break;
8178 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
8179 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
8182 // use float as more appropriate for negative values and percent applying
8183 float heal = (healamount + DoneTotal)*DoneTotalMod;
8184 // apply spellmod to Done amount
8185 if(Player* modOwner = GetSpellModOwner())
8186 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8188 // Taken mods
8189 // Healing Wave cast
8190 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8192 // Search for Healing Way on Victim
8193 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8194 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8195 if((*itr)->GetId() == 29203)
8196 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8199 // Healing taken percent
8200 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8201 if(minval)
8202 TakenTotalMod *= (100.0f + minval) / 100.0f;
8204 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8205 if(maxval)
8206 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8208 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8209 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8210 if ((*i)->isAffectedOnSpell(spellProto))
8211 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8213 heal = (heal + TakenTotal) * TakenTotalMod;
8215 return heal < 0 ? 0 : uint32(heal);
8218 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8220 int32 AdvertisedBenefit = 0;
8222 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8223 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8224 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8225 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8227 // Healing bonus of spirit, intellect and strength
8228 if (GetTypeId() == TYPEID_PLAYER)
8230 // Base value
8231 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8233 // Healing bonus from stats
8234 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8235 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8237 // stat used dependent from misc value (stat index)
8238 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8239 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8242 // ... and attack power
8243 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8244 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8245 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8246 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8248 return AdvertisedBenefit;
8251 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8253 int32 AdvertisedBenefit = 0;
8254 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8255 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8256 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8257 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8258 return AdvertisedBenefit;
8261 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8263 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8264 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8265 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8266 if(itr->type & shoolMask)
8267 return true;
8269 //If m_immuneToDamage type contain magic, IMMUNE damage.
8270 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8271 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8272 if(itr->type & shoolMask)
8273 return true;
8275 return false;
8278 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8280 if (!spellInfo)
8281 return false;
8283 //FIX ME this hack: don't get feared if stunned
8284 if (spellInfo->Mechanic == MECHANIC_FEAR )
8286 if ( hasUnitState(UNIT_STAT_STUNNED) )
8287 return true;
8290 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
8291 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
8293 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8294 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8295 if(itr->type == spellInfo->Dispel)
8296 return true;
8298 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8299 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8301 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8302 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8303 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8304 (itr->type & GetSpellSchoolMask(spellInfo)) )
8305 return true;
8308 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8309 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8311 if(itr->type == spellInfo->Mechanic)
8313 return true;
8317 return false;
8320 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8322 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8323 uint32 effect = spellInfo->Effect[index];
8324 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8325 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8326 if(itr->type == effect)
8327 return true;
8329 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8331 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8332 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8333 if(itr->type == mechanic)
8334 return true;
8337 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8339 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8340 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8341 if(itr->type == aura)
8342 return true;
8343 // Check for immune to application of harmful magical effects
8344 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8345 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8346 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8347 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8348 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8349 return true;
8352 return false;
8355 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8357 if(!spellInfo)
8358 return false;
8360 uint32 family = spellInfo->SpellFamilyName;
8361 uint64 flags = spellInfo->SpellFamilyFlags;
8363 if((family == 5 && flags == 256) || //Searing Pain
8364 (family == 6 && flags == 8192) || //Mind Blast
8365 (family == 11 && flags == 1048576)) //Earth Shock
8366 return true;
8368 return false;
8371 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8373 if(!pVictim)
8374 return;
8376 if(*pdamage == 0)
8377 return;
8379 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8381 // Taken/Done fixed damage bonus auras
8382 int32 DoneFlatBenefit = 0;
8383 int32 TakenFlatBenefit = 0;
8385 // ..done (for creature type by mask) in taken
8386 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8387 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8388 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8389 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8391 // ..done
8392 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8394 // ..done (base at attack power for marked target and base at attack power for creature type)
8395 int32 APbonus = 0;
8396 if(attType == RANGED_ATTACK)
8398 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8400 // ..done (base at attack power and creature type)
8401 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8402 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8403 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8404 APbonus += (*i)->GetModifier()->m_amount;
8406 else
8408 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8410 // ..done (base at attack power and creature type)
8411 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8412 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8413 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8414 APbonus += (*i)->GetModifier()->m_amount;
8417 if (APbonus!=0) // Can be negative
8419 bool normalized = false;
8420 if(spellProto)
8422 for (uint8 i = 0; i<3;i++)
8424 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8426 normalized = true;
8427 break;
8432 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8435 // ..taken
8436 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8437 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8438 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8439 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8441 if(attType!=RANGED_ATTACK)
8442 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8443 else
8444 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8446 // Done/Taken total percent damage auras
8447 float DoneTotalMod = 1.0f;
8448 float TakenTotalMod = 1.0f;
8450 // ..done
8451 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8452 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8454 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8455 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8456 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8457 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8459 // ..taken
8460 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8461 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8462 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8463 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8465 // .. taken pct: dummy auras
8466 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8467 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8469 switch((*i)->GetSpellProto()->SpellIconID)
8471 //Cheat Death
8472 case 2109:
8473 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8475 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8476 continue;
8477 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8478 if (mod < (*i)->GetModifier()->m_amount)
8479 mod = (*i)->GetModifier()->m_amount;
8480 TakenTotalMod *= (mod+100.0f)/100.0f;
8482 break;
8483 //Mangle
8484 case 2312:
8485 if(spellProto==NULL)
8486 break;
8487 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8488 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8489 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8490 break;
8494 // .. taken pct: class scripts
8495 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8496 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8498 switch((*i)->GetMiscValue())
8500 case 6427: case 6428: // Dirty Deeds
8501 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8503 Aura* eff0 = GetAura((*i)->GetId(),0);
8504 if(!eff0 || (*i)->GetEffIndex()!=1)
8506 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8507 continue;
8510 // effect 0 have expected value but in negative state
8511 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8513 break;
8517 if(attType != RANGED_ATTACK)
8519 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8520 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8521 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8523 else
8525 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8526 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8527 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8530 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8532 // apply spellmod to Done damage
8533 if(spellProto)
8535 if(Player* modOwner = GetSpellModOwner())
8536 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8539 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8541 // bonus result can be negative
8542 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8545 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8547 if (apply)
8549 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8551 next = itr; ++next;
8552 if(itr->type == type)
8554 m_spellImmune[op].erase(itr);
8555 next = m_spellImmune[op].begin();
8558 SpellImmune Immune;
8559 Immune.spellId = spellId;
8560 Immune.type = type;
8561 m_spellImmune[op].push_back(Immune);
8563 else
8565 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8567 if(itr->spellId == spellId)
8569 m_spellImmune[op].erase(itr);
8570 break;
8577 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8579 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8581 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8582 RemoveAurasWithDispelType(type);
8585 float Unit::GetWeaponProcChance() const
8587 // normalized proc chance for weapon attack speed
8588 // (odd formula...)
8589 if(isAttackReady(BASE_ATTACK))
8590 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8591 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8592 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8593 return 0;
8596 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8598 // proc per minute chance calculation
8599 if (PPM <= 0) return 0.0f;
8600 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8601 return result;
8604 void Unit::Mount(uint32 mount)
8606 if(!mount)
8607 return;
8609 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8611 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8613 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8615 // unsummon pet
8616 if(GetTypeId() == TYPEID_PLAYER)
8617 ((Player*)this)->UnsummonPetTemporaryIfAny();
8620 void Unit::Unmount()
8622 if(!IsMounted())
8623 return;
8625 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8627 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8628 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8630 // only resummon old pet if the player is already added to a map
8631 // this prevents adding a pet to a not created map which would otherwise cause a crash
8632 // (it could probably happen when logging in after a previous crash)
8633 if(GetTypeId() == TYPEID_PLAYER)
8634 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
8637 void Unit::SetInCombatWith(Unit* enemy)
8639 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8640 if(eOwner->IsPvP())
8642 SetInCombatState(true);
8643 return;
8646 //check for duel
8647 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8649 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8650 if(((Player const*)eOwner)->duel->opponent == myOwner)
8652 SetInCombatState(true);
8653 return;
8656 SetInCombatState(false);
8659 void Unit::SetInCombatState(bool PvP)
8661 // only alive units can be in combat
8662 if(!isAlive())
8663 return;
8665 if(PvP)
8666 m_CombatTimer = 5000;
8667 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8669 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8670 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8673 void Unit::ClearInCombat()
8675 m_CombatTimer = 0;
8676 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8678 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8679 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8681 // Player's state will be cleared in Player::UpdateContestedPvP
8682 if(GetTypeId()!=TYPEID_PLAYER)
8683 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8684 else
8685 ((Player*)this)->UpdatePotionCooldown();
8688 bool Unit::isTargetableForAttack() const
8690 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8691 return false;
8693 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8694 return false;
8696 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8699 int32 Unit::ModifyHealth(int32 dVal)
8701 int32 gain = 0;
8703 if(dVal==0)
8704 return 0;
8706 int32 curHealth = (int32)GetHealth();
8708 int32 val = dVal + curHealth;
8709 if(val <= 0)
8711 SetHealth(0);
8712 return -curHealth;
8715 int32 maxHealth = (int32)GetMaxHealth();
8717 if(val < maxHealth)
8719 SetHealth(val);
8720 gain = val - curHealth;
8722 else if(curHealth != maxHealth)
8724 SetHealth(maxHealth);
8725 gain = maxHealth - curHealth;
8728 return gain;
8731 int32 Unit::ModifyPower(Powers power, int32 dVal)
8733 int32 gain = 0;
8735 if(dVal==0)
8736 return 0;
8738 int32 curPower = (int32)GetPower(power);
8740 int32 val = dVal + curPower;
8741 if(val <= 0)
8743 SetPower(power,0);
8744 return -curPower;
8747 int32 maxPower = (int32)GetMaxPower(power);
8749 if(val < maxPower)
8751 SetPower(power,val);
8752 gain = val - curPower;
8754 else if(curPower != maxPower)
8756 SetPower(power,maxPower);
8757 gain = maxPower - curPower;
8760 return gain;
8763 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8765 if(!u)
8766 return false;
8768 // Always can see self
8769 if (u==this)
8770 return true;
8772 // player visible for other player if not logout and at same transport
8773 // including case when player is out of world
8774 bool at_same_transport =
8775 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8776 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8777 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8778 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8780 // not in world
8781 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8782 return false;
8784 // forbidden to seen (at GM respawn command)
8785 if(m_Visibility==VISIBILITY_RESPAWN)
8786 return false;
8788 // always seen by owner
8789 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8790 return true;
8792 // Grid dead/alive checks
8793 if( u->GetTypeId()==TYPEID_PLAYER)
8795 // non visible at grid for any stealth state
8796 if(!IsVisibleInGridForPlayer((Player *)u))
8797 return false;
8799 // if player is dead then he can't detect anyone in any cases
8800 if(!u->isAlive())
8801 detect = false;
8803 else
8805 // all dead creatures/players not visible for any creatures
8806 if(!u->isAlive() || !isAlive())
8807 return false;
8810 // different visible distance checks
8811 if(u->isInFlight()) // what see player in flight
8813 // use object grey distance for all (only see objects any way)
8814 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8815 return false;
8817 else if(!isAlive()) // distance for show body
8819 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8820 return false;
8822 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8824 if(u->GetTypeId()==TYPEID_PLAYER)
8826 // Players far than max visible distance for player or not in our map are not visible too
8827 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8828 return false;
8830 else
8832 // Units far than max visible distance for creature or not in our map are not visible too
8833 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8834 return false;
8837 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8839 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8840 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8841 return false;
8843 else // distance for show creature
8845 // Units far than max visible distance for creature or not in our map are not visible too
8846 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8847 return false;
8850 // Visible units, always are visible for all units, except for units under invisibility and phases
8851 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
8852 return true;
8854 // GMs see any players, not higher GMs and all units in any phase
8855 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8857 if(GetTypeId() == TYPEID_PLAYER)
8858 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8859 else
8860 return true;
8863 // non faction visibility non-breakable for non-GMs
8864 if (m_Visibility == VISIBILITY_OFF)
8865 return false;
8867 // phased visibility (both must phased in same way)
8868 if(!InSamePhase(u))
8869 return false;
8871 // raw invisibility
8872 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8874 // detectable invisibility case
8875 if( invisible && (
8876 // Invisible units, always are visible for units under same invisibility type
8877 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8878 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8879 u->canDetectInvisibilityOf(this) ||
8880 // Units that can detect invisibility always are visible for units that can be detected
8881 canDetectInvisibilityOf(u) ))
8883 invisible = false;
8886 // special cases for always overwrite invisibility/stealth
8887 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8889 // non-hostile case
8890 if (!u->IsHostileTo(this))
8892 // 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)
8893 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8895 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8896 return true;
8898 // else apply same rules as for hostile case (detecting check for stealth)
8901 // hostile case
8902 else
8904 // Hunter mark functionality
8905 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8906 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8907 if((*iter)->GetCasterGUID()==u->GetGUID())
8908 return true;
8910 // else apply detecting check for stealth
8913 // none other cases for detect invisibility, so invisible
8914 if(invisible)
8915 return false;
8917 // else apply stealth detecting check
8920 // unit got in stealth in this moment and must ignore old detected state
8921 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8922 return false;
8924 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8925 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8926 return true;
8928 // NOW ONLY STEALTH CASE
8930 // stealth and detected and visible for some seconds
8931 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8932 return true;
8934 //if in non-detect mode then invisible for unit
8935 if (!detect)
8936 return false;
8938 // Special cases
8940 // If is attacked then stealth is lost, some creature can use stealth too
8941 if( !getAttackers().empty() )
8942 return true;
8944 // If there is collision rogue is seen regardless of level difference
8945 // TODO: check sizes in DB
8946 float distance = GetDistance(u);
8947 if (distance < 0.24f)
8948 return true;
8950 //If a mob or player is stunned he will not be able to detect stealth
8951 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8952 return false;
8954 // Creature can detect target only in aggro radius
8955 if(u->GetTypeId() != TYPEID_PLAYER)
8957 //Always invisible from back and out of aggro range
8958 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8959 if(!isInFront)
8960 return false;
8962 else
8964 //Always invisible from back
8965 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
8966 if(!isInFront)
8967 return false;
8970 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
8971 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
8973 //Calculation if target is in front
8975 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
8976 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
8978 //Visible distance is modified by
8979 //-Level Diff (every level diff = 1.0f in visible distance)
8980 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
8982 //This allows to check talent tree and will add addition stealth dependent on used points)
8983 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
8984 if(stealthMod < 0)
8985 stealthMod = 0;
8987 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
8988 //based on wowwiki every 5 mod we have 1 more level diff in calculation
8989 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
8991 if(distance > visibleDistance)
8992 return false;
8995 // Now check is target visible with LoS
8996 float ox,oy,oz;
8997 u->GetPosition(ox,oy,oz);
8998 return IsWithinLOS(ox,oy,oz);
9001 void Unit::SetVisibility(UnitVisibility x)
9003 m_Visibility = x;
9005 if(IsInWorld())
9007 Map *m = GetMap();
9009 if(GetTypeId()==TYPEID_PLAYER)
9010 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9011 else
9012 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9016 bool Unit::canDetectInvisibilityOf(Unit const* u) const
9018 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
9020 for(uint32 i = 0; i < 10; ++i)
9022 if(((1 << i) & mask)==0)
9023 continue;
9025 // find invisibility level
9026 uint32 invLevel = 0;
9027 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
9028 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
9029 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
9030 invLevel = (*itr)->GetModifier()->m_amount;
9032 // find invisibility detect level
9033 uint32 detectLevel = 0;
9034 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
9035 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
9036 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
9037 detectLevel = (*itr)->GetModifier()->m_amount;
9039 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
9041 detectLevel = ((Player*)this)->GetDrunkValue();
9044 if(invLevel <= detectLevel)
9045 return true;
9049 return false;
9052 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
9054 int32 main_speed_mod = 0;
9055 float stack_bonus = 1.0f;
9056 float non_stack_bonus = 1.0f;
9058 switch(mtype)
9060 case MOVE_WALK:
9061 return;
9062 case MOVE_RUN:
9064 if (IsMounted()) // Use on mount auras
9066 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
9067 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
9068 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
9070 else
9072 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
9073 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
9074 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
9076 break;
9078 case MOVE_RUN_BACK:
9079 return;
9080 case MOVE_SWIM:
9082 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
9083 break;
9085 case MOVE_SWIM_BACK:
9086 return;
9087 case MOVE_FLIGHT:
9089 if (IsMounted()) // Use on mount auras
9090 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9091 else // Use not mount (shapeshift for example) auras (should stack)
9092 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9093 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9094 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9095 break;
9097 case MOVE_FLIGHT_BACK:
9098 return;
9099 default:
9100 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9101 return;
9104 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9105 // now we ready for speed calculation
9106 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9108 switch(mtype)
9110 case MOVE_RUN:
9111 case MOVE_SWIM:
9112 case MOVE_FLIGHT:
9114 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9115 // TODO: possible affect only on MOVE_RUN
9116 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9118 // Use speed from aura
9119 float max_speed = normalization / baseMoveSpeed[mtype];
9120 if (speed > max_speed)
9121 speed = max_speed;
9123 break;
9125 default:
9126 break;
9129 // Apply strongest slow aura mod to speed
9130 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9131 if (slow)
9132 speed *=(100.0f + slow)/100.0f;
9133 SetSpeed(mtype, speed, forced);
9136 float Unit::GetSpeed( UnitMoveType mtype ) const
9138 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9141 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9143 if (rate < 0)
9144 rate = 0.0f;
9146 // Update speed only on change
9147 if (m_speed_rate[mtype] == rate)
9148 return;
9150 m_speed_rate[mtype] = rate;
9152 propagateSpeedChange();
9154 WorldPacket data;
9155 if(!forced)
9157 switch(mtype)
9159 case MOVE_WALK:
9160 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9161 break;
9162 case MOVE_RUN:
9163 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9164 break;
9165 case MOVE_RUN_BACK:
9166 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9167 break;
9168 case MOVE_SWIM:
9169 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9170 break;
9171 case MOVE_SWIM_BACK:
9172 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9173 break;
9174 case MOVE_TURN_RATE:
9175 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9176 break;
9177 case MOVE_FLIGHT:
9178 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9179 break;
9180 case MOVE_FLIGHT_BACK:
9181 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9182 break;
9183 case MOVE_PITCH_RATE:
9184 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9185 break;
9186 default:
9187 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9188 return;
9191 data.append(GetPackGUID());
9192 data << uint32(0); // movement flags
9193 data << uint16(0); // unk flags
9194 data << uint32(getMSTime());
9195 data << float(GetPositionX());
9196 data << float(GetPositionY());
9197 data << float(GetPositionZ());
9198 data << float(GetOrientation());
9199 data << uint32(0); // fall time
9200 data << float(GetSpeed(mtype));
9201 SendMessageToSet( &data, true );
9203 else
9205 if(GetTypeId() == TYPEID_PLAYER)
9207 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9208 // and do it only for real sent packets and use run for run/mounted as client expected
9209 ++((Player*)this)->m_forced_speed_changes[mtype];
9212 switch(mtype)
9214 case MOVE_WALK:
9215 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9216 break;
9217 case MOVE_RUN:
9218 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9219 break;
9220 case MOVE_RUN_BACK:
9221 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9222 break;
9223 case MOVE_SWIM:
9224 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9225 break;
9226 case MOVE_SWIM_BACK:
9227 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9228 break;
9229 case MOVE_TURN_RATE:
9230 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9231 break;
9232 case MOVE_FLIGHT:
9233 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9234 break;
9235 case MOVE_FLIGHT_BACK:
9236 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9237 break;
9238 case MOVE_PITCH_RATE:
9239 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9240 break;
9241 default:
9242 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9243 return;
9245 data.append(GetPackGUID());
9246 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9247 if (mtype == MOVE_RUN)
9248 data << uint8(0); // new 2.1.0
9249 data << float(GetSpeed(mtype));
9250 SendMessageToSet( &data, true );
9252 if(Pet* pet = GetPet())
9253 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9256 void Unit::SetHover(bool on)
9258 if(on)
9259 CastSpell(this,11010,true);
9260 else
9261 RemoveAurasDueToSpell(11010);
9264 void Unit::setDeathState(DeathState s)
9266 if (s != ALIVE && s!= JUST_ALIVED)
9268 CombatStop();
9269 DeleteThreatList();
9270 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9272 if(IsNonMeleeSpellCasted(false))
9273 InterruptNonMeleeSpells(false);
9276 if (s == JUST_DIED)
9278 RemoveAllAurasOnDeath();
9279 UnsummonAllTotems();
9281 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9282 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9283 // remove aurastates allowing special moves
9284 ClearAllReactives();
9285 ClearDiminishings();
9287 else if(s == JUST_ALIVED)
9289 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9292 if (m_deathState != ALIVE && s == ALIVE)
9294 //_ApplyAllAuraMods();
9296 m_deathState = s;
9299 /*########################################
9300 ######## ########
9301 ######## AGGRO SYSTEM ########
9302 ######## ########
9303 ########################################*/
9304 bool Unit::CanHaveThreatList() const
9306 // only creatures can have threat list
9307 if( GetTypeId() != TYPEID_UNIT )
9308 return false;
9310 // only alive units can have threat list
9311 if( !isAlive() )
9312 return false;
9314 // totems can not have threat list
9315 if( ((Creature*)this)->isTotem() )
9316 return false;
9318 // vehicles can not have threat list
9319 if( ((Creature*)this)->isVehicle() )
9320 return false;
9322 // pets can not have a threat list, unless they are controlled by a creature
9323 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9324 return false;
9326 return true;
9329 //======================================================================
9331 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9333 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9334 return threat;
9336 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9338 return threat * m_threatModifier[school];
9341 //======================================================================
9343 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9345 // Only mobs can manage threat lists
9346 if(CanHaveThreatList())
9347 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9350 //======================================================================
9352 void Unit::DeleteThreatList()
9354 m_ThreatManager.clearReferences();
9357 //======================================================================
9359 void Unit::TauntApply(Unit* taunter)
9361 assert(GetTypeId()== TYPEID_UNIT);
9363 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9364 return;
9366 if(!CanHaveThreatList())
9367 return;
9369 Unit *target = getVictim();
9370 if(target && target == taunter)
9371 return;
9373 SetInFront(taunter);
9374 if (((Creature*)this)->AI())
9375 ((Creature*)this)->AI()->AttackStart(taunter);
9377 m_ThreatManager.tauntApply(taunter);
9380 //======================================================================
9382 void Unit::TauntFadeOut(Unit *taunter)
9384 assert(GetTypeId()== TYPEID_UNIT);
9386 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9387 return;
9389 if(!CanHaveThreatList())
9390 return;
9392 Unit *target = getVictim();
9393 if(!target || target != taunter)
9394 return;
9396 if(m_ThreatManager.isThreatListEmpty())
9398 if(((Creature*)this)->AI())
9399 ((Creature*)this)->AI()->EnterEvadeMode();
9400 return;
9403 m_ThreatManager.tauntFadeOut(taunter);
9404 target = m_ThreatManager.getHostilTarget();
9406 if (target && target != taunter)
9408 SetInFront(target);
9409 if (((Creature*)this)->AI())
9410 ((Creature*)this)->AI()->AttackStart(target);
9414 //======================================================================
9416 bool Unit::SelectHostilTarget()
9418 //function provides main threat functionality
9419 //next-victim-selection algorithm and evade mode are called
9420 //threat list sorting etc.
9422 assert(GetTypeId()== TYPEID_UNIT);
9424 if (!this->isAlive())
9425 return false;
9426 //This function only useful once AI has been initialized
9427 if (!((Creature*)this)->AI())
9428 return false;
9430 Unit* target = NULL;
9432 // First checking if we have some taunt on us
9433 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9434 if ( !tauntAuras.empty() )
9436 Unit* caster;
9438 // The last taunt aura caster is alive an we are happy to attack him
9439 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9440 return true;
9441 else if (tauntAuras.size() > 1)
9443 // We do not have last taunt aura caster but we have more taunt auras,
9444 // so find first available target
9446 // Auras are pushed_back, last caster will be on the end
9447 AuraList::const_iterator aura = --tauntAuras.end();
9450 --aura;
9451 if ( (caster = (*aura)->GetCaster()) &&
9452 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9454 target = caster;
9455 break;
9457 }while (aura != tauntAuras.begin());
9461 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9462 // No taunt aura or taunt aura caster is dead standart target selection
9463 target = m_ThreatManager.getHostilTarget();
9465 if(target)
9467 if(!hasUnitState(UNIT_STAT_STUNNED))
9468 SetInFront(target);
9469 ((Creature*)this)->AI()->AttackStart(target);
9470 return true;
9473 // no target but something prevent go to evade mode
9474 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9475 return false;
9477 // last case when creature don't must go to evade mode:
9478 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9479 // for example at owner command to pet attack some far away creature
9480 // Note: creature not have targeted movement generator but have attacker in this case
9481 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9483 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9485 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9486 return false;
9490 // enter in evade mode in other case
9491 ((Creature*)this)->AI()->EnterEvadeMode();
9493 return false;
9496 //======================================================================
9497 //======================================================================
9498 //======================================================================
9500 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9502 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9504 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9506 int32 level = int32(getLevel());
9507 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9508 level = (int32)spellProto->maxLevel;
9509 else if (level < (int32)spellProto->baseLevel)
9510 level = (int32)spellProto->baseLevel;
9511 level-= (int32)spellProto->spellLevel;
9513 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9514 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9515 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9516 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9517 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9519 // range can have possitive and negative values, so order its for irand
9520 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9521 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9522 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9524 int32 value = basePoints + randvalue;
9525 //random damage
9526 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9527 value += (int32)(comboDamage * comboPoints);
9529 if(Player* modOwner = GetSpellModOwner())
9531 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9532 switch(effect_index)
9534 case 0:
9535 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9536 break;
9537 case 1:
9538 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9539 break;
9540 case 2:
9541 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9542 break;
9546 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9547 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9548 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9549 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9551 return value;
9554 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9556 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9558 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9560 int32 minduration = GetSpellDuration(spellProto);
9561 int32 maxduration = GetSpellMaxDuration(spellProto);
9563 int32 duration;
9565 if( minduration != -1 && minduration != maxduration )
9566 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9567 else
9568 duration = minduration;
9570 if (duration > 0)
9572 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9573 // Find total mod value (negative bonus)
9574 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9575 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9576 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9577 // Find max mod (negative bonus)
9578 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9580 int32 durationMod = 0;
9581 // Select strongest negative mod
9582 if (durationMod_always > durationMod_not_stack)
9583 durationMod = durationMod_not_stack;
9584 else
9585 durationMod = durationMod_always;
9587 if (durationMod != 0)
9588 duration = int32(int64(duration) * (100+durationMod) /100);
9590 if (duration < 0) duration = 0;
9593 return duration;
9596 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9598 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9600 if(i->DRGroup != group)
9601 continue;
9603 if(!i->hitCount)
9604 return DIMINISHING_LEVEL_1;
9606 if(!i->hitTime)
9607 return DIMINISHING_LEVEL_1;
9609 // If last spell was casted more than 15 seconds ago - reset the count.
9610 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9612 i->hitCount = DIMINISHING_LEVEL_1;
9613 return DIMINISHING_LEVEL_1;
9615 // or else increase the count.
9616 else
9618 return DiminishingLevels(i->hitCount);
9621 return DIMINISHING_LEVEL_1;
9624 void Unit::IncrDiminishing(DiminishingGroup group)
9626 // Checking for existing in the table
9627 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9629 if(i->DRGroup != group)
9630 continue;
9631 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9632 i->hitCount += 1;
9633 return;
9635 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9638 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9640 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9641 return;
9643 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9644 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9646 // test pet/charm masters instead pets/charmeds
9647 Unit const* targetOwner = GetCharmerOrOwner();
9648 Unit const* casterOwner = caster->GetCharmerOrOwner();
9650 Unit const* target = targetOwner ? targetOwner : this;
9651 Unit const* source = casterOwner ? casterOwner : caster;
9653 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9654 duration = 10000;
9657 float mod = 1.0f;
9659 // Some diminishings applies to mobs too (for example, Stun)
9660 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9662 DiminishingLevels diminish = Level;
9663 switch(diminish)
9665 case DIMINISHING_LEVEL_1: break;
9666 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9667 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9668 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9669 default: break;
9673 duration = int32(duration * mod);
9676 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9678 // Checking for existing in the table
9679 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9681 if(i->DRGroup != group)
9682 continue;
9684 if(apply)
9685 i->stack += 1;
9686 else if(i->stack)
9688 i->stack -= 1;
9689 // Remember time after last aura from group removed
9690 if (i->stack == 0)
9691 i->hitTime = getMSTime();
9693 break;
9697 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9699 return ObjectAccessor::GetUnit(object,guid);
9702 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9704 return isVisibleForOrDetect(u, false, inVisibleList, false);
9707 uint32 Unit::GetCreatureType() const
9709 if(GetTypeId() == TYPEID_PLAYER)
9711 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
9712 if(ssEntry && ssEntry->creatureType > 0)
9713 return ssEntry->creatureType;
9714 else
9715 return CREATURE_TYPE_HUMANOID;
9717 else
9718 return ((Creature*)this)->GetCreatureInfo()->type;
9721 /*#######################################
9722 ######## ########
9723 ######## STAT SYSTEM ########
9724 ######## ########
9725 #######################################*/
9727 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9729 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9731 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9732 return false;
9735 float val = 1.0f;
9737 switch(modifierType)
9739 case BASE_VALUE:
9740 case TOTAL_VALUE:
9741 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9742 break;
9743 case BASE_PCT:
9744 case TOTAL_PCT:
9745 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9746 amount = -200.0f;
9748 val = (100.0f + amount) / 100.0f;
9749 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9750 break;
9752 default:
9753 break;
9756 if(!CanModifyStats())
9757 return false;
9759 switch(unitMod)
9761 case UNIT_MOD_STAT_STRENGTH:
9762 case UNIT_MOD_STAT_AGILITY:
9763 case UNIT_MOD_STAT_STAMINA:
9764 case UNIT_MOD_STAT_INTELLECT:
9765 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9767 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9768 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9770 case UNIT_MOD_MANA:
9771 case UNIT_MOD_RAGE:
9772 case UNIT_MOD_FOCUS:
9773 case UNIT_MOD_ENERGY:
9774 case UNIT_MOD_HAPPINESS:
9775 case UNIT_MOD_RUNE:
9776 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9778 case UNIT_MOD_RESISTANCE_HOLY:
9779 case UNIT_MOD_RESISTANCE_FIRE:
9780 case UNIT_MOD_RESISTANCE_NATURE:
9781 case UNIT_MOD_RESISTANCE_FROST:
9782 case UNIT_MOD_RESISTANCE_SHADOW:
9783 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9785 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9786 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9788 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9789 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9790 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9792 default:
9793 break;
9796 return true;
9799 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9801 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9803 sLog.outError("trial to access non existed modifier value from UnitMods!");
9804 return 0.0f;
9807 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9808 return 0.0f;
9810 return m_auraModifiersGroup[unitMod][modifierType];
9813 float Unit::GetTotalStatValue(Stats stat) const
9815 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9817 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9818 return 0.0f;
9820 // value = ((base_value * base_pct) + total_value) * total_pct
9821 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9822 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9823 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9824 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9826 return value;
9829 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9831 if(unitMod >= UNIT_MOD_END)
9833 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
9834 return 0.0f;
9837 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9838 return 0.0f;
9840 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9841 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9842 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9843 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9845 return value;
9848 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9850 SpellSchools school = SPELL_SCHOOL_NORMAL;
9852 switch(unitMod)
9854 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9855 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9856 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9857 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9858 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9859 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9861 default:
9862 break;
9865 return school;
9868 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9870 Stats stat = STAT_STRENGTH;
9872 switch(unitMod)
9874 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9875 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9876 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9877 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9878 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9880 default:
9881 break;
9884 return stat;
9887 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9889 switch(unitMod)
9891 case UNIT_MOD_MANA: return POWER_MANA;
9892 case UNIT_MOD_RAGE: return POWER_RAGE;
9893 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9894 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9895 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9896 case UNIT_MOD_RUNE: return POWER_RUNE;
9897 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9900 return POWER_MANA;
9903 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9905 if (attType == RANGED_ATTACK)
9907 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
9908 if (ap < 0)
9909 return 0.0f;
9910 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
9912 else
9914 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
9915 if (ap < 0)
9916 return 0.0f;
9917 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
9921 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9923 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9924 return 0.0f;
9926 return m_weaponDamage[attType][type];
9929 void Unit::SetLevel(uint32 lvl)
9931 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9933 // group update
9934 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9935 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9938 void Unit::SetHealth(uint32 val)
9940 uint32 maxHealth = GetMaxHealth();
9941 if(maxHealth < val)
9942 val = maxHealth;
9944 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9946 // group update
9947 if(GetTypeId() == TYPEID_PLAYER)
9949 if(((Player*)this)->GetGroup())
9950 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9952 else if(((Creature*)this)->isPet())
9954 Pet *pet = ((Pet*)this);
9955 if(pet->isControlled())
9957 Unit *owner = GetOwner();
9958 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9959 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
9964 void Unit::SetMaxHealth(uint32 val)
9966 uint32 health = GetHealth();
9967 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
9969 // group update
9970 if(GetTypeId() == TYPEID_PLAYER)
9972 if(((Player*)this)->GetGroup())
9973 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
9975 else if(((Creature*)this)->isPet())
9977 Pet *pet = ((Pet*)this);
9978 if(pet->isControlled())
9980 Unit *owner = GetOwner();
9981 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9982 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
9986 if(val < health)
9987 SetHealth(val);
9990 void Unit::SetPower(Powers power, uint32 val)
9992 if(GetPower(power) == val)
9993 return;
9995 uint32 maxPower = GetMaxPower(power);
9996 if(maxPower < val)
9997 val = maxPower;
9999 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
10001 WorldPacket data(SMSG_POWER_UPDATE);
10002 data.append(GetPackGUID());
10003 data << uint8(power);
10004 data << uint32(val);
10005 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
10007 // group update
10008 if(GetTypeId() == TYPEID_PLAYER)
10010 if(((Player*)this)->GetGroup())
10011 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10013 else if(((Creature*)this)->isPet())
10015 Pet *pet = ((Pet*)this);
10016 if(pet->isControlled())
10018 Unit *owner = GetOwner();
10019 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10020 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10023 // Update the pet's character sheet with happiness damage bonus
10024 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
10026 pet->UpdateDamagePhysical(BASE_ATTACK);
10031 void Unit::SetMaxPower(Powers power, uint32 val)
10033 uint32 cur_power = GetPower(power);
10034 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
10036 // group update
10037 if(GetTypeId() == TYPEID_PLAYER)
10039 if(((Player*)this)->GetGroup())
10040 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10042 else if(((Creature*)this)->isPet())
10044 Pet *pet = ((Pet*)this);
10045 if(pet->isControlled())
10047 Unit *owner = GetOwner();
10048 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10049 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10053 if(val < cur_power)
10054 SetPower(power, val);
10057 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
10059 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
10061 // group update
10062 if(GetTypeId() == TYPEID_PLAYER)
10064 if(((Player*)this)->GetGroup())
10065 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10067 else if(((Creature*)this)->isPet())
10069 Pet *pet = ((Pet*)this);
10070 if(pet->isControlled())
10072 Unit *owner = GetOwner();
10073 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10074 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10079 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
10081 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
10083 // group update
10084 if(GetTypeId() == TYPEID_PLAYER)
10086 if(((Player*)this)->GetGroup())
10087 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10089 else if(((Creature*)this)->isPet())
10091 Pet *pet = ((Pet*)this);
10092 if(pet->isControlled())
10094 Unit *owner = GetOwner();
10095 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10096 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10101 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10103 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10104 if(apply)
10105 tAuraProcTriggerDamage.push_back(aura);
10106 else
10107 tAuraProcTriggerDamage.remove(aura);
10110 uint32 Unit::GetCreatePowers( Powers power ) const
10112 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10113 switch(power)
10115 case POWER_MANA: return GetCreateMana();
10116 case POWER_RAGE: return 1000;
10117 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10118 case POWER_ENERGY: return 100;
10119 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10120 case POWER_RUNIC_POWER: return 1000;
10123 return 0;
10126 void Unit::AddToWorld()
10128 Object::AddToWorld();
10131 void Unit::RemoveFromWorld()
10133 // cleanup
10134 if(IsInWorld())
10136 RemoveNotOwnSingleTargetAuras();
10139 Object::RemoveFromWorld();
10142 void Unit::CleanupsBeforeDelete()
10144 if(m_uint32Values) // only for fully created object
10146 InterruptNonMeleeSpells(true);
10147 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10148 CombatStop();
10149 ClearComboPointHolders();
10150 DeleteThreatList();
10151 getHostilRefManager().setOnlineOfflineState(false);
10152 RemoveAllAuras();
10153 RemoveAllGameObjects();
10154 RemoveAllDynObjects();
10155 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10157 RemoveFromWorld();
10160 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10162 if(!m_charmInfo)
10163 m_charmInfo = new CharmInfo(charm);
10164 return m_charmInfo;
10167 CharmInfo::CharmInfo(Unit* unit)
10168 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10170 for(int i =0; i<4; ++i)
10172 m_charmspells[i].spellId = 0;
10173 m_charmspells[i].active = ACT_DISABLED;
10177 void CharmInfo::InitPetActionBar()
10179 // the first 3 SpellOrActions are attack, follow and stay
10180 for(uint32 i = 0; i < 3; i++)
10182 PetActionBar[i].Type = ACT_COMMAND;
10183 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
10185 PetActionBar[i + 7].Type = ACT_REACTION;
10186 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
10188 for(uint32 i=0; i < 4; i++)
10190 PetActionBar[i + 3].Type = ACT_DISABLED;
10191 PetActionBar[i + 3].SpellOrAction = 0;
10195 void CharmInfo::InitEmptyActionBar()
10197 for(uint32 x = 1; x < 10; ++x)
10199 PetActionBar[x].Type = ACT_PASSIVE;
10200 PetActionBar[x].SpellOrAction = 0;
10202 PetActionBar[0].Type = ACT_COMMAND;
10203 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
10206 void CharmInfo::InitPossessCreateSpells()
10208 InitEmptyActionBar(); //charm action bar
10210 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
10211 return;
10213 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10215 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10216 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10217 else
10218 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10222 void CharmInfo::InitCharmCreateSpells()
10224 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10226 InitEmptyActionBar();
10227 return;
10230 InitPetActionBar();
10232 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10234 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10235 m_charmspells[x].spellId = spellId;
10237 if(!spellId)
10238 continue;
10240 if (IsPassiveSpell(spellId))
10242 m_unit->CastSpell(m_unit, spellId, true);
10243 m_charmspells[x].active = ACT_PASSIVE;
10245 else
10247 ActiveStates newstate;
10248 bool onlyselfcast = true;
10249 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10251 if(!spellInfo) onlyselfcast = false;
10252 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10254 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10255 onlyselfcast = false;
10258 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10259 newstate = ACT_DISABLED;
10260 else
10261 newstate = ACT_PASSIVE;
10263 AddSpellToAB(0, spellId, newstate);
10268 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
10270 for(uint8 i = 0; i < 10; i++)
10272 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
10274 PetActionBar[i].SpellOrAction = newid;
10275 if(!oldid)
10277 if(newstate == ACT_DECIDE)
10278 PetActionBar[i].Type = ACT_DISABLED;
10279 else
10280 PetActionBar[i].Type = newstate;
10283 return true;
10286 return false;
10289 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10291 if(IsPassiveSpell(spellid))
10292 return;
10294 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10296 if(spellid == m_charmspells[x].spellId)
10298 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10303 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10305 m_petnumber = petnumber;
10306 if(statwindow)
10307 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10308 else
10309 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10312 bool Unit::isFrozen() const
10314 return HasAuraState(AURA_STATE_FROZEN);
10317 struct ProcTriggeredData
10319 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10320 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10321 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10323 SpellProcEventEntry const *spellProcEvent;
10324 Aura* triggeredByAura;
10325 Unit::spellEffectPair triggeredByAura_SpellPair;
10328 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10329 typedef std::list< uint32> RemoveSpellList;
10331 // List of auras that CAN be trigger but may not exist in spell_proc_event
10332 // in most case need for drop charges
10333 // in some types of aura need do additional check
10334 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10335 bool InitTriggerAuraData()
10337 for (int i=0;i<TOTAL_AURAS;i++)
10339 isTriggerAura[i]=false;
10340 isNonTriggerAura[i] = false;
10342 isTriggerAura[SPELL_AURA_DUMMY] = true;
10343 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10344 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10345 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10346 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10347 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10348 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10349 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10350 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10351 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10352 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10353 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10354 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
10355 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10356 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10357 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10358 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10359 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10360 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10361 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10362 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10363 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10364 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10365 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10366 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10367 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10368 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10369 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10370 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
10372 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10373 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
10375 return true;
10378 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10380 uint32 procEx = PROC_EX_NONE;
10381 // Check victim state
10382 if (missCondition!=SPELL_MISS_NONE)
10383 switch (missCondition)
10385 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10386 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10387 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10388 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10389 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10390 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10391 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10392 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10393 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10394 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10395 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10396 default:
10397 break;
10399 else
10401 // On block
10402 if (damageInfo->blocked)
10403 procEx|=PROC_EX_BLOCK;
10404 // On absorb
10405 if (damageInfo->absorb)
10406 procEx|=PROC_EX_ABSORB;
10407 // On crit
10408 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10409 procEx|=PROC_EX_CRITICAL_HIT;
10410 else
10411 procEx|=PROC_EX_NORMAL_HIT;
10413 return procEx;
10416 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10418 // For melee/ranged based attack need update skills and set some Aura states
10419 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10421 // Update skills here for players
10422 if (GetTypeId() == TYPEID_PLAYER)
10424 // On melee based hit/miss/resist need update skill (for victim and attacker)
10425 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10427 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10428 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10430 // Update defence if player is victim and parry/dodge/block
10431 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10432 ((Player*)this)->UpdateDefense();
10434 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10435 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10437 // for victim
10438 if (isVictim)
10440 // if victim and dodge attack
10441 if (procExtra&PROC_EX_DODGE)
10443 //Update AURA_STATE on dodge
10444 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10446 ModifyAuraState(AURA_STATE_DEFENSE, true);
10447 StartReactiveTimer( REACTIVE_DEFENSE );
10450 // if victim and parry attack
10451 if (procExtra & PROC_EX_PARRY)
10453 // For Hunters only Counterattack (skip Mongoose bite)
10454 if (getClass() == CLASS_HUNTER)
10456 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10457 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10459 else
10461 ModifyAuraState(AURA_STATE_DEFENSE, true);
10462 StartReactiveTimer( REACTIVE_DEFENSE );
10465 // if and victim block attack
10466 if (procExtra & PROC_EX_BLOCK)
10468 ModifyAuraState(AURA_STATE_DEFENSE,true);
10469 StartReactiveTimer( REACTIVE_DEFENSE );
10472 else //For attacker
10474 // Overpower on victim dodge
10475 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10477 ((Player*)this)->AddComboPoints(pTarget, 1);
10478 StartReactiveTimer( REACTIVE_OVERPOWER );
10484 RemoveSpellList removedSpells;
10485 ProcTriggeredList procTriggered;
10486 // Fill procTriggered list
10487 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10489 SpellProcEventEntry const* spellProcEvent = NULL;
10490 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10491 continue;
10493 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10496 // Nothing found
10497 if (procTriggered.empty())
10498 return;
10500 // Handle effects proceed this time
10501 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10503 // Some auras can be deleted in function called in this loop (except first, ofc)
10504 // Until storing auars in std::multimap to hard check deleting by another way
10505 if(i != procTriggered.begin())
10507 bool found = false;
10508 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10509 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10510 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10512 if(itr->second==i->triggeredByAura)
10514 found = true;
10515 break;
10518 if(!found)
10520 // 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);
10521 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10522 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
10523 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10524 // sLog.outDebug(" <end of list>");
10525 continue;
10529 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10530 Aura *triggeredByAura = i->triggeredByAura;
10531 Modifier *auraModifier = triggeredByAura->GetModifier();
10532 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10533 uint32 effIndex = triggeredByAura->GetEffIndex();
10534 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10535 // For players set spell cooldown if need
10536 uint32 cooldown = 0;
10537 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10538 cooldown = spellProcEvent->cooldown;
10540 switch(auraModifier->m_auraname)
10542 case SPELL_AURA_PROC_TRIGGER_SPELL:
10544 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10545 // Don`t drop charge or add cooldown for not started trigger
10546 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10547 continue;
10548 break;
10550 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10552 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());
10553 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10554 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10555 SendSpellNonMeleeDamageLog(&damageInfo);
10556 DealSpellDamage(&damageInfo, true);
10557 break;
10559 case SPELL_AURA_MANA_SHIELD:
10560 case SPELL_AURA_DUMMY:
10562 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());
10563 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10564 continue;
10565 break;
10567 case SPELL_AURA_MOD_HASTE:
10569 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());
10570 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10571 continue;
10572 break;
10574 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10576 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());
10577 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10578 continue;
10579 break;
10581 case SPELL_AURA_PRAYER_OF_MENDING:
10583 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10584 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10586 HandleMeandingAuraProc(triggeredByAura);
10587 break;
10589 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10591 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());
10593 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10594 continue;
10595 break;
10597 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
10598 // Skip melee hits or instant cast spells
10599 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10600 continue;
10601 break;
10602 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10603 // Skip Melee hits and spells ws wrong school
10604 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10605 continue;
10606 break;
10607 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10608 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10609 // Skip melee hits and spells ws wrong school or zero cost
10610 if (procSpell == NULL ||
10611 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10612 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10613 continue;
10614 break;
10615 case SPELL_AURA_MECHANIC_IMMUNITY:
10616 // Compare mechanic
10617 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10618 continue;
10619 break;
10620 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10621 // Compare mechanic
10622 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10623 continue;
10624 break;
10625 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
10626 // Compare casters
10627 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
10628 continue;
10629 break;
10630 default:
10631 // nothing do, just charges counter
10632 break;
10634 // Remove charge (aura can be removed by triggers)
10635 if(useCharges)
10637 // need found aura on drop (can be dropped by triggers)
10638 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10639 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10640 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10642 // If last charge dropped add spell to remove list
10643 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10645 removedSpells.push_back(triggeredByAura->GetId());
10646 break;
10651 if (!removedSpells.empty())
10653 // Sort spells and remove dublicates
10654 removedSpells.sort();
10655 removedSpells.unique();
10656 // Remove auras from removedAuras
10657 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10658 RemoveAurasDueToSpell(*i);
10662 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10664 return SPELL_SCHOOL_MASK_NORMAL;
10667 Player* Unit::GetSpellModOwner()
10669 if(GetTypeId()==TYPEID_PLAYER)
10670 return (Player*)this;
10671 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10673 Unit* owner = GetOwner();
10674 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10675 return (Player*)owner;
10677 return NULL;
10680 ///----------Pet responses methods-----------------
10681 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
10683 if(msg == SPELL_CAST_OK)
10684 return;
10686 Unit *owner = GetCharmerOrOwner();
10687 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10688 return;
10690 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10691 data << uint8(0); // cast count?
10692 data << uint32(spellid);
10693 data << uint8(msg);
10694 // uint32 for some reason
10695 // uint32 for some reason
10696 ((Player*)owner)->GetSession()->SendPacket(&data);
10699 void Unit::SendPetActionFeedback (uint8 msg)
10701 Unit* owner = GetOwner();
10702 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10703 return;
10705 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10706 data << uint8(msg);
10707 ((Player*)owner)->GetSession()->SendPacket(&data);
10710 void Unit::SendPetTalk (uint32 pettalk)
10712 Unit* owner = GetOwner();
10713 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10714 return;
10716 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10717 data << uint64(GetGUID());
10718 data << uint32(pettalk);
10719 ((Player*)owner)->GetSession()->SendPacket(&data);
10722 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10724 Unit* owner = GetOwner();
10725 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10726 return;
10728 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10729 data << uint64(GetGUID());
10730 data << uint8(0x0); // flags (0x1, 0x2)
10731 data << uint32(spellid);
10732 data << uint32(cooltime);
10734 ((Player*)owner)->GetSession()->SendPacket(&data);
10737 void Unit::SendPetClearCooldown (uint32 spellid)
10739 Unit* owner = GetOwner();
10740 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10741 return;
10743 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10744 data << uint32(spellid);
10745 data << uint64(GetGUID());
10746 ((Player*)owner)->GetSession()->SendPacket(&data);
10749 void Unit::SendPetAIReaction(uint64 guid)
10751 Unit* owner = GetOwner();
10752 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10753 return;
10755 WorldPacket data(SMSG_AI_REACTION, 12);
10756 data << uint64(guid) << uint32(00000002);
10757 ((Player*)owner)->GetSession()->SendPacket(&data);
10760 ///----------End of Pet responses methods----------
10762 void Unit::StopMoving()
10764 clearUnitState(UNIT_STAT_MOVING);
10766 // send explicit stop packet
10767 // rely on vmaps here because for example stormwind is in air
10768 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10769 //if (fabs(GetPositionZ() - z) < 2.0f)
10770 // Relocate(GetPositionX(), GetPositionY(), z);
10771 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10773 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10775 // update position and orientation;
10776 WorldPacket data;
10777 BuildHeartBeatMsg(&data);
10778 SendMessageToSet(&data,false);
10781 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10783 if( apply )
10785 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10786 return;
10788 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10790 GetMotionMaster()->MovementExpired(false);
10791 CastStop(GetGUID()==casterGUID ? spellID : 0);
10793 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10795 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10797 else
10799 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10801 GetMotionMaster()->MovementExpired(false);
10803 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10805 // restore appropriate movement generator
10806 if(getVictim())
10807 GetMotionMaster()->MoveChase(getVictim());
10808 else
10809 GetMotionMaster()->Initialize();
10811 // attack caster if can
10812 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10813 if(caster && ((Creature*)this)->AI())
10814 ((Creature*)this)->AI()->AttackedBy(caster);
10818 if (GetTypeId() == TYPEID_PLAYER)
10819 ((Player*)this)->SetClientControl(this, !apply);
10822 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10824 if( apply )
10826 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10828 CastStop(GetGUID()==casterGUID ? spellID : 0);
10830 GetMotionMaster()->MoveConfused();
10832 else
10834 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10836 GetMotionMaster()->MovementExpired(false);
10838 if (GetTypeId() == TYPEID_UNIT)
10840 // if in combat restore movement generator
10841 if(getVictim())
10842 GetMotionMaster()->MoveChase(getVictim());
10846 if(GetTypeId() == TYPEID_PLAYER)
10847 ((Player*)this)->SetClientControl(this, !apply);
10850 bool Unit::IsSitState() const
10852 uint8 s = getStandState();
10853 return
10854 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
10855 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
10856 s == UNIT_STAND_STATE_SIT;
10859 bool Unit::IsStandState() const
10861 uint8 s = getStandState();
10862 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
10865 void Unit::SetStandState(uint8 state)
10867 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10869 if (IsStandState())
10870 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10872 if(GetTypeId()==TYPEID_PLAYER)
10874 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10875 data << (uint8)state;
10876 ((Player*)this)->GetSession()->SendPacket(&data);
10880 bool Unit::IsPolymorphed() const
10882 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10885 void Unit::SetDisplayId(uint32 modelId)
10887 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10889 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10891 Pet *pet = ((Pet*)this);
10892 if(!pet->isControlled())
10893 return;
10894 Unit *owner = GetOwner();
10895 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10896 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10900 void Unit::ClearComboPointHolders()
10902 while(!m_ComboPointHolders.empty())
10904 uint32 lowguid = *m_ComboPointHolders.begin();
10906 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10907 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10908 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10909 else
10910 m_ComboPointHolders.erase(lowguid); // or remove manually
10914 void Unit::ClearAllReactives()
10916 for(int i=0; i < MAX_REACTIVE; ++i)
10917 m_reactiveTimer[i] = 0;
10919 if (HasAuraState( AURA_STATE_DEFENSE))
10920 ModifyAuraState(AURA_STATE_DEFENSE, false);
10921 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10922 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10923 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10924 ((Player*)this)->ClearComboPoints();
10927 void Unit::UpdateReactives( uint32 p_time )
10929 for(int i = 0; i < MAX_REACTIVE; ++i)
10931 ReactiveType reactive = ReactiveType(i);
10933 if(!m_reactiveTimer[reactive])
10934 continue;
10936 if ( m_reactiveTimer[reactive] <= p_time)
10938 m_reactiveTimer[reactive] = 0;
10940 switch ( reactive )
10942 case REACTIVE_DEFENSE:
10943 if (HasAuraState(AURA_STATE_DEFENSE))
10944 ModifyAuraState(AURA_STATE_DEFENSE, false);
10945 break;
10946 case REACTIVE_HUNTER_PARRY:
10947 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10948 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10949 break;
10950 case REACTIVE_OVERPOWER:
10951 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10952 ((Player*)this)->ClearComboPoints();
10953 break;
10954 default:
10955 break;
10958 else
10960 m_reactiveTimer[reactive] -= p_time;
10965 Unit* Unit::SelectNearbyTarget() const
10967 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
10968 Cell cell(p);
10969 cell.data.Part.reserved = ALL_DISTRICT;
10970 cell.SetNoCreate();
10972 std::list<Unit *> targets;
10975 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
10976 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
10978 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
10979 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
10981 CellLock<GridReadGuard> cell_lock(cell, p);
10982 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
10983 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
10986 // remove current target
10987 if(getVictim())
10988 targets.remove(getVictim());
10990 // remove not LoS targets
10991 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
10993 if(!IsWithinLOSInMap(*tIter))
10995 std::list<Unit *>::iterator tIter2 = tIter;
10996 ++tIter;
10997 targets.erase(tIter2);
10999 else
11000 ++tIter;
11003 // no appropriate targets
11004 if(targets.empty())
11005 return NULL;
11007 // select random
11008 uint32 rIdx = urand(0,targets.size()-1);
11009 std::list<Unit *>::const_iterator tcIter = targets.begin();
11010 for(uint32 i = 0; i < rIdx; ++i)
11011 ++tcIter;
11013 return *tcIter;
11016 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
11018 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
11020 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
11021 return true;
11023 return false;
11026 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
11028 if(val > 0)
11030 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
11031 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
11033 else
11035 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
11036 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
11040 void Unit::ApplyCastTimePercentMod(float val, bool apply )
11042 if(val > 0)
11043 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
11044 else
11045 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
11048 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
11050 // Not apply this to creature casted spells with casttime==0
11051 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
11052 return 3500;
11054 if (CastingTime > 7000) CastingTime = 7000;
11055 if (CastingTime < 1500) CastingTime = 1500;
11057 if(damagetype == DOT && !IsChanneledSpell(spellProto))
11058 CastingTime = 3500;
11060 int32 overTime = 0;
11061 uint8 effects = 0;
11062 bool DirectDamage = false;
11063 bool AreaEffect = false;
11065 for ( uint32 i=0; i<3;i++)
11067 switch ( spellProto->Effect[i] )
11069 case SPELL_EFFECT_SCHOOL_DAMAGE:
11070 case SPELL_EFFECT_POWER_DRAIN:
11071 case SPELL_EFFECT_HEALTH_LEECH:
11072 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
11073 case SPELL_EFFECT_POWER_BURN:
11074 case SPELL_EFFECT_HEAL:
11075 DirectDamage = true;
11076 break;
11077 case SPELL_EFFECT_APPLY_AURA:
11078 switch ( spellProto->EffectApplyAuraName[i] )
11080 case SPELL_AURA_PERIODIC_DAMAGE:
11081 case SPELL_AURA_PERIODIC_HEAL:
11082 case SPELL_AURA_PERIODIC_LEECH:
11083 if ( GetSpellDuration(spellProto) )
11084 overTime = GetSpellDuration(spellProto);
11085 break;
11086 default:
11087 // -5% per additional effect
11088 ++effects;
11089 break;
11091 default:
11092 break;
11095 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11096 AreaEffect = true;
11099 // Combined Spells with Both Over Time and Direct Damage
11100 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11102 // mainly for DoTs which are 3500 here otherwise
11103 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11104 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11105 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11106 // Portion to Over Time
11107 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
11109 if ( damagetype == DOT )
11110 CastingTime = uint32(CastingTime * PtOT);
11111 else if ( PtOT < 1.0f )
11112 CastingTime = uint32(CastingTime * (1 - PtOT));
11113 else
11114 CastingTime = 0;
11117 // Area Effect Spells receive only half of bonus
11118 if ( AreaEffect )
11119 CastingTime /= 2;
11121 // -5% of total per any additional effect
11122 for ( uint8 i=0; i<effects; ++i)
11124 if ( CastingTime > 175 )
11126 CastingTime -= 175;
11128 else
11130 CastingTime = 0;
11131 break;
11135 return CastingTime;
11138 void Unit::UpdateAuraForGroup(uint8 slot)
11140 if(GetTypeId() == TYPEID_PLAYER)
11142 Player* player = (Player*)this;
11143 if(player->GetGroup())
11145 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11146 player->SetAuraUpdateMask(slot);
11149 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11151 Pet *pet = ((Pet*)this);
11152 if(pet->isControlled())
11154 Unit *owner = GetOwner();
11155 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11157 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11158 pet->SetAuraUpdateMask(slot);
11164 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11166 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11167 return float(GetAttackTime(attType))/1000.0f;
11169 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11170 if (!Weapon)
11171 return 2.4; // fist attack
11173 switch (Weapon->GetProto()->InventoryType)
11175 case INVTYPE_2HWEAPON:
11176 return 3.3;
11177 case INVTYPE_RANGED:
11178 case INVTYPE_RANGEDRIGHT:
11179 case INVTYPE_THROWN:
11180 return 2.8;
11181 case INVTYPE_WEAPON:
11182 case INVTYPE_WEAPONMAINHAND:
11183 case INVTYPE_WEAPONOFFHAND:
11184 default:
11185 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11189 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11191 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11192 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11193 if ((*itr)->GetId() == spell_id)
11194 return *itr;
11196 return NULL;
11199 bool Unit::IsUnderLastManaUseEffect() const
11201 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11204 void Unit::SetContestedPvP(Player *attackedPlayer)
11206 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11208 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11209 return;
11211 player->SetContestedPvPTimer(30000);
11212 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11214 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11215 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11216 // call MoveInLineOfSight for nearby contested guards
11217 SetVisibility(GetVisibility());
11219 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11221 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11222 // call MoveInLineOfSight for nearby contested guards
11223 SetVisibility(GetVisibility());
11227 void Unit::AddPetAura(PetAura const* petSpell)
11229 m_petAuras.insert(petSpell);
11230 if(Pet* pet = GetPet())
11231 pet->CastPetAura(petSpell);
11234 void Unit::RemovePetAura(PetAura const* petSpell)
11236 m_petAuras.erase(petSpell);
11237 if(Pet* pet = GetPet())
11238 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11241 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11243 Pet* pet = new Pet(HUNTER_PET);
11245 if(!pet->CreateBaseAtCreature(creatureTarget))
11247 delete pet;
11248 return NULL;
11251 pet->SetOwnerGUID(GetGUID());
11252 pet->SetCreatorGUID(GetGUID());
11253 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11254 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11256 if(GetTypeId()==TYPEID_PLAYER)
11257 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11259 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11261 if(!pet->InitStatsForLevel(level))
11263 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11264 delete pet;
11265 return NULL;
11268 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11269 // this enables pet details window (Shift+P)
11270 pet->AIM_Initialize();
11271 pet->InitPetCreateSpells();
11272 pet->InitTalentForLevel();
11273 pet->SetHealth(pet->GetMaxHealth());
11275 return pet;
11278 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11280 SpellEntry const* spellProto = aura->GetSpellProto ();
11282 // Get proc Event Entry
11283 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11285 // Aura info stored here
11286 Modifier *mod = aura->GetModifier();
11287 // Skip this auras
11288 if (isNonTriggerAura[mod->m_auraname])
11289 return false;
11290 // If not trigger by default and spellProcEvent==NULL - skip
11291 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11292 return false;
11294 // Get EventProcFlag
11295 uint32 EventProcFlag;
11296 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11297 EventProcFlag = spellProcEvent->procFlags;
11298 else
11299 EventProcFlag = spellProto->procFlags; // else get from spell proto
11300 // Continue if no trigger exist
11301 if (!EventProcFlag)
11302 return false;
11304 // Check spellProcEvent data requirements
11305 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11306 return false;
11308 // In most cases req get honor or XP from kill
11309 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11311 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11312 // Shadow Word: Death - can trigger from every kill
11313 if (aura->GetId() == 32409)
11314 allow = true;
11315 if (!allow)
11316 return false;
11318 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11319 // But except periodic triggers (can triggered from self)
11320 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11321 return false;
11323 // Check if current equipment allows aura to proc
11324 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11326 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11328 Item *item = NULL;
11329 if(attType == BASE_ATTACK)
11330 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11331 else if (attType == OFF_ATTACK)
11332 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11333 else
11334 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11336 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11337 return false;
11339 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11340 return false;
11342 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11344 // Check if player is wearing shield
11345 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11346 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11347 return false;
11350 // Get chance from spell
11351 float chance = (float)spellProto->procChance;
11352 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11353 if(spellProcEvent && spellProcEvent->customChance)
11354 chance = spellProcEvent->customChance;
11355 // If PPM exist calculate chance from PPM
11356 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11358 uint32 WeaponSpeed = GetAttackTime(attType);
11359 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11361 // Apply chance modifer aura
11362 if(Player* modOwner = GetSpellModOwner())
11363 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11365 return roll_chance_f(chance);
11368 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11370 // aura can be deleted at casts
11371 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11372 uint32 effIdx = triggeredByAura->GetEffIndex();
11373 int32 heal = triggeredByAura->GetModifier()->m_amount;
11374 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11376 // jumps
11377 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11379 // current aura expire
11380 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11382 // next target selection
11383 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11385 float radius;
11386 if (spellProto->EffectRadiusIndex[effIdx])
11387 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11388 else
11389 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11391 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11393 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11395 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11397 // aura will applied from caster, but spell casted from current aura holder
11398 SpellModifier *mod = new SpellModifier;
11399 mod->op = SPELLMOD_CHARGES;
11400 mod->value = jumps-5; // negative
11401 mod->type = SPELLMOD_FLAT;
11402 mod->spellId = spellProto->Id;
11403 mod->mask = spellProto->SpellFamilyFlags;
11404 mod->mask2 = spellProto->SpellFamilyFlags2;
11406 caster->AddSpellMod(mod, true);
11407 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11408 caster->AddSpellMod(mod, false);
11413 // heal
11414 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11415 return true;
11418 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11420 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11422 if(!IS_UNIT_GUID(target_guid))
11423 return;
11425 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11426 if(!target)
11427 return;
11429 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11431 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11432 target->RemoveAura(iter);
11433 else
11434 ++iter;
11438 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
11440 WorldObject::SetPhaseMask(newPhaseMask,update);
11442 if(IsInWorld())
11443 if(Pet* pet = GetPet())
11444 pet->SetPhaseMask(newPhaseMask,true);
11447 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
11449 if(GetTypeId() == TYPEID_PLAYER)
11450 ((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));
11451 else
11453 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
11455 WorldPacket data;
11456 // Work strange for many spells: triggered active mover set for targeted player to creature
11457 //BuildTeleportAckMsg(&data, x, y, z, orientation);
11458 BuildHeartBeatMsg(&data);
11459 SendMessageToSet(&data, false);