[7587] Hmm, lost change.
[AHbot.git] / src / game / Spell.cpp
blob104b9546f0d1344d5048cf08a964c2908291add4
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 ? ObjectAccessor::GetGameObject(*caster,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_BEHIND_VICTIM: // use B case that not dependent from from A in fact
461 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
462 break;
463 default:
464 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
465 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
466 break;
468 break;
469 case TARGET_CASTER_COORDINATES:
470 // Note: this hack with search required until GO casting not implemented
471 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
472 // currently each enemy selected explicitly and self cast damage
473 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
475 if(m_targets.getUnitTarget())
476 tmpUnitMap.push_back(m_targets.getUnitTarget());
478 else
480 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
481 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
483 break;
484 case TARGET_TABLE_X_Y_Z_COORDINATES:
485 // Only if target A, for target B (used in teleports) dest select in effect
486 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
487 break;
488 default:
489 switch(m_spellInfo->EffectImplicitTargetB[i])
491 case 0:
492 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
493 break;
494 case TARGET_SCRIPT_COORDINATES: // B case filled in CheckCast but we need fill unit list base at A case
495 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
496 break;
497 default:
498 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
499 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
500 break;
502 break;
505 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
506 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
508 // add here custom effects that need default target.
509 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
510 switch(m_spellInfo->Effect[i])
512 case SPELL_EFFECT_DUMMY:
514 switch(m_spellInfo->Id)
516 case 20577: // Cannibalize
518 // non-standard target selection
519 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
520 float max_range = GetSpellMaxRange(srange);
522 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
523 Cell cell(p);
524 cell.data.Part.reserved = ALL_DISTRICT;
525 cell.SetNoCreate();
527 WorldObject* result = NULL;
529 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
530 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(m_caster, result, u_check);
532 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
533 CellLock<GridReadGuard> cell_lock(cell, p);
534 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
536 if(!result)
538 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
539 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
542 if(result)
544 switch(result->GetTypeId())
546 case TYPEID_UNIT:
547 case TYPEID_PLAYER:
548 tmpUnitMap.push_back((Unit*)result);
549 break;
550 case TYPEID_CORPSE:
551 m_targets.setCorpseTarget((Corpse*)result);
552 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
553 tmpUnitMap.push_back(owner);
554 break;
557 else
559 // clear cooldown at fail
560 if(m_caster->GetTypeId()==TYPEID_PLAYER)
562 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
564 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
565 data << uint32(m_spellInfo->Id);
566 data << uint64(m_caster->GetGUID());
567 ((Player*)m_caster)->GetSession()->SendPacket(&data);
570 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
571 finish(false);
573 break;
575 default:
576 if(m_targets.getUnitTarget())
577 tmpUnitMap.push_back(m_targets.getUnitTarget());
578 break;
580 break;
582 case SPELL_EFFECT_RESURRECT:
583 case SPELL_EFFECT_PARRY:
584 case SPELL_EFFECT_BLOCK:
585 case SPELL_EFFECT_CREATE_ITEM:
586 case SPELL_EFFECT_TRIGGER_SPELL:
587 case SPELL_EFFECT_TRIGGER_MISSILE:
588 case SPELL_EFFECT_LEARN_SPELL:
589 case SPELL_EFFECT_SKILL_STEP:
590 case SPELL_EFFECT_PROFICIENCY:
591 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
592 case SPELL_EFFECT_SELF_RESURRECT:
593 case SPELL_EFFECT_REPUTATION:
594 if(m_targets.getUnitTarget())
595 tmpUnitMap.push_back(m_targets.getUnitTarget());
596 // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
597 else if(m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL)
598 tmpUnitMap.push_back(m_caster);
599 break;
600 case SPELL_EFFECT_SUMMON_PLAYER:
601 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
603 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
604 if(target)
605 tmpUnitMap.push_back(target);
607 break;
608 case SPELL_EFFECT_RESURRECT_NEW:
609 if(m_targets.getUnitTarget())
610 tmpUnitMap.push_back(m_targets.getUnitTarget());
611 if(m_targets.getCorpseTargetGUID())
613 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
614 if(corpse)
616 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
617 if(owner)
618 tmpUnitMap.push_back(owner);
621 break;
622 case SPELL_EFFECT_SUMMON:
623 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
625 if(m_targets.getUnitTarget())
626 tmpUnitMap.push_back(m_targets.getUnitTarget());
628 else
629 tmpUnitMap.push_back(m_caster);
630 break;
631 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
632 case SPELL_EFFECT_TRANS_DOOR:
633 case SPELL_EFFECT_ADD_FARSIGHT:
634 case SPELL_EFFECT_APPLY_GLYPH:
635 case SPELL_EFFECT_STUCK:
636 case SPELL_EFFECT_FEED_PET:
637 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
638 case SPELL_EFFECT_SKILL:
639 tmpUnitMap.push_back(m_caster);
640 break;
641 case SPELL_EFFECT_LEARN_PET_SPELL:
642 if(Pet* pet = m_caster->GetPet())
643 tmpUnitMap.push_back(pet);
644 break;
645 case SPELL_EFFECT_ENCHANT_ITEM:
646 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
647 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
648 case SPELL_EFFECT_DISENCHANT:
649 case SPELL_EFFECT_PROSPECTING:
650 case SPELL_EFFECT_MILLING:
651 if(m_targets.getItemTarget())
652 AddItemTarget(m_targets.getItemTarget(), i);
653 break;
654 case SPELL_EFFECT_APPLY_AURA:
655 switch(m_spellInfo->EffectApplyAuraName[i])
657 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)
658 case SPELL_AURA_ADD_PCT_MODIFIER:
659 tmpUnitMap.push_back(m_caster);
660 break;
661 default: // apply to target in other case
662 if(m_targets.getUnitTarget())
663 tmpUnitMap.push_back(m_targets.getUnitTarget());
664 break;
666 break;
667 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
668 // AreaAura
669 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
670 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
671 break;
672 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
673 if(m_targets.getUnitTarget())
675 tmpUnitMap.push_back(m_targets.getUnitTarget());
677 else if (m_targets.getCorpseTargetGUID())
679 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
680 if(corpse)
682 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
683 if(owner)
684 tmpUnitMap.push_back(owner);
687 break;
688 default:
689 break;
693 if(m_caster->GetTypeId() == TYPEID_PLAYER)
695 Player *me = (Player*)m_caster;
696 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
698 Unit *owner = (*itr)->GetOwner();
699 Unit *u = owner ? owner : (*itr);
700 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
702 me->UpdatePvP(true);
703 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
704 break;
709 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
711 if (!CheckTarget (*itr, i))
713 itr = tmpUnitMap.erase(itr);
714 continue;
716 else
717 ++itr;
720 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
721 AddUnitTarget((*iunit), i);
725 void Spell::prepareDataForTriggerSystem()
727 //==========================================================================================
728 // Now fill data for trigger system, need know:
729 // Ñan spell trigger another or not ( m_canTrigger )
730 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
731 //==========================================================================================
732 // Fill flag can spell trigger or not
733 // TODO: possible exist spell attribute for this
734 m_canTrigger = false;
736 if (m_CastItem)
737 m_canTrigger = false; // Do not trigger from item cast spell
738 else if (!m_IsTriggeredSpell)
739 m_canTrigger = true; // Normal cast - can trigger
740 else if (!m_triggeredByAuraSpell)
741 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
743 if (!m_canTrigger) // Exceptions (some periodic triggers)
745 switch (m_spellInfo->SpellFamilyName)
747 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
748 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
749 break;
750 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
751 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
752 break;
753 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
754 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
755 break;
756 case SPELLFAMILY_ROGUE: // For poisons need do it
757 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
758 break;
759 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
760 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000214LL ||
761 m_spellInfo->SpellFamilyFlags2 & 0x200) m_canTrigger = true;
762 break;
763 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
764 if (m_spellInfo->SpellFamilyFlags & 0x0001000900B80400LL) m_canTrigger = true;
765 break;
769 // Get data for type of attack and fill base info for trigger
770 switch (m_spellInfo->DmgClass)
772 case SPELL_DAMAGE_CLASS_MELEE:
773 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
774 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
775 break;
776 case SPELL_DAMAGE_CLASS_RANGED:
777 // Auto attack
778 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
780 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
781 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
783 else // Ranged spell attack
785 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
786 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
788 break;
789 default:
790 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
792 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
793 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
795 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
797 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
798 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
800 else // Negative spell
802 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
803 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
805 break;
807 // Hunter traps spells (for Entrapment trigger)
808 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
809 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x000020000000001CLL)
810 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
813 void Spell::CleanupTargetList()
815 m_UniqueTargetInfo.clear();
816 m_UniqueGOTargetInfo.clear();
817 m_UniqueItemInfo.clear();
818 m_delayMoment = 0;
821 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
823 if( m_spellInfo->Effect[effIndex]==0 )
824 return;
826 // Check for effect immune skip if immuned
827 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
829 uint64 targetGUID = pVictim->GetGUID();
831 // Lookup target in already in list
832 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
834 if (targetGUID == ihit->targetGUID) // Found in list
836 if (!immuned)
837 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
838 return;
842 // This is new target calculate data for him
844 // Get spell hit result on target
845 TargetInfo target;
846 target.targetGUID = targetGUID; // Store target GUID
847 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
848 target.processed = false; // Effects not apply on target
850 // Calculate hit result
851 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
853 // Spell have speed - need calculate incoming time
854 if (m_spellInfo->speed > 0.0f)
856 // calculate spell incoming interval
857 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
858 if (dist < 5.0f) dist = 5.0f;
859 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
861 // Calculate minimum incoming time
862 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
863 m_delayMoment = target.timeDelay;
865 else
866 target.timeDelay = 0LL;
868 // If target reflect spell back to caster
869 if (target.missCondition==SPELL_MISS_REFLECT)
871 // Calculate reflected spell result on caster
872 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
874 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
875 target.reflectResult = SPELL_MISS_PARRY;
877 // Increase time interval for reflected spells by 1.5
878 target.timeDelay+=target.timeDelay>>1;
880 else
881 target.reflectResult = SPELL_MISS_NONE;
883 // Add target to list
884 m_UniqueTargetInfo.push_back(target);
887 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
889 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
890 if (unit)
891 AddUnitTarget(unit, effIndex);
894 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
896 if( m_spellInfo->Effect[effIndex]==0 )
897 return;
899 uint64 targetGUID = pVictim->GetGUID();
901 // Lookup target in already in list
902 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
904 if (targetGUID == ihit->targetGUID) // Found in list
906 ihit->effectMask |= 1<<effIndex; // Add only effect mask
907 return;
911 // This is new target calculate data for him
913 GOTargetInfo target;
914 target.targetGUID = targetGUID;
915 target.effectMask = 1<<effIndex;
916 target.processed = false; // Effects not apply on target
918 // Spell have speed - need calculate incoming time
919 if (m_spellInfo->speed > 0.0f)
921 // calculate spell incoming interval
922 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
923 if (dist < 5.0f) dist = 5.0f;
924 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
925 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
926 m_delayMoment = target.timeDelay;
928 else
929 target.timeDelay = 0LL;
931 // Add target to list
932 m_UniqueGOTargetInfo.push_back(target);
935 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
937 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
938 if (go)
939 AddGOTarget(go, effIndex);
942 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
944 if( m_spellInfo->Effect[effIndex]==0 )
945 return;
947 // Lookup target in already in list
948 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
950 if (pitem == ihit->item) // Found in list
952 ihit->effectMask |= 1<<effIndex; // Add only effect mask
953 return;
957 // This is new target add data
959 ItemTargetInfo target;
960 target.item = pitem;
961 target.effectMask = 1<<effIndex;
962 m_UniqueItemInfo.push_back(target);
965 void Spell::DoAllEffectOnTarget(TargetInfo *target)
967 if (target->processed) // Check target
968 return;
969 target->processed = true; // Target checked in apply effects procedure
971 // Get mask of effects for target
972 uint32 mask = target->effectMask;
974 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
975 if (!unit)
976 return;
978 // Get original caster (if exist) and calculate damage/healing from him data
979 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
981 // Skip if m_originalCaster not available
982 if (!caster)
983 return;
985 SpellMissInfo missInfo = target->missCondition;
986 // Need init unitTarget by default unit (can changed in code on reflect)
987 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
988 unitTarget = unit;
990 // Reset damage/healing counter
991 m_damage = 0;
992 m_healing = 0;
994 // Fill base trigger info
995 uint32 procAttacker = m_procAttacker;
996 uint32 procVictim = m_procVictim;
997 uint32 procEx = PROC_EX_NONE;
999 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
1000 DoSpellHitOnUnit(unit, mask);
1001 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
1003 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
1004 DoSpellHitOnUnit(m_caster, mask);
1007 // All calculated do it!
1008 // Do healing and triggers
1009 if (m_healing)
1011 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
1012 uint32 addhealth = m_healing;
1013 if (crit)
1015 procEx |= PROC_EX_CRITICAL_HIT;
1016 addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
1018 else
1019 procEx |= PROC_EX_NORMAL_HIT;
1021 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
1023 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1024 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1025 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
1027 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
1029 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
1030 if(caster->GetTypeId()==TYPEID_PLAYER)
1031 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
1032 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
1034 // Do damage and triggers
1035 else if (m_damage)
1037 // Fill base damage struct (unitTarget - is real spell target)
1038 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1040 // Add bonuses and fill damageInfo struct
1041 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
1043 // Send log damage message to client
1044 caster->SendSpellNonMeleeDamageLog(&damageInfo);
1046 procEx = createProcExtendMask(&damageInfo, missInfo);
1047 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1049 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1050 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1051 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1053 caster->DealSpellDamage(&damageInfo, true);
1055 // Judgement of Blood
1056 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1058 int32 damagePoint = damageInfo.damage * 33 / 100;
1059 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1062 // Passive spell hits/misses or active spells only misses (only triggers)
1063 else
1065 // Fill base damage struct (unitTarget - is real spell target)
1066 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1067 procEx = createProcExtendMask(&damageInfo, missInfo);
1068 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1069 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1070 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1073 // Call scripted function for AI if this spell is casted upon a creature
1074 if(unit->GetTypeId()==TYPEID_UNIT)
1076 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1077 // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... )
1078 if( !((Creature*)unit)->isPet() && m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1079 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1081 if(((Creature*)unit)->AI())
1082 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1085 // Call scripted function for AI if this spell is casted by a creature
1086 if(m_caster->GetTypeId()==TYPEID_UNIT && ((Creature*)m_caster)->AI())
1087 ((Creature*)m_caster)->AI()->SpellHitTarget(unit,m_spellInfo);
1090 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1092 if(!unit || !effectMask)
1093 return;
1095 // Recheck immune (only for delayed spells)
1096 if( m_spellInfo->speed && (
1097 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1098 unit->IsImmunedToSpell(m_spellInfo)))
1100 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1101 return;
1104 if (unit->GetTypeId() == TYPEID_PLAYER)
1106 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1107 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1110 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1112 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1115 if( m_caster != unit )
1117 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1118 if (m_spellInfo->speed > 0.0f &&
1119 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1120 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1122 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1123 return;
1126 if( !m_caster->IsFriendlyTo(unit) )
1128 // for delayed spells ignore not visible explicit target
1129 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1131 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1132 return;
1135 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1137 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1139 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1140 unit->SetStandState(UNIT_STAND_STATE_STAND);
1142 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1143 ((Creature*)unit)->AI()->AttackStart(m_caster);
1145 unit->SetInCombatWith(m_caster);
1146 m_caster->SetInCombatWith(unit);
1148 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1150 m_caster->SetContestedPvP(attackedPlayer);
1152 unit->AddThreat(m_caster, 0.0f);
1155 else
1157 // for delayed spells ignore negative spells (after duel end) for friendly targets
1158 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1160 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1161 return;
1164 // assisting case, healing and resurrection
1165 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1166 m_caster->SetContestedPvP();
1167 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1169 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1170 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1175 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1176 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1177 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1178 // Increase Diminishing on unit, current informations for actually casts will use values above
1179 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1180 unit->IncrDiminishing(m_diminishGroup);
1182 // Apply additional spell effects to target
1183 if (m_preCastSpell)
1184 m_caster->CastSpell(unit,m_preCastSpell, true, m_CastItem);
1186 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1188 if (effectMask & (1<<effectNumber))
1190 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1191 if ( m_applyMultiplierMask & (1 << effectNumber) )
1193 // Get multiplier
1194 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1195 // Apply multiplier mods
1196 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1197 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1198 m_damageMultipliers[effectNumber] *= multiplier;
1204 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1206 if (target->processed) // Check target
1207 return;
1208 target->processed = true; // Target checked in apply effects procedure
1210 uint32 effectMask = target->effectMask;
1211 if(!effectMask)
1212 return;
1214 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1215 if(!go)
1216 return;
1218 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1219 if (effectMask & (1<<effectNumber))
1220 HandleEffects(NULL,NULL,go,effectNumber);
1222 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1223 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1224 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1225 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1227 // Call scripted function for AI if this spell is casted by a creature
1228 if(m_caster->GetTypeId()==TYPEID_UNIT && ((Creature*)m_caster)->AI())
1229 ((Creature*)m_caster)->AI()->SpellHitTarget(go,m_spellInfo);
1232 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1234 uint32 effectMask = target->effectMask;
1235 if(!target->item || !effectMask)
1236 return;
1238 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1239 if (effectMask & (1<<effectNumber))
1240 HandleEffects(NULL, target->item, NULL, effectNumber);
1243 bool Spell::IsAliveUnitPresentInTargetList()
1245 // Not need check return true
1246 if (m_needAliveTargetMask == 0)
1247 return true;
1249 uint8 needAliveTargetMask = m_needAliveTargetMask;
1251 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1253 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1255 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1257 if (unit && unit->isAlive())
1258 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1262 // is all effects from m_needAliveTargetMask have alive targets
1263 return needAliveTargetMask==0;
1266 // Helper for Chain Healing
1267 // Spell target first
1268 // Raidmates then descending by injury suffered (MaxHealth - Health)
1269 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1270 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1272 const Unit* MainTarget;
1273 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1274 // functor for operator ">"
1275 bool operator()(Unit const* _Left, Unit const* _Right) const
1277 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1279 int32 ChainHealingHash(Unit const* Target) const
1281 if (Target == MainTarget)
1282 return 0;
1283 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1284 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1286 if (Target->GetHealth() == Target->GetMaxHealth())
1287 return 40000;
1288 else
1289 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1291 else
1292 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1296 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1298 public:
1299 const Unit* MainTarget;
1300 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1302 bool operator()(const Unit* Target)
1304 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1308 // Helper for targets nearest to the spell target
1309 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1310 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1312 const Unit* MainTarget;
1313 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1314 // functor for operator ">"
1315 bool operator()(const Unit* _Left, const Unit* _Right) const
1317 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1321 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1323 float radius;
1324 if (m_spellInfo->EffectRadiusIndex[i])
1325 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1326 else
1327 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1329 if(m_originalCaster)
1330 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1331 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1333 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1334 if(m_originalCaster)
1335 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1336 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1338 // Get spell max affected targets
1339 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1341 // custom target amount cases
1342 switch(m_spellInfo->SpellFamilyName)
1344 case SPELLFAMILY_DRUID:
1345 // Starfall
1346 if (m_spellInfo->SpellFamilyFlags2 & 0x00000100LL)
1347 unMaxTargets = 2;
1348 break;
1349 default:
1350 break;
1353 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1354 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1356 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1357 continue;
1358 unMaxTargets+=(*m)->GetModifier()->m_amount;
1361 switch(cur)
1363 case TARGET_TOTEM_EARTH:
1364 case TARGET_TOTEM_WATER:
1365 case TARGET_TOTEM_AIR:
1366 case TARGET_TOTEM_FIRE:
1367 case TARGET_SELF:
1368 case TARGET_SELF2:
1369 case TARGET_DYNAMIC_OBJECT:
1370 case TARGET_AREAEFFECT_CUSTOM:
1371 case TARGET_AREAEFFECT_CUSTOM_2:
1372 case TARGET_SUMMON:
1374 TagUnitMap.push_back(m_caster);
1375 break;
1377 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1379 m_targets.m_targetMask = 0;
1380 unMaxTargets = EffectChainTarget;
1381 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1383 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1384 Cell cell(p);
1385 cell.data.Part.reserved = ALL_DISTRICT;
1386 cell.SetNoCreate();
1388 std::list<Unit *> tempUnitMap;
1391 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1392 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1394 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1395 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1397 CellLock<GridReadGuard> cell_lock(cell, p);
1398 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1399 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1402 if(tempUnitMap.empty())
1403 break;
1405 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1407 //Now to get us a random target that's in the initial range of the spell
1408 uint32 t = 0;
1409 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1410 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1411 ++t, ++itr;
1413 if(!t)
1414 break;
1416 itr = tempUnitMap.begin();
1417 std::advance(itr, rand()%t);
1418 Unit *pUnitTarget = *itr;
1419 TagUnitMap.push_back(pUnitTarget);
1421 tempUnitMap.erase(itr);
1423 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1425 t = unMaxTargets - 1;
1426 Unit *prev = pUnitTarget;
1427 std::list<Unit*>::iterator next = tempUnitMap.begin();
1429 while(t && next != tempUnitMap.end() )
1431 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1432 break;
1434 if(!prev->IsWithinLOSInMap(*next))
1436 ++next;
1437 continue;
1440 prev = *next;
1441 TagUnitMap.push_back(prev);
1442 tempUnitMap.erase(next);
1443 tempUnitMap.sort(TargetDistanceOrder(prev));
1444 next = tempUnitMap.begin();
1446 --t;
1448 }break;
1449 case TARGET_RANDOM_FRIEND_CHAIN_IN_AREA:
1451 m_targets.m_targetMask = 0;
1452 unMaxTargets = EffectChainTarget;
1453 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1454 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1455 Cell cell(p);
1456 cell.data.Part.reserved = ALL_DISTRICT;
1457 cell.SetNoCreate();
1458 std::list<Unit *> tempUnitMap;
1460 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1461 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1463 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1464 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1466 CellLock<GridReadGuard> cell_lock(cell, p);
1467 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1468 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1471 if(tempUnitMap.empty())
1472 break;
1474 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1476 //Now to get us a random target that's in the initial range of the spell
1477 uint32 t = 0;
1478 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1479 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1480 ++t, ++itr;
1482 if(!t)
1483 break;
1485 itr = tempUnitMap.begin();
1486 std::advance(itr, rand()%t);
1487 Unit *pUnitTarget = *itr;
1488 TagUnitMap.push_back(pUnitTarget);
1490 tempUnitMap.erase(itr);
1492 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1494 t = unMaxTargets - 1;
1495 Unit *prev = pUnitTarget;
1496 std::list<Unit*>::iterator next = tempUnitMap.begin();
1498 while(t && next != tempUnitMap.end() )
1500 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1501 break;
1503 if(!prev->IsWithinLOSInMap(*next))
1505 ++next;
1506 continue;
1508 prev = *next;
1509 TagUnitMap.push_back(prev);
1510 tempUnitMap.erase(next);
1511 tempUnitMap.sort(TargetDistanceOrder(prev));
1512 next = tempUnitMap.begin();
1513 --t;
1515 }break;
1516 case TARGET_PET:
1518 Pet* tmpUnit = m_caster->GetPet();
1519 if (!tmpUnit) break;
1520 TagUnitMap.push_back(tmpUnit);
1521 break;
1523 case TARGET_CHAIN_DAMAGE:
1525 if (EffectChainTarget <= 1)
1527 Unit* pUnitTarget = SelectMagnetTarget();
1528 if(pUnitTarget)
1529 TagUnitMap.push_back(pUnitTarget);
1531 else
1533 Unit* pUnitTarget = m_targets.getUnitTarget();
1534 if(!pUnitTarget)
1535 break;
1537 unMaxTargets = EffectChainTarget;
1539 float max_range;
1540 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1541 max_range = radius; //
1542 else
1543 //FIXME: This very like horrible hack and wrong for most spells
1544 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1546 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1547 Cell cell(p);
1548 cell.data.Part.reserved = ALL_DISTRICT;
1549 cell.SetNoCreate();
1551 Unit* originalCaster = GetOriginalCaster();
1552 if(originalCaster)
1554 std::list<Unit *> tempUnitMap;
1557 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1558 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1560 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1561 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1563 CellLock<GridReadGuard> cell_lock(cell, p);
1564 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1565 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1568 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1570 if(tempUnitMap.empty())
1571 break;
1573 if(*tempUnitMap.begin() == pUnitTarget)
1574 tempUnitMap.erase(tempUnitMap.begin());
1576 TagUnitMap.push_back(pUnitTarget);
1577 uint32 t = unMaxTargets - 1;
1578 Unit *prev = pUnitTarget;
1579 std::list<Unit*>::iterator next = tempUnitMap.begin();
1581 while(t && next != tempUnitMap.end() )
1583 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1584 break;
1586 if(!prev->IsWithinLOSInMap(*next))
1588 ++next;
1589 continue;
1592 prev = *next;
1593 TagUnitMap.push_back(prev);
1594 tempUnitMap.erase(next);
1595 tempUnitMap.sort(TargetDistanceOrder(prev));
1596 next = tempUnitMap.begin();
1598 --t;
1602 }break;
1603 case TARGET_ALL_ENEMY_IN_AREA:
1605 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1606 Cell cell(p);
1607 cell.data.Part.reserved = ALL_DISTRICT;
1608 cell.SetNoCreate();
1610 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1612 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1613 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1615 CellLock<GridReadGuard> cell_lock(cell, p);
1616 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1617 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1618 }break;
1619 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1621 // targets the ground, not the units in the area
1622 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1624 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1625 Cell cell(p);
1626 cell.data.Part.reserved = ALL_DISTRICT;
1627 cell.SetNoCreate();
1629 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1631 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1632 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1634 CellLock<GridReadGuard> cell_lock(cell, p);
1635 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1636 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1638 // exclude caster (this can be important if this not original caster)
1639 TagUnitMap.remove(m_caster);
1641 }break;
1642 case TARGET_DUELVSPLAYER_COORDINATES:
1644 if(Unit* currentTarget = m_targets.getUnitTarget())
1646 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1647 TagUnitMap.push_back(currentTarget);
1649 }break;
1650 case TARGET_ALL_PARTY_AROUND_CASTER:
1651 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1652 case TARGET_ALL_PARTY:
1654 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1655 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1657 if(pGroup)
1659 uint8 subgroup = pTarget->GetSubGroup();
1661 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1663 Player* Target = itr->getSource();
1665 // IsHostileTo check duel and controlled by enemy
1666 if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1668 if( m_caster->IsWithinDistInMap(Target, radius) )
1669 TagUnitMap.push_back(Target);
1671 if(Pet* pet = Target->GetPet())
1672 if( m_caster->IsWithinDistInMap(pet, radius) )
1673 TagUnitMap.push_back(pet);
1677 else
1679 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1680 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1681 TagUnitMap.push_back(ownerOrSelf);
1682 if(Pet* pet = ownerOrSelf->GetPet())
1683 if( m_caster->IsWithinDistInMap(pet, radius) )
1684 TagUnitMap.push_back(pet);
1686 break;
1688 case TARGET_ALL_RAID_AROUND_CASTER:
1690 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1691 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1693 if(m_spellInfo->Id==57669) //Replenishment (special target selection)
1695 if(pGroup)
1697 typedef std::priority_queue<PrioritizeManaPlayerWraper, std::vector<PrioritizeManaPlayerWraper>, PrioritizeMana> Top10;
1698 Top10 manaUsers;
1700 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL && manaUsers.size() < 10; itr = itr->next())
1702 Player* Target = itr->getSource();
1703 if (m_caster->GetGUID() != Target->GetGUID() && Target->getPowerType() == POWER_MANA &&
1704 !Target->isDead() && m_caster->IsWithinDistInMap(Target, radius))
1706 PrioritizeManaPlayerWraper WTarget(Target);
1707 manaUsers.push(WTarget);
1711 while(!manaUsers.empty())
1713 TagUnitMap.push_back(manaUsers.top().getPlayer());
1714 manaUsers.pop();
1717 else
1719 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1720 if ((ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius)) &&
1721 ownerOrSelf->getPowerType() == POWER_MANA)
1722 TagUnitMap.push_back(ownerOrSelf);
1724 if(Pet* pet = ownerOrSelf->GetPet())
1725 if( m_caster->IsWithinDistInMap(pet, radius) && pet->getPowerType() == POWER_MANA )
1726 TagUnitMap.push_back(pet);
1729 else
1731 if(pGroup)
1733 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1735 Player* Target = itr->getSource();
1737 // IsHostileTo check duel and controlled by enemy
1738 if( Target && !m_caster->IsHostileTo(Target) )
1740 if( m_caster->IsWithinDistInMap(Target, radius) )
1741 TagUnitMap.push_back(Target);
1743 if(Pet* pet = Target->GetPet())
1744 if( m_caster->IsWithinDistInMap(pet, radius) )
1745 TagUnitMap.push_back(pet);
1749 else
1751 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1752 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1753 TagUnitMap.push_back(ownerOrSelf);
1754 if(Pet* pet = ownerOrSelf->GetPet())
1755 if( m_caster->IsWithinDistInMap(pet, radius) )
1756 TagUnitMap.push_back(pet);
1759 break;
1761 case TARGET_SINGLE_FRIEND:
1762 case TARGET_SINGLE_FRIEND_2:
1764 if(m_targets.getUnitTarget())
1765 TagUnitMap.push_back(m_targets.getUnitTarget());
1766 }break;
1767 case TARGET_NONCOMBAT_PET:
1769 if(Unit* target = m_targets.getUnitTarget())
1770 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1771 TagUnitMap.push_back(target);
1772 }break;
1773 case TARGET_CASTER_COORDINATES:
1775 // Check original caster is GO - set its coordinates as dst cast
1776 WorldObject *caster = NULL;
1777 if (m_originalCasterGUID)
1778 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
1779 if (!caster)
1780 caster = m_caster;
1781 // Set dest for targets
1782 m_targets.setDestination(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
1783 }break;
1784 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1786 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1787 Cell cell(p);
1788 cell.data.Part.reserved = ALL_DISTRICT;
1789 cell.SetNoCreate();
1791 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1793 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1794 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1796 CellLock<GridReadGuard> cell_lock(cell, p);
1797 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1798 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1799 }break;
1800 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1802 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1803 Cell cell(p);
1804 cell.data.Part.reserved = ALL_DISTRICT;
1805 cell.SetNoCreate();
1807 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1809 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1810 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1812 CellLock<GridReadGuard> cell_lock(cell, p);
1813 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1814 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1815 }break;
1816 // 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..)
1817 case TARGET_SINGLE_PARTY:
1819 Unit *target = m_targets.getUnitTarget();
1820 // Thoses spells apparently can't be casted on the caster.
1821 if( target && target != m_caster)
1823 // Can only be casted on group's members or its pets
1824 Group *pGroup = NULL;
1826 Unit* owner = m_caster->GetCharmerOrOwner();
1827 Unit *targetOwner = target->GetCharmerOrOwner();
1828 if(owner)
1830 if(owner->GetTypeId() == TYPEID_PLAYER)
1832 if( target == owner )
1834 TagUnitMap.push_back(target);
1835 break;
1837 pGroup = ((Player*)owner)->GetGroup();
1840 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1842 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1844 TagUnitMap.push_back(target);
1845 break;
1847 pGroup = ((Player*)m_caster)->GetGroup();
1850 if(pGroup)
1852 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1853 if(targetOwner)
1855 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1856 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1857 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1858 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1860 TagUnitMap.push_back(target);
1863 // 1Our target can be a player who is on our group
1864 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1866 TagUnitMap.push_back(target);
1870 }break;
1871 case TARGET_GAMEOBJECT:
1873 if(m_targets.getGOTarget())
1874 AddGOTarget(m_targets.getGOTarget(), i);
1875 }break;
1876 case TARGET_IN_FRONT_OF_CASTER:
1878 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1879 Cell cell(p);
1880 cell.data.Part.reserved = ALL_DISTRICT;
1881 cell.SetNoCreate();
1883 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1884 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1886 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1887 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1889 CellLock<GridReadGuard> cell_lock(cell, p);
1890 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1891 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1892 }break;
1893 case TARGET_DUELVSPLAYER:
1895 Unit *target = m_targets.getUnitTarget();
1896 if(target)
1898 if(m_caster->IsFriendlyTo(target))
1900 TagUnitMap.push_back(target);
1902 else
1904 Unit* pUnitTarget = SelectMagnetTarget();
1905 if(pUnitTarget)
1906 TagUnitMap.push_back(pUnitTarget);
1909 }break;
1910 case TARGET_GAMEOBJECT_ITEM:
1912 if(m_targets.getGOTargetGUID())
1913 AddGOTarget(m_targets.getGOTarget(), i);
1914 else if(m_targets.getItemTarget())
1915 AddItemTarget(m_targets.getItemTarget(), i);
1916 break;
1918 case TARGET_MASTER:
1920 if(Unit* owner = m_caster->GetCharmerOrOwner())
1921 TagUnitMap.push_back(owner);
1922 break;
1924 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1926 // targets the ground, not the units in the area
1927 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1929 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1930 Cell cell(p);
1931 cell.data.Part.reserved = ALL_DISTRICT;
1932 cell.SetNoCreate();
1934 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1936 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1937 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1939 CellLock<GridReadGuard> cell_lock(cell, p);
1940 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1941 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1943 }break;
1944 case TARGET_MINION:
1946 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1947 TagUnitMap.push_back(m_caster);
1948 }break;
1949 case TARGET_SINGLE_ENEMY:
1951 Unit* pUnitTarget = SelectMagnetTarget();
1952 if(pUnitTarget)
1953 TagUnitMap.push_back(pUnitTarget);
1954 }break;
1955 case TARGET_AREAEFFECT_PARTY:
1957 Unit* owner = m_caster->GetCharmerOrOwner();
1958 Player *pTarget = NULL;
1960 if(owner)
1962 TagUnitMap.push_back(m_caster);
1963 if(owner->GetTypeId() == TYPEID_PLAYER)
1964 pTarget = (Player*)owner;
1966 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1968 if(Unit* target = m_targets.getUnitTarget())
1970 if( target->GetTypeId() != TYPEID_PLAYER)
1972 if(((Creature*)target)->isPet())
1974 Unit *targetOwner = target->GetOwner();
1975 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1976 pTarget = (Player*)targetOwner;
1979 else
1980 pTarget = (Player*)target;
1984 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1986 if(pGroup)
1988 uint8 subgroup = pTarget->GetSubGroup();
1990 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1992 Player* Target = itr->getSource();
1994 // IsHostileTo check duel and controlled by enemy
1995 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1997 if( pTarget->IsWithinDistInMap(Target, radius) )
1998 TagUnitMap.push_back(Target);
2000 if(Pet* pet = Target->GetPet())
2001 if( pTarget->IsWithinDistInMap(pet, radius) )
2002 TagUnitMap.push_back(pet);
2006 else if (owner)
2008 if(m_caster->IsWithinDistInMap(owner, radius))
2009 TagUnitMap.push_back(owner);
2011 else if(pTarget)
2013 TagUnitMap.push_back(pTarget);
2015 if(Pet* pet = pTarget->GetPet())
2016 if( m_caster->IsWithinDistInMap(pet, radius) )
2017 TagUnitMap.push_back(pet);
2020 }break;
2021 case TARGET_SCRIPT:
2023 if(m_targets.getUnitTarget())
2024 TagUnitMap.push_back(m_targets.getUnitTarget());
2025 if(m_targets.getItemTarget())
2026 AddItemTarget(m_targets.getItemTarget(), i);
2027 }break;
2028 case TARGET_SELF_FISHING:
2030 TagUnitMap.push_back(m_caster);
2031 }break;
2032 case TARGET_CHAIN_HEAL:
2034 Unit* pUnitTarget = m_targets.getUnitTarget();
2035 if(!pUnitTarget)
2036 break;
2038 if (EffectChainTarget <= 1)
2039 TagUnitMap.push_back(pUnitTarget);
2040 else
2042 unMaxTargets = EffectChainTarget;
2043 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
2045 std::list<Unit *> tempUnitMap;
2048 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
2049 Cell cell(p);
2050 cell.data.Part.reserved = ALL_DISTRICT;
2051 cell.SetNoCreate();
2053 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
2055 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
2056 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
2058 CellLock<GridReadGuard> cell_lock(cell, p);
2059 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
2060 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
2064 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
2065 tempUnitMap.push_front(m_caster);
2067 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
2069 if(tempUnitMap.empty())
2070 break;
2072 if(*tempUnitMap.begin() == pUnitTarget)
2073 tempUnitMap.erase(tempUnitMap.begin());
2075 TagUnitMap.push_back(pUnitTarget);
2076 uint32 t = unMaxTargets - 1;
2077 Unit *prev = pUnitTarget;
2078 std::list<Unit*>::iterator next = tempUnitMap.begin();
2080 while(t && next != tempUnitMap.end() )
2082 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
2083 break;
2085 if(!prev->IsWithinLOSInMap(*next))
2087 ++next;
2088 continue;
2091 if((*next)->GetHealth() == (*next)->GetMaxHealth())
2093 next = tempUnitMap.erase(next);
2094 continue;
2097 prev = *next;
2098 TagUnitMap.push_back(prev);
2099 tempUnitMap.erase(next);
2100 tempUnitMap.sort(TargetDistanceOrder(prev));
2101 next = tempUnitMap.begin();
2103 --t;
2106 }break;
2107 case TARGET_CURRENT_ENEMY_COORDINATES:
2109 Unit* currentTarget = m_targets.getUnitTarget();
2110 if(currentTarget)
2112 TagUnitMap.push_back(currentTarget);
2113 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
2114 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
2116 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
2117 Cell cell(p);
2118 cell.data.Part.reserved = ALL_DISTRICT;
2119 cell.SetNoCreate();
2120 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
2121 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
2122 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
2123 CellLock<GridReadGuard> cell_lock(cell, p);
2124 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
2125 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
2128 }break;
2129 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
2131 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
2132 ? (Player*)m_targets.getUnitTarget() : NULL;
2134 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
2135 if(pGroup)
2137 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
2139 Player* Target = itr->getSource();
2141 // IsHostileTo check duel and controlled by enemy
2142 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
2143 targetPlayer->getClass() == Target->getClass() &&
2144 !m_caster->IsHostileTo(Target) )
2146 TagUnitMap.push_back(Target);
2150 else if(m_targets.getUnitTarget())
2151 TagUnitMap.push_back(m_targets.getUnitTarget());
2152 break;
2154 case TARGET_TABLE_X_Y_Z_COORDINATES:
2156 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
2157 if(st)
2159 if (st->target_mapId == m_caster->GetMapId())
2160 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
2162 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
2163 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
2165 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
2166 Cell cell(p);
2167 cell.data.Part.reserved = ALL_DISTRICT;
2168 cell.SetNoCreate();
2170 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
2171 // Select friendly targets for positive effect
2172 if (IsPositiveEffect(m_spellInfo->Id, i))
2173 targetB = SPELL_TARGETS_FRIENDLY;
2175 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
2177 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
2178 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
2180 CellLock<GridReadGuard> cell_lock(cell, p);
2181 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
2182 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
2185 else
2186 sLog.outError( "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id );
2187 }break;
2188 case TARGET_BEHIND_VICTIM:
2190 Unit *pTarget = NULL;
2192 // explicit cast data from client or server-side cast
2193 // some spell at client send caster
2194 if(m_targets.getUnitTarget() && m_targets.getUnitTarget()!=m_caster)
2195 pTarget = m_targets.getUnitTarget();
2196 else if(m_caster->getVictim())
2197 pTarget = m_caster->getVictim();
2198 else if(m_caster->GetTypeId() == TYPEID_PLAYER)
2199 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
2201 if(pTarget)
2203 float _target_x, _target_y, _target_z;
2204 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
2205 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
2207 TagUnitMap.push_back(m_caster);
2208 m_targets.setDestination(_target_x, _target_y, _target_z);
2211 break;
2213 case TARGET_DYNAMIC_OBJECT_COORDINATES:
2215 // if parent spell create dynamic object extract area from it
2216 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
2217 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2218 break;
2220 case TARGET_DIRECTLY_FORWARD:
2222 if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION))
2224 SpellRangeEntry const* rEntry = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
2225 float minRange = GetSpellMinRange(rEntry);
2226 float maxRange = GetSpellMaxRange(rEntry);
2227 float dist = minRange+ rand_norm()*(maxRange-minRange);
2229 float _target_x, _target_y, _target_z;
2230 m_caster->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), dist);
2231 m_targets.setDestination(_target_x, _target_y, _target_z);
2234 TagUnitMap.push_back(m_caster);
2235 break;
2237 default:
2238 break;
2241 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2243 // make sure one unit is always removed per iteration
2244 uint32 removed_utarget = 0;
2245 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2247 next = itr;
2248 ++next;
2249 if (!*itr) continue;
2250 if ((*itr) == m_targets.getUnitTarget())
2252 TagUnitMap.erase(itr);
2253 removed_utarget = 1;
2254 // break;
2257 // remove random units from the map
2258 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2260 uint32 poz = urand(0, TagUnitMap.size()-1);
2261 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2263 if (!*itr) continue;
2264 if (!poz)
2266 TagUnitMap.erase(itr);
2267 break;
2271 // the player's target will always be added to the map
2272 if (removed_utarget && m_targets.getUnitTarget())
2273 TagUnitMap.push_back(m_targets.getUnitTarget());
2277 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2279 m_targets = *targets;
2281 m_spellState = SPELL_STATE_PREPARING;
2283 m_castPositionX = m_caster->GetPositionX();
2284 m_castPositionY = m_caster->GetPositionY();
2285 m_castPositionZ = m_caster->GetPositionZ();
2286 m_castOrientation = m_caster->GetOrientation();
2288 if(triggeredByAura)
2289 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2291 // create and add update event for this spell
2292 SpellEvent* Event = new SpellEvent(this);
2293 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2295 //Prevent casting at cast another spell (ServerSide check)
2296 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2298 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2299 finish(false);
2300 return;
2303 // Fill cost data
2304 m_powerCost = CalculatePowerCost();
2306 SpellCastResult result = CheckCast(true);
2307 if(result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2309 if(triggeredByAura)
2311 SendChannelUpdate(0);
2312 triggeredByAura->SetAuraDuration(0);
2314 SendCastResult(result);
2315 finish(false);
2316 return;
2319 // Prepare data for triggers
2320 prepareDataForTriggerSystem();
2322 // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
2323 m_casttime = GetSpellCastTime(m_spellInfo, this);
2325 // set timer base at cast time
2326 ReSetTimer();
2328 // stealth must be removed at cast starting (at show channel bar)
2329 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2330 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2332 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2333 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2336 if(m_IsTriggeredSpell)
2337 cast(true);
2338 else
2340 m_caster->SetCurrentCastedSpell( this );
2341 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2342 SendSpellStart();
2346 void Spell::cancel()
2348 if(m_spellState == SPELL_STATE_FINISHED)
2349 return;
2351 m_autoRepeat = false;
2352 switch (m_spellState)
2354 case SPELL_STATE_PREPARING:
2355 case SPELL_STATE_DELAYED:
2357 SendInterrupted(0);
2358 SendCastResult(SPELL_FAILED_INTERRUPTED);
2359 } break;
2361 case SPELL_STATE_CASTING:
2363 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2365 if( ihit->missCondition == SPELL_MISS_NONE )
2367 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2368 if( unit && unit->isAlive() )
2369 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2373 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2374 SendChannelUpdate(0);
2375 SendInterrupted(0);
2376 SendCastResult(SPELL_FAILED_INTERRUPTED);
2377 } break;
2379 default:
2381 } break;
2384 finish(false);
2385 m_caster->RemoveDynObject(m_spellInfo->Id);
2386 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2389 void Spell::cast(bool skipCheck)
2391 SetExecutedCurrently(true);
2393 // update pointers base at GUIDs to prevent access to non-existed already object
2394 UpdatePointers();
2396 // cancel at lost main target unit
2397 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2399 cancel();
2400 SetExecutedCurrently(false);
2401 return;
2404 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2405 m_caster->SetInFront(m_targets.getUnitTarget());
2407 SpellCastResult castResult = CheckPower();
2408 if(castResult != SPELL_CAST_OK)
2410 SendCastResult(castResult);
2411 finish(false);
2412 SetExecutedCurrently(false);
2413 return;
2416 // triggered cast called from Spell::prepare where it was already checked
2417 if(!skipCheck)
2419 castResult = CheckCast(false);
2420 if(castResult != SPELL_CAST_OK)
2422 SendCastResult(castResult);
2423 finish(false);
2424 SetExecutedCurrently(false);
2425 return;
2429 switch(m_spellInfo->SpellFamilyName)
2431 case SPELLFAMILY_GENERIC:
2433 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2434 m_preCastSpell = 11196; // Recently Bandaged
2435 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2436 m_preCastSpell = 23230; // Blood Fury - Healing Reduction
2437 break;
2439 case SPELLFAMILY_MAGE:
2441 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2442 m_preCastSpell = 41425; // Hypothermia
2443 break;
2445 case SPELLFAMILY_PRIEST:
2447 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2448 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2449 m_preCastSpell = 6788; // Weakened Soul
2450 if (m_spellInfo->Id == 47585) // Dispersion (transform)
2451 m_preCastSpell = 60069; // Dispersion (mana regen)
2452 break;
2454 case SPELLFAMILY_PALADIN:
2456 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2457 m_preCastSpell = 25771; // Forbearance
2458 break;
2460 case SPELLFAMILY_SHAMAN:
2462 if (m_spellInfo->Id == 2825) // Bloodlust
2463 m_preCastSpell = 57724; // Sated
2464 else if (m_spellInfo->Id == 32182) // Heroism
2465 m_preCastSpell = 57723; // Exhaustion
2466 break;
2468 default:
2469 break;
2472 // Conflagrate - consumes immolate
2473 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2475 // for caster applied auras only
2476 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2477 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2479 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2480 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2482 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2483 break;
2488 // traded items have trade slot instead of guid in m_itemTargetGUID
2489 // set to real guid to be sent later to the client
2490 m_targets.updateTradeSlotItem();
2492 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2494 if (m_CastItem)
2495 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2497 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2500 // CAST SPELL
2501 SendSpellCooldown();
2503 TakePower();
2504 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2505 FillTargetMap();
2507 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2509 SetExecutedCurrently(false);
2510 return;
2513 SendCastResult(castResult);
2514 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2516 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2517 if (m_spellInfo->speed > 0.0f)
2520 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2521 // in case delayed spell remove item at cast delay start
2522 TakeCastItem();
2524 // Okay, maps created, now prepare flags
2525 m_immediateHandled = false;
2526 m_spellState = SPELL_STATE_DELAYED;
2527 SetDelayStart(0);
2529 else
2531 // Immediate spell, no big deal
2532 handle_immediate();
2535 SetExecutedCurrently(false);
2538 void Spell::handle_immediate()
2540 // start channeling if applicable
2541 if(IsChanneledSpell(m_spellInfo))
2543 int32 duration = GetSpellDuration(m_spellInfo);
2544 if (duration)
2546 // Apply duration mod
2547 if(Player* modOwner = m_caster->GetSpellModOwner())
2548 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2549 m_spellState = SPELL_STATE_CASTING;
2550 SendChannelStart(duration);
2554 // process immediate effects (items, ground, etc.) also initialize some variables
2555 _handle_immediate_phase();
2557 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2558 DoAllEffectOnTarget(&(*ihit));
2560 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2561 DoAllEffectOnTarget(&(*ihit));
2563 // spell is finished, perform some last features of the spell here
2564 _handle_finish_phase();
2566 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2567 TakeCastItem();
2569 if(m_spellState != SPELL_STATE_CASTING)
2570 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2573 uint64 Spell::handle_delayed(uint64 t_offset)
2575 uint64 next_time = 0;
2577 if (!m_immediateHandled)
2579 _handle_immediate_phase();
2580 m_immediateHandled = true;
2583 // 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)
2584 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2586 if (ihit->processed == false)
2588 if ( ihit->timeDelay <= t_offset )
2589 DoAllEffectOnTarget(&(*ihit));
2590 else if( next_time == 0 || ihit->timeDelay < next_time )
2591 next_time = ihit->timeDelay;
2595 // now recheck gameobject targeting correctness
2596 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2598 if (ighit->processed == false)
2600 if ( ighit->timeDelay <= t_offset )
2601 DoAllEffectOnTarget(&(*ighit));
2602 else if( next_time == 0 || ighit->timeDelay < next_time )
2603 next_time = ighit->timeDelay;
2606 // All targets passed - need finish phase
2607 if (next_time == 0)
2609 // spell is finished, perform some last features of the spell here
2610 _handle_finish_phase();
2612 finish(true); // successfully finish spell cast
2614 // return zero, spell is finished now
2615 return 0;
2617 else
2619 // spell is unfinished, return next execution time
2620 return next_time;
2624 void Spell::_handle_immediate_phase()
2626 // handle some immediate features of the spell here
2627 HandleThreatSpells(m_spellInfo->Id);
2629 m_needSpellLog = IsNeedSendToClient();
2630 for(uint32 j = 0;j<3;j++)
2632 if(m_spellInfo->Effect[j]==0)
2633 continue;
2635 // apply Send Event effect to ground in case empty target lists
2636 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2638 HandleEffects(NULL,NULL,NULL, j);
2639 continue;
2642 // Don't do spell log, if is school damage spell
2643 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2644 m_needSpellLog = false;
2646 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2647 if(m_originalCaster)
2648 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2649 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2651 // initialize multipliers
2652 m_damageMultipliers[j] = 1.0f;
2653 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2654 (EffectChainTarget > 1) )
2655 m_applyMultiplierMask |= 1 << j;
2658 // initialize Diminishing Returns Data
2659 m_diminishLevel = DIMINISHING_LEVEL_1;
2660 m_diminishGroup = DIMINISHING_NONE;
2662 // process items
2663 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2664 DoAllEffectOnTarget(&(*ihit));
2666 // process ground
2667 for(uint32 j = 0;j<3;j++)
2669 // persistent area auras target only the ground
2670 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2671 HandleEffects(NULL,NULL,NULL, j);
2675 void Spell::_handle_finish_phase()
2677 // spell log
2678 if(m_needSpellLog)
2679 SendLogExecute();
2682 void Spell::SendSpellCooldown()
2684 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2685 return;
2687 Player* _player = (Player*)m_caster;
2689 // mana/health/etc potions, disabled by client (until combat out as declarate)
2690 if (m_CastItem && m_CastItem->IsPotion())
2692 // need in some way provided data for Spell::finish SendCooldownEvent
2693 _player->SetLastPotionId(m_CastItem->GetEntry());
2694 return;
2697 // have infinity cooldown but set at aura apply
2698 if(m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2699 return;
2701 _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this);
2704 void Spell::update(uint32 difftime)
2706 // update pointers based at it's GUIDs
2707 UpdatePointers();
2709 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2711 cancel();
2712 return;
2715 // check if the player caster has moved before the spell finished
2716 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2717 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2718 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2720 // always cancel for channeled spells
2721 if( m_spellState == SPELL_STATE_CASTING )
2722 cancel();
2723 // don't cancel for melee, autorepeat, triggered and instant spells
2724 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2725 cancel();
2728 switch(m_spellState)
2730 case SPELL_STATE_PREPARING:
2732 if(m_timer)
2734 if(difftime >= m_timer)
2735 m_timer = 0;
2736 else
2737 m_timer -= difftime;
2740 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2741 cast();
2742 } break;
2743 case SPELL_STATE_CASTING:
2745 if(m_timer > 0)
2747 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2749 // check if player has jumped before the channeling finished
2750 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2751 cancel();
2753 // check for incapacitating player states
2754 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2755 cancel();
2757 // check if player has turned if flag is set
2758 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2759 cancel();
2762 // check if there are alive targets left
2763 if (!IsAliveUnitPresentInTargetList())
2765 SendChannelUpdate(0);
2766 finish();
2769 if(difftime >= m_timer)
2770 m_timer = 0;
2771 else
2772 m_timer -= difftime;
2775 if(m_timer == 0)
2777 SendChannelUpdate(0);
2779 // channeled spell processed independently for quest targeting
2780 // cast at creature (or GO) quest objectives update at successful cast channel finished
2781 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2782 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2784 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2786 TargetInfo* target = &*ihit;
2787 if(!IS_CREATURE_GUID(target->targetGUID))
2788 continue;
2790 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2791 if (unit==NULL)
2792 continue;
2794 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2797 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2799 GOTargetInfo* target = &*ihit;
2801 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2802 if(!go)
2803 continue;
2805 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2809 finish();
2811 } break;
2812 default:
2814 }break;
2818 void Spell::finish(bool ok)
2820 if(!m_caster)
2821 return;
2823 if(m_spellState == SPELL_STATE_FINISHED)
2824 return;
2826 m_spellState = SPELL_STATE_FINISHED;
2828 // other code related only to successfully finished spells
2829 if(!ok)
2830 return;
2832 //remove spell mods
2833 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2834 ((Player*)m_caster)->RemoveSpellMods(this);
2836 // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2837 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2838 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2840 if (!(*i)->isAffectedOnSpell(m_spellInfo))
2841 continue;
2842 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2843 if( ihit->missCondition == SPELL_MISS_NONE )
2845 // check m_caster->GetGUID() let load auras at login and speedup most often case
2846 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2847 if (unit && unit->isAlive())
2849 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2850 uint32 auraSpellIdx = (*i)->GetEffIndex();
2851 // Calculate chance at that moment (can be depend for example from combo points)
2852 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2853 if(roll_chance_i(chance))
2854 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2859 // Heal caster for all health leech from all targets
2860 if (m_healthLeech)
2862 m_caster->ModifyHealth(m_healthLeech);
2863 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2866 if (IsMeleeAttackResetSpell())
2868 m_caster->resetAttackTimer(BASE_ATTACK);
2869 if(m_caster->haveOffhandWeapon())
2870 m_caster->resetAttackTimer(OFF_ATTACK);
2873 /*if (IsRangedAttackResetSpell())
2874 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2876 // Clear combo at finish state
2877 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2879 // Not drop combopoints if negative spell and if any miss on enemy exist
2880 bool needDrop = true;
2881 if (!IsPositiveSpell(m_spellInfo->Id))
2882 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2883 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2885 needDrop = false;
2886 break;
2888 if (needDrop)
2889 ((Player*)m_caster)->ClearComboPoints();
2892 // potions disabled by client, send event "not in combat" if need
2893 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2894 ((Player*)m_caster)->UpdatePotionCooldown(this);
2896 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2897 if(!m_TriggerSpells.empty())
2898 TriggerSpell();
2900 // Stop Attack for some spells
2901 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2902 m_caster->AttackStop();
2905 void Spell::SendCastResult(SpellCastResult result)
2907 if(result == SPELL_CAST_OK)
2908 return;
2910 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2911 return;
2913 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2914 return;
2916 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2917 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2918 data << uint32(m_spellInfo->Id);
2919 data << uint8(result); // problem
2920 switch (result)
2922 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2923 data << uint32(m_spellInfo->RequiresSpellFocus);
2924 break;
2925 case SPELL_FAILED_REQUIRES_AREA:
2926 // hardcode areas limitation case
2927 switch(m_spellInfo->Id)
2929 case 41617: // Cenarion Mana Salve
2930 case 41619: // Cenarion Healing Salve
2931 data << uint32(3905);
2932 break;
2933 case 41618: // Bottled Nethergon Energy
2934 case 41620: // Bottled Nethergon Vapor
2935 data << uint32(3842);
2936 break;
2937 case 45373: // Bloodberry Elixir
2938 data << uint32(4075);
2939 break;
2940 default: // default case (don't must be)
2941 data << uint32(0);
2942 break;
2944 break;
2945 case SPELL_FAILED_TOTEMS:
2946 if(m_spellInfo->Totem[0])
2947 data << uint32(m_spellInfo->Totem[0]);
2948 if(m_spellInfo->Totem[1])
2949 data << uint32(m_spellInfo->Totem[1]);
2950 break;
2951 case SPELL_FAILED_TOTEM_CATEGORY:
2952 if(m_spellInfo->TotemCategory[0])
2953 data << uint32(m_spellInfo->TotemCategory[0]);
2954 if(m_spellInfo->TotemCategory[1])
2955 data << uint32(m_spellInfo->TotemCategory[1]);
2956 break;
2957 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2958 data << uint32(m_spellInfo->EquippedItemClass);
2959 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2960 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2961 break;
2963 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2966 void Spell::SendSpellStart()
2968 if(!IsNeedSendToClient())
2969 return;
2971 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2973 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2974 if(IsRangedSpell())
2975 castFlags |= CAST_FLAG_AMMO;
2977 if(m_spellInfo->runeCostID)
2978 castFlags |= CAST_FLAG_UNKNOWN10;
2980 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2982 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2983 if(m_CastItem)
2984 data.append(m_CastItem->GetPackGUID());
2985 else
2986 data.append(m_caster->GetPackGUID());
2988 data.append(m_caster->GetPackGUID());
2989 data << uint8(m_cast_count); // pending spell cast?
2990 data << uint32(m_spellInfo->Id); // spellId
2991 data << uint32(castFlags); // cast flags
2992 data << uint32(m_timer); // delay?
2994 m_targets.write(&data);
2996 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2997 data << uint32(0);
2999 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
3001 uint8 v1 = 0;//m_runesState;
3002 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
3003 data << uint8(v1); // runes state before
3004 data << uint8(v2); // runes state after
3005 for(uint8 i = 0; i < MAX_RUNES; ++i)
3007 uint8 m = (1 << i);
3008 if(m & v1) // usable before...
3009 if(!(m & v2)) // ...but on cooldown now...
3010 data << uint8(0); // some unknown byte (time?)
3014 if ( castFlags & CAST_FLAG_AMMO )
3015 WriteAmmoToPacket(&data);
3017 m_caster->SendMessageToSet(&data, true);
3020 void Spell::SendSpellGo()
3022 // not send invisible spell casting
3023 if(!IsNeedSendToClient())
3024 return;
3026 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
3028 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3030 uint32 castFlags = CAST_FLAG_UNKNOWN3;
3031 if(IsRangedSpell())
3032 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
3034 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
3036 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
3037 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
3038 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
3041 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
3043 if(m_CastItem)
3044 data.append(m_CastItem->GetPackGUID());
3045 else
3046 data.append(m_caster->GetPackGUID());
3048 data.append(m_caster->GetPackGUID());
3049 data << uint8(m_cast_count); // pending spell cast?
3050 data << uint32(m_spellInfo->Id); // spellId
3051 data << uint32(castFlags); // cast flags
3052 data << uint32(getMSTime()); // timestamp
3054 WriteSpellGoTargets(&data);
3056 m_targets.write(&data);
3058 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
3059 data << uint32(0);
3061 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
3063 uint8 v1 = m_runesState;
3064 uint8 v2 = ((Player*)m_caster)->GetRunesState();
3065 data << uint8(v1); // runes state before
3066 data << uint8(v2); // runes state after
3067 for(uint8 i = 0; i < MAX_RUNES; ++i)
3069 uint8 m = (1 << i);
3070 if(m & v1) // usable before...
3071 if(!(m & v2)) // ...but on cooldown now...
3072 data << uint8(0); // some unknown byte (time?)
3076 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
3078 data << float(0);
3079 data << uint32(0);
3082 if ( castFlags & CAST_FLAG_AMMO )
3083 WriteAmmoToPacket(&data);
3085 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
3087 data << uint32(0);
3088 data << uint32(0);
3091 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
3093 data << uint8(0);
3096 m_caster->SendMessageToSet(&data, true);
3099 void Spell::WriteAmmoToPacket( WorldPacket * data )
3101 uint32 ammoInventoryType = 0;
3102 uint32 ammoDisplayID = 0;
3104 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3106 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
3107 if(pItem)
3109 ammoInventoryType = pItem->GetProto()->InventoryType;
3110 if( ammoInventoryType == INVTYPE_THROWN )
3111 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
3112 else
3114 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
3115 if(ammoID)
3117 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
3118 if(pProto)
3120 ammoDisplayID = pProto->DisplayInfoID;
3121 ammoInventoryType = pProto->InventoryType;
3124 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
3126 ammoDisplayID = 5996; // normal arrow
3127 ammoInventoryType = INVTYPE_AMMO;
3132 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
3134 *data << uint32(ammoDisplayID);
3135 *data << uint32(ammoInventoryType);
3138 void Spell::WriteSpellGoTargets( WorldPacket * data )
3140 // This function also fill data for channeled spells:
3141 // m_needAliveTargetMask req for stop channelig if one target die
3142 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3143 uint32 miss = 0;
3144 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3146 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3148 // possibly SPELL_MISS_IMMUNE2 for this??
3149 ihit->missCondition = SPELL_MISS_IMMUNE2;
3150 miss++;
3152 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3153 hit++;
3154 else
3155 miss++;
3158 *data << (uint8)hit;
3159 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3160 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3162 *data << uint64(ihit->targetGUID);
3163 m_needAliveTargetMask |=ihit->effectMask;
3166 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3167 *data << uint64(ighit->targetGUID); // Always hits
3169 *data << (uint8)miss;
3170 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3172 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3174 *data << uint64(ihit->targetGUID);
3175 *data << uint8(ihit->missCondition);
3176 if( ihit->missCondition == SPELL_MISS_REFLECT )
3177 *data << uint8(ihit->reflectResult);
3180 // Reset m_needAliveTargetMask for non channeled spell
3181 if(!IsChanneledSpell(m_spellInfo))
3182 m_needAliveTargetMask = 0;
3185 void Spell::SendLogExecute()
3187 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3189 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3191 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3192 data.append(m_caster->GetPackGUID());
3193 else
3194 data.append(target->GetPackGUID());
3196 data << uint32(m_spellInfo->Id);
3197 uint32 count1 = 1;
3198 data << uint32(count1); // count1 (effect count?)
3199 for(uint32 i = 0; i < count1; ++i)
3201 data << uint32(m_spellInfo->Effect[0]); // spell effect
3202 uint32 count2 = 1;
3203 data << uint32(count2); // count2 (target count?)
3204 for(uint32 j = 0; j < count2; ++j)
3206 switch(m_spellInfo->Effect[0])
3208 case SPELL_EFFECT_POWER_DRAIN:
3209 if(Unit *unit = m_targets.getUnitTarget())
3210 data.append(unit->GetPackGUID());
3211 else
3212 data << uint8(0);
3213 data << uint32(0);
3214 data << uint32(0);
3215 data << float(0);
3216 break;
3217 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3218 if(Unit *unit = m_targets.getUnitTarget())
3219 data.append(unit->GetPackGUID());
3220 else
3221 data << uint8(0);
3222 data << uint32(0); // count?
3223 break;
3224 case SPELL_EFFECT_INTERRUPT_CAST:
3225 if(Unit *unit = m_targets.getUnitTarget())
3226 data.append(unit->GetPackGUID());
3227 else
3228 data << uint8(0);
3229 data << uint32(0); // spellid
3230 break;
3231 case SPELL_EFFECT_DURABILITY_DAMAGE:
3232 if(Unit *unit = m_targets.getUnitTarget())
3233 data.append(unit->GetPackGUID());
3234 else
3235 data << uint8(0);
3236 data << uint32(0);
3237 data << uint32(0);
3238 break;
3239 case SPELL_EFFECT_OPEN_LOCK:
3240 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3241 if(Item *item = m_targets.getItemTarget())
3242 data.append(item->GetPackGUID());
3243 else
3244 data << uint8(0);
3245 break;
3246 case SPELL_EFFECT_CREATE_ITEM:
3247 case SPELL_EFFECT_CREATE_ITEM_2:
3248 data << uint32(m_spellInfo->EffectItemType[0]);
3249 break;
3250 case SPELL_EFFECT_SUMMON:
3251 case SPELL_EFFECT_TRANS_DOOR:
3252 case SPELL_EFFECT_SUMMON_PET:
3253 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3254 case SPELL_EFFECT_CREATE_HOUSE:
3255 case SPELL_EFFECT_DUEL:
3256 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3257 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3258 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3259 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3260 if(Unit *unit = m_targets.getUnitTarget())
3261 data.append(unit->GetPackGUID());
3262 else if(m_targets.getItemTargetGUID())
3263 data.appendPackGUID(m_targets.getItemTargetGUID());
3264 else if(GameObject *go = m_targets.getGOTarget())
3265 data.append(go->GetPackGUID());
3266 else
3267 data << uint8(0); // guid
3268 break;
3269 case SPELL_EFFECT_FEED_PET:
3270 data << uint32(m_targets.getItemTargetEntry());
3271 break;
3272 case SPELL_EFFECT_DISMISS_PET:
3273 if(Unit *unit = m_targets.getUnitTarget())
3274 data.append(unit->GetPackGUID());
3275 else
3276 data << uint8(0);
3277 break;
3278 case SPELL_EFFECT_RESURRECT:
3279 case SPELL_EFFECT_RESURRECT_NEW:
3280 if(Unit *unit = m_targets.getUnitTarget())
3281 data.append(unit->GetPackGUID());
3282 else
3283 data << uint8(0);
3284 break;
3285 default:
3286 return;
3291 m_caster->SendMessageToSet(&data, true);
3294 void Spell::SendInterrupted(uint8 result)
3296 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3297 data.append(m_caster->GetPackGUID());
3298 data << uint8(m_cast_count);
3299 data << uint32(m_spellInfo->Id);
3300 data << uint8(result);
3301 m_caster->SendMessageToSet(&data, true);
3303 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3304 data.append(m_caster->GetPackGUID());
3305 data << uint8(m_cast_count);
3306 data << uint32(m_spellInfo->Id);
3307 data << uint8(result);
3308 m_caster->SendMessageToSet(&data, true);
3311 void Spell::SendChannelUpdate(uint32 time)
3313 if(time == 0)
3315 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3316 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3319 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3320 return;
3322 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3323 data.append(m_caster->GetPackGUID());
3324 data << uint32(time);
3326 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3329 void Spell::SendChannelStart(uint32 duration)
3331 WorldObject* target = NULL;
3333 // select first not resisted target from target list for _0_ effect
3334 if(!m_UniqueTargetInfo.empty())
3336 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3338 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3340 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3341 break;
3345 else if(!m_UniqueGOTargetInfo.empty())
3347 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3349 if(itr->effectMask & (1<<0) )
3351 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3352 break;
3357 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3359 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3360 data.append(m_caster->GetPackGUID());
3361 data << uint32(m_spellInfo->Id);
3362 data << uint32(duration);
3364 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3367 m_timer = duration;
3368 if(target)
3369 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3370 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3373 void Spell::SendResurrectRequest(Player* target)
3375 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3376 // However, the packet structure differs slightly
3378 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3380 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3381 data << uint64(m_caster->GetGUID());
3382 data << uint32(strlen(sentName)+1);
3384 data << sentName;
3385 data << uint8(0);
3387 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3388 target->GetSession()->SendPacket(&data);
3391 void Spell::SendPlaySpellVisual(uint32 SpellID)
3393 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3394 return;
3396 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3397 data << uint64(m_caster->GetGUID());
3398 data << uint32(SpellID); // spell visual id?
3399 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3402 void Spell::TakeCastItem()
3404 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3405 return;
3407 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3408 if(m_IsTriggeredSpell)
3409 return;
3411 ItemPrototype const *proto = m_CastItem->GetProto();
3413 if(!proto)
3415 // This code is to avoid a crash
3416 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3417 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3418 return;
3421 bool expendable = false;
3422 bool withoutCharges = false;
3424 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
3426 if (proto->Spells[i].SpellId)
3428 // item has limited charges
3429 if (proto->Spells[i].SpellCharges)
3431 if (proto->Spells[i].SpellCharges < 0)
3432 expendable = true;
3434 int32 charges = m_CastItem->GetSpellCharges(i);
3436 // item has charges left
3437 if (charges)
3439 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3440 if (proto->Stackable == 1)
3441 m_CastItem->SetSpellCharges(i, charges);
3442 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3445 // all charges used
3446 withoutCharges = (charges == 0);
3451 if (expendable && withoutCharges)
3453 uint32 count = 1;
3454 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3456 // prevent crash at access to deleted m_targets.getItemTarget
3457 if(m_CastItem==m_targets.getItemTarget())
3458 m_targets.setItemTarget(NULL);
3460 m_CastItem = NULL;
3464 void Spell::TakePower()
3466 if(m_CastItem || m_triggeredByAuraSpell)
3467 return;
3469 // health as power used
3470 if(m_spellInfo->powerType == POWER_HEALTH)
3472 m_caster->ModifyHealth( -(int32)m_powerCost );
3473 return;
3476 if(m_spellInfo->powerType >= MAX_POWERS)
3478 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3479 return;
3482 Powers powerType = Powers(m_spellInfo->powerType);
3484 if(powerType == POWER_RUNE)
3486 TakeRunePower();
3487 return;
3490 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3492 // Set the five second timer
3493 if (powerType == POWER_MANA && m_powerCost > 0)
3494 m_caster->SetLastManaUse(getMSTime());
3497 SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
3499 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3500 return SPELL_CAST_OK;
3502 Player *plr = (Player*)m_caster;
3504 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3505 return SPELL_CAST_OK;
3507 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3509 if(!src)
3510 return SPELL_CAST_OK;
3512 if(src->NoRuneCost())
3513 return SPELL_CAST_OK;
3515 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3517 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3518 runeCost[i] = src->RuneCost[i];
3520 runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
3522 for(uint32 i = 0; i < MAX_RUNES; ++i)
3524 uint8 rune = plr->GetCurrentRune(i);
3525 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3526 runeCost[rune]--;
3529 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3530 if(runeCost[i] > 0)
3531 runeCost[RUNE_DEATH] += runeCost[i];
3533 if(runeCost[RUNE_DEATH] > MAX_RUNES)
3534 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3536 return SPELL_CAST_OK;
3539 void Spell::TakeRunePower()
3541 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3542 return;
3544 Player *plr = (Player*)m_caster;
3546 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3547 return;
3549 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3551 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3552 return;
3554 m_runesState = plr->GetRunesState(); // store previous state
3556 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3558 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3560 runeCost[i] = src->RuneCost[i];
3563 runeCost[RUNE_DEATH] = 0; // calculated later
3565 for(uint32 i = 0; i < MAX_RUNES; ++i)
3567 uint8 rune = plr->GetCurrentRune(i);
3568 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3570 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3571 runeCost[rune]--;
3575 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3577 if(runeCost[RUNE_DEATH] > 0)
3579 for(uint32 i = 0; i < MAX_RUNES; ++i)
3581 uint8 rune = plr->GetCurrentRune(i);
3582 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3584 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3585 runeCost[rune]--;
3586 plr->ConvertRune(i, plr->GetBaseRune(i));
3587 if(runeCost[RUNE_DEATH] == 0)
3588 break;
3593 // you can gain some runic power when use runes
3594 float rp = src->runePowerGain;;
3595 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3596 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3599 void Spell::TakeReagents()
3601 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3602 return;
3604 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3605 return;
3607 Player* p_caster = (Player*)m_caster;
3608 if (p_caster->CanNoReagentCast(m_spellInfo))
3609 return;
3611 for(uint32 x=0;x<8;x++)
3613 if(m_spellInfo->Reagent[x] <= 0)
3614 continue;
3616 uint32 itemid = m_spellInfo->Reagent[x];
3617 uint32 itemcount = m_spellInfo->ReagentCount[x];
3619 // if CastItem is also spell reagent
3620 if (m_CastItem)
3622 ItemPrototype const *proto = m_CastItem->GetProto();
3623 if( proto && proto->ItemId == itemid )
3625 for(int s=0;s < MAX_ITEM_PROTO_SPELLS; ++s)
3627 // CastItem will be used up and does not count as reagent
3628 int32 charges = m_CastItem->GetSpellCharges(s);
3629 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3631 ++itemcount;
3632 break;
3636 m_CastItem = NULL;
3640 // if getItemTarget is also spell reagent
3641 if (m_targets.getItemTargetEntry()==itemid)
3642 m_targets.setItemTarget(NULL);
3644 p_caster->DestroyItemCount(itemid, itemcount, true);
3648 void Spell::HandleThreatSpells(uint32 spellId)
3650 if(!m_targets.getUnitTarget() || !spellId)
3651 return;
3653 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3654 return;
3656 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3657 if(!threatSpell)
3658 return;
3660 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3662 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3665 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3667 unitTarget = pUnitTarget;
3668 itemTarget = pItemTarget;
3669 gameObjTarget = pGOTarget;
3671 uint8 eff = m_spellInfo->Effect[i];
3673 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3675 sLog.outDebug( "Spell: Effect : %u", eff);
3677 if(eff<TOTAL_SPELL_EFFECTS)
3679 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3680 (*this.*SpellEffects[eff])(i);
3683 else
3685 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3686 if (m_CastItem)
3687 EffectEnchantItemTmp(i);
3688 else
3690 sLog.outError("SPELL: unknown effect %u spell id %u",
3691 eff, m_spellInfo->Id);
3697 void Spell::TriggerSpell()
3699 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3701 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3702 spell->prepare(&m_targets); // use original spell original targets
3706 SpellCastResult Spell::CheckCast(bool strict)
3708 // check cooldowns to prevent cheating
3709 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3711 if(m_triggeredByAuraSpell)
3712 return SPELL_FAILED_DONT_REPORT;
3713 else
3714 return SPELL_FAILED_NOT_READY;
3717 // only allow triggered spells if at an ended battleground
3718 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3719 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3720 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3721 return SPELL_FAILED_DONT_REPORT;
3723 // only check at first call, Stealth auras are already removed at second call
3724 // for now, ignore triggered spells
3725 if( strict && !m_IsTriggeredSpell)
3727 bool checkForm = true;
3728 // Ignore form req aura
3729 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3730 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3732 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3733 continue;
3734 checkForm = false;
3735 break;
3737 if (checkForm)
3739 // Cannot be used in this stance/form
3740 SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form);
3741 if(shapeError != SPELL_CAST_OK)
3742 return shapeError;
3744 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3745 return SPELL_FAILED_ONLY_STEALTHED;
3749 // caster state requirements
3750 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3751 return SPELL_FAILED_CASTER_AURASTATE;
3752 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3753 return SPELL_FAILED_CASTER_AURASTATE;
3755 // Caster aura req check if need
3756 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3757 return SPELL_FAILED_CASTER_AURASTATE;
3758 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3759 return SPELL_FAILED_CASTER_AURASTATE;
3761 // cancel autorepeat spells if cast start when moving
3762 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3763 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3765 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3766 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3767 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3768 return SPELL_FAILED_MOVING;
3771 if(Unit *target = m_targets.getUnitTarget())
3773 // target state requirements (not allowed state), apply to self also
3774 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3775 return SPELL_FAILED_TARGET_AURASTATE;
3777 // Target aura req check if need
3778 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3779 return SPELL_FAILED_CASTER_AURASTATE;
3780 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3781 return SPELL_FAILED_CASTER_AURASTATE;
3783 if(target != m_caster)
3785 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3786 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3787 return SPELL_FAILED_TARGET_AURASTATE;
3789 // Not allow casting on flying player
3790 if (target->isInFlight())
3791 return SPELL_FAILED_BAD_TARGETS;
3793 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3794 return SPELL_FAILED_LINE_OF_SIGHT;
3796 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3797 // this case can be triggered if rank not found (too low-level target for first rank)
3798 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3799 for(int i=0;i<3;i++)
3800 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3801 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3802 return SPELL_FAILED_LOWLEVEL;
3804 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3806 // Additional check for some spells
3807 // If 0 spell effect empty - client not send target data (need use selection)
3808 // TODO: check it on next client version
3809 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3810 m_spellInfo->EffectImplicitTargetA[1] == TARGET_CHAIN_DAMAGE)
3812 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3813 m_targets.setUnitTarget(target);
3814 else
3815 return SPELL_FAILED_BAD_TARGETS;
3819 // check pet presents
3820 for(int j=0;j<3;j++)
3822 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3824 target = m_caster->GetPet();
3825 if(!target)
3827 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3828 return SPELL_FAILED_DONT_REPORT;
3829 else
3830 return SPELL_FAILED_NO_PET;
3832 break;
3836 //check creature type
3837 //ignore self casts (including area casts when caster selected as target)
3838 if(target != m_caster)
3840 if(!CheckTargetCreatureType(target))
3842 if(target->GetTypeId()==TYPEID_PLAYER)
3843 return SPELL_FAILED_TARGET_IS_PLAYER;
3844 else
3845 return SPELL_FAILED_BAD_TARGETS;
3849 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3850 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3851 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3853 // check correctness positive/negative cast target (pet cast real check and cheating check)
3854 if(IsPositiveSpell(m_spellInfo->Id))
3856 if(m_caster->IsHostileTo(target))
3857 return SPELL_FAILED_BAD_TARGETS;
3859 else
3861 if(m_caster->IsFriendlyTo(target))
3862 return SPELL_FAILED_BAD_TARGETS;
3866 if(IsPositiveSpell(m_spellInfo->Id))
3867 if(target->IsImmunedToSpell(m_spellInfo))
3868 return SPELL_FAILED_TARGET_AURASTATE;
3870 //Must be behind the target.
3871 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3873 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3874 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3876 SendInterrupted(2);
3877 return SPELL_FAILED_NOT_BEHIND;
3881 //Target must be facing you.
3882 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3884 SendInterrupted(2);
3885 return SPELL_FAILED_NOT_INFRONT;
3888 // check if target is in combat
3889 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3890 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3893 // Spell casted only on battleground
3894 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3895 if(!((Player*)m_caster)->InBattleGround())
3896 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3898 // do not allow spells to be cast in arenas
3899 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3900 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3901 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3902 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * IN_MILISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3903 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3904 if(mapEntry->IsBattleArena())
3905 return SPELL_FAILED_NOT_IN_ARENA;
3907 // zone check
3908 uint32 zone, area;
3909 m_caster->GetZoneAndAreaId(zone,area);
3911 SpellCastResult locRes= spellmgr.GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area,
3912 m_caster->GetTypeId()==TYPEID_PLAYER ? ((Player*)m_caster) : NULL);
3913 if(locRes != SPELL_CAST_OK)
3914 return locRes;
3916 // not let players cast spells at mount (and let do it to creatures)
3917 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3918 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3920 if(m_caster->isInFlight())
3921 return SPELL_FAILED_NOT_FLYING;
3922 else
3923 return SPELL_FAILED_NOT_MOUNTED;
3926 // always (except passive spells) check items (focus object can be required for any type casts)
3927 if(!IsPassiveSpell(m_spellInfo->Id))
3929 SpellCastResult castResult = CheckItems();
3930 if(castResult != SPELL_CAST_OK)
3931 return castResult;
3934 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3935 if(m_UniqueTargetInfo.empty()) // skip second CheckCast apply (for delayed spells for example)
3937 for(uint8 j = 0; j < 3; j++)
3939 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3940 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3941 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3942 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3944 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3945 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3946 if(lower==upper)
3947 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);
3949 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3950 float range = GetSpellMaxRange(srange);
3952 Creature* creatureScriptTarget = NULL;
3953 GameObject* goScriptTarget = NULL;
3955 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3957 switch(i_spellST->second.type)
3959 case SPELL_TARGET_TYPE_GAMEOBJECT:
3961 GameObject* p_GameObject = NULL;
3963 if(i_spellST->second.targetEntry)
3965 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3966 Cell cell(p);
3967 cell.data.Part.reserved = ALL_DISTRICT;
3969 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3970 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
3972 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3973 CellLock<GridReadGuard> cell_lock(cell, p);
3974 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3976 if(p_GameObject)
3978 // remember found target and range, next attempt will find more near target with another entry
3979 creatureScriptTarget = NULL;
3980 goScriptTarget = p_GameObject;
3981 range = go_check.GetLastRange();
3984 else if( focusObject ) //Focus Object
3986 float frange = m_caster->GetDistance(focusObject);
3987 if(range >= frange)
3989 creatureScriptTarget = NULL;
3990 goScriptTarget = focusObject;
3991 range = frange;
3994 break;
3996 case SPELL_TARGET_TYPE_CREATURE:
3997 case SPELL_TARGET_TYPE_DEAD:
3998 default:
4000 Creature *p_Creature = NULL;
4002 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4003 Cell cell(p);
4004 cell.data.Part.reserved = ALL_DISTRICT;
4005 cell.SetNoCreate(); // Really don't know what is that???
4007 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
4008 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
4010 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
4012 CellLock<GridReadGuard> cell_lock(cell, p);
4013 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
4015 if(p_Creature )
4017 creatureScriptTarget = p_Creature;
4018 goScriptTarget = NULL;
4019 range = u_check.GetLastRange();
4021 break;
4026 if(creatureScriptTarget)
4028 // store coordinates for TARGET_SCRIPT_COORDINATES
4029 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
4030 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
4032 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
4034 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
4035 AddUnitTarget(creatureScriptTarget, j);
4037 // store explicit target for TARGET_SCRIPT
4038 else
4039 AddUnitTarget(creatureScriptTarget, j);
4041 else if(goScriptTarget)
4043 // store coordinates for TARGET_SCRIPT_COORDINATES
4044 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
4045 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
4047 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
4049 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
4050 AddGOTarget(goScriptTarget, j);
4052 // store explicit target for TARGET_SCRIPT
4053 else
4054 AddGOTarget(goScriptTarget, j);
4056 //Missing DB Entry or targets for this spellEffect.
4057 else
4059 // not report target not existence for triggered spells
4060 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
4061 return SPELL_FAILED_DONT_REPORT;
4062 else
4063 return SPELL_FAILED_BAD_TARGETS;
4069 if(!m_IsTriggeredSpell)
4071 SpellCastResult castResult = CheckRange(strict);
4072 if(castResult != SPELL_CAST_OK)
4073 return castResult;
4077 SpellCastResult castResult = CheckPower();
4078 if(castResult != SPELL_CAST_OK)
4079 return castResult;
4082 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
4084 SpellCastResult castResult = CheckCasterAuras();
4085 if(castResult != SPELL_CAST_OK)
4086 return castResult;
4089 for (int i = 0; i < 3; i++)
4091 // for effects of spells that have only one target
4092 switch(m_spellInfo->Effect[i])
4094 case SPELL_EFFECT_DUMMY:
4096 if(m_spellInfo->SpellIconID == 1648) // Execute
4098 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4099 return SPELL_FAILED_BAD_TARGETS;
4101 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
4103 if(m_caster->IsInWater())
4104 return SPELL_FAILED_ONLY_ABOVEWATER;
4106 else if(m_spellInfo->SpellIconID==156) // Holy Shock
4108 // spell different for friends and enemies
4109 // hart version required facing
4110 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, m_targets.getUnitTarget() ))
4111 return SPELL_FAILED_UNIT_NOT_INFRONT;
4113 break;
4115 case SPELL_EFFECT_SCHOOL_DAMAGE:
4117 // Hammer of Wrath
4118 if(m_spellInfo->SpellVisual[0] == 7250)
4120 if (!m_targets.getUnitTarget())
4121 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4123 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4124 return SPELL_FAILED_BAD_TARGETS;
4126 break;
4128 case SPELL_EFFECT_TAMECREATURE:
4130 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
4131 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4133 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
4134 return SPELL_FAILED_HIGHLEVEL;
4136 // use SMSG_PET_TAME_FAILURE?
4137 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
4138 return SPELL_FAILED_BAD_TARGETS;
4140 if(m_caster->GetPetGUID())
4141 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4143 if(m_caster->GetCharmGUID())
4144 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4146 break;
4148 case SPELL_EFFECT_LEARN_SPELL:
4150 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4151 break;
4153 Pet* pet = m_caster->GetPet();
4155 if(!pet)
4156 return SPELL_FAILED_NO_PET;
4158 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4160 if(!learn_spellproto)
4161 return SPELL_FAILED_NOT_KNOWN;
4163 if(m_spellInfo->spellLevel > pet->getLevel())
4164 return SPELL_FAILED_LOWLEVEL;
4166 break;
4168 case SPELL_EFFECT_LEARN_PET_SPELL:
4170 Pet* pet = m_caster->GetPet();
4172 if(!pet)
4173 return SPELL_FAILED_NO_PET;
4175 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4177 if(!learn_spellproto)
4178 return SPELL_FAILED_NOT_KNOWN;
4180 if(m_spellInfo->spellLevel > pet->getLevel())
4181 return SPELL_FAILED_LOWLEVEL;
4183 break;
4185 case SPELL_EFFECT_FEED_PET:
4187 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4188 return SPELL_FAILED_BAD_TARGETS;
4190 Item* foodItem = m_targets.getItemTarget();
4191 if(!foodItem)
4192 return SPELL_FAILED_BAD_TARGETS;
4194 Pet* pet = m_caster->GetPet();
4196 if(!pet)
4197 return SPELL_FAILED_NO_PET;
4199 if(!pet->HaveInDiet(foodItem->GetProto()))
4200 return SPELL_FAILED_WRONG_PET_FOOD;
4202 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4203 return SPELL_FAILED_FOOD_LOWLEVEL;
4205 if(m_caster->isInCombat() || pet->isInCombat())
4206 return SPELL_FAILED_AFFECTING_COMBAT;
4208 break;
4210 case SPELL_EFFECT_POWER_BURN:
4211 case SPELL_EFFECT_POWER_DRAIN:
4213 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4214 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4215 if(Unit* target = m_targets.getUnitTarget())
4216 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4217 return SPELL_FAILED_BAD_TARGETS;
4218 break;
4220 case SPELL_EFFECT_CHARGE:
4222 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4223 return SPELL_FAILED_ROOTED;
4225 break;
4227 case SPELL_EFFECT_SKINNING:
4229 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4230 return SPELL_FAILED_BAD_TARGETS;
4232 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4233 return SPELL_FAILED_TARGET_UNSKINNABLE;
4235 Creature* creature = (Creature*)m_targets.getUnitTarget();
4236 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4238 return SPELL_FAILED_TARGET_NOT_LOOTED;
4241 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4243 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4244 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4245 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4246 if (ReqValue > skillValue)
4247 return SPELL_FAILED_LOW_CASTLEVEL;
4249 // chance for fail at orange skinning attempt
4250 if( (m_selfContainer && (*m_selfContainer) == this) &&
4251 skillValue < sWorld.GetConfigMaxSkillValue() &&
4252 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4253 return SPELL_FAILED_TRY_AGAIN;
4255 break;
4257 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4258 case SPELL_EFFECT_OPEN_LOCK:
4260 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4261 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4262 break;
4264 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4265 // we need a go target in case of TARGET_GAMEOBJECT
4266 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4267 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4268 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4269 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4270 return SPELL_FAILED_BAD_TARGETS;
4272 // In BattleGround players can use only flags and banners
4273 if( ((Player*)m_caster)->InBattleGround() &&
4274 !((Player*)m_caster)->CanUseBattleGroundObject() )
4275 return SPELL_FAILED_TRY_AGAIN;
4277 // get the lock entry
4278 uint32 lockId = 0;
4279 if (GameObject* go=m_targets.getGOTarget())
4280 lockId = go->GetLockId();
4281 else if(Item* itm=m_targets.getItemTarget())
4282 lockId = itm->GetProto()->LockID;
4284 SkillType skillId =SKILL_NONE;
4285 int32 reqSkillValue = 0;
4286 int32 skillValue = 0;
4288 // check lock compatibility
4289 SpellCastResult res = CanOpenLock(i,lockId,skillId,reqSkillValue,skillValue);
4290 if(res != SPELL_CAST_OK)
4291 return res;
4293 // chance for fail at orange mining/herb/LockPicking gathering attempt
4294 // second check prevent fail at rechecks
4295 if(skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
4297 bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
4299 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4300 if((canFailAtMax || skillValue < sWorld.GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue-25, skillValue+37))
4301 return SPELL_FAILED_TRY_AGAIN;
4303 break;
4305 case SPELL_EFFECT_SUMMON_DEAD_PET:
4307 Creature *pet = m_caster->GetPet();
4308 if(!pet)
4309 return SPELL_FAILED_NO_PET;
4311 if(pet->isAlive())
4312 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4314 break;
4316 // This is generic summon effect
4317 case SPELL_EFFECT_SUMMON:
4319 switch(m_spellInfo->EffectMiscValueB[i])
4321 case SUMMON_TYPE_POSESSED:
4322 case SUMMON_TYPE_POSESSED2:
4323 case SUMMON_TYPE_DEMON:
4324 case SUMMON_TYPE_SUMMON:
4326 if(m_caster->GetPetGUID())
4327 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4329 if(m_caster->GetCharmGUID())
4330 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4331 break;
4334 break;
4336 // Not used for summon?
4337 case SPELL_EFFECT_SUMMON_PHANTASM:
4339 if(m_caster->GetPetGUID())
4340 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4342 if(m_caster->GetCharmGUID())
4343 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4345 break;
4347 case SPELL_EFFECT_SUMMON_PET:
4349 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4352 Pet* pet = ((Player*)m_caster)->GetPet();
4354 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4356 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4357 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4359 else
4360 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4363 if(m_caster->GetCharmGUID())
4364 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4366 break;
4368 case SPELL_EFFECT_SUMMON_PLAYER:
4370 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4371 return SPELL_FAILED_BAD_TARGETS;
4372 if(!((Player*)m_caster)->GetSelection())
4373 return SPELL_FAILED_BAD_TARGETS;
4375 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4376 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4377 return SPELL_FAILED_BAD_TARGETS;
4379 // check if our map is dungeon
4380 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4382 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4383 if(!instance)
4384 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4385 if ( instance->levelMin > target->getLevel() )
4386 return SPELL_FAILED_LOWLEVEL;
4387 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4388 return SPELL_FAILED_HIGHLEVEL;
4390 break;
4392 case SPELL_EFFECT_LEAP:
4393 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4395 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4396 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4397 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4398 // teleport a bit above terrain level to avoid falling below it
4399 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4400 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4401 return SPELL_FAILED_TRY_AGAIN;
4403 float caster_pos_z = m_caster->GetPositionZ();
4404 // Control the caster to not climb or drop when +-fz > 8
4405 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4406 return SPELL_FAILED_TRY_AGAIN;
4408 // not allow use this effect at battleground until battleground start
4409 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4410 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4411 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4412 return SPELL_FAILED_TRY_AGAIN;
4413 break;
4415 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4417 if (m_targets.getUnitTarget()==m_caster)
4418 return SPELL_FAILED_BAD_TARGETS;
4419 break;
4421 default:break;
4425 for (int i = 0; i < 3; i++)
4427 switch(m_spellInfo->EffectApplyAuraName[i])
4429 case SPELL_AURA_DUMMY:
4431 //custom check
4432 switch(m_spellInfo->Id)
4434 case 61336:
4435 if(m_caster->GetTypeId()!=TYPEID_PLAYER || !((Player*)m_caster)->IsInFeralForm())
4436 return SPELL_FAILED_ONLY_SHAPESHIFT;
4437 break;
4438 default:
4439 break;
4441 break;
4443 case SPELL_AURA_MOD_POSSESS:
4444 case SPELL_AURA_MOD_CHARM:
4446 if(m_caster->GetPetGUID())
4447 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4449 if(m_caster->GetCharmGUID())
4450 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4452 if(m_caster->GetCharmerGUID())
4453 return SPELL_FAILED_CHARMED;
4455 if(!m_targets.getUnitTarget())
4456 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4458 if(m_targets.getUnitTarget()->GetCharmerGUID())
4459 return SPELL_FAILED_CHARMED;
4461 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4462 return SPELL_FAILED_HIGHLEVEL;
4464 break;
4466 case SPELL_AURA_MOUNTED:
4468 if (m_caster->IsInWater())
4469 return SPELL_FAILED_ONLY_ABOVEWATER;
4471 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4472 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4474 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4475 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4476 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4478 ShapeshiftForm form = m_caster->m_form;
4479 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4480 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4481 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4482 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4483 return SPELL_FAILED_NOT_SHAPESHIFT;
4485 break;
4487 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4489 if(!m_targets.getUnitTarget())
4490 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4492 // can be casted at non-friendly unit or own pet/charm
4493 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4494 return SPELL_FAILED_TARGET_FRIENDLY;
4496 break;
4498 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4499 case SPELL_AURA_FLY:
4501 // not allow cast fly spells at old maps by players (all spells is self target)
4502 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4504 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4505 return SPELL_FAILED_NOT_HERE;
4508 break;
4510 case SPELL_AURA_PERIODIC_MANA_LEECH:
4512 if (!m_targets.getUnitTarget())
4513 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4515 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4516 break;
4518 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4519 return SPELL_FAILED_BAD_TARGETS;
4521 break;
4523 default:
4524 break;
4528 // all ok
4529 return SPELL_CAST_OK;
4532 SpellCastResult Spell::CheckPetCast(Unit* target)
4534 if(!m_caster->isAlive())
4535 return SPELL_FAILED_CASTER_DEAD;
4537 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4538 return SPELL_FAILED_SPELL_IN_PROGRESS;
4539 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4540 return SPELL_FAILED_AFFECTING_COMBAT;
4542 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4544 //dead owner (pets still alive when owners ressed?)
4545 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4546 return SPELL_FAILED_CASTER_DEAD;
4548 if(!target && m_targets.getUnitTarget())
4549 target = m_targets.getUnitTarget();
4551 bool need = false;
4552 for(uint32 i = 0;i<3;i++)
4554 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)
4556 need = true;
4557 if(!target)
4558 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4559 break;
4562 if(need)
4563 m_targets.setUnitTarget(target);
4565 Unit* _target = m_targets.getUnitTarget();
4567 if(_target) //for target dead/target not valid
4569 if(!_target->isAlive())
4570 return SPELL_FAILED_BAD_TARGETS;
4572 if(IsPositiveSpell(m_spellInfo->Id))
4574 if(m_caster->IsHostileTo(_target))
4575 return SPELL_FAILED_BAD_TARGETS;
4577 else
4579 bool duelvsplayertar = false;
4580 for(int j=0;j<3;j++)
4582 //TARGET_DUELVSPLAYER is positive AND negative
4583 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4585 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4587 return SPELL_FAILED_BAD_TARGETS;
4591 //cooldown
4592 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4593 return SPELL_FAILED_NOT_READY;
4596 return CheckCast(true);
4599 SpellCastResult Spell::CheckCasterAuras() const
4601 // Flag drop spells totally immuned to caster auras
4602 // FIXME: find more nice check for all totally immuned spells
4603 // AttributesEx3 & 0x10000000?
4604 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4605 return SPELL_CAST_OK;
4607 uint8 school_immune = 0;
4608 uint32 mechanic_immune = 0;
4609 uint32 dispel_immune = 0;
4611 //Check if the spell grants school or mechanic immunity.
4612 //We use bitmasks so the loop is done only once and not on every aura check below.
4613 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4615 for(int i = 0;i < 3; i ++)
4617 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4618 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4619 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4620 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4621 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4622 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4624 //immune movement impairment and loss of control
4625 if(m_spellInfo->Id==(uint32)42292)
4626 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4629 //Check whether the cast should be prevented by any state you might have.
4630 SpellCastResult prevented_reason = SPELL_CAST_OK;
4631 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4632 uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
4633 if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4634 prevented_reason = SPELL_FAILED_STUNNED;
4635 else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4636 prevented_reason = SPELL_FAILED_CONFUSED;
4637 else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4638 prevented_reason = SPELL_FAILED_FLEEING;
4639 else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4640 prevented_reason = SPELL_FAILED_SILENCED;
4641 else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4642 prevented_reason = SPELL_FAILED_PACIFIED;
4644 // Attr must make flag drop spell totally immune from all effects
4645 if(prevented_reason != SPELL_CAST_OK)
4647 if(school_immune || mechanic_immune || dispel_immune)
4649 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4650 Unit::AuraMap const& auras = m_caster->GetAuras();
4651 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4653 if(itr->second)
4655 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4656 continue;
4657 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4658 continue;
4659 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4660 continue;
4662 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4663 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4664 switch(itr->second->GetModifier()->m_auraname)
4666 case SPELL_AURA_MOD_STUN:
4667 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4668 return SPELL_FAILED_STUNNED;
4669 break;
4670 case SPELL_AURA_MOD_CONFUSE:
4671 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4672 return SPELL_FAILED_CONFUSED;
4673 break;
4674 case SPELL_AURA_MOD_FEAR:
4675 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4676 return SPELL_FAILED_FLEEING;
4677 break;
4678 case SPELL_AURA_MOD_SILENCE:
4679 case SPELL_AURA_MOD_PACIFY:
4680 case SPELL_AURA_MOD_PACIFY_SILENCE:
4681 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4682 return SPELL_FAILED_PACIFIED;
4683 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4684 return SPELL_FAILED_SILENCED;
4685 break;
4690 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4691 else
4692 return prevented_reason;
4694 return SPELL_CAST_OK;
4697 bool Spell::CanAutoCast(Unit* target)
4699 uint64 targetguid = target->GetGUID();
4701 for(uint32 j = 0;j<3;j++)
4703 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4705 if( m_spellInfo->StackAmount <= 1)
4707 if( target->HasAura(m_spellInfo->Id, j) )
4708 return false;
4710 else
4712 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4713 return false;
4716 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4718 if( target->HasAura(m_spellInfo->Id, j) )
4719 return false;
4723 SpellCastResult result = CheckPetCast(target);
4725 if(result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4727 FillTargetMap();
4728 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4729 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4730 if( ihit->targetGUID == targetguid )
4731 return true;
4733 return false; //target invalid
4736 SpellCastResult Spell::CheckRange(bool strict)
4738 float range_mod;
4740 // self cast doesn't need range checking -- also for Starshards fix
4741 if (m_spellInfo->rangeIndex == 1)
4742 return SPELL_CAST_OK;
4744 if (strict) //add radius of caster
4745 range_mod = 1.25;
4746 else //add radius of caster and ~5 yds "give"
4747 range_mod = 6.25;
4749 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4750 float max_range = GetSpellMaxRange(srange) + range_mod;
4751 float min_range = GetSpellMinRange(srange);
4753 if(Player* modOwner = m_caster->GetSpellModOwner())
4754 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4756 Unit *target = m_targets.getUnitTarget();
4758 if(target && target != m_caster)
4760 // distance from target in checks
4761 float dist = m_caster->GetCombatDistance(target);
4763 if(dist > max_range)
4764 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4765 if(dist < min_range)
4766 return SPELL_FAILED_TOO_CLOSE;
4767 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4768 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4769 return SPELL_FAILED_UNIT_NOT_INFRONT;
4772 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4774 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4775 if(dist > max_range)
4776 return SPELL_FAILED_OUT_OF_RANGE;
4777 if(dist < min_range)
4778 return SPELL_FAILED_TOO_CLOSE;
4781 return SPELL_CAST_OK;
4784 int32 Spell::CalculatePowerCost()
4786 // item cast not used power
4787 if(m_CastItem)
4788 return 0;
4790 // Spell drain all exist power on cast (Only paladin lay of Hands)
4791 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4793 // If power type - health drain all
4794 if (m_spellInfo->powerType == POWER_HEALTH)
4795 return m_caster->GetHealth();
4796 // Else drain all power
4797 if (m_spellInfo->powerType < MAX_POWERS)
4798 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4799 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4800 return 0;
4803 // Base powerCost
4804 int32 powerCost = m_spellInfo->manaCost;
4805 // PCT cost from total amount
4806 if (m_spellInfo->ManaCostPercentage)
4808 switch (m_spellInfo->powerType)
4810 // health as power used
4811 case POWER_HEALTH:
4812 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4813 break;
4814 case POWER_MANA:
4815 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4816 break;
4817 case POWER_RAGE:
4818 case POWER_FOCUS:
4819 case POWER_ENERGY:
4820 case POWER_HAPPINESS:
4821 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4822 break;
4823 case POWER_RUNE:
4824 case POWER_RUNIC_POWER:
4825 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4826 break;
4827 default:
4828 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4829 return 0;
4832 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4833 // Flat mod from caster auras by spell school
4834 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4835 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4836 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4837 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4838 // Apply cost mod by spell
4839 if(Player* modOwner = m_caster->GetSpellModOwner())
4840 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4842 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4843 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4845 // PCT mod from user auras by school
4846 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4847 if (powerCost < 0)
4848 powerCost = 0;
4849 return powerCost;
4852 SpellCastResult Spell::CheckPower()
4854 // item cast not used power
4855 if(m_CastItem)
4856 return SPELL_CAST_OK;
4858 // health as power used - need check health amount
4859 if(m_spellInfo->powerType == POWER_HEALTH)
4861 if(m_caster->GetHealth() <= m_powerCost)
4862 return SPELL_FAILED_CASTER_AURASTATE;
4863 return SPELL_CAST_OK;
4865 // Check valid power type
4866 if( m_spellInfo->powerType >= MAX_POWERS )
4868 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4869 return SPELL_FAILED_UNKNOWN;
4872 SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID);
4873 if(failReason != SPELL_CAST_OK)
4874 return failReason;
4876 // Check power amount
4877 Powers powerType = Powers(m_spellInfo->powerType);
4878 if(m_caster->GetPower(powerType) < m_powerCost)
4879 return SPELL_FAILED_NO_POWER;
4880 else
4881 return SPELL_CAST_OK;
4884 SpellCastResult Spell::CheckItems()
4886 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4887 return SPELL_CAST_OK;
4889 Player* p_caster = (Player*)m_caster;
4891 // cast item checks
4892 if(m_CastItem)
4894 uint32 itemid = m_CastItem->GetEntry();
4895 if( !p_caster->HasItemCount(itemid,1) )
4896 return SPELL_FAILED_ITEM_NOT_READY;
4898 ItemPrototype const *proto = m_CastItem->GetProto();
4899 if(!proto)
4900 return SPELL_FAILED_ITEM_NOT_READY;
4902 for (int i = 0; i<5; i++)
4903 if (proto->Spells[i].SpellCharges)
4904 if(m_CastItem->GetSpellCharges(i)==0)
4905 return SPELL_FAILED_NO_CHARGES_REMAIN;
4907 // consumable cast item checks
4908 if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4910 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4911 SpellCastResult failReason = SPELL_CAST_OK;
4912 for (int i = 0; i < 3; i++)
4914 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4915 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4916 continue;
4918 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4920 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4922 failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4923 continue;
4925 else
4927 failReason = SPELL_CAST_OK;
4928 break;
4932 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4933 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4935 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4937 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4938 continue;
4941 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4942 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4944 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4945 continue;
4947 else
4949 failReason = SPELL_CAST_OK;
4950 break;
4954 if (failReason != SPELL_CAST_OK)
4955 return failReason;
4959 // check target item
4960 if(m_targets.getItemTargetGUID())
4962 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4963 return SPELL_FAILED_BAD_TARGETS;
4965 if(!m_targets.getItemTarget())
4966 return SPELL_FAILED_ITEM_GONE;
4968 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4969 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4971 // if not item target then required item must be equipped
4972 else
4974 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4975 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4978 // check spell focus object
4979 if(m_spellInfo->RequiresSpellFocus)
4981 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4982 Cell cell(p);
4983 cell.data.Part.reserved = ALL_DISTRICT;
4985 GameObject* ok = NULL;
4986 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4987 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(m_caster,ok,go_check);
4989 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4990 CellLock<GridReadGuard> cell_lock(cell, p);
4991 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4993 if(!ok)
4994 return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4996 focusObject = ok; // game object found in range
4999 // check reagents
5000 if (!p_caster->CanNoReagentCast(m_spellInfo))
5002 for(uint32 i=0;i<8;i++)
5004 if(m_spellInfo->Reagent[i] <= 0)
5005 continue;
5007 uint32 itemid = m_spellInfo->Reagent[i];
5008 uint32 itemcount = m_spellInfo->ReagentCount[i];
5010 // if CastItem is also spell reagent
5011 if( m_CastItem && m_CastItem->GetEntry() == itemid )
5013 ItemPrototype const *proto = m_CastItem->GetProto();
5014 if(!proto)
5015 return SPELL_FAILED_ITEM_NOT_READY;
5016 for(int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s)
5018 // CastItem will be used up and does not count as reagent
5019 int32 charges = m_CastItem->GetSpellCharges(s);
5020 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
5022 ++itemcount;
5023 break;
5027 if( !p_caster->HasItemCount(itemid,itemcount) )
5028 return SPELL_FAILED_ITEM_NOT_READY; //0x54
5032 // check totem-item requirements (items presence in inventory)
5033 uint32 totems = 2;
5034 for(int i=0;i<2;++i)
5036 if(m_spellInfo->Totem[i] != 0)
5038 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
5040 totems -= 1;
5041 continue;
5043 }else
5044 totems -= 1;
5046 if(totems != 0)
5047 return SPELL_FAILED_TOTEMS; //0x7C
5049 // Check items for TotemCategory (items presence in inventory)
5050 uint32 TotemCategory = 2;
5051 for(int i=0;i<2;++i)
5053 if(m_spellInfo->TotemCategory[i] != 0)
5055 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
5057 TotemCategory -= 1;
5058 continue;
5061 else
5062 TotemCategory -= 1;
5064 if(TotemCategory != 0)
5065 return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
5067 // special checks for spell effects
5068 for(int i = 0; i < 3; i++)
5070 switch (m_spellInfo->Effect[i])
5072 case SPELL_EFFECT_CREATE_ITEM:
5074 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
5076 ItemPosCountVec dest;
5077 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5078 if (msg != EQUIP_ERR_OK )
5080 p_caster->SendEquipError( msg, NULL, NULL );
5081 return SPELL_FAILED_DONT_REPORT;
5084 break;
5086 case SPELL_EFFECT_ENCHANT_ITEM:
5087 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
5089 Item* targetItem = m_targets.getItemTarget();
5090 if(!targetItem)
5091 return SPELL_FAILED_ITEM_NOT_FOUND;
5093 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5094 return SPELL_FAILED_LOWLEVEL;
5095 // Not allow enchant in trade slot for some enchant type
5096 if( targetItem->GetOwner() != m_caster )
5098 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5099 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5100 if(!pEnchant)
5101 return SPELL_FAILED_ERROR;
5102 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5103 return SPELL_FAILED_NOT_TRADEABLE;
5105 break;
5107 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5109 Item *item = m_targets.getItemTarget();
5110 if(!item)
5111 return SPELL_FAILED_ITEM_NOT_FOUND;
5112 // Not allow enchant in trade slot for some enchant type
5113 if( item->GetOwner() != m_caster )
5115 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5116 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5117 if(!pEnchant)
5118 return SPELL_FAILED_ERROR;
5119 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5120 return SPELL_FAILED_NOT_TRADEABLE;
5122 break;
5124 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5125 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5126 break;
5127 case SPELL_EFFECT_DISENCHANT:
5129 if(!m_targets.getItemTarget())
5130 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5132 // prevent disenchanting in trade slot
5133 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5134 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5136 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5137 if(!itemProto)
5138 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5140 uint32 item_quality = itemProto->Quality;
5141 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5142 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5143 if (item_disenchantskilllevel == uint32(-1))
5144 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5145 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5146 return SPELL_FAILED_LOW_CASTLEVEL;
5147 if(item_quality > 4 || item_quality < 2)
5148 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5149 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5150 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5151 if (!itemProto->DisenchantID)
5152 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5153 break;
5155 case SPELL_EFFECT_PROSPECTING:
5157 if(!m_targets.getItemTarget())
5158 return SPELL_FAILED_CANT_BE_PROSPECTED;
5159 //ensure item is a prospectable ore
5160 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5161 return SPELL_FAILED_CANT_BE_PROSPECTED;
5162 //prevent prospecting in trade slot
5163 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5164 return SPELL_FAILED_CANT_BE_PROSPECTED;
5165 //Check for enough skill in jewelcrafting
5166 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5167 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5168 return SPELL_FAILED_LOW_CASTLEVEL;
5169 //make sure the player has the required ores in inventory
5170 if(m_targets.getItemTarget()->GetCount() < 5)
5171 return SPELL_FAILED_NEED_MORE_ITEMS;
5173 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5174 return SPELL_FAILED_CANT_BE_PROSPECTED;
5176 break;
5178 case SPELL_EFFECT_MILLING:
5180 if(!m_targets.getItemTarget())
5181 return SPELL_FAILED_CANT_BE_MILLED;
5182 //ensure item is a millable herb
5183 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5184 return SPELL_FAILED_CANT_BE_MILLED;
5185 //prevent milling in trade slot
5186 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5187 return SPELL_FAILED_CANT_BE_MILLED;
5188 //Check for enough skill in inscription
5189 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5190 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5191 return SPELL_FAILED_LOW_CASTLEVEL;
5192 //make sure the player has the required herbs in inventory
5193 if(m_targets.getItemTarget()->GetCount() < 5)
5194 return SPELL_FAILED_NEED_MORE_ITEMS;
5196 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5197 return SPELL_FAILED_CANT_BE_MILLED;
5199 break;
5201 case SPELL_EFFECT_WEAPON_DAMAGE:
5202 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5204 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5205 if( m_attackType != RANGED_ATTACK )
5206 break;
5207 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5208 if(!pItem || pItem->IsBroken())
5209 return SPELL_FAILED_EQUIPPED_ITEM;
5211 switch(pItem->GetProto()->SubClass)
5213 case ITEM_SUBCLASS_WEAPON_THROWN:
5215 uint32 ammo = pItem->GetEntry();
5216 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5217 return SPELL_FAILED_NO_AMMO;
5218 }; break;
5219 case ITEM_SUBCLASS_WEAPON_GUN:
5220 case ITEM_SUBCLASS_WEAPON_BOW:
5221 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5223 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5224 if(!ammo)
5226 // Requires No Ammo
5227 if(m_caster->GetDummyAura(46699))
5228 break; // skip other checks
5230 return SPELL_FAILED_NO_AMMO;
5233 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5234 if(!ammoProto)
5235 return SPELL_FAILED_NO_AMMO;
5237 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5238 return SPELL_FAILED_NO_AMMO;
5240 // check ammo ws. weapon compatibility
5241 switch(pItem->GetProto()->SubClass)
5243 case ITEM_SUBCLASS_WEAPON_BOW:
5244 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5245 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5246 return SPELL_FAILED_NO_AMMO;
5247 break;
5248 case ITEM_SUBCLASS_WEAPON_GUN:
5249 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5250 return SPELL_FAILED_NO_AMMO;
5251 break;
5252 default:
5253 return SPELL_FAILED_NO_AMMO;
5256 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5257 return SPELL_FAILED_NO_AMMO;
5258 }; break;
5259 case ITEM_SUBCLASS_WEAPON_WAND:
5260 default:
5261 break;
5263 break;
5265 default:break;
5269 return SPELL_CAST_OK;
5272 void Spell::Delayed()
5274 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5275 return;
5277 if (m_spellState == SPELL_STATE_DELAYED)
5278 return; // spell is active and can't be time-backed
5280 if(isDelayableNoMore()) // Spells may only be delayed twice
5281 return;
5283 // spells not loosing casting time ( slam, dynamites, bombs.. )
5284 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5285 return;
5287 //check pushback reduce
5288 int32 delaytime = 500; // spellcasting delay is normally 500ms
5289 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5290 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5291 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5292 if(delayReduce >= 100)
5293 return;
5295 delaytime = delaytime * (100 - delayReduce) / 100;
5297 if(int32(m_timer) + delaytime > m_casttime)
5299 delaytime = m_casttime - m_timer;
5300 m_timer = m_casttime;
5302 else
5303 m_timer += delaytime;
5305 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5307 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5308 data.append(m_caster->GetPackGUID());
5309 data << uint32(delaytime);
5311 m_caster->SendMessageToSet(&data,true);
5314 void Spell::DelayedChannel()
5316 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5317 return;
5319 if(isDelayableNoMore()) // Spells may only be delayed twice
5320 return;
5322 //check pushback reduce
5323 int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
5324 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5325 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,delayReduce, this);
5326 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5327 if(delayReduce >= 100)
5328 return;
5330 delaytime = delaytime * (100 - delayReduce) / 100;
5332 if(int32(m_timer) < delaytime)
5334 delaytime = m_timer;
5335 m_timer = 0;
5337 else
5338 m_timer -= delaytime;
5340 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5342 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5344 if ((*ihit).missCondition == SPELL_MISS_NONE)
5346 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5347 if (unit)
5349 for (int j=0;j<3;j++)
5350 if( ihit->effectMask & (1<<j) )
5351 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5357 for(int j = 0; j < 3; j++)
5359 // partially interrupt persistent area auras
5360 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5361 if(dynObj)
5362 dynObj->Delay(delaytime);
5365 SendChannelUpdate(m_timer);
5368 void Spell::UpdatePointers()
5370 if(m_originalCasterGUID==m_caster->GetGUID())
5371 m_originalCaster = m_caster;
5372 else
5374 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5375 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5378 m_targets.Update(m_caster);
5381 bool Spell::IsAffectedByAura(Aura *aura)
5383 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5386 bool Spell::CheckTargetCreatureType(Unit* target) const
5388 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5390 // Curse of Doom : not find another way to fix spell target check :/
5391 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5393 // not allow cast at player
5394 if(target->GetTypeId()==TYPEID_PLAYER)
5395 return false;
5397 spellCreatureTargetMask = 0x7FF;
5400 // Dismiss Pet and Taming Lesson skipped
5401 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5402 spellCreatureTargetMask = 0;
5404 if (spellCreatureTargetMask)
5406 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5408 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5410 return true;
5413 CurrentSpellTypes Spell::GetCurrentContainer()
5415 if (IsNextMeleeSwingSpell())
5416 return(CURRENT_MELEE_SPELL);
5417 else if (IsAutoRepeat())
5418 return(CURRENT_AUTOREPEAT_SPELL);
5419 else if (IsChanneledSpell(m_spellInfo))
5420 return(CURRENT_CHANNELED_SPELL);
5421 else
5422 return(CURRENT_GENERIC_SPELL);
5425 bool Spell::CheckTarget( Unit* target, uint32 eff )
5427 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5428 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5430 if (!CheckTargetCreatureType(target))
5431 return false;
5434 // Check Aura spell req (need for AoE spells)
5435 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5436 return false;
5437 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5438 return false;
5440 // Check targets for not_selectable unit flag and remove
5441 // A player can cast spells on his pet (or other controlled unit) though in any state
5442 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5444 // any unattackable target skipped
5445 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5446 return false;
5448 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5449 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5450 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5451 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5452 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5453 return false;
5456 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5457 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5459 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5460 return false;
5462 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5463 return false;
5466 //Check targets for LOS visibility (except spells without range limitations )
5467 switch(m_spellInfo->Effect[eff])
5469 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5470 break;
5471 case SPELL_EFFECT_DUMMY:
5472 if(m_spellInfo->Id!=20577) // Cannibalize
5473 break;
5474 //fall through
5475 case SPELL_EFFECT_RESURRECT_NEW:
5476 // player far away, maybe his corpse near?
5477 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5479 if(!m_targets.getCorpseTargetGUID())
5480 return false;
5482 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5483 if(!corpse)
5484 return false;
5486 if(target->GetGUID()!=corpse->GetOwnerGUID())
5487 return false;
5489 if(!corpse->IsWithinLOSInMap(m_caster))
5490 return false;
5493 // all ok by some way or another, skip normal check
5494 break;
5495 default: // normal case
5496 // Get GO cast coordinates if original caster -> GO
5497 WorldObject *caster = NULL;
5498 if (m_originalCasterGUID)
5499 caster = ObjectAccessor::GetGameObject(*m_caster, m_originalCasterGUID);
5500 if (!caster)
5501 caster = m_caster;
5502 if(target!=m_caster && !target->IsWithinLOSInMap(caster))
5503 return false;
5504 break;
5507 return true;
5510 Unit* Spell::SelectMagnetTarget()
5512 Unit* target = m_targets.getUnitTarget();
5514 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5516 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5517 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5519 if(Unit* magnet = (*itr)->GetCaster())
5521 if(magnet->IsWithinLOSInMap(m_caster))
5523 target = magnet;
5524 m_targets.setUnitTarget(target);
5525 break;
5531 return target;
5534 bool Spell::IsNeedSendToClient() const
5536 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5537 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5540 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5542 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5543 if(itr->effectMask & (1<<effect))
5544 return true;
5546 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5547 if(itr->effectMask & (1<<effect))
5548 return true;
5550 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5551 if(itr->effectMask & (1<<effect))
5552 return true;
5554 return false;
5557 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5559 m_Spell = spell;
5562 SpellEvent::~SpellEvent()
5564 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5565 m_Spell->cancel();
5567 if (m_Spell->IsDeletable())
5569 delete m_Spell;
5571 else
5573 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5574 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5578 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5580 // update spell if it is not finished
5581 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5582 m_Spell->update(p_time);
5584 // check spell state to process
5585 switch (m_Spell->getState())
5587 case SPELL_STATE_FINISHED:
5589 // spell was finished, check deletable state
5590 if (m_Spell->IsDeletable())
5592 // check, if we do have unfinished triggered spells
5594 return(true); // spell is deletable, finish event
5596 // event will be re-added automatically at the end of routine)
5597 } break;
5599 case SPELL_STATE_CASTING:
5601 // this spell is in channeled state, process it on the next update
5602 // event will be re-added automatically at the end of routine)
5603 } break;
5605 case SPELL_STATE_DELAYED:
5607 // first, check, if we have just started
5608 if (m_Spell->GetDelayStart() != 0)
5610 // no, we aren't, do the typical update
5611 // check, if we have channeled spell on our hands
5612 if (IsChanneledSpell(m_Spell->m_spellInfo))
5614 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5615 // check, if we have casting anything else except this channeled spell and autorepeat
5616 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5618 // another non-melee non-delayed spell is casted now, abort
5619 m_Spell->cancel();
5621 else
5623 // do the action (pass spell to channeling state)
5624 m_Spell->handle_immediate();
5626 // event will be re-added automatically at the end of routine)
5628 else
5630 // run the spell handler and think about what we can do next
5631 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5632 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5633 if (n_offset)
5635 // re-add us to the queue
5636 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5637 return(false); // event not complete
5639 // event complete
5640 // finish update event will be re-added automatically at the end of routine)
5643 else
5645 // delaying had just started, record the moment
5646 m_Spell->SetDelayStart(e_time);
5647 // re-plan the event for the delay moment
5648 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5649 return(false); // event not complete
5651 } break;
5653 default:
5655 // all other states
5656 // event will be re-added automatically at the end of routine)
5657 } break;
5660 // spell processing not complete, plan event on the next update interval
5661 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5662 return(false); // event not complete
5665 void SpellEvent::Abort(uint64 /*e_time*/)
5667 // oops, the spell we try to do is aborted
5668 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5669 m_Spell->cancel();
5672 bool SpellEvent::IsDeletable() const
5674 return m_Spell->IsDeletable();
5677 SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
5679 if(!lockId) // possible case for GO and maybe for items.
5680 return SPELL_CAST_OK;
5682 // Get LockInfo
5683 LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
5685 if (!lockInfo)
5686 return SPELL_FAILED_BAD_TARGETS;
5688 bool reqKey = false; // some locks not have reqs
5690 for(int j = 0; j < 8; ++j)
5692 switch(lockInfo->Type[j])
5694 // check key item (many fit cases can be)
5695 case LOCK_KEY_ITEM:
5696 if(lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[j])
5697 return SPELL_CAST_OK;
5698 reqKey = true;
5699 break;
5700 // check key skill (only single first fit case can be)
5701 case LOCK_KEY_SKILL:
5703 reqKey = true;
5705 // wrong locktype, skip
5706 if(uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j])
5707 continue;
5709 skillId = SkillByLockType(LockType(lockInfo->Index[j]));
5711 if ( skillId != SKILL_NONE )
5713 // skill bonus provided by casting spell (mostly item spells)
5714 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
5715 uint32 spellSkillBonus = uint32(m_currentBasePoints[effIndex]+1);
5716 reqSkillValue = lockInfo->Skill[j];
5718 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
5719 skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
5720 0 : ((Player*)m_caster)->GetSkillValue(skillId);
5722 skillValue += spellSkillBonus;
5724 if (skillValue < reqSkillValue)
5725 return SPELL_FAILED_LOW_CASTLEVEL;
5728 return SPELL_CAST_OK;
5733 if(reqKey)
5734 return SPELL_FAILED_BAD_TARGETS;
5736 return SPELL_CAST_OK;