[7770] Prevent access to possible deleted aura's spell proto in Aura::HandleModStealth.
[AHbot.git] / src / game / Spell.cpp
blob3629d0c4bf1daa37ba1720b232d270fb7567bca0
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 "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "Group.h"
37 #include "UpdateData.h"
38 #include "MapManager.h"
39 #include "ObjectAccessor.h"
40 #include "CellImpl.h"
41 #include "Policies/SingletonImp.h"
42 #include "SharedDefines.h"
43 #include "LootMgr.h"
44 #include "VMapFactory.h"
45 #include "BattleGround.h"
46 #include "Util.h"
48 #define SPELL_CHANNEL_UPDATE_INTERVAL (1*IN_MILISECONDS)
50 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
52 class PrioritizeManaPlayerWraper
54 friend struct PrioritizeMana;
56 public:
57 explicit PrioritizeManaPlayerWraper(Player* player) : player(player)
59 uint32 maxmana = player->GetMaxPower(POWER_MANA);
60 percentMana = maxmana ? player->GetPower(POWER_MANA) * 100 / maxmana : 101;
62 Player* getPlayer() const { return player; }
63 private:
64 Player* player;
65 uint32 percentMana;
68 struct PrioritizeMana
70 int operator()( PrioritizeManaPlayerWraper const& x, PrioritizeManaPlayerWraper const& y ) const
72 return x.percentMana < y.percentMana;
77 bool IsQuestTameSpell(uint32 spellId)
79 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
80 if (!spellproto) return false;
82 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
83 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
86 SpellCastTargets::SpellCastTargets()
88 m_unitTarget = NULL;
89 m_itemTarget = NULL;
90 m_GOTarget = NULL;
92 m_unitTargetGUID = 0;
93 m_GOTargetGUID = 0;
94 m_CorpseTargetGUID = 0;
95 m_itemTargetGUID = 0;
96 m_itemTargetEntry = 0;
98 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
99 m_strTarget = "";
100 m_targetMask = 0;
103 SpellCastTargets::~SpellCastTargets()
107 void SpellCastTargets::setUnitTarget(Unit *target)
109 if (!target)
110 return;
112 m_destX = target->GetPositionX();
113 m_destY = target->GetPositionY();
114 m_destZ = target->GetPositionZ();
115 m_unitTarget = target;
116 m_unitTargetGUID = target->GetGUID();
117 m_targetMask |= TARGET_FLAG_UNIT;
120 void SpellCastTargets::setDestination(float x, float y, float z)
122 m_destX = x;
123 m_destY = y;
124 m_destZ = z;
125 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
128 void SpellCastTargets::setSource(float x, float y, float z)
130 m_srcX = x;
131 m_srcY = y;
132 m_srcZ = z;
133 m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
136 void SpellCastTargets::setGOTarget(GameObject *target)
138 m_GOTarget = target;
139 m_GOTargetGUID = target->GetGUID();
140 // m_targetMask |= TARGET_FLAG_OBJECT;
143 void SpellCastTargets::setItemTarget(Item* item)
145 if(!item)
146 return;
148 m_itemTarget = item;
149 m_itemTargetGUID = item->GetGUID();
150 m_itemTargetEntry = item->GetEntry();
151 m_targetMask |= TARGET_FLAG_ITEM;
154 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
156 m_CorpseTargetGUID = corpse->GetGUID();
159 void SpellCastTargets::Update(Unit* caster)
161 m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL;
162 m_unitTarget = m_unitTargetGUID ?
163 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
164 NULL;
166 m_itemTarget = NULL;
167 if(caster->GetTypeId()==TYPEID_PLAYER)
169 if(m_targetMask & TARGET_FLAG_ITEM)
170 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
171 else
173 Player* pTrader = ((Player*)caster)->GetTrader();
174 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
175 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
177 if(m_itemTarget)
178 m_itemTargetEntry = m_itemTarget->GetEntry();
182 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
184 if(data->rpos()+4 > data->size())
185 return false;
187 *data >> m_targetMask;
189 if(m_targetMask == TARGET_FLAG_SELF)
191 m_destX = caster->GetPositionX();
192 m_destY = caster->GetPositionY();
193 m_destZ = caster->GetPositionZ();
194 m_unitTarget = caster;
195 m_unitTargetGUID = caster->GetGUID();
196 return true;
199 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
200 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
201 if(!data->readPackGUID(m_unitTargetGUID))
202 return false;
204 if( m_targetMask & ( TARGET_FLAG_OBJECT ))
205 if(!data->readPackGUID(m_GOTargetGUID))
206 return false;
208 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
209 if(!data->readPackGUID(m_itemTargetGUID))
210 return false;
212 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
213 if(!data->readPackGUID(m_CorpseTargetGUID))
214 return false;
216 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
218 if(data->rpos()+4+4+4 > data->size())
219 return false;
221 *data >> m_srcX >> m_srcY >> m_srcZ;
222 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
223 return false;
226 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
228 if(data->rpos()+1+4+4+4 > data->size())
229 return false;
231 if(!data->readPackGUID(m_unitTargetGUID))
232 return false;
234 *data >> m_destX >> m_destY >> m_destZ;
235 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
236 return false;
239 if( m_targetMask & TARGET_FLAG_STRING )
241 if(data->rpos()+1 > data->size())
242 return false;
244 *data >> m_strTarget;
247 // find real units/GOs
248 Update(caster);
249 return true;
252 void SpellCastTargets::write ( WorldPacket * data )
254 *data << uint32(m_targetMask);
256 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
258 if(m_targetMask & TARGET_FLAG_UNIT)
260 if(m_unitTarget)
261 data->append(m_unitTarget->GetPackGUID());
262 else
263 *data << uint8(0);
265 else if( m_targetMask & TARGET_FLAG_OBJECT )
267 if(m_GOTarget)
268 data->append(m_GOTarget->GetPackGUID());
269 else
270 *data << uint8(0);
272 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
273 data->appendPackGUID(m_CorpseTargetGUID);
274 else
275 *data << uint8(0);
278 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
280 if(m_itemTarget)
281 data->append(m_itemTarget->GetPackGUID());
282 else
283 *data << uint8(0);
286 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
287 *data << m_srcX << m_srcY << m_srcZ;
289 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
291 if(m_unitTarget)
292 data->append(m_unitTarget->GetPackGUID());
293 else
294 *data << uint8(0);
296 *data << m_destX << m_destY << m_destZ;
299 if( m_targetMask & TARGET_FLAG_STRING )
300 *data << m_strTarget;
303 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
305 ASSERT( Caster != NULL && info != NULL );
306 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
308 m_spellInfo = info;
309 m_caster = Caster;
310 m_selfContainer = NULL;
311 m_triggeringContainer = triggeringContainer;
312 m_referencedFromCurrentSpell = false;
313 m_executedCurrently = false;
314 m_delayStart = 0;
315 m_delayAtDamageCount = 0;
317 m_applyMultiplierMask = 0;
319 // Get data for type of attack
320 switch (m_spellInfo->DmgClass)
322 case SPELL_DAMAGE_CLASS_MELEE:
323 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
324 m_attackType = OFF_ATTACK;
325 else
326 m_attackType = BASE_ATTACK;
327 break;
328 case SPELL_DAMAGE_CLASS_RANGED:
329 m_attackType = RANGED_ATTACK;
330 break;
331 default:
332 // Wands
333 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
334 m_attackType = RANGED_ATTACK;
335 else
336 m_attackType = BASE_ATTACK;
337 break;
340 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
342 if(m_attackType == RANGED_ATTACK)
344 // wand case
345 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
347 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
348 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage[0].DamageType);
351 // Set health leech amount to zero
352 m_healthLeech = 0;
354 if(originalCasterGUID)
355 m_originalCasterGUID = originalCasterGUID;
356 else
357 m_originalCasterGUID = m_caster->GetGUID();
359 if(m_originalCasterGUID==m_caster->GetGUID())
360 m_originalCaster = m_caster;
361 else
363 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
364 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
367 for(int i=0; i <3; ++i)
368 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
370 m_spellState = SPELL_STATE_NULL;
372 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
373 m_TriggerSpells.clear();
374 m_IsTriggeredSpell = triggered;
375 //m_AreaAura = false;
376 m_CastItem = NULL;
378 unitTarget = NULL;
379 itemTarget = NULL;
380 gameObjTarget = NULL;
381 focusObject = NULL;
382 m_cast_count = 0;
383 m_glyphIndex = 0;
384 m_preCastSpell = 0;
385 m_triggeredByAuraSpell = NULL;
387 //Auto Shot & Shoot (wand)
388 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
390 m_runesState = 0;
391 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
392 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
393 m_timer = 0; // will set to castime in prepare
395 m_needAliveTargetMask = 0;
397 // determine reflection
398 m_canReflect = false;
400 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
402 for(int j=0;j<3;j++)
404 if (m_spellInfo->Effect[j]==0)
405 continue;
407 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
408 m_canReflect = true;
409 else
410 m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
412 if(m_canReflect)
413 continue;
414 else
415 break;
419 CleanupTargetList();
422 Spell::~Spell()
426 void Spell::FillTargetMap()
428 // TODO: ADD the correct target FILLS!!!!!!
430 for(uint32 i=0;i<3;++i)
432 // not call for empty effect.
433 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
434 if(m_spellInfo->Effect[i]==0)
435 continue;
437 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::CheckCast call
438 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
439 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
440 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
441 continue;
443 // TODO: find a way so this is not needed?
444 // for area auras always add caster as target (needed for totems for example)
445 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
446 AddUnitTarget(m_caster, i);
448 std::list<Unit*> tmpUnitMap;
450 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
451 // but need it support in some know cases
452 switch(m_spellInfo->EffectImplicitTargetA[i])
454 case TARGET_SELF:
455 switch(m_spellInfo->EffectImplicitTargetB[i])
457 case 0:
458 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
459 break;
460 case TARGET_AREAEFFECT_INSTANT: // use B case that not dependent from from A in fact
461 if((m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION)==0)
462 m_targets.setDestination(m_caster->GetPositionX(),m_caster->GetPositionY(),m_caster->GetPositionZ());
463 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
464 break;
465 case TARGET_BEHIND_VICTIM: // use B case that not dependent from from A in fact
466 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
467 break;
468 default:
469 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
470 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
471 break;
473 break;
474 case TARGET_CASTER_COORDINATES:
475 // Note: this hack with search required until GO casting not implemented
476 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
477 // currently each enemy selected explicitly and self cast damage
478 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
480 if(m_targets.getUnitTarget())
481 tmpUnitMap.push_back(m_targets.getUnitTarget());
483 else
485 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
486 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
488 break;
489 case TARGET_TABLE_X_Y_Z_COORDINATES:
490 switch(m_spellInfo->EffectImplicitTargetB[i])
492 case 0:
493 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
495 // need some target for proccesing
496 if(m_targets.getUnitTarget())
497 tmpUnitMap.push_back(m_targets.getUnitTarget());
498 else
499 tmpUnitMap.push_back(m_caster);
500 break;
501 case TARGET_AREAEFFECT_INSTANT: // All 17/7 pairs used for dest teleportation, A processed in effect code
502 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
503 break;
504 default:
505 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
506 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
507 break;
509 break;
510 default:
511 switch(m_spellInfo->EffectImplicitTargetB[i])
513 case 0:
514 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
515 break;
516 case TARGET_SCRIPT_COORDINATES: // B case filled in CheckCast but we need fill unit list base at A case
517 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
518 break;
519 default:
520 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
521 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
522 break;
524 break;
527 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
528 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
530 // add here custom effects that need default target.
531 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
532 switch(m_spellInfo->Effect[i])
534 case SPELL_EFFECT_DUMMY:
536 switch(m_spellInfo->Id)
538 case 20577: // Cannibalize
540 // non-standard target selection
541 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
542 float max_range = GetSpellMaxRange(srange);
544 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
545 Cell cell(p);
546 cell.data.Part.reserved = ALL_DISTRICT;
547 cell.SetNoCreate();
549 WorldObject* result = NULL;
551 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
552 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(m_caster, result, u_check);
554 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
555 CellLock<GridReadGuard> cell_lock(cell, p);
556 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
558 if(!result)
560 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
561 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
564 if(result)
566 switch(result->GetTypeId())
568 case TYPEID_UNIT:
569 case TYPEID_PLAYER:
570 tmpUnitMap.push_back((Unit*)result);
571 break;
572 case TYPEID_CORPSE:
573 m_targets.setCorpseTarget((Corpse*)result);
574 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
575 tmpUnitMap.push_back(owner);
576 break;
579 else
581 // clear cooldown at fail
582 if(m_caster->GetTypeId()==TYPEID_PLAYER)
584 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
586 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
587 data << uint32(m_spellInfo->Id);
588 data << uint64(m_caster->GetGUID());
589 ((Player*)m_caster)->GetSession()->SendPacket(&data);
592 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
593 finish(false);
595 break;
597 default:
598 if(m_targets.getUnitTarget())
599 tmpUnitMap.push_back(m_targets.getUnitTarget());
600 break;
602 break;
604 case SPELL_EFFECT_RESURRECT:
605 case SPELL_EFFECT_PARRY:
606 case SPELL_EFFECT_BLOCK:
607 case SPELL_EFFECT_CREATE_ITEM:
608 case SPELL_EFFECT_TRIGGER_SPELL:
609 case SPELL_EFFECT_TRIGGER_MISSILE:
610 case SPELL_EFFECT_LEARN_SPELL:
611 case SPELL_EFFECT_SKILL_STEP:
612 case SPELL_EFFECT_PROFICIENCY:
613 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
614 case SPELL_EFFECT_SELF_RESURRECT:
615 case SPELL_EFFECT_REPUTATION:
616 if(m_targets.getUnitTarget())
617 tmpUnitMap.push_back(m_targets.getUnitTarget());
618 // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
619 else if(m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL)
620 tmpUnitMap.push_back(m_caster);
621 break;
622 case SPELL_EFFECT_SUMMON_PLAYER:
623 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
625 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
626 if(target)
627 tmpUnitMap.push_back(target);
629 break;
630 case SPELL_EFFECT_RESURRECT_NEW:
631 if(m_targets.getUnitTarget())
632 tmpUnitMap.push_back(m_targets.getUnitTarget());
633 if(m_targets.getCorpseTargetGUID())
635 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
636 if(corpse)
638 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
639 if(owner)
640 tmpUnitMap.push_back(owner);
643 break;
644 case SPELL_EFFECT_SUMMON:
645 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
647 if(m_targets.getUnitTarget())
648 tmpUnitMap.push_back(m_targets.getUnitTarget());
650 else
651 tmpUnitMap.push_back(m_caster);
652 break;
653 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
654 case SPELL_EFFECT_TRANS_DOOR:
655 case SPELL_EFFECT_ADD_FARSIGHT:
656 case SPELL_EFFECT_APPLY_GLYPH:
657 case SPELL_EFFECT_STUCK:
658 case SPELL_EFFECT_FEED_PET:
659 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
660 case SPELL_EFFECT_SKILL:
661 tmpUnitMap.push_back(m_caster);
662 break;
663 case SPELL_EFFECT_LEARN_PET_SPELL:
664 if(Pet* pet = m_caster->GetPet())
665 tmpUnitMap.push_back(pet);
666 break;
667 case SPELL_EFFECT_ENCHANT_ITEM:
668 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
669 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
670 case SPELL_EFFECT_DISENCHANT:
671 case SPELL_EFFECT_PROSPECTING:
672 case SPELL_EFFECT_MILLING:
673 if(m_targets.getItemTarget())
674 AddItemTarget(m_targets.getItemTarget(), i);
675 break;
676 case SPELL_EFFECT_APPLY_AURA:
677 switch(m_spellInfo->EffectApplyAuraName[i])
679 case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_SELF(1) (and present for other ranks for same spell for example)
680 case SPELL_AURA_ADD_PCT_MODIFIER:
681 tmpUnitMap.push_back(m_caster);
682 break;
683 default: // apply to target in other case
684 if(m_targets.getUnitTarget())
685 tmpUnitMap.push_back(m_targets.getUnitTarget());
686 break;
688 break;
689 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
690 // AreaAura
691 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
692 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
693 break;
694 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
695 if(m_targets.getUnitTarget())
697 tmpUnitMap.push_back(m_targets.getUnitTarget());
699 else if (m_targets.getCorpseTargetGUID())
701 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
702 if(corpse)
704 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
705 if(owner)
706 tmpUnitMap.push_back(owner);
709 break;
710 default:
711 break;
715 if(m_caster->GetTypeId() == TYPEID_PLAYER)
717 Player *me = (Player*)m_caster;
718 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
720 Unit *owner = (*itr)->GetOwner();
721 Unit *u = owner ? owner : (*itr);
722 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
724 me->UpdatePvP(true);
725 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
726 break;
731 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
733 if (!CheckTarget (*itr, i))
735 itr = tmpUnitMap.erase(itr);
736 continue;
738 else
739 ++itr;
742 for(std::list<Unit*>::const_iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
743 AddUnitTarget((*iunit), i);
747 void Spell::prepareDataForTriggerSystem()
749 //==========================================================================================
750 // Now fill data for trigger system, need know:
751 // an spell trigger another or not ( m_canTrigger )
752 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
753 //==========================================================================================
754 // Fill flag can spell trigger or not
755 // TODO: possible exist spell attribute for this
756 m_canTrigger = false;
758 if (m_CastItem)
759 m_canTrigger = false; // Do not trigger from item cast spell
760 else if (!m_IsTriggeredSpell)
761 m_canTrigger = true; // Normal cast - can trigger
762 else if (!m_triggeredByAuraSpell)
763 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
765 if (!m_canTrigger) // Exceptions (some periodic triggers)
767 switch (m_spellInfo->SpellFamilyName)
769 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
770 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
771 break;
772 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
773 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
774 break;
775 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
776 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
777 break;
778 case SPELLFAMILY_ROGUE: // For poisons need do it
779 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
780 break;
781 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
782 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000214LL ||
783 m_spellInfo->SpellFamilyFlags2 & 0x200) m_canTrigger = true;
784 break;
785 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
786 if (m_spellInfo->SpellFamilyFlags & 0x0001000900B80400LL) m_canTrigger = true;
787 break;
791 // Get data for type of attack and fill base info for trigger
792 switch (m_spellInfo->DmgClass)
794 case SPELL_DAMAGE_CLASS_MELEE:
795 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
796 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
797 break;
798 case SPELL_DAMAGE_CLASS_RANGED:
799 // Auto attack
800 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
802 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
803 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
805 else // Ranged spell attack
807 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
808 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
810 break;
811 default:
812 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
814 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
815 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
817 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
819 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
820 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
822 else // Negative spell
824 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
825 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
827 break;
829 // Hunter traps spells (for Entrapment trigger)
830 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
831 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x000020000000001CLL)
832 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
835 void Spell::CleanupTargetList()
837 m_UniqueTargetInfo.clear();
838 m_UniqueGOTargetInfo.clear();
839 m_UniqueItemInfo.clear();
840 m_delayMoment = 0;
843 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
845 if( m_spellInfo->Effect[effIndex]==0 )
846 return;
848 // Check for effect immune skip if immuned
849 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
851 uint64 targetGUID = pVictim->GetGUID();
853 // Lookup target in already in list
854 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
856 if (targetGUID == ihit->targetGUID) // Found in list
858 if (!immuned)
859 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
860 return;
864 // This is new target calculate data for him
866 // Get spell hit result on target
867 TargetInfo target;
868 target.targetGUID = targetGUID; // Store target GUID
869 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
870 target.processed = false; // Effects not apply on target
872 // Calculate hit result
873 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
875 // Spell have speed - need calculate incoming time
876 if (m_spellInfo->speed > 0.0f)
878 // calculate spell incoming interval
879 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
880 if (dist < 5.0f) dist = 5.0f;
881 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
883 // Calculate minimum incoming time
884 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
885 m_delayMoment = target.timeDelay;
887 else
888 target.timeDelay = 0LL;
890 // If target reflect spell back to caster
891 if (target.missCondition==SPELL_MISS_REFLECT)
893 // Calculate reflected spell result on caster
894 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
896 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
897 target.reflectResult = SPELL_MISS_PARRY;
899 // Increase time interval for reflected spells by 1.5
900 target.timeDelay+=target.timeDelay>>1;
902 else
903 target.reflectResult = SPELL_MISS_NONE;
905 // Add target to list
906 m_UniqueTargetInfo.push_back(target);
909 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
911 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
912 if (unit)
913 AddUnitTarget(unit, effIndex);
916 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
918 if( m_spellInfo->Effect[effIndex]==0 )
919 return;
921 uint64 targetGUID = pVictim->GetGUID();
923 // Lookup target in already in list
924 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
926 if (targetGUID == ihit->targetGUID) // Found in list
928 ihit->effectMask |= 1<<effIndex; // Add only effect mask
929 return;
933 // This is new target calculate data for him
935 GOTargetInfo target;
936 target.targetGUID = targetGUID;
937 target.effectMask = 1<<effIndex;
938 target.processed = false; // Effects not apply on target
940 // Spell have speed - need calculate incoming time
941 if (m_spellInfo->speed > 0.0f)
943 // calculate spell incoming interval
944 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
945 if (dist < 5.0f) dist = 5.0f;
946 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
947 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
948 m_delayMoment = target.timeDelay;
950 else
951 target.timeDelay = 0LL;
953 // Add target to list
954 m_UniqueGOTargetInfo.push_back(target);
957 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
959 GameObject* go = m_caster->GetMap()->GetGameObject(goGUID);
960 if (go)
961 AddGOTarget(go, effIndex);
964 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
966 if( m_spellInfo->Effect[effIndex]==0 )
967 return;
969 // Lookup target in already in list
970 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
972 if (pitem == ihit->item) // Found in list
974 ihit->effectMask |= 1<<effIndex; // Add only effect mask
975 return;
979 // This is new target add data
981 ItemTargetInfo target;
982 target.item = pitem;
983 target.effectMask = 1<<effIndex;
984 m_UniqueItemInfo.push_back(target);
987 void Spell::DoAllEffectOnTarget(TargetInfo *target)
989 if (target->processed) // Check target
990 return;
991 target->processed = true; // Target checked in apply effects procedure
993 // Get mask of effects for target
994 uint32 mask = target->effectMask;
996 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
997 if (!unit)
998 return;
1000 // Get original caster (if exist) and calculate damage/healing from him data
1001 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
1003 // Skip if m_originalCaster not available
1004 if (!caster)
1005 return;
1007 SpellMissInfo missInfo = target->missCondition;
1008 // Need init unitTarget by default unit (can changed in code on reflect)
1009 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
1010 unitTarget = unit;
1012 // Reset damage/healing counter
1013 m_damage = 0;
1014 m_healing = 0;
1016 // Fill base trigger info
1017 uint32 procAttacker = m_procAttacker;
1018 uint32 procVictim = m_procVictim;
1019 uint32 procEx = PROC_EX_NONE;
1021 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
1022 DoSpellHitOnUnit(unit, mask);
1023 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
1025 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
1026 DoSpellHitOnUnit(m_caster, mask);
1029 // All calculated do it!
1030 // Do healing and triggers
1031 if (m_healing)
1033 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
1034 uint32 addhealth = m_healing;
1035 if (crit)
1037 procEx |= PROC_EX_CRITICAL_HIT;
1038 addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
1040 else
1041 procEx |= PROC_EX_NORMAL_HIT;
1043 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1044 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1045 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
1047 int32 gain = caster->DealHeal(unitTarget, addhealth, m_spellInfo, crit);
1048 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
1050 // Do damage and triggers
1051 else if (m_damage)
1053 // Fill base damage struct (unitTarget - is real spell target)
1054 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1056 // Add bonuses and fill damageInfo struct
1057 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
1059 // Send log damage message to client
1060 caster->SendSpellNonMeleeDamageLog(&damageInfo);
1062 procEx = createProcExtendMask(&damageInfo, missInfo);
1063 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1065 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1066 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1067 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1069 caster->DealSpellDamage(&damageInfo, true);
1071 // Judgement of Blood
1072 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1074 int32 damagePoint = damageInfo.damage * 33 / 100;
1075 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1078 // Passive spell hits/misses or active spells only misses (only triggers)
1079 else
1081 // Fill base damage struct (unitTarget - is real spell target)
1082 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1083 procEx = createProcExtendMask(&damageInfo, missInfo);
1084 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1085 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1086 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1089 // Call scripted function for AI if this spell is casted upon a creature
1090 if(unit->GetTypeId()==TYPEID_UNIT)
1092 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1093 // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... )
1094 if( !((Creature*)unit)->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1096 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
1097 p->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1100 if(((Creature*)unit)->AI())
1101 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1104 // Call scripted function for AI if this spell is casted by a creature
1105 if(m_caster->GetTypeId()==TYPEID_UNIT && ((Creature*)m_caster)->AI())
1106 ((Creature*)m_caster)->AI()->SpellHitTarget(unit,m_spellInfo);
1109 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1111 if(!unit || !effectMask)
1112 return;
1114 // Recheck immune (only for delayed spells)
1115 if( m_spellInfo->speed && (
1116 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1117 unit->IsImmunedToSpell(m_spellInfo)))
1119 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1120 return;
1123 if (unit->GetTypeId() == TYPEID_PLAYER)
1125 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1126 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1129 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1131 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1134 if( m_caster != unit )
1136 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1137 if (m_spellInfo->speed > 0.0f &&
1138 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1139 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1141 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1142 return;
1145 if( !m_caster->IsFriendlyTo(unit) )
1147 // for delayed spells ignore not visible explicit target
1148 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1150 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1151 return;
1154 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1156 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1158 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1159 unit->SetStandState(UNIT_STAND_STATE_STAND);
1161 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1162 ((Creature*)unit)->AI()->AttackedBy(m_caster);
1164 unit->AddThreat(m_caster, 0.0f);
1165 unit->SetInCombatWith(m_caster);
1166 m_caster->SetInCombatWith(unit);
1168 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1170 m_caster->SetContestedPvP(attackedPlayer);
1174 else
1176 // for delayed spells ignore negative spells (after duel end) for friendly targets
1177 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1179 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1180 return;
1183 // assisting case, healing and resurrection
1184 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1185 m_caster->SetContestedPvP();
1186 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1188 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1189 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1194 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1195 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1196 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1197 // Increase Diminishing on unit, current informations for actually casts will use values above
1198 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1199 unit->IncrDiminishing(m_diminishGroup);
1201 // Apply additional spell effects to target
1202 if (m_preCastSpell)
1203 m_caster->CastSpell(unit,m_preCastSpell, true, m_CastItem);
1205 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1207 if (effectMask & (1<<effectNumber))
1209 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1210 if ( m_applyMultiplierMask & (1 << effectNumber) )
1212 // Get multiplier
1213 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1214 // Apply multiplier mods
1215 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1216 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1217 m_damageMultipliers[effectNumber] *= multiplier;
1223 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1225 if (target->processed) // Check target
1226 return;
1227 target->processed = true; // Target checked in apply effects procedure
1229 uint32 effectMask = target->effectMask;
1230 if(!effectMask)
1231 return;
1233 GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
1234 if(!go)
1235 return;
1237 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1238 if (effectMask & (1<<effectNumber))
1239 HandleEffects(NULL,NULL,go,effectNumber);
1241 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1242 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1243 if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1245 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
1246 p->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1250 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1252 uint32 effectMask = target->effectMask;
1253 if(!target->item || !effectMask)
1254 return;
1256 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1257 if (effectMask & (1<<effectNumber))
1258 HandleEffects(NULL, target->item, NULL, effectNumber);
1261 bool Spell::IsAliveUnitPresentInTargetList()
1263 // Not need check return true
1264 if (m_needAliveTargetMask == 0)
1265 return true;
1267 uint8 needAliveTargetMask = m_needAliveTargetMask;
1269 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1271 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1273 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1275 if (unit && unit->isAlive())
1276 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1280 // is all effects from m_needAliveTargetMask have alive targets
1281 return needAliveTargetMask==0;
1284 // Helper for Chain Healing
1285 // Spell target first
1286 // Raidmates then descending by injury suffered (MaxHealth - Health)
1287 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1288 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1290 const Unit* MainTarget;
1291 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1292 // functor for operator ">"
1293 bool operator()(Unit const* _Left, Unit const* _Right) const
1295 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1297 int32 ChainHealingHash(Unit const* Target) const
1299 if (Target == MainTarget)
1300 return 0;
1301 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1302 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1304 if (Target->GetHealth() == Target->GetMaxHealth())
1305 return 40000;
1306 else
1307 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1309 else
1310 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1314 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1316 public:
1317 const Unit* MainTarget;
1318 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1320 bool operator()(const Unit* Target)
1322 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1326 // Helper for targets nearest to the spell target
1327 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1328 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1330 const Unit* MainTarget;
1331 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1332 // functor for operator ">"
1333 bool operator()(const Unit* _Left, const Unit* _Right) const
1335 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1339 void Spell::SetTargetMap(uint32 i,uint32 cur,UnitList& TagUnitMap)
1341 float radius;
1342 if (m_spellInfo->EffectRadiusIndex[i])
1343 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1344 else
1345 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1347 if(m_originalCaster)
1348 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1349 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1351 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1352 if(m_originalCaster)
1353 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1354 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1356 // Get spell max affected targets
1357 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1359 // custom target amount cases
1360 switch(m_spellInfo->SpellFamilyName)
1362 case SPELLFAMILY_DRUID:
1363 // Starfall
1364 if (m_spellInfo->SpellFamilyFlags2 & 0x00000100LL)
1365 unMaxTargets = 2;
1366 break;
1367 default:
1368 break;
1371 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1372 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1374 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1375 continue;
1376 unMaxTargets+=(*m)->GetModifier()->m_amount;
1379 switch(cur)
1381 case TARGET_TOTEM_EARTH:
1382 case TARGET_TOTEM_WATER:
1383 case TARGET_TOTEM_AIR:
1384 case TARGET_TOTEM_FIRE:
1385 case TARGET_SELF:
1386 case TARGET_SELF2:
1387 case TARGET_DYNAMIC_OBJECT:
1388 case TARGET_AREAEFFECT_CUSTOM:
1389 case TARGET_AREAEFFECT_CUSTOM_2:
1390 case TARGET_SUMMON:
1392 TagUnitMap.push_back(m_caster);
1393 break;
1395 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1397 m_targets.m_targetMask = 0;
1398 unMaxTargets = EffectChainTarget;
1399 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1401 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1402 Cell cell(p);
1403 cell.data.Part.reserved = ALL_DISTRICT;
1404 cell.SetNoCreate();
1406 std::list<Unit *> tempUnitMap;
1409 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1410 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1412 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1413 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1415 CellLock<GridReadGuard> cell_lock(cell, p);
1416 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1417 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1420 if(tempUnitMap.empty())
1421 break;
1423 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1425 //Now to get us a random target that's in the initial range of the spell
1426 uint32 t = 0;
1427 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1428 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1429 ++t, ++itr;
1431 if(!t)
1432 break;
1434 itr = tempUnitMap.begin();
1435 std::advance(itr, rand()%t);
1436 Unit *pUnitTarget = *itr;
1437 TagUnitMap.push_back(pUnitTarget);
1439 tempUnitMap.erase(itr);
1441 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1443 t = unMaxTargets - 1;
1444 Unit *prev = pUnitTarget;
1445 std::list<Unit*>::iterator next = tempUnitMap.begin();
1447 while(t && next != tempUnitMap.end() )
1449 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1450 break;
1452 if(!prev->IsWithinLOSInMap(*next))
1454 ++next;
1455 continue;
1458 prev = *next;
1459 TagUnitMap.push_back(prev);
1460 tempUnitMap.erase(next);
1461 tempUnitMap.sort(TargetDistanceOrder(prev));
1462 next = tempUnitMap.begin();
1464 --t;
1466 }break;
1467 case TARGET_RANDOM_FRIEND_CHAIN_IN_AREA:
1469 m_targets.m_targetMask = 0;
1470 unMaxTargets = EffectChainTarget;
1471 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1472 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1473 Cell cell(p);
1474 cell.data.Part.reserved = ALL_DISTRICT;
1475 cell.SetNoCreate();
1476 std::list<Unit *> tempUnitMap;
1478 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1479 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1481 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1482 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1484 CellLock<GridReadGuard> cell_lock(cell, p);
1485 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1486 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1489 if(tempUnitMap.empty())
1490 break;
1492 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1494 //Now to get us a random target that's in the initial range of the spell
1495 uint32 t = 0;
1496 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1497 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1498 ++t, ++itr;
1500 if(!t)
1501 break;
1503 itr = tempUnitMap.begin();
1504 std::advance(itr, rand()%t);
1505 Unit *pUnitTarget = *itr;
1506 TagUnitMap.push_back(pUnitTarget);
1508 tempUnitMap.erase(itr);
1510 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1512 t = unMaxTargets - 1;
1513 Unit *prev = pUnitTarget;
1514 std::list<Unit*>::iterator next = tempUnitMap.begin();
1516 while(t && next != tempUnitMap.end() )
1518 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1519 break;
1521 if(!prev->IsWithinLOSInMap(*next))
1523 ++next;
1524 continue;
1526 prev = *next;
1527 TagUnitMap.push_back(prev);
1528 tempUnitMap.erase(next);
1529 tempUnitMap.sort(TargetDistanceOrder(prev));
1530 next = tempUnitMap.begin();
1531 --t;
1533 }break;
1534 case TARGET_PET:
1536 Pet* tmpUnit = m_caster->GetPet();
1537 if (!tmpUnit) break;
1538 TagUnitMap.push_back(tmpUnit);
1539 break;
1541 case TARGET_CHAIN_DAMAGE:
1543 if (EffectChainTarget <= 1)
1545 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1547 m_targets.setUnitTarget(pUnitTarget);
1548 TagUnitMap.push_back(pUnitTarget);
1551 else
1553 Unit* pUnitTarget = m_targets.getUnitTarget();
1554 if(!pUnitTarget)
1555 break;
1557 unMaxTargets = EffectChainTarget;
1559 float max_range;
1560 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1561 max_range = radius; //
1562 else
1563 //FIXME: This very like horrible hack and wrong for most spells
1564 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1566 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1567 Cell cell(p);
1568 cell.data.Part.reserved = ALL_DISTRICT;
1569 cell.SetNoCreate();
1571 Unit* originalCaster = GetOriginalCaster();
1572 if(originalCaster)
1574 std::list<Unit *> tempUnitMap;
1577 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1578 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1580 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1581 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1583 CellLock<GridReadGuard> cell_lock(cell, p);
1584 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1585 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1588 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1590 if(tempUnitMap.empty())
1591 break;
1593 if(*tempUnitMap.begin() == pUnitTarget)
1594 tempUnitMap.erase(tempUnitMap.begin());
1596 TagUnitMap.push_back(pUnitTarget);
1597 uint32 t = unMaxTargets - 1;
1598 Unit *prev = pUnitTarget;
1599 std::list<Unit*>::iterator next = tempUnitMap.begin();
1601 while(t && next != tempUnitMap.end() )
1603 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1604 break;
1606 if(!prev->IsWithinLOSInMap(*next))
1608 ++next;
1609 continue;
1612 prev = *next;
1613 TagUnitMap.push_back(prev);
1614 tempUnitMap.erase(next);
1615 tempUnitMap.sort(TargetDistanceOrder(prev));
1616 next = tempUnitMap.begin();
1618 --t;
1622 }break;
1623 case TARGET_ALL_ENEMY_IN_AREA:
1625 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1626 break;
1628 case TARGET_AREAEFFECT_INSTANT:
1630 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1631 // Select friendly targets for positive effect
1632 if (IsPositiveEffect(m_spellInfo->Id, i))
1633 targetB = SPELL_TARGETS_FRIENDLY;
1635 FillAreaTargets(TagUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),radius, PUSH_DEST_CENTER, targetB);
1637 // exclude caster
1638 TagUnitMap.remove(m_caster);
1640 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1642 // targets the ground, not the units in the area
1643 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1645 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1647 // exclude caster (this can be important if this not original caster)
1648 TagUnitMap.remove(m_caster);
1650 }break;
1651 case TARGET_DUELVSPLAYER_COORDINATES:
1653 if(Unit* currentTarget = m_targets.getUnitTarget())
1655 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1656 TagUnitMap.push_back(currentTarget);
1658 }break;
1659 case TARGET_ALL_PARTY_AROUND_CASTER:
1660 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1661 case TARGET_ALL_PARTY:
1663 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1664 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1666 if(pGroup)
1668 uint8 subgroup = pTarget->GetSubGroup();
1670 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1672 Player* Target = itr->getSource();
1674 // IsHostileTo check duel and controlled by enemy
1675 if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1677 if( m_caster->IsWithinDistInMap(Target, radius) )
1678 TagUnitMap.push_back(Target);
1680 if(Pet* pet = Target->GetPet())
1681 if( m_caster->IsWithinDistInMap(pet, radius) )
1682 TagUnitMap.push_back(pet);
1686 else
1688 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1689 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1690 TagUnitMap.push_back(ownerOrSelf);
1691 if(Pet* pet = ownerOrSelf->GetPet())
1692 if( m_caster->IsWithinDistInMap(pet, radius) )
1693 TagUnitMap.push_back(pet);
1695 break;
1697 case TARGET_ALL_RAID_AROUND_CASTER:
1699 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1700 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1702 if(m_spellInfo->Id==57669) //Replenishment (special target selection)
1704 if(pGroup)
1706 typedef std::priority_queue<PrioritizeManaPlayerWraper, std::vector<PrioritizeManaPlayerWraper>, PrioritizeMana> Top10;
1707 Top10 manaUsers;
1709 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL && manaUsers.size() < 10; itr = itr->next())
1711 Player* Target = itr->getSource();
1712 if (m_caster->GetGUID() != Target->GetGUID() && Target->getPowerType() == POWER_MANA &&
1713 !Target->isDead() && m_caster->IsWithinDistInMap(Target, radius))
1715 PrioritizeManaPlayerWraper WTarget(Target);
1716 manaUsers.push(WTarget);
1720 while(!manaUsers.empty())
1722 TagUnitMap.push_back(manaUsers.top().getPlayer());
1723 manaUsers.pop();
1726 else
1728 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1729 if ((ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius)) &&
1730 ownerOrSelf->getPowerType() == POWER_MANA)
1731 TagUnitMap.push_back(ownerOrSelf);
1733 if(Pet* pet = ownerOrSelf->GetPet())
1734 if( m_caster->IsWithinDistInMap(pet, radius) && pet->getPowerType() == POWER_MANA )
1735 TagUnitMap.push_back(pet);
1738 else
1740 if(pGroup)
1742 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1744 Player* Target = itr->getSource();
1746 // IsHostileTo check duel and controlled by enemy
1747 if( Target && !m_caster->IsHostileTo(Target) )
1749 if( m_caster->IsWithinDistInMap(Target, radius) )
1750 TagUnitMap.push_back(Target);
1752 if(Pet* pet = Target->GetPet())
1753 if( m_caster->IsWithinDistInMap(pet, radius) )
1754 TagUnitMap.push_back(pet);
1758 else
1760 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1761 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1762 TagUnitMap.push_back(ownerOrSelf);
1763 if(Pet* pet = ownerOrSelf->GetPet())
1764 if( m_caster->IsWithinDistInMap(pet, radius) )
1765 TagUnitMap.push_back(pet);
1768 break;
1770 case TARGET_SINGLE_FRIEND:
1771 case TARGET_SINGLE_FRIEND_2:
1773 if(m_targets.getUnitTarget())
1774 TagUnitMap.push_back(m_targets.getUnitTarget());
1775 }break;
1776 case TARGET_NONCOMBAT_PET:
1778 if(Unit* target = m_targets.getUnitTarget())
1779 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1780 TagUnitMap.push_back(target);
1781 }break;
1782 case TARGET_CASTER_COORDINATES:
1784 // Check original caster is GO - set its coordinates as dst cast
1785 WorldObject *caster = NULL;
1786 if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
1787 caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
1788 if (!caster)
1789 caster = m_caster;
1790 // Set dest for targets
1791 m_targets.setDestination(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
1792 }break;
1793 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1794 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1795 break;
1796 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1797 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1798 break;
1799 // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some seals, fire shield from imp, etc..)
1800 case TARGET_SINGLE_PARTY:
1802 Unit *target = m_targets.getUnitTarget();
1803 // Thoses spells apparently can't be casted on the caster.
1804 if( target && target != m_caster)
1806 // Can only be casted on group's members or its pets
1807 Group *pGroup = NULL;
1809 Unit* owner = m_caster->GetCharmerOrOwner();
1810 Unit *targetOwner = target->GetCharmerOrOwner();
1811 if(owner)
1813 if(owner->GetTypeId() == TYPEID_PLAYER)
1815 if( target == owner )
1817 TagUnitMap.push_back(target);
1818 break;
1820 pGroup = ((Player*)owner)->GetGroup();
1823 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1825 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1827 TagUnitMap.push_back(target);
1828 break;
1830 pGroup = ((Player*)m_caster)->GetGroup();
1833 if(pGroup)
1835 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1836 if(targetOwner)
1838 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1839 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1840 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1841 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1843 TagUnitMap.push_back(target);
1846 // 1Our target can be a player who is on our group
1847 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1849 TagUnitMap.push_back(target);
1853 }break;
1854 case TARGET_GAMEOBJECT:
1856 if(m_targets.getGOTarget())
1857 AddGOTarget(m_targets.getGOTarget(), i);
1858 }break;
1859 case TARGET_IN_FRONT_OF_CASTER:
1861 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1862 FillAreaTargets(TagUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),radius,inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1863 break;
1865 case TARGET_DUELVSPLAYER:
1867 Unit *target = m_targets.getUnitTarget();
1868 if(target)
1870 if(m_caster->IsFriendlyTo(target))
1872 TagUnitMap.push_back(target);
1874 else
1876 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1878 m_targets.setUnitTarget(pUnitTarget);
1879 TagUnitMap.push_back(pUnitTarget);
1883 }break;
1884 case TARGET_GAMEOBJECT_ITEM:
1886 if(m_targets.getGOTargetGUID())
1887 AddGOTarget(m_targets.getGOTarget(), i);
1888 else if(m_targets.getItemTarget())
1889 AddItemTarget(m_targets.getItemTarget(), i);
1890 break;
1892 case TARGET_MASTER:
1894 if(Unit* owner = m_caster->GetCharmerOrOwner())
1895 TagUnitMap.push_back(owner);
1896 break;
1898 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1900 // targets the ground, not the units in the area
1901 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1902 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1903 break;
1905 case TARGET_MINION:
1907 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1908 TagUnitMap.push_back(m_caster);
1909 }break;
1910 case TARGET_SINGLE_ENEMY:
1912 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1914 m_targets.setUnitTarget(pUnitTarget);
1915 TagUnitMap.push_back(pUnitTarget);
1917 }break;
1918 case TARGET_AREAEFFECT_PARTY:
1920 Unit* owner = m_caster->GetCharmerOrOwner();
1921 Player *pTarget = NULL;
1923 if(owner)
1925 TagUnitMap.push_back(m_caster);
1926 if(owner->GetTypeId() == TYPEID_PLAYER)
1927 pTarget = (Player*)owner;
1929 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1931 if(Unit* target = m_targets.getUnitTarget())
1933 if( target->GetTypeId() != TYPEID_PLAYER)
1935 if(((Creature*)target)->isPet())
1937 Unit *targetOwner = target->GetOwner();
1938 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1939 pTarget = (Player*)targetOwner;
1942 else
1943 pTarget = (Player*)target;
1947 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1949 if(pGroup)
1951 uint8 subgroup = pTarget->GetSubGroup();
1953 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1955 Player* Target = itr->getSource();
1957 // IsHostileTo check duel and controlled by enemy
1958 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1960 if( pTarget->IsWithinDistInMap(Target, radius) )
1961 TagUnitMap.push_back(Target);
1963 if(Pet* pet = Target->GetPet())
1964 if( pTarget->IsWithinDistInMap(pet, radius) )
1965 TagUnitMap.push_back(pet);
1969 else if (owner)
1971 if(m_caster->IsWithinDistInMap(owner, radius))
1972 TagUnitMap.push_back(owner);
1974 else if(pTarget)
1976 TagUnitMap.push_back(pTarget);
1978 if(Pet* pet = pTarget->GetPet())
1979 if( m_caster->IsWithinDistInMap(pet, radius) )
1980 TagUnitMap.push_back(pet);
1983 }break;
1984 case TARGET_SCRIPT:
1986 if(m_targets.getUnitTarget())
1987 TagUnitMap.push_back(m_targets.getUnitTarget());
1988 if(m_targets.getItemTarget())
1989 AddItemTarget(m_targets.getItemTarget(), i);
1990 }break;
1991 case TARGET_SELF_FISHING:
1993 TagUnitMap.push_back(m_caster);
1994 }break;
1995 case TARGET_CHAIN_HEAL:
1997 Unit* pUnitTarget = m_targets.getUnitTarget();
1998 if(!pUnitTarget)
1999 break;
2001 if (EffectChainTarget <= 1)
2002 TagUnitMap.push_back(pUnitTarget);
2003 else
2005 unMaxTargets = EffectChainTarget;
2006 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
2008 UnitList tempUnitMap;
2010 FillAreaTargets(tempUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),max_range,PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
2012 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
2013 tempUnitMap.push_front(m_caster);
2015 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
2017 if(tempUnitMap.empty())
2018 break;
2020 if(*tempUnitMap.begin() == pUnitTarget)
2021 tempUnitMap.erase(tempUnitMap.begin());
2023 TagUnitMap.push_back(pUnitTarget);
2024 uint32 t = unMaxTargets - 1;
2025 Unit *prev = pUnitTarget;
2026 std::list<Unit*>::iterator next = tempUnitMap.begin();
2028 while(t && next != tempUnitMap.end() )
2030 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
2031 break;
2033 if(!prev->IsWithinLOSInMap(*next))
2035 ++next;
2036 continue;
2039 if((*next)->GetHealth() == (*next)->GetMaxHealth())
2041 next = tempUnitMap.erase(next);
2042 continue;
2045 prev = *next;
2046 TagUnitMap.push_back(prev);
2047 tempUnitMap.erase(next);
2048 tempUnitMap.sort(TargetDistanceOrder(prev));
2049 next = tempUnitMap.begin();
2051 --t;
2054 }break;
2055 case TARGET_CURRENT_ENEMY_COORDINATES:
2057 Unit* currentTarget = m_targets.getUnitTarget();
2058 if(currentTarget)
2060 TagUnitMap.push_back(currentTarget);
2061 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
2062 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
2063 FillAreaTargets(TagUnitMap, currentTarget->GetPositionX(), currentTarget->GetPositionY(), radius, PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
2065 break;
2067 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
2069 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
2070 ? (Player*)m_targets.getUnitTarget() : NULL;
2072 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
2073 if(pGroup)
2075 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
2077 Player* Target = itr->getSource();
2079 // IsHostileTo check duel and controlled by enemy
2080 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
2081 targetPlayer->getClass() == Target->getClass() &&
2082 !m_caster->IsHostileTo(Target) )
2084 TagUnitMap.push_back(Target);
2088 else if(m_targets.getUnitTarget())
2089 TagUnitMap.push_back(m_targets.getUnitTarget());
2090 break;
2092 case TARGET_TABLE_X_Y_Z_COORDINATES:
2094 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
2095 if(st)
2097 if (st->target_mapId == m_caster->GetMapId())
2098 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
2099 else
2100 sLog.outError( "SPELL: wrong map (%u instead %u) target coordinates for spell ID %u", st->target_mapId, m_caster->GetMapId(), m_spellInfo->Id );
2102 else
2103 sLog.outError( "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id );
2104 }break;
2105 case TARGET_BEHIND_VICTIM:
2107 Unit *pTarget = NULL;
2109 // explicit cast data from client or server-side cast
2110 // some spell at client send caster
2111 if(m_targets.getUnitTarget() && m_targets.getUnitTarget()!=m_caster)
2112 pTarget = m_targets.getUnitTarget();
2113 else if(m_caster->getVictim())
2114 pTarget = m_caster->getVictim();
2115 else if(m_caster->GetTypeId() == TYPEID_PLAYER)
2116 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
2118 if(pTarget)
2120 float _target_x, _target_y, _target_z;
2121 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
2122 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
2124 TagUnitMap.push_back(m_caster);
2125 m_targets.setDestination(_target_x, _target_y, _target_z);
2128 break;
2130 case TARGET_DYNAMIC_OBJECT_COORDINATES:
2132 // if parent spell create dynamic object extract area from it
2133 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
2134 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2135 break;
2137 case TARGET_DIRECTLY_FORWARD:
2139 if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION))
2141 SpellRangeEntry const* rEntry = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
2142 float minRange = GetSpellMinRange(rEntry);
2143 float maxRange = GetSpellMaxRange(rEntry);
2144 float dist = minRange+ rand_norm()*(maxRange-minRange);
2146 float _target_x, _target_y, _target_z;
2147 m_caster->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), dist);
2148 m_targets.setDestination(_target_x, _target_y, _target_z);
2151 TagUnitMap.push_back(m_caster);
2152 break;
2154 default:
2155 break;
2158 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2160 // make sure one unit is always removed per iteration
2161 uint32 removed_utarget = 0;
2162 for (UnitList::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2164 next = itr;
2165 ++next;
2166 if (!*itr) continue;
2167 if ((*itr) == m_targets.getUnitTarget())
2169 TagUnitMap.erase(itr);
2170 removed_utarget = 1;
2171 // break;
2174 // remove random units from the map
2175 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2177 uint32 poz = urand(0, TagUnitMap.size()-1);
2178 for (UnitList::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2180 if (!*itr) continue;
2182 if (!poz)
2184 TagUnitMap.erase(itr);
2185 break;
2189 // the player's target will always be added to the map
2190 if (removed_utarget && m_targets.getUnitTarget())
2191 TagUnitMap.push_back(m_targets.getUnitTarget());
2195 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2197 m_targets = *targets;
2199 m_spellState = SPELL_STATE_PREPARING;
2201 m_castPositionX = m_caster->GetPositionX();
2202 m_castPositionY = m_caster->GetPositionY();
2203 m_castPositionZ = m_caster->GetPositionZ();
2204 m_castOrientation = m_caster->GetOrientation();
2206 if(triggeredByAura)
2207 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2209 // create and add update event for this spell
2210 SpellEvent* Event = new SpellEvent(this);
2211 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2213 //Prevent casting at cast another spell (ServerSide check)
2214 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2216 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2217 finish(false);
2218 return;
2221 // Fill cost data
2222 m_powerCost = CalculatePowerCost();
2224 SpellCastResult result = CheckCast(true);
2225 if(result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2227 if(triggeredByAura)
2229 SendChannelUpdate(0);
2230 triggeredByAura->SetAuraDuration(0);
2232 SendCastResult(result);
2233 finish(false);
2234 return;
2237 // Prepare data for triggers
2238 prepareDataForTriggerSystem();
2240 // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
2241 m_casttime = GetSpellCastTime(m_spellInfo, this);
2243 // set timer base at cast time
2244 ReSetTimer();
2246 // stealth must be removed at cast starting (at show channel bar)
2247 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2248 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2250 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2251 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2254 if(m_IsTriggeredSpell)
2255 cast(true);
2256 else
2258 m_caster->SetCurrentCastedSpell( this );
2259 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2260 SendSpellStart();
2264 void Spell::cancel()
2266 if(m_spellState == SPELL_STATE_FINISHED)
2267 return;
2269 m_autoRepeat = false;
2270 switch (m_spellState)
2272 case SPELL_STATE_PREPARING:
2273 case SPELL_STATE_DELAYED:
2275 SendInterrupted(0);
2276 SendCastResult(SPELL_FAILED_INTERRUPTED);
2277 } break;
2279 case SPELL_STATE_CASTING:
2281 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2283 if( ihit->missCondition == SPELL_MISS_NONE )
2285 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2286 if( unit && unit->isAlive() )
2287 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2291 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2292 SendChannelUpdate(0);
2293 SendInterrupted(0);
2294 SendCastResult(SPELL_FAILED_INTERRUPTED);
2295 } break;
2297 default:
2299 } break;
2302 finish(false);
2303 m_caster->RemoveDynObject(m_spellInfo->Id);
2304 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2307 void Spell::cast(bool skipCheck)
2309 SetExecutedCurrently(true);
2311 // update pointers base at GUIDs to prevent access to non-existed already object
2312 UpdatePointers();
2314 // cancel at lost main target unit
2315 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2317 cancel();
2318 SetExecutedCurrently(false);
2319 return;
2322 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2323 m_caster->SetInFront(m_targets.getUnitTarget());
2325 SpellCastResult castResult = CheckPower();
2326 if(castResult != SPELL_CAST_OK)
2328 SendCastResult(castResult);
2329 finish(false);
2330 SetExecutedCurrently(false);
2331 return;
2334 // triggered cast called from Spell::prepare where it was already checked
2335 if(!skipCheck)
2337 castResult = CheckCast(false);
2338 if(castResult != SPELL_CAST_OK)
2340 SendCastResult(castResult);
2341 finish(false);
2342 SetExecutedCurrently(false);
2343 return;
2347 switch(m_spellInfo->SpellFamilyName)
2349 case SPELLFAMILY_GENERIC:
2351 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2352 m_preCastSpell = 11196; // Recently Bandaged
2353 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2354 m_preCastSpell = 23230; // Blood Fury - Healing Reduction
2355 break;
2357 case SPELLFAMILY_MAGE:
2359 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2360 m_preCastSpell = 41425; // Hypothermia
2361 break;
2363 case SPELLFAMILY_PRIEST:
2365 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2366 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2367 m_preCastSpell = 6788; // Weakened Soul
2368 if (m_spellInfo->Id == 47585) // Dispersion (transform)
2369 m_preCastSpell = 60069; // Dispersion (mana regen)
2370 break;
2372 case SPELLFAMILY_PALADIN:
2374 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2375 m_preCastSpell = 25771; // Forbearance
2376 break;
2378 case SPELLFAMILY_SHAMAN:
2380 if (m_spellInfo->Id == 2825) // Bloodlust
2381 m_preCastSpell = 57724; // Sated
2382 else if (m_spellInfo->Id == 32182) // Heroism
2383 m_preCastSpell = 57723; // Exhaustion
2384 break;
2386 default:
2387 break;
2390 // Conflagrate - consumes immolate
2391 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2393 // for caster applied auras only
2394 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2395 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2397 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2398 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2400 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2401 break;
2406 // traded items have trade slot instead of guid in m_itemTargetGUID
2407 // set to real guid to be sent later to the client
2408 m_targets.updateTradeSlotItem();
2410 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2412 if (!m_IsTriggeredSpell && m_CastItem)
2413 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2415 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2418 // CAST SPELL
2419 SendSpellCooldown();
2421 TakePower();
2422 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2423 FillTargetMap();
2425 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2427 SetExecutedCurrently(false);
2428 return;
2431 SendCastResult(castResult);
2432 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2434 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2435 if (m_spellInfo->speed > 0.0f)
2438 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2439 // in case delayed spell remove item at cast delay start
2440 TakeCastItem();
2442 // Okay, maps created, now prepare flags
2443 m_immediateHandled = false;
2444 m_spellState = SPELL_STATE_DELAYED;
2445 SetDelayStart(0);
2447 else
2449 // Immediate spell, no big deal
2450 handle_immediate();
2453 SetExecutedCurrently(false);
2456 void Spell::handle_immediate()
2458 // start channeling if applicable
2459 if(IsChanneledSpell(m_spellInfo))
2461 int32 duration = GetSpellDuration(m_spellInfo);
2462 if (duration)
2464 // Apply duration mod
2465 if(Player* modOwner = m_caster->GetSpellModOwner())
2466 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2467 m_spellState = SPELL_STATE_CASTING;
2468 SendChannelStart(duration);
2472 // process immediate effects (items, ground, etc.) also initialize some variables
2473 _handle_immediate_phase();
2475 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2476 DoAllEffectOnTarget(&(*ihit));
2478 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2479 DoAllEffectOnTarget(&(*ihit));
2481 // spell is finished, perform some last features of the spell here
2482 _handle_finish_phase();
2484 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2485 TakeCastItem();
2487 if(m_spellState != SPELL_STATE_CASTING)
2488 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2491 uint64 Spell::handle_delayed(uint64 t_offset)
2493 uint64 next_time = 0;
2495 if (!m_immediateHandled)
2497 _handle_immediate_phase();
2498 m_immediateHandled = true;
2501 // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
2502 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2504 if (ihit->processed == false)
2506 if ( ihit->timeDelay <= t_offset )
2507 DoAllEffectOnTarget(&(*ihit));
2508 else if( next_time == 0 || ihit->timeDelay < next_time )
2509 next_time = ihit->timeDelay;
2513 // now recheck gameobject targeting correctness
2514 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2516 if (ighit->processed == false)
2518 if ( ighit->timeDelay <= t_offset )
2519 DoAllEffectOnTarget(&(*ighit));
2520 else if( next_time == 0 || ighit->timeDelay < next_time )
2521 next_time = ighit->timeDelay;
2524 // All targets passed - need finish phase
2525 if (next_time == 0)
2527 // spell is finished, perform some last features of the spell here
2528 _handle_finish_phase();
2530 finish(true); // successfully finish spell cast
2532 // return zero, spell is finished now
2533 return 0;
2535 else
2537 // spell is unfinished, return next execution time
2538 return next_time;
2542 void Spell::_handle_immediate_phase()
2544 // handle some immediate features of the spell here
2545 HandleThreatSpells(m_spellInfo->Id);
2547 m_needSpellLog = IsNeedSendToClient();
2548 for(uint32 j = 0;j<3;j++)
2550 if(m_spellInfo->Effect[j]==0)
2551 continue;
2553 // apply Send Event effect to ground in case empty target lists
2554 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2556 HandleEffects(NULL,NULL,NULL, j);
2557 continue;
2560 // Don't do spell log, if is school damage spell
2561 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2562 m_needSpellLog = false;
2564 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2565 if(m_originalCaster)
2566 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2567 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2569 // initialize multipliers
2570 m_damageMultipliers[j] = 1.0f;
2571 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2572 (EffectChainTarget > 1) )
2573 m_applyMultiplierMask |= 1 << j;
2576 // initialize Diminishing Returns Data
2577 m_diminishLevel = DIMINISHING_LEVEL_1;
2578 m_diminishGroup = DIMINISHING_NONE;
2580 // process items
2581 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2582 DoAllEffectOnTarget(&(*ihit));
2584 // process ground
2585 for(uint32 j = 0;j<3;j++)
2587 // persistent area auras target only the ground
2588 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2589 HandleEffects(NULL,NULL,NULL, j);
2593 void Spell::_handle_finish_phase()
2595 // spell log
2596 if(m_needSpellLog)
2597 SendLogExecute();
2600 void Spell::SendSpellCooldown()
2602 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2603 return;
2605 Player* _player = (Player*)m_caster;
2607 // mana/health/etc potions, disabled by client (until combat out as declarate)
2608 if (m_CastItem && m_CastItem->IsPotion())
2610 // need in some way provided data for Spell::finish SendCooldownEvent
2611 _player->SetLastPotionId(m_CastItem->GetEntry());
2612 return;
2615 // have infinity cooldown but set at aura apply
2616 if(m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2617 return;
2619 _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this);
2622 void Spell::update(uint32 difftime)
2624 // update pointers based at it's GUIDs
2625 UpdatePointers();
2627 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2629 cancel();
2630 return;
2633 // check if the player caster has moved before the spell finished
2634 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2635 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2636 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2638 // always cancel for channeled spells
2639 if( m_spellState == SPELL_STATE_CASTING )
2640 cancel();
2641 // don't cancel for melee, autorepeat, triggered and instant spells
2642 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2643 cancel();
2646 switch(m_spellState)
2648 case SPELL_STATE_PREPARING:
2650 if(m_timer)
2652 if(difftime >= m_timer)
2653 m_timer = 0;
2654 else
2655 m_timer -= difftime;
2658 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2659 cast();
2660 } break;
2661 case SPELL_STATE_CASTING:
2663 if(m_timer > 0)
2665 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2667 // check if player has jumped before the channeling finished
2668 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2669 cancel();
2671 // check for incapacitating player states
2672 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2673 cancel();
2675 // check if player has turned if flag is set
2676 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2677 cancel();
2680 // check if there are alive targets left
2681 if (!IsAliveUnitPresentInTargetList())
2683 SendChannelUpdate(0);
2684 finish();
2687 if(difftime >= m_timer)
2688 m_timer = 0;
2689 else
2690 m_timer -= difftime;
2693 if(m_timer == 0)
2695 SendChannelUpdate(0);
2697 // channeled spell processed independently for quest targeting
2698 // cast at creature (or GO) quest objectives update at successful cast channel finished
2699 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2700 if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2702 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
2704 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2706 TargetInfo* target = &*ihit;
2707 if(!IS_CREATURE_GUID(target->targetGUID))
2708 continue;
2710 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2711 if (unit==NULL)
2712 continue;
2714 p->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2717 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2719 GOTargetInfo* target = &*ihit;
2721 GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
2722 if(!go)
2723 continue;
2725 p->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2730 finish();
2732 } break;
2733 default:
2735 }break;
2739 void Spell::finish(bool ok)
2741 if(!m_caster)
2742 return;
2744 if(m_spellState == SPELL_STATE_FINISHED)
2745 return;
2747 m_spellState = SPELL_STATE_FINISHED;
2749 // other code related only to successfully finished spells
2750 if(!ok)
2751 return;
2753 //remove spell mods
2754 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2755 ((Player*)m_caster)->RemoveSpellMods(this);
2757 // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2758 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2759 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2761 if (!(*i)->isAffectedOnSpell(m_spellInfo))
2762 continue;
2763 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2764 if( ihit->missCondition == SPELL_MISS_NONE )
2766 // check m_caster->GetGUID() let load auras at login and speedup most often case
2767 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2768 if (unit && unit->isAlive())
2770 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2771 uint32 auraSpellIdx = (*i)->GetEffIndex();
2772 // Calculate chance at that moment (can be depend for example from combo points)
2773 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2774 if(roll_chance_i(chance))
2775 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2780 // Heal caster for all health leech from all targets
2781 if (m_healthLeech)
2782 m_caster->DealHeal(m_caster, uint32(m_healthLeech), m_spellInfo);
2784 if (IsMeleeAttackResetSpell())
2786 m_caster->resetAttackTimer(BASE_ATTACK);
2787 if(m_caster->haveOffhandWeapon())
2788 m_caster->resetAttackTimer(OFF_ATTACK);
2791 /*if (IsRangedAttackResetSpell())
2792 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2794 // Clear combo at finish state
2795 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2797 // Not drop combopoints if negative spell and if any miss on enemy exist
2798 bool needDrop = true;
2799 if (!IsPositiveSpell(m_spellInfo->Id))
2800 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2801 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2803 needDrop = false;
2804 break;
2806 if (needDrop)
2807 ((Player*)m_caster)->ClearComboPoints();
2810 // potions disabled by client, send event "not in combat" if need
2811 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2812 ((Player*)m_caster)->UpdatePotionCooldown(this);
2814 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2815 if(!m_TriggerSpells.empty())
2816 TriggerSpell();
2818 // Stop Attack for some spells
2819 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2820 m_caster->AttackStop();
2823 void Spell::SendCastResult(SpellCastResult result)
2825 if(result == SPELL_CAST_OK)
2826 return;
2828 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2829 return;
2831 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2832 return;
2834 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2835 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2836 data << uint32(m_spellInfo->Id);
2837 data << uint8(result); // problem
2838 switch (result)
2840 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2841 data << uint32(m_spellInfo->RequiresSpellFocus);
2842 break;
2843 case SPELL_FAILED_REQUIRES_AREA:
2844 // hardcode areas limitation case
2845 switch(m_spellInfo->Id)
2847 case 41617: // Cenarion Mana Salve
2848 case 41619: // Cenarion Healing Salve
2849 data << uint32(3905);
2850 break;
2851 case 41618: // Bottled Nethergon Energy
2852 case 41620: // Bottled Nethergon Vapor
2853 data << uint32(3842);
2854 break;
2855 case 45373: // Bloodberry Elixir
2856 data << uint32(4075);
2857 break;
2858 default: // default case (don't must be)
2859 data << uint32(0);
2860 break;
2862 break;
2863 case SPELL_FAILED_TOTEMS:
2864 if(m_spellInfo->Totem[0])
2865 data << uint32(m_spellInfo->Totem[0]);
2866 if(m_spellInfo->Totem[1])
2867 data << uint32(m_spellInfo->Totem[1]);
2868 break;
2869 case SPELL_FAILED_TOTEM_CATEGORY:
2870 if(m_spellInfo->TotemCategory[0])
2871 data << uint32(m_spellInfo->TotemCategory[0]);
2872 if(m_spellInfo->TotemCategory[1])
2873 data << uint32(m_spellInfo->TotemCategory[1]);
2874 break;
2875 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2876 data << uint32(m_spellInfo->EquippedItemClass);
2877 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2878 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2879 break;
2880 default:
2881 break;
2883 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2886 void Spell::SendSpellStart()
2888 if(!IsNeedSendToClient())
2889 return;
2891 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2893 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2894 if(IsRangedSpell())
2895 castFlags |= CAST_FLAG_AMMO;
2897 if(m_spellInfo->runeCostID)
2898 castFlags |= CAST_FLAG_UNKNOWN10;
2900 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2901 if(m_CastItem)
2902 data.append(m_CastItem->GetPackGUID());
2903 else
2904 data.append(m_caster->GetPackGUID());
2906 data.append(m_caster->GetPackGUID());
2907 data << uint8(m_cast_count); // pending spell cast?
2908 data << uint32(m_spellInfo->Id); // spellId
2909 data << uint32(castFlags); // cast flags
2910 data << uint32(m_timer); // delay?
2912 m_targets.write(&data);
2914 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2915 data << uint32(0);
2917 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2919 uint8 v1 = 0;//m_runesState;
2920 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2921 data << uint8(v1); // runes state before
2922 data << uint8(v2); // runes state after
2923 for(uint8 i = 0; i < MAX_RUNES; ++i)
2925 uint8 m = (1 << i);
2926 if(m & v1) // usable before...
2927 if(!(m & v2)) // ...but on cooldown now...
2928 data << uint8(0); // some unknown byte (time?)
2932 if ( castFlags & CAST_FLAG_AMMO )
2933 WriteAmmoToPacket(&data);
2935 m_caster->SendMessageToSet(&data, true);
2938 void Spell::SendSpellGo()
2940 // not send invisible spell casting
2941 if(!IsNeedSendToClient())
2942 return;
2944 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2946 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2947 if(IsRangedSpell())
2948 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2950 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2952 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2953 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2954 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2957 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2959 if(m_CastItem)
2960 data.append(m_CastItem->GetPackGUID());
2961 else
2962 data.append(m_caster->GetPackGUID());
2964 data.append(m_caster->GetPackGUID());
2965 data << uint8(m_cast_count); // pending spell cast?
2966 data << uint32(m_spellInfo->Id); // spellId
2967 data << uint32(castFlags); // cast flags
2968 data << uint32(getMSTime()); // timestamp
2970 WriteSpellGoTargets(&data);
2972 m_targets.write(&data);
2974 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2975 data << uint32(0);
2977 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2979 uint8 v1 = m_runesState;
2980 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2981 data << uint8(v1); // runes state before
2982 data << uint8(v2); // runes state after
2983 for(uint8 i = 0; i < MAX_RUNES; ++i)
2985 uint8 m = (1 << i);
2986 if(m & v1) // usable before...
2987 if(!(m & v2)) // ...but on cooldown now...
2988 data << uint8(0); // some unknown byte (time?)
2992 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2994 data << float(0);
2995 data << uint32(0);
2998 if ( castFlags & CAST_FLAG_AMMO )
2999 WriteAmmoToPacket(&data);
3001 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
3003 data << uint32(0);
3004 data << uint32(0);
3007 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
3009 data << uint8(0);
3012 m_caster->SendMessageToSet(&data, true);
3015 void Spell::WriteAmmoToPacket( WorldPacket * data )
3017 uint32 ammoInventoryType = 0;
3018 uint32 ammoDisplayID = 0;
3020 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3022 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
3023 if(pItem)
3025 ammoInventoryType = pItem->GetProto()->InventoryType;
3026 if( ammoInventoryType == INVTYPE_THROWN )
3027 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
3028 else
3030 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
3031 if(ammoID)
3033 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
3034 if(pProto)
3036 ammoDisplayID = pProto->DisplayInfoID;
3037 ammoInventoryType = pProto->InventoryType;
3040 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
3042 ammoDisplayID = 5996; // normal arrow
3043 ammoInventoryType = INVTYPE_AMMO;
3048 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
3050 *data << uint32(ammoDisplayID);
3051 *data << uint32(ammoInventoryType);
3054 void Spell::WriteSpellGoTargets( WorldPacket * data )
3056 // This function also fill data for channeled spells:
3057 // m_needAliveTargetMask req for stop channelig if one target die
3058 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3059 uint32 miss = 0;
3060 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3062 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3064 // possibly SPELL_MISS_IMMUNE2 for this??
3065 ihit->missCondition = SPELL_MISS_IMMUNE2;
3066 miss++;
3068 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3069 hit++;
3070 else
3071 miss++;
3074 *data << (uint8)hit;
3075 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3076 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3078 *data << uint64(ihit->targetGUID);
3079 m_needAliveTargetMask |=ihit->effectMask;
3082 for(std::list<GOTargetInfo>::const_iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3083 *data << uint64(ighit->targetGUID); // Always hits
3085 *data << (uint8)miss;
3086 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3088 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3090 *data << uint64(ihit->targetGUID);
3091 *data << uint8(ihit->missCondition);
3092 if( ihit->missCondition == SPELL_MISS_REFLECT )
3093 *data << uint8(ihit->reflectResult);
3096 // Reset m_needAliveTargetMask for non channeled spell
3097 if(!IsChanneledSpell(m_spellInfo))
3098 m_needAliveTargetMask = 0;
3101 void Spell::SendLogExecute()
3103 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3105 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3107 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3108 data.append(m_caster->GetPackGUID());
3109 else
3110 data.append(target->GetPackGUID());
3112 data << uint32(m_spellInfo->Id);
3113 uint32 count1 = 1;
3114 data << uint32(count1); // count1 (effect count?)
3115 for(uint32 i = 0; i < count1; ++i)
3117 data << uint32(m_spellInfo->Effect[0]); // spell effect
3118 uint32 count2 = 1;
3119 data << uint32(count2); // count2 (target count?)
3120 for(uint32 j = 0; j < count2; ++j)
3122 switch(m_spellInfo->Effect[0])
3124 case SPELL_EFFECT_POWER_DRAIN:
3125 if(Unit *unit = m_targets.getUnitTarget())
3126 data.append(unit->GetPackGUID());
3127 else
3128 data << uint8(0);
3129 data << uint32(0);
3130 data << uint32(0);
3131 data << float(0);
3132 break;
3133 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3134 if(Unit *unit = m_targets.getUnitTarget())
3135 data.append(unit->GetPackGUID());
3136 else
3137 data << uint8(0);
3138 data << uint32(0); // count?
3139 break;
3140 case SPELL_EFFECT_INTERRUPT_CAST:
3141 if(Unit *unit = m_targets.getUnitTarget())
3142 data.append(unit->GetPackGUID());
3143 else
3144 data << uint8(0);
3145 data << uint32(0); // spellid
3146 break;
3147 case SPELL_EFFECT_DURABILITY_DAMAGE:
3148 if(Unit *unit = m_targets.getUnitTarget())
3149 data.append(unit->GetPackGUID());
3150 else
3151 data << uint8(0);
3152 data << uint32(0);
3153 data << uint32(0);
3154 break;
3155 case SPELL_EFFECT_OPEN_LOCK:
3156 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3157 if(Item *item = m_targets.getItemTarget())
3158 data.append(item->GetPackGUID());
3159 else
3160 data << uint8(0);
3161 break;
3162 case SPELL_EFFECT_CREATE_ITEM:
3163 case SPELL_EFFECT_CREATE_ITEM_2:
3164 data << uint32(m_spellInfo->EffectItemType[0]);
3165 break;
3166 case SPELL_EFFECT_SUMMON:
3167 case SPELL_EFFECT_TRANS_DOOR:
3168 case SPELL_EFFECT_SUMMON_PET:
3169 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3170 case SPELL_EFFECT_CREATE_HOUSE:
3171 case SPELL_EFFECT_DUEL:
3172 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3173 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3174 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3175 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3176 if(Unit *unit = m_targets.getUnitTarget())
3177 data.append(unit->GetPackGUID());
3178 else if(m_targets.getItemTargetGUID())
3179 data.appendPackGUID(m_targets.getItemTargetGUID());
3180 else if(GameObject *go = m_targets.getGOTarget())
3181 data.append(go->GetPackGUID());
3182 else
3183 data << uint8(0); // guid
3184 break;
3185 case SPELL_EFFECT_FEED_PET:
3186 data << uint32(m_targets.getItemTargetEntry());
3187 break;
3188 case SPELL_EFFECT_DISMISS_PET:
3189 if(Unit *unit = m_targets.getUnitTarget())
3190 data.append(unit->GetPackGUID());
3191 else
3192 data << uint8(0);
3193 break;
3194 case SPELL_EFFECT_RESURRECT:
3195 case SPELL_EFFECT_RESURRECT_NEW:
3196 if(Unit *unit = m_targets.getUnitTarget())
3197 data.append(unit->GetPackGUID());
3198 else
3199 data << uint8(0);
3200 break;
3201 default:
3202 return;
3207 m_caster->SendMessageToSet(&data, true);
3210 void Spell::SendInterrupted(uint8 result)
3212 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3213 data.append(m_caster->GetPackGUID());
3214 data << uint8(m_cast_count);
3215 data << uint32(m_spellInfo->Id);
3216 data << uint8(result);
3217 m_caster->SendMessageToSet(&data, true);
3219 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3220 data.append(m_caster->GetPackGUID());
3221 data << uint8(m_cast_count);
3222 data << uint32(m_spellInfo->Id);
3223 data << uint8(result);
3224 m_caster->SendMessageToSet(&data, true);
3227 void Spell::SendChannelUpdate(uint32 time)
3229 if(time == 0)
3231 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3232 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3235 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3236 return;
3238 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3239 data.append(m_caster->GetPackGUID());
3240 data << uint32(time);
3242 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3245 void Spell::SendChannelStart(uint32 duration)
3247 WorldObject* target = NULL;
3249 // select first not resisted target from target list for _0_ effect
3250 if(!m_UniqueTargetInfo.empty())
3252 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3254 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3256 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3257 break;
3261 else if(!m_UniqueGOTargetInfo.empty())
3263 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3265 if(itr->effectMask & (1<<0) )
3267 target = m_caster->GetMap()->GetGameObject(itr->targetGUID);
3268 break;
3273 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3275 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3276 data.append(m_caster->GetPackGUID());
3277 data << uint32(m_spellInfo->Id);
3278 data << uint32(duration);
3280 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3283 m_timer = duration;
3284 if(target)
3285 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3286 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3289 void Spell::SendResurrectRequest(Player* target)
3291 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3292 // However, the packet structure differs slightly
3294 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3296 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3297 data << uint64(m_caster->GetGUID());
3298 data << uint32(strlen(sentName)+1);
3300 data << sentName;
3301 data << uint8(0);
3303 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3304 target->GetSession()->SendPacket(&data);
3307 void Spell::SendPlaySpellVisual(uint32 SpellID)
3309 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3310 return;
3312 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3313 data << uint64(m_caster->GetGUID());
3314 data << uint32(SpellID); // spell visual id?
3315 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3318 void Spell::TakeCastItem()
3320 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3321 return;
3323 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3324 if(m_IsTriggeredSpell)
3325 return;
3327 ItemPrototype const *proto = m_CastItem->GetProto();
3329 if(!proto)
3331 // This code is to avoid a crash
3332 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3333 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3334 return;
3337 bool expendable = false;
3338 bool withoutCharges = false;
3340 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
3342 if (proto->Spells[i].SpellId)
3344 // item has limited charges
3345 if (proto->Spells[i].SpellCharges)
3347 if (proto->Spells[i].SpellCharges < 0)
3348 expendable = true;
3350 int32 charges = m_CastItem->GetSpellCharges(i);
3352 // item has charges left
3353 if (charges)
3355 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3356 if (proto->Stackable == 1)
3357 m_CastItem->SetSpellCharges(i, charges);
3358 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3361 // all charges used
3362 withoutCharges = (charges == 0);
3367 if (expendable && withoutCharges)
3369 uint32 count = 1;
3370 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3372 // prevent crash at access to deleted m_targets.getItemTarget
3373 if(m_CastItem==m_targets.getItemTarget())
3374 m_targets.setItemTarget(NULL);
3376 m_CastItem = NULL;
3380 void Spell::TakePower()
3382 if(m_CastItem || m_triggeredByAuraSpell)
3383 return;
3385 // health as power used
3386 if(m_spellInfo->powerType == POWER_HEALTH)
3388 m_caster->ModifyHealth( -(int32)m_powerCost );
3389 return;
3392 if(m_spellInfo->powerType >= MAX_POWERS)
3394 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3395 return;
3398 Powers powerType = Powers(m_spellInfo->powerType);
3400 if(powerType == POWER_RUNE)
3402 TakeRunePower();
3403 return;
3406 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3408 // Set the five second timer
3409 if (powerType == POWER_MANA && m_powerCost > 0)
3410 m_caster->SetLastManaUse(getMSTime());
3413 SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
3415 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3416 return SPELL_CAST_OK;
3418 Player *plr = (Player*)m_caster;
3420 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3421 return SPELL_CAST_OK;
3423 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3425 if(!src)
3426 return SPELL_CAST_OK;
3428 if(src->NoRuneCost())
3429 return SPELL_CAST_OK;
3431 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3433 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3434 runeCost[i] = src->RuneCost[i];
3436 runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
3438 for(uint32 i = 0; i < MAX_RUNES; ++i)
3440 uint8 rune = plr->GetCurrentRune(i);
3441 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3442 runeCost[rune]--;
3445 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3446 if(runeCost[i] > 0)
3447 runeCost[RUNE_DEATH] += runeCost[i];
3449 if(runeCost[RUNE_DEATH] > MAX_RUNES)
3450 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3452 return SPELL_CAST_OK;
3455 void Spell::TakeRunePower()
3457 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3458 return;
3460 Player *plr = (Player*)m_caster;
3462 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3463 return;
3465 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3467 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3468 return;
3470 m_runesState = plr->GetRunesState(); // store previous state
3472 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3474 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3476 runeCost[i] = src->RuneCost[i];
3479 runeCost[RUNE_DEATH] = 0; // calculated later
3481 for(uint32 i = 0; i < MAX_RUNES; ++i)
3483 uint8 rune = plr->GetCurrentRune(i);
3484 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3486 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3487 runeCost[rune]--;
3491 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3493 if(runeCost[RUNE_DEATH] > 0)
3495 for(uint32 i = 0; i < MAX_RUNES; ++i)
3497 uint8 rune = plr->GetCurrentRune(i);
3498 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3500 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3501 runeCost[rune]--;
3502 plr->ConvertRune(i, plr->GetBaseRune(i));
3503 if(runeCost[RUNE_DEATH] == 0)
3504 break;
3509 // you can gain some runic power when use runes
3510 float rp = src->runePowerGain;;
3511 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3512 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3515 void Spell::TakeReagents()
3517 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3518 return;
3520 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3521 return;
3523 Player* p_caster = (Player*)m_caster;
3524 if (p_caster->CanNoReagentCast(m_spellInfo))
3525 return;
3527 for(uint32 x=0;x<8;x++)
3529 if(m_spellInfo->Reagent[x] <= 0)
3530 continue;
3532 uint32 itemid = m_spellInfo->Reagent[x];
3533 uint32 itemcount = m_spellInfo->ReagentCount[x];
3535 // if CastItem is also spell reagent
3536 if (m_CastItem)
3538 ItemPrototype const *proto = m_CastItem->GetProto();
3539 if( proto && proto->ItemId == itemid )
3541 for(int s=0;s < MAX_ITEM_PROTO_SPELLS; ++s)
3543 // CastItem will be used up and does not count as reagent
3544 int32 charges = m_CastItem->GetSpellCharges(s);
3545 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3547 ++itemcount;
3548 break;
3552 m_CastItem = NULL;
3556 // if getItemTarget is also spell reagent
3557 if (m_targets.getItemTargetEntry()==itemid)
3558 m_targets.setItemTarget(NULL);
3560 p_caster->DestroyItemCount(itemid, itemcount, true);
3564 void Spell::HandleThreatSpells(uint32 spellId)
3566 if(!m_targets.getUnitTarget() || !spellId)
3567 return;
3569 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3570 return;
3572 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3573 if(!threatSpell)
3574 return;
3576 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3578 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3581 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3583 unitTarget = pUnitTarget;
3584 itemTarget = pItemTarget;
3585 gameObjTarget = pGOTarget;
3587 uint8 eff = m_spellInfo->Effect[i];
3589 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3591 sLog.outDebug( "Spell: Effect : %u", eff);
3593 if(eff<TOTAL_SPELL_EFFECTS)
3595 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3596 (*this.*SpellEffects[eff])(i);
3599 else
3601 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3602 if (m_CastItem)
3603 EffectEnchantItemTmp(i);
3604 else
3606 sLog.outError("SPELL: unknown effect %u spell id %u",
3607 eff, m_spellInfo->Id);
3613 void Spell::TriggerSpell()
3615 for(TriggerSpells::const_iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3617 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3618 spell->prepare(&m_targets); // use original spell original targets
3622 SpellCastResult Spell::CheckCast(bool strict)
3624 // check cooldowns to prevent cheating
3625 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3627 if(m_triggeredByAuraSpell)
3628 return SPELL_FAILED_DONT_REPORT;
3629 else
3630 return SPELL_FAILED_NOT_READY;
3633 // only allow triggered spells if at an ended battleground
3634 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3635 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3636 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3637 return SPELL_FAILED_DONT_REPORT;
3639 // only check at first call, Stealth auras are already removed at second call
3640 // for now, ignore triggered spells
3641 if( strict && !m_IsTriggeredSpell)
3643 bool checkForm = true;
3644 // Ignore form req aura
3645 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3646 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3648 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3649 continue;
3650 checkForm = false;
3651 break;
3653 if (checkForm)
3655 // Cannot be used in this stance/form
3656 SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form);
3657 if(shapeError != SPELL_CAST_OK)
3658 return shapeError;
3660 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3661 return SPELL_FAILED_ONLY_STEALTHED;
3665 // caster state requirements
3666 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3667 return SPELL_FAILED_CASTER_AURASTATE;
3668 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3669 return SPELL_FAILED_CASTER_AURASTATE;
3671 // Caster aura req check if need
3672 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3673 return SPELL_FAILED_CASTER_AURASTATE;
3674 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3675 return SPELL_FAILED_CASTER_AURASTATE;
3677 // cancel autorepeat spells if cast start when moving
3678 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3679 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3681 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3682 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3683 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3684 return SPELL_FAILED_MOVING;
3687 if(Unit *target = m_targets.getUnitTarget())
3689 // target state requirements (not allowed state), apply to self also
3690 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3691 return SPELL_FAILED_TARGET_AURASTATE;
3693 // Target aura req check if need
3694 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3695 return SPELL_FAILED_CASTER_AURASTATE;
3696 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3697 return SPELL_FAILED_CASTER_AURASTATE;
3699 if(target != m_caster)
3701 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3702 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3703 return SPELL_FAILED_TARGET_AURASTATE;
3705 // Not allow casting on flying player
3706 if (target->isInFlight())
3707 return SPELL_FAILED_BAD_TARGETS;
3709 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3710 return SPELL_FAILED_LINE_OF_SIGHT;
3712 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3713 // this case can be triggered if rank not found (too low-level target for first rank)
3714 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3715 for(int i=0;i<3;++i)
3716 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3717 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3718 return SPELL_FAILED_LOWLEVEL;
3720 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3722 // Additional check for some spells
3723 // If 0 spell effect empty - client not send target data (need use selection)
3724 // TODO: check it on next client version
3725 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3726 m_spellInfo->EffectImplicitTargetA[1] == TARGET_CHAIN_DAMAGE)
3728 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3729 m_targets.setUnitTarget(target);
3730 else
3731 return SPELL_FAILED_BAD_TARGETS;
3735 // check pet presents
3736 for(int j=0;j<3;j++)
3738 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3740 target = m_caster->GetPet();
3741 if(!target)
3743 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3744 return SPELL_FAILED_DONT_REPORT;
3745 else
3746 return SPELL_FAILED_NO_PET;
3748 break;
3752 //check creature type
3753 //ignore self casts (including area casts when caster selected as target)
3754 if(target != m_caster)
3756 if(!CheckTargetCreatureType(target))
3758 if(target->GetTypeId()==TYPEID_PLAYER)
3759 return SPELL_FAILED_TARGET_IS_PLAYER;
3760 else
3761 return SPELL_FAILED_BAD_TARGETS;
3765 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3766 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3767 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3769 // check correctness positive/negative cast target (pet cast real check and cheating check)
3770 if(IsPositiveSpell(m_spellInfo->Id))
3772 if(m_caster->IsHostileTo(target))
3773 return SPELL_FAILED_BAD_TARGETS;
3775 else
3777 if(m_caster->IsFriendlyTo(target))
3778 return SPELL_FAILED_BAD_TARGETS;
3782 if(IsPositiveSpell(m_spellInfo->Id))
3783 if(target->IsImmunedToSpell(m_spellInfo))
3784 return SPELL_FAILED_TARGET_AURASTATE;
3786 //Must be behind the target.
3787 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3789 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3790 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3792 SendInterrupted(2);
3793 return SPELL_FAILED_NOT_BEHIND;
3797 //Target must be facing you.
3798 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3800 SendInterrupted(2);
3801 return SPELL_FAILED_NOT_INFRONT;
3804 // check if target is in combat
3805 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3806 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3809 // Spell casted only on battleground
3810 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3811 if(!((Player*)m_caster)->InBattleGround())
3812 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3814 // do not allow spells to be cast in arenas
3815 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3816 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3817 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3818 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * IN_MILISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3819 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3820 if(mapEntry->IsBattleArena())
3821 return SPELL_FAILED_NOT_IN_ARENA;
3823 // zone check
3824 uint32 zone, area;
3825 m_caster->GetZoneAndAreaId(zone,area);
3827 SpellCastResult locRes= spellmgr.GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area,
3828 m_caster->GetTypeId()==TYPEID_PLAYER ? ((Player*)m_caster) : NULL);
3829 if(locRes != SPELL_CAST_OK)
3830 return locRes;
3832 // not let players cast spells at mount (and let do it to creatures)
3833 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3834 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3836 if(m_caster->isInFlight())
3837 return SPELL_FAILED_NOT_FLYING;
3838 else
3839 return SPELL_FAILED_NOT_MOUNTED;
3842 // always (except passive spells) check items (focus object can be required for any type casts)
3843 if(!IsPassiveSpell(m_spellInfo->Id))
3845 SpellCastResult castResult = CheckItems();
3846 if(castResult != SPELL_CAST_OK)
3847 return castResult;
3850 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3851 if(m_UniqueTargetInfo.empty()) // skip second CheckCast apply (for delayed spells for example)
3853 for(uint8 j = 0; j < 3; j++)
3855 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3856 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3857 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3858 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3860 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3861 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3862 if(lower==upper)
3863 sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT or TARGET_SCRIPT_COORDINATES, but does not have record in `spell_script_target`",m_spellInfo->Id);
3865 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3866 float range = GetSpellMaxRange(srange);
3868 Creature* creatureScriptTarget = NULL;
3869 GameObject* goScriptTarget = NULL;
3871 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3873 switch(i_spellST->second.type)
3875 case SPELL_TARGET_TYPE_GAMEOBJECT:
3877 GameObject* p_GameObject = NULL;
3879 if(i_spellST->second.targetEntry)
3881 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3882 Cell cell(p);
3883 cell.data.Part.reserved = ALL_DISTRICT;
3885 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3886 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
3888 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3889 CellLock<GridReadGuard> cell_lock(cell, p);
3890 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3892 if(p_GameObject)
3894 // remember found target and range, next attempt will find more near target with another entry
3895 creatureScriptTarget = NULL;
3896 goScriptTarget = p_GameObject;
3897 range = go_check.GetLastRange();
3900 else if( focusObject ) //Focus Object
3902 float frange = m_caster->GetDistance(focusObject);
3903 if(range >= frange)
3905 creatureScriptTarget = NULL;
3906 goScriptTarget = focusObject;
3907 range = frange;
3910 break;
3912 case SPELL_TARGET_TYPE_CREATURE:
3913 case SPELL_TARGET_TYPE_DEAD:
3914 default:
3916 Creature *p_Creature = NULL;
3918 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3919 Cell cell(p);
3920 cell.data.Part.reserved = ALL_DISTRICT;
3921 cell.SetNoCreate(); // Really don't know what is that???
3923 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3924 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
3926 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3928 CellLock<GridReadGuard> cell_lock(cell, p);
3929 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3931 if(p_Creature )
3933 creatureScriptTarget = p_Creature;
3934 goScriptTarget = NULL;
3935 range = u_check.GetLastRange();
3937 break;
3942 if(creatureScriptTarget)
3944 // store coordinates for TARGET_SCRIPT_COORDINATES
3945 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3946 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3948 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3950 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3951 AddUnitTarget(creatureScriptTarget, j);
3953 // store explicit target for TARGET_SCRIPT
3954 else
3955 AddUnitTarget(creatureScriptTarget, j);
3957 else if(goScriptTarget)
3959 // store coordinates for TARGET_SCRIPT_COORDINATES
3960 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3961 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3963 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3965 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3966 AddGOTarget(goScriptTarget, j);
3968 // store explicit target for TARGET_SCRIPT
3969 else
3970 AddGOTarget(goScriptTarget, j);
3972 //Missing DB Entry or targets for this spellEffect.
3973 else
3975 // not report target not existence for triggered spells
3976 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3977 return SPELL_FAILED_DONT_REPORT;
3978 else
3979 return SPELL_FAILED_BAD_TARGETS;
3985 if(!m_IsTriggeredSpell)
3987 SpellCastResult castResult = CheckRange(strict);
3988 if(castResult != SPELL_CAST_OK)
3989 return castResult;
3993 SpellCastResult castResult = CheckPower();
3994 if(castResult != SPELL_CAST_OK)
3995 return castResult;
3998 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
4000 SpellCastResult castResult = CheckCasterAuras();
4001 if(castResult != SPELL_CAST_OK)
4002 return castResult;
4005 for (int i = 0; i < 3; ++i)
4007 // for effects of spells that have only one target
4008 switch(m_spellInfo->Effect[i])
4010 case SPELL_EFFECT_DUMMY:
4012 if(m_spellInfo->SpellIconID == 1648) // Execute
4014 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4015 return SPELL_FAILED_BAD_TARGETS;
4017 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
4019 if(m_caster->IsInWater())
4020 return SPELL_FAILED_ONLY_ABOVEWATER;
4022 else if(m_spellInfo->SpellIconID==156) // Holy Shock
4024 // spell different for friends and enemies
4025 // hart version required facing
4026 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, m_targets.getUnitTarget() ))
4027 return SPELL_FAILED_UNIT_NOT_INFRONT;
4029 break;
4031 case SPELL_EFFECT_SCHOOL_DAMAGE:
4033 // Hammer of Wrath
4034 if(m_spellInfo->SpellVisual[0] == 7250)
4036 if (!m_targets.getUnitTarget())
4037 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4039 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4040 return SPELL_FAILED_BAD_TARGETS;
4042 break;
4044 case SPELL_EFFECT_TAMECREATURE:
4046 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
4047 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4049 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
4050 return SPELL_FAILED_HIGHLEVEL;
4052 // use SMSG_PET_TAME_FAILURE?
4053 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
4054 return SPELL_FAILED_BAD_TARGETS;
4056 if(m_caster->GetPetGUID())
4057 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4059 if(m_caster->GetCharmGUID())
4060 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4062 break;
4064 case SPELL_EFFECT_LEARN_SPELL:
4066 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4067 break;
4069 Pet* pet = m_caster->GetPet();
4071 if(!pet)
4072 return SPELL_FAILED_NO_PET;
4074 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4076 if(!learn_spellproto)
4077 return SPELL_FAILED_NOT_KNOWN;
4079 if(m_spellInfo->spellLevel > pet->getLevel())
4080 return SPELL_FAILED_LOWLEVEL;
4082 break;
4084 case SPELL_EFFECT_LEARN_PET_SPELL:
4086 Pet* pet = m_caster->GetPet();
4088 if(!pet)
4089 return SPELL_FAILED_NO_PET;
4091 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4093 if(!learn_spellproto)
4094 return SPELL_FAILED_NOT_KNOWN;
4096 if(m_spellInfo->spellLevel > pet->getLevel())
4097 return SPELL_FAILED_LOWLEVEL;
4099 break;
4101 case SPELL_EFFECT_FEED_PET:
4103 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4104 return SPELL_FAILED_BAD_TARGETS;
4106 Item* foodItem = m_targets.getItemTarget();
4107 if(!foodItem)
4108 return SPELL_FAILED_BAD_TARGETS;
4110 Pet* pet = m_caster->GetPet();
4112 if(!pet)
4113 return SPELL_FAILED_NO_PET;
4115 if(!pet->HaveInDiet(foodItem->GetProto()))
4116 return SPELL_FAILED_WRONG_PET_FOOD;
4118 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4119 return SPELL_FAILED_FOOD_LOWLEVEL;
4121 if(m_caster->isInCombat() || pet->isInCombat())
4122 return SPELL_FAILED_AFFECTING_COMBAT;
4124 break;
4126 case SPELL_EFFECT_POWER_BURN:
4127 case SPELL_EFFECT_POWER_DRAIN:
4129 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4130 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4131 if(Unit* target = m_targets.getUnitTarget())
4132 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4133 return SPELL_FAILED_BAD_TARGETS;
4134 break;
4136 case SPELL_EFFECT_CHARGE:
4138 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4139 return SPELL_FAILED_ROOTED;
4141 break;
4143 case SPELL_EFFECT_SKINNING:
4145 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4146 return SPELL_FAILED_BAD_TARGETS;
4148 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4149 return SPELL_FAILED_TARGET_UNSKINNABLE;
4151 Creature* creature = (Creature*)m_targets.getUnitTarget();
4152 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4154 return SPELL_FAILED_TARGET_NOT_LOOTED;
4157 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4159 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4160 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4161 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4162 if (ReqValue > skillValue)
4163 return SPELL_FAILED_LOW_CASTLEVEL;
4165 // chance for fail at orange skinning attempt
4166 if( (m_selfContainer && (*m_selfContainer) == this) &&
4167 skillValue < sWorld.GetConfigMaxSkillValue() &&
4168 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4169 return SPELL_FAILED_TRY_AGAIN;
4171 break;
4173 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4174 case SPELL_EFFECT_OPEN_LOCK:
4176 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4177 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4178 break;
4180 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4181 // we need a go target in case of TARGET_GAMEOBJECT
4182 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4183 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4184 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4185 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4186 return SPELL_FAILED_BAD_TARGETS;
4188 // In BattleGround players can use only flags and banners
4189 if( ((Player*)m_caster)->InBattleGround() &&
4190 !((Player*)m_caster)->CanUseBattleGroundObject() )
4191 return SPELL_FAILED_TRY_AGAIN;
4193 // get the lock entry
4194 uint32 lockId = 0;
4195 if (GameObject* go=m_targets.getGOTarget())
4196 lockId = go->GetLockId();
4197 else if(Item* itm=m_targets.getItemTarget())
4198 lockId = itm->GetProto()->LockID;
4200 SkillType skillId =SKILL_NONE;
4201 int32 reqSkillValue = 0;
4202 int32 skillValue = 0;
4204 // check lock compatibility
4205 SpellCastResult res = CanOpenLock(i,lockId,skillId,reqSkillValue,skillValue);
4206 if(res != SPELL_CAST_OK)
4207 return res;
4209 // chance for fail at orange mining/herb/LockPicking gathering attempt
4210 // second check prevent fail at rechecks
4211 if(skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
4213 bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
4215 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4216 if((canFailAtMax || skillValue < sWorld.GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue-25, skillValue+37))
4217 return SPELL_FAILED_TRY_AGAIN;
4219 break;
4221 case SPELL_EFFECT_SUMMON_DEAD_PET:
4223 Creature *pet = m_caster->GetPet();
4224 if(!pet)
4225 return SPELL_FAILED_NO_PET;
4227 if(pet->isAlive())
4228 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4230 break;
4232 // This is generic summon effect
4233 case SPELL_EFFECT_SUMMON:
4235 switch(m_spellInfo->EffectMiscValueB[i])
4237 case SUMMON_TYPE_POSESSED:
4238 case SUMMON_TYPE_POSESSED2:
4239 case SUMMON_TYPE_DEMON:
4240 case SUMMON_TYPE_SUMMON:
4242 if(m_caster->GetPetGUID())
4243 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4245 if(m_caster->GetCharmGUID())
4246 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4247 break;
4250 break;
4252 // Not used for summon?
4253 case SPELL_EFFECT_SUMMON_PHANTASM:
4255 if(m_caster->GetPetGUID())
4256 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4258 if(m_caster->GetCharmGUID())
4259 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4261 break;
4263 case SPELL_EFFECT_SUMMON_PET:
4265 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4268 Pet* pet = ((Player*)m_caster)->GetPet();
4270 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4272 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4273 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4275 else
4276 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4279 if(m_caster->GetCharmGUID())
4280 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4282 break;
4284 case SPELL_EFFECT_SUMMON_PLAYER:
4286 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4287 return SPELL_FAILED_BAD_TARGETS;
4288 if(!((Player*)m_caster)->GetSelection())
4289 return SPELL_FAILED_BAD_TARGETS;
4291 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4292 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4293 return SPELL_FAILED_BAD_TARGETS;
4295 // check if our map is dungeon
4296 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4298 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4299 if(!instance)
4300 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4301 if ( instance->levelMin > target->getLevel() )
4302 return SPELL_FAILED_LOWLEVEL;
4303 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4304 return SPELL_FAILED_HIGHLEVEL;
4306 break;
4308 case SPELL_EFFECT_LEAP:
4309 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4311 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4312 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4313 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4314 // teleport a bit above terrain level to avoid falling below it
4315 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4316 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4317 return SPELL_FAILED_TRY_AGAIN;
4319 float caster_pos_z = m_caster->GetPositionZ();
4320 // Control the caster to not climb or drop when +-fz > 8
4321 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4322 return SPELL_FAILED_TRY_AGAIN;
4324 // not allow use this effect at battleground until battleground start
4325 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4326 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4327 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4328 return SPELL_FAILED_TRY_AGAIN;
4329 break;
4331 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4333 if (m_targets.getUnitTarget()==m_caster)
4334 return SPELL_FAILED_BAD_TARGETS;
4335 break;
4337 default:break;
4341 for (int i = 0; i < 3; ++i)
4343 switch(m_spellInfo->EffectApplyAuraName[i])
4345 case SPELL_AURA_DUMMY:
4347 //custom check
4348 switch(m_spellInfo->Id)
4350 case 61336:
4351 if(m_caster->GetTypeId()!=TYPEID_PLAYER || !((Player*)m_caster)->IsInFeralForm())
4352 return SPELL_FAILED_ONLY_SHAPESHIFT;
4353 break;
4354 default:
4355 break;
4357 break;
4359 case SPELL_AURA_MOD_POSSESS:
4360 case SPELL_AURA_MOD_CHARM:
4362 if(m_caster->GetPetGUID())
4363 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4365 if(m_caster->GetCharmGUID())
4366 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4368 if(m_caster->GetCharmerGUID())
4369 return SPELL_FAILED_CHARMED;
4371 if(!m_targets.getUnitTarget())
4372 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4374 if(m_targets.getUnitTarget()->GetCharmerGUID())
4375 return SPELL_FAILED_CHARMED;
4377 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4378 return SPELL_FAILED_HIGHLEVEL;
4380 break;
4382 case SPELL_AURA_MOUNTED:
4384 if (m_caster->IsInWater())
4385 return SPELL_FAILED_ONLY_ABOVEWATER;
4387 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4388 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4390 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4391 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4392 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4394 ShapeshiftForm form = m_caster->m_form;
4395 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4396 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4397 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4398 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4399 return SPELL_FAILED_NOT_SHAPESHIFT;
4401 break;
4403 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4405 if(!m_targets.getUnitTarget())
4406 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4408 // can be casted at non-friendly unit or own pet/charm
4409 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4410 return SPELL_FAILED_TARGET_FRIENDLY;
4412 break;
4414 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4415 case SPELL_AURA_FLY:
4417 // not allow cast fly spells at old maps by players (all spells is self target)
4418 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4420 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4421 return SPELL_FAILED_NOT_HERE;
4424 break;
4426 case SPELL_AURA_PERIODIC_MANA_LEECH:
4428 if (!m_targets.getUnitTarget())
4429 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4431 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4432 break;
4434 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4435 return SPELL_FAILED_BAD_TARGETS;
4437 break;
4439 default:
4440 break;
4444 // all ok
4445 return SPELL_CAST_OK;
4448 SpellCastResult Spell::CheckPetCast(Unit* target)
4450 if(!m_caster->isAlive())
4451 return SPELL_FAILED_CASTER_DEAD;
4453 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4454 return SPELL_FAILED_SPELL_IN_PROGRESS;
4455 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4456 return SPELL_FAILED_AFFECTING_COMBAT;
4458 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4460 //dead owner (pets still alive when owners ressed?)
4461 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4462 return SPELL_FAILED_CASTER_DEAD;
4464 if(!target && m_targets.getUnitTarget())
4465 target = m_targets.getUnitTarget();
4467 bool need = false;
4468 for(uint32 i = 0;i<3;++i)
4470 if(m_spellInfo->EffectImplicitTargetA[i] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_FRIEND || m_spellInfo->EffectImplicitTargetA[i] == TARGET_DUELVSPLAYER || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_PARTY || m_spellInfo->EffectImplicitTargetA[i] == TARGET_CURRENT_ENEMY_COORDINATES)
4472 need = true;
4473 if(!target)
4474 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4475 break;
4478 if(need)
4479 m_targets.setUnitTarget(target);
4481 Unit* _target = m_targets.getUnitTarget();
4483 if(_target) //for target dead/target not valid
4485 if(!_target->isAlive())
4486 return SPELL_FAILED_BAD_TARGETS;
4488 if(IsPositiveSpell(m_spellInfo->Id))
4490 if(m_caster->IsHostileTo(_target))
4491 return SPELL_FAILED_BAD_TARGETS;
4493 else
4495 bool duelvsplayertar = false;
4496 for(int j=0;j<3;j++)
4498 //TARGET_DUELVSPLAYER is positive AND negative
4499 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4501 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4503 return SPELL_FAILED_BAD_TARGETS;
4507 //cooldown
4508 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4509 return SPELL_FAILED_NOT_READY;
4512 return CheckCast(true);
4515 SpellCastResult Spell::CheckCasterAuras() const
4517 // Flag drop spells totally immuned to caster auras
4518 // FIXME: find more nice check for all totally immuned spells
4519 // AttributesEx3 & 0x10000000?
4520 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4521 return SPELL_CAST_OK;
4523 uint8 school_immune = 0;
4524 uint32 mechanic_immune = 0;
4525 uint32 dispel_immune = 0;
4527 //Check if the spell grants school or mechanic immunity.
4528 //We use bitmasks so the loop is done only once and not on every aura check below.
4529 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4531 for(int i = 0;i < 3; i ++)
4533 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4534 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4535 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4536 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4537 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4538 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4540 //immune movement impairment and loss of control
4541 if(m_spellInfo->Id==(uint32)42292)
4542 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4545 //Check whether the cast should be prevented by any state you might have.
4546 SpellCastResult prevented_reason = SPELL_CAST_OK;
4547 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4548 uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
4549 if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4550 prevented_reason = SPELL_FAILED_STUNNED;
4551 else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4552 prevented_reason = SPELL_FAILED_CONFUSED;
4553 else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4554 prevented_reason = SPELL_FAILED_FLEEING;
4555 else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4556 prevented_reason = SPELL_FAILED_SILENCED;
4557 else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4558 prevented_reason = SPELL_FAILED_PACIFIED;
4560 // Attr must make flag drop spell totally immune from all effects
4561 if(prevented_reason != SPELL_CAST_OK)
4563 if(school_immune || mechanic_immune || dispel_immune)
4565 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4566 Unit::AuraMap const& auras = m_caster->GetAuras();
4567 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4569 if(itr->second)
4571 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4572 continue;
4573 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4574 continue;
4575 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4576 continue;
4578 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4579 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4580 switch(itr->second->GetModifier()->m_auraname)
4582 case SPELL_AURA_MOD_STUN:
4583 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4584 return SPELL_FAILED_STUNNED;
4585 break;
4586 case SPELL_AURA_MOD_CONFUSE:
4587 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4588 return SPELL_FAILED_CONFUSED;
4589 break;
4590 case SPELL_AURA_MOD_FEAR:
4591 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4592 return SPELL_FAILED_FLEEING;
4593 break;
4594 case SPELL_AURA_MOD_SILENCE:
4595 case SPELL_AURA_MOD_PACIFY:
4596 case SPELL_AURA_MOD_PACIFY_SILENCE:
4597 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4598 return SPELL_FAILED_PACIFIED;
4599 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4600 return SPELL_FAILED_SILENCED;
4601 break;
4606 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4607 else
4608 return prevented_reason;
4610 return SPELL_CAST_OK;
4613 bool Spell::CanAutoCast(Unit* target)
4615 uint64 targetguid = target->GetGUID();
4617 for(uint32 j = 0;j<3;j++)
4619 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4621 if( m_spellInfo->StackAmount <= 1)
4623 if( target->HasAura(m_spellInfo->Id, j) )
4624 return false;
4626 else
4628 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4629 return false;
4632 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4634 if( target->HasAura(m_spellInfo->Id, j) )
4635 return false;
4639 SpellCastResult result = CheckPetCast(target);
4641 if(result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4643 FillTargetMap();
4644 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4645 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4646 if( ihit->targetGUID == targetguid )
4647 return true;
4649 return false; //target invalid
4652 SpellCastResult Spell::CheckRange(bool strict)
4654 float range_mod;
4656 // self cast doesn't need range checking -- also for Starshards fix
4657 if (m_spellInfo->rangeIndex == 1)
4658 return SPELL_CAST_OK;
4660 if (strict) //add radius of caster
4661 range_mod = 1.25;
4662 else //add radius of caster and ~5 yds "give"
4663 range_mod = 6.25;
4665 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4666 float max_range = GetSpellMaxRange(srange) + range_mod;
4667 float min_range = GetSpellMinRange(srange);
4669 if(Player* modOwner = m_caster->GetSpellModOwner())
4670 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4672 Unit *target = m_targets.getUnitTarget();
4674 if(target && target != m_caster)
4676 // distance from target in checks
4677 float dist = m_caster->GetCombatDistance(target);
4679 if(dist > max_range)
4680 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4681 if(dist < min_range)
4682 return SPELL_FAILED_TOO_CLOSE;
4683 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4684 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4685 return SPELL_FAILED_UNIT_NOT_INFRONT;
4688 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4690 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4691 if(dist > max_range)
4692 return SPELL_FAILED_OUT_OF_RANGE;
4693 if(dist < min_range)
4694 return SPELL_FAILED_TOO_CLOSE;
4697 return SPELL_CAST_OK;
4700 int32 Spell::CalculatePowerCost()
4702 // item cast not used power
4703 if(m_CastItem)
4704 return 0;
4706 // Spell drain all exist power on cast (Only paladin lay of Hands)
4707 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4709 // If power type - health drain all
4710 if (m_spellInfo->powerType == POWER_HEALTH)
4711 return m_caster->GetHealth();
4712 // Else drain all power
4713 if (m_spellInfo->powerType < MAX_POWERS)
4714 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4715 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4716 return 0;
4719 // Base powerCost
4720 int32 powerCost = m_spellInfo->manaCost;
4721 // PCT cost from total amount
4722 if (m_spellInfo->ManaCostPercentage)
4724 switch (m_spellInfo->powerType)
4726 // health as power used
4727 case POWER_HEALTH:
4728 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4729 break;
4730 case POWER_MANA:
4731 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4732 break;
4733 case POWER_RAGE:
4734 case POWER_FOCUS:
4735 case POWER_ENERGY:
4736 case POWER_HAPPINESS:
4737 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4738 break;
4739 case POWER_RUNE:
4740 case POWER_RUNIC_POWER:
4741 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4742 break;
4743 default:
4744 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4745 return 0;
4748 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4749 // Flat mod from caster auras by spell school
4750 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4751 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4752 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4753 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4754 // Apply cost mod by spell
4755 if(Player* modOwner = m_caster->GetSpellModOwner())
4756 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4758 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4759 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4761 // PCT mod from user auras by school
4762 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4763 if (powerCost < 0)
4764 powerCost = 0;
4765 return powerCost;
4768 SpellCastResult Spell::CheckPower()
4770 // item cast not used power
4771 if(m_CastItem)
4772 return SPELL_CAST_OK;
4774 // health as power used - need check health amount
4775 if(m_spellInfo->powerType == POWER_HEALTH)
4777 if(m_caster->GetHealth() <= m_powerCost)
4778 return SPELL_FAILED_CASTER_AURASTATE;
4779 return SPELL_CAST_OK;
4781 // Check valid power type
4782 if( m_spellInfo->powerType >= MAX_POWERS )
4784 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4785 return SPELL_FAILED_UNKNOWN;
4788 SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID);
4789 if(failReason != SPELL_CAST_OK)
4790 return failReason;
4792 // Check power amount
4793 Powers powerType = Powers(m_spellInfo->powerType);
4794 if(m_caster->GetPower(powerType) < m_powerCost)
4795 return SPELL_FAILED_NO_POWER;
4796 else
4797 return SPELL_CAST_OK;
4800 SpellCastResult Spell::CheckItems()
4802 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4803 return SPELL_CAST_OK;
4805 Player* p_caster = (Player*)m_caster;
4807 // cast item checks
4808 if(m_CastItem)
4810 uint32 itemid = m_CastItem->GetEntry();
4811 if( !p_caster->HasItemCount(itemid,1) )
4812 return SPELL_FAILED_ITEM_NOT_READY;
4814 ItemPrototype const *proto = m_CastItem->GetProto();
4815 if(!proto)
4816 return SPELL_FAILED_ITEM_NOT_READY;
4818 for (int i = 0; i<5; ++i)
4819 if (proto->Spells[i].SpellCharges)
4820 if(m_CastItem->GetSpellCharges(i)==0)
4821 return SPELL_FAILED_NO_CHARGES_REMAIN;
4823 // consumable cast item checks
4824 if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4826 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4827 SpellCastResult failReason = SPELL_CAST_OK;
4828 for (int i = 0; i < 3; ++i)
4830 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4831 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4832 continue;
4834 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4836 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4838 failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4839 continue;
4841 else
4843 failReason = SPELL_CAST_OK;
4844 break;
4848 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4849 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4851 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4853 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4854 continue;
4857 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4858 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4860 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4861 continue;
4863 else
4865 failReason = SPELL_CAST_OK;
4866 break;
4870 if (failReason != SPELL_CAST_OK)
4871 return failReason;
4875 // check target item
4876 if(m_targets.getItemTargetGUID())
4878 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4879 return SPELL_FAILED_BAD_TARGETS;
4881 if(!m_targets.getItemTarget())
4882 return SPELL_FAILED_ITEM_GONE;
4884 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4885 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4887 // if not item target then required item must be equipped
4888 else
4890 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4891 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4894 // check spell focus object
4895 if(m_spellInfo->RequiresSpellFocus)
4897 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4898 Cell cell(p);
4899 cell.data.Part.reserved = ALL_DISTRICT;
4901 GameObject* ok = NULL;
4902 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4903 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(m_caster,ok,go_check);
4905 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4906 CellLock<GridReadGuard> cell_lock(cell, p);
4907 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4909 if(!ok)
4910 return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4912 focusObject = ok; // game object found in range
4915 // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
4916 if (!m_IsTriggeredSpell && !p_caster->CanNoReagentCast(m_spellInfo))
4918 for(uint32 i=0;i<8;++i)
4920 if(m_spellInfo->Reagent[i] <= 0)
4921 continue;
4923 uint32 itemid = m_spellInfo->Reagent[i];
4924 uint32 itemcount = m_spellInfo->ReagentCount[i];
4926 // if CastItem is also spell reagent
4927 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4929 ItemPrototype const *proto = m_CastItem->GetProto();
4930 if(!proto)
4931 return SPELL_FAILED_ITEM_NOT_READY;
4932 for(int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s)
4934 // CastItem will be used up and does not count as reagent
4935 int32 charges = m_CastItem->GetSpellCharges(s);
4936 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4938 ++itemcount;
4939 break;
4943 if( !p_caster->HasItemCount(itemid,itemcount) )
4944 return SPELL_FAILED_ITEM_NOT_READY; //0x54
4948 // check totem-item requirements (items presence in inventory)
4949 uint32 totems = 2;
4950 for(int i=0;i<2;++i)
4952 if(m_spellInfo->Totem[i] != 0)
4954 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4956 totems -= 1;
4957 continue;
4959 }else
4960 totems -= 1;
4962 if(totems != 0)
4963 return SPELL_FAILED_TOTEMS; //0x7C
4965 // Check items for TotemCategory (items presence in inventory)
4966 uint32 TotemCategory = 2;
4967 for(int i=0;i<2;++i)
4969 if(m_spellInfo->TotemCategory[i] != 0)
4971 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4973 TotemCategory -= 1;
4974 continue;
4977 else
4978 TotemCategory -= 1;
4980 if(TotemCategory != 0)
4981 return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
4983 // special checks for spell effects
4984 for(int i = 0; i < 3; ++i)
4986 switch (m_spellInfo->Effect[i])
4988 case SPELL_EFFECT_CREATE_ITEM:
4990 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4992 ItemPosCountVec dest;
4993 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4994 if (msg != EQUIP_ERR_OK )
4996 p_caster->SendEquipError( msg, NULL, NULL );
4997 return SPELL_FAILED_DONT_REPORT;
5000 break;
5002 case SPELL_EFFECT_ENCHANT_ITEM:
5003 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
5005 Item* targetItem = m_targets.getItemTarget();
5006 if(!targetItem)
5007 return SPELL_FAILED_ITEM_NOT_FOUND;
5009 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5010 return SPELL_FAILED_LOWLEVEL;
5011 // Not allow enchant in trade slot for some enchant type
5012 if( targetItem->GetOwner() != m_caster )
5014 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5015 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5016 if(!pEnchant)
5017 return SPELL_FAILED_ERROR;
5018 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5019 return SPELL_FAILED_NOT_TRADEABLE;
5021 break;
5023 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5025 Item *item = m_targets.getItemTarget();
5026 if(!item)
5027 return SPELL_FAILED_ITEM_NOT_FOUND;
5028 // Not allow enchant in trade slot for some enchant type
5029 if( item->GetOwner() != m_caster )
5031 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5032 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5033 if(!pEnchant)
5034 return SPELL_FAILED_ERROR;
5035 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5036 return SPELL_FAILED_NOT_TRADEABLE;
5038 break;
5040 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5041 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5042 break;
5043 case SPELL_EFFECT_DISENCHANT:
5045 if(!m_targets.getItemTarget())
5046 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5048 // prevent disenchanting in trade slot
5049 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5050 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5052 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5053 if(!itemProto)
5054 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5056 uint32 item_quality = itemProto->Quality;
5057 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5058 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5059 if (item_disenchantskilllevel == uint32(-1))
5060 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5061 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5062 return SPELL_FAILED_LOW_CASTLEVEL;
5063 if(item_quality > 4 || item_quality < 2)
5064 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5065 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5066 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5067 if (!itemProto->DisenchantID)
5068 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5069 break;
5071 case SPELL_EFFECT_PROSPECTING:
5073 if(!m_targets.getItemTarget())
5074 return SPELL_FAILED_CANT_BE_PROSPECTED;
5075 //ensure item is a prospectable ore
5076 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5077 return SPELL_FAILED_CANT_BE_PROSPECTED;
5078 //prevent prospecting in trade slot
5079 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5080 return SPELL_FAILED_CANT_BE_PROSPECTED;
5081 //Check for enough skill in jewelcrafting
5082 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5083 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5084 return SPELL_FAILED_LOW_CASTLEVEL;
5085 //make sure the player has the required ores in inventory
5086 if(m_targets.getItemTarget()->GetCount() < 5)
5087 return SPELL_FAILED_NEED_MORE_ITEMS;
5089 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5090 return SPELL_FAILED_CANT_BE_PROSPECTED;
5092 break;
5094 case SPELL_EFFECT_MILLING:
5096 if(!m_targets.getItemTarget())
5097 return SPELL_FAILED_CANT_BE_MILLED;
5098 //ensure item is a millable herb
5099 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5100 return SPELL_FAILED_CANT_BE_MILLED;
5101 //prevent milling in trade slot
5102 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5103 return SPELL_FAILED_CANT_BE_MILLED;
5104 //Check for enough skill in inscription
5105 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5106 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5107 return SPELL_FAILED_LOW_CASTLEVEL;
5108 //make sure the player has the required herbs in inventory
5109 if(m_targets.getItemTarget()->GetCount() < 5)
5110 return SPELL_FAILED_NEED_MORE_ITEMS;
5112 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5113 return SPELL_FAILED_CANT_BE_MILLED;
5115 break;
5117 case SPELL_EFFECT_WEAPON_DAMAGE:
5118 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5120 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5121 if( m_attackType != RANGED_ATTACK )
5122 break;
5123 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5124 if(!pItem || pItem->IsBroken())
5125 return SPELL_FAILED_EQUIPPED_ITEM;
5127 switch(pItem->GetProto()->SubClass)
5129 case ITEM_SUBCLASS_WEAPON_THROWN:
5131 uint32 ammo = pItem->GetEntry();
5132 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5133 return SPELL_FAILED_NO_AMMO;
5134 }; break;
5135 case ITEM_SUBCLASS_WEAPON_GUN:
5136 case ITEM_SUBCLASS_WEAPON_BOW:
5137 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5139 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5140 if(!ammo)
5142 // Requires No Ammo
5143 if(m_caster->GetDummyAura(46699))
5144 break; // skip other checks
5146 return SPELL_FAILED_NO_AMMO;
5149 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5150 if(!ammoProto)
5151 return SPELL_FAILED_NO_AMMO;
5153 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5154 return SPELL_FAILED_NO_AMMO;
5156 // check ammo ws. weapon compatibility
5157 switch(pItem->GetProto()->SubClass)
5159 case ITEM_SUBCLASS_WEAPON_BOW:
5160 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5161 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5162 return SPELL_FAILED_NO_AMMO;
5163 break;
5164 case ITEM_SUBCLASS_WEAPON_GUN:
5165 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5166 return SPELL_FAILED_NO_AMMO;
5167 break;
5168 default:
5169 return SPELL_FAILED_NO_AMMO;
5172 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5173 return SPELL_FAILED_NO_AMMO;
5174 }; break;
5175 case ITEM_SUBCLASS_WEAPON_WAND:
5176 default:
5177 break;
5179 break;
5181 default:break;
5185 return SPELL_CAST_OK;
5188 void Spell::Delayed()
5190 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5191 return;
5193 if (m_spellState == SPELL_STATE_DELAYED)
5194 return; // spell is active and can't be time-backed
5196 if(isDelayableNoMore()) // Spells may only be delayed twice
5197 return;
5199 // spells not loosing casting time ( slam, dynamites, bombs.. )
5200 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5201 return;
5203 //check pushback reduce
5204 int32 delaytime = 500; // spellcasting delay is normally 500ms
5205 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5206 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5207 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5208 if(delayReduce >= 100)
5209 return;
5211 delaytime = delaytime * (100 - delayReduce) / 100;
5213 if(int32(m_timer) + delaytime > m_casttime)
5215 delaytime = m_casttime - m_timer;
5216 m_timer = m_casttime;
5218 else
5219 m_timer += delaytime;
5221 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5223 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5224 data.append(m_caster->GetPackGUID());
5225 data << uint32(delaytime);
5227 m_caster->SendMessageToSet(&data,true);
5230 void Spell::DelayedChannel()
5232 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5233 return;
5235 if(isDelayableNoMore()) // Spells may only be delayed twice
5236 return;
5238 //check pushback reduce
5239 int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
5240 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5241 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,delayReduce, this);
5242 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5243 if(delayReduce >= 100)
5244 return;
5246 delaytime = delaytime * (100 - delayReduce) / 100;
5248 if(int32(m_timer) < delaytime)
5250 delaytime = m_timer;
5251 m_timer = 0;
5253 else
5254 m_timer -= delaytime;
5256 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5258 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5260 if ((*ihit).missCondition == SPELL_MISS_NONE)
5262 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5263 if (unit)
5265 for (int j=0;j<3;j++)
5266 if( ihit->effectMask & (1<<j) )
5267 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5273 for(int j = 0; j < 3; j++)
5275 // partially interrupt persistent area auras
5276 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5277 if(dynObj)
5278 dynObj->Delay(delaytime);
5281 SendChannelUpdate(m_timer);
5284 void Spell::UpdatePointers()
5286 if(m_originalCasterGUID==m_caster->GetGUID())
5287 m_originalCaster = m_caster;
5288 else
5290 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5291 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5294 m_targets.Update(m_caster);
5297 bool Spell::IsAffectedByAura(Aura *aura)
5299 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5302 bool Spell::CheckTargetCreatureType(Unit* target) const
5304 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5306 // Curse of Doom : not find another way to fix spell target check :/
5307 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5309 // not allow cast at player
5310 if(target->GetTypeId()==TYPEID_PLAYER)
5311 return false;
5313 spellCreatureTargetMask = 0x7FF;
5316 // Dismiss Pet and Taming Lesson skipped
5317 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5318 spellCreatureTargetMask = 0;
5320 if (spellCreatureTargetMask)
5322 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5324 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5326 return true;
5329 CurrentSpellTypes Spell::GetCurrentContainer()
5331 if (IsNextMeleeSwingSpell())
5332 return(CURRENT_MELEE_SPELL);
5333 else if (IsAutoRepeat())
5334 return(CURRENT_AUTOREPEAT_SPELL);
5335 else if (IsChanneledSpell(m_spellInfo))
5336 return(CURRENT_CHANNELED_SPELL);
5337 else
5338 return(CURRENT_GENERIC_SPELL);
5341 bool Spell::CheckTarget( Unit* target, uint32 eff )
5343 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5344 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5346 if (!CheckTargetCreatureType(target))
5347 return false;
5350 // Check Aura spell req (need for AoE spells)
5351 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5352 return false;
5353 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5354 return false;
5356 // Check targets for not_selectable unit flag and remove
5357 // A player can cast spells on his pet (or other controlled unit) though in any state
5358 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5360 // any unattackable target skipped
5361 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5362 return false;
5364 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5365 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5366 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5367 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5368 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5369 return false;
5372 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5373 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5375 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5376 return false;
5378 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5379 return false;
5382 //Check targets for LOS visibility (except spells without range limitations )
5383 switch(m_spellInfo->Effect[eff])
5385 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5386 break;
5387 case SPELL_EFFECT_DUMMY:
5388 if(m_spellInfo->Id!=20577) // Cannibalize
5389 break;
5390 //fall through
5391 case SPELL_EFFECT_RESURRECT_NEW:
5392 // player far away, maybe his corpse near?
5393 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5395 if(!m_targets.getCorpseTargetGUID())
5396 return false;
5398 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5399 if(!corpse)
5400 return false;
5402 if(target->GetGUID()!=corpse->GetOwnerGUID())
5403 return false;
5405 if(!corpse->IsWithinLOSInMap(m_caster))
5406 return false;
5409 // all ok by some way or another, skip normal check
5410 break;
5411 default: // normal case
5412 // Get GO cast coordinates if original caster -> GO
5413 WorldObject *caster = NULL;
5414 if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
5415 caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
5416 if (!caster)
5417 caster = m_caster;
5418 if(target!=m_caster && !target->IsWithinLOSInMap(caster))
5419 return false;
5420 break;
5423 return true;
5426 bool Spell::IsNeedSendToClient() const
5428 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5429 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5432 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5434 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5435 if(itr->effectMask & (1<<effect))
5436 return true;
5438 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5439 if(itr->effectMask & (1<<effect))
5440 return true;
5442 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5443 if(itr->effectMask & (1<<effect))
5444 return true;
5446 return false;
5449 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5451 m_Spell = spell;
5454 SpellEvent::~SpellEvent()
5456 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5457 m_Spell->cancel();
5459 if (m_Spell->IsDeletable())
5461 delete m_Spell;
5463 else
5465 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5466 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5470 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5472 // update spell if it is not finished
5473 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5474 m_Spell->update(p_time);
5476 // check spell state to process
5477 switch (m_Spell->getState())
5479 case SPELL_STATE_FINISHED:
5481 // spell was finished, check deletable state
5482 if (m_Spell->IsDeletable())
5484 // check, if we do have unfinished triggered spells
5486 return(true); // spell is deletable, finish event
5488 // event will be re-added automatically at the end of routine)
5489 } break;
5491 case SPELL_STATE_CASTING:
5493 // this spell is in channeled state, process it on the next update
5494 // event will be re-added automatically at the end of routine)
5495 } break;
5497 case SPELL_STATE_DELAYED:
5499 // first, check, if we have just started
5500 if (m_Spell->GetDelayStart() != 0)
5502 // no, we aren't, do the typical update
5503 // check, if we have channeled spell on our hands
5504 if (IsChanneledSpell(m_Spell->m_spellInfo))
5506 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5507 // check, if we have casting anything else except this channeled spell and autorepeat
5508 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5510 // another non-melee non-delayed spell is casted now, abort
5511 m_Spell->cancel();
5513 else
5515 // do the action (pass spell to channeling state)
5516 m_Spell->handle_immediate();
5518 // event will be re-added automatically at the end of routine)
5520 else
5522 // run the spell handler and think about what we can do next
5523 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5524 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5525 if (n_offset)
5527 // re-add us to the queue
5528 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5529 return(false); // event not complete
5531 // event complete
5532 // finish update event will be re-added automatically at the end of routine)
5535 else
5537 // delaying had just started, record the moment
5538 m_Spell->SetDelayStart(e_time);
5539 // re-plan the event for the delay moment
5540 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5541 return(false); // event not complete
5543 } break;
5545 default:
5547 // all other states
5548 // event will be re-added automatically at the end of routine)
5549 } break;
5552 // spell processing not complete, plan event on the next update interval
5553 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5554 return(false); // event not complete
5557 void SpellEvent::Abort(uint64 /*e_time*/)
5559 // oops, the spell we try to do is aborted
5560 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5561 m_Spell->cancel();
5564 bool SpellEvent::IsDeletable() const
5566 return m_Spell->IsDeletable();
5569 SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
5571 if(!lockId) // possible case for GO and maybe for items.
5572 return SPELL_CAST_OK;
5574 // Get LockInfo
5575 LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
5577 if (!lockInfo)
5578 return SPELL_FAILED_BAD_TARGETS;
5580 bool reqKey = false; // some locks not have reqs
5582 for(int j = 0; j < 8; ++j)
5584 switch(lockInfo->Type[j])
5586 // check key item (many fit cases can be)
5587 case LOCK_KEY_ITEM:
5588 if(lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[j])
5589 return SPELL_CAST_OK;
5590 reqKey = true;
5591 break;
5592 // check key skill (only single first fit case can be)
5593 case LOCK_KEY_SKILL:
5595 reqKey = true;
5597 // wrong locktype, skip
5598 if(uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j])
5599 continue;
5601 skillId = SkillByLockType(LockType(lockInfo->Index[j]));
5603 if ( skillId != SKILL_NONE )
5605 // skill bonus provided by casting spell (mostly item spells)
5606 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
5607 uint32 spellSkillBonus = uint32(m_currentBasePoints[effIndex]+1);
5608 reqSkillValue = lockInfo->Skill[j];
5610 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
5611 skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
5612 0 : ((Player*)m_caster)->GetSkillValue(skillId);
5614 skillValue += spellSkillBonus;
5616 if (skillValue < reqSkillValue)
5617 return SPELL_FAILED_LOW_CASTLEVEL;
5620 return SPELL_CAST_OK;
5625 if(reqKey)
5626 return SPELL_FAILED_BAD_TARGETS;
5628 return SPELL_CAST_OK;
5631 void Spell::FillAreaTargets( UnitList& TagUnitMap, float x, float y, float radius, SpellNotifyPushType pushType, SpellTargets spellTargets )
5633 CellPair p(MaNGOS::ComputeCellPair(x, y));
5634 Cell cell(p);
5635 cell.data.Part.reserved = ALL_DISTRICT;
5636 cell.SetNoCreate();
5637 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, pushType, spellTargets);
5638 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
5639 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
5640 CellLock<GridReadGuard> cell_lock(cell, p);
5641 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
5642 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());