[7629] Update paladin talent 25988 work to 3.0.x
[AHbot.git] / src / game / Unit.cpp
blobfc2e2c124c0acfe8e5aa1a92c8290b2f6a216d21
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 // Point A, starting location
264 data << GetPositionX() << GetPositionY() << GetPositionZ();
265 // unknown field - unrelated to orientation
266 // seems to increment about 1000 for every 1.7 seconds
267 // for now, we'll just use mstime
268 data << getMSTime();
270 data << uint8(type); // unknown
271 switch(type)
273 case 0: // normal packet
274 break;
275 case 1: // stop packet
276 SendMessageToSet( &data, true );
277 return;
278 case 2: // not used currently
279 data << float(0);
280 data << float(0);
281 data << float(0);
282 break;
283 case 3: // not used currently
284 data << uint64(0); // probably target guid
285 break;
286 case 4: // not used currently
287 data << float(0); // probably orientation
288 break;
291 //Movement Flags (0x0 = walk, 0x100 = run, 0x200 = fly/swim)
292 data << uint32(MovementFlags);
294 data << Time; // Time in between points
295 data << uint32(1); // 1 single waypoint
296 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
298 if(player)
299 player->GetSession()->SendPacket(&data);
300 else
301 SendMessageToSet( &data, true );
304 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
306 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
308 uint32 pathSize = end-start;
310 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
311 data.append(GetPackGUID());
312 data << GetPositionX();
313 data << GetPositionY();
314 data << GetPositionZ();
316 // unknown field - unrelated to orientation
317 // seems to increment about 1000 for every 1.7 seconds
318 // for now, we'll just use mstime
319 data << getMSTime();
321 data << uint8( 0 );
322 data << uint32( MovementFlags );
323 data << uint32( traveltime );
324 data << uint32( pathSize );
325 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
327 //WPAssert( data.size() == 37 + pathnodes.Size( ) * 4 * 3 );
328 SendMessageToSet(&data, true);
331 void Unit::resetAttackTimer(WeaponAttackType type)
333 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
336 bool Unit::canReachWithAttack(Unit *pVictim) const
338 assert(pVictim);
339 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
340 if( reach <= 0.0f )
341 reach = 1.0f;
342 return IsWithinDistInMap(pVictim, reach);
345 void Unit::RemoveSpellsCausingAura(AuraType auraType)
347 if (auraType >= TOTAL_AURAS) return;
348 AuraList::iterator iter, next;
349 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
351 next = iter;
352 ++next;
354 if (*iter)
356 RemoveAurasDueToSpell((*iter)->GetId());
357 if (!m_modAuras[auraType].empty())
358 next = m_modAuras[auraType].begin();
359 else
360 return;
365 bool Unit::HasAuraType(AuraType auraType) const
367 return (!m_modAuras[auraType].empty());
370 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
371 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
373 if(!HasAuraType(auraType))
374 return;
376 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
377 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
378 float chance = float(damage) / max_dmg * 100.0f;
379 if (roll_chance_f(chance))
380 RemoveSpellsCausingAura(auraType);
383 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
385 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
386 return 0;
388 //You don't lose health from damage taken from another player while in a sanctuary
389 //You still see it in the combat log though
390 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
392 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
393 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
394 return 0;
397 // remove affects from victim (including from 0 damage and DoTs)
398 if(pVictim != this)
399 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
401 // remove affects from attacker at any non-DoT damage (including 0 damage)
402 if( damagetype != DOT)
404 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
405 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
407 if(pVictim != this)
408 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
410 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
411 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
414 //Script Event damage Deal
415 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
416 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
417 //Script Event damage taken
418 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
419 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
421 if(!damage)
423 // Rage from physical damage received .
424 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
425 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
427 return 0;
429 if (!spellProto || !IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR, spellProto->Id))
430 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
431 // root type spells do not dispel the root effect
432 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT, spellProto->Id)))
433 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
435 if(pVictim->GetTypeId() != TYPEID_PLAYER)
437 // no xp,health if type 8 /critters/
438 if ( pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
440 pVictim->setDeathState(JUST_DIED);
441 pVictim->SetHealth(0);
443 // allow loot only if has loot_id in creature_template
444 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
445 if(cInfo && cInfo->lootid)
446 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
448 // some critters required for quests
449 if(GetTypeId() == TYPEID_PLAYER)
450 ((Player*)this)->KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
452 return damage;
455 if(!pVictim->isInCombat() && ((Creature*)pVictim)->AI())
456 ((Creature*)pVictim)->AI()->AttackStart(this);
459 DEBUG_LOG("DealDamageStart");
461 uint32 health = pVictim->GetHealth();
462 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
464 // duel ends when player has 1 or less hp
465 bool duel_hasEnded = false;
466 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
468 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
469 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
470 damage = health-1;
472 duel_hasEnded = true;
474 //Get in CombatState
475 if(pVictim != this && damagetype != DOT)
477 SetInCombatWith(pVictim);
478 pVictim->SetInCombatWith(this);
480 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
481 SetContestedPvP(attackedPlayer);
484 // Rage from Damage made (only from direct weapon damage)
485 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
487 uint32 weaponSpeedHitFactor;
489 switch(cleanDamage->attackType)
491 case BASE_ATTACK:
493 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
494 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
495 else
496 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
498 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
500 break;
502 case OFF_ATTACK:
504 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
505 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
506 else
507 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
509 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
511 break;
513 case RANGED_ATTACK:
514 break;
518 if(pVictim->GetTypeId() == TYPEID_PLAYER && GetTypeId() == TYPEID_PLAYER)
520 if(((Player*)pVictim)->InBattleGround())
522 Player *killer = ((Player*)this);
523 if(killer != ((Player*)pVictim))
524 if(BattleGround *bg = killer->GetBattleGround())
525 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
529 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
530 ((Creature*)pVictim)->SetLootRecipient(this);
532 if (health <= damage)
534 DEBUG_LOG("DealDamage: victim just died");
536 // find player: owner of controlled `this` or `this` itself maybe
537 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
539 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
540 player = ((Creature*)pVictim)->GetLootRecipient();
541 // Reward player, his pets, and group/raid members
542 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
543 if(player && player!=pVictim)
545 player->RewardPlayerAndGroupAtKill(pVictim);
546 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
549 DEBUG_LOG("DealDamageAttackStop");
551 // stop combat
552 pVictim->CombatStop();
553 pVictim->getHostilRefManager().deleteReferences();
555 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
557 // if talent known but not triggered (check priest class for speedup check)
558 Aura* spiritOfRedemtionTalentReady = NULL;
559 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
560 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
562 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
563 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
565 if((*itr)->GetSpellProto()->SpellIconID==1654)
567 spiritOfRedemtionTalentReady = *itr;
568 break;
573 DEBUG_LOG("SET JUST_DIED");
574 if(!spiritOfRedemtionTalentReady)
575 pVictim->setDeathState(JUST_DIED);
577 DEBUG_LOG("DealDamageHealth1");
579 if(spiritOfRedemtionTalentReady)
581 // save value before aura remove
582 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
583 if(!ressSpellId)
584 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
586 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
587 pVictim->RemoveAllAurasOnDeath();
589 // restore for use at real death
590 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
592 // FORM_SPIRITOFREDEMPTION and related auras
593 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
595 else
596 pVictim->SetHealth(0);
598 // remember victim PvP death for corpse type and corpse reclaim delay
599 // at original death (not at SpiritOfRedemtionTalent timeout)
600 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
601 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
603 // Call KilledUnit for creatures
604 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
605 ((Creature*)this)->AI()->KilledUnit(pVictim);
607 // achievement stuff
608 if (pVictim->GetTypeId() == TYPEID_PLAYER)
610 if (GetTypeId() == TYPEID_UNIT)
611 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
612 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
613 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
616 // 10% durability loss on death
617 // clean InHateListOf
618 if (pVictim->GetTypeId() == TYPEID_PLAYER)
620 // only if not player and not controlled by player pet. And not at BG
621 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
623 DEBUG_LOG("We are dead, loosing 10 percents durability");
624 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
625 // durability lost message
626 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
627 ((Player*)pVictim)->GetSession()->SendPacket(&data);
630 else // creature died
632 DEBUG_LOG("DealDamageNotPlayer");
633 Creature *cVictim = (Creature*)pVictim;
635 if(!cVictim->isPet())
637 cVictim->DeleteThreatList();
638 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
640 // Call creature just died function
641 if (cVictim->AI())
642 cVictim->AI()->JustDied(this);
644 // Dungeon specific stuff, only applies to players killing creatures
645 if(cVictim->GetInstanceId())
647 Map *m = cVictim->GetMap();
648 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
649 // TODO: do instance binding anyway if the charmer/owner is offline
651 if(m->IsDungeon() && creditedPlayer)
653 if(m->IsRaid() || m->IsHeroic())
655 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
656 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
658 else
660 // the reset time is set but not added to the scheduler
661 // until the players leave the instance
662 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
663 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
664 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
670 // last damage from non duel opponent or opponent controlled creature
671 if(duel_hasEnded)
673 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
674 Player *he = (Player*)pVictim;
676 assert(he->duel);
678 he->duel->opponent->CombatStopWithPets(true);
679 he->CombatStopWithPets(true);
681 he->DuelComplete(DUEL_INTERUPTED);
684 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
685 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
687 Player *killed = ((Player*)pVictim);
688 if(BattleGround *bg = killed->GetBattleGround())
689 if(player)
690 bg->HandleKillPlayer(killed, player);
691 //later we can add support for creature->player kills here i'm
692 //not sure, but i guess those kills also get counted in av
693 //else if(GetTypeId() == TYPEID_UNIT)
694 // bg->HandleKillPlayer(killed,(Creature*)this);
697 else // if (health <= damage)
699 DEBUG_LOG("DealDamageAlive");
701 pVictim->ModifyHealth(- (int32)damage);
703 if(damagetype != DOT)
705 if(getVictim())
707 // if have target and damage pVictim just call AI reaction
708 if(pVictim != getVictim() && pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
709 ((Creature*)pVictim)->AI()->AttackedBy(this);
711 else
713 // if not have main target then attack state with target (including AI call)
714 //start melee attacks only after melee hit
715 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
719 // polymorphed and other negative transformed cases
720 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
721 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
723 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
725 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
726 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
728 if (pVictim->GetTypeId() != TYPEID_PLAYER)
730 if(spellProto && IsDamageToThreatSpell(spellProto))
731 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
732 else
733 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
735 else // victim is a player
737 // Rage from damage received
738 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
740 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
741 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
744 // random durability for items (HIT TAKEN)
745 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
747 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
748 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
752 if(GetTypeId()==TYPEID_PLAYER)
754 // random durability for items (HIT DONE)
755 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
757 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
758 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
762 // TODO: Store auras by interrupt flag to speed this up.
763 AuraMap& vAuras = pVictim->GetAuras();
764 for (AuraMap::iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
766 const SpellEntry *se = i->second->GetSpellProto();
767 next = i; ++next;
768 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
769 continue;
770 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
772 bool remove = true;
773 if (se->procFlags & (1<<3))
775 if (!roll_chance_i(se->procChance))
776 remove = false;
778 if (remove)
780 pVictim->RemoveAurasDueToSpell(i->second->GetId());
781 // FIXME: this may cause the auras with proc chance to be rerolled several times
782 next = vAuras.begin();
787 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
789 if( damagetype != DOT )
791 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
793 // skip channeled spell (processed differently below)
794 if (i == CURRENT_CHANNELED_SPELL)
795 continue;
797 if(Spell* spell = pVictim->m_currentSpells[i])
798 if(spell->getState() == SPELL_STATE_PREPARING)
800 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
801 pVictim->InterruptSpell(i);
802 else
803 spell->Delayed();
808 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
810 if (spell->getState() == SPELL_STATE_CASTING)
812 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
813 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
815 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
816 spell->DelayedChannel();
818 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
820 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
821 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
824 else if (spell->getState() == SPELL_STATE_DELAYED)
825 // break channeled spell in delayed state on damage
827 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
828 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
833 // last damage from duel opponent
834 if(duel_hasEnded)
836 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
837 Player *he = (Player*)pVictim;
839 assert(he->duel);
841 he->SetHealth(1);
843 he->duel->opponent->CombatStopWithPets(true);
844 he->CombatStopWithPets(true);
846 he->CastSpell(he, 7267, true); // beg
847 he->DuelComplete(DUEL_WON);
851 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
853 return damage;
856 void Unit::CastStop(uint32 except_spellid)
858 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
859 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
860 InterruptSpell(i,false);
863 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
865 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
867 if(!spellInfo)
869 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
870 return;
873 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
876 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
878 if(!spellInfo)
880 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
881 return;
884 if (castItem)
885 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
887 if(!originalCaster && triggeredByAura)
888 originalCaster = triggeredByAura->GetCasterGUID();
890 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
892 SpellCastTargets targets;
893 targets.setUnitTarget( Victim );
894 spell->m_CastItem = castItem;
895 spell->prepare(&targets, triggeredByAura);
898 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
900 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
902 if(!spellInfo)
904 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
905 return;
908 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
911 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)
913 if(!spellInfo)
915 sLog.outError("CastCustomSpell: unknown spell");
916 return;
919 if (castItem)
920 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
922 if(!originalCaster && triggeredByAura)
923 originalCaster = triggeredByAura->GetCasterGUID();
925 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
927 if(bp0)
928 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
930 if(bp1)
931 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
933 if(bp2)
934 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
936 SpellCastTargets targets;
937 targets.setUnitTarget( Victim );
938 spell->m_CastItem = castItem;
939 spell->prepare(&targets, triggeredByAura);
942 // used for scripting
943 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
945 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
947 if(!spellInfo)
949 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()));
950 return;
953 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
956 // used for scripting
957 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
959 if(!spellInfo)
961 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
962 return;
965 if (castItem)
966 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
968 if(!originalCaster && triggeredByAura)
969 originalCaster = triggeredByAura->GetCasterGUID();
971 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
973 SpellCastTargets targets;
974 targets.setDestination(x, y, z);
975 spell->m_CastItem = castItem;
976 spell->prepare(&targets, triggeredByAura);
979 // Obsolete func need remove, here only for comotability vs another patches
980 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
982 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
983 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
984 CalculateSpellDamage(&damageInfo, damage, spellInfo);
985 SendSpellNonMeleeDamageLog(&damageInfo);
986 DealSpellDamage(&damageInfo, true);
987 return damageInfo.damage;
990 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
992 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
993 Unit *pVictim = damageInfo->target;
995 if (damage < 0)
996 return;
998 if(!this || !pVictim)
999 return;
1000 if(!this->isAlive() || !pVictim->isAlive())
1001 return;
1003 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1004 // Check spell crit chance
1005 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1006 bool blocked = false;
1007 // Per-school calc
1008 switch (spellInfo->DmgClass)
1010 // Melee and Ranged Spells
1011 case SPELL_DAMAGE_CLASS_RANGED:
1012 case SPELL_DAMAGE_CLASS_MELEE:
1014 // Physical Damage
1015 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1017 //Calculate armor mitigation
1018 damage = CalcArmorReducedDamage(pVictim, damage);
1019 // Get blocked status
1020 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1022 // Magical Damage
1023 else
1025 // Calculate damage bonus
1026 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1028 if (crit)
1030 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1032 // Calculate crit bonus
1033 uint32 crit_bonus = damage;
1034 // Apply crit_damage bonus for melee spells
1035 if(Player* modOwner = GetSpellModOwner())
1036 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1037 damage += crit_bonus;
1039 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1040 int32 critPctDamageMod=0;
1041 if(attackType == RANGED_ATTACK)
1042 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1043 else
1045 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1046 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1048 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1049 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1051 if (critPctDamageMod!=0)
1052 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1054 // Resilience - reduce crit damage
1055 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1056 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1058 // Spell weapon based damage CAN BE crit & blocked at same time
1059 if (blocked)
1061 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1062 if (damage < damageInfo->blocked)
1063 damageInfo->blocked = damage;
1064 damage-=damageInfo->blocked;
1067 break;
1068 // Magical Attacks
1069 case SPELL_DAMAGE_CLASS_NONE:
1070 case SPELL_DAMAGE_CLASS_MAGIC:
1072 // Calculate damage bonus
1073 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1074 // If crit add critical bonus
1075 if (crit)
1077 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1078 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1079 // Resilience - reduce crit damage
1080 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1081 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1084 break;
1087 // Calculate absorb resist
1088 if(damage > 0)
1090 // lookup absorb/resist ignore auras on caster for spell
1091 bool ignore = false;
1092 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1093 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1094 if ((*i)->isAffectedOnSpell(spellInfo))
1096 ignore = true;
1097 break;
1100 if (!ignore)
1102 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1103 damage-= damageInfo->absorb + damageInfo->resist;
1106 else
1107 damage = 0;
1108 damageInfo->damage = damage;
1111 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1113 if (damageInfo==0)
1114 return;
1116 Unit *pVictim = damageInfo->target;
1118 if(!this || !pVictim)
1119 return;
1121 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1122 return;
1124 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1125 if (spellProto == NULL)
1127 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1128 return;
1131 //You don't lose health from damage taken from another player while in a sanctuary
1132 //You still see it in the combat log though
1133 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1135 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1136 if(area && area->flags & 0x800) //sanctuary
1137 return;
1140 // Call default DealDamage
1141 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1142 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1145 //TODO for melee need create structure as in
1146 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1148 damageInfo->attacker = this;
1149 damageInfo->target = pVictim;
1150 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1151 damageInfo->attackType = attackType;
1152 damageInfo->damage = 0;
1153 damageInfo->cleanDamage = 0;
1154 damageInfo->absorb = 0;
1155 damageInfo->resist = 0;
1156 damageInfo->blocked_amount = 0;
1158 damageInfo->TargetState = 0;
1159 damageInfo->HitInfo = 0;
1160 damageInfo->procAttacker = PROC_FLAG_NONE;
1161 damageInfo->procVictim = PROC_FLAG_NONE;
1162 damageInfo->procEx = PROC_EX_NONE;
1163 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1165 if(!this || !pVictim)
1166 return;
1167 if(!this->isAlive() || !pVictim->isAlive())
1168 return;
1170 // Select HitInfo/procAttacker/procVictim flag based on attack type
1171 switch (attackType)
1173 case BASE_ATTACK:
1174 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1175 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1176 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1177 break;
1178 case OFF_ATTACK:
1179 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1180 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1181 damageInfo->HitInfo = HITINFO_LEFTSWING;
1182 break;
1183 case RANGED_ATTACK:
1184 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1185 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1186 damageInfo->HitInfo = 0x08;// test
1187 break;
1188 default:
1189 break;
1192 // Physical Immune check
1193 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1195 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1196 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1198 damageInfo->procEx |=PROC_EX_IMMUNE;
1199 damageInfo->damage = 0;
1200 damageInfo->cleanDamage = 0;
1201 return;
1203 damage += CalculateDamage (damageInfo->attackType, false);
1204 // Add melee damage bonus
1205 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1206 // Calculate armor reduction
1207 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1208 damageInfo->cleanDamage += damage - damageInfo->damage;
1210 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1212 // Disable parry or dodge for ranged attack
1213 if(damageInfo->attackType == RANGED_ATTACK)
1215 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1216 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1219 switch(damageInfo->hitOutCome)
1221 case MELEE_HIT_EVADE:
1223 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1224 damageInfo->TargetState = VICTIMSTATE_EVADES;
1226 damageInfo->procEx|=PROC_EX_EVADE;
1227 damageInfo->damage = 0;
1228 damageInfo->cleanDamage = 0;
1229 return;
1231 case MELEE_HIT_MISS:
1233 damageInfo->HitInfo |= HITINFO_MISS;
1234 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1236 damageInfo->procEx|=PROC_EX_MISS;
1237 damageInfo->damage = 0;
1238 damageInfo->cleanDamage = 0;
1239 break;
1241 case MELEE_HIT_NORMAL:
1242 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1243 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1244 break;
1245 case MELEE_HIT_CRIT:
1247 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1248 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1250 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1251 // Crit bonus calc
1252 damageInfo->damage += damageInfo->damage;
1253 int32 mod=0;
1254 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1255 if(damageInfo->attackType == RANGED_ATTACK)
1256 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1257 else
1259 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1260 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1263 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1265 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1266 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1267 if (mod!=0)
1268 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1270 // Resilience - reduce crit damage
1271 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1273 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1274 damageInfo->damage -= resilienceReduction;
1275 damageInfo->cleanDamage += resilienceReduction;
1277 break;
1279 case MELEE_HIT_PARRY:
1280 damageInfo->TargetState = VICTIMSTATE_PARRY;
1281 damageInfo->procEx|=PROC_EX_PARRY;
1282 damageInfo->cleanDamage += damageInfo->damage;
1283 damageInfo->damage = 0;
1284 break;
1286 case MELEE_HIT_DODGE:
1287 damageInfo->TargetState = VICTIMSTATE_DODGE;
1288 damageInfo->procEx|=PROC_EX_DODGE;
1289 damageInfo->cleanDamage += damageInfo->damage;
1290 damageInfo->damage = 0;
1291 break;
1292 case MELEE_HIT_BLOCK:
1294 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1295 damageInfo->HitInfo |= HITINFO_BLOCK;
1296 damageInfo->procEx|=PROC_EX_BLOCK;
1297 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1298 if (damageInfo->blocked_amount >= damageInfo->damage)
1300 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1301 damageInfo->blocked_amount = damageInfo->damage;
1303 damageInfo->damage -= damageInfo->blocked_amount;
1304 damageInfo->cleanDamage += damageInfo->blocked_amount;
1305 break;
1307 case MELEE_HIT_GLANCING:
1309 damageInfo->HitInfo |= HITINFO_GLANCING;
1310 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1311 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1312 float reducePercent = 1.0f; //damage factor
1313 // calculate base values and mods
1314 float baseLowEnd = 1.3;
1315 float baseHighEnd = 1.2;
1316 switch(getClass()) // lowering base values for casters
1318 case CLASS_SHAMAN:
1319 case CLASS_PRIEST:
1320 case CLASS_MAGE:
1321 case CLASS_WARLOCK:
1322 case CLASS_DRUID:
1323 baseLowEnd -= 0.7;
1324 baseHighEnd -= 0.3;
1325 break;
1328 float maxLowEnd = 0.6;
1329 switch(getClass()) // upper for melee classes
1331 case CLASS_WARRIOR:
1332 case CLASS_ROGUE:
1333 maxLowEnd = 0.91; //If the attacker is a melee class then instead the lower value of 0.91
1336 // calculate values
1337 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1338 float lowEnd = baseLowEnd - ( 0.05f * diff );
1339 float highEnd = baseHighEnd - ( 0.03f * diff );
1341 // apply max/min bounds
1342 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1343 lowEnd = 0.01f;
1344 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1345 lowEnd = maxLowEnd;
1347 if ( highEnd < 0.2f ) //high end limits
1348 highEnd = 0.2f;
1349 if ( highEnd > 0.99f )
1350 highEnd = 0.99f;
1352 if(lowEnd > highEnd) // prevent negative range size
1353 lowEnd = highEnd;
1355 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1357 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1358 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1359 break;
1361 case MELEE_HIT_CRUSHING:
1363 damageInfo->HitInfo |= HITINFO_CRUSHING;
1364 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1365 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1366 // 150% normal damage
1367 damageInfo->damage += (damageInfo->damage / 2);
1368 break;
1370 default:
1372 break;
1375 // Calculate absorb resist
1376 if(int32(damageInfo->damage) > 0)
1378 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1379 // Calculate absorb & resists
1380 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1381 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1382 if (damageInfo->absorb)
1384 damageInfo->HitInfo|=HITINFO_ABSORB;
1385 damageInfo->procEx|=PROC_EX_ABSORB;
1387 if (damageInfo->resist)
1388 damageInfo->HitInfo|=HITINFO_RESIST;
1391 else // Umpossible get negative result but....
1392 damageInfo->damage = 0;
1395 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1397 if (damageInfo==0) return;
1398 Unit *pVictim = damageInfo->target;
1400 if(!this || !pVictim)
1401 return;
1403 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1404 return;
1406 //You don't lose health from damage taken from another player while in a sanctuary
1407 //You still see it in the combat log though
1408 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1410 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1411 if(area && area->flags & 0x800) //sanctuary
1412 return;
1415 // Hmmmm dont like this emotes cloent must by self do all animations
1416 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1417 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1418 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1419 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1421 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1423 // Get attack timers
1424 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1425 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1426 // Reduce attack time
1427 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1429 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20;
1430 float percent60 = 3 * percent20;
1431 if(offtime > percent20 && offtime <= percent60)
1433 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1435 else if(offtime > percent60)
1437 offtime -= 2 * percent20;
1438 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1441 else
1443 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1444 float percent60 = 3 * percent20;
1445 if(basetime > percent20 && basetime <= percent60)
1447 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1449 else if(basetime > percent60)
1451 basetime -= 2 * percent20;
1452 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1457 // Call default DealDamage
1458 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1459 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1461 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1462 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1463 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1465 // -probability is between 0% and 40%
1466 // 20% base chance
1467 float Probability = 20;
1469 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1470 if( pVictim->getLevel() < 30 )
1471 Probability = 0.65f*pVictim->getLevel()+0.5;
1473 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1474 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1476 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1478 if(Probability > 40)
1479 Probability = 40;
1481 if(roll_chance_f(Probability))
1482 CastSpell(pVictim, 1604, true);
1485 // If not miss
1486 if (!(damageInfo->HitInfo & HITINFO_MISS))
1488 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1490 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1491 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1494 // victim's damage shield
1495 std::set<Aura*> alreadyDone;
1496 uint32 removedAuras = pVictim->m_removedAuras;
1497 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1498 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1500 next++;
1501 if (alreadyDone.find(*i) == alreadyDone.end())
1503 alreadyDone.insert(*i);
1504 uint32 damage=(*i)->GetModifier()->m_amount;
1505 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1506 if(!spellProto)
1507 continue;
1508 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1509 //uint32 absorb;
1510 //uint32 resist;
1511 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1512 //damage-=absorb + resist;
1514 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1515 data << uint64(pVictim->GetGUID());
1516 data << uint64(GetGUID());
1517 data << uint32(spellProto->Id);
1518 data << uint32(damage); // Damage
1519 data << uint32(0); // Overkill
1520 data << uint32(spellProto->SchoolMask);
1521 pVictim->SendMessageToSet(&data, true );
1523 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1525 if (pVictim->m_removedAuras > removedAuras)
1527 removedAuras = pVictim->m_removedAuras;
1528 next = vDamageShields.begin();
1536 void Unit::HandleEmoteCommand(uint32 anim_id)
1538 WorldPacket data( SMSG_EMOTE, 12 );
1539 data << uint32(anim_id);
1540 data << uint64(GetGUID());
1541 SendMessageToSet(&data, true);
1544 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1546 uint32 newdamage = 0;
1547 float armor = pVictim->GetArmor();
1548 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1549 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1551 // Apply Player CR_ARMOR_PENETRATION rating
1552 if (GetTypeId()==TYPEID_PLAYER)
1553 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1555 if (armor < 0.0f) armor=0.0f;
1557 float levelModifier = getLevel();
1558 if ( levelModifier > 59 )
1559 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1561 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1562 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1564 if(tmpvalue < 0.0f)
1565 tmpvalue = 0.0f;
1566 if(tmpvalue > 0.75f)
1567 tmpvalue = 0.75f;
1568 newdamage = uint32(damage - (damage * tmpvalue));
1570 return (newdamage > 1) ? newdamage : 1;
1573 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1575 if(!pVictim || !pVictim->isAlive() || !damage)
1576 return;
1578 // Magic damage, check for resists
1579 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1581 // Get base victim resistance for school
1582 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1583 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1584 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1586 tmpvalue2 *= (float)(0.15f / getLevel());
1587 if (tmpvalue2 < 0.0f)
1588 tmpvalue2 = 0.0f;
1589 if (tmpvalue2 > 0.75f)
1590 tmpvalue2 = 0.75f;
1591 uint32 ran = urand(0, 100);
1592 uint32 faq[4] = {24,6,4,6};
1593 uint8 m = 0;
1594 float Binom = 0.0f;
1595 for (uint8 i = 0; i < 4; i++)
1597 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1598 if (ran > Binom )
1599 ++m;
1600 else
1601 break;
1603 if (damagetype == DOT && m == 4)
1604 *resist += uint32(damage - 1);
1605 else
1606 *resist += uint32(damage * m / 4);
1607 if(*resist > damage)
1608 *resist = damage;
1610 else
1611 *resist = 0;
1613 int32 RemainingDamage = damage - *resist;
1615 // Get unit state (need for some absorb check)
1616 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1617 // Reflect damage spells (not cast any damage spell in aura lookup)
1618 uint32 reflectSpell = 0;
1619 int32 reflectDamage = 0;
1620 // Need remove expired auras after
1621 bool existExpired = false;
1622 // absorb without mana cost
1623 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1624 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1626 Modifier* mod = (*i)->GetModifier();
1627 if (!(mod->m_miscvalue & schoolMask))
1628 continue;
1630 SpellEntry const* spellProto = (*i)->GetSpellProto();
1632 // Max Amount can be absorbed by this aura
1633 int32 currentAbsorb = mod->m_amount;
1635 // Found empty aura (umpossible but..)
1636 if (currentAbsorb <=0)
1638 existExpired = true;
1639 continue;
1641 // Handle custom absorb auras
1642 // TODO: try find better way
1643 switch(spellProto->SpellFamilyName)
1645 case SPELLFAMILY_GENERIC:
1647 // Astral Shift
1648 if (spellProto->SpellIconID == 3066)
1650 //reduces all damage taken while stun, fear or silence
1651 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1652 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1653 continue;
1655 // Nerves of Steel
1656 if (spellProto->SpellIconID == 2115)
1658 // while affected by Stun and Fear
1659 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1660 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1661 continue;
1663 // Spell Deflection
1664 if (spellProto->SpellIconID == 3006)
1666 // You have a chance equal to your Parry chance
1667 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1668 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1669 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1670 continue;
1672 // Reflective Shield (Lady Malande boss)
1673 if (spellProto->Id == 41475)
1675 if(RemainingDamage < currentAbsorb)
1676 reflectDamage = RemainingDamage / 2;
1677 else
1678 reflectDamage = currentAbsorb / 2;
1679 reflectSpell = 33619;
1680 break;
1682 if (spellProto->Id == 39228 || // Argussian Compass
1683 spellProto->Id == 60218) // Essence of Gossamer
1685 // Max absorb stored in 1 dummy effect
1686 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1687 currentAbsorb = spellProto->EffectBasePoints[1];
1688 break;
1690 break;
1692 case SPELLFAMILY_DRUID:
1694 // Primal Tenacity
1695 if (spellProto->SpellIconID == 2253)
1697 //reduces all damage taken while Stunned
1698 if (unitflag & UNIT_FLAG_STUNNED)
1699 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1700 continue;
1702 break;
1704 case SPELLFAMILY_ROGUE:
1706 // Cheat Death
1707 if(spellProto->SpellIconID == 2109)
1709 if (pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1710 pVictim->GetHealth() <= RemainingDamage && // Only if damage kill
1711 !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
1712 roll_chance_i(currentAbsorb)) // Only if roll
1714 pVictim->CastSpell(pVictim,31231,true);
1715 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1716 // with health > 10% lost health until health==10%, in other case no losses
1717 uint32 health10 = pVictim->GetMaxHealth()/10;
1718 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1720 continue;
1722 break;
1724 case SPELLFAMILY_PRIEST:
1726 // Reflective Shield
1727 if (spellProto->SpellFamilyFlags == 0x1)
1729 if (pVictim == this)
1730 break;
1731 Unit* caster = (*i)->GetCaster();
1732 if (!caster)
1733 break;
1734 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1735 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1737 switch((*k)->GetModifier()->m_miscvalue)
1739 case 5065: // Rank 1
1740 case 5064: // Rank 2
1741 case 5063: // Rank 3
1743 if(RemainingDamage >= currentAbsorb)
1744 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1745 else
1746 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1747 reflectSpell = 33619;
1748 } break;
1749 default: break;
1752 break;
1754 break;
1756 case SPELLFAMILY_SHAMAN:
1758 // Astral Shift
1759 if (spellProto->SpellIconID == 3066)
1761 //reduces all damage taken while stun, fear or silence
1762 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1763 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1764 continue;
1766 break;
1768 case SPELLFAMILY_DEATHKNIGHT:
1770 // Shadow of Death
1771 if (spellProto->SpellIconID == 1958)
1773 // TODO: absorb only while transform
1774 continue;
1776 // Anti-Magic Shell (on self)
1777 if (spellProto->Id == 48707)
1779 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1780 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1781 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1782 int32 regen = absorbed * 2 / 10;
1783 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1784 RemainingDamage -= absorbed;
1785 continue;
1787 // Anti-Magic Shell (on single party/raid member)
1788 if (spellProto->Id == 50462)
1790 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1791 continue;
1793 // Anti-Magic Zone
1794 if (spellProto->Id == 50461)
1796 Unit* caster = (*i)->GetCaster();
1797 if (!caster)
1798 continue;
1799 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1800 int32 canabsorb = caster->GetHealth();
1801 if (canabsorb < absorbed)
1802 absorbed = canabsorb;
1803 DealDamage(caster, absorbed, NULL, damagetype, schoolMask, 0, false);
1804 RemainingDamage -= absorbed;
1805 continue;
1807 break;
1809 default:
1810 break;
1813 // currentAbsorb - damage can be absorbed by shield
1814 // If need absorb less damage
1815 if (RemainingDamage < currentAbsorb)
1816 currentAbsorb = RemainingDamage;
1818 RemainingDamage -= currentAbsorb;
1820 // Reduce shield amount
1821 mod->m_amount-=currentAbsorb;
1822 // Need remove it later
1823 if (mod->m_amount<=0)
1824 existExpired = true;
1827 // Remove all expired absorb auras
1828 if (existExpired)
1830 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1832 if ((*i)->GetModifier()->m_amount<=0)
1834 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1835 i = vSchoolAbsorb.begin();
1837 else
1838 ++i;
1841 // Cast back reflect damage spell
1842 if (reflectSpell)
1843 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true);
1845 // absorb by mana cost
1846 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1847 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1849 next = i; ++next;
1851 // check damage school mask
1852 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1853 continue;
1855 int32 currentAbsorb;
1856 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1857 currentAbsorb = (*i)->GetModifier()->m_amount;
1858 else
1859 currentAbsorb = RemainingDamage;
1861 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1862 if(Player *modOwner = pVictim->GetSpellModOwner())
1863 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1865 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1866 if (currentAbsorb > maxAbsorb)
1867 currentAbsorb = maxAbsorb;
1869 (*i)->GetModifier()->m_amount -= currentAbsorb;
1870 if((*i)->GetModifier()->m_amount <= 0)
1872 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1873 next = vManaShield.begin();
1876 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1877 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1879 RemainingDamage -= currentAbsorb;
1882 // only split damage if not damaging yourself
1883 if(pVictim != this)
1885 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1886 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1888 next = i; ++next;
1890 // check damage school mask
1891 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1892 continue;
1894 // Damage can be splitted only if aura has an alive caster
1895 Unit *caster = (*i)->GetCaster();
1896 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1897 continue;
1899 int32 currentAbsorb;
1900 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1901 currentAbsorb = (*i)->GetModifier()->m_amount;
1902 else
1903 currentAbsorb = RemainingDamage;
1905 RemainingDamage -= currentAbsorb;
1907 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1909 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1910 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1913 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1914 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1916 next = i; ++next;
1918 // check damage school mask
1919 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1920 continue;
1922 // Damage can be splitted only if aura has an alive caster
1923 Unit *caster = (*i)->GetCaster();
1924 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1925 continue;
1927 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1929 RemainingDamage -= splitted;
1931 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1933 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1934 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1938 *absorb = damage - RemainingDamage - *resist;
1941 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1943 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1944 return;
1946 if (!pVictim->isAlive())
1947 return;
1949 if(IsNonMeleeSpellCasted(false))
1950 return;
1952 uint32 hitInfo;
1953 if (attType == BASE_ATTACK)
1954 hitInfo = HITINFO_NORMALSWING2;
1955 else if (attType == OFF_ATTACK)
1956 hitInfo = HITINFO_LEFTSWING;
1957 else
1958 return; // ignore ranged case
1960 uint32 extraAttacks = m_extraAttacks;
1962 // melee attack spell casted at main hand attack only
1963 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1965 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1967 // not recent extra attack only at any non extra attack (melee spell case)
1968 if(!extra && extraAttacks)
1970 while(m_extraAttacks)
1972 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1973 if(m_extraAttacks > 0)
1974 --m_extraAttacks;
1978 return;
1981 CalcDamageInfo damageInfo;
1982 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1983 // Send log damage message to client
1984 SendAttackStateUpdate(&damageInfo);
1985 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1986 DealMeleeDamage(&damageInfo,true);
1988 if (GetTypeId() == TYPEID_PLAYER)
1989 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1990 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1991 else
1992 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1993 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1995 // extra attack only at any non extra attack (normal case)
1996 if(!extra && extraAttacks)
1998 while(m_extraAttacks)
2000 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2001 if(m_extraAttacks > 0)
2002 --m_extraAttacks;
2007 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2009 // This is only wrapper
2011 // Miss chance based on melee
2012 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2014 // Critical hit chance
2015 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2017 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2018 float dodge_chance = pVictim->GetUnitDodgeChance();
2019 float block_chance = pVictim->GetUnitBlockChance();
2020 float parry_chance = pVictim->GetUnitParryChance();
2022 // Useful if want to specify crit & miss chances for melee, else it could be removed
2023 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2025 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2028 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2030 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2031 return MELEE_HIT_EVADE;
2033 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2034 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2036 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2037 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2039 // bonus from skills is 0.04%
2040 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2041 int32 sum = 0, tmp = 0;
2042 int32 roll = urand (0, 10000);
2044 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2045 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2046 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2048 tmp = miss_chance;
2050 if (tmp > 0 && roll < (sum += tmp ))
2052 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2053 return MELEE_HIT_MISS;
2056 // always crit against a sitting target (except 0 crit chance)
2057 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2059 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2060 return MELEE_HIT_CRIT;
2063 // Dodge chance
2065 // only players can't dodge if attacker is behind
2066 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2068 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2070 else
2072 // Reduce dodge chance by attacker expertise rating
2073 if (GetTypeId() == TYPEID_PLAYER)
2074 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2076 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2077 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2079 tmp = dodge_chance;
2080 if ( (tmp > 0) // check if unit _can_ dodge
2081 && ((tmp -= skillBonus) > 0)
2082 && roll < (sum += tmp))
2084 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2085 return MELEE_HIT_DODGE;
2089 // parry & block chances
2091 // check if attack comes from behind, nobody can parry or block if attacker is behind
2092 if (!pVictim->HasInArc(M_PI,this))
2094 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2096 else
2098 // Reduce parry chance by attacker expertise rating
2099 if (GetTypeId() == TYPEID_PLAYER)
2100 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2102 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2104 int32 tmp = int32(parry_chance);
2105 if ( (tmp > 0) // check if unit _can_ parry
2106 && ((tmp -= skillBonus) > 0)
2107 && (roll < (sum += tmp)))
2109 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
2110 return MELEE_HIT_PARRY;
2114 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2116 tmp = block_chance;
2117 if ( (tmp > 0) // check if unit _can_ block
2118 && ((tmp -= skillBonus) > 0)
2119 && (roll < (sum += tmp)))
2121 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2122 return MELEE_HIT_BLOCK;
2127 // Critical chance
2128 tmp = crit_chance;
2130 if (tmp > 0 && roll < (sum += tmp))
2132 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2133 return MELEE_HIT_CRIT;
2136 // 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)
2137 if( attType != RANGED_ATTACK &&
2138 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2139 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2140 getLevel() < pVictim->getLevelForTarget(this) )
2142 // cap possible value (with bonuses > max skill)
2143 int32 skill = attackerWeaponSkill;
2144 int32 maxskill = attackerMaxSkillValueForLevel;
2145 skill = (skill > maxskill) ? maxskill : skill;
2147 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2148 tmp = tmp > 4000 ? 4000 : tmp;
2149 if (roll < (sum += tmp))
2151 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2152 return MELEE_HIT_GLANCING;
2156 // mobs can score crushing blows if they're 4 or more levels above victim
2157 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2158 // can be from by creature (if can) or from controlled player that considered as creature
2159 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2160 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2161 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2163 // when their weapon skill is 15 or more above victim's defense skill
2164 tmp = victimDefenseSkill;
2165 int32 tmpmax = victimMaxSkillValueForLevel;
2166 // having defense above your maximum (from items, talents etc.) has no effect
2167 tmp = tmp > tmpmax ? tmpmax : tmp;
2168 // tmp = mob's level * 5 - player's current defense skill
2169 tmp = attackerMaxSkillValueForLevel - tmp;
2170 if(tmp >= 15)
2172 // add 2% chance per lacking skill point, min. is 15%
2173 tmp = tmp * 200 - 1500;
2174 if (roll < (sum += tmp))
2176 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2177 return MELEE_HIT_CRUSHING;
2182 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2183 return MELEE_HIT_NORMAL;
2186 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2188 float min_damage, max_damage;
2190 if (normalized && GetTypeId()==TYPEID_PLAYER)
2191 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2192 else
2194 switch (attType)
2196 case RANGED_ATTACK:
2197 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2198 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2199 break;
2200 case BASE_ATTACK:
2201 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2202 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2203 break;
2204 case OFF_ATTACK:
2205 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2206 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2207 break;
2208 // Just for good manner
2209 default:
2210 min_damage = 0.0f;
2211 max_damage = 0.0f;
2212 break;
2216 if (min_damage > max_damage)
2218 std::swap(min_damage,max_damage);
2221 if(max_damage == 0.0f)
2222 max_damage = 5.0f;
2224 return urand((uint32)min_damage, (uint32)max_damage);
2227 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2229 if(spellProto->spellLevel <= 0)
2230 return 1.0f;
2232 float LvlPenalty = 0.0f;
2234 if(spellProto->spellLevel < 20)
2235 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2236 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2237 if(LvlFactor > 1.0f)
2238 LvlFactor = 1.0f;
2240 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2243 void Unit::SendAttackStart(Unit* pVictim)
2245 WorldPacket data( SMSG_ATTACKSTART, 16 );
2246 data << uint64(GetGUID());
2247 data << uint64(pVictim->GetGUID());
2249 SendMessageToSet(&data, true);
2250 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2253 void Unit::SendAttackStop(Unit* victim)
2255 if(!victim)
2256 return;
2258 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2259 data.append(GetPackGUID());
2260 data.append(victim->GetPackGUID()); // can be 0x00...
2261 data << uint32(0); // can be 0x1
2262 SendMessageToSet(&data, true);
2263 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2265 /*if(victim->GetTypeId() == TYPEID_UNIT)
2266 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2269 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2271 if (pVictim->HasInArc(M_PI,this))
2273 /* Currently not exist spells with ignore block
2274 // Ignore combat result aura (parry/dodge check on prepare)
2275 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2276 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2278 if (!(*i)->isAffectedOnSpell(spellProto))
2279 continue;
2280 if ((*i)->GetModifier()->m_miscvalue == )
2281 return false;
2285 // Check creatures flags_extra for disable block
2286 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2287 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2288 return false;
2290 float blockChance = pVictim->GetUnitBlockChance();
2291 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2292 if (roll_chance_f(blockChance))
2293 return true;
2295 return false;
2298 // Melee based spells can be miss, parry or dodge on this step
2299 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2300 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2302 // Calculate hit chance (more correct for chance mod)
2303 int32 HitChance;
2305 // PvP - PvE melee chances
2306 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2307 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2308 if(leveldif < 3)
2309 HitChance = 95 - leveldif;
2310 else
2311 HitChance = 93 - (leveldif - 2) * lchance;
2313 // Hit chance depends from victim auras
2314 if(attType == RANGED_ATTACK)
2315 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2316 else
2317 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2319 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2320 if(Player *modOwner = GetSpellModOwner())
2321 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2323 // Miss = 100 - hit
2324 float miss_chance= 100.0f - HitChance;
2326 // Bonuses from attacker aura and ratings
2327 if (attType == RANGED_ATTACK)
2328 miss_chance -= m_modRangedHitChance;
2329 else
2330 miss_chance -= m_modMeleeHitChance;
2332 // bonus from skills is 0.04%
2333 miss_chance -= skillDiff * 0.04f;
2335 // Limit miss chance from 0 to 60%
2336 if (miss_chance < 0.0f)
2337 return 0.0f;
2338 if (miss_chance > 60.0f)
2339 return 60.0f;
2340 return miss_chance;
2343 // Melee based spells hit result calculations
2344 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2346 WeaponAttackType attType = BASE_ATTACK;
2348 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2349 attType = RANGED_ATTACK;
2351 // bonus from skills is 0.04% per skill Diff
2352 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2353 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2354 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2356 uint32 roll = urand (0, 10000);
2358 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2359 // Roll miss
2360 uint32 tmp = missChance;
2361 if (roll < tmp)
2362 return SPELL_MISS_MISS;
2364 // Chance resist mechanic (select max value from every mechanic spell effect)
2365 int32 resist_mech = 0;
2366 // Get effects mechanic and chance
2367 for(int eff = 0; eff < 3; ++eff)
2369 int32 effect_mech = GetEffectMechanic(spell, eff);
2370 if (effect_mech)
2372 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2373 if (resist_mech < temp*100)
2374 resist_mech = temp*100;
2377 // Roll chance
2378 tmp += resist_mech;
2379 if (roll < tmp)
2380 return SPELL_MISS_RESIST;
2382 bool canDodge = true;
2383 bool canParry = true;
2385 // Same spells cannot be parry/dodge
2386 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2387 return SPELL_MISS_NONE;
2389 // Ranged attack cannot be parry/dodge only deflect
2390 if (attType == RANGED_ATTACK)
2392 // only if in front
2393 if (pVictim->HasInArc(M_PI,this))
2395 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2396 tmp+=deflect_chance;
2397 if (roll < tmp)
2398 return SPELL_MISS_DEFLECT;
2400 return SPELL_MISS_NONE;
2403 // Check for attack from behind
2404 if (!pVictim->HasInArc(M_PI,this))
2406 // Can`t dodge from behind in PvP (but its possible in PvE)
2407 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2408 canDodge = false;
2409 // Can`t parry
2410 canParry = false;
2412 // Check creatures flags_extra for disable parry
2413 if(pVictim->GetTypeId()==TYPEID_UNIT)
2415 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2416 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2417 canParry = false;
2419 // Ignore combat result aura
2420 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2421 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2423 if (!(*i)->isAffectedOnSpell(spell))
2424 continue;
2425 switch((*i)->GetModifier()->m_miscvalue)
2427 case MELEE_HIT_DODGE: canDodge = false; break;
2428 case MELEE_HIT_BLOCK: break; // Block check in hit step
2429 case MELEE_HIT_PARRY: canParry = false; break;
2430 default:
2431 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2432 break;
2436 if (canDodge)
2438 // Roll dodge
2439 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2440 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2441 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2442 // Reduce dodge chance by attacker expertise rating
2443 if (GetTypeId() == TYPEID_PLAYER)
2444 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2445 if (dodgeChance < 0)
2446 dodgeChance = 0;
2448 tmp += dodgeChance;
2449 if (roll < tmp)
2450 return SPELL_MISS_DODGE;
2453 if (canParry)
2455 // Roll parry
2456 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2457 // Reduce parry chance by attacker expertise rating
2458 if (GetTypeId() == TYPEID_PLAYER)
2459 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2460 if (parryChance < 0)
2461 parryChance = 0;
2463 tmp += parryChance;
2464 if (roll < tmp)
2465 return SPELL_MISS_PARRY;
2468 return SPELL_MISS_NONE;
2471 // TODO need use unit spell resistances in calculations
2472 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2474 // Can`t miss on dead target (on skinning for example)
2475 if (!pVictim->isAlive())
2476 return SPELL_MISS_NONE;
2478 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2479 // PvP - PvE spell misschances per leveldif > 2
2480 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2481 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2483 // Base hit chance from attacker and victim levels
2484 int32 modHitChance;
2485 if(leveldif < 3)
2486 modHitChance = 96 - leveldif;
2487 else
2488 modHitChance = 94 - (leveldif - 2) * lchance;
2490 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2491 if(Player *modOwner = GetSpellModOwner())
2492 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2493 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2494 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2495 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2496 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2497 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2498 if (IsAreaOfEffectSpell(spell))
2499 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2500 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2501 if (IsDispelSpell(spell))
2502 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2503 // Chance resist mechanic (select max value from every mechanic spell effect)
2504 int32 resist_mech = 0;
2505 // Get effects mechanic and chance
2506 for(int eff = 0; eff < 3; ++eff)
2508 int32 effect_mech = GetEffectMechanic(spell, eff);
2509 if (effect_mech)
2511 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2512 if (resist_mech < temp)
2513 resist_mech = temp;
2516 // Apply mod
2517 modHitChance-=resist_mech;
2519 // Chance resist debuff
2520 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2522 int32 HitChance = modHitChance * 100;
2523 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2524 HitChance += int32(m_modSpellHitChance*100.0f);
2526 // Decrease hit chance from victim rating bonus
2527 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2528 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2530 if (HitChance < 100) HitChance = 100;
2531 if (HitChance > 9900) HitChance = 9900;
2533 int32 tmp = 10000 - HitChance;
2535 uint32 rand = urand(0,10000);
2537 if (rand < tmp)
2538 return SPELL_MISS_RESIST;
2540 // cast by caster in front of victim
2541 if (pVictim->HasInArc(M_PI,this))
2543 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2544 tmp+=deflect_chance;
2545 if (rand < tmp)
2546 return SPELL_MISS_DEFLECT;
2549 return SPELL_MISS_NONE;
2552 // Calculate spell hit result can be:
2553 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2554 // For melee based spells:
2555 // Miss
2556 // Dodge
2557 // Parry
2558 // For spells
2559 // Resist
2560 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2562 // Return evade for units in evade mode
2563 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2564 return SPELL_MISS_EVADE;
2566 // Check for immune
2567 if (pVictim->IsImmunedToSpell(spell))
2568 return SPELL_MISS_IMMUNE;
2570 // All positive spells can`t miss
2571 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2572 if (IsPositiveSpell(spell->Id))
2573 return SPELL_MISS_NONE;
2575 // Check for immune
2576 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2577 return SPELL_MISS_IMMUNE;
2579 // Try victim reflect spell
2580 if (CanReflect)
2582 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2583 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2584 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2585 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2586 reflectchance += (*i)->GetModifier()->m_amount;
2587 if (reflectchance > 0 && roll_chance_i(reflectchance))
2589 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2590 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2591 return SPELL_MISS_REFLECT;
2595 switch (spell->DmgClass)
2597 case SPELL_DAMAGE_CLASS_RANGED:
2598 case SPELL_DAMAGE_CLASS_MELEE:
2599 return MeleeSpellHitResult(pVictim, spell);
2600 case SPELL_DAMAGE_CLASS_NONE:
2601 case SPELL_DAMAGE_CLASS_MAGIC:
2602 return MagicSpellHitResult(pVictim, spell);
2604 return SPELL_MISS_NONE;
2607 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2609 if(!pVictim)
2610 return 0.0f;
2612 // Base misschance 5%
2613 float misschance = 5.0f;
2615 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2616 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2618 bool isNormal = false;
2619 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2621 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2623 isNormal = true;
2624 break;
2627 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2629 misschance = 5.0f;
2631 else
2633 misschance = 24.0f;
2637 // PvP : PvE melee misschances per leveldif > 2
2638 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2640 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2641 if(leveldif < 0)
2642 leveldif = 0;
2644 // Hit chance from attacker based on ratings and auras
2645 float m_modHitChance;
2646 if (attType == RANGED_ATTACK)
2647 m_modHitChance = m_modRangedHitChance;
2648 else
2649 m_modHitChance = m_modMeleeHitChance;
2651 if(leveldif < 3)
2652 misschance += (leveldif - m_modHitChance);
2653 else
2654 misschance += ((leveldif - 2) * chance - m_modHitChance);
2656 // Hit chance for victim based on ratings
2657 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2659 if (attType == RANGED_ATTACK)
2660 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2661 else
2662 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2665 // Modify miss chance by victim auras
2666 if(attType == RANGED_ATTACK)
2667 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2668 else
2669 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2671 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2672 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2673 misschance -= skillBonus * 0.04f;
2675 // Limit miss chance from 0 to 60%
2676 if ( misschance < 0.0f)
2677 return 0.0f;
2678 if ( misschance > 60.0f)
2679 return 60.0f;
2681 return misschance;
2684 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2686 if(GetTypeId() == TYPEID_PLAYER)
2688 // in PvP use full skill instead current skill value
2689 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2690 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2691 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2692 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2693 return value;
2695 else
2696 return GetUnitMeleeSkill(target);
2699 float Unit::GetUnitDodgeChance() const
2701 if(hasUnitState(UNIT_STAT_STUNNED))
2702 return 0.0f;
2703 if( GetTypeId() == TYPEID_PLAYER )
2704 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2705 else
2707 if(((Creature const*)this)->isTotem())
2708 return 0.0f;
2709 else
2711 float dodge = 5.0f;
2712 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2713 return dodge > 0.0f ? dodge : 0.0f;
2718 float Unit::GetUnitParryChance() const
2720 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2721 return 0.0f;
2723 float chance = 0.0f;
2725 if(GetTypeId() == TYPEID_PLAYER)
2727 Player const* player = (Player const*)this;
2728 if(player->CanParry() )
2730 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2731 if(!tmpitem)
2732 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2734 if(tmpitem)
2735 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2738 else if(GetTypeId() == TYPEID_UNIT)
2740 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2742 chance = 5.0f;
2743 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2747 return chance > 0.0f ? chance : 0.0f;
2750 float Unit::GetUnitBlockChance() const
2752 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2753 return 0.0f;
2755 if(GetTypeId() == TYPEID_PLAYER)
2757 Player const* player = (Player const*)this;
2758 if(player->CanBlock() )
2760 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2761 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2762 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2764 // is player but has no block ability or no not broken shield equipped
2765 return 0.0f;
2767 else
2769 if(((Creature const*)this)->isTotem())
2770 return 0.0f;
2771 else
2773 float block = 5.0f;
2774 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2775 return block > 0.0f ? block : 0.0f;
2780 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2782 float crit;
2784 if(GetTypeId() == TYPEID_PLAYER)
2786 switch(attackType)
2788 case BASE_ATTACK:
2789 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2790 break;
2791 case OFF_ATTACK:
2792 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2793 break;
2794 case RANGED_ATTACK:
2795 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2796 break;
2797 // Just for good manner
2798 default:
2799 crit = 0.0f;
2800 break;
2803 else
2805 crit = 5.0f;
2806 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2809 // flat aura mods
2810 if(attackType == RANGED_ATTACK)
2811 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2812 else
2813 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2815 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2817 // reduce crit chance from Rating for players
2818 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2820 if (attackType==RANGED_ATTACK)
2821 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2822 else
2823 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2826 // Apply crit chance from defence skill
2827 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2829 if (crit < 0.0f)
2830 crit = 0.0f;
2831 return crit;
2834 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2836 uint32 value = 0;
2837 if(GetTypeId() == TYPEID_PLAYER)
2839 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2841 // feral or unarmed skill only for base attack
2842 if(attType != BASE_ATTACK && !item )
2843 return 0;
2845 if(IsInFeralForm())
2846 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2848 // weapon skill or (unarmed for base attack)
2849 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2851 // in PvP use full skill instead current skill value
2852 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2853 ? ((Player*)this)->GetMaxSkillValue(skill)
2854 : ((Player*)this)->GetSkillValue(skill);
2855 // Modify value from ratings
2856 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2857 switch (attType)
2859 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2860 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2861 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2864 else
2865 value = GetUnitMeleeSkill(target);
2866 return value;
2869 void Unit::_UpdateSpells( uint32 time )
2871 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2872 _UpdateAutoRepeatSpell();
2874 // remove finished spells from current pointers
2875 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2877 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2879 m_currentSpells[i]->SetReferencedFromCurrent(false);
2880 m_currentSpells[i] = NULL; // remove pointer
2884 // TODO: Find a better way to prevent crash when multiple auras are removed.
2885 m_removedAuras = 0;
2886 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2887 if ((*i).second)
2888 (*i).second->SetUpdated(false);
2890 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2892 next = i;
2893 ++next;
2894 if ((*i).second)
2896 // prevent double update
2897 if ((*i).second->IsUpdated())
2898 continue;
2899 (*i).second->SetUpdated(true);
2900 (*i).second->Update( time );
2901 // several auras can be deleted due to update
2902 if (m_removedAuras)
2904 if (m_Auras.empty()) break;
2905 next = m_Auras.begin();
2906 m_removedAuras = 0;
2911 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2913 if ((*i).second)
2915 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2917 RemoveAura(i);
2919 else
2921 ++i;
2924 else
2926 ++i;
2930 if(!m_gameObj.empty())
2932 std::list<GameObject*>::iterator ite1, dnext1;
2933 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2935 dnext1 = ite1;
2936 //(*i)->Update( difftime );
2937 if( !(*ite1)->isSpawned() )
2939 (*ite1)->SetOwnerGUID(0);
2940 (*ite1)->SetRespawnTime(0);
2941 (*ite1)->Delete();
2942 dnext1 = m_gameObj.erase(ite1);
2944 else
2945 ++dnext1;
2950 void Unit::_UpdateAutoRepeatSpell()
2952 //check "realtime" interrupts
2953 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2955 // cancel wand shoot
2956 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2957 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2958 m_AutoRepeatFirstCast = true;
2959 return;
2962 //apply delay
2963 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2964 setAttackTimer(RANGED_ATTACK,500);
2965 m_AutoRepeatFirstCast = false;
2967 //castroutine
2968 if (isAttackReady(RANGED_ATTACK))
2970 // Check if able to cast
2971 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
2973 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2974 return;
2977 // we want to shoot
2978 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2979 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2981 // all went good, reset attack
2982 resetAttackTimer(RANGED_ATTACK);
2986 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2988 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2990 uint32 CSpellType = pSpell->GetCurrentContainer();
2992 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2994 // break same type spell if it is not delayed
2995 InterruptSpell(CSpellType,false);
2997 // special breakage effects:
2998 switch (CSpellType)
3000 case CURRENT_GENERIC_SPELL:
3002 // generic spells always break channeled not delayed spells
3003 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3005 // autorepeat breaking
3006 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3008 // break autorepeat if not Auto Shot
3009 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3010 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3011 m_AutoRepeatFirstCast = true;
3013 } break;
3015 case CURRENT_CHANNELED_SPELL:
3017 // channel spells always break generic non-delayed and any channeled spells
3018 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3019 InterruptSpell(CURRENT_CHANNELED_SPELL);
3021 // it also does break autorepeat if not Auto Shot
3022 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3023 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3024 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3025 } break;
3027 case CURRENT_AUTOREPEAT_SPELL:
3029 // only Auto Shoot does not break anything
3030 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3032 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3033 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3034 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3036 // special action: set first cast flag
3037 m_AutoRepeatFirstCast = true;
3038 } break;
3040 default:
3042 // other spell types don't break anything now
3043 } break;
3046 // current spell (if it is still here) may be safely deleted now
3047 if (m_currentSpells[CSpellType])
3048 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3050 // set new current spell
3051 m_currentSpells[CSpellType] = pSpell;
3052 pSpell->SetReferencedFromCurrent(true);
3055 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3057 assert(spellType < CURRENT_MAX_SPELL);
3059 if(m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3061 // send autorepeat cancel message for autorepeat spells
3062 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3064 if(GetTypeId()==TYPEID_PLAYER)
3065 ((Player*)this)->SendAutoRepeatCancel();
3068 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3069 m_currentSpells[spellType]->cancel();
3070 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3071 m_currentSpells[spellType] = NULL;
3075 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3077 // We don't do loop here to explicitly show that melee spell is excluded.
3078 // Maybe later some special spells will be excluded too.
3080 // generic spells are casted when they are not finished and not delayed
3081 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3082 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3083 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3084 return(true);
3086 // channeled spells may be delayed, but they are still considered casted
3087 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3088 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3089 return(true);
3091 // autorepeat spells may be finished or delayed, but they are still considered casted
3092 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3093 return(true);
3095 return(false);
3098 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3100 // generic spells are interrupted if they are not finished or delayed
3101 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3103 if ( (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3104 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3105 m_currentSpells[CURRENT_GENERIC_SPELL]->cancel();
3106 m_currentSpells[CURRENT_GENERIC_SPELL]->SetReferencedFromCurrent(false);
3107 m_currentSpells[CURRENT_GENERIC_SPELL] = NULL;
3110 // autorepeat spells are interrupted if they are not finished or delayed
3111 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3113 // send disable autorepeat packet in any case
3114 if(GetTypeId()==TYPEID_PLAYER)
3115 ((Player*)this)->SendAutoRepeatCancel();
3117 if ( (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3118 (withDelayed || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->getState() != SPELL_STATE_DELAYED) )
3119 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->cancel();
3120 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->SetReferencedFromCurrent(false);
3121 m_currentSpells[CURRENT_AUTOREPEAT_SPELL] = NULL;
3124 // channeled spells are interrupted if they are not finished, even if they are delayed
3125 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3127 if (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)
3128 m_currentSpells[CURRENT_CHANNELED_SPELL]->cancel();
3129 m_currentSpells[CURRENT_CHANNELED_SPELL]->SetReferencedFromCurrent(false);
3130 m_currentSpells[CURRENT_CHANNELED_SPELL] = NULL;
3134 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3136 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
3137 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3138 return m_currentSpells[i];
3139 return NULL;
3142 bool Unit::isInFront(Unit const* target, float distance, float arc) const
3144 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3147 void Unit::SetInFront(Unit const* target)
3149 SetOrientation(GetAngle(target));
3152 bool Unit::isInBack(Unit const* target, float distance, float arc) const
3154 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3157 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3159 if(IsInWater())
3160 return c->canSwim();
3161 else
3162 return c->canWalk() || c->canFly();
3165 bool Unit::IsInWater() const
3167 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3170 bool Unit::IsUnderWater() const
3172 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3175 void Unit::DeMorph()
3177 SetDisplayId(GetNativeDisplayId());
3180 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3182 int32 modifier = 0;
3184 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3185 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3186 modifier += (*i)->GetModifier()->m_amount;
3188 return modifier;
3191 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3193 float multiplier = 1.0f;
3195 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3196 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3197 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3199 return multiplier;
3202 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3204 int32 modifier = 0;
3206 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3207 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3208 if ((*i)->GetModifier()->m_amount > modifier)
3209 modifier = (*i)->GetModifier()->m_amount;
3211 return modifier;
3214 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3216 int32 modifier = 0;
3218 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3219 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3220 if ((*i)->GetModifier()->m_amount < modifier)
3221 modifier = (*i)->GetModifier()->m_amount;
3223 return modifier;
3226 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3228 int32 modifier = 0;
3230 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3231 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3233 Modifier* mod = (*i)->GetModifier();
3234 if (mod->m_miscvalue & misc_mask)
3235 modifier += mod->m_amount;
3237 return modifier;
3240 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3242 float multiplier = 1.0f;
3244 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3245 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3247 Modifier* mod = (*i)->GetModifier();
3248 if (mod->m_miscvalue & misc_mask)
3249 multiplier *= (100.0f + mod->m_amount)/100.0f;
3251 return multiplier;
3254 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3256 int32 modifier = 0;
3258 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3259 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3261 Modifier* mod = (*i)->GetModifier();
3262 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3263 modifier = mod->m_amount;
3266 return modifier;
3269 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3271 int32 modifier = 0;
3273 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3274 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3276 Modifier* mod = (*i)->GetModifier();
3277 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3278 modifier = mod->m_amount;
3281 return modifier;
3284 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3286 int32 modifier = 0;
3288 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3289 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3291 Modifier* mod = (*i)->GetModifier();
3292 if (mod->m_miscvalue == misc_value)
3293 modifier += mod->m_amount;
3295 return modifier;
3298 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3300 float multiplier = 1.0f;
3302 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3303 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3305 Modifier* mod = (*i)->GetModifier();
3306 if (mod->m_miscvalue == misc_value)
3307 multiplier *= (100.0f + mod->m_amount)/100.0f;
3309 return multiplier;
3312 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3314 int32 modifier = 0;
3316 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3317 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3319 Modifier* mod = (*i)->GetModifier();
3320 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3321 modifier = mod->m_amount;
3324 return modifier;
3327 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3329 int32 modifier = 0;
3331 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3332 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3334 Modifier* mod = (*i)->GetModifier();
3335 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3336 modifier = mod->m_amount;
3339 return modifier;
3342 bool Unit::AddAura(Aura *Aur)
3344 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3345 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3346 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3348 delete Aur;
3349 return false;
3352 if(Aur->GetTarget() != this)
3354 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3355 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3356 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3357 delete Aur;
3358 return false;
3361 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3363 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3364 AuraMap::iterator i = m_Auras.find( spair );
3366 // take out same spell
3367 if (i != m_Auras.end())
3369 // passive and persistent auras can stack with themselves any number of times
3370 if (!Aur->IsPassive() && !Aur->IsPersistent())
3372 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3374 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3376 // Aura can stack on self -> Stack it;
3377 if(aurSpellInfo->StackAmount)
3379 i2->second->modStackAmount(1);
3380 delete Aur;
3381 return false;
3383 // can be only single (this check done at _each_ aura add
3384 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3385 break;
3388 bool stop = false;
3389 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3391 // DoT/HoT/etc
3392 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3393 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3394 case SPELL_AURA_PERIODIC_LEECH:
3395 case SPELL_AURA_PERIODIC_HEAL:
3396 case SPELL_AURA_OBS_MOD_HEALTH:
3397 case SPELL_AURA_PERIODIC_MANA_LEECH:
3398 case SPELL_AURA_PERIODIC_ENERGIZE:
3399 case SPELL_AURA_OBS_MOD_MANA:
3400 case SPELL_AURA_POWER_BURN_MANA:
3401 break;
3402 default: // not allow
3403 // can be only single (this check done at _each_ aura add
3404 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3405 stop = true;
3406 break;
3409 if(stop)
3410 break;
3415 // passive auras not stacable with other ranks
3416 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3418 if (!RemoveNoStackAurasDueToAura(Aur))
3420 delete Aur;
3421 return false; // couldn't remove conflicting aura with higher rank
3425 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3426 if (Aur->IsSingleTarget() && Aur->GetTarget())
3428 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3429 for(;;)
3431 Unit* caster = Aur->GetCaster();
3432 if(!caster) // caster deleted and not required adding scAura
3433 break;
3435 bool restart = false;
3436 AuraList& scAuras = caster->GetSingleCastAuras();
3437 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3439 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3440 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3442 if ((*itr)->IsInUse())
3444 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());
3445 continue;
3447 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3448 restart = true;
3449 break;
3453 if(!restart)
3455 // done
3456 scAuras.push_back(Aur);
3457 break;
3462 // add aura, register in lists and arrays
3463 Aur->_AddAura();
3464 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3465 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3467 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3470 Aur->ApplyModifier(true,true);
3471 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3472 return true;
3475 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3477 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3478 if(!spellInfo)
3479 return;
3480 AuraMap::iterator i,next;
3481 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3483 next = i;
3484 ++next;
3485 uint32 i_spellId = (*i).second->GetId();
3486 if((*i).second && i_spellId && i_spellId != spellId)
3488 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3490 RemoveAurasDueToSpell(i_spellId);
3492 if( m_Auras.empty() )
3493 break;
3494 else
3495 next = m_Auras.begin();
3501 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3503 if (!Aur)
3504 return false;
3506 SpellEntry const* spellProto = Aur->GetSpellProto();
3507 if (!spellProto)
3508 return false;
3510 uint32 spellId = Aur->GetId();
3511 uint32 effIndex = Aur->GetEffIndex();
3513 // passive spell special case (only non stackable with ranks)
3514 if(IsPassiveSpell(spellId))
3516 if(IsPassiveSpellStackableWithRanks(spellProto))
3517 return true;
3520 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3522 AuraMap::iterator i,next;
3523 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3525 next = i;
3526 ++next;
3527 if (!(*i).second) continue;
3529 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3531 if (!i_spellProto)
3532 continue;
3534 uint32 i_spellId = i_spellProto->Id;
3536 // early checks that spellId is passive non stackable spell
3537 if(IsPassiveSpell(i_spellId))
3539 // passive non-stackable spells not stackable only for same caster
3540 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3541 continue;
3543 // passive non-stackable spells not stackable only with another rank of same spell
3544 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3545 continue;
3548 uint32 i_effIndex = (*i).second->GetEffIndex();
3550 if(i_spellId == spellId) continue;
3552 bool is_triggered_by_spell = false;
3553 // prevent triggered aura of removing aura that triggered it
3554 for(int j = 0; j < 3; ++j)
3555 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3556 is_triggered_by_spell = true;
3558 if (is_triggered_by_spell)
3559 continue;
3561 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3563 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3564 bool is_sspt = IsSingleFromSpellSpecificRanksPerTarget(spellId_spec,i_spellId_spec);
3566 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3568 // cannot remove higher rank
3569 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3570 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3571 return false;
3573 // Its a parent aura (create this aura in ApplyModifier)
3574 if ((*i).second->IsInUse())
3576 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());
3577 continue;
3579 RemoveAurasDueToSpell(i_spellId);
3581 if( m_Auras.empty() )
3582 break;
3583 else
3584 next = m_Auras.begin();
3586 else if( is_sspt && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId) )
3588 // cannot remove higher rank
3589 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3590 return false;
3592 // Its a parent aura (create this aura in ApplyModifier)
3593 if ((*i).second->IsInUse())
3595 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());
3596 continue;
3598 RemoveAurasDueToSpell(i_spellId);
3600 if( m_Auras.empty() )
3601 break;
3602 else
3603 next = m_Auras.begin();
3605 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3607 // Its a parent aura (create this aura in ApplyModifier)
3608 if ((*i).second->IsInUse())
3610 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());
3611 continue;
3613 RemoveAurasDueToSpell(i_spellId);
3615 if( m_Auras.empty() )
3616 break;
3617 else
3618 next = m_Auras.begin();
3620 // Potions stack aura by aura (elixirs/flask already checked)
3621 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3623 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3625 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3626 return false; // cannot remove higher rank
3628 // Its a parent aura (create this aura in ApplyModifier)
3629 if ((*i).second->IsInUse())
3631 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());
3632 continue;
3634 RemoveAura(i);
3635 next = i;
3639 return true;
3642 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3644 spellEffectPair spair = spellEffectPair(spellId, effindex);
3645 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3647 if(iter->second!=except)
3649 RemoveAura(iter);
3650 iter = m_Auras.lower_bound(spair);
3652 else
3653 ++iter;
3657 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3659 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3661 Aura *aur = iter->second;
3662 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3663 RemoveAura(iter);
3664 else
3665 ++iter;
3669 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3671 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3673 Aura *aur = iter->second;
3674 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3676 // Custom dispel case
3677 // Unstable Affliction
3678 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3680 int32 damage = aur->GetModifier()->m_amount*9;
3681 uint64 caster_guid = aur->GetCasterGUID();
3683 // Remove aura
3684 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3686 // backfire damage and silence
3687 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3689 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3691 else
3692 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3694 else
3695 ++iter;
3699 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3701 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3703 Aura *aur = iter->second;
3704 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3706 int32 basePoints = aur->GetBasePoints();
3707 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3708 // some different constructors
3709 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3711 // set its duration and maximum duration
3712 // max duration 2 minutes (in msecs)
3713 int32 dur = aur->GetAuraDuration();
3714 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3715 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3716 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3718 // Unregister _before_ adding to stealer
3719 aur->UnregisterSingleCastAura();
3721 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3722 new_aur->SetIsSingleTarget(false);
3724 // add the new aura to stealer
3725 stealer->AddAura(new_aur);
3727 // Remove aura as dispel
3728 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3730 else
3731 ++iter;
3735 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3737 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3739 if (iter->second->GetId() == spellId)
3740 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3741 else
3742 ++iter;
3746 void Unit::RemoveAurasWithDispelType( DispelType type )
3748 // Create dispel mask by dispel type
3749 uint32 dispelMask = GetDispellMask(type);
3750 // Dispel all existing auras vs current dispel type
3751 AuraMap& auras = GetAuras();
3752 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3754 SpellEntry const* spell = itr->second->GetSpellProto();
3755 if( (1<<spell->Dispel) & dispelMask )
3757 // Dispel aura
3758 RemoveAurasDueToSpell(spell->Id);
3759 itr = auras.begin();
3761 else
3762 ++itr;
3766 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3768 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3769 if(iter != m_Auras.end())
3771 if (iter->second->modStackAmount(-1))
3772 RemoveAura(iter);
3776 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3778 for (int i=0; i<3; ++i)
3779 RemoveSingleAuraFromStack(spellId, i);
3782 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3784 for (int i = 0; i < 3; ++i)
3785 RemoveAura(spellId,i,except);
3788 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3790 for (int k=0; k < 3; ++k)
3792 spellEffectPair spair = spellEffectPair(spellId, k);
3793 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3795 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3797 RemoveAura(iter);
3798 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3800 else
3801 ++iter;
3806 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3808 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3810 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3811 RemoveAura(iter);
3812 else
3813 ++iter;
3817 void Unit::RemoveNotOwnSingleTargetAuras()
3819 // single target auras from other casters
3820 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3822 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3823 RemoveAura(iter);
3824 else
3825 ++iter;
3828 // single target auras at other targets
3829 AuraList& scAuras = GetSingleCastAuras();
3830 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3832 Aura* aura = *iter;
3833 if (aura->GetTarget()!=this)
3835 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3836 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3837 iter = scAuras.begin();
3839 else
3840 ++iter;
3845 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3847 Aura* Aur = i->second;
3848 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3850 Aur->UnregisterSingleCastAura();
3852 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3853 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3855 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3858 // Set remove mode
3859 Aur->SetRemoveMode(mode);
3860 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3861 // remove aura from list before to prevent deleting it before
3862 m_Auras.erase(i);
3863 ++m_removedAuras; // internal count used by unit update
3865 // Statue unsummoned at aura remove
3866 Totem* statue = NULL;
3867 bool caster_channeled = false;
3868 if(IsChanneledSpell(AurSpellInfo))
3870 Unit* caster = Aur->GetCaster();
3872 if(caster)
3874 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3875 statue = ((Totem*)caster);
3876 else
3877 caster_channeled = caster==this;
3881 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3882 Aur->ApplyModifier(false,true);
3883 Aur->_RemoveAura();
3884 delete Aur;
3886 if(caster_channeled)
3887 RemoveAurasAtChanneledTarget (AurSpellInfo);
3889 if(statue)
3890 statue->UnSummon();
3892 // only way correctly remove all auras from list
3893 if( m_Auras.empty() )
3894 i = m_Auras.end();
3895 else
3896 i = m_Auras.begin();
3899 void Unit::RemoveAllAuras()
3901 while (!m_Auras.empty())
3903 AuraMap::iterator iter = m_Auras.begin();
3904 RemoveAura(iter);
3908 void Unit::RemoveArenaAuras(bool onleave)
3910 // in join, remove positive buffs, on end, remove negative
3911 // used to remove positive visible auras in arenas
3912 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3914 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3915 && !iter->second->IsPassive() // don't remove passive auras
3916 && (!(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)
3917 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3918 RemoveAura(iter);
3919 else
3920 ++iter;
3924 void Unit::RemoveAllAurasOnDeath()
3926 // used just after dieing to remove all visible auras
3927 // and disable the mods for the passive ones
3928 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3930 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3931 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3932 else
3933 ++iter;
3937 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3939 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3940 if (iter != m_Auras.end())
3942 if (iter->second->GetAuraDuration() < delaytime)
3943 iter->second->SetAuraDuration(0);
3944 else
3945 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3946 iter->second->SendAuraUpdate(false);
3947 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3951 void Unit::_RemoveAllAuraMods()
3953 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3955 (*i).second->ApplyModifier(false);
3959 void Unit::_ApplyAllAuraMods()
3961 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3963 (*i).second->ApplyModifier(true);
3967 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3969 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3970 if (iter != m_Auras.end())
3971 return iter->second;
3972 return NULL;
3975 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
3977 AuraList const& auras = GetAurasByType(type);
3978 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
3980 SpellEntry const *spell = (*i)->GetSpellProto();
3981 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
3983 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
3984 continue;
3985 return (*i);
3988 return NULL;
3991 bool Unit::HasAura(uint32 spellId) const
3993 for (int i = 0; i < 3 ; ++i)
3995 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3996 if (iter != m_Auras.end())
3997 return true;
3999 return false;
4002 void Unit::AddDynObject(DynamicObject* dynObj)
4004 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4007 void Unit::RemoveDynObject(uint32 spellid)
4009 if(m_dynObjGUIDs.empty())
4010 return;
4011 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4013 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*i);
4014 if(!dynObj)
4016 i = m_dynObjGUIDs.erase(i);
4018 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4020 dynObj->Delete();
4021 i = m_dynObjGUIDs.erase(i);
4023 else
4024 ++i;
4028 void Unit::RemoveAllDynObjects()
4030 while(!m_dynObjGUIDs.empty())
4032 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*m_dynObjGUIDs.begin());
4033 if(dynObj)
4034 dynObj->Delete();
4035 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4039 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4041 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4043 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*i);
4044 if(!dynObj)
4046 i = m_dynObjGUIDs.erase(i);
4047 continue;
4050 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4051 return dynObj;
4052 ++i;
4054 return NULL;
4057 DynamicObject * Unit::GetDynObject(uint32 spellId)
4059 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4061 DynamicObject* dynObj = ObjectAccessor::GetDynamicObject(*this,*i);
4062 if(!dynObj)
4064 i = m_dynObjGUIDs.erase(i);
4065 continue;
4068 if (dynObj->GetSpellId() == spellId)
4069 return dynObj;
4070 ++i;
4072 return NULL;
4075 void Unit::AddGameObject(GameObject* gameObj)
4077 assert(gameObj && gameObj->GetOwnerGUID()==0);
4078 m_gameObj.push_back(gameObj);
4079 gameObj->SetOwnerGUID(GetGUID());
4081 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4083 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4084 // Need disable spell use for owner
4085 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4086 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4087 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4091 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4093 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4095 gameObj->SetOwnerGUID(0);
4097 // GO created by some spell
4098 if (uint32 spellid = gameObj->GetSpellId())
4100 RemoveAurasDueToSpell(spellid);
4102 if (GetTypeId()==TYPEID_PLAYER)
4104 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4105 // Need activate spell use for owner
4106 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4107 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4108 ((Player*)this)->SendCooldownEvent(createBySpell);
4112 m_gameObj.remove(gameObj);
4114 if(del)
4116 gameObj->SetRespawnTime(0);
4117 gameObj->Delete();
4121 void Unit::RemoveGameObject(uint32 spellid, bool del)
4123 if(m_gameObj.empty())
4124 return;
4125 std::list<GameObject*>::iterator i, next;
4126 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4128 next = i;
4129 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4131 (*i)->SetOwnerGUID(0);
4132 if(del)
4134 (*i)->SetRespawnTime(0);
4135 (*i)->Delete();
4138 next = m_gameObj.erase(i);
4140 else
4141 ++next;
4145 void Unit::RemoveAllGameObjects()
4147 // remove references to unit
4148 for(std::list<GameObject*>::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4150 (*i)->SetOwnerGUID(0);
4151 (*i)->SetRespawnTime(0);
4152 (*i)->Delete();
4153 i = m_gameObj.erase(i);
4157 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4159 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4160 data.append(log->target->GetPackGUID());
4161 data.append(log->attacker->GetPackGUID());
4162 data << uint32(log->SpellID);
4163 data << uint32(log->damage); //damage amount
4164 data << uint32(0);
4165 data << uint8 (log->schoolMask); //damage school
4166 data << uint32(log->absorb); //AbsorbedDamage
4167 data << uint32(log->resist); //resist
4168 data << uint8 (log->phusicalLog); // damsge type? flag
4169 data << uint8 (log->unused); //unused
4170 data << uint32(log->blocked); //blocked
4171 data << uint32(log->HitInfo);
4172 data << uint8 (0); // flag to use extend data
4173 SendMessageToSet( &data, true );
4176 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4178 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
4179 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4180 data.append(target->GetPackGUID());
4181 data.append(GetPackGUID());
4182 data << uint32(SpellID);
4183 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
4184 data << uint32(0); // wotlk
4185 data << uint8(damageSchoolMask); // spell school
4186 data << uint32(AbsorbedDamage); // AbsorbedDamage
4187 data << uint32(Resist); // resist
4188 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
4189 data << uint8(0); // unk isFromAura
4190 data << uint32(Blocked); // blocked
4191 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
4192 data << uint8(0); // isDebug?
4193 SendMessageToSet( &data, true );
4196 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4198 // Not much to do if no flags are set.
4199 if (procAttacker)
4200 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4201 // Now go on with a victim's events'n'auras
4202 // Not much to do if no flags are set or there is no victim
4203 if(pVictim && pVictim->isAlive() && procVictim)
4204 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4207 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4209 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4210 data << uint32(spellID);
4211 data << uint64(GetGUID());
4212 data << uint8(0); // can be 0 or 1
4213 data << uint32(1); // target count
4214 // for(i = 0; i < target count; ++i)
4215 data << uint64(target->GetGUID()); // target GUID
4216 data << uint8(missInfo);
4217 // end loop
4218 SendMessageToSet(&data, true);
4221 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4223 uint32 count = 1;
4224 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4225 data << (uint32)damageInfo->HitInfo;
4226 data.append(GetPackGUID());
4227 data.append(damageInfo->target->GetPackGUID());
4228 data << (uint32)(damageInfo->damage); // Full damage
4229 data << uint32(0); // overkill value
4231 data << (uint8)count; // Sub damage count
4233 for(int i = 0; i < count; ++i)
4235 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4236 data << (float)damageInfo->damage; // sub damage
4237 data << (uint32)damageInfo->damage; // Sub Damage
4240 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4242 for(int i = 0; i < count; ++i)
4243 data << (uint32)damageInfo->absorb; // Absorb
4246 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4248 for(int i = 0; i < count; ++i)
4249 data << (uint32)damageInfo->resist; // Resist
4252 data << (uint8)damageInfo->TargetState;
4253 data << (uint32)0;
4254 data << (uint32)0;
4256 if(damageInfo->HitInfo & HITINFO_BLOCK)
4257 data << (uint32)damageInfo->blocked_amount;
4259 if(damageInfo->HitInfo & HITINFO_UNK3)
4260 data << uint32(0);
4262 if(damageInfo->HitInfo & HITINFO_UNK1)
4264 data << uint32(0);
4265 data << float(0);
4266 data << float(0);
4267 data << float(0);
4268 data << float(0);
4269 data << float(0);
4270 data << float(0);
4271 data << float(0);
4272 data << float(0);
4273 for(uint8 i = 0; i < 5; ++i)
4275 data << float(0);
4276 data << float(0);
4278 data << uint32(0);
4281 SendMessageToSet( &data, true );
4284 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4286 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4288 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4289 data << uint32(HitInfo); // flags
4290 data.append(GetPackGUID());
4291 data.append(target->GetPackGUID());
4292 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4293 data << uint32(0); // overkill value
4295 data << (uint8)SwingType; // count?
4297 // for(i = 0; i < SwingType; ++i)
4298 data << (uint32)damageSchoolMask;
4299 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4300 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4301 // end loop
4303 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4305 // for(i = 0; i < SwingType; ++i)
4306 data << uint32(AbsorbDamage);
4307 // end loop
4310 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4312 // for(i = 0; i < SwingType; ++i)
4313 data << uint32(Resist);
4314 // end loop
4317 data << (uint8)TargetState;
4318 data << (uint32)0;
4319 data << (uint32)0;
4321 if(HitInfo & HITINFO_BLOCK)
4323 data << uint32(BlockedAmount);
4326 if(HitInfo & HITINFO_UNK3)
4328 data << uint32(0);
4331 if(HitInfo & HITINFO_UNK1)
4333 data << uint32(0);
4334 data << float(0);
4335 data << float(0);
4336 data << float(0);
4337 data << float(0);
4338 data << float(0);
4339 data << float(0);
4340 data << float(0);
4341 data << float(0);
4342 for(uint8 i = 0; i < 5; ++i)
4344 data << float(0);
4345 data << float(0);
4347 data << uint32(0);
4350 SendMessageToSet( &data, true );
4353 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4355 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4357 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4358 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4360 uint32 triggered_spell_id = 0;
4361 Unit* target = pVictim;
4362 int32 basepoints0 = 0;
4364 switch(hasteSpell->SpellFamilyName)
4366 case SPELLFAMILY_ROGUE:
4368 switch(hasteSpell->Id)
4370 // Blade Flurry
4371 case 13877:
4372 case 33735:
4374 target = SelectNearbyTarget();
4375 if(!target)
4376 return false;
4377 basepoints0 = damage;
4378 triggered_spell_id = 22482;
4379 break;
4382 break;
4386 // processed charge only counting case
4387 if(!triggered_spell_id)
4388 return true;
4390 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4392 if(!triggerEntry)
4394 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4395 return false;
4398 // default case
4399 if(!target || target!=this && !target->isAlive())
4400 return false;
4402 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4403 return false;
4405 if(basepoints0)
4406 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4407 else
4408 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4410 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4411 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4413 return true;
4416 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4418 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4419 uint32 effIndex = triggeredByAura->GetEffIndex();
4420 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4422 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4423 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4425 uint32 triggered_spell_id = 0;
4426 Unit* target = pVictim;
4427 int32 basepoints0 = 0;
4429 switch(dummySpell->SpellFamilyName)
4431 case SPELLFAMILY_GENERIC:
4433 switch (dummySpell->Id)
4435 // Eye for an Eye
4436 case 9799:
4437 case 25988:
4439 // return damage % to attacker but < 50% own total health
4440 basepoints0 = triggerAmount*int32(damage)/100;
4441 if(basepoints0 > GetMaxHealth()/2)
4442 basepoints0 = GetMaxHealth()/2;
4444 triggered_spell_id = 25997;
4445 break;
4447 // Sweeping Strikes
4448 case 12328:
4449 case 18765:
4450 case 35429:
4452 // prevent chain of triggered spell from same triggered spell
4453 if(procSpell && procSpell->Id==26654)
4454 return false;
4456 target = SelectNearbyTarget();
4457 if(!target)
4458 return false;
4460 triggered_spell_id = 26654;
4461 break;
4463 // Unstable Power
4464 case 24658:
4466 if (!procSpell || procSpell->Id == 24659)
4467 return false;
4468 // Need remove one 24659 aura
4469 RemoveSingleSpellAurasFromStack(24659);
4470 return true;
4472 // Restless Strength
4473 case 24661:
4475 // Need remove one 24662 aura
4476 RemoveSingleSpellAurasFromStack(24662);
4477 return true;
4479 // Adaptive Warding (Frostfire Regalia set)
4480 case 28764:
4482 if(!procSpell)
4483 return false;
4485 // find Mage Armor
4486 bool found = false;
4487 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4488 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4490 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4492 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4494 found=true;
4495 break;
4499 if(!found)
4500 return false;
4502 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4504 case SPELL_SCHOOL_NORMAL:
4505 case SPELL_SCHOOL_HOLY:
4506 return false; // ignored
4507 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4508 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4509 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4510 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4511 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4512 default:
4513 return false;
4516 target = this;
4517 break;
4519 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4520 case 27539:
4522 if(!procSpell)
4523 return false;
4525 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4527 case SPELL_SCHOOL_NORMAL:
4528 return false; // ignore
4529 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4530 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4531 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4532 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4533 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4534 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4535 default:
4536 return false;
4539 target = this;
4540 break;
4542 // Mana Leech (Passive) (Priest Pet Aura)
4543 case 28305:
4545 // Cast on owner
4546 target = GetOwner();
4547 if(!target)
4548 return false;
4550 triggered_spell_id = 34650;
4551 break;
4553 // Mark of Malice
4554 case 33493:
4556 // Cast finish spell at last charge
4557 if (triggeredByAura->GetAuraCharges() > 1)
4558 return false;
4560 target = this;
4561 triggered_spell_id = 33494;
4562 break;
4564 // Twisted Reflection (boss spell)
4565 case 21063:
4566 triggered_spell_id = 21064;
4567 break;
4568 // Vampiric Aura (boss spell)
4569 case 38196:
4571 basepoints0 = 3 * damage; // 300%
4572 if (basepoints0 < 0)
4573 return false;
4575 triggered_spell_id = 31285;
4576 target = this;
4577 break;
4579 // Aura of Madness (Darkmoon Card: Madness trinket)
4580 //=====================================================
4581 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4582 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4583 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4584 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4585 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4586 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4587 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4588 // 41011 Martyr Complex: +35 stamina (All classes)
4589 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4590 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4591 case 39446:
4593 if(GetTypeId() != TYPEID_PLAYER)
4594 return false;
4596 // Select class defined buff
4597 switch (getClass())
4599 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4600 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4602 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4603 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4604 break;
4606 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4607 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4609 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4610 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4611 break;
4613 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4614 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4615 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4616 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4618 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4619 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4620 break;
4622 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4624 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4625 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4626 break;
4628 default:
4629 return false;
4632 target = this;
4633 if (roll_chance_i(10))
4634 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4635 break;
4638 // TODO: need find item for aura and triggered spells
4639 // Sunwell Exalted Caster Neck (??? neck)
4640 // cast ??? Light's Wrath if Exalted by Aldor
4641 // cast ??? Arcane Bolt if Exalted by Scryers*/
4642 case 46569:
4643 return false; // disable for while
4646 if(GetTypeId() != TYPEID_PLAYER)
4647 return false;
4649 // Get Aldor reputation rank
4650 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4652 target = this;
4653 triggered_spell_id = ???
4654 break;
4656 // Get Scryers reputation rank
4657 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4659 triggered_spell_id = ???
4660 break;
4662 return false;
4663 }/**/
4664 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4665 // cast 45479 Light's Wrath if Exalted by Aldor
4666 // cast 45429 Arcane Bolt if Exalted by Scryers
4667 case 45481:
4669 if(GetTypeId() != TYPEID_PLAYER)
4670 return false;
4672 // Get Aldor reputation rank
4673 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4675 target = this;
4676 triggered_spell_id = 45479;
4677 break;
4679 // Get Scryers reputation rank
4680 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4682 triggered_spell_id = 45429;
4683 break;
4685 return false;
4687 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4688 // cast 45480 Light's Strength if Exalted by Aldor
4689 // cast 45428 Arcane Strike if Exalted by Scryers
4690 case 45482:
4692 if(GetTypeId() != TYPEID_PLAYER)
4693 return false;
4695 // Get Aldor reputation rank
4696 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4698 target = this;
4699 triggered_spell_id = 45480;
4700 break;
4702 // Get Scryers reputation rank
4703 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4705 triggered_spell_id = 45428;
4706 break;
4708 return false;
4710 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4711 // cast 45431 Arcane Insight if Exalted by Aldor
4712 // cast 45432 Light's Ward if Exalted by Scryers
4713 case 45483:
4715 if(GetTypeId() != TYPEID_PLAYER)
4716 return false;
4718 // Get Aldor reputation rank
4719 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4721 target = this;
4722 triggered_spell_id = 45432;
4723 break;
4725 // Get Scryers reputation rank
4726 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4728 target = this;
4729 triggered_spell_id = 45431;
4730 break;
4732 return false;
4734 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4735 // cast 45478 Light's Salvation if Exalted by Aldor
4736 // cast 45430 Arcane Surge if Exalted by Scryers
4737 case 45484:
4739 if(GetTypeId() != TYPEID_PLAYER)
4740 return false;
4742 // Get Aldor reputation rank
4743 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4745 target = this;
4746 triggered_spell_id = 45478;
4747 break;
4749 // Get Scryers reputation rank
4750 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4752 triggered_spell_id = 45430;
4753 break;
4755 return false;
4757 // Living Seed
4758 case 48504:
4760 triggered_spell_id = 48503;
4761 basepoints0 = triggerAmount;
4762 target = this;
4763 break;
4765 // Vampiric Touch (generic, used by some boss)
4766 case 52723:
4767 case 60501:
4769 triggered_spell_id = 52724;
4770 basepoints0 = damage / 2;
4771 target = this;
4772 break;
4774 // Divine purpose
4775 case 31871:
4776 case 31872:
4778 // Roll chane
4779 if (!roll_chance_i(triggerAmount))
4780 return false;
4782 // Remove any stun effect on target
4783 AuraMap& Auras = pVictim->GetAuras();
4784 for(AuraMap::iterator iter = Auras.begin(); iter != Auras.end();)
4786 SpellEntry const *spell = iter->second->GetSpellProto();
4787 if( spell->Mechanic == MECHANIC_STUN ||
4788 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4790 pVictim->RemoveAurasDueToSpell(spell->Id);
4791 iter = Auras.begin();
4793 else
4794 ++iter;
4796 return true;
4799 break;
4801 case SPELLFAMILY_MAGE:
4803 // Magic Absorption
4804 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4806 if (getPowerType() != POWER_MANA)
4807 return false;
4809 // mana reward
4810 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
4811 target = this;
4812 triggered_spell_id = 29442;
4813 break;
4815 // Master of Elements
4816 if (dummySpell->SpellIconID == 1920)
4818 if(!procSpell)
4819 return false;
4821 // mana cost save
4822 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4823 basepoints0 = cost * triggerAmount/100;
4824 if( basepoints0 <=0 )
4825 return false;
4827 target = this;
4828 triggered_spell_id = 29077;
4829 break;
4831 // Hot Streak
4832 if (dummySpell->SpellIconID == 2999)
4834 if (effIndex!=0)
4835 return true;
4836 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4837 if (!counter)
4838 return true;
4840 // Count spell criticals in a row in second aura
4841 Modifier *mod = counter->GetModifier();
4842 if (procEx & PROC_EX_CRITICAL_HIT)
4844 mod->m_amount *=2;
4845 if (mod->m_amount < 100) // not enough
4846 return true;
4847 // Crititcal counted -> roll chance
4848 if (roll_chance_i(triggerAmount))
4849 CastSpell(this, 48108, true, castItem, triggeredByAura);
4851 mod->m_amount = 25;
4852 return true;
4854 // Burnout
4855 if (dummySpell->SpellIconID == 2998)
4857 if(!procSpell)
4858 return false;
4860 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4861 basepoints0 = cost * triggerAmount/100;
4862 if( basepoints0 <=0 )
4863 return false;
4864 triggered_spell_id = 44450;
4865 target = this;
4866 break;
4868 // Incanter's Regalia set (add trigger chance to Mana Shield)
4869 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4871 if(GetTypeId() != TYPEID_PLAYER)
4872 return false;
4874 target = this;
4875 triggered_spell_id = 37436;
4876 break;
4878 switch(dummySpell->Id)
4880 // Ignite
4881 case 11119:
4882 case 11120:
4883 case 12846:
4884 case 12847:
4885 case 12848:
4887 switch (dummySpell->Id)
4889 case 11119: basepoints0 = int32(0.04f*damage); break;
4890 case 11120: basepoints0 = int32(0.08f*damage); break;
4891 case 12846: basepoints0 = int32(0.12f*damage); break;
4892 case 12847: basepoints0 = int32(0.16f*damage); break;
4893 case 12848: basepoints0 = int32(0.20f*damage); break;
4894 default:
4895 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4896 return false;
4899 triggered_spell_id = 12654;
4900 break;
4902 // Combustion
4903 case 11129:
4905 //last charge and crit
4906 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4908 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4909 return true; // charge counting (will removed)
4912 CastSpell(this, 28682, true, castItem, triggeredByAura);
4913 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4916 break;
4918 case SPELLFAMILY_WARRIOR:
4920 // Retaliation
4921 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4923 // check attack comes not from behind
4924 if (!HasInArc(M_PI, pVictim))
4925 return false;
4927 triggered_spell_id = 22858;
4928 break;
4930 // Second Wind
4931 if (dummySpell->SpellIconID == 1697)
4933 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4934 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4935 return false;
4936 // Need stun or root mechanic
4937 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
4938 return false;
4940 switch (dummySpell->Id)
4942 case 29838: triggered_spell_id=29842; break;
4943 case 29834: triggered_spell_id=29841; break;
4944 case 42770: triggered_spell_id=42771; break;
4945 default:
4946 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4947 return false;
4950 target = this;
4951 break;
4953 // Damage Shield
4954 if (dummySpell->SpellIconID == 3214)
4956 triggered_spell_id = 59653;
4957 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
4958 break;
4960 break;
4962 case SPELLFAMILY_WARLOCK:
4964 // Seed of Corruption
4965 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4967 Modifier* mod = triggeredByAura->GetModifier();
4968 // if damage is more than need or target die from damage deal finish spell
4969 if( mod->m_amount <= damage || GetHealth() <= damage )
4971 // remember guid before aura delete
4972 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4974 // Remove aura (before cast for prevent infinite loop handlers)
4975 RemoveAurasDueToSpell(triggeredByAura->GetId());
4977 // Cast finish spell (triggeredByAura already not exist!)
4978 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4979 return true; // no hidden cooldown
4982 // Damage counting
4983 mod->m_amount-=damage;
4984 return true;
4986 // Seed of Corruption (Mobs cast) - no die req
4987 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4989 Modifier* mod = triggeredByAura->GetModifier();
4990 // if damage is more than need deal finish spell
4991 if( mod->m_amount <= damage )
4993 // remember guid before aura delete
4994 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4996 // Remove aura (before cast for prevent infinite loop handlers)
4997 RemoveAurasDueToSpell(triggeredByAura->GetId());
4999 // Cast finish spell (triggeredByAura already not exist!)
5000 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5001 return true; // no hidden cooldown
5003 // Damage counting
5004 mod->m_amount-=damage;
5005 return true;
5007 // Fel Synergy
5008 if (dummySpell->SpellIconID == 3222)
5010 target = GetPet();
5011 if (!target)
5012 return false;
5013 triggered_spell_id = 54181;
5014 basepoints0 = damage * triggerAmount / 100;
5015 break;
5017 switch(dummySpell->Id)
5019 // Nightfall
5020 case 18094:
5021 case 18095:
5023 target = this;
5024 triggered_spell_id = 17941;
5025 break;
5027 //Soul Leech
5028 case 30293:
5029 case 30295:
5030 case 30296:
5032 // health
5033 basepoints0 = int32(damage*triggerAmount/100);
5034 target = this;
5035 triggered_spell_id = 30294;
5036 break;
5038 // Shadowflame (Voidheart Raiment set bonus)
5039 case 37377:
5041 triggered_spell_id = 37379;
5042 break;
5044 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5045 case 37381:
5047 target = GetPet();
5048 if(!target)
5049 return false;
5051 // heal amount
5052 basepoints0 = damage * triggerAmount/100;
5053 triggered_spell_id = 37382;
5054 break;
5056 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5057 case 39437:
5059 triggered_spell_id = 37378;
5060 break;
5063 break;
5065 case SPELLFAMILY_PRIEST:
5067 // Vampiric Touch
5068 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
5070 if(!pVictim || !pVictim->isAlive())
5071 return false;
5073 // pVictim is caster of aura
5074 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5075 return false;
5077 // energize amount
5078 basepoints0 = triggerAmount*damage/100;
5079 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5080 return true; // no hidden cooldown
5082 // Divine Aegis
5083 if (dummySpell->SpellIconID == 2820)
5085 basepoints0 = damage * triggerAmount/100;
5086 triggered_spell_id = 47753;
5087 break;
5089 switch(dummySpell->Id)
5091 // Vampiric Embrace
5092 case 15286:
5094 if(!pVictim || !pVictim->isAlive())
5095 return false;
5097 // pVictim is caster of aura
5098 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5099 return false;
5101 // heal amount
5102 int32 team = triggerAmount*damage/500;
5103 int32 self = triggerAmount*damage/100 - team;
5104 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5105 return true; // no hidden cooldown
5107 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5108 case 40438:
5110 // Shadow Word: Pain
5111 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5112 triggered_spell_id = 40441;
5113 // Renew
5114 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5115 triggered_spell_id = 40440;
5116 else
5117 return false;
5119 target = this;
5120 break;
5122 // Oracle Healing Bonus ("Garments of the Oracle" set)
5123 case 26169:
5125 // heal amount
5126 basepoints0 = int32(damage * 10/100);
5127 target = this;
5128 triggered_spell_id = 26170;
5129 break;
5131 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5132 case 39372:
5134 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5135 return false;
5137 // heal amount
5138 basepoints0 = damage * triggerAmount/100;
5139 target = this;
5140 triggered_spell_id = 39373;
5141 break;
5143 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5144 case 28809:
5146 triggered_spell_id = 28810;
5147 break;
5149 // Glyph of Dispel Magic
5150 case 55677:
5152 if(!target->IsFriendlyTo(this))
5153 return false;
5155 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5156 triggered_spell_id = 56131;
5157 break;
5160 break;
5162 case SPELLFAMILY_DRUID:
5164 switch(dummySpell->Id)
5166 // Healing Touch (Dreamwalker Raiment set)
5167 case 28719:
5169 // mana back
5170 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5171 target = this;
5172 triggered_spell_id = 28742;
5173 break;
5175 // Healing Touch Refund (Idol of Longevity trinket)
5176 case 28847:
5178 target = this;
5179 triggered_spell_id = 28848;
5180 break;
5182 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5183 case 37288:
5184 case 37295:
5186 target = this;
5187 triggered_spell_id = 37238;
5188 break;
5190 // Druid Tier 6 Trinket
5191 case 40442:
5193 float chance;
5195 // Starfire
5196 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5198 triggered_spell_id = 40445;
5199 chance = 25.f;
5201 // Rejuvenation
5202 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5204 triggered_spell_id = 40446;
5205 chance = 25.f;
5207 // Mangle (cat/bear)
5208 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5210 triggered_spell_id = 40452;
5211 chance = 40.f;
5213 else
5214 return false;
5216 if (!roll_chance_f(chance))
5217 return false;
5219 target = this;
5220 break;
5222 // Maim Interrupt
5223 case 44835:
5225 // Deadly Interrupt Effect
5226 triggered_spell_id = 32747;
5227 break;
5230 // Eclipse
5231 if (dummySpell->SpellIconID == 2856)
5233 if (!procSpell)
5234 return false;
5235 // Only 0 aura can proc
5236 if (effIndex!=0)
5237 return true;
5238 // Wrath crit
5239 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5241 if (!roll_chance_i(60))
5242 return false;
5243 triggered_spell_id = 48518;
5244 target = this;
5245 break;
5247 // Starfire crit
5248 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5250 triggered_spell_id = 48517;
5251 target = this;
5252 break;
5254 return false;
5256 // Living Seed
5257 else if (dummySpell->SpellIconID == 2860)
5259 triggered_spell_id = 48504;
5260 basepoints0 = triggerAmount * damage / 100;
5261 break;
5263 break;
5265 case SPELLFAMILY_ROGUE:
5267 switch(dummySpell->Id)
5269 // Deadly Throw Interrupt
5270 case 32748:
5272 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5273 if(this == pVictim)
5274 return false;
5276 triggered_spell_id = 32747;
5277 break;
5280 // Cut to the Chase
5281 if( dummySpell->SpellIconID == 2909 )
5283 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5284 // lookup Slice and Dice
5285 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5286 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5288 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5289 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5290 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5292 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5293 (*itr)->RefreshAura();
5294 return true;
5297 return false;
5299 // Deadly Brew
5300 if( dummySpell->SpellIconID == 2963 )
5302 triggered_spell_id = 25809;
5303 break;
5305 // Quick Recovery
5306 if( dummySpell->SpellIconID == 2116 )
5308 if(!procSpell)
5309 return false;
5311 // energy cost save
5312 basepoints0 = procSpell->manaCost * triggerAmount/100;
5313 if(basepoints0 <= 0)
5314 return false;
5316 target = this;
5317 triggered_spell_id = 31663;
5318 break;
5320 break;
5322 case SPELLFAMILY_HUNTER:
5324 // Thrill of the Hunt
5325 if ( dummySpell->SpellIconID == 2236 )
5327 if(!procSpell)
5328 return false;
5330 // mana cost save
5331 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5332 basepoints0 = mana * 40/100;
5333 if(basepoints0 <= 0)
5334 return false;
5336 target = this;
5337 triggered_spell_id = 34720;
5338 break;
5340 // Hunting Party
5341 if ( dummySpell->SpellIconID == 3406 )
5343 triggered_spell_id = 57669;
5344 target = this;
5345 break;
5347 // Lock and Load
5348 if ( dummySpell->SpellIconID == 3579 )
5350 // Proc only from periodic (from trap activation proc another aura of this spell)
5351 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5352 return false;
5353 triggered_spell_id = 56453;
5354 target = this;
5355 break;
5357 // Rapid Recuperation
5358 if ( dummySpell->SpellIconID == 3560 )
5360 // This effect only from Rapid Killing (mana regen)
5361 if (!(procSpell->SpellFamilyFlags & 0x0100000000000000LL))
5362 return false;
5363 triggered_spell_id = 56654;
5364 target = this;
5365 break;
5367 break;
5369 case SPELLFAMILY_PALADIN:
5371 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5372 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && effIndex==0)
5374 triggered_spell_id = 25742;
5375 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5376 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5377 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5378 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5379 break;
5381 // Sacred Shield
5382 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5384 triggered_spell_id = 58597;
5385 target = this;
5386 break;
5388 // Righteous Vengeance
5389 if (dummySpell->SpellIconID == 3025)
5391 // 4 damage tick
5392 basepoints0 = triggerAmount*damage/400;
5393 triggered_spell_id = 61840;
5394 break;
5396 // Sheath of Light
5397 if (dummySpell->SpellIconID == 3030)
5399 // 4 healing tick
5400 basepoints0 = triggerAmount*damage/400;
5401 triggered_spell_id = 54203;
5402 break;
5404 switch(dummySpell->Id)
5406 // Judgement of Light
5407 case 20185:
5409 // Get judgement caster
5410 Unit *caster = triggeredByAura->GetCaster();
5411 if (!caster)
5412 return false;
5413 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5414 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5415 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5416 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5417 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5418 return true;
5420 // Judgement of Wisdom
5421 case 20186:
5423 if (pVictim->getPowerType() == POWER_MANA)
5424 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5425 return true;
5427 // Holy Power (Redemption Armor set)
5428 case 28789:
5430 if(!pVictim)
5431 return false;
5433 // Set class defined buff
5434 switch (pVictim->getClass())
5436 case CLASS_PALADIN:
5437 case CLASS_PRIEST:
5438 case CLASS_SHAMAN:
5439 case CLASS_DRUID:
5440 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5441 break;
5442 case CLASS_MAGE:
5443 case CLASS_WARLOCK:
5444 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5445 break;
5446 case CLASS_HUNTER:
5447 case CLASS_ROGUE:
5448 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5449 break;
5450 case CLASS_WARRIOR:
5451 triggered_spell_id = 28790; // Increases the friendly target's armor
5452 break;
5453 default:
5454 return false;
5456 break;
5458 // Seal of Vengeance (damage calc on apply aura)
5459 case 31801:
5461 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5462 return false;
5464 triggered_spell_id = 31803;
5465 break;
5467 // Spiritual Attunement
5468 case 31785:
5469 case 33776:
5471 // if healed by another unit (pVictim)
5472 if(this == pVictim)
5473 return false;
5475 // heal amount
5476 basepoints0 = triggerAmount*damage/100;
5477 target = this;
5478 triggered_spell_id = 31786;
5479 break;
5481 // Seal of Blood do damage trigger
5482 case 31892:
5484 if (effIndex == 0) // 0 effect - is proc on enemy
5485 triggered_spell_id = 31893;
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 = 32221;
5494 else
5495 return true;
5496 break;
5498 // Seal of the Martyr do damage trigger
5499 case 53720:
5501 if (effIndex == 0) // 0 effect - is proc on enemy
5502 triggered_spell_id = 53719;
5503 else if (effIndex == 1) // 1 effect - is proc on self
5505 // add spell damage from prev effect (27%)
5506 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5507 basepoints0 = triggerAmount * damage / 100;
5508 target = this;
5509 triggered_spell_id = 53718;
5511 else
5512 return true;
5513 break;
5515 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5516 case 40470:
5518 if( !procSpell )
5519 return false;
5521 float chance;
5523 // Flash of light/Holy light
5524 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5526 triggered_spell_id = 40471;
5527 chance = 15.f;
5529 // Judgement
5530 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5532 triggered_spell_id = 40472;
5533 chance = 50.f;
5535 else
5536 return false;
5538 if (!roll_chance_f(chance))
5539 return false;
5541 break;
5543 // Glyph of Divinity
5544 case 54939:
5546 // Lookup base amount mana restore
5547 for (int i=0; i<3;i++)
5548 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5550 int32 mana = procSpell->EffectBasePoints[i];
5551 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5552 break;
5554 return true;
5556 // Glyph of Flash of Light
5557 case 54936:
5559 triggered_spell_id = 54957;
5560 basepoints0 = triggerAmount*damage/100;
5561 break;
5563 // Glyph of Holy Light
5564 case 54937:
5566 triggered_spell_id = 54968;
5567 basepoints0 = triggerAmount*damage/100;
5568 break;
5571 break;
5573 case SPELLFAMILY_SHAMAN:
5575 switch(dummySpell->Id)
5577 // Totemic Power (The Earthshatterer set)
5578 case 28823:
5580 if( !pVictim )
5581 return false;
5583 // Set class defined buff
5584 switch (pVictim->getClass())
5586 case CLASS_PALADIN:
5587 case CLASS_PRIEST:
5588 case CLASS_SHAMAN:
5589 case CLASS_DRUID:
5590 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5591 break;
5592 case CLASS_MAGE:
5593 case CLASS_WARLOCK:
5594 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5595 break;
5596 case CLASS_HUNTER:
5597 case CLASS_ROGUE:
5598 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5599 break;
5600 case CLASS_WARRIOR:
5601 triggered_spell_id = 28827; // Increases the friendly target's armor
5602 break;
5603 default:
5604 return false;
5606 break;
5608 // Lesser Healing Wave (Totem of Flowing Water Relic)
5609 case 28849:
5611 target = this;
5612 triggered_spell_id = 28850;
5613 break;
5615 // Windfury Weapon (Passive) 1-5 Ranks
5616 case 33757:
5618 if(GetTypeId()!=TYPEID_PLAYER)
5619 return false;
5621 if(!castItem || !castItem->IsEquipped())
5622 return false;
5624 // custom cooldown processing case
5625 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5626 return false;
5628 // Now amount of extra power stored in 1 effect of Enchant spell
5629 // Get it by item enchant id
5630 uint32 spellId;
5631 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5633 case 283: spellId = 8232; break; // 1 Rank
5634 case 284: spellId = 8235; break; // 2 Rank
5635 case 525: spellId = 10486; break; // 3 Rank
5636 case 1669:spellId = 16362; break; // 4 Rank
5637 case 2636:spellId = 25505; break; // 5 Rank
5638 case 3785:spellId = 58801; break; // 6 Rank
5639 case 3786:spellId = 58803; break; // 7 Rank
5640 case 3787:spellId = 58804; break; // 8 Rank
5641 default:
5643 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5644 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5645 return false;
5649 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5650 if(!windfurySpellEntry)
5652 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5653 return false;
5656 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5658 // Off-Hand case
5659 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5661 // Value gained from additional AP
5662 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5663 triggered_spell_id = 33750;
5665 // Main-Hand case
5666 else
5668 // Value gained from additional AP
5669 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5670 triggered_spell_id = 25504;
5673 // apply cooldown before cast to prevent processing itself
5674 if( cooldown )
5675 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5677 // Attack Twice
5678 for ( uint32 i = 0; i<2; ++i )
5679 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5681 return true;
5683 // Shaman Tier 6 Trinket
5684 case 40463:
5686 if( !procSpell )
5687 return false;
5689 float chance;
5690 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5692 triggered_spell_id = 40465; // Lightning Bolt
5693 chance = 15.f;
5695 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5697 triggered_spell_id = 40465; // Lesser Healing Wave
5698 chance = 10.f;
5700 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5702 triggered_spell_id = 40466; // Stormstrike
5703 chance = 50.f;
5705 else
5706 return false;
5708 if (!roll_chance_f(chance))
5709 return false;
5711 target = this;
5712 break;
5714 // Glyph of Healing Wave
5715 case 55440:
5717 // Not proc from self heals
5718 if (this==pVictim)
5719 return false;
5720 basepoints0 = triggerAmount * damage / 100;
5721 target = this;
5722 triggered_spell_id = 55533;
5723 break;
5725 // Spirit Hunt
5726 case 58877:
5728 // Cast on owner
5729 target = GetOwner();
5730 if(!target)
5731 return false;
5732 basepoints0 = triggerAmount * damage / 100;
5733 triggered_spell_id = 58879;
5734 break;
5737 // Ancestral Awakening
5738 if (dummySpell->SpellIconID == 3065)
5740 // TODO: frite dummy fot triggered spell
5741 triggered_spell_id = 52759;
5742 basepoints0 = triggerAmount * damage / 100;
5743 target = this;
5744 break;
5746 // Earth Shield
5747 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5749 basepoints0 = triggerAmount;
5750 target = this;
5751 triggered_spell_id = 379;
5752 break;
5754 // Improved Water Shield
5755 if (dummySpell->SpellIconID == 2287)
5757 // Lesser Healing Wave need aditional 60% roll
5758 if (procSpell->SpellFamilyFlags & 0x0000000000000080LL && !roll_chance_i(60))
5759 return false;
5760 // lookup water shield
5761 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5762 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5764 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5765 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5767 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5768 CastSpell(this, spell, true, castItem, triggeredByAura);
5769 if ((*itr)->DropAuraCharge())
5770 RemoveAurasDueToSpell((*itr)->GetId());
5771 return true;
5774 return false;
5775 break;
5777 // Lightning Overload
5778 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5780 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5781 return false;
5783 // custom cooldown processing case
5784 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5785 return false;
5787 uint32 spellId = 0;
5788 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5789 switch (procSpell->Id)
5791 // Lightning Bolt
5792 case 403: spellId = 45284; break; // Rank 1
5793 case 529: spellId = 45286; break; // Rank 2
5794 case 548: spellId = 45287; break; // Rank 3
5795 case 915: spellId = 45288; break; // Rank 4
5796 case 943: spellId = 45289; break; // Rank 5
5797 case 6041: spellId = 45290; break; // Rank 6
5798 case 10391: spellId = 45291; break; // Rank 7
5799 case 10392: spellId = 45292; break; // Rank 8
5800 case 15207: spellId = 45293; break; // Rank 9
5801 case 15208: spellId = 45294; break; // Rank 10
5802 case 25448: spellId = 45295; break; // Rank 11
5803 case 25449: spellId = 45296; break; // Rank 12
5804 case 49237: spellId = 49239; break; // Rank 13
5805 case 49238: spellId = 49240; break; // Rank 14
5806 // Chain Lightning
5807 case 421: spellId = 45297; break; // Rank 1
5808 case 930: spellId = 45298; break; // Rank 2
5809 case 2860: spellId = 45299; break; // Rank 3
5810 case 10605: spellId = 45300; break; // Rank 4
5811 case 25439: spellId = 45301; break; // Rank 5
5812 case 25442: spellId = 45302; break; // Rank 6
5813 case 49268: spellId = 49270; break; // Rank 7
5814 case 49269: spellId = 49271; break; // Rank 8
5815 default:
5816 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5817 return false;
5819 // No thread generated mod
5820 // TODO: exist special flag in spell attributes for this, need found and use!
5821 SpellModifier *mod = new SpellModifier;
5822 mod->op = SPELLMOD_THREAT;
5823 mod->value = -100;
5824 mod->type = SPELLMOD_PCT;
5825 mod->spellId = dummySpell->Id;
5826 mod->mask = 0x0000000000000003LL;
5827 mod->mask2= 0LL;
5828 ((Player*)this)->AddSpellMod(mod, true);
5830 // Remove cooldown (Chain Lightning - have Category Recovery time)
5831 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5832 ((Player*)this)->RemoveSpellCooldown(spellId);
5834 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5836 ((Player*)this)->AddSpellMod(mod, false);
5838 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5839 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5841 return true;
5843 // Static Shock
5844 if(dummySpell->SpellIconID == 3059)
5846 // lookup Lightning Shield
5847 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5848 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5850 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5851 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5853 uint32 spell = 0;
5854 switch ((*itr)->GetId())
5856 case 324: spell = 26364; break;
5857 case 325: spell = 26365; break;
5858 case 905: spell = 26366; break;
5859 case 945: spell = 26367; break;
5860 case 8134: spell = 26369; break;
5861 case 10431: spell = 26370; break;
5862 case 10432: spell = 26363; break;
5863 case 25469: spell = 26371; break;
5864 case 25472: spell = 26372; break;
5865 case 49280: spell = 49278; break;
5866 case 49281: spell = 49279; break;
5867 default:
5868 return false;
5870 CastSpell(this, spell, true, castItem, triggeredByAura);
5871 if ((*itr)->DropAuraCharge())
5872 RemoveAurasDueToSpell((*itr)->GetId());
5873 return true;
5876 return false;
5877 break;
5879 break;
5881 case SPELLFAMILY_DEATHKNIGHT:
5883 // Blood Aura
5884 if (dummySpell->SpellIconID == 2636)
5886 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5887 return false;
5888 basepoints0 = triggerAmount * damage / 100;
5889 triggered_spell_id = 53168;
5890 break;
5892 // Butchery
5893 if (dummySpell->SpellIconID == 2664)
5895 basepoints0 = triggerAmount;
5896 triggered_spell_id = 50163;
5897 target = this;
5898 break;
5900 // Dancing Rune Weapon
5901 if (dummySpell->Id == 49028)
5903 // 1 dummy aura for dismiss rune blade
5904 if (effIndex!=2)
5905 return false;
5906 // TODO: wite script for this "fights on its own, doing the same attacks"
5907 // NOTE: Trigger here on every attack and spell cast
5908 return false;
5910 // Mark of Blood
5911 if (dummySpell->Id == 49005)
5913 // TODO: need more info (cooldowns/PPM)
5914 triggered_spell_id = 50424;
5915 break;
5917 // Vendetta
5918 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5920 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5921 triggered_spell_id = 50181;
5922 target = this;
5923 break;
5925 // Necrosis
5926 if (dummySpell->SpellIconID == 2709)
5928 basepoints0 = triggerAmount * damage / 100;
5929 triggered_spell_id = 51460;
5930 break;
5932 // Runic Power Back on Snare/Root
5933 if (dummySpell->Id == 61257)
5935 // only for spells and hit/crit (trigger start always) and not start from self casted spells
5936 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5937 return false;
5938 // Need snare or root mechanic
5939 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
5940 return false;
5941 triggered_spell_id = 61258;
5942 target = this;
5943 break;
5945 // Wandering Plague
5946 if (dummySpell->SpellIconID == 1614)
5948 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
5949 return false;
5950 basepoints0 = triggerAmount * damage / 100;
5951 triggered_spell_id = 50526;
5952 break;
5954 break;
5956 default:
5957 break;
5960 // processed charge only counting case
5961 if(!triggered_spell_id)
5962 return true;
5964 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5966 if(!triggerEntry)
5968 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5969 return false;
5972 // default case
5973 if(!target || target!=this && !target->isAlive())
5974 return false;
5976 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5977 return false;
5979 if(basepoints0)
5980 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5981 else
5982 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5984 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5985 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5987 return true;
5990 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5992 // Get triggered aura spell info
5993 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5995 // Basepoints of trigger aura
5996 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5998 // Set trigger spell id, target, custom basepoints
5999 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
6000 Unit* target = NULL;
6001 int32 basepoints0 = 0;
6003 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
6004 basepoints0 = triggerAmount;
6006 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6007 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6009 // Try handle uncnown trigger spells
6010 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
6012 switch (auraSpellInfo->SpellFamilyName)
6014 case SPELLFAMILY_GENERIC:
6015 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
6016 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6017 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6018 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6019 trigger_spell_id = 23781;
6020 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6021 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6023 // trigger_spell_id = 48877;
6025 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6027 // trigger_spell_id = 59233;
6029 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6031 // trigger_spell_id = 29471; // gain mana
6032 // 27526; // drain mana if possible
6034 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6035 //else if (auraSpellInfo->Id==54476) // Blood Presence
6036 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6037 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6038 //else if (auraSpellInfo->Id==52856) // Charge
6039 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6041 // Pct value stored in dummy
6042 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6043 target = pVictim;
6044 break;
6046 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6047 // trigger_spell_id = 41249;
6048 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6049 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6050 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6051 // trigger_spell_id = 41055;
6052 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6053 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6054 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6056 float stat = 0.0f;
6057 // strength
6058 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6059 // agility
6060 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6061 // intellect
6062 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6063 // spirit
6064 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6066 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6067 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6068 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6069 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6070 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6071 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6072 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6073 trigger_spell_id = 33898;
6074 //else if (auraSpellInfo->Id==18943) // Double Attack
6075 //else if (auraSpellInfo->Id==19194) // Double Attack
6076 //else if (auraSpellInfo->Id==19817) // Double Attack
6077 //else if (auraSpellInfo->Id==19818) // Double Attack
6078 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6079 // trigger_spell_id = 14822;
6081 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6083 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6085 case 34191:
6086 case 34329:
6087 case 34524:
6088 case 34582:
6089 case 36733:
6090 break;
6091 default:
6092 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6093 return false;
6095 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6096 switch (procSpell->School)
6098 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6099 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6100 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6101 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6102 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6103 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6104 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6105 default:
6106 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6107 return false;
6111 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6112 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6113 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6114 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6115 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6116 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6117 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6118 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6119 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6120 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6121 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6122 //else if (auraSpellInfo->Id==40250) // Improved Duration
6123 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6124 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6125 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6126 // Mana Drain Trigger
6128 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6129 if (this && this->isAlive())
6130 CastSpell(this, 29471, true, castItem, triggeredByAura);
6131 if (pVictim && pVictim->isAlive())
6132 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6133 return true;
6135 //else if (auraSpellInfo->Id==55580) // Mana Link
6136 //else if (auraSpellInfo->Id==45903) // Offensive State
6137 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6138 //else if (auraSpellInfo->Id==43453) // Rune Ward
6139 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6140 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6141 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6142 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6143 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6144 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6145 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6146 //else if (auraSpellInfo->Id==35205) // Vanish
6147 //else if (auraSpellInfo->Id==42730) // Woe Strike
6148 //else if (auraSpellInfo->Id==59735) // Woe Strike
6149 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6150 break;
6151 case SPELLFAMILY_MAGE:
6152 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6154 switch (auraSpellInfo->Id)
6156 case 31641: // Rank 1
6157 case 31642: // Rank 2
6158 trigger_spell_id = 31643;
6159 break;
6160 default:
6161 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6162 return false;
6165 break;
6166 case SPELLFAMILY_WARRIOR:
6167 if (auraSpellInfo->Id == 50421) // Scent of Blood
6168 trigger_spell_id = 50422;
6169 break;
6170 case SPELLFAMILY_WARLOCK:
6172 // Pyroclasm
6173 if (auraSpellInfo->SpellIconID == 1137)
6175 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6176 return false;
6177 // Calculate spell tick count for spells
6178 uint32 tick = 1; // Default tick = 1
6180 // Hellfire have 15 tick
6181 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6182 tick = 15;
6183 // Rain of Fire have 4 tick
6184 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6185 tick = 4;
6186 else
6187 return false;
6189 // Calculate chance = baseChance / tick
6190 float chance = 0;
6191 switch (auraSpellInfo->Id)
6193 case 18096: chance = 13.0f / tick; break;
6194 case 18073: chance = 26.0f / tick; break;
6196 // Roll chance
6197 if (!roll_chance_f(chance))
6198 return false;
6200 trigger_spell_id = 18093;
6202 // Drain Soul
6203 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6205 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6206 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6208 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6210 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6211 // Drain Soul
6212 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6213 break;
6216 // Not remove charge (aura removed on death in any cases)
6217 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6218 return false;
6220 // Nether Protection
6221 else if (auraSpellInfo->SpellIconID == 1985)
6223 if (!procSpell)
6224 return false;
6225 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6227 case SPELL_SCHOOL_NORMAL:
6228 case SPELL_SCHOOL_HOLY:
6229 return false; // ignore
6230 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6231 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6232 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6233 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6234 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6235 default:
6236 return false;
6239 break;
6241 case SPELLFAMILY_PRIEST:
6243 // Greater Heal Refund
6244 if (auraSpellInfo->Id==37594)
6245 trigger_spell_id = 37595;
6246 // Blessed Recovery
6247 else if (auraSpellInfo->SpellIconID == 1875)
6249 switch (auraSpellInfo->Id)
6251 case 27811: trigger_spell_id = 27813; break;
6252 case 27815: trigger_spell_id = 27817; break;
6253 case 27816: trigger_spell_id = 27818; break;
6254 default:
6255 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6256 return false;
6258 basepoints0 = damage * triggerAmount / 100 / 3;
6259 target = this;
6261 break;
6263 case SPELLFAMILY_DRUID:
6265 // Druid Forms Trinket
6266 if (auraSpellInfo->Id==37336)
6268 switch(m_form)
6270 case FORM_NONE: trigger_spell_id = 37344;break;
6271 case FORM_CAT: trigger_spell_id = 37341;break;
6272 case FORM_BEAR:
6273 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6274 case FORM_TREE: trigger_spell_id = 37342;break;
6275 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6276 default:
6277 return false;
6280 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6281 // trigger_spell_id = ????;
6282 // Leader of the Pack
6283 else if (auraSpellInfo->Id == 24932)
6285 if (triggerAmount == 0)
6286 return false;
6287 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6288 trigger_spell_id = 34299;
6290 break;
6292 case SPELLFAMILY_HUNTER:
6293 break;
6294 case SPELLFAMILY_PALADIN:
6297 // Blessed Life
6298 if (auraSpellInfo->SpellIconID == 2137)
6300 switch (auraSpellInfo->Id)
6302 case 31828: // Rank 1
6303 case 31829: // Rank 2
6304 case 31830: // Rank 3
6305 break;
6306 default:
6307 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6308 return false;
6312 // Healing Discount
6313 if (auraSpellInfo->Id==37705)
6315 trigger_spell_id = 37706;
6316 target = this;
6318 // Soul Preserver
6319 if (auraSpellInfo->Id==60510)
6321 trigger_spell_id = 60515;
6322 target = this;
6324 // Illumination
6325 else if (auraSpellInfo->SpellIconID==241)
6327 if(!procSpell)
6328 return false;
6329 // procspell is triggered spell but we need mana cost of original casted spell
6330 uint32 originalSpellId = procSpell->Id;
6331 // Holy Shock heal
6332 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6334 switch(procSpell->Id)
6336 case 25914: originalSpellId = 20473; break;
6337 case 25913: originalSpellId = 20929; break;
6338 case 25903: originalSpellId = 20930; break;
6339 case 27175: originalSpellId = 27174; break;
6340 case 33074: originalSpellId = 33072; break;
6341 case 48820: originalSpellId = 48824; break;
6342 case 48821: originalSpellId = 48825; break;
6343 default:
6344 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6345 return false;
6348 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6349 if(!originalSpell)
6351 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6352 return false;
6354 // percent stored in effect 1 (class scripts) base points
6355 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6356 basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6357 trigger_spell_id = 20272;
6358 target = this;
6360 // Lightning Capacitor
6361 else if (auraSpellInfo->Id==37657)
6363 if(!pVictim || !pVictim->isAlive())
6364 return false;
6365 // stacking
6366 CastSpell(this, 37658, true, NULL, triggeredByAura);
6368 Aura * dummy = GetDummyAura(37658);
6369 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6370 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6371 return false;
6373 RemoveAurasDueToSpell(37658);
6374 trigger_spell_id = 37661;
6375 target = pVictim;
6377 // Thunder Capacitor
6378 else if (auraSpellInfo->Id == 54841)
6380 if(!pVictim || !pVictim->isAlive())
6381 return false;
6382 // stacking
6383 CastSpell(this, 54842, true, NULL, triggeredByAura);
6385 // counting
6386 Aura * dummy = GetDummyAura(54842);
6387 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6388 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6389 return false;
6391 RemoveAurasDueToSpell(54842);
6392 trigger_spell_id = 54843;
6393 target = pVictim;
6395 break;
6397 case SPELLFAMILY_SHAMAN:
6399 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6400 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6402 switch(auraSpellInfo->Id)
6404 case 324: // Rank 1
6405 trigger_spell_id = 26364; break;
6406 case 325: // Rank 2
6407 trigger_spell_id = 26365; break;
6408 case 905: // Rank 3
6409 trigger_spell_id = 26366; break;
6410 case 945: // Rank 4
6411 trigger_spell_id = 26367; break;
6412 case 8134: // Rank 5
6413 trigger_spell_id = 26369; break;
6414 case 10431: // Rank 6
6415 trigger_spell_id = 26370; break;
6416 case 10432: // Rank 7
6417 trigger_spell_id = 26363; break;
6418 case 25469: // Rank 8
6419 trigger_spell_id = 26371; break;
6420 case 25472: // Rank 9
6421 trigger_spell_id = 26372; break;
6422 case 49280: // Rank 10
6423 trigger_spell_id = 49278; break;
6424 case 49281: // Rank 11
6425 trigger_spell_id = 49279; break;
6426 default:
6427 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6428 return false;
6431 // Lightning Shield (The Ten Storms set)
6432 else if (auraSpellInfo->Id == 23551)
6434 trigger_spell_id = 23552;
6435 target = pVictim;
6437 // Damage from Lightning Shield (The Ten Storms set)
6438 else if (auraSpellInfo->Id == 23552)
6439 trigger_spell_id = 27635;
6440 // Mana Surge (The Earthfury set)
6441 else if (auraSpellInfo->Id == 23572)
6443 if(!procSpell)
6444 return false;
6445 basepoints0 = procSpell->manaCost * 35 / 100;
6446 trigger_spell_id = 23571;
6447 target = this;
6449 // Nature's Guardian
6450 else if (auraSpellInfo->SpellIconID == 2013)
6452 // Check health condition - should drop to less 30% (damage deal after this!)
6453 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6454 return false;
6456 if(pVictim && pVictim->isAlive())
6457 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6459 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6460 trigger_spell_id = 31616;
6461 target = this;
6463 break;
6465 case SPELLFAMILY_DEATHKNIGHT:
6467 // Acclimation
6468 if (auraSpellInfo->SpellIconID == 1930)
6470 if (!procSpell)
6471 return false;
6472 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6474 case SPELL_SCHOOL_NORMAL:
6475 return false; // ignore
6476 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6477 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6478 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6479 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6480 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6481 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6482 default:
6483 return false;
6486 // Blood Presence
6487 else if (auraSpellInfo->Id == 48266)
6489 if (GetTypeId() != TYPEID_PLAYER)
6490 return false;
6491 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6492 return false;
6493 trigger_spell_id = 50475;
6494 basepoints0 = damage * triggerAmount / 100;
6496 break;
6498 default:
6499 break;
6503 // All ok. Check current trigger spell
6504 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6505 if ( triggerEntry == NULL )
6507 // Not cast unknown spell
6508 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6509 return false;
6512 // not allow proc extra attack spell at extra attack
6513 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6514 return false;
6516 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6517 // Custom triggered spells
6518 switch (auraSpellInfo->Id)
6520 // Persistent Shield (Scarab Brooch trinket)
6521 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6522 case 26467:
6524 basepoints0 = damage * 15 / 100;
6525 target = pVictim;
6526 trigger_spell_id = 26470;
6527 break;
6529 // Cheat Death
6530 case 28845:
6532 // When your health drops below 20% ....
6533 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6534 return false;
6535 break;
6537 // Deadly Swiftness (Rank 1)
6538 case 31255:
6540 // whenever you deal damage to a target who is below 20% health.
6541 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6542 return false;
6544 target = this;
6545 trigger_spell_id = 22588;
6547 // Greater Heal Refund (Avatar Raiment set)
6548 case 37594:
6550 // Not give if target alredy have full health
6551 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6552 return false;
6553 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6554 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6555 return false;
6556 break;
6558 // Bonus Healing (Crystal Spire of Karabor mace)
6559 case 40971:
6561 // If your target is below $s1% health
6562 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6563 return false;
6564 break;
6566 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6567 case 45057:
6569 // reduce you below $s1% health
6570 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6571 return false;
6572 break;
6574 // Rapid Recuperation
6575 case 53228:
6576 case 53232:
6578 // This effect only from Rapid Fire (ability cast)
6579 if (!(procSpell->SpellFamilyFlags & 0x0000000000000020LL))
6580 return false;
6581 break;
6585 // Costum basepoints/target for exist spell
6586 // dummy basepoints or other customs
6587 switch(trigger_spell_id)
6589 // Cast positive spell on enemy target
6590 case 7099: // Curse of Mending
6591 case 39647: // Curse of Mending
6592 case 29494: // Temptation
6593 case 20233: // Improved Lay on Hands (cast on target)
6595 target = pVictim;
6596 break;
6598 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6599 case 15250: // Rogue Setup
6601 if(!pVictim || pVictim != getVictim()) // applied only for main target
6602 return false;
6603 break; // continue normal case
6605 // Finish movies that add combo
6606 case 14189: // Seal Fate (Netherblade set)
6607 case 14157: // Ruthlessness
6609 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6610 break;
6612 // Bloodthirst (($m/100)% of max health)
6613 case 23880:
6615 basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
6616 break;
6618 // Shamanistic Rage triggered spell
6619 case 30824:
6621 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6622 break;
6624 // Enlightenment (trigger only from mana cost spells)
6625 case 35095:
6627 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6628 return false;
6629 break;
6631 // Brain Freeze
6632 case 57761:
6634 if(!procSpell)
6635 return false;
6636 // For trigger from Blizzard need exist Improved Blizzard
6637 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080LL)
6639 bool found = false;
6640 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6641 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6643 int32 script = (*i)->GetModifier()->m_miscvalue;
6644 if(script==836 || script==988 || script==989)
6646 found=true;
6647 break;
6650 if(!found)
6651 return false;
6653 break;
6655 // Astral Shift
6656 case 52179:
6658 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6659 return false;
6661 // Need stun, fear or silence mechanic
6662 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6663 return false;
6664 break;
6666 // Burning Determination
6667 case 54748:
6669 if(!procSpell)
6670 return false;
6671 // Need Interrupt or Silenced mechanic
6672 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6673 return false;
6674 break;
6676 // Lock and Load
6677 case 56453:
6679 // Proc only from trap activation (from periodic proc another aura of this spell)
6680 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
6681 return false;
6682 break;
6686 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6687 return false;
6689 // try detect target manually if not set
6690 if ( target == NULL )
6691 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6693 // default case
6694 if(!target || target!=this && !target->isAlive())
6695 return false;
6697 if(basepoints0)
6698 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6699 else
6700 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6702 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6703 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6705 return true;
6708 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6710 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6712 if(!pVictim || !pVictim->isAlive())
6713 return false;
6715 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6716 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6718 uint32 triggered_spell_id = 0;
6720 switch(scriptId)
6722 case 836: // Improved Blizzard (Rank 1)
6724 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6725 return false;
6726 triggered_spell_id = 12484;
6727 break;
6729 case 988: // Improved Blizzard (Rank 2)
6731 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6732 return false;
6733 triggered_spell_id = 12485;
6734 break;
6736 case 989: // Improved Blizzard (Rank 3)
6738 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6739 return false;
6740 triggered_spell_id = 12486;
6741 break;
6743 case 4086: // Improved Mend Pet (Rank 1)
6744 case 4087: // Improved Mend Pet (Rank 2)
6746 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6747 if(!roll_chance_i(chance))
6748 return false;
6750 triggered_spell_id = 24406;
6751 break;
6753 case 4533: // Dreamwalker Raiment 2 pieces bonus
6755 // Chance 50%
6756 if (!roll_chance_i(50))
6757 return false;
6759 switch (pVictim->getPowerType())
6761 case POWER_MANA: triggered_spell_id = 28722; break;
6762 case POWER_RAGE: triggered_spell_id = 28723; break;
6763 case POWER_ENERGY: triggered_spell_id = 28724; break;
6764 default:
6765 return false;
6767 break;
6769 case 4537: // Dreamwalker Raiment 6 pieces bonus
6770 triggered_spell_id = 28750; // Blessing of the Claw
6771 break;
6772 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6773 triggered_spell_id = 37445; // Mana Surge
6774 break;
6775 case 8152: // Serendipity
6777 // if heal your target over maximum health
6778 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6779 return false;
6780 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6781 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6782 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6783 return true;
6787 // not processed
6788 if(!triggered_spell_id)
6789 return false;
6791 // standard non-dummy case
6792 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6794 if(!triggerEntry)
6796 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6797 return false;
6800 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6801 return false;
6803 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6805 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6806 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6808 return true;
6811 void Unit::setPowerType(Powers new_powertype)
6813 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6815 if(GetTypeId() == TYPEID_PLAYER)
6817 if(((Player*)this)->GetGroup())
6818 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6820 else if(((Creature*)this)->isPet())
6822 Pet *pet = ((Pet*)this);
6823 if(pet->isControlled())
6825 Unit *owner = GetOwner();
6826 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6827 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6831 switch(new_powertype)
6833 default:
6834 case POWER_MANA:
6835 break;
6836 case POWER_RAGE:
6837 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6838 SetPower( POWER_RAGE,0);
6839 break;
6840 case POWER_FOCUS:
6841 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6842 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6843 break;
6844 case POWER_ENERGY:
6845 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6846 SetPower( POWER_ENERGY,0);
6847 break;
6848 case POWER_HAPPINESS:
6849 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6850 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6851 break;
6855 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6857 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6858 if(!entry)
6860 static uint64 guid = 0; // prevent repeating spam same faction problem
6862 if(GetGUID() != guid)
6864 if(GetTypeId() == TYPEID_PLAYER)
6865 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6866 else
6867 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6868 guid = GetGUID();
6871 return entry;
6874 bool Unit::IsHostileTo(Unit const* unit) const
6876 // always non-hostile to self
6877 if(unit==this)
6878 return false;
6880 // always non-hostile to GM in GM mode
6881 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6882 return false;
6884 // always hostile to enemy
6885 if(getVictim()==unit || unit->getVictim()==this)
6886 return true;
6888 // test pet/charm masters instead pers/charmeds
6889 Unit const* testerOwner = GetCharmerOrOwner();
6890 Unit const* targetOwner = unit->GetCharmerOrOwner();
6892 // always hostile to owner's enemy
6893 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6894 return true;
6896 // always hostile to enemy owner
6897 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6898 return true;
6900 // always hostile to owner of owner's enemy
6901 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6902 return true;
6904 Unit const* tester = testerOwner ? testerOwner : this;
6905 Unit const* target = targetOwner ? targetOwner : unit;
6907 // always non-hostile to target with common owner, or to owner/pet
6908 if(tester==target)
6909 return false;
6911 // special cases (Duel, etc)
6912 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6914 Player const* pTester = (Player const*)tester;
6915 Player const* pTarget = (Player const*)target;
6917 // Duel
6918 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6919 return true;
6921 // Group
6922 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6923 return false;
6925 // Sanctuary
6926 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6927 return false;
6929 // PvP FFA state
6930 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))
6931 return true;
6933 //= PvP states
6934 // Green/Blue (can't attack)
6935 if(pTester->GetTeam()==pTarget->GetTeam())
6936 return false;
6938 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6939 return pTester->IsPvP() && pTarget->IsPvP();
6942 // faction base cases
6943 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6944 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6945 if(!tester_faction || !target_faction)
6946 return false;
6948 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6949 return true;
6951 // PvC forced reaction and reputation case
6952 if(tester->GetTypeId()==TYPEID_PLAYER)
6954 // forced reaction
6955 if(target_faction->faction)
6957 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
6958 return *force <= REP_HOSTILE;
6960 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6961 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6962 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
6963 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6966 // CvP forced reaction and reputation case
6967 else if(target->GetTypeId()==TYPEID_PLAYER)
6969 // forced reaction
6970 if(tester_faction->faction)
6972 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
6973 return *force <= REP_HOSTILE;
6975 // apply reputation state
6976 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6977 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6978 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
6982 // common faction based case (CvC,PvC,CvP)
6983 return tester_faction->IsHostileTo(*target_faction);
6986 bool Unit::IsFriendlyTo(Unit const* unit) const
6988 // always friendly to self
6989 if(unit==this)
6990 return true;
6992 // always friendly to GM in GM mode
6993 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6994 return true;
6996 // always non-friendly to enemy
6997 if(getVictim()==unit || unit->getVictim()==this)
6998 return false;
7000 // test pet/charm masters instead pers/charmeds
7001 Unit const* testerOwner = GetCharmerOrOwner();
7002 Unit const* targetOwner = unit->GetCharmerOrOwner();
7004 // always non-friendly to owner's enemy
7005 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7006 return false;
7008 // always non-friendly to enemy owner
7009 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7010 return false;
7012 // always non-friendly to owner of owner's enemy
7013 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7014 return false;
7016 Unit const* tester = testerOwner ? testerOwner : this;
7017 Unit const* target = targetOwner ? targetOwner : unit;
7019 // always friendly to target with common owner, or to owner/pet
7020 if(tester==target)
7021 return true;
7023 // special cases (Duel)
7024 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7026 Player const* pTester = (Player const*)tester;
7027 Player const* pTarget = (Player const*)target;
7029 // Duel
7030 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7031 return false;
7033 // Group
7034 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7035 return true;
7037 // Sanctuary
7038 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7039 return true;
7041 // PvP FFA state
7042 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))
7043 return false;
7045 //= PvP states
7046 // Green/Blue (non-attackable)
7047 if(pTester->GetTeam()==pTarget->GetTeam())
7048 return true;
7050 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7051 return !pTarget->IsPvP();
7054 // faction base cases
7055 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7056 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7057 if(!tester_faction || !target_faction)
7058 return false;
7060 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7061 return false;
7063 // PvC forced reaction and reputation case
7064 if(tester->GetTypeId()==TYPEID_PLAYER)
7066 // forced reaction
7067 if(target_faction->faction)
7069 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7070 return *force >= REP_FRIENDLY;
7072 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7073 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7074 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7075 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7078 // CvP forced reaction and reputation case
7079 else if(target->GetTypeId()==TYPEID_PLAYER)
7081 // forced reaction
7082 if(tester_faction->faction)
7084 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7085 return *force >= REP_FRIENDLY;
7087 // apply reputation state
7088 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7089 if(raw_tester_faction->reputationListID >=0 )
7090 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7094 // common faction based case (CvC,PvC,CvP)
7095 return tester_faction->IsFriendlyTo(*target_faction);
7098 bool Unit::IsHostileToPlayers() const
7100 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7101 if(!my_faction || !my_faction->faction)
7102 return false;
7104 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7105 if(raw_faction && raw_faction->reputationListID >=0 )
7106 return false;
7108 return my_faction->IsHostileToPlayers();
7111 bool Unit::IsNeutralToAll() const
7113 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7114 if(!my_faction || !my_faction->faction)
7115 return true;
7117 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7118 if(raw_faction && raw_faction->reputationListID >=0 )
7119 return false;
7121 return my_faction->IsNeutralToAll();
7124 bool Unit::Attack(Unit *victim, bool meleeAttack)
7126 if(!victim || victim == this)
7127 return false;
7129 // dead units can neither attack nor be attacked
7130 if(!isAlive() || !victim->isAlive())
7131 return false;
7133 // player cannot attack in mount state
7134 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7135 return false;
7137 // nobody can attack GM in GM-mode
7138 if(victim->GetTypeId()==TYPEID_PLAYER)
7140 if(((Player*)victim)->isGameMaster())
7141 return false;
7143 else
7145 if(((Creature*)victim)->IsInEvadeMode())
7146 return false;
7149 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7150 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7151 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7153 // in fighting already
7154 if (m_attacking)
7156 if (m_attacking == victim)
7158 // switch to melee attack from ranged/magic
7159 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7161 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7162 SendAttackStart(victim);
7163 return true;
7165 return false;
7168 // remove old target data
7169 AttackStop(true);
7171 // new battle
7172 else
7174 // set position before any AI calls/assistance
7175 if(GetTypeId()==TYPEID_UNIT)
7176 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7179 //Set our target
7180 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7182 if(meleeAttack)
7183 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7185 m_attacking = victim;
7186 m_attacking->_addAttacker(this);
7188 if(m_attacking->GetTypeId()==TYPEID_UNIT && ((Creature*)m_attacking)->AI())
7189 ((Creature*)m_attacking)->AI()->AttackedBy(this);
7191 if(GetTypeId()==TYPEID_UNIT)
7193 WorldPacket data(SMSG_AI_REACTION, 12);
7194 data << uint64(GetGUID());
7195 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7196 ((WorldObject*)this)->SendMessageToSet(&data, true);
7198 ((Creature*)this)->CallAssistance();
7201 // delay offhand weapon attack to next attack time
7202 if(haveOffhandWeapon())
7203 resetAttackTimer(OFF_ATTACK);
7205 if(meleeAttack)
7206 SendAttackStart(victim);
7208 return true;
7211 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7213 if (!m_attacking)
7214 return false;
7216 Unit* victim = m_attacking;
7218 m_attacking->_removeAttacker(this);
7219 m_attacking = NULL;
7221 //Clear our target
7222 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7224 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7226 InterruptSpell(CURRENT_MELEE_SPELL);
7228 // reset only at real combat stop
7229 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7230 ((Creature*)this)->SetNoCallAssistance(false);
7232 SendAttackStop(victim);
7234 return true;
7237 void Unit::CombatStop(bool cast)
7239 if(cast& IsNonMeleeSpellCasted(false))
7240 InterruptNonMeleeSpells(false);
7242 AttackStop();
7243 RemoveAllAttackers();
7244 if( GetTypeId()==TYPEID_PLAYER )
7245 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7246 ClearInCombat();
7249 void Unit::CombatStopWithPets(bool cast)
7251 CombatStop(cast);
7252 if(Pet* pet = GetPet())
7253 pet->CombatStop(cast);
7254 if(Unit* charm = GetCharm())
7255 charm->CombatStop(cast);
7256 if(GetTypeId()==TYPEID_PLAYER)
7258 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7259 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7260 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7261 guardian->CombatStop(cast);
7265 bool Unit::isAttackingPlayer() const
7267 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7268 return true;
7270 Pet* pet = GetPet();
7271 if(pet && pet->isAttackingPlayer())
7272 return true;
7274 Unit* charmed = GetCharm();
7275 if(charmed && charmed->isAttackingPlayer())
7276 return true;
7278 for (int8 i = 0; i < MAX_TOTEM; i++)
7280 if(m_TotemSlot[i])
7282 Creature *totem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
7283 if(totem && totem->isAttackingPlayer())
7284 return true;
7288 return false;
7291 void Unit::RemoveAllAttackers()
7293 while (!m_attackers.empty())
7295 AttackerSet::iterator iter = m_attackers.begin();
7296 if(!(*iter)->AttackStop())
7298 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7299 m_attackers.erase(iter);
7304 void Unit::ModifyAuraState(AuraState flag, bool apply)
7306 ApplyModFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1), apply);
7309 Unit *Unit::GetOwner() const
7311 uint64 ownerid = GetOwnerGUID();
7312 if(!ownerid)
7313 return NULL;
7314 return ObjectAccessor::GetUnit(*this, ownerid);
7317 Unit *Unit::GetCharmer() const
7319 if(uint64 charmerid = GetCharmerGUID())
7320 return ObjectAccessor::GetUnit(*this, charmerid);
7321 return NULL;
7324 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7326 uint64 guid = GetCharmerOrOwnerGUID();
7327 if(IS_PLAYER_GUID(guid))
7328 return ObjectAccessor::GetPlayer(*this, guid);
7330 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7333 Pet* Unit::GetPet() const
7335 if(uint64 pet_guid = GetPetGUID())
7337 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7338 return pet;
7340 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7341 const_cast<Unit*>(this)->SetPet(0);
7344 return NULL;
7347 Unit* Unit::GetCharm() const
7349 if(uint64 charm_guid = GetCharmGUID())
7351 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7352 return pet;
7354 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7355 const_cast<Unit*>(this)->SetCharm(NULL);
7358 return NULL;
7361 float Unit::GetCombatDistance( const Unit* target ) const
7363 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
7364 float dx = GetPositionX() - target->GetPositionX();
7365 float dy = GetPositionY() - target->GetPositionY();
7366 float dz = GetPositionZ() - target->GetPositionZ();
7367 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
7368 return ( dist > 0 ? dist : 0);
7371 void Unit::SetPet(Pet* pet)
7373 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7375 // FIXME: hack, speed must be set only at follow
7376 if(pet)
7377 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7378 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7381 void Unit::SetCharm(Unit* pet)
7383 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7385 if(GetTypeId() == TYPEID_PLAYER)
7386 ((Player*)this)->m_mover = pet ? pet : this;
7389 void Unit::UnsummonAllTotems()
7391 for (int8 i = 0; i < MAX_TOTEM; ++i)
7393 if(!m_TotemSlot[i])
7394 continue;
7396 Creature *OldTotem = ObjectAccessor::GetCreature(*this, m_TotemSlot[i]);
7397 if (OldTotem && OldTotem->isTotem())
7398 ((Totem*)OldTotem)->UnSummon();
7402 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7404 // we guess size
7405 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7406 data.append(pVictim->GetPackGUID());
7407 data.append(GetPackGUID());
7408 data << uint32(SpellID);
7409 data << uint32(Damage);
7410 data << uint32(0); // over healing?
7411 data << uint8(critical ? 1 : 0);
7412 data << uint8(0); // unused in client?
7413 SendMessageToSet(&data, true);
7416 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7418 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7419 data.append(pVictim->GetPackGUID());
7420 data.append(GetPackGUID());
7421 data << uint32(SpellID);
7422 data << uint32(powertype);
7423 data << uint32(Damage);
7424 SendMessageToSet(&data, true);
7427 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
7429 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7430 return pdamage;
7432 // For totems get damage bonus from owner (statue isn't totem in fact)
7433 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7435 if(Unit* owner = GetOwner())
7436 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7439 // Taken/Done total percent damage auras
7440 float DoneTotalMod = 1.0f;
7441 float TakenTotalMod = 1.0f;
7442 int32 DoneTotal = 0;
7443 int32 TakenTotal = 0;
7445 // ..done
7446 // Pet damage
7447 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7448 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7450 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7451 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7453 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7454 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7455 // -1 == any item class (not wand then)
7456 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7457 // 0 == any inventory type (not wand then)
7459 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7463 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7464 // Add flat bonus from spell damage versus
7465 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7466 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7467 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7468 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7469 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7471 // done scripted mod (take it from owner)
7472 Unit *owner = GetOwner();
7473 if (!owner) owner = this;
7474 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7475 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7477 if (!(*i)->isAffectedOnSpell(spellProto))
7478 continue;
7479 switch((*i)->GetModifier()->m_miscvalue)
7481 case 4920: // Molten Fury
7482 case 4919:
7483 case 6917: // Death's Embrace
7484 case 6926:
7485 case 6928:
7487 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7488 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7489 break;
7491 // Soul Siphon
7492 case 4992:
7493 case 4993:
7495 // effect 1 m_amount
7496 int32 maxPercent = (*i)->GetModifier()->m_amount;
7497 // effect 0 m_amount
7498 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
7499 // count affliction effects and calc additional damage in percentage
7500 int32 modPercent = 0;
7501 AuraMap const& victimAuras = pVictim->GetAuras();
7502 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7504 SpellEntry const* m_spell = itr->second->GetSpellProto();
7505 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & 0x0004071B8044C402LL))
7506 continue;
7507 modPercent += stepPercent * itr->second->GetStackAmount();
7508 if (modPercent >= maxPercent)
7510 modPercent = maxPercent;
7511 break;
7514 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7515 break;
7517 case 6916: // Death's Embrace
7518 case 6925:
7519 case 6927:
7520 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
7521 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7522 break;
7523 case 5481: // Starfire Bonus
7525 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x0000000000200002LL))
7526 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7527 break;
7529 case 4418: // Increased Shock Damage
7530 case 4554: // Increased Lightning Damage
7531 case 4555: // Improved Moonfire
7532 case 5142: // Increased Lightning Damage
7533 case 5147: // Improved Consecration / Libram of Resurgence
7534 case 5148: // Idol of the Shooting Star
7535 case 6008: // Increased Lightning Damage / Totem of Hex
7537 DoneTotal+=(*i)->GetModifier()->m_amount;
7538 break;
7540 // Tundra Stalker
7541 // Merciless Combat
7542 case 7277:
7544 // Merciless Combat
7545 if ((*i)->GetSpellProto()->SpellIconID == 2656)
7547 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7548 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7550 else // Tundra Stalker
7552 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_DEATHKNIGHT, 0x0400000000000000LL))
7553 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7554 break;
7556 break;
7558 case 7293: // Rage of Rivendare
7560 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0x0200000000000000LL))
7561 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7562 break;
7564 // Twisted Faith
7565 case 7377:
7567 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x0000000000008000LL, 0, GetGUID()))
7568 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7569 break;
7571 // Marked for Death
7572 case 7598:
7573 case 7599:
7574 case 7600:
7575 case 7601:
7576 case 7602:
7578 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x0000000000000400LL))
7579 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7580 break;
7585 // Custom scripted damage
7586 // Ice Lance
7587 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 186)
7589 if (pVictim->isFrozen())
7590 DoneTotalMod *= 3.0f;
7593 // ..taken
7594 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7595 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7596 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7597 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7599 // .. taken pct: dummy auras
7600 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7602 //Cheat Death
7603 if (Aura *dummy = pVictim->GetDummyAura(45182))
7605 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7606 if (mod < dummy->GetModifier()->m_amount)
7607 mod = dummy->GetModifier()->m_amount;
7608 TakenTotalMod *= (mod+100.0f)/100.0f;
7612 // From caster spells
7613 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
7614 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
7615 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
7616 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7618 // Mod damage from spell mechanic
7619 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
7620 if (mechanicMask)
7622 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
7623 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
7624 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
7625 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7628 // Taken/Done fixed damage bonus auras
7629 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
7630 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7632 // Pets just add their bonus damage to their spell damage
7633 // note that their spell damage is just gain of their own auras
7634 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
7635 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
7637 float LvlPenalty = CalculateLevelPenalty(spellProto);
7638 // Spellmod SpellDamage
7639 float SpellModSpellDamage = 100.0f;
7640 if(Player* modOwner = GetSpellModOwner())
7641 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7642 SpellModSpellDamage /= 100.0f;
7644 // Check for table values
7645 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
7646 if (bonus)
7648 float coeff;
7649 if (damagetype == DOT)
7650 coeff = bonus->dot_damage * LvlPenalty * stack;
7651 else
7652 coeff = bonus->direct_damage * LvlPenalty * stack;
7654 if (bonus->ap_bonus)
7655 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
7657 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
7658 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
7660 // Default calculation
7661 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
7663 // Damage Done from spell damage bonus
7664 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7665 // Damage over Time spells bonus calculation
7666 float DotFactor = 1.0f;
7667 if(damagetype == DOT)
7669 int32 DotDuration = GetSpellDuration(spellProto);
7670 // 200% limit
7671 if(DotDuration > 0)
7673 if(DotDuration > 30000) DotDuration = 30000;
7674 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7675 int x = 0;
7676 for(int j = 0; j < 3; j++)
7678 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7679 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7680 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7682 x = j;
7683 break;
7686 int32 DotTicks = 6;
7687 if(spellProto->EffectAmplitude[x] != 0)
7688 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7689 if(DotTicks)
7691 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
7692 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
7696 // Distribute Damage over multiple effects, reduce by AoE
7697 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7698 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7699 for(int j = 0; j < 3; ++j)
7701 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7702 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7704 CastingTime /= 2;
7705 break;
7708 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
7709 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
7712 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
7713 // apply spellmod to Done damage (flat and pct)
7714 if(Player* modOwner = GetSpellModOwner())
7715 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7717 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
7719 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7722 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7724 int32 DoneAdvertisedBenefit = 0;
7726 // ..done
7727 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7728 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7729 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7730 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7731 // -1 == any item class (not wand then)
7732 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7733 // 0 == any inventory type (not wand then)
7734 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7736 if (GetTypeId() == TYPEID_PLAYER)
7738 // Base value
7739 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7741 // Damage bonus from stats
7742 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7743 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7745 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7747 // stat used stored in miscValueB for this aura
7748 Stats usedStat = Stats((*i)->GetMiscBValue());
7749 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7752 // ... and attack power
7753 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7754 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7755 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7756 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7759 return DoneAdvertisedBenefit;
7762 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7764 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7766 int32 TakenAdvertisedBenefit = 0;
7767 // ..done (for creature type by mask) in taken
7768 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7769 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7770 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7771 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7773 // ..taken
7774 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7775 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7776 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7777 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7779 return TakenAdvertisedBenefit;
7782 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7784 // not critting spell
7785 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7786 return false;
7788 float crit_chance = 0.0f;
7789 switch(spellProto->DmgClass)
7791 case SPELL_DAMAGE_CLASS_NONE:
7792 return false;
7793 case SPELL_DAMAGE_CLASS_MAGIC:
7795 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7796 crit_chance = 0.0f;
7797 // For other schools
7798 else if (GetTypeId() == TYPEID_PLAYER)
7799 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7800 else
7802 crit_chance = m_baseSpellCritChance;
7803 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7805 // taken
7806 if (pVictim)
7808 if (!IsPositiveSpell(spellProto->Id))
7810 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7811 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7812 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7813 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7814 // Modify by player victim resilience
7815 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7816 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7819 // scripted (increase crit chance ... against ... target by x%
7820 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7821 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7823 if (!((*i)->isAffectedOnSpell(spellProto)))
7824 continue;
7825 switch((*i)->GetModifier()->m_miscvalue)
7827 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
7828 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
7829 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
7830 case 7917: // Glyph of Shadowburn
7831 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7832 crit_chance+=(*i)->GetModifier()->m_amount;
7833 break;
7834 case 7997: // Renewed Hope
7835 case 7998:
7836 if (pVictim->HasAura(6788))
7837 crit_chance+=(*i)->GetModifier()->m_amount;
7838 break;
7839 case 21: // Test of Faith
7840 case 6935:
7841 case 6918:
7842 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
7843 crit_chance+=(*i)->GetModifier()->m_amount;
7844 break;
7845 default:
7846 break;
7849 // Custom crit by class
7850 switch(spellProto->SpellFamilyName)
7852 case SPELLFAMILY_PALADIN:
7853 // Sacred Shield
7854 if (spellProto->SpellFamilyFlags & 0x0000000040000000LL)
7856 Aura *aura = pVictim->GetDummyAura(58597);
7857 if (aura && aura->GetCasterGUID() == GetGUID())
7858 crit_chance+=aura->GetModifier()->m_amount;
7859 break;
7861 break;
7862 case SPELLFAMILY_SHAMAN:
7863 // Lava Burst
7864 if (spellProto->SpellFamilyFlags & 0x0000100000000000LL)
7866 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x0000000010000000LL, 0, GetGUID()))
7868 // Consume shock aura if not have Glyph of Flame Shock
7869 if (!GetAura(55447, 0))
7870 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
7871 return true;
7873 break;
7875 break;
7879 break;
7881 case SPELL_DAMAGE_CLASS_MELEE:
7882 case SPELL_DAMAGE_CLASS_RANGED:
7884 if (pVictim)
7886 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7887 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7889 break;
7891 default:
7892 return false;
7894 // percent done
7895 // only players use intelligence for critical chance computations
7896 if(Player* modOwner = GetSpellModOwner())
7897 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7899 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7900 if (roll_chance_f(crit_chance))
7901 return true;
7902 return false;
7905 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7907 // Calculate critical bonus
7908 int32 crit_bonus;
7909 switch(spellProto->DmgClass)
7911 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7912 case SPELL_DAMAGE_CLASS_RANGED:
7913 // TODO: write here full calculation for melee/ranged spells
7914 crit_bonus = damage;
7915 break;
7916 default:
7917 crit_bonus = damage / 2; // for spells is 50%
7918 break;
7921 // adds additional damage to crit_bonus (from talents)
7922 if(Player* modOwner = GetSpellModOwner())
7923 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
7925 if(pVictim)
7927 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7928 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7931 if(crit_bonus > 0)
7932 damage += crit_bonus;
7934 return damage;
7937 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7939 // Calculate critical bonus
7940 int32 crit_bonus;
7941 switch(spellProto->DmgClass)
7943 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
7944 case SPELL_DAMAGE_CLASS_RANGED:
7945 // TODO: write here full calculation for melee/ranged spells
7946 crit_bonus = damage;
7947 break;
7948 default:
7949 crit_bonus = damage / 2; // for spells is 50%
7950 break;
7953 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_BONUS));
7955 if(pVictim)
7957 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7958 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
7961 if(crit_bonus > 0)
7962 damage += crit_bonus;
7964 return damage;
7967 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
7969 // No heal amount for this class spells
7970 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
7971 return healamount;
7973 // For totems get healing bonus from owner (statue isn't totem in fact)
7974 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7975 if(Unit* owner = GetOwner())
7976 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
7978 // Healing Done
7979 // Taken/Done total percent damage auras
7980 float DoneTotalMod = 1.0f;
7981 float TakenTotalMod = 1.0f;
7982 int32 DoneTotal = 0;
7983 int32 TakenTotal = 0;
7985 // Healing done percent
7986 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
7987 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
7988 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
7990 // done scripted mod (take it from owner)
7991 Unit *owner = GetOwner();
7992 if (!owner) owner = this;
7993 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7994 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7996 if (!(*i)->isAffectedOnSpell(spellProto))
7997 continue;
7998 switch((*i)->GetModifier()->m_miscvalue)
8000 case 4415: // Increased Rejuvenation Healing
8001 case 4953:
8002 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
8003 DoneTotal+=(*i)->GetModifier()->m_amount;
8004 break;
8005 case 7997: // Renewed Hope
8006 case 7998:
8007 if (pVictim->HasAura(6788))
8008 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8009 break;
8010 case 21: // Test of Faith
8011 case 6935:
8012 case 6918:
8013 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8014 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8015 break;
8016 case 7798: // Glyph of Regrowth
8018 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x0000000000000040LL))
8019 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8020 break;
8022 case 8477: // Nourish Heal Boost
8024 int32 stepPercent = (*i)->GetModifier()->m_amount;
8025 int32 modPercent = 0;
8026 AuraMap const& victimAuras = pVictim->GetAuras();
8027 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8029 if (itr->second->GetCasterGUID()!=GetGUID())
8030 continue;
8031 SpellEntry const* m_spell = itr->second->GetSpellProto();
8032 if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8033 !(m_spell->SpellFamilyFlags & 0x0000001000000050LL))
8034 continue;
8035 modPercent += stepPercent * itr->second->GetStackAmount();
8037 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8038 break;
8040 case 7871: // Glyph of Lesser Healing Wave
8042 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x0000040000000000LL, 0, GetGUID()))
8043 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8044 break;
8046 default:
8047 break;
8051 // Taken/Done fixed damage bonus auras
8052 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8053 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8055 float LvlPenalty = CalculateLevelPenalty(spellProto);
8056 // Spellmod SpellDamage
8057 float SpellModSpellDamage = 100.0f;
8058 if(Player* modOwner = GetSpellModOwner())
8059 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8060 SpellModSpellDamage /= 100.0f;
8062 // Check for table values
8063 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8064 if (bonus)
8066 float coeff;
8067 if (damagetype == DOT)
8068 coeff = bonus->dot_damage * LvlPenalty * stack;
8069 else
8070 coeff = bonus->direct_damage * LvlPenalty * stack;
8072 if (bonus->ap_bonus)
8073 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8075 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8076 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8078 // Default calculation
8079 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8081 // Damage Done from spell damage bonus
8082 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8083 // Damage over Time spells bonus calculation
8084 float DotFactor = 1.0f;
8085 if(damagetype == DOT)
8087 int32 DotDuration = GetSpellDuration(spellProto);
8088 // 200% limit
8089 if(DotDuration > 0)
8091 if(DotDuration > 30000) DotDuration = 30000;
8092 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8093 int x = 0;
8094 for(int j = 0; j < 3; j++)
8096 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8097 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8098 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8100 x = j;
8101 break;
8104 int32 DotTicks = 6;
8105 if(spellProto->EffectAmplitude[x] != 0)
8106 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8107 if(DotTicks)
8109 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8110 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8114 // Distribute Damage over multiple effects, reduce by AoE
8115 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8116 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8117 for(int j = 0; j < 3; ++j)
8119 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8120 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8122 CastingTime /= 2;
8123 break;
8126 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
8127 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
8130 // use float as more appropriate for negative values and percent applying
8131 float heal = (healamount + DoneTotal)*DoneTotalMod;
8132 // apply spellmod to Done amount
8133 if(Player* modOwner = GetSpellModOwner())
8134 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8136 // Taken mods
8137 // Healing Wave cast
8138 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8140 // Search for Healing Way on Victim
8141 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8142 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8143 if((*itr)->GetId() == 29203)
8144 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8147 // Healing taken percent
8148 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8149 if(minval)
8150 TakenTotalMod *= (100.0f + minval) / 100.0f;
8152 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8153 if(maxval)
8154 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8156 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8157 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8158 if ((*i)->isAffectedOnSpell(spellProto))
8159 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8161 heal = (heal + TakenTotal) * TakenTotalMod;
8163 return heal < 0 ? 0 : uint32(heal);
8166 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8168 int32 AdvertisedBenefit = 0;
8170 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8171 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8172 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8173 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8175 // Healing bonus of spirit, intellect and strength
8176 if (GetTypeId() == TYPEID_PLAYER)
8178 // Base value
8179 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8181 // Healing bonus from stats
8182 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8183 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8185 // stat used dependent from misc value (stat index)
8186 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8187 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8190 // ... and attack power
8191 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8192 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8193 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8194 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8196 return AdvertisedBenefit;
8199 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8201 int32 AdvertisedBenefit = 0;
8202 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8203 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8204 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8205 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8206 return AdvertisedBenefit;
8209 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8211 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8212 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8213 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8214 if(itr->type & shoolMask)
8215 return true;
8217 //If m_immuneToDamage type contain magic, IMMUNE damage.
8218 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8219 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8220 if(itr->type & shoolMask)
8221 return true;
8223 return false;
8226 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8228 if (!spellInfo)
8229 return false;
8231 //FIX ME this hack: don't get feared if stunned
8232 if (spellInfo->Mechanic == MECHANIC_FEAR )
8234 if ( hasUnitState(UNIT_STAT_STUNNED) )
8235 return true;
8238 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
8239 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
8241 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8242 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8243 if(itr->type == spellInfo->Dispel)
8244 return true;
8246 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8247 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8249 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8250 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8251 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8252 (itr->type & GetSpellSchoolMask(spellInfo)) )
8253 return true;
8256 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8257 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8259 if(itr->type == spellInfo->Mechanic)
8261 return true;
8265 return false;
8268 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8270 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8271 uint32 effect = spellInfo->Effect[index];
8272 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8273 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8274 if(itr->type == effect)
8275 return true;
8277 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8279 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8280 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8281 if(itr->type == mechanic)
8282 return true;
8285 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8287 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8288 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8289 if(itr->type == aura)
8290 return true;
8291 // Check for immune to application of harmful magical effects
8292 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8293 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8294 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8295 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8296 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8297 return true;
8300 return false;
8303 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8305 if(!spellInfo)
8306 return false;
8308 uint32 family = spellInfo->SpellFamilyName;
8309 uint64 flags = spellInfo->SpellFamilyFlags;
8311 if((family == 5 && flags == 256) || //Searing Pain
8312 (family == 6 && flags == 8192) || //Mind Blast
8313 (family == 11 && flags == 1048576)) //Earth Shock
8314 return true;
8316 return false;
8319 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8321 if(!pVictim)
8322 return;
8324 if(*pdamage == 0)
8325 return;
8327 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8329 // Taken/Done fixed damage bonus auras
8330 int32 DoneFlatBenefit = 0;
8331 int32 TakenFlatBenefit = 0;
8333 // ..done (for creature type by mask) in taken
8334 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8335 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8336 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8337 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8339 // ..done
8340 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8342 // ..done (base at attack power for marked target and base at attack power for creature type)
8343 int32 APbonus = 0;
8344 if(attType == RANGED_ATTACK)
8346 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8348 // ..done (base at attack power and creature type)
8349 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8350 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8351 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8352 APbonus += (*i)->GetModifier()->m_amount;
8354 else
8356 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8358 // ..done (base at attack power and creature type)
8359 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8360 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8361 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8362 APbonus += (*i)->GetModifier()->m_amount;
8365 if (APbonus!=0) // Can be negative
8367 bool normalized = false;
8368 if(spellProto)
8370 for (uint8 i = 0; i<3;i++)
8372 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8374 normalized = true;
8375 break;
8380 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8383 // ..taken
8384 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8385 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8386 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8387 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8389 if(attType!=RANGED_ATTACK)
8390 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8391 else
8392 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8394 // Done/Taken total percent damage auras
8395 float DoneTotalMod = 1.0f;
8396 float TakenTotalMod = 1.0f;
8398 // ..done
8399 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8400 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8402 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8403 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8404 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8405 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8407 // ..taken
8408 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8409 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8410 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8411 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8413 // .. taken pct: dummy auras
8414 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8415 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8417 switch((*i)->GetSpellProto()->SpellIconID)
8419 //Cheat Death
8420 case 2109:
8421 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8423 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8424 continue;
8425 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8426 if (mod < (*i)->GetModifier()->m_amount)
8427 mod = (*i)->GetModifier()->m_amount;
8428 TakenTotalMod *= (mod+100.0f)/100.0f;
8430 break;
8431 //Mangle
8432 case 2312:
8433 if(spellProto==NULL)
8434 break;
8435 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8436 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8437 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8438 break;
8442 // .. taken pct: class scripts
8443 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8444 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8446 switch((*i)->GetMiscValue())
8448 case 6427: case 6428: // Dirty Deeds
8449 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8451 Aura* eff0 = GetAura((*i)->GetId(),0);
8452 if(!eff0 || (*i)->GetEffIndex()!=1)
8454 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8455 continue;
8458 // effect 0 have expected value but in negative state
8459 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8461 break;
8465 if(attType != RANGED_ATTACK)
8467 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8468 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8469 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8471 else
8473 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8474 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8475 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8478 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8480 // apply spellmod to Done damage
8481 if(spellProto)
8483 if(Player* modOwner = GetSpellModOwner())
8484 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8487 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8489 // bonus result can be negative
8490 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8493 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8495 if (apply)
8497 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8499 next = itr; ++next;
8500 if(itr->type == type)
8502 m_spellImmune[op].erase(itr);
8503 next = m_spellImmune[op].begin();
8506 SpellImmune Immune;
8507 Immune.spellId = spellId;
8508 Immune.type = type;
8509 m_spellImmune[op].push_back(Immune);
8511 else
8513 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8515 if(itr->spellId == spellId)
8517 m_spellImmune[op].erase(itr);
8518 break;
8525 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8527 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8529 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8530 RemoveAurasWithDispelType(type);
8533 float Unit::GetWeaponProcChance() const
8535 // normalized proc chance for weapon attack speed
8536 // (odd formula...)
8537 if(isAttackReady(BASE_ATTACK))
8538 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8539 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8540 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8541 return 0;
8544 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8546 // proc per minute chance calculation
8547 if (PPM <= 0) return 0.0f;
8548 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8549 return result;
8552 void Unit::Mount(uint32 mount)
8554 if(!mount)
8555 return;
8557 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8559 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8561 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8563 // unsummon pet
8564 if(GetTypeId() == TYPEID_PLAYER)
8566 Pet* pet = GetPet();
8567 if(pet)
8569 if(pet->isControlled())
8571 ((Player*)this)->SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
8572 ((Player*)this)->SetOldPetSpell(pet->GetUInt32Value(UNIT_CREATED_BY_SPELL));
8575 ((Player*)this)->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT);
8577 else
8578 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8582 void Unit::Unmount()
8584 if(!IsMounted())
8585 return;
8587 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8589 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8590 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8592 // only resummon old pet if the player is already added to a map
8593 // this prevents adding a pet to a not created map which would otherwise cause a crash
8594 // (it could probably happen when logging in after a previous crash)
8595 if(GetTypeId() == TYPEID_PLAYER && IsInWorld() && ((Player*)this)->GetTemporaryUnsummonedPetNumber() && isAlive())
8597 Pet* NewPet = new Pet;
8598 if(!NewPet->LoadPetFromDB((Player*)this, 0, ((Player*)this)->GetTemporaryUnsummonedPetNumber(), true))
8599 delete NewPet;
8601 ((Player*)this)->SetTemporaryUnsummonedPetNumber(0);
8605 void Unit::SetInCombatWith(Unit* enemy)
8607 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8608 if(eOwner->IsPvP())
8610 SetInCombatState(true);
8611 return;
8614 //check for duel
8615 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8617 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8618 if(((Player const*)eOwner)->duel->opponent == myOwner)
8620 SetInCombatState(true);
8621 return;
8624 SetInCombatState(false);
8627 void Unit::SetInCombatState(bool PvP)
8629 // only alive units can be in combat
8630 if(!isAlive())
8631 return;
8633 if(PvP)
8634 m_CombatTimer = 5000;
8635 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8637 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8638 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8641 void Unit::ClearInCombat()
8643 m_CombatTimer = 0;
8644 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8646 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8647 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8649 // Player's state will be cleared in Player::UpdateContestedPvP
8650 if(GetTypeId()!=TYPEID_PLAYER)
8651 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8652 else
8653 ((Player*)this)->UpdatePotionCooldown();
8656 bool Unit::isTargetableForAttack() const
8658 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8659 return false;
8661 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8662 return false;
8664 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8667 int32 Unit::ModifyHealth(int32 dVal)
8669 int32 gain = 0;
8671 if(dVal==0)
8672 return 0;
8674 int32 curHealth = (int32)GetHealth();
8676 int32 val = dVal + curHealth;
8677 if(val <= 0)
8679 SetHealth(0);
8680 return -curHealth;
8683 int32 maxHealth = (int32)GetMaxHealth();
8685 if(val < maxHealth)
8687 SetHealth(val);
8688 gain = val - curHealth;
8690 else if(curHealth != maxHealth)
8692 SetHealth(maxHealth);
8693 gain = maxHealth - curHealth;
8696 return gain;
8699 int32 Unit::ModifyPower(Powers power, int32 dVal)
8701 int32 gain = 0;
8703 if(dVal==0)
8704 return 0;
8706 int32 curPower = (int32)GetPower(power);
8708 int32 val = dVal + curPower;
8709 if(val <= 0)
8711 SetPower(power,0);
8712 return -curPower;
8715 int32 maxPower = (int32)GetMaxPower(power);
8717 if(val < maxPower)
8719 SetPower(power,val);
8720 gain = val - curPower;
8722 else if(curPower != maxPower)
8724 SetPower(power,maxPower);
8725 gain = maxPower - curPower;
8728 return gain;
8731 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8733 if(!u)
8734 return false;
8736 // Always can see self
8737 if (u==this)
8738 return true;
8740 // player visible for other player if not logout and at same transport
8741 // including case when player is out of world
8742 bool at_same_transport =
8743 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8744 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8745 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8746 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8748 // not in world
8749 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8750 return false;
8752 // forbidden to seen (at GM respawn command)
8753 if(m_Visibility==VISIBILITY_RESPAWN)
8754 return false;
8756 // always seen by owner
8757 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8758 return true;
8760 // Grid dead/alive checks
8761 if( u->GetTypeId()==TYPEID_PLAYER)
8763 // non visible at grid for any stealth state
8764 if(!IsVisibleInGridForPlayer((Player *)u))
8765 return false;
8767 // if player is dead then he can't detect anyone in any cases
8768 if(!u->isAlive())
8769 detect = false;
8771 else
8773 // all dead creatures/players not visible for any creatures
8774 if(!u->isAlive() || !isAlive())
8775 return false;
8778 // different visible distance checks
8779 if(u->isInFlight()) // what see player in flight
8781 // use object grey distance for all (only see objects any way)
8782 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8783 return false;
8785 else if(!isAlive()) // distance for show body
8787 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8788 return false;
8790 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8792 if(u->GetTypeId()==TYPEID_PLAYER)
8794 // Players far than max visible distance for player or not in our map are not visible too
8795 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8796 return false;
8798 else
8800 // Units far than max visible distance for creature or not in our map are not visible too
8801 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8802 return false;
8805 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8807 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8808 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8809 return false;
8811 else // distance for show creature
8813 // Units far than max visible distance for creature or not in our map are not visible too
8814 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8815 return false;
8818 // Visible units, always are visible for all units, except for units under invisibility and phases
8819 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
8820 return true;
8822 // GMs see any players, not higher GMs and all units in any phase
8823 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8825 if(GetTypeId() == TYPEID_PLAYER)
8826 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8827 else
8828 return true;
8831 // non faction visibility non-breakable for non-GMs
8832 if (m_Visibility == VISIBILITY_OFF)
8833 return false;
8835 // phased visibility (both must phased in same way)
8836 if(!InSamePhase(u))
8837 return false;
8839 // raw invisibility
8840 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8842 // detectable invisibility case
8843 if( invisible && (
8844 // Invisible units, always are visible for units under same invisibility type
8845 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8846 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8847 u->canDetectInvisibilityOf(this) ||
8848 // Units that can detect invisibility always are visible for units that can be detected
8849 canDetectInvisibilityOf(u) ))
8851 invisible = false;
8854 // special cases for always overwrite invisibility/stealth
8855 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8857 // non-hostile case
8858 if (!u->IsHostileTo(this))
8860 // 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)
8861 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8863 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8864 return true;
8866 // else apply same rules as for hostile case (detecting check for stealth)
8869 // hostile case
8870 else
8872 // Hunter mark functionality
8873 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8874 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8875 if((*iter)->GetCasterGUID()==u->GetGUID())
8876 return true;
8878 // else apply detecting check for stealth
8881 // none other cases for detect invisibility, so invisible
8882 if(invisible)
8883 return false;
8885 // else apply stealth detecting check
8888 // unit got in stealth in this moment and must ignore old detected state
8889 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8890 return false;
8892 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8893 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8894 return true;
8896 // NOW ONLY STEALTH CASE
8898 // stealth and detected and visible for some seconds
8899 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8900 return true;
8902 //if in non-detect mode then invisible for unit
8903 if (!detect)
8904 return false;
8906 // Special cases
8908 // If is attacked then stealth is lost, some creature can use stealth too
8909 if( !getAttackers().empty() )
8910 return true;
8912 // If there is collision rogue is seen regardless of level difference
8913 // TODO: check sizes in DB
8914 float distance = GetDistance(u);
8915 if (distance < 0.24f)
8916 return true;
8918 //If a mob or player is stunned he will not be able to detect stealth
8919 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8920 return false;
8922 // Creature can detect target only in aggro radius
8923 if(u->GetTypeId() != TYPEID_PLAYER)
8925 //Always invisible from back and out of aggro range
8926 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8927 if(!isInFront)
8928 return false;
8930 else
8932 //Always invisible from back
8933 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
8934 if(!isInFront)
8935 return false;
8938 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
8939 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
8941 //Calculation if target is in front
8943 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
8944 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
8946 //Visible distance is modified by
8947 //-Level Diff (every level diff = 1.0f in visible distance)
8948 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
8950 //This allows to check talent tree and will add addition stealth dependent on used points)
8951 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
8952 if(stealthMod < 0)
8953 stealthMod = 0;
8955 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
8956 //based on wowwiki every 5 mod we have 1 more level diff in calculation
8957 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
8959 if(distance > visibleDistance)
8960 return false;
8963 // Now check is target visible with LoS
8964 float ox,oy,oz;
8965 u->GetPosition(ox,oy,oz);
8966 return IsWithinLOS(ox,oy,oz);
8969 void Unit::SetVisibility(UnitVisibility x)
8971 m_Visibility = x;
8973 if(IsInWorld())
8975 Map *m = GetMap();
8977 if(GetTypeId()==TYPEID_PLAYER)
8978 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8979 else
8980 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
8984 bool Unit::canDetectInvisibilityOf(Unit const* u) const
8986 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
8988 for(uint32 i = 0; i < 10; ++i)
8990 if(((1 << i) & mask)==0)
8991 continue;
8993 // find invisibility level
8994 uint32 invLevel = 0;
8995 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
8996 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
8997 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
8998 invLevel = (*itr)->GetModifier()->m_amount;
9000 // find invisibility detect level
9001 uint32 detectLevel = 0;
9002 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
9003 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
9004 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
9005 detectLevel = (*itr)->GetModifier()->m_amount;
9007 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
9009 detectLevel = ((Player*)this)->GetDrunkValue();
9012 if(invLevel <= detectLevel)
9013 return true;
9017 return false;
9020 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
9022 int32 main_speed_mod = 0;
9023 float stack_bonus = 1.0f;
9024 float non_stack_bonus = 1.0f;
9026 switch(mtype)
9028 case MOVE_WALK:
9029 return;
9030 case MOVE_RUN:
9032 if (IsMounted()) // Use on mount auras
9034 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
9035 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
9036 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
9038 else
9040 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
9041 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
9042 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
9044 break;
9046 case MOVE_RUN_BACK:
9047 return;
9048 case MOVE_SWIM:
9050 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
9051 break;
9053 case MOVE_SWIM_BACK:
9054 return;
9055 case MOVE_FLIGHT:
9057 if (IsMounted()) // Use on mount auras
9058 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9059 else // Use not mount (shapeshift for example) auras (should stack)
9060 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9061 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9062 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9063 break;
9065 case MOVE_FLIGHT_BACK:
9066 return;
9067 default:
9068 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9069 return;
9072 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9073 // now we ready for speed calculation
9074 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9076 switch(mtype)
9078 case MOVE_RUN:
9079 case MOVE_SWIM:
9080 case MOVE_FLIGHT:
9082 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9083 // TODO: possible affect only on MOVE_RUN
9084 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9086 // Use speed from aura
9087 float max_speed = normalization / baseMoveSpeed[mtype];
9088 if (speed > max_speed)
9089 speed = max_speed;
9091 break;
9093 default:
9094 break;
9097 // Apply strongest slow aura mod to speed
9098 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9099 if (slow)
9100 speed *=(100.0f + slow)/100.0f;
9101 SetSpeed(mtype, speed, forced);
9104 float Unit::GetSpeed( UnitMoveType mtype ) const
9106 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9109 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9111 if (rate < 0)
9112 rate = 0.0f;
9114 // Update speed only on change
9115 if (m_speed_rate[mtype] == rate)
9116 return;
9118 m_speed_rate[mtype] = rate;
9120 propagateSpeedChange();
9122 WorldPacket data;
9123 if(!forced)
9125 switch(mtype)
9127 case MOVE_WALK:
9128 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9129 break;
9130 case MOVE_RUN:
9131 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9132 break;
9133 case MOVE_RUN_BACK:
9134 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9135 break;
9136 case MOVE_SWIM:
9137 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9138 break;
9139 case MOVE_SWIM_BACK:
9140 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9141 break;
9142 case MOVE_TURN_RATE:
9143 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9144 break;
9145 case MOVE_FLIGHT:
9146 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9147 break;
9148 case MOVE_FLIGHT_BACK:
9149 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9150 break;
9151 case MOVE_PITCH_RATE:
9152 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9153 break;
9154 default:
9155 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9156 return;
9159 data.append(GetPackGUID());
9160 data << uint32(0); // movement flags
9161 data << uint16(0); // unk flags
9162 data << uint32(getMSTime());
9163 data << float(GetPositionX());
9164 data << float(GetPositionY());
9165 data << float(GetPositionZ());
9166 data << float(GetOrientation());
9167 data << uint32(0); // fall time
9168 data << float(GetSpeed(mtype));
9169 SendMessageToSet( &data, true );
9171 else
9173 if(GetTypeId() == TYPEID_PLAYER)
9175 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9176 // and do it only for real sent packets and use run for run/mounted as client expected
9177 ++((Player*)this)->m_forced_speed_changes[mtype];
9180 switch(mtype)
9182 case MOVE_WALK:
9183 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9184 break;
9185 case MOVE_RUN:
9186 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9187 break;
9188 case MOVE_RUN_BACK:
9189 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9190 break;
9191 case MOVE_SWIM:
9192 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9193 break;
9194 case MOVE_SWIM_BACK:
9195 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9196 break;
9197 case MOVE_TURN_RATE:
9198 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9199 break;
9200 case MOVE_FLIGHT:
9201 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9202 break;
9203 case MOVE_FLIGHT_BACK:
9204 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9205 break;
9206 case MOVE_PITCH_RATE:
9207 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9208 break;
9209 default:
9210 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9211 return;
9213 data.append(GetPackGUID());
9214 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9215 if (mtype == MOVE_RUN)
9216 data << uint8(0); // new 2.1.0
9217 data << float(GetSpeed(mtype));
9218 SendMessageToSet( &data, true );
9220 if(Pet* pet = GetPet())
9221 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9224 void Unit::SetHover(bool on)
9226 if(on)
9227 CastSpell(this,11010,true);
9228 else
9229 RemoveAurasDueToSpell(11010);
9232 void Unit::setDeathState(DeathState s)
9234 if (s != ALIVE && s!= JUST_ALIVED)
9236 CombatStop();
9237 DeleteThreatList();
9238 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9240 if(IsNonMeleeSpellCasted(false))
9241 InterruptNonMeleeSpells(false);
9244 if (s == JUST_DIED)
9246 RemoveAllAurasOnDeath();
9247 UnsummonAllTotems();
9249 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9250 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9251 // remove aurastates allowing special moves
9252 ClearAllReactives();
9253 ClearDiminishings();
9255 else if(s == JUST_ALIVED)
9257 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9260 if (m_deathState != ALIVE && s == ALIVE)
9262 //_ApplyAllAuraMods();
9264 m_deathState = s;
9267 /*########################################
9268 ######## ########
9269 ######## AGGRO SYSTEM ########
9270 ######## ########
9271 ########################################*/
9272 bool Unit::CanHaveThreatList() const
9274 // only creatures can have threat list
9275 if( GetTypeId() != TYPEID_UNIT )
9276 return false;
9278 // only alive units can have threat list
9279 if( !isAlive() )
9280 return false;
9282 // totems can not have threat list
9283 if( ((Creature*)this)->isTotem() )
9284 return false;
9286 // vehicles can not have threat list
9287 if( ((Creature*)this)->isVehicle() )
9288 return false;
9290 // pets can not have a threat list, unless they are controlled by a creature
9291 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9292 return false;
9294 return true;
9297 //======================================================================
9299 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9301 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9302 return threat;
9304 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9306 return threat * m_threatModifier[school];
9309 //======================================================================
9311 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9313 // Only mobs can manage threat lists
9314 if(CanHaveThreatList())
9315 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9318 //======================================================================
9320 void Unit::DeleteThreatList()
9322 m_ThreatManager.clearReferences();
9325 //======================================================================
9327 void Unit::TauntApply(Unit* taunter)
9329 assert(GetTypeId()== TYPEID_UNIT);
9331 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9332 return;
9334 if(!CanHaveThreatList())
9335 return;
9337 Unit *target = getVictim();
9338 if(target && target == taunter)
9339 return;
9341 SetInFront(taunter);
9342 if (((Creature*)this)->AI())
9343 ((Creature*)this)->AI()->AttackStart(taunter);
9345 m_ThreatManager.tauntApply(taunter);
9348 //======================================================================
9350 void Unit::TauntFadeOut(Unit *taunter)
9352 assert(GetTypeId()== TYPEID_UNIT);
9354 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9355 return;
9357 if(!CanHaveThreatList())
9358 return;
9360 Unit *target = getVictim();
9361 if(!target || target != taunter)
9362 return;
9364 if(m_ThreatManager.isThreatListEmpty())
9366 if(((Creature*)this)->AI())
9367 ((Creature*)this)->AI()->EnterEvadeMode();
9368 return;
9371 m_ThreatManager.tauntFadeOut(taunter);
9372 target = m_ThreatManager.getHostilTarget();
9374 if (target && target != taunter)
9376 SetInFront(target);
9377 if (((Creature*)this)->AI())
9378 ((Creature*)this)->AI()->AttackStart(target);
9382 //======================================================================
9384 bool Unit::SelectHostilTarget()
9386 //function provides main threat functionality
9387 //next-victim-selection algorithm and evade mode are called
9388 //threat list sorting etc.
9390 assert(GetTypeId()== TYPEID_UNIT);
9392 if (!this->isAlive())
9393 return false;
9394 //This function only useful once AI has been initialized
9395 if (!((Creature*)this)->AI())
9396 return false;
9398 Unit* target = NULL;
9400 // First checking if we have some taunt on us
9401 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9402 if ( !tauntAuras.empty() )
9404 Unit* caster;
9406 // The last taunt aura caster is alive an we are happy to attack him
9407 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9408 return true;
9409 else if (tauntAuras.size() > 1)
9411 // We do not have last taunt aura caster but we have more taunt auras,
9412 // so find first available target
9414 // Auras are pushed_back, last caster will be on the end
9415 AuraList::const_iterator aura = --tauntAuras.end();
9418 --aura;
9419 if ( (caster = (*aura)->GetCaster()) &&
9420 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9422 target = caster;
9423 break;
9425 }while (aura != tauntAuras.begin());
9429 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9430 // No taunt aura or taunt aura caster is dead standart target selection
9431 target = m_ThreatManager.getHostilTarget();
9433 if(target)
9435 if(!hasUnitState(UNIT_STAT_STUNNED))
9436 SetInFront(target);
9437 ((Creature*)this)->AI()->AttackStart(target);
9438 return true;
9441 // no target but something prevent go to evade mode
9442 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9443 return false;
9445 // last case when creature don't must go to evade mode:
9446 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9447 // for example at owner command to pet attack some far away creature
9448 // Note: creature not have targeted movement generator but have attacker in this case
9449 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9451 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9453 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9454 return false;
9458 // enter in evade mode in other case
9459 ((Creature*)this)->AI()->EnterEvadeMode();
9461 return false;
9464 //======================================================================
9465 //======================================================================
9466 //======================================================================
9468 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9470 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9472 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9474 int32 level = int32(getLevel());
9475 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9476 level = (int32)spellProto->maxLevel;
9477 else if (level < (int32)spellProto->baseLevel)
9478 level = (int32)spellProto->baseLevel;
9479 level-= (int32)spellProto->spellLevel;
9481 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9482 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9483 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9484 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9485 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9487 // range can have possitive and negative values, so order its for irand
9488 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9489 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9490 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9492 int32 value = basePoints + randvalue;
9493 //random damage
9494 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9495 value += (int32)(comboDamage * comboPoints);
9497 if(Player* modOwner = GetSpellModOwner())
9499 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9500 switch(effect_index)
9502 case 0:
9503 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9504 break;
9505 case 1:
9506 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9507 break;
9508 case 2:
9509 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9510 break;
9514 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9515 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9516 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9517 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9519 return value;
9522 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9524 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9526 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9528 int32 minduration = GetSpellDuration(spellProto);
9529 int32 maxduration = GetSpellMaxDuration(spellProto);
9531 int32 duration;
9533 if( minduration != -1 && minduration != maxduration )
9534 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9535 else
9536 duration = minduration;
9538 if (duration > 0)
9540 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9541 // Find total mod value (negative bonus)
9542 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9543 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9544 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9545 // Find max mod (negative bonus)
9546 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9548 int32 durationMod = 0;
9549 // Select strongest negative mod
9550 if (durationMod_always > durationMod_not_stack)
9551 durationMod = durationMod_not_stack;
9552 else
9553 durationMod = durationMod_always;
9555 if (durationMod != 0)
9556 duration = int32(int64(duration) * (100+durationMod) /100);
9558 if (duration < 0) duration = 0;
9561 return duration;
9564 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9566 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9568 if(i->DRGroup != group)
9569 continue;
9571 if(!i->hitCount)
9572 return DIMINISHING_LEVEL_1;
9574 if(!i->hitTime)
9575 return DIMINISHING_LEVEL_1;
9577 // If last spell was casted more than 15 seconds ago - reset the count.
9578 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9580 i->hitCount = DIMINISHING_LEVEL_1;
9581 return DIMINISHING_LEVEL_1;
9583 // or else increase the count.
9584 else
9586 return DiminishingLevels(i->hitCount);
9589 return DIMINISHING_LEVEL_1;
9592 void Unit::IncrDiminishing(DiminishingGroup group)
9594 // Checking for existing in the table
9595 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9597 if(i->DRGroup != group)
9598 continue;
9599 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9600 i->hitCount += 1;
9601 return;
9603 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9606 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9608 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9609 return;
9611 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9612 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9614 // test pet/charm masters instead pets/charmeds
9615 Unit const* targetOwner = GetCharmerOrOwner();
9616 Unit const* casterOwner = caster->GetCharmerOrOwner();
9618 Unit const* target = targetOwner ? targetOwner : this;
9619 Unit const* source = casterOwner ? casterOwner : caster;
9621 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9622 duration = 10000;
9625 float mod = 1.0f;
9627 // Some diminishings applies to mobs too (for example, Stun)
9628 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9630 DiminishingLevels diminish = Level;
9631 switch(diminish)
9633 case DIMINISHING_LEVEL_1: break;
9634 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9635 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9636 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9637 default: break;
9641 duration = int32(duration * mod);
9644 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9646 // Checking for existing in the table
9647 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9649 if(i->DRGroup != group)
9650 continue;
9652 if(apply)
9653 i->stack += 1;
9654 else if(i->stack)
9656 i->stack -= 1;
9657 // Remember time after last aura from group removed
9658 if (i->stack == 0)
9659 i->hitTime = getMSTime();
9661 break;
9665 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9667 return ObjectAccessor::GetUnit(object,guid);
9670 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9672 return isVisibleForOrDetect(u, false, inVisibleList, false);
9675 uint32 Unit::GetCreatureType() const
9677 if(GetTypeId() == TYPEID_PLAYER)
9679 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
9680 if(ssEntry && ssEntry->creatureType > 0)
9681 return ssEntry->creatureType;
9682 else
9683 return CREATURE_TYPE_HUMANOID;
9685 else
9686 return ((Creature*)this)->GetCreatureInfo()->type;
9689 /*#######################################
9690 ######## ########
9691 ######## STAT SYSTEM ########
9692 ######## ########
9693 #######################################*/
9695 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9697 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9699 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9700 return false;
9703 float val = 1.0f;
9705 switch(modifierType)
9707 case BASE_VALUE:
9708 case TOTAL_VALUE:
9709 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9710 break;
9711 case BASE_PCT:
9712 case TOTAL_PCT:
9713 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9714 amount = -200.0f;
9716 val = (100.0f + amount) / 100.0f;
9717 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9718 break;
9720 default:
9721 break;
9724 if(!CanModifyStats())
9725 return false;
9727 switch(unitMod)
9729 case UNIT_MOD_STAT_STRENGTH:
9730 case UNIT_MOD_STAT_AGILITY:
9731 case UNIT_MOD_STAT_STAMINA:
9732 case UNIT_MOD_STAT_INTELLECT:
9733 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9735 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9736 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9738 case UNIT_MOD_MANA:
9739 case UNIT_MOD_RAGE:
9740 case UNIT_MOD_FOCUS:
9741 case UNIT_MOD_ENERGY:
9742 case UNIT_MOD_HAPPINESS:
9743 case UNIT_MOD_RUNE:
9744 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9746 case UNIT_MOD_RESISTANCE_HOLY:
9747 case UNIT_MOD_RESISTANCE_FIRE:
9748 case UNIT_MOD_RESISTANCE_NATURE:
9749 case UNIT_MOD_RESISTANCE_FROST:
9750 case UNIT_MOD_RESISTANCE_SHADOW:
9751 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9753 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9754 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9756 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9757 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9758 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9760 default:
9761 break;
9764 return true;
9767 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9769 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9771 sLog.outError("trial to access non existed modifier value from UnitMods!");
9772 return 0.0f;
9775 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9776 return 0.0f;
9778 return m_auraModifiersGroup[unitMod][modifierType];
9781 float Unit::GetTotalStatValue(Stats stat) const
9783 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9785 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9786 return 0.0f;
9788 // value = ((base_value * base_pct) + total_value) * total_pct
9789 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9790 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9791 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9792 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9794 return value;
9797 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9799 if(unitMod >= UNIT_MOD_END)
9801 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
9802 return 0.0f;
9805 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9806 return 0.0f;
9808 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9809 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9810 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9811 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9813 return value;
9816 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9818 SpellSchools school = SPELL_SCHOOL_NORMAL;
9820 switch(unitMod)
9822 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9823 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9824 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9825 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9826 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9827 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9829 default:
9830 break;
9833 return school;
9836 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9838 Stats stat = STAT_STRENGTH;
9840 switch(unitMod)
9842 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9843 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9844 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9845 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9846 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9848 default:
9849 break;
9852 return stat;
9855 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9857 switch(unitMod)
9859 case UNIT_MOD_MANA: return POWER_MANA;
9860 case UNIT_MOD_RAGE: return POWER_RAGE;
9861 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9862 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9863 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9864 case UNIT_MOD_RUNE: return POWER_RUNE;
9865 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9868 return POWER_MANA;
9871 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9873 if (attType == RANGED_ATTACK)
9875 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
9876 if (ap < 0)
9877 return 0.0f;
9878 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
9880 else
9882 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
9883 if (ap < 0)
9884 return 0.0f;
9885 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
9889 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9891 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9892 return 0.0f;
9894 return m_weaponDamage[attType][type];
9897 void Unit::SetLevel(uint32 lvl)
9899 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9901 // group update
9902 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9903 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9906 void Unit::SetHealth(uint32 val)
9908 uint32 maxHealth = GetMaxHealth();
9909 if(maxHealth < val)
9910 val = maxHealth;
9912 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9914 // group update
9915 if(GetTypeId() == TYPEID_PLAYER)
9917 if(((Player*)this)->GetGroup())
9918 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9920 else if(((Creature*)this)->isPet())
9922 Pet *pet = ((Pet*)this);
9923 if(pet->isControlled())
9925 Unit *owner = GetOwner();
9926 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9927 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
9932 void Unit::SetMaxHealth(uint32 val)
9934 uint32 health = GetHealth();
9935 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
9937 // group update
9938 if(GetTypeId() == TYPEID_PLAYER)
9940 if(((Player*)this)->GetGroup())
9941 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
9943 else if(((Creature*)this)->isPet())
9945 Pet *pet = ((Pet*)this);
9946 if(pet->isControlled())
9948 Unit *owner = GetOwner();
9949 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9950 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
9954 if(val < health)
9955 SetHealth(val);
9958 void Unit::SetPower(Powers power, uint32 val)
9960 if(GetPower(power) == val)
9961 return;
9963 uint32 maxPower = GetMaxPower(power);
9964 if(maxPower < val)
9965 val = maxPower;
9967 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
9969 WorldPacket data(SMSG_POWER_UPDATE);
9970 data.append(GetPackGUID());
9971 data << uint8(power);
9972 data << uint32(val);
9973 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
9975 // group update
9976 if(GetTypeId() == TYPEID_PLAYER)
9978 if(((Player*)this)->GetGroup())
9979 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
9981 else if(((Creature*)this)->isPet())
9983 Pet *pet = ((Pet*)this);
9984 if(pet->isControlled())
9986 Unit *owner = GetOwner();
9987 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9988 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
9991 // Update the pet's character sheet with happiness damage bonus
9992 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
9994 pet->UpdateDamagePhysical(BASE_ATTACK);
9999 void Unit::SetMaxPower(Powers power, uint32 val)
10001 uint32 cur_power = GetPower(power);
10002 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
10004 // group update
10005 if(GetTypeId() == TYPEID_PLAYER)
10007 if(((Player*)this)->GetGroup())
10008 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10010 else if(((Creature*)this)->isPet())
10012 Pet *pet = ((Pet*)this);
10013 if(pet->isControlled())
10015 Unit *owner = GetOwner();
10016 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10017 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10021 if(val < cur_power)
10022 SetPower(power, val);
10025 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
10027 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
10029 // group update
10030 if(GetTypeId() == TYPEID_PLAYER)
10032 if(((Player*)this)->GetGroup())
10033 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10035 else if(((Creature*)this)->isPet())
10037 Pet *pet = ((Pet*)this);
10038 if(pet->isControlled())
10040 Unit *owner = GetOwner();
10041 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10042 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10047 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
10049 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
10051 // group update
10052 if(GetTypeId() == TYPEID_PLAYER)
10054 if(((Player*)this)->GetGroup())
10055 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10057 else if(((Creature*)this)->isPet())
10059 Pet *pet = ((Pet*)this);
10060 if(pet->isControlled())
10062 Unit *owner = GetOwner();
10063 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10064 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10069 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10071 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10072 if(apply)
10073 tAuraProcTriggerDamage.push_back(aura);
10074 else
10075 tAuraProcTriggerDamage.remove(aura);
10078 uint32 Unit::GetCreatePowers( Powers power ) const
10080 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10081 switch(power)
10083 case POWER_MANA: return GetCreateMana();
10084 case POWER_RAGE: return 1000;
10085 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10086 case POWER_ENERGY: return 100;
10087 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10088 case POWER_RUNIC_POWER: return 1000;
10091 return 0;
10094 void Unit::AddToWorld()
10096 Object::AddToWorld();
10099 void Unit::RemoveFromWorld()
10101 // cleanup
10102 if(IsInWorld())
10104 RemoveNotOwnSingleTargetAuras();
10107 Object::RemoveFromWorld();
10110 void Unit::CleanupsBeforeDelete()
10112 if(m_uint32Values) // only for fully created object
10114 InterruptNonMeleeSpells(true);
10115 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10116 CombatStop();
10117 ClearComboPointHolders();
10118 DeleteThreatList();
10119 getHostilRefManager().setOnlineOfflineState(false);
10120 RemoveAllAuras();
10121 RemoveAllGameObjects();
10122 RemoveAllDynObjects();
10123 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10125 RemoveFromWorld();
10128 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10130 if(!m_charmInfo)
10131 m_charmInfo = new CharmInfo(charm);
10132 return m_charmInfo;
10135 CharmInfo::CharmInfo(Unit* unit)
10136 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10138 for(int i =0; i<4; ++i)
10140 m_charmspells[i].spellId = 0;
10141 m_charmspells[i].active = ACT_DISABLED;
10145 void CharmInfo::InitPetActionBar()
10147 // the first 3 SpellOrActions are attack, follow and stay
10148 for(uint32 i = 0; i < 3; i++)
10150 PetActionBar[i].Type = ACT_COMMAND;
10151 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
10153 PetActionBar[i + 7].Type = ACT_REACTION;
10154 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
10156 for(uint32 i=0; i < 4; i++)
10158 PetActionBar[i + 3].Type = ACT_DISABLED;
10159 PetActionBar[i + 3].SpellOrAction = 0;
10163 void CharmInfo::InitEmptyActionBar()
10165 for(uint32 x = 1; x < 10; ++x)
10167 PetActionBar[x].Type = ACT_PASSIVE;
10168 PetActionBar[x].SpellOrAction = 0;
10170 PetActionBar[0].Type = ACT_COMMAND;
10171 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
10174 void CharmInfo::InitPossessCreateSpells()
10176 InitEmptyActionBar(); //charm action bar
10178 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
10179 return;
10181 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10183 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10184 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10185 else
10186 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10190 void CharmInfo::InitCharmCreateSpells()
10192 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10194 InitEmptyActionBar();
10195 return;
10198 InitPetActionBar();
10200 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10202 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10203 m_charmspells[x].spellId = spellId;
10205 if(!spellId)
10206 continue;
10208 if (IsPassiveSpell(spellId))
10210 m_unit->CastSpell(m_unit, spellId, true);
10211 m_charmspells[x].active = ACT_PASSIVE;
10213 else
10215 ActiveStates newstate;
10216 bool onlyselfcast = true;
10217 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10219 if(!spellInfo) onlyselfcast = false;
10220 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10222 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10223 onlyselfcast = false;
10226 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10227 newstate = ACT_DISABLED;
10228 else
10229 newstate = ACT_PASSIVE;
10231 AddSpellToAB(0, spellId, newstate);
10236 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
10238 for(uint8 i = 0; i < 10; i++)
10240 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
10242 PetActionBar[i].SpellOrAction = newid;
10243 if(!oldid)
10245 if(newstate == ACT_DECIDE)
10246 PetActionBar[i].Type = ACT_DISABLED;
10247 else
10248 PetActionBar[i].Type = newstate;
10251 return true;
10254 return false;
10257 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10259 if(IsPassiveSpell(spellid))
10260 return;
10262 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10264 if(spellid == m_charmspells[x].spellId)
10266 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10271 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10273 m_petnumber = petnumber;
10274 if(statwindow)
10275 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10276 else
10277 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10280 bool Unit::isFrozen() const
10282 return HasAuraState(AURA_STATE_FROZEN);
10285 struct ProcTriggeredData
10287 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10288 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10289 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10291 SpellProcEventEntry const *spellProcEvent;
10292 Aura* triggeredByAura;
10293 Unit::spellEffectPair triggeredByAura_SpellPair;
10296 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10297 typedef std::list< uint32> RemoveSpellList;
10299 // List of auras that CAN be trigger but may not exist in spell_proc_event
10300 // in most case need for drop charges
10301 // in some types of aura need do additional check
10302 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10303 bool InitTriggerAuraData()
10305 for (int i=0;i<TOTAL_AURAS;i++)
10307 isTriggerAura[i]=false;
10308 isNonTriggerAura[i] = false;
10310 isTriggerAura[SPELL_AURA_DUMMY] = true;
10311 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10312 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10313 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10314 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10315 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10316 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10317 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10318 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10319 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10320 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10321 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10322 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
10323 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10324 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10325 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10326 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10327 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10328 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10329 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10330 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10331 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10332 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10333 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10334 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10335 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10336 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10337 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10338 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
10340 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10341 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
10343 return true;
10346 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10348 uint32 procEx = PROC_EX_NONE;
10349 // Check victim state
10350 if (missCondition!=SPELL_MISS_NONE)
10351 switch (missCondition)
10353 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10354 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10355 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10356 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10357 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10358 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10359 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10360 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10361 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10362 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10363 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10364 default:
10365 break;
10367 else
10369 // On block
10370 if (damageInfo->blocked)
10371 procEx|=PROC_EX_BLOCK;
10372 // On absorb
10373 if (damageInfo->absorb)
10374 procEx|=PROC_EX_ABSORB;
10375 // On crit
10376 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10377 procEx|=PROC_EX_CRITICAL_HIT;
10378 else
10379 procEx|=PROC_EX_NORMAL_HIT;
10381 return procEx;
10384 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10386 // For melee/ranged based attack need update skills and set some Aura states
10387 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10389 // Update skills here for players
10390 if (GetTypeId() == TYPEID_PLAYER)
10392 // On melee based hit/miss/resist need update skill (for victim and attacker)
10393 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10395 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10396 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10398 // Update defence if player is victim and parry/dodge/block
10399 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10400 ((Player*)this)->UpdateDefense();
10402 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10403 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10405 // for victim
10406 if (isVictim)
10408 // if victim and dodge attack
10409 if (procExtra&PROC_EX_DODGE)
10411 //Update AURA_STATE on dodge
10412 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10414 ModifyAuraState(AURA_STATE_DEFENSE, true);
10415 StartReactiveTimer( REACTIVE_DEFENSE );
10418 // if victim and parry attack
10419 if (procExtra & PROC_EX_PARRY)
10421 // For Hunters only Counterattack (skip Mongoose bite)
10422 if (getClass() == CLASS_HUNTER)
10424 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10425 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10427 else
10429 ModifyAuraState(AURA_STATE_DEFENSE, true);
10430 StartReactiveTimer( REACTIVE_DEFENSE );
10433 // if and victim block attack
10434 if (procExtra & PROC_EX_BLOCK)
10436 ModifyAuraState(AURA_STATE_DEFENSE,true);
10437 StartReactiveTimer( REACTIVE_DEFENSE );
10440 else //For attacker
10442 // Overpower on victim dodge
10443 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10445 ((Player*)this)->AddComboPoints(pTarget, 1);
10446 StartReactiveTimer( REACTIVE_OVERPOWER );
10452 RemoveSpellList removedSpells;
10453 ProcTriggeredList procTriggered;
10454 // Fill procTriggered list
10455 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10457 SpellProcEventEntry const* spellProcEvent = NULL;
10458 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10459 continue;
10461 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10464 // Nothing found
10465 if (procTriggered.empty())
10466 return;
10468 // Handle effects proceed this time
10469 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10471 // Some auras can be deleted in function called in this loop (except first, ofc)
10472 // Until storing auars in std::multimap to hard check deleting by another way
10473 if(i != procTriggered.begin())
10475 bool found = false;
10476 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10477 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10478 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10480 if(itr->second==i->triggeredByAura)
10482 found = true;
10483 break;
10486 if(!found)
10488 // 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);
10489 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10490 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
10491 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10492 // sLog.outDebug(" <end of list>");
10493 continue;
10497 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10498 Aura *triggeredByAura = i->triggeredByAura;
10499 Modifier *auraModifier = triggeredByAura->GetModifier();
10500 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10501 uint32 effIndex = triggeredByAura->GetEffIndex();
10502 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10503 // For players set spell cooldown if need
10504 uint32 cooldown = 0;
10505 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10506 cooldown = spellProcEvent->cooldown;
10508 switch(auraModifier->m_auraname)
10510 case SPELL_AURA_PROC_TRIGGER_SPELL:
10512 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10513 // Don`t drop charge or add cooldown for not started trigger
10514 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10515 continue;
10516 break;
10518 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10520 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());
10521 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10522 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10523 SendSpellNonMeleeDamageLog(&damageInfo);
10524 DealSpellDamage(&damageInfo, true);
10525 break;
10527 case SPELL_AURA_MANA_SHIELD:
10528 case SPELL_AURA_DUMMY:
10530 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());
10531 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10532 continue;
10533 break;
10535 case SPELL_AURA_MOD_HASTE:
10537 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());
10538 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10539 continue;
10540 break;
10542 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10544 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());
10545 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10546 continue;
10547 break;
10549 case SPELL_AURA_PRAYER_OF_MENDING:
10551 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10552 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10554 HandleMeandingAuraProc(triggeredByAura);
10555 break;
10557 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10559 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());
10561 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10562 continue;
10563 break;
10565 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
10566 // Skip melee hits or instant cast spells
10567 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10568 continue;
10569 break;
10570 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10571 // Skip Melee hits and spells ws wrong school
10572 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10573 continue;
10574 break;
10575 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10576 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10577 // Skip melee hits and spells ws wrong school or zero cost
10578 if (procSpell == NULL ||
10579 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10580 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10581 continue;
10582 break;
10583 case SPELL_AURA_MECHANIC_IMMUNITY:
10584 // Compare mechanic
10585 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10586 continue;
10587 break;
10588 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10589 // Compare mechanic
10590 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10591 continue;
10592 break;
10593 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
10594 // Compare casters
10595 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
10596 continue;
10597 break;
10598 default:
10599 // nothing do, just charges counter
10600 break;
10602 // Remove charge (aura can be removed by triggers)
10603 if(useCharges)
10605 // need found aura on drop (can be dropped by triggers)
10606 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10607 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10608 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10610 // If last charge dropped add spell to remove list
10611 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10613 removedSpells.push_back(triggeredByAura->GetId());
10614 break;
10619 if (!removedSpells.empty())
10621 // Sort spells and remove dublicates
10622 removedSpells.sort();
10623 removedSpells.unique();
10624 // Remove auras from removedAuras
10625 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10626 RemoveAurasDueToSpell(*i);
10630 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10632 return SPELL_SCHOOL_MASK_NORMAL;
10635 Player* Unit::GetSpellModOwner()
10637 if(GetTypeId()==TYPEID_PLAYER)
10638 return (Player*)this;
10639 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10641 Unit* owner = GetOwner();
10642 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10643 return (Player*)owner;
10645 return NULL;
10648 ///----------Pet responses methods-----------------
10649 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
10651 if(msg == SPELL_CAST_OK)
10652 return;
10654 Unit *owner = GetCharmerOrOwner();
10655 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10656 return;
10658 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10659 data << uint8(0); // cast count?
10660 data << uint32(spellid);
10661 data << uint8(msg);
10662 // uint32 for some reason
10663 // uint32 for some reason
10664 ((Player*)owner)->GetSession()->SendPacket(&data);
10667 void Unit::SendPetActionFeedback (uint8 msg)
10669 Unit* owner = GetOwner();
10670 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10671 return;
10673 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10674 data << uint8(msg);
10675 ((Player*)owner)->GetSession()->SendPacket(&data);
10678 void Unit::SendPetTalk (uint32 pettalk)
10680 Unit* owner = GetOwner();
10681 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10682 return;
10684 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10685 data << uint64(GetGUID());
10686 data << uint32(pettalk);
10687 ((Player*)owner)->GetSession()->SendPacket(&data);
10690 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10692 Unit* owner = GetOwner();
10693 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10694 return;
10696 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10697 data << uint64(GetGUID());
10698 data << uint8(0x0); // flags (0x1, 0x2)
10699 data << uint32(spellid);
10700 data << uint32(cooltime);
10702 ((Player*)owner)->GetSession()->SendPacket(&data);
10705 void Unit::SendPetClearCooldown (uint32 spellid)
10707 Unit* owner = GetOwner();
10708 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10709 return;
10711 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10712 data << uint32(spellid);
10713 data << uint64(GetGUID());
10714 ((Player*)owner)->GetSession()->SendPacket(&data);
10717 void Unit::SendPetAIReaction(uint64 guid)
10719 Unit* owner = GetOwner();
10720 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10721 return;
10723 WorldPacket data(SMSG_AI_REACTION, 12);
10724 data << uint64(guid) << uint32(00000002);
10725 ((Player*)owner)->GetSession()->SendPacket(&data);
10728 ///----------End of Pet responses methods----------
10730 void Unit::StopMoving()
10732 clearUnitState(UNIT_STAT_MOVING);
10734 // send explicit stop packet
10735 // rely on vmaps here because for example stormwind is in air
10736 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10737 //if (fabs(GetPositionZ() - z) < 2.0f)
10738 // Relocate(GetPositionX(), GetPositionY(), z);
10739 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10741 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10743 // update position and orientation;
10744 WorldPacket data;
10745 BuildHeartBeatMsg(&data);
10746 SendMessageToSet(&data,false);
10749 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10751 if( apply )
10753 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10754 return;
10756 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10758 GetMotionMaster()->MovementExpired(false);
10759 CastStop(GetGUID()==casterGUID ? spellID : 0);
10761 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10763 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10765 else
10767 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10769 GetMotionMaster()->MovementExpired(false);
10771 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10773 // restore appropriate movement generator
10774 if(getVictim())
10775 GetMotionMaster()->MoveChase(getVictim());
10776 else
10777 GetMotionMaster()->Initialize();
10779 // attack caster if can
10780 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10781 if(caster && caster != getVictim() && ((Creature*)this)->AI())
10782 ((Creature*)this)->AI()->AttackStart(caster);
10786 if (GetTypeId() == TYPEID_PLAYER)
10787 ((Player*)this)->SetClientControl(this, !apply);
10790 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10792 if( apply )
10794 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10796 CastStop(GetGUID()==casterGUID ? spellID : 0);
10798 GetMotionMaster()->MoveConfused();
10800 else
10802 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10804 GetMotionMaster()->MovementExpired(false);
10806 if (GetTypeId() == TYPEID_UNIT)
10808 // if in combat restore movement generator
10809 if(getVictim())
10810 GetMotionMaster()->MoveChase(getVictim());
10814 if(GetTypeId() == TYPEID_PLAYER)
10815 ((Player*)this)->SetClientControl(this, !apply);
10818 bool Unit::IsSitState() const
10820 uint8 s = getStandState();
10821 return
10822 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
10823 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
10824 s == UNIT_STAND_STATE_SIT;
10827 bool Unit::IsStandState() const
10829 uint8 s = getStandState();
10830 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
10833 void Unit::SetStandState(uint8 state)
10835 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10837 if (IsStandState())
10838 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10840 if(GetTypeId()==TYPEID_PLAYER)
10842 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10843 data << (uint8)state;
10844 ((Player*)this)->GetSession()->SendPacket(&data);
10848 bool Unit::IsPolymorphed() const
10850 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10853 void Unit::SetDisplayId(uint32 modelId)
10855 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10857 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10859 Pet *pet = ((Pet*)this);
10860 if(!pet->isControlled())
10861 return;
10862 Unit *owner = GetOwner();
10863 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10864 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10868 void Unit::ClearComboPointHolders()
10870 while(!m_ComboPointHolders.empty())
10872 uint32 lowguid = *m_ComboPointHolders.begin();
10874 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10875 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10876 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10877 else
10878 m_ComboPointHolders.erase(lowguid); // or remove manually
10882 void Unit::ClearAllReactives()
10884 for(int i=0; i < MAX_REACTIVE; ++i)
10885 m_reactiveTimer[i] = 0;
10887 if (HasAuraState( AURA_STATE_DEFENSE))
10888 ModifyAuraState(AURA_STATE_DEFENSE, false);
10889 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10890 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10891 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10892 ((Player*)this)->ClearComboPoints();
10895 void Unit::UpdateReactives( uint32 p_time )
10897 for(int i = 0; i < MAX_REACTIVE; ++i)
10899 ReactiveType reactive = ReactiveType(i);
10901 if(!m_reactiveTimer[reactive])
10902 continue;
10904 if ( m_reactiveTimer[reactive] <= p_time)
10906 m_reactiveTimer[reactive] = 0;
10908 switch ( reactive )
10910 case REACTIVE_DEFENSE:
10911 if (HasAuraState(AURA_STATE_DEFENSE))
10912 ModifyAuraState(AURA_STATE_DEFENSE, false);
10913 break;
10914 case REACTIVE_HUNTER_PARRY:
10915 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10916 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10917 break;
10918 case REACTIVE_OVERPOWER:
10919 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10920 ((Player*)this)->ClearComboPoints();
10921 break;
10922 default:
10923 break;
10926 else
10928 m_reactiveTimer[reactive] -= p_time;
10933 Unit* Unit::SelectNearbyTarget() const
10935 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
10936 Cell cell(p);
10937 cell.data.Part.reserved = ALL_DISTRICT;
10938 cell.SetNoCreate();
10940 std::list<Unit *> targets;
10943 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
10944 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
10946 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
10947 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
10949 CellLock<GridReadGuard> cell_lock(cell, p);
10950 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
10951 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
10954 // remove current target
10955 if(getVictim())
10956 targets.remove(getVictim());
10958 // remove not LoS targets
10959 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
10961 if(!IsWithinLOSInMap(*tIter))
10963 std::list<Unit *>::iterator tIter2 = tIter;
10964 ++tIter;
10965 targets.erase(tIter2);
10967 else
10968 ++tIter;
10971 // no appropriate targets
10972 if(targets.empty())
10973 return NULL;
10975 // select random
10976 uint32 rIdx = urand(0,targets.size()-1);
10977 std::list<Unit *>::const_iterator tcIter = targets.begin();
10978 for(uint32 i = 0; i < rIdx; ++i)
10979 ++tcIter;
10981 return *tcIter;
10984 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
10986 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
10988 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
10989 return true;
10991 return false;
10994 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
10996 if(val > 0)
10998 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
10999 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
11001 else
11003 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
11004 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
11008 void Unit::ApplyCastTimePercentMod(float val, bool apply )
11010 if(val > 0)
11011 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
11012 else
11013 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
11016 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
11018 // Not apply this to creature casted spells with casttime==0
11019 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
11020 return 3500;
11022 if (CastingTime > 7000) CastingTime = 7000;
11023 if (CastingTime < 1500) CastingTime = 1500;
11025 if(damagetype == DOT && !IsChanneledSpell(spellProto))
11026 CastingTime = 3500;
11028 int32 overTime = 0;
11029 uint8 effects = 0;
11030 bool DirectDamage = false;
11031 bool AreaEffect = false;
11033 for ( uint32 i=0; i<3;i++)
11035 switch ( spellProto->Effect[i] )
11037 case SPELL_EFFECT_SCHOOL_DAMAGE:
11038 case SPELL_EFFECT_POWER_DRAIN:
11039 case SPELL_EFFECT_HEALTH_LEECH:
11040 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
11041 case SPELL_EFFECT_POWER_BURN:
11042 case SPELL_EFFECT_HEAL:
11043 DirectDamage = true;
11044 break;
11045 case SPELL_EFFECT_APPLY_AURA:
11046 switch ( spellProto->EffectApplyAuraName[i] )
11048 case SPELL_AURA_PERIODIC_DAMAGE:
11049 case SPELL_AURA_PERIODIC_HEAL:
11050 case SPELL_AURA_PERIODIC_LEECH:
11051 if ( GetSpellDuration(spellProto) )
11052 overTime = GetSpellDuration(spellProto);
11053 break;
11054 default:
11055 // -5% per additional effect
11056 ++effects;
11057 break;
11059 default:
11060 break;
11063 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11064 AreaEffect = true;
11067 // Combined Spells with Both Over Time and Direct Damage
11068 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11070 // mainly for DoTs which are 3500 here otherwise
11071 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11072 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11073 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11074 // Portion to Over Time
11075 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
11077 if ( damagetype == DOT )
11078 CastingTime = uint32(CastingTime * PtOT);
11079 else if ( PtOT < 1.0f )
11080 CastingTime = uint32(CastingTime * (1 - PtOT));
11081 else
11082 CastingTime = 0;
11085 // Area Effect Spells receive only half of bonus
11086 if ( AreaEffect )
11087 CastingTime /= 2;
11089 // -5% of total per any additional effect
11090 for ( uint8 i=0; i<effects; ++i)
11092 if ( CastingTime > 175 )
11094 CastingTime -= 175;
11096 else
11098 CastingTime = 0;
11099 break;
11103 return CastingTime;
11106 void Unit::UpdateAuraForGroup(uint8 slot)
11108 if(GetTypeId() == TYPEID_PLAYER)
11110 Player* player = (Player*)this;
11111 if(player->GetGroup())
11113 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11114 player->SetAuraUpdateMask(slot);
11117 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11119 Pet *pet = ((Pet*)this);
11120 if(pet->isControlled())
11122 Unit *owner = GetOwner();
11123 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11125 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11126 pet->SetAuraUpdateMask(slot);
11132 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11134 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11135 return float(GetAttackTime(attType))/1000.0f;
11137 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11138 if (!Weapon)
11139 return 2.4; // fist attack
11141 switch (Weapon->GetProto()->InventoryType)
11143 case INVTYPE_2HWEAPON:
11144 return 3.3;
11145 case INVTYPE_RANGED:
11146 case INVTYPE_RANGEDRIGHT:
11147 case INVTYPE_THROWN:
11148 return 2.8;
11149 case INVTYPE_WEAPON:
11150 case INVTYPE_WEAPONMAINHAND:
11151 case INVTYPE_WEAPONOFFHAND:
11152 default:
11153 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11157 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11159 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11160 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11161 if ((*itr)->GetId() == spell_id)
11162 return *itr;
11164 return NULL;
11167 bool Unit::IsUnderLastManaUseEffect() const
11169 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11172 void Unit::SetContestedPvP(Player *attackedPlayer)
11174 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11176 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11177 return;
11179 player->SetContestedPvPTimer(30000);
11180 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11182 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11183 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11184 // call MoveInLineOfSight for nearby contested guards
11185 SetVisibility(GetVisibility());
11187 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11189 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11190 // call MoveInLineOfSight for nearby contested guards
11191 SetVisibility(GetVisibility());
11195 void Unit::AddPetAura(PetAura const* petSpell)
11197 m_petAuras.insert(petSpell);
11198 if(Pet* pet = GetPet())
11199 pet->CastPetAura(petSpell);
11202 void Unit::RemovePetAura(PetAura const* petSpell)
11204 m_petAuras.erase(petSpell);
11205 if(Pet* pet = GetPet())
11206 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11209 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11211 Pet* pet = new Pet(HUNTER_PET);
11213 if(!pet->CreateBaseAtCreature(creatureTarget))
11215 delete pet;
11216 return NULL;
11219 pet->SetOwnerGUID(GetGUID());
11220 pet->SetCreatorGUID(GetGUID());
11221 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11222 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11224 if(GetTypeId()==TYPEID_PLAYER)
11225 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11227 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11229 if(!pet->InitStatsForLevel(level))
11231 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11232 delete pet;
11233 return NULL;
11236 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11237 // this enables pet details window (Shift+P)
11238 pet->AIM_Initialize();
11239 pet->InitPetCreateSpells();
11240 pet->InitTalentForLevel();
11241 pet->SetHealth(pet->GetMaxHealth());
11243 return pet;
11246 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11248 SpellEntry const* spellProto = aura->GetSpellProto ();
11250 // Get proc Event Entry
11251 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11253 // Aura info stored here
11254 Modifier *mod = aura->GetModifier();
11255 // Skip this auras
11256 if (isNonTriggerAura[mod->m_auraname])
11257 return false;
11258 // If not trigger by default and spellProcEvent==NULL - skip
11259 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11260 return false;
11262 // Get EventProcFlag
11263 uint32 EventProcFlag;
11264 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11265 EventProcFlag = spellProcEvent->procFlags;
11266 else
11267 EventProcFlag = spellProto->procFlags; // else get from spell proto
11268 // Continue if no trigger exist
11269 if (!EventProcFlag)
11270 return false;
11272 // Check spellProcEvent data requirements
11273 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11274 return false;
11276 // In most cases req get honor or XP from kill
11277 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11279 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11280 // Shadow Word: Death - can trigger from every kill
11281 if (aura->GetId() == 32409)
11282 allow = true;
11283 if (!allow)
11284 return false;
11286 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11287 // But except periodic triggers (can triggered from self)
11288 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11289 return false;
11291 // Check if current equipment allows aura to proc
11292 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11294 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11296 Item *item = NULL;
11297 if(attType == BASE_ATTACK)
11298 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11299 else if (attType == OFF_ATTACK)
11300 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11301 else
11302 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11304 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11305 return false;
11307 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11308 return false;
11310 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11312 // Check if player is wearing shield
11313 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11314 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11315 return false;
11318 // Get chance from spell
11319 float chance = (float)spellProto->procChance;
11320 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11321 if(spellProcEvent && spellProcEvent->customChance)
11322 chance = spellProcEvent->customChance;
11323 // If PPM exist calculate chance from PPM
11324 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11326 uint32 WeaponSpeed = GetAttackTime(attType);
11327 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11329 // Apply chance modifer aura
11330 if(Player* modOwner = GetSpellModOwner())
11331 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11333 return roll_chance_f(chance);
11336 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11338 // aura can be deleted at casts
11339 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11340 uint32 effIdx = triggeredByAura->GetEffIndex();
11341 int32 heal = triggeredByAura->GetModifier()->m_amount;
11342 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11344 // jumps
11345 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11347 // current aura expire
11348 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11350 // next target selection
11351 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11353 float radius;
11354 if (spellProto->EffectRadiusIndex[effIdx])
11355 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11356 else
11357 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11359 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11361 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11363 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11365 // aura will applied from caster, but spell casted from current aura holder
11366 SpellModifier *mod = new SpellModifier;
11367 mod->op = SPELLMOD_CHARGES;
11368 mod->value = jumps-5; // negative
11369 mod->type = SPELLMOD_FLAT;
11370 mod->spellId = spellProto->Id;
11371 mod->mask = spellProto->SpellFamilyFlags;
11372 mod->mask2 = spellProto->SpellFamilyFlags2;
11374 caster->AddSpellMod(mod, true);
11375 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11376 caster->AddSpellMod(mod, false);
11381 // heal
11382 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11383 return true;
11386 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11388 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11390 if(!IS_UNIT_GUID(target_guid))
11391 return;
11393 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11394 if(!target)
11395 return;
11397 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11399 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11400 target->RemoveAura(iter);
11401 else
11402 ++iter;
11406 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
11408 WorldObject::SetPhaseMask(newPhaseMask,update);
11410 if(IsInWorld())
11411 if(Pet* pet = GetPet())
11412 pet->SetPhaseMask(newPhaseMask,true);
11415 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
11417 if(GetTypeId() == TYPEID_PLAYER)
11418 ((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));
11419 else
11421 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
11423 WorldPacket data;
11424 // Work strange for many spells: triggered active mover set for targeted player to creature
11425 //BuildTeleportAckMsg(&data, x, y, z, orientation);
11426 BuildHeartBeatMsg(&data);
11427 SendMessageToSet(&data, false);