Initial Patch of Auction House bot rev. 135
[auctionmangos.git] / src / game / Spell.cpp
blobb42c59eb928b5f5667ac8f3f588b6eb001af343e
1 /*
2 * Copyright (C) 2005-2008 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 "SpellAuras.h"
37 #include "Group.h"
38 #include "UpdateData.h"
39 #include "MapManager.h"
40 #include "ObjectAccessor.h"
41 #include "CellImpl.h"
42 #include "Policies/SingletonImp.h"
43 #include "SharedDefines.h"
44 #include "Tools.h"
45 #include "LootMgr.h"
46 #include "VMapFactory.h"
47 #include "BattleGround.h"
48 #include "Util.h"
50 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
52 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
54 bool IsQuestTameSpell(uint32 spellId)
56 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
57 if (!spellproto) return false;
59 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
60 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
63 SpellCastTargets::SpellCastTargets()
65 m_unitTarget = NULL;
66 m_itemTarget = NULL;
67 m_GOTarget = NULL;
69 m_unitTargetGUID = 0;
70 m_GOTargetGUID = 0;
71 m_CorpseTargetGUID = 0;
72 m_itemTargetGUID = 0;
73 m_itemTargetEntry = 0;
75 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
76 m_strTarget = "";
77 m_targetMask = 0;
80 SpellCastTargets::~SpellCastTargets()
84 void SpellCastTargets::setUnitTarget(Unit *target)
86 if (!target)
87 return;
89 m_destX = target->GetPositionX();
90 m_destY = target->GetPositionY();
91 m_destZ = target->GetPositionZ();
92 m_unitTarget = target;
93 m_unitTargetGUID = target->GetGUID();
94 m_targetMask |= TARGET_FLAG_UNIT;
97 void SpellCastTargets::setDestination(float x, float y, float z)
99 m_destX = x;
100 m_destY = y;
101 m_destZ = z;
102 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
105 void SpellCastTargets::setGOTarget(GameObject *target)
107 m_GOTarget = target;
108 m_GOTargetGUID = target->GetGUID();
109 // m_targetMask |= TARGET_FLAG_OBJECT;
112 void SpellCastTargets::setItemTarget(Item* item)
114 if(!item)
115 return;
117 m_itemTarget = item;
118 m_itemTargetGUID = item->GetGUID();
119 m_itemTargetEntry = item->GetEntry();
120 m_targetMask |= TARGET_FLAG_ITEM;
123 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
125 m_CorpseTargetGUID = corpse->GetGUID();
128 void SpellCastTargets::Update(Unit* caster)
130 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
131 m_unitTarget = m_unitTargetGUID ?
132 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
133 NULL;
135 m_itemTarget = NULL;
136 if(caster->GetTypeId()==TYPEID_PLAYER)
138 if(m_targetMask & TARGET_FLAG_ITEM)
139 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
140 else
142 Player* pTrader = ((Player*)caster)->GetTrader();
143 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
144 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
146 if(m_itemTarget)
147 m_itemTargetEntry = m_itemTarget->GetEntry();
151 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
153 if(data->rpos()+4 > data->size())
154 return false;
156 *data >> m_targetMask;
158 if(m_targetMask == TARGET_FLAG_SELF)
160 m_destX = caster->GetPositionX();
161 m_destY = caster->GetPositionY();
162 m_destZ = caster->GetPositionZ();
163 m_unitTarget = caster;
164 m_unitTargetGUID = caster->GetGUID();
165 return true;
168 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
169 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
170 if(!readGUID(*data, m_unitTargetGUID))
171 return false;
173 if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
174 if(!readGUID(*data, m_GOTargetGUID))
175 return false;
177 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
178 if(!readGUID(*data, m_itemTargetGUID))
179 return false;
181 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
183 if(data->rpos()+4+4+4 > data->size())
184 return false;
186 *data >> m_srcX >> m_srcY >> m_srcZ;
187 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
188 return false;
191 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
193 if(data->rpos()+4+4+4 > data->size())
194 return false;
196 *data >> m_destX >> m_destY >> m_destZ;
197 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
198 return false;
201 if( m_targetMask & TARGET_FLAG_STRING )
203 if(data->rpos()+1 > data->size())
204 return false;
206 *data >> m_strTarget;
209 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
210 if(!readGUID(*data, m_CorpseTargetGUID))
211 return false;
213 // find real units/GOs
214 Update(caster);
215 return true;
218 void SpellCastTargets::write ( WorldPacket * data )
220 *data << uint32(m_targetMask);
222 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
224 if(m_targetMask & TARGET_FLAG_UNIT)
226 if(m_unitTarget)
227 data->append(m_unitTarget->GetPackGUID());
228 else
229 *data << uint8(0);
231 else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
233 if(m_GOTarget)
234 data->append(m_GOTarget->GetPackGUID());
235 else
236 *data << uint8(0);
238 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
239 data->appendPackGUID(m_CorpseTargetGUID);
240 else
241 *data << uint8(0);
244 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
246 if(m_itemTarget)
247 data->append(m_itemTarget->GetPackGUID());
248 else
249 *data << uint8(0);
252 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
253 *data << m_srcX << m_srcY << m_srcZ;
255 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
256 *data << m_destX << m_destY << m_destZ;
258 if( m_targetMask & TARGET_FLAG_STRING )
259 *data << m_strTarget;
262 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
264 ASSERT( Caster != NULL && info != NULL );
265 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
267 m_spellInfo = info;
268 m_caster = Caster;
269 m_selfContainer = NULL;
270 m_triggeringContainer = triggeringContainer;
271 m_referencedFromCurrentSpell = false;
272 m_executedCurrently = false;
273 m_delayAtDamageCount = 0;
275 m_applyMultiplierMask = 0;
277 // Get data for type of attack
278 switch (m_spellInfo->DmgClass)
280 case SPELL_DAMAGE_CLASS_MELEE:
281 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
282 m_attackType = OFF_ATTACK;
283 else
284 m_attackType = BASE_ATTACK;
285 break;
286 case SPELL_DAMAGE_CLASS_RANGED:
287 m_attackType = RANGED_ATTACK;
288 break;
289 default:
290 // Wands
291 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_WAND)
292 m_attackType = RANGED_ATTACK;
293 else
294 m_attackType = BASE_ATTACK;
295 break;
298 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
300 if(m_attackType == RANGED_ATTACK)
302 // wand case
303 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
305 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
306 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
310 if(originalCasterGUID)
311 m_originalCasterGUID = originalCasterGUID;
312 else
313 m_originalCasterGUID = m_caster->GetGUID();
315 if(m_originalCasterGUID==m_caster->GetGUID())
316 m_originalCaster = m_caster;
317 else
319 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
320 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
323 for(int i=0; i <3; ++i)
324 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
326 m_spellState = SPELL_STATE_NULL;
328 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
329 m_TriggerSpells.clear();
330 m_IsTriggeredSpell = triggered;
331 //m_AreaAura = false;
332 m_CastItem = NULL;
334 unitTarget = NULL;
335 itemTarget = NULL;
336 gameObjTarget = NULL;
337 focusObject = NULL;
338 m_cast_count = 0;
339 m_triggeredByAuraSpell = NULL;
341 //Auto Shot & Shoot
342 if( m_spellInfo->AttributesEx2 == 0x000020 && !triggered )
343 m_autoRepeat = true;
344 else
345 m_autoRepeat = false;
347 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
348 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
349 m_timer = 0; // will set to castime in prepare
351 m_needAliveTargetMask = 0;
353 // determine reflection
354 m_canReflect = false;
356 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
358 for(int j=0;j<3;j++)
360 if (m_spellInfo->Effect[j]==0)
361 continue;
363 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
364 m_canReflect = true;
365 else
366 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
368 if(m_canReflect)
369 continue;
370 else
371 break;
375 CleanupTargetList();
378 Spell::~Spell()
382 void Spell::FillTargetMap()
384 // TODO: ADD the correct target FILLS!!!!!!
386 for(uint32 i=0;i<3;i++)
388 // not call for empty effect.
389 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
390 if(m_spellInfo->Effect[i]==0)
391 continue;
393 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
394 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
395 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
396 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
397 continue;
399 // TODO: find a way so this is not needed?
400 // for area auras always add caster as target (needed for totems for example)
401 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
402 AddUnitTarget(m_caster, i);
404 std::list<Unit*> tmpUnitMap;
406 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
407 // but need it support in some know cases
408 switch(m_spellInfo->EffectImplicitTargetA[i])
410 case TARGET_ALL_AROUND_CASTER:
411 if( m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_PARTY ||
412 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER ||
413 m_spellInfo->EffectImplicitTargetB[i]==TARGET_RANDOM_RAID_MEMBER )
415 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
417 // Note: this hack with search required until GO casting not implemented
418 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
419 // currently each enemy selected explicitly and self cast damage
420 else if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
422 if(m_targets.getUnitTarget())
423 tmpUnitMap.push_back(m_targets.getUnitTarget());
425 else
427 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
428 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
430 break;
431 case TARGET_TABLE_X_Y_Z_COORDINATES:
432 // Only if target A, for target B (used in teleports) dest select in effect
433 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
434 break;
435 default:
436 switch(m_spellInfo->EffectImplicitTargetB[i])
438 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
439 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
440 break;
441 default:
442 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
443 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
444 break;
446 break;
449 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
450 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
452 // add here custom effects that need default target.
453 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
454 switch(m_spellInfo->Effect[i])
456 case SPELL_EFFECT_DUMMY:
458 switch(m_spellInfo->Id)
460 case 20577: // Cannibalize
462 // non-standard target selection
463 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
464 float max_range = GetSpellMaxRange(srange);
466 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
467 Cell cell(p);
468 cell.data.Part.reserved = ALL_DISTRICT;
469 cell.SetNoCreate();
471 WorldObject* result = NULL;
473 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
474 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
476 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
477 CellLock<GridReadGuard> cell_lock(cell, p);
478 cell_lock->Visit(cell_lock, grid_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
480 if(!result)
482 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
483 cell_lock->Visit(cell_lock, world_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
486 if(result)
488 switch(result->GetTypeId())
490 case TYPEID_UNIT:
491 case TYPEID_PLAYER:
492 tmpUnitMap.push_back((Unit*)result);
493 break;
494 case TYPEID_CORPSE:
495 m_targets.setCorpseTarget((Corpse*)result);
496 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
497 tmpUnitMap.push_back(owner);
498 break;
501 else
503 // clear cooldown at fail
504 if(m_caster->GetTypeId()==TYPEID_PLAYER)
506 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
508 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
509 data << uint32(m_spellInfo->Id);
510 data << uint64(m_caster->GetGUID());
511 ((Player*)m_caster)->GetSession()->SendPacket(&data);
514 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
515 finish(false);
517 break;
519 default:
520 if(m_targets.getUnitTarget())
521 tmpUnitMap.push_back(m_targets.getUnitTarget());
522 break;
524 break;
526 case SPELL_EFFECT_RESURRECT:
527 case SPELL_EFFECT_PARRY:
528 case SPELL_EFFECT_BLOCK:
529 case SPELL_EFFECT_CREATE_ITEM:
530 case SPELL_EFFECT_TRIGGER_SPELL:
531 case SPELL_EFFECT_TRIGGER_MISSILE:
532 case SPELL_EFFECT_LEARN_SPELL:
533 case SPELL_EFFECT_SKILL_STEP:
534 case SPELL_EFFECT_PROFICIENCY:
535 case SPELL_EFFECT_SUMMON_POSSESSED:
536 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
537 case SPELL_EFFECT_SELF_RESURRECT:
538 case SPELL_EFFECT_REPUTATION:
539 if(m_targets.getUnitTarget())
540 tmpUnitMap.push_back(m_targets.getUnitTarget());
541 break;
542 case SPELL_EFFECT_SUMMON_PLAYER:
543 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
545 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
546 if(target)
547 tmpUnitMap.push_back(target);
549 break;
550 case SPELL_EFFECT_RESURRECT_NEW:
551 if(m_targets.getUnitTarget())
552 tmpUnitMap.push_back(m_targets.getUnitTarget());
553 if(m_targets.getCorpseTargetGUID())
555 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
556 if(corpse)
558 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
559 if(owner)
560 tmpUnitMap.push_back(owner);
563 break;
564 case SPELL_EFFECT_SUMMON:
565 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
567 if(m_targets.getUnitTarget())
568 tmpUnitMap.push_back(m_targets.getUnitTarget());
570 else
571 tmpUnitMap.push_back(m_caster);
572 break;
573 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
574 case SPELL_EFFECT_SUMMON_WILD:
575 case SPELL_EFFECT_SUMMON_GUARDIAN:
576 case SPELL_EFFECT_TRANS_DOOR:
577 case SPELL_EFFECT_ADD_FARSIGHT:
578 case SPELL_EFFECT_STUCK:
579 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
580 case SPELL_EFFECT_SUMMON_DEMON:
581 case SPELL_EFFECT_SKILL:
582 tmpUnitMap.push_back(m_caster);
583 break;
584 case SPELL_EFFECT_LEARN_PET_SPELL:
585 if(Pet* pet = m_caster->GetPet())
586 tmpUnitMap.push_back(pet);
587 break;
588 case SPELL_EFFECT_ENCHANT_ITEM:
589 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
590 case SPELL_EFFECT_DISENCHANT:
591 case SPELL_EFFECT_FEED_PET:
592 case SPELL_EFFECT_PROSPECTING:
593 if(m_targets.getItemTarget())
594 AddItemTarget(m_targets.getItemTarget(), i);
595 break;
596 case SPELL_EFFECT_APPLY_AURA:
597 switch(m_spellInfo->EffectApplyAuraName[i])
599 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)
600 case SPELL_AURA_ADD_PCT_MODIFIER:
601 tmpUnitMap.push_back(m_caster);
602 break;
603 default: // apply to target in other case
604 if(m_targets.getUnitTarget())
605 tmpUnitMap.push_back(m_targets.getUnitTarget());
606 break;
608 break;
609 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
610 // AreaAura
611 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
612 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
613 break;
614 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
615 if(m_targets.getUnitTarget())
617 tmpUnitMap.push_back(m_targets.getUnitTarget());
619 else if (m_targets.getCorpseTargetGUID())
621 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
622 if(corpse)
624 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
625 if(owner)
626 tmpUnitMap.push_back(owner);
629 break;
630 default:
631 break;
634 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
635 m_needAliveTargetMask |= (1<<i);
637 if(m_caster->GetTypeId() == TYPEID_PLAYER)
639 Player *me = (Player*)m_caster;
640 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); itr++)
642 Unit *owner = (*itr)->GetOwner();
643 Unit *u = owner ? owner : (*itr);
644 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
646 me->UpdatePvP(true);
647 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
648 break;
653 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
655 if (!CheckTarget (*itr, i))
657 itr = tmpUnitMap.erase(itr);
658 continue;
660 else
661 ++itr;
664 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
665 AddUnitTarget((*iunit), i);
669 void Spell::CleanupTargetList()
671 m_UniqueTargetInfo.clear();
672 m_UniqueGOTargetInfo.clear();
673 m_UniqueItemInfo.clear();
674 m_countOfHit = 0;
675 m_countOfMiss = 0;
676 m_delayMoment = 0;
679 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
681 if( m_spellInfo->Effect[effIndex]==0 )
682 return;
684 uint64 targetGUID = pVictim->GetGUID();
686 // Lookup target in already in list
687 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
689 if (targetGUID == ihit->targetGUID) // Found in list
691 ihit->effectMask |= 1<<effIndex; // Add only effect mask
692 return;
696 // This is new target calculate data for him
698 // Get spell hit result on target
699 TargetInfo target;
700 target.targetGUID = targetGUID; // Store target GUID
701 target.effectMask = 1<<effIndex; // Store index of effect
702 target.processed = false; // Effects not apply on target
704 // Calculate hit result
705 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
706 if (target.missCondition == SPELL_MISS_NONE)
707 ++m_countOfHit;
708 else
709 ++m_countOfMiss;
711 // Spell have speed - need calculate incoming time
712 if (m_spellInfo->speed > 0.0f)
714 // calculate spell incoming interval
715 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
716 if (dist < 5.0f) dist = 5.0f;
717 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
719 // Calculate minimum incoming time
720 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
721 m_delayMoment = target.timeDelay;
723 else
724 target.timeDelay = 0LL;
726 // If target reflect spell back to caster
727 if (target.missCondition==SPELL_MISS_REFLECT)
729 // Calculate reflected spell result on caster
730 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
732 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
733 target.reflectResult = SPELL_MISS_PARRY;
735 // Increase time interval for reflected spells by 1.5
736 target.timeDelay+=target.timeDelay>>1;
738 else
739 target.reflectResult = SPELL_MISS_NONE;
741 // Add target to list
742 m_UniqueTargetInfo.push_back(target);
745 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
747 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
748 if (unit)
749 AddUnitTarget(unit, effIndex);
752 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
754 if( m_spellInfo->Effect[effIndex]==0 )
755 return;
757 uint64 targetGUID = pVictim->GetGUID();
759 // Lookup target in already in list
760 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
762 if (targetGUID == ihit->targetGUID) // Found in list
764 ihit->effectMask |= 1<<effIndex; // Add only effect mask
765 return;
769 // This is new target calculate data for him
771 GOTargetInfo target;
772 target.targetGUID = targetGUID;
773 target.effectMask = 1<<effIndex;
774 target.processed = false; // Effects not apply on target
776 // Spell have speed - need calculate incoming time
777 if (m_spellInfo->speed > 0.0f)
779 // calculate spell incoming interval
780 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
781 if (dist < 5.0f) dist = 5.0f;
782 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
783 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
784 m_delayMoment = target.timeDelay;
786 else
787 target.timeDelay = 0LL;
789 ++m_countOfHit;
791 // Add target to list
792 m_UniqueGOTargetInfo.push_back(target);
795 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
797 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
798 if (go)
799 AddGOTarget(go, effIndex);
802 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
804 if( m_spellInfo->Effect[effIndex]==0 )
805 return;
807 // Lookup target in already in list
808 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
810 if (pitem == ihit->item) // Found in list
812 ihit->effectMask |= 1<<effIndex; // Add only effect mask
813 return;
817 // This is new target add data
819 ItemTargetInfo target;
820 target.item = pitem;
821 target.effectMask = 1<<effIndex;
822 m_UniqueItemInfo.push_back(target);
825 void Spell::doTriggers(SpellMissInfo missInfo, uint32 damage, SpellSchoolMask damageSchoolMask, uint32 block, uint32 absorb, bool crit)
827 // Do triggers depends from hit result (triggers on hit do in effects)
828 // Set aura states depends from hit result
829 if (missInfo!=SPELL_MISS_NONE)
831 // Miss/dodge/parry/block only for melee based spells
832 // Resist only for magic based spells
833 switch (missInfo)
835 case SPELL_MISS_MISS:
836 if(m_caster->GetTypeId()== TYPEID_PLAYER)
837 ((Player*)m_caster)->UpdateWeaponSkill(BASE_ATTACK);
839 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_MISS, m_spellInfo, m_IsTriggeredSpell);
840 break;
841 case SPELL_MISS_RESIST:
842 m_caster->ProcDamageAndSpell(unitTarget, PROC_FLAG_TARGET_RESISTS, PROC_FLAG_RESIST_SPELL, 0, damageSchoolMask, m_spellInfo, m_IsTriggeredSpell);
843 break;
844 case SPELL_MISS_DODGE:
845 if(unitTarget->GetTypeId() == TYPEID_PLAYER)
846 ((Player*)unitTarget)->UpdateDefense();
848 // Overpower
849 if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARRIOR)
851 ((Player*) m_caster)->AddComboPoints(unitTarget, 1);
852 m_caster->StartReactiveTimer( REACTIVE_OVERPOWER );
855 // Riposte
856 if (unitTarget->getClass() != CLASS_ROGUE)
858 unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
859 unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
862 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_DODGE, m_spellInfo, m_IsTriggeredSpell);
863 break;
864 case SPELL_MISS_PARRY:
865 // Update victim defense ?
866 if(unitTarget->GetTypeId() == TYPEID_PLAYER)
867 ((Player*)unitTarget)->UpdateDefense();
868 // Mongoose bite - set only Counterattack here
869 if (unitTarget->getClass() == CLASS_HUNTER)
871 unitTarget->ModifyAuraState(AURA_STATE_HUNTER_PARRY,true);
872 unitTarget->StartReactiveTimer( REACTIVE_HUNTER_PARRY );
874 else
876 unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
877 unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
879 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_PARRY, m_spellInfo, m_IsTriggeredSpell);
880 break;
881 case SPELL_MISS_BLOCK:
882 unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
883 unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
885 m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_BLOCK, m_spellInfo, m_IsTriggeredSpell);
886 break;
887 // Trigger from this events not supported
888 case SPELL_MISS_EVADE:
889 case SPELL_MISS_IMMUNE:
890 case SPELL_MISS_IMMUNE2:
891 case SPELL_MISS_DEFLECT:
892 case SPELL_MISS_ABSORB:
893 // Trigger from reflects need do after get reflect result
894 case SPELL_MISS_REFLECT:
895 break;
896 default:
897 break;
902 void Spell::DoAllEffectOnTarget(TargetInfo *target)
904 if (target->processed) // Check target
905 return;
906 target->processed = true; // Target checked in apply effects procedure
908 // Get mask of effects for target
909 uint32 mask = target->effectMask;
910 if (mask == 0) // No effects
911 return;
913 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
914 if (!unit)
915 return;
917 SpellMissInfo missInfo = target->missCondition;
918 // Need init unitTarget by default unit (can changed in code on reflect)
919 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
920 unitTarget = unit;
922 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
923 DoSpellHitOnUnit(unit, mask);
924 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
926 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
927 DoSpellHitOnUnit(m_caster, mask);
930 // Do triggers only on miss/resist/parry/dodge
931 if (missInfo!=SPELL_MISS_NONE)
932 doTriggers(missInfo);
934 // Call scripted function for AI if this spell is casted upon a creature (except pets)
935 if(IS_CREATURE_GUID(target->targetGUID))
937 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
938 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
939 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
940 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
942 if(((Creature*)unit)->AI())
943 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
947 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
949 if(!unit || !effectMask)
950 return;
952 // Recheck immune (only for delayed spells)
953 if( m_spellInfo->speed && (
954 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo),true) ||
955 unit->IsImmunedToSpell(m_spellInfo,true) ))
957 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
958 return;
961 if( m_caster != unit )
963 if( !m_caster->IsFriendlyTo(unit) )
965 // for delayed spells ignore not visible explicit target
966 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
968 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
969 return;
972 // exclude Arcane Missiles Dummy Aura aura for now (attack on hit)
973 // TODO: find way to not need this?
974 if(!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE &&
975 m_spellInfo->SpellFamilyFlags & 0x800LL))
977 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
979 if( !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
981 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
982 unit->SetStandState(PLAYER_STATE_NONE);
984 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
985 ((Creature*)unit)->AI()->AttackStart(m_caster);
987 unit->SetInCombatWith(m_caster);
988 m_caster->SetInCombatWith(unit);
990 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
992 m_caster->SetContestedPvP(attackedPlayer);
994 unit->AddThreat(m_caster, 0.0f);
998 else
1000 // for delayed spells ignore negative spells (after duel end) for friendly targets
1001 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1003 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1004 return;
1007 // assisting case, healing and resurrection
1008 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1009 m_caster->SetContestedPvP();
1010 if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
1012 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1013 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1018 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1019 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1020 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1021 // Increase Diminishing on unit, current informations for actually casts will use values above
1022 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1023 unit->IncrDiminishing(m_diminishGroup);
1025 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1027 if (effectMask & (1<<effectNumber))
1029 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1030 if ( m_applyMultiplierMask & (1 << effectNumber) )
1032 // Get multiplier
1033 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1034 // Apply multiplier mods
1035 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1036 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1037 m_damageMultipliers[effectNumber] *= multiplier;
1043 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1045 if (target->processed) // Check target
1046 return;
1047 target->processed = true; // Target checked in apply effects procedure
1049 uint32 effectMask = target->effectMask;
1050 if(!effectMask)
1051 return;
1053 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1054 if(!go)
1055 return;
1057 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1058 if (effectMask & (1<<effectNumber))
1059 HandleEffects(NULL,NULL,go,effectNumber);
1061 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1062 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1063 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1064 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1067 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1069 uint32 effectMask = target->effectMask;
1070 if(!target->item || !effectMask)
1071 return;
1073 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1074 if (effectMask & (1<<effectNumber))
1075 HandleEffects(NULL, target->item, NULL, effectNumber);
1078 bool Spell::IsAliveUnitPresentInTargetList()
1080 // Not need check return true
1081 if (m_needAliveTargetMask == 0)
1082 return true;
1084 uint8 needAliveTargetMask = m_needAliveTargetMask;
1086 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1088 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1090 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1092 if (unit && unit->isAlive())
1093 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1097 // is all effects from m_needAliveTargetMask have alive targets
1098 return needAliveTargetMask==0;
1101 // Helper for Chain Healing
1102 // Spell target first
1103 // Raidmates then descending by injury suffered (MaxHealth - Health)
1104 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1105 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1107 const Unit* MainTarget;
1108 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1109 // functor for operator ">"
1110 bool operator()(Unit const* _Left, Unit const* _Right) const
1112 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1114 int32 ChainHealingHash(Unit const* Target) const
1116 if (Target == MainTarget)
1117 return 0;
1118 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1119 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1121 if (Target->GetHealth() == Target->GetMaxHealth())
1122 return 40000;
1123 else
1124 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1126 else
1127 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1131 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1133 public:
1134 const Unit* MainTarget;
1135 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1137 bool operator()(const Unit* Target)
1139 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1143 // Helper for targets nearest to the spell target
1144 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1145 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1147 const Unit* MainTarget;
1148 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1149 // functor for operator ">"
1150 bool operator()(const Unit* _Left, const Unit* _Right) const
1152 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1156 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1158 float radius;
1159 if (m_spellInfo->EffectRadiusIndex[i])
1160 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1161 else
1162 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1164 if(m_originalCaster)
1165 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1166 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1168 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1169 if(m_originalCaster)
1170 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1171 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1173 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1174 switch(cur)
1176 case TARGET_TOTEM_EARTH:
1177 case TARGET_TOTEM_WATER:
1178 case TARGET_TOTEM_AIR:
1179 case TARGET_TOTEM_FIRE:
1180 case TARGET_SELF:
1181 case TARGET_SELF2:
1182 case TARGET_DYNAMIC_OBJECT:
1183 case TARGET_AREAEFFECT_CUSTOM:
1184 case TARGET_AREAEFFECT_CUSTOM_2:
1185 case TARGET_SUMMON:
1187 TagUnitMap.push_back(m_caster);
1188 break;
1190 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1192 m_targets.m_targetMask = 0;
1193 unMaxTargets = EffectChainTarget;
1194 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1196 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1197 Cell cell(p);
1198 cell.data.Part.reserved = ALL_DISTRICT;
1199 cell.SetNoCreate();
1201 std::list<Unit *> tempUnitMap;
1204 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1205 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1207 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1208 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1210 CellLock<GridReadGuard> cell_lock(cell, p);
1211 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1212 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1215 if(tempUnitMap.empty())
1216 break;
1218 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1220 //Now to get us a random target that's in the initial range of the spell
1221 uint32 t = 0;
1222 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1223 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1224 ++t, ++itr;
1226 if(!t)
1227 break;
1229 itr = tempUnitMap.begin();
1230 std::advance(itr, rand()%t);
1231 Unit *pUnitTarget = *itr;
1232 TagUnitMap.push_back(pUnitTarget);
1234 tempUnitMap.erase(itr);
1236 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1238 t = unMaxTargets - 1;
1239 Unit *prev = pUnitTarget;
1240 std::list<Unit*>::iterator next = tempUnitMap.begin();
1242 while(t && next != tempUnitMap.end() )
1244 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1245 break;
1247 if(!prev->IsWithinLOSInMap(*next))
1249 ++next;
1250 continue;
1253 prev = *next;
1254 TagUnitMap.push_back(prev);
1255 tempUnitMap.erase(next);
1256 tempUnitMap.sort(TargetDistanceOrder(prev));
1257 next = tempUnitMap.begin();
1259 --t;
1261 }break;
1262 case TARGET_PET:
1264 Pet* tmpUnit = m_caster->GetPet();
1265 if (!tmpUnit) break;
1266 TagUnitMap.push_back(tmpUnit);
1267 break;
1269 case TARGET_CHAIN_DAMAGE:
1271 if (EffectChainTarget <= 1)
1273 Unit* pUnitTarget = SelectMagnetTarget();
1274 if(pUnitTarget)
1275 TagUnitMap.push_back(pUnitTarget);
1277 else
1279 Unit* pUnitTarget = m_targets.getUnitTarget();
1280 if(!pUnitTarget)
1281 break;
1283 unMaxTargets = EffectChainTarget;
1285 float max_range;
1286 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1287 max_range = radius; //
1288 else
1289 //FIXME: This very like horrible hack and wrong for most spells
1290 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1292 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1293 Cell cell(p);
1294 cell.data.Part.reserved = ALL_DISTRICT;
1295 cell.SetNoCreate();
1297 Unit* originalCaster = GetOriginalCaster();
1298 if(originalCaster)
1300 std::list<Unit *> tempUnitMap;
1303 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1304 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1306 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1307 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1309 CellLock<GridReadGuard> cell_lock(cell, p);
1310 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1311 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1314 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1316 if(tempUnitMap.empty())
1317 break;
1319 if(*tempUnitMap.begin() == pUnitTarget)
1320 tempUnitMap.erase(tempUnitMap.begin());
1322 TagUnitMap.push_back(pUnitTarget);
1323 uint32 t = unMaxTargets - 1;
1324 Unit *prev = pUnitTarget;
1325 std::list<Unit*>::iterator next = tempUnitMap.begin();
1327 while(t && next != tempUnitMap.end() )
1329 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1330 break;
1332 if(!prev->IsWithinLOSInMap(*next))
1334 ++next;
1335 continue;
1338 prev = *next;
1339 TagUnitMap.push_back(prev);
1340 tempUnitMap.erase(next);
1341 tempUnitMap.sort(TargetDistanceOrder(prev));
1342 next = tempUnitMap.begin();
1344 --t;
1348 }break;
1349 case TARGET_ALL_ENEMY_IN_AREA:
1351 }break;
1352 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1354 // targets the ground, not the units in the area
1355 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1357 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1358 Cell cell(p);
1359 cell.data.Part.reserved = ALL_DISTRICT;
1360 cell.SetNoCreate();
1362 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1364 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1365 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1367 CellLock<GridReadGuard> cell_lock(cell, p);
1368 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1369 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1371 // exclude caster (this can be important if this not original caster)
1372 TagUnitMap.remove(m_caster);
1374 }break;
1375 case TARGET_DUELVSPLAYER_COORDINATES:
1377 if(Unit* currentTarget = m_targets.getUnitTarget())
1379 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1380 TagUnitMap.push_back(currentTarget);
1382 }break;
1383 case TARGET_ALL_PARTY_AROUND_CASTER:
1384 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1385 case TARGET_ALL_PARTY:
1387 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1388 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1390 if(pGroup)
1392 uint8 subgroup = pTarget->GetSubGroup();
1394 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1396 Player* Target = itr->getSource();
1398 // IsHostileTo check duel and controlled by enemy
1399 if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1401 if( m_caster->IsWithinDistInMap(Target, radius) )
1402 TagUnitMap.push_back(Target);
1404 if(Pet* pet = Target->GetPet())
1405 if( m_caster->IsWithinDistInMap(pet, radius) )
1406 TagUnitMap.push_back(pet);
1410 else
1412 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1413 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1414 TagUnitMap.push_back(ownerOrSelf);
1415 if(Pet* pet = ownerOrSelf->GetPet())
1416 if( m_caster->IsWithinDistInMap(pet, radius) )
1417 TagUnitMap.push_back(pet);
1419 }break;
1420 case TARGET_RANDOM_RAID_MEMBER:
1422 if (m_caster->GetTypeId() == TYPEID_PLAYER)
1423 if(Player* target = ((Player*)m_caster)->GetNextRandomRaidMember(radius))
1424 TagUnitMap.push_back(target);
1425 }break;
1426 case TARGET_SINGLE_FRIEND:
1427 case TARGET_SINGLE_FRIEND_2:
1429 if(m_targets.getUnitTarget())
1430 TagUnitMap.push_back(m_targets.getUnitTarget());
1431 }break;
1432 case TARGET_NONCOMBAT_PET:
1434 if(Unit* target = m_targets.getUnitTarget())
1435 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1436 TagUnitMap.push_back(target);
1437 }break;
1438 case TARGET_ALL_AROUND_CASTER:
1440 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1441 Cell cell(p);
1442 cell.data.Part.reserved = ALL_DISTRICT;
1443 cell.SetNoCreate();
1445 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1447 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1448 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1450 CellLock<GridReadGuard> cell_lock(cell, p);
1451 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1452 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1453 }break;
1454 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1456 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1457 Cell cell(p);
1458 cell.data.Part.reserved = ALL_DISTRICT;
1459 cell.SetNoCreate();
1461 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1463 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1464 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1466 CellLock<GridReadGuard> cell_lock(cell, p);
1467 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1468 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1469 }break;
1470 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1472 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1473 Cell cell(p);
1474 cell.data.Part.reserved = ALL_DISTRICT;
1475 cell.SetNoCreate();
1477 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1479 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1480 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1482 CellLock<GridReadGuard> cell_lock(cell, p);
1483 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1484 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1485 }break;
1486 // 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..)
1487 case TARGET_SINGLE_PARTY:
1489 Unit *target = m_targets.getUnitTarget();
1490 // Thoses spells apparently can't be casted on the caster.
1491 if( target && target != m_caster)
1493 // Can only be casted on group's members or its pets
1494 Group *pGroup = NULL;
1496 Unit* owner = m_caster->GetCharmerOrOwner();
1497 Unit *targetOwner = target->GetCharmerOrOwner();
1498 if(owner)
1500 if(owner->GetTypeId() == TYPEID_PLAYER)
1502 if( target == owner )
1504 TagUnitMap.push_back(target);
1505 break;
1507 pGroup = ((Player*)owner)->GetGroup();
1510 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1512 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1514 TagUnitMap.push_back(target);
1515 break;
1517 pGroup = ((Player*)m_caster)->GetGroup();
1520 if(pGroup)
1522 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1523 if(targetOwner)
1525 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1526 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1527 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1528 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1530 TagUnitMap.push_back(target);
1533 // 1Our target can be a player who is on our group
1534 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1536 TagUnitMap.push_back(target);
1540 }break;
1541 case TARGET_GAMEOBJECT:
1543 if(m_targets.getGOTarget())
1544 AddGOTarget(m_targets.getGOTarget(), i);
1545 }break;
1546 case TARGET_IN_FRONT_OF_CASTER:
1548 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1549 Cell cell(p);
1550 cell.data.Part.reserved = ALL_DISTRICT;
1551 cell.SetNoCreate();
1553 bool inFront = m_spellInfo->SpellVisual != 3879;
1554 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1556 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1557 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1559 CellLock<GridReadGuard> cell_lock(cell, p);
1560 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1561 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1562 }break;
1563 case TARGET_DUELVSPLAYER:
1565 Unit *target = m_targets.getUnitTarget();
1566 if(target)
1568 if(m_caster->IsFriendlyTo(target))
1570 TagUnitMap.push_back(target);
1572 else
1574 Unit* pUnitTarget = SelectMagnetTarget();
1575 if(pUnitTarget)
1576 TagUnitMap.push_back(pUnitTarget);
1579 }break;
1580 case TARGET_GAMEOBJECT_ITEM:
1582 if(m_targets.getGOTargetGUID())
1583 AddGOTarget(m_targets.getGOTarget(), i);
1584 else if(m_targets.getItemTarget())
1585 AddItemTarget(m_targets.getItemTarget(), i);
1586 break;
1588 case TARGET_MASTER:
1590 if(Unit* owner = m_caster->GetCharmerOrOwner())
1591 TagUnitMap.push_back(owner);
1592 break;
1594 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1596 // targets the ground, not the units in the area
1597 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1599 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1600 Cell cell(p);
1601 cell.data.Part.reserved = ALL_DISTRICT;
1602 cell.SetNoCreate();
1604 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1606 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1607 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1609 CellLock<GridReadGuard> cell_lock(cell, p);
1610 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1611 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1613 }break;
1614 case TARGET_MINION:
1616 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1617 TagUnitMap.push_back(m_caster);
1618 }break;
1619 case TARGET_SINGLE_ENEMY:
1621 Unit* pUnitTarget = SelectMagnetTarget();
1622 if(pUnitTarget)
1623 TagUnitMap.push_back(pUnitTarget);
1624 }break;
1625 case TARGET_AREAEFFECT_PARTY:
1627 Unit* owner = m_caster->GetCharmerOrOwner();
1628 Player *pTarget = NULL;
1630 if(owner)
1632 TagUnitMap.push_back(m_caster);
1633 if(owner->GetTypeId() == TYPEID_PLAYER)
1634 pTarget = (Player*)owner;
1636 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1638 if(Unit* target = m_targets.getUnitTarget())
1640 if( target->GetTypeId() != TYPEID_PLAYER)
1642 if(((Creature*)target)->isPet())
1644 Unit *targetOwner = target->GetOwner();
1645 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1646 pTarget = (Player*)targetOwner;
1649 else
1650 pTarget = (Player*)target;
1654 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1656 if(pGroup)
1658 uint8 subgroup = pTarget->GetSubGroup();
1660 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1662 Player* Target = itr->getSource();
1664 // IsHostileTo check duel and controlled by enemy
1665 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1667 if( pTarget->IsWithinDistInMap(Target, radius) )
1668 TagUnitMap.push_back(Target);
1670 if(Pet* pet = Target->GetPet())
1671 if( pTarget->IsWithinDistInMap(pet, radius) )
1672 TagUnitMap.push_back(pet);
1676 else if (owner)
1678 if(m_caster->IsWithinDistInMap(owner, radius))
1679 TagUnitMap.push_back(owner);
1681 else if(pTarget)
1683 TagUnitMap.push_back(pTarget);
1685 if(Pet* pet = pTarget->GetPet())
1686 if( m_caster->IsWithinDistInMap(pet, radius) )
1687 TagUnitMap.push_back(pet);
1690 }break;
1691 case TARGET_SCRIPT:
1693 if(m_targets.getUnitTarget())
1694 TagUnitMap.push_back(m_targets.getUnitTarget());
1695 if(m_targets.getItemTarget())
1696 AddItemTarget(m_targets.getItemTarget(), i);
1697 }break;
1698 case TARGET_SELF_FISHING:
1700 TagUnitMap.push_back(m_caster);
1701 }break;
1702 case TARGET_CHAIN_HEAL:
1704 Unit* pUnitTarget = m_targets.getUnitTarget();
1705 if(!pUnitTarget)
1706 break;
1708 if (EffectChainTarget <= 1)
1709 TagUnitMap.push_back(pUnitTarget);
1710 else
1712 unMaxTargets = EffectChainTarget;
1713 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1715 std::list<Unit *> tempUnitMap;
1718 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1719 Cell cell(p);
1720 cell.data.Part.reserved = ALL_DISTRICT;
1721 cell.SetNoCreate();
1723 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1725 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1726 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1728 CellLock<GridReadGuard> cell_lock(cell, p);
1729 cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1730 cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1734 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1735 tempUnitMap.push_front(m_caster);
1737 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1739 if(tempUnitMap.empty())
1740 break;
1742 if(*tempUnitMap.begin() == pUnitTarget)
1743 tempUnitMap.erase(tempUnitMap.begin());
1745 TagUnitMap.push_back(pUnitTarget);
1746 uint32 t = unMaxTargets - 1;
1747 Unit *prev = pUnitTarget;
1748 std::list<Unit*>::iterator next = tempUnitMap.begin();
1750 while(t && next != tempUnitMap.end() )
1752 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1753 break;
1755 if(!prev->IsWithinLOSInMap(*next))
1757 ++next;
1758 continue;
1761 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1763 next = tempUnitMap.erase(next);
1764 continue;
1767 prev = *next;
1768 TagUnitMap.push_back(prev);
1769 tempUnitMap.erase(next);
1770 tempUnitMap.sort(TargetDistanceOrder(prev));
1771 next = tempUnitMap.begin();
1773 --t;
1776 }break;
1777 case TARGET_CURRENT_ENEMY_COORDINATES:
1779 Unit* currentTarget = m_targets.getUnitTarget();
1780 if(currentTarget)
1782 TagUnitMap.push_back(currentTarget);
1783 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1784 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1786 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1787 Cell cell(p);
1788 cell.data.Part.reserved = ALL_DISTRICT;
1789 cell.SetNoCreate();
1790 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1791 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1792 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1793 CellLock<GridReadGuard> cell_lock(cell, p);
1794 cell_lock->Visit(cell_lock, world_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1795 cell_lock->Visit(cell_lock, grid_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1798 }break;
1799 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1801 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1802 ? (Player*)m_targets.getUnitTarget() : NULL;
1804 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1805 if(pGroup)
1807 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1809 Player* Target = itr->getSource();
1811 // IsHostileTo check duel and controlled by enemy
1812 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1813 targetPlayer->getClass() == Target->getClass() &&
1814 !m_caster->IsHostileTo(Target) )
1816 TagUnitMap.push_back(Target);
1820 else if(m_targets.getUnitTarget())
1821 TagUnitMap.push_back(m_targets.getUnitTarget());
1822 break;
1824 case TARGET_TABLE_X_Y_Z_COORDINATES:
1826 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1827 if(st)
1829 if (st->target_mapId == m_caster->GetMapId())
1830 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1832 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1833 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1835 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1836 Cell cell(p);
1837 cell.data.Part.reserved = ALL_DISTRICT;
1838 cell.SetNoCreate();
1840 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1841 // Select friendly targets for positive effect
1842 if (IsPositiveEffect(m_spellInfo->Id, i))
1843 targetB = SPELL_TARGETS_FRIENDLY;
1845 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1847 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1848 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1850 CellLock<GridReadGuard> cell_lock(cell, p);
1851 cell_lock->Visit(cell_lock, world_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1852 cell_lock->Visit(cell_lock, grid_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1855 else
1856 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1857 }break;
1858 case TARGET_BEHIND_VICTIM:
1860 Unit *pTarget = m_caster->getVictim();
1861 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1862 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1864 if(pTarget)
1866 float _target_x, _target_y, _target_z;
1867 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1868 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1869 m_targets.setDestination(_target_x, _target_y, _target_z);
1871 }break;
1872 default:
1873 break;
1876 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
1878 // make sure one unit is always removed per iteration
1879 uint32 removed_utarget = 0;
1880 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
1882 next = itr;
1883 ++next;
1884 if (!*itr) continue;
1885 if ((*itr) == m_targets.getUnitTarget())
1887 TagUnitMap.erase(itr);
1888 removed_utarget = 1;
1889 // break;
1892 // remove random units from the map
1893 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
1895 uint32 poz = urand(0, TagUnitMap.size()-1);
1896 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
1898 if (!*itr) continue;
1899 if (!poz)
1901 TagUnitMap.erase(itr);
1902 break;
1906 // the player's target will always be added to the map
1907 if (removed_utarget && m_targets.getUnitTarget())
1908 TagUnitMap.push_back(m_targets.getUnitTarget());
1912 void Spell::prepare(SpellCastTargets * targets, Aura* triggeredByAura)
1914 m_targets = *targets;
1916 m_spellState = SPELL_STATE_PREPARING;
1918 m_castPositionX = m_caster->GetPositionX();
1919 m_castPositionY = m_caster->GetPositionY();
1920 m_castPositionZ = m_caster->GetPositionZ();
1921 m_castOrientation = m_caster->GetOrientation();
1923 if(triggeredByAura)
1924 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
1926 // create and add update event for this spell
1927 SpellEvent* Event = new SpellEvent(this);
1928 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
1930 //Prevent casting at cast another spell (ServerSide check)
1931 if(m_caster->IsNonMeleeSpellCasted(false, true) && m_cast_count)
1933 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
1934 finish(false);
1935 return;
1938 // Fill cost data
1939 m_powerCost = CalculatePowerCost();
1941 uint8 result = CanCast(true);
1942 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
1944 if(triggeredByAura)
1946 SendChannelUpdate(0);
1947 triggeredByAura->SetAuraDuration(0);
1949 SendCastResult(result);
1950 finish(false);
1951 return;
1954 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
1955 m_casttime = GetSpellCastTime(m_spellInfo, this);
1957 // set timer base at cast time
1958 ReSetTimer();
1960 // stealth must be removed at cast starting (at show channel bar)
1961 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
1962 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
1964 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1965 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
1968 if(m_IsTriggeredSpell)
1969 cast(true);
1970 else
1972 m_caster->SetCurrentCastedSpell( this );
1973 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
1974 SendSpellStart();
1978 void Spell::cancel()
1980 if(m_spellState == SPELL_STATE_FINISHED)
1981 return;
1983 m_autoRepeat = false;
1984 switch (m_spellState)
1986 case SPELL_STATE_PREPARING:
1987 case SPELL_STATE_DELAYED:
1989 SendInterrupted(0);
1990 SendCastResult(SPELL_FAILED_INTERRUPTED);
1991 } break;
1993 case SPELL_STATE_CASTING:
1995 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1997 if( ihit->missCondition == SPELL_MISS_NONE )
1999 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2000 if( unit && unit->isAlive() )
2001 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2005 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2006 SendChannelUpdate(0);
2007 SendInterrupted(0);
2008 SendCastResult(SPELL_FAILED_INTERRUPTED);
2009 } break;
2011 default:
2013 } break;
2016 finish(false);
2017 m_caster->RemoveDynObject(m_spellInfo->Id);
2018 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2021 void Spell::cast(bool skipCheck)
2023 SetExecutedCurrently(true);
2025 uint8 castResult = 0;
2027 // update pointers base at GUIDs to prevent access to non-existed already object
2028 UpdatePointers();
2030 // cancel at lost main target unit
2031 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2033 cancel();
2034 SetExecutedCurrently(false);
2035 return;
2038 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2039 m_caster->SetInFront(m_targets.getUnitTarget());
2041 castResult = CheckPower();
2042 if(castResult != 0)
2044 SendCastResult(castResult);
2045 finish(false);
2046 SetExecutedCurrently(false);
2047 return;
2050 // triggered cast called from Spell::prepare where it was already checked
2051 if(!skipCheck)
2053 castResult = CanCast(false);
2054 if(castResult != 0)
2056 SendCastResult(castResult);
2057 finish(false);
2058 SetExecutedCurrently(false);
2059 return;
2063 // Conflagrate - consumes immolate
2064 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2066 // for caster applied auras only
2067 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2068 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2070 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2071 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2073 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2074 break;
2079 // traded items have trade slot instead of guid in m_itemTargetGUID
2080 // set to real guid to be sent later to the client
2081 m_targets.updateTradeSlotItem();
2083 // CAST SPELL
2084 SendSpellCooldown();
2086 TakePower();
2087 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2088 FillTargetMap();
2090 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2092 SetExecutedCurrently(false);
2093 return;
2096 SendCastResult(castResult);
2097 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2099 // Pass cast spell event to handler (not send triggered by aura spells)
2100 if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE && m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_RANGED && !m_triggeredByAuraSpell)
2102 m_caster->ProcDamageAndSpell(m_targets.getUnitTarget(), PROC_FLAG_CAST_SPELL, PROC_FLAG_NONE, 0, SPELL_SCHOOL_MASK_NONE, m_spellInfo, m_IsTriggeredSpell);
2104 // update pointers base at GUIDs to prevent access to non-existed already object
2105 UpdatePointers(); // pointers can be invalidate at triggered spell casting
2108 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2109 if (m_spellInfo->speed > 0.0f)
2112 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2113 // in case delayed spell remove item at cast delay start
2114 TakeCastItem();
2116 // Okay, maps created, now prepare flags
2117 m_immediateHandled = false;
2118 m_spellState = SPELL_STATE_DELAYED;
2119 SetDelayStart(0);
2121 else
2123 // Immediate spell, no big deal
2124 handle_immediate();
2127 SetExecutedCurrently(false);
2130 void Spell::handle_immediate()
2132 // start channeling if applicable
2133 if(IsChanneledSpell(m_spellInfo))
2135 m_spellState = SPELL_STATE_CASTING;
2136 SendChannelStart(GetSpellDuration(m_spellInfo));
2139 // process immediate effects (items, ground, etc.) also initialize some variables
2140 _handle_immediate_phase();
2142 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2143 DoAllEffectOnTarget(&(*ihit));
2145 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2146 DoAllEffectOnTarget(&(*ihit));
2148 // spell is finished, perform some last features of the spell here
2149 _handle_finish_phase();
2151 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2152 TakeCastItem();
2154 if(m_spellState != SPELL_STATE_CASTING)
2155 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2158 uint64 Spell::handle_delayed(uint64 t_offset)
2160 uint64 next_time = 0;
2162 if (!m_immediateHandled)
2164 _handle_immediate_phase();
2165 m_immediateHandled = true;
2168 // 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)
2169 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2171 if (ihit->processed == false)
2173 if ( ihit->timeDelay <= t_offset )
2174 DoAllEffectOnTarget(&(*ihit));
2175 else if( next_time == 0 || ihit->timeDelay < next_time )
2176 next_time = ihit->timeDelay;
2180 // now recheck gameobject targeting correctness
2181 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2183 if (ighit->processed == false)
2185 if ( ighit->timeDelay <= t_offset )
2186 DoAllEffectOnTarget(&(*ighit));
2187 else if( next_time == 0 || ighit->timeDelay < next_time )
2188 next_time = ighit->timeDelay;
2191 // All targets passed - need finish phase
2192 if (next_time == 0)
2194 // spell is finished, perform some last features of the spell here
2195 _handle_finish_phase();
2197 finish(true); // successfully finish spell cast
2199 // return zero, spell is finished now
2200 return 0;
2202 else
2204 // spell is unfinished, return next execution time
2205 return next_time;
2209 void Spell::_handle_immediate_phase()
2211 // handle some immediate features of the spell here
2212 HandleThreatSpells(m_spellInfo->Id);
2214 m_needSpellLog = IsNeedSendToClient();
2215 for(uint32 j = 0;j<3;j++)
2217 if(m_spellInfo->Effect[j]==0)
2218 continue;
2220 // apply Send Event effect to ground in case empty target lists
2221 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2223 HandleEffects(NULL,NULL,NULL, j);
2224 continue;
2227 // Don't do spell log, if is school damage spell
2228 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2229 m_needSpellLog = false;
2231 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2232 if(m_originalCaster)
2233 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2234 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2236 // initialize multipliers
2237 m_damageMultipliers[j] = 1.0f;
2238 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2239 (EffectChainTarget > 1) )
2240 m_applyMultiplierMask |= 1 << j;
2243 // initialize Diminishing Returns Data
2244 m_diminishLevel = DIMINISHING_LEVEL_1;
2245 m_diminishGroup = DIMINISHING_NONE;
2247 // process items
2248 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2249 DoAllEffectOnTarget(&(*ihit));
2251 // process ground
2252 for(uint32 j = 0;j<3;j++)
2254 // persistent area auras target only the ground
2255 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2256 HandleEffects(NULL,NULL,NULL, j);
2260 void Spell::_handle_finish_phase()
2262 // spell log
2263 if(m_needSpellLog)
2264 SendLogExecute();
2267 void Spell::SendSpellCooldown()
2269 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2270 return;
2272 Player* _player = (Player*)m_caster;
2273 // Add cooldown for max (disable spell)
2274 // Cooldown started on SendCooldownEvent call
2275 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2277 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2278 return;
2281 // init cooldown values
2282 uint32 cat = 0;
2283 int32 rec = -1;
2284 int32 catrec = -1;
2286 // some special item spells without correct cooldown in SpellInfo
2287 // cooldown information stored in item prototype
2288 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2290 if(m_CastItem)
2292 ItemPrototype const* proto = m_CastItem->GetProto();
2293 if(proto)
2295 for(int idx = 0; idx < 5; ++idx)
2297 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2299 cat = proto->Spells[idx].SpellCategory;
2300 rec = proto->Spells[idx].SpellCooldown;
2301 catrec = proto->Spells[idx].SpellCategoryCooldown;
2302 break;
2308 // if no cooldown found above then base at DBC data
2309 if(rec < 0 && catrec < 0)
2311 cat = m_spellInfo->Category;
2312 rec = m_spellInfo->RecoveryTime;
2313 catrec = m_spellInfo->CategoryRecoveryTime;
2316 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2317 // prevent 0 cooldowns set by another way
2318 if (rec <= 0 && catrec <= 0 && (cat == 76 || cat == 351))
2319 rec = _player->GetAttackTime(RANGED_ATTACK);
2321 // Now we have cooldown data (if found any), time to apply mods
2322 if(rec > 0)
2323 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2325 if(catrec > 0)
2326 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2328 // replace negative cooldowns by 0
2329 if (rec < 0) rec = 0;
2330 if (catrec < 0) catrec = 0;
2332 // no cooldown after applying spell mods
2333 if( rec == 0 && catrec == 0)
2334 return;
2336 time_t curTime = time(NULL);
2338 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2339 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2341 // self spell cooldown
2342 if(recTime > 0)
2343 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2345 // category spells
2346 if (catrec > 0)
2348 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2349 if(i_scstore != sSpellCategoryStore.end())
2351 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2353 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2354 continue;
2356 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2362 void Spell::update(uint32 difftime)
2364 // update pointers based at it's GUIDs
2365 UpdatePointers();
2367 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2369 cancel();
2370 return;
2373 // check if the player caster has moved before the spell finished
2374 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2375 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2376 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2378 // always cancel for channeled spells
2379 if( m_spellState == SPELL_STATE_CASTING )
2380 cancel();
2381 // don't cancel for melee, autorepeat, triggered and instant spells
2382 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2383 cancel();
2386 switch(m_spellState)
2388 case SPELL_STATE_PREPARING:
2390 if(m_timer)
2392 if(difftime >= m_timer)
2393 m_timer = 0;
2394 else
2395 m_timer -= difftime;
2398 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2399 cast();
2400 } break;
2401 case SPELL_STATE_CASTING:
2403 if(m_timer > 0)
2405 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2407 // check if player has jumped before the channeling finished
2408 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2409 cancel();
2411 // check for incapacitating player states
2412 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2413 cancel();
2415 // check if player has turned if flag is set
2416 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2417 cancel();
2420 // check if there are alive targets left
2421 if (!IsAliveUnitPresentInTargetList())
2423 SendChannelUpdate(0);
2424 finish();
2427 if(difftime >= m_timer)
2428 m_timer = 0;
2429 else
2430 m_timer -= difftime;
2433 if(m_timer == 0)
2435 SendChannelUpdate(0);
2437 // channeled spell processed independently for quest targeting
2438 // cast at creature (or GO) quest objectives update at successful cast channel finished
2439 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2440 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2442 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2444 TargetInfo* target = &*ihit;
2445 if(!IS_CREATURE_GUID(target->targetGUID))
2446 continue;
2448 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2449 if (unit==NULL)
2450 continue;
2452 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2455 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2457 GOTargetInfo* target = &*ihit;
2459 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2460 if(!go)
2461 continue;
2463 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2467 finish();
2469 } break;
2470 default:
2472 }break;
2476 void Spell::finish(bool ok)
2478 if(!m_caster)
2479 return;
2481 if(m_spellState == SPELL_STATE_FINISHED)
2482 return;
2484 m_spellState = SPELL_STATE_FINISHED;
2486 //remove spell mods
2487 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2488 ((Player*)m_caster)->RemoveSpellMods(this);
2490 // other code related only to successfully finished spells
2491 if(!ok)
2492 return;
2494 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2495 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2496 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2498 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2499 uint32 auraSpellIdx = (*i)->GetEffIndex();
2500 if (IsAffectedBy(auraSpellInfo, auraSpellIdx))
2502 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2503 if( ihit->effectMask & (1<<auraSpellIdx) )
2505 // check m_caster->GetGUID() let load auras at login and speedup most often case
2506 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2507 if (unit && unit->isAlive())
2509 // Calculate chance at that moment (can be depend for example from combo points)
2510 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2512 if(roll_chance_i(chance))
2513 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2519 if (IsMeleeAttackResetSpell())
2521 m_caster->resetAttackTimer(BASE_ATTACK);
2522 if(m_caster->haveOffhandWeapon())
2523 m_caster->resetAttackTimer(OFF_ATTACK);
2526 /*if (IsRangedAttackResetSpell())
2527 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2529 // Clear combo at finish state
2530 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2532 // Not drop combopoints if any miss exist
2533 bool needDrop = true;
2534 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2535 if (ihit->missCondition != SPELL_MISS_NONE)
2537 needDrop = false;
2538 break;
2540 if (needDrop)
2541 ((Player*)m_caster)->ClearComboPoints();
2544 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2545 if(!m_TriggerSpells.empty())
2546 TriggerSpell();
2548 // Stop Attack for some spells
2549 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2550 m_caster->AttackStop();
2553 void Spell::SendCastResult(uint8 result)
2555 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2556 return;
2558 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2559 return;
2561 if(result != 0)
2563 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2564 data << uint32(m_spellInfo->Id);
2565 data << uint8(result); // problem
2566 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2567 switch (result)
2569 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2570 data << uint32(m_spellInfo->RequiresSpellFocus);
2571 break;
2572 case SPELL_FAILED_REQUIRES_AREA:
2573 // hardcode areas limitation case
2574 if( m_spellInfo->Id==41618 || m_spellInfo->Id==41620 )
2575 data << uint32(3842);
2576 else if( m_spellInfo->Id==41617 || m_spellInfo->Id==41619 )
2577 data << uint32(3905);
2578 // normal case
2579 else
2580 data << uint32(m_spellInfo->AreaId);
2581 break;
2582 case SPELL_FAILED_TOTEMS:
2583 if(m_spellInfo->Totem[0])
2584 data << uint32(m_spellInfo->Totem[0]);
2585 if(m_spellInfo->Totem[1])
2586 data << uint32(m_spellInfo->Totem[1]);
2587 break;
2588 case SPELL_FAILED_TOTEM_CATEGORY:
2589 if(m_spellInfo->TotemCategory[0])
2590 data << uint32(m_spellInfo->TotemCategory[0]);
2591 if(m_spellInfo->TotemCategory[1])
2592 data << uint32(m_spellInfo->TotemCategory[1]);
2593 break;
2594 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2595 data << uint32(m_spellInfo->EquippedItemClass);
2596 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2597 data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2598 break;
2600 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2602 else
2604 WorldPacket data(SMSG_CLEAR_EXTRA_AURA_INFO, (8+4));
2605 data.append(m_caster->GetPackGUID());
2606 data << uint32(m_spellInfo->Id);
2607 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2611 void Spell::SendSpellStart()
2613 if(!IsNeedSendToClient())
2614 return;
2616 sLog.outDebug("Sending SMSG_SPELL_START id=%u",m_spellInfo->Id);
2618 uint16 castFlags = CAST_FLAG_UNKNOWN1;
2619 if(IsRangedSpell())
2620 castFlags |= CAST_FLAG_AMMO;
2622 Unit * target;
2623 if(!m_targets.getUnitTarget())
2624 target = m_caster;
2625 else
2626 target = m_targets.getUnitTarget();
2628 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2629 if(m_CastItem)
2630 data.append(m_CastItem->GetPackGUID());
2631 else
2632 data.append(m_caster->GetPackGUID());
2634 data.append(m_caster->GetPackGUID());
2635 data << uint32(m_spellInfo->Id);
2636 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2637 data << uint16(castFlags);
2638 data << uint32(m_timer);
2640 m_targets.write(&data);
2642 if( castFlags & CAST_FLAG_AMMO )
2643 WriteAmmoToPacket(&data);
2645 m_caster->SendMessageToSet(&data, true);
2648 void Spell::SendSpellGo()
2650 // not send invisible spell casting
2651 if(!IsNeedSendToClient())
2652 return;
2654 sLog.outDebug("Sending SMSG_SPELL_GO id=%u",m_spellInfo->Id);
2656 Unit * target;
2657 if(!m_targets.getUnitTarget())
2658 target = m_caster;
2659 else
2660 target = m_targets.getUnitTarget();
2662 uint16 castFlags = CAST_FLAG_UNKNOWN3;
2663 if(IsRangedSpell())
2664 castFlags |= CAST_FLAG_AMMO;
2666 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2667 if(m_CastItem)
2668 data.append(m_CastItem->GetPackGUID());
2669 else
2670 data.append(m_caster->GetPackGUID());
2672 data.append(m_caster->GetPackGUID());
2673 data << uint32(m_spellInfo->Id);
2674 data << uint16(castFlags);
2675 data << uint32(getMSTime()); // timestamp
2677 WriteSpellGoTargets(&data);
2679 m_targets.write(&data);
2681 if( castFlags & CAST_FLAG_AMMO )
2682 WriteAmmoToPacket(&data);
2684 m_caster->SendMessageToSet(&data, true);
2687 void Spell::WriteAmmoToPacket( WorldPacket * data )
2689 uint32 ammoInventoryType = 0;
2690 uint32 ammoDisplayID = 0;
2692 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2694 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2695 if(pItem)
2697 ammoInventoryType = pItem->GetProto()->InventoryType;
2698 if( ammoInventoryType == INVTYPE_THROWN )
2699 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2700 else
2702 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2703 if(ammoID)
2705 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2706 if(pProto)
2708 ammoDisplayID = pProto->DisplayInfoID;
2709 ammoInventoryType = pProto->InventoryType;
2712 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2714 ammoDisplayID = 5996; // normal arrow
2715 ammoInventoryType = INVTYPE_AMMO;
2720 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2722 *data << uint32(ammoDisplayID);
2723 *data << uint32(ammoInventoryType);
2726 void Spell::WriteSpellGoTargets( WorldPacket * data )
2728 *data << (uint8)m_countOfHit;
2729 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2730 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
2731 *data << uint64(ihit->targetGUID);
2733 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
2734 *data << uint64(ighit->targetGUID); // Always hits
2736 *data << (uint8)m_countOfMiss;
2737 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2739 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
2741 *data << uint64(ihit->targetGUID);
2742 *data << uint8(ihit->missCondition);
2743 if( ihit->missCondition == SPELL_MISS_REFLECT )
2744 *data << uint8(ihit->reflectResult);
2749 void Spell::SendLogExecute()
2751 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2753 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
2755 if(m_caster->GetTypeId() == TYPEID_PLAYER)
2756 data.append(m_caster->GetPackGUID());
2757 else
2758 data.append(target->GetPackGUID());
2760 data << uint32(m_spellInfo->Id);
2761 uint32 count1 = 1;
2762 data << uint32(count1); // count1 (effect count?)
2763 for(uint32 i = 0; i < count1; ++i)
2765 data << uint32(m_spellInfo->Effect[0]); // spell effect?
2766 uint32 count2 = 1;
2767 data << uint32(count2); // count2 (target count?)
2768 for(uint32 j = 0; j < count2; ++j)
2770 switch(m_spellInfo->Effect[0])
2772 case SPELL_EFFECT_POWER_DRAIN:
2773 if(Unit *unit = m_targets.getUnitTarget())
2774 data.append(unit->GetPackGUID());
2775 else
2776 data << uint8(0);
2777 data << uint32(0);
2778 data << uint32(0);
2779 data << float(0);
2780 break;
2781 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
2782 if(Unit *unit = m_targets.getUnitTarget())
2783 data.append(unit->GetPackGUID());
2784 else
2785 data << uint8(0);
2786 data << uint32(0); // count?
2787 break;
2788 case SPELL_EFFECT_INTERRUPT_CAST:
2789 if(Unit *unit = m_targets.getUnitTarget())
2790 data.append(unit->GetPackGUID());
2791 else
2792 data << uint8(0);
2793 data << uint32(0); // spellid
2794 break;
2795 case SPELL_EFFECT_DURABILITY_DAMAGE:
2796 if(Unit *unit = m_targets.getUnitTarget())
2797 data.append(unit->GetPackGUID());
2798 else
2799 data << uint8(0);
2800 data << uint32(0);
2801 data << uint32(0);
2802 break;
2803 case SPELL_EFFECT_OPEN_LOCK:
2804 case SPELL_EFFECT_OPEN_LOCK_ITEM:
2805 if(Item *item = m_targets.getItemTarget())
2806 data.append(item->GetPackGUID());
2807 else
2808 data << uint8(0);
2809 break;
2810 case SPELL_EFFECT_CREATE_ITEM:
2811 data << uint32(m_spellInfo->EffectItemType[0]);
2812 break;
2813 case SPELL_EFFECT_SUMMON:
2814 case SPELL_EFFECT_SUMMON_WILD:
2815 case SPELL_EFFECT_SUMMON_GUARDIAN:
2816 case SPELL_EFFECT_TRANS_DOOR:
2817 case SPELL_EFFECT_SUMMON_PET:
2818 case SPELL_EFFECT_SUMMON_POSSESSED:
2819 case SPELL_EFFECT_SUMMON_TOTEM:
2820 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
2821 case SPELL_EFFECT_CREATE_HOUSE:
2822 case SPELL_EFFECT_DUEL:
2823 case SPELL_EFFECT_SUMMON_TOTEM_SLOT1:
2824 case SPELL_EFFECT_SUMMON_TOTEM_SLOT2:
2825 case SPELL_EFFECT_SUMMON_TOTEM_SLOT3:
2826 case SPELL_EFFECT_SUMMON_TOTEM_SLOT4:
2827 case SPELL_EFFECT_SUMMON_PHANTASM:
2828 case SPELL_EFFECT_SUMMON_CRITTER:
2829 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
2830 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
2831 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
2832 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
2833 case SPELL_EFFECT_SUMMON_DEMON:
2834 case SPELL_EFFECT_150:
2835 if(Unit *unit = m_targets.getUnitTarget())
2836 data.append(unit->GetPackGUID());
2837 else if(m_targets.getItemTargetGUID())
2838 data.appendPackGUID(m_targets.getItemTargetGUID());
2839 else if(GameObject *go = m_targets.getGOTarget())
2840 data.append(go->GetPackGUID());
2841 else
2842 data << uint8(0); // guid
2843 break;
2844 case SPELL_EFFECT_FEED_PET:
2845 data << uint32(m_targets.getItemTargetEntry());
2846 break;
2847 case SPELL_EFFECT_DISMISS_PET:
2848 if(Unit *unit = m_targets.getUnitTarget())
2849 data.append(unit->GetPackGUID());
2850 else
2851 data << uint8(0);
2852 break;
2853 default:
2854 return;
2859 m_caster->SendMessageToSet(&data, true);
2862 void Spell::SendInterrupted(uint8 result)
2864 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
2865 data.append(m_caster->GetPackGUID());
2866 data << m_spellInfo->Id;
2867 data << result;
2868 m_caster->SendMessageToSet(&data, true);
2870 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
2871 data.append(m_caster->GetPackGUID());
2872 data << m_spellInfo->Id;
2873 m_caster->SendMessageToSet(&data, true);
2876 void Spell::SendChannelUpdate(uint32 time)
2878 if(time == 0)
2880 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
2881 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
2884 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2885 return;
2887 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
2888 data.append(m_caster->GetPackGUID());
2889 data << time;
2891 ((Player*)m_caster)->GetSession()->SendPacket( &data );
2894 void Spell::SendChannelStart(uint32 duration)
2896 WorldObject* target = NULL;
2898 // select first not resisted target from target list for _0_ effect
2899 if(!m_UniqueTargetInfo.empty())
2901 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
2903 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
2905 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
2906 break;
2910 else if(!m_UniqueGOTargetInfo.empty())
2912 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
2914 if(itr->effectMask & (1<<0) )
2916 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
2917 break;
2922 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2924 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
2925 data.append(m_caster->GetPackGUID());
2926 data << m_spellInfo->Id;
2927 data << duration;
2929 ((Player*)m_caster)->GetSession()->SendPacket( &data );
2932 m_timer = duration;
2933 if(target)
2934 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
2935 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
2938 void Spell::SendResurrectRequest(Player* target)
2940 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+2+4));
2941 data << m_caster->GetGUID();
2942 data << uint32(1) << uint16(0) << uint32(1);
2944 target->GetSession()->SendPacket(&data);
2947 void Spell::SendPlaySpellVisual(uint32 SpellID)
2949 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2950 return;
2952 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
2953 data << m_caster->GetGUID();
2954 data << SpellID;
2955 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2958 void Spell::TakeCastItem()
2960 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
2961 return;
2963 // not remove cast item at triggered spell (equipping, weapon damage, etc)
2964 if(m_IsTriggeredSpell)
2965 return;
2967 ItemPrototype const *proto = m_CastItem->GetProto();
2969 if(!proto)
2971 // This code is to avoid a crash
2972 // I'm not sure, if this is really an error, but I guess every item needs a prototype
2973 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
2974 return;
2977 bool expendable = false;
2978 bool withoutCharges = false;
2980 for (int i = 0; i<5; i++)
2982 if (proto->Spells[i].SpellId)
2984 // item has limited charges
2985 if (proto->Spells[i].SpellCharges)
2987 if (proto->Spells[i].SpellCharges < 0)
2988 expendable = true;
2990 int32 charges = m_CastItem->GetSpellCharges(i);
2992 // item has charges left
2993 if (charges)
2995 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
2996 if (proto->Stackable < 2)
2997 m_CastItem->SetSpellCharges(i, charges);
2998 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3001 // all charges used
3002 withoutCharges = (charges == 0);
3007 if (expendable && withoutCharges)
3009 uint32 count = 1;
3010 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3012 // prevent crash at access to deleted m_targets.getItemTarget
3013 if(m_CastItem==m_targets.getItemTarget())
3014 m_targets.setItemTarget(NULL);
3016 m_CastItem = NULL;
3020 void Spell::TakePower()
3022 if(m_CastItem || m_triggeredByAuraSpell)
3023 return;
3025 // health as power used
3026 if(m_spellInfo->powerType == POWER_HEALTH)
3028 m_caster->ModifyHealth( -(int32)m_powerCost );
3029 return;
3032 if(m_spellInfo->powerType >= MAX_POWERS)
3034 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3035 return;
3038 Powers powerType = Powers(m_spellInfo->powerType);
3040 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3042 // Set the five second timer
3043 if (powerType == POWER_MANA && m_powerCost > 0)
3044 m_caster->SetLastManaUse(getMSTime());
3047 void Spell::TakeReagents()
3049 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3050 return;
3052 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3053 return;
3055 if (m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
3056 m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
3057 return;
3059 Player* p_caster = (Player*)m_caster;
3061 for(uint32 x=0;x<8;x++)
3063 if(m_spellInfo->Reagent[x] <= 0)
3064 continue;
3066 uint32 itemid = m_spellInfo->Reagent[x];
3067 uint32 itemcount = m_spellInfo->ReagentCount[x];
3069 // if CastItem is also spell reagent
3070 if (m_CastItem)
3072 ItemPrototype const *proto = m_CastItem->GetProto();
3073 if( proto && proto->ItemId == itemid )
3075 for(int s=0;s<5;s++)
3077 // CastItem will be used up and does not count as reagent
3078 int32 charges = m_CastItem->GetSpellCharges(s);
3079 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3081 ++itemcount;
3082 break;
3086 m_CastItem = NULL;
3090 // if getItemTarget is also spell reagent
3091 if (m_targets.getItemTargetEntry()==itemid)
3092 m_targets.setItemTarget(NULL);
3094 p_caster->DestroyItemCount(itemid, itemcount, true);
3098 void Spell::HandleThreatSpells(uint32 spellId)
3100 if(!m_targets.getUnitTarget() || !spellId)
3101 return;
3103 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3104 return;
3106 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3107 if(!threatSpell)
3108 return;
3110 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3112 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3115 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3117 unitTarget = pUnitTarget;
3118 itemTarget = pItemTarget;
3119 gameObjTarget = pGOTarget;
3121 uint8 eff = m_spellInfo->Effect[i];
3122 uint32 mechanic = m_spellInfo->EffectMechanic[i];
3124 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3126 sLog.outDebug( "Spell: Effect : %u", eff);
3128 //Simply return. Do not display "immune" in red text on client
3129 if(unitTarget && unitTarget->IsImmunedToSpellEffect(eff, mechanic))
3130 return;
3132 if(eff<TOTAL_SPELL_EFFECTS)
3134 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3135 (*this.*SpellEffects[eff])(i);
3138 else
3140 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3141 if (m_CastItem)
3142 EffectEnchantItemTmp(i);
3143 else
3145 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3146 eff, m_spellInfo->Id);
3152 void Spell::TriggerSpell()
3154 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3156 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3157 spell->prepare(&m_targets); // use original spell original targets
3161 uint8 Spell::CanCast(bool strict)
3163 // check cooldowns to prevent cheating
3164 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3166 if(m_triggeredByAuraSpell)
3167 return SPELL_FAILED_DONT_REPORT;
3168 else
3169 return SPELL_FAILED_NOT_READY;
3172 // only allow triggered spells if at an ended battleground
3173 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3174 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3175 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3176 return SPELL_FAILED_DONT_REPORT;
3178 // only check at first call, Stealth auras are already removed at second call
3179 // for now, ignore triggered spells
3180 if( strict && !m_IsTriggeredSpell)
3182 // Cannot be used in this stance/form
3183 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3184 return shapeError;
3186 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3187 return SPELL_FAILED_ONLY_STEALTHED;
3190 // caster state requirements
3191 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3192 return SPELL_FAILED_CASTER_AURASTATE;
3193 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3194 return SPELL_FAILED_CASTER_AURASTATE;
3196 // cancel autorepeat spells if cast start when moving
3197 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3198 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3200 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3201 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3202 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3203 return SPELL_FAILED_MOVING;
3206 Unit *target = m_targets.getUnitTarget();
3208 if(target)
3210 // target state requirements (not allowed state), apply to self also
3211 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3212 return SPELL_FAILED_TARGET_AURASTATE;
3214 if(target != m_caster)
3216 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3217 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3218 return SPELL_FAILED_TARGET_AURASTATE;
3220 // Not allow casting on flying player
3221 if (target->isInFlight())
3222 return SPELL_FAILED_BAD_TARGETS;
3224 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3225 return SPELL_FAILED_LINE_OF_SIGHT;
3227 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3228 // this case can be triggered if rank not found (too low-level target for first rank)
3229 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3231 for(int i=0;i<3;i++)
3233 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3234 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3235 return SPELL_FAILED_LOWLEVEL;
3240 // check pet presents
3241 for(int j=0;j<3;j++)
3243 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3245 target = m_caster->GetPet();
3246 if(!target)
3248 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3249 return SPELL_FAILED_DONT_REPORT;
3250 else
3251 return SPELL_FAILED_NO_PET;
3253 break;
3257 //check creature type
3258 //ignore self casts (including area casts when caster selected as target)
3259 if(target != m_caster)
3261 if(!CheckTargetCreatureType(target))
3263 if(target->GetTypeId()==TYPEID_PLAYER)
3264 return SPELL_FAILED_TARGET_IS_PLAYER;
3265 else
3266 return SPELL_FAILED_BAD_TARGETS;
3270 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3271 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3272 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3274 // check correctness positive/negative cast target (pet cast real check and cheating check)
3275 if(IsPositiveSpell(m_spellInfo->Id))
3277 if(m_caster->IsHostileTo(target))
3278 return SPELL_FAILED_BAD_TARGETS;
3280 else
3282 if(m_caster->IsFriendlyTo(target))
3283 return SPELL_FAILED_BAD_TARGETS;
3287 if(IsPositiveSpell(m_spellInfo->Id))
3289 if(target->IsImmunedToSpell(m_spellInfo,false))
3290 return SPELL_FAILED_TARGET_AURASTATE;
3293 //Must be behind the target.
3294 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3296 SendInterrupted(2);
3297 return SPELL_FAILED_NOT_BEHIND;
3300 //Target must be facing you.
3301 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3303 SendInterrupted(2);
3304 return SPELL_FAILED_NOT_INFRONT;
3307 // check if target is in combat
3308 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3310 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3313 // Spell casted only on battleground
3314 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3315 if(!((Player*)m_caster)->InBattleGround())
3316 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3318 // do not allow spells to be cast in arenas
3319 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3320 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3321 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3322 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3323 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3324 if(mapEntry->IsBattleArena())
3325 return SPELL_FAILED_NOT_IN_ARENA;
3327 // zone check
3328 if(!IsSpellAllowedInLocation(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3329 return SPELL_FAILED_REQUIRES_AREA;
3331 // not let players cast spells at mount (and let do it to creatures)
3332 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3333 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3335 if(m_caster->isInFlight())
3336 return SPELL_FAILED_NOT_FLYING;
3337 else
3338 return SPELL_FAILED_NOT_MOUNTED;
3341 // always (except passive spells) check items (focus object can be required for any type casts)
3342 if(!IsPassiveSpell(m_spellInfo->Id))
3343 if(uint8 castResult = CheckItems())
3344 return castResult;
3346 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3347 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3349 for(uint8 j = 0; j < 3; j++)
3351 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3352 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3353 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3354 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3356 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3357 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3358 if(lower==upper)
3359 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);
3361 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3362 float range = GetSpellMaxRange(srange);
3364 Creature* creatureScriptTarget = NULL;
3365 GameObject* goScriptTarget = NULL;
3367 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3369 switch(i_spellST->second.type)
3371 case SPELL_TARGET_TYPE_GAMEOBJECT:
3373 GameObject* p_GameObject = NULL;
3375 if(i_spellST->second.targetEntry)
3377 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3378 Cell cell(p);
3379 cell.data.Part.reserved = ALL_DISTRICT;
3381 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3382 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
3384 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3385 CellLock<GridReadGuard> cell_lock(cell, p);
3386 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
3388 if(p_GameObject)
3390 // remember found target and range, next attempt will find more near target with another entry
3391 creatureScriptTarget = NULL;
3392 goScriptTarget = p_GameObject;
3393 range = go_check.GetLastRange();
3396 else if( focusObject ) //Focus Object
3398 float frange = m_caster->GetDistance(focusObject);
3399 if(range >= frange)
3401 creatureScriptTarget = NULL;
3402 goScriptTarget = focusObject;
3403 range = frange;
3406 break;
3408 case SPELL_TARGET_TYPE_CREATURE:
3409 case SPELL_TARGET_TYPE_DEAD:
3410 default:
3412 Creature *p_Creature = NULL;
3414 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3415 Cell cell(p);
3416 cell.data.Part.reserved = ALL_DISTRICT;
3417 cell.SetNoCreate(); // Really don't know what is that???
3419 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3420 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
3422 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3424 CellLock<GridReadGuard> cell_lock(cell, p);
3425 cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
3427 if(p_Creature )
3429 creatureScriptTarget = p_Creature;
3430 goScriptTarget = NULL;
3431 range = u_check.GetLastRange();
3433 break;
3438 if(creatureScriptTarget)
3440 // store coordinates for TARGET_SCRIPT_COORDINATES
3441 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3442 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3444 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3446 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3447 AddUnitTarget(creatureScriptTarget, j);
3449 // store explicit target for TARGET_SCRIPT
3450 else
3451 AddUnitTarget(creatureScriptTarget, j);
3453 else if(goScriptTarget)
3455 // store coordinates for TARGET_SCRIPT_COORDINATES
3456 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3457 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3459 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3461 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3462 AddGOTarget(goScriptTarget, j);
3464 // store explicit target for TARGET_SCRIPT
3465 else
3466 AddGOTarget(goScriptTarget, j);
3468 //Missing DB Entry or targets for this spellEffect.
3469 else
3471 // not report target not existence for triggered spells
3472 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3473 return SPELL_FAILED_DONT_REPORT;
3474 else
3475 return SPELL_FAILED_BAD_TARGETS;
3481 if(uint8 castResult = CheckRange(strict))
3482 return castResult;
3485 if(uint8 castResult = CheckPower())
3486 return castResult;
3489 if(!m_triggeredByAuraSpell) // triggered spell not affected by stun/etc
3490 if(uint8 castResult = CheckCasterAuras())
3491 return castResult;
3493 for (int i = 0; i < 3; i++)
3495 // for effects of spells that have only one target
3496 switch(m_spellInfo->Effect[i])
3498 case SPELL_EFFECT_DUMMY:
3500 if(m_spellInfo->SpellIconID == 1648) // Execute
3502 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3503 return SPELL_FAILED_BAD_TARGETS;
3505 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
3507 if(m_caster->IsInWater())
3508 return SPELL_FAILED_ONLY_ABOVEWATER;
3510 else if(m_spellInfo->SpellIconID==156) // Holy Shock
3512 // spell different for friends and enemies
3513 // hart version required facing
3514 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3515 return SPELL_FAILED_UNIT_NOT_INFRONT;
3517 break;
3519 case SPELL_EFFECT_SCHOOL_DAMAGE:
3521 // Hammer of Wrath
3522 if(m_spellInfo->SpellVisual == 7250)
3524 if (!m_targets.getUnitTarget())
3525 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3527 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3528 return SPELL_FAILED_BAD_TARGETS;
3530 break;
3532 case SPELL_EFFECT_TAMECREATURE:
3534 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3535 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3537 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3538 return SPELL_FAILED_HIGHLEVEL;
3540 // use SMSG_PET_TAME_FAILURE?
3541 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3542 return SPELL_FAILED_BAD_TARGETS;
3544 if(m_caster->GetPetGUID())
3545 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3547 if(m_caster->GetCharmGUID())
3548 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3550 break;
3552 case SPELL_EFFECT_LEARN_SPELL:
3554 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3555 break;
3557 Pet* pet = m_caster->GetPet();
3559 if(!pet)
3560 return SPELL_FAILED_NO_PET;
3562 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3564 if(!learn_spellproto)
3565 return SPELL_FAILED_NOT_KNOWN;
3567 if(!pet->CanTakeMoreActiveSpells(learn_spellproto->Id))
3568 return SPELL_FAILED_TOO_MANY_SKILLS;
3570 if(m_spellInfo->spellLevel > pet->getLevel())
3571 return SPELL_FAILED_LOWLEVEL;
3573 if(!pet->HasTPForSpell(learn_spellproto->Id))
3574 return SPELL_FAILED_TRAINING_POINTS;
3576 break;
3578 case SPELL_EFFECT_LEARN_PET_SPELL:
3580 Pet* pet = m_caster->GetPet();
3582 if(!pet)
3583 return SPELL_FAILED_NO_PET;
3585 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3587 if(!learn_spellproto)
3588 return SPELL_FAILED_NOT_KNOWN;
3590 if(!pet->CanTakeMoreActiveSpells(learn_spellproto->Id))
3591 return SPELL_FAILED_TOO_MANY_SKILLS;
3593 if(m_spellInfo->spellLevel > pet->getLevel())
3594 return SPELL_FAILED_LOWLEVEL;
3596 if(!pet->HasTPForSpell(learn_spellproto->Id))
3597 return SPELL_FAILED_TRAINING_POINTS;
3599 break;
3601 case SPELL_EFFECT_FEED_PET:
3603 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getItemTarget() )
3604 return SPELL_FAILED_BAD_TARGETS;
3606 Pet* pet = m_caster->GetPet();
3608 if(!pet)
3609 return SPELL_FAILED_NO_PET;
3611 if(!pet->HaveInDiet(m_targets.getItemTarget()->GetProto()))
3612 return SPELL_FAILED_WRONG_PET_FOOD;
3614 if(!pet->GetCurrentFoodBenefitLevel(m_targets.getItemTarget()->GetProto()->ItemLevel))
3615 return SPELL_FAILED_FOOD_LOWLEVEL;
3617 if(m_caster->isInCombat() || pet->isInCombat())
3618 return SPELL_FAILED_AFFECTING_COMBAT;
3620 break;
3622 case SPELL_EFFECT_POWER_BURN:
3623 case SPELL_EFFECT_POWER_DRAIN:
3625 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
3626 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3627 if(Unit* target = m_targets.getUnitTarget())
3628 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
3629 return SPELL_FAILED_BAD_TARGETS;
3630 break;
3632 case SPELL_EFFECT_CHARGE:
3634 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
3635 return SPELL_FAILED_ROOTED;
3637 break;
3639 case SPELL_EFFECT_SKINNING:
3641 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
3642 return SPELL_FAILED_BAD_TARGETS;
3644 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
3645 return SPELL_FAILED_TARGET_UNSKINNABLE;
3647 Creature* creature = (Creature*)m_targets.getUnitTarget();
3648 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
3650 return SPELL_FAILED_TARGET_NOT_LOOTED;
3653 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
3655 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
3656 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
3657 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
3658 if (ReqValue > skillValue)
3659 return SPELL_FAILED_LOW_CASTLEVEL;
3661 // chance for fail at orange skinning attempt
3662 if( (m_selfContainer && (*m_selfContainer) == this) &&
3663 skillValue < sWorld.GetConfigMaxSkillValue() &&
3664 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
3665 return SPELL_FAILED_TRY_AGAIN;
3667 break;
3669 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3670 case SPELL_EFFECT_OPEN_LOCK:
3672 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
3673 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
3674 break;
3676 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
3677 // we need a go target in case of TARGET_GAMEOBJECT
3678 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
3679 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
3680 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
3681 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
3682 return SPELL_FAILED_BAD_TARGETS;
3684 // In BattleGround players can use only flags and banners
3685 if( ((Player*)m_caster)->InBattleGround() &&
3686 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
3687 return SPELL_FAILED_TRY_AGAIN;
3689 // get the lock entry
3690 LockEntry const *lockInfo = NULL;
3691 if (GameObject* go=m_targets.getGOTarget())
3692 lockInfo = sLockStore.LookupEntry(go->GetLockId());
3693 else if(Item* itm=m_targets.getItemTarget())
3694 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
3696 // check lock compatibility
3697 if (lockInfo)
3699 // check for lock - key pair (checked by client also, just prevent cheating
3700 bool ok_key = false;
3701 for(int it = 0; it < 5; ++it)
3703 switch(lockInfo->keytype[it])
3705 case LOCK_KEY_NONE:
3706 break;
3707 case LOCK_KEY_ITEM:
3709 if(lockInfo->key[it])
3711 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->key[it])
3712 ok_key =true;
3713 break;
3716 case LOCK_KEY_SKILL:
3718 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->key[it])
3719 break;
3721 switch(lockInfo->key[it])
3723 case LOCKTYPE_HERBALISM:
3724 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
3725 ok_key =true;
3726 break;
3727 case LOCKTYPE_MINING:
3728 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
3729 ok_key =true;
3730 break;
3731 default:
3732 ok_key =true;
3733 break;
3737 if(ok_key)
3738 break;
3741 if(!ok_key)
3742 return SPELL_FAILED_BAD_TARGETS;
3745 // chance for fail at orange mining/herb/LockPicking gathering attempt
3746 if (!m_selfContainer || ((*m_selfContainer) != this))
3747 break;
3749 // get the skill value of the player
3750 int32 SkillValue = 0;
3751 bool canFailAtMax = true;
3752 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
3754 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
3755 canFailAtMax = false;
3757 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
3759 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
3760 canFailAtMax = false;
3762 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3763 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
3765 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
3766 if(m_CastItem)
3767 SkillValue = 0;
3769 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
3770 SkillValue += m_currentBasePoints[i]+1;
3772 // get the required lock value
3773 int32 ReqValue=0;
3774 if (lockInfo)
3776 // check for lock - key pair
3777 bool ok = false;
3778 for(int it = 0; it < 5; ++it)
3780 if(lockInfo->keytype[it]==LOCK_KEY_ITEM && lockInfo->key[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->key[it])
3782 // if so, we're good to go
3783 ok = true;
3784 break;
3787 if(ok)
3788 break;
3790 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3791 ReqValue = lockInfo->requiredlockskill;
3792 else
3793 ReqValue = lockInfo->requiredminingskill;
3796 // skill doesn't meet the required value
3797 if (ReqValue > SkillValue)
3798 return SPELL_FAILED_LOW_CASTLEVEL;
3800 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
3801 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
3802 return SPELL_FAILED_TRY_AGAIN;
3804 break;
3806 case SPELL_EFFECT_SUMMON_DEAD_PET:
3808 Creature *pet = m_caster->GetPet();
3809 if(!pet)
3810 return SPELL_FAILED_NO_PET;
3812 if(pet->isAlive())
3813 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3815 break;
3817 // This is generic summon effect now and don't make this check for summon types similar
3818 // SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3819 // These won't show up in m_caster->GetPetGUID()
3820 case SPELL_EFFECT_SUMMON:
3822 switch(m_spellInfo->EffectMiscValueB[i])
3824 case SUMMON_TYPE_POSESSED:
3825 case SUMMON_TYPE_POSESSED2:
3826 case SUMMON_TYPE_DEMON:
3827 case SUMMON_TYPE_SUMMON:
3829 if(m_caster->GetPetGUID())
3830 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3832 if(m_caster->GetCharmGUID())
3833 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3834 break;
3837 break;
3839 // Don't make this check for SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3840 // These won't show up in m_caster->GetPetGUID()
3841 case SPELL_EFFECT_SUMMON_POSSESSED:
3842 case SPELL_EFFECT_SUMMON_PHANTASM:
3843 case SPELL_EFFECT_SUMMON_DEMON:
3845 if(m_caster->GetPetGUID())
3846 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3848 if(m_caster->GetCharmGUID())
3849 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3851 break;
3853 case SPELL_EFFECT_SUMMON_PET:
3855 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
3858 Pet* pet = ((Player*)m_caster)->GetPet();
3860 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
3862 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
3863 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
3865 else
3866 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3869 if(m_caster->GetCharmGUID())
3870 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3872 break;
3874 case SPELL_EFFECT_SUMMON_PLAYER:
3876 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
3877 return SPELL_FAILED_BAD_TARGETS;
3878 if(!((Player*)m_caster)->GetSelection())
3879 return SPELL_FAILED_BAD_TARGETS;
3881 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
3882 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
3883 return SPELL_FAILED_BAD_TARGETS;
3885 // check if our map is dungeon
3886 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
3888 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
3889 if(!instance)
3890 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
3891 if ( instance->levelMin > target->getLevel() )
3892 return SPELL_FAILED_LOWLEVEL;
3893 if ( instance->levelMax && instance->levelMax < target->getLevel() )
3894 return SPELL_FAILED_HIGHLEVEL;
3896 break;
3898 case SPELL_EFFECT_LEAP:
3899 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
3901 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
3902 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
3903 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
3904 // teleport a bit above terrain level to avoid falling below it
3905 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
3906 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
3907 return SPELL_FAILED_TRY_AGAIN;
3909 float caster_pos_z = m_caster->GetPositionZ();
3910 // Control the caster to not climb or drop when +-fz > 8
3911 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
3912 return SPELL_FAILED_TRY_AGAIN;
3914 // not allow use this effect at battleground until battleground start
3915 if(m_caster->GetTypeId()==TYPEID_PLAYER)
3916 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
3917 if(bg->GetStatus() != STATUS_IN_PROGRESS)
3918 return SPELL_FAILED_TRY_AGAIN;
3919 break;
3921 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
3923 if (m_targets.getUnitTarget()==m_caster)
3924 return SPELL_FAILED_BAD_TARGETS;
3925 break;
3927 default:break;
3931 for (int i = 0; i < 3; i++)
3933 switch(m_spellInfo->EffectApplyAuraName[i])
3935 case SPELL_AURA_MOD_POSSESS:
3936 case SPELL_AURA_MOD_CHARM:
3938 if(m_caster->GetPetGUID())
3939 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3941 if(m_caster->GetCharmGUID())
3942 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3944 if(m_caster->GetCharmerGUID())
3945 return SPELL_FAILED_CHARMED;
3947 if(!m_targets.getUnitTarget())
3948 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3950 if(m_targets.getUnitTarget()->GetCharmerGUID())
3951 return SPELL_FAILED_CHARMED;
3953 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
3954 return SPELL_FAILED_HIGHLEVEL;
3955 };break;
3956 case SPELL_AURA_MOUNTED:
3958 if (m_caster->IsInWater())
3959 return SPELL_FAILED_ONLY_ABOVEWATER;
3961 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
3962 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
3964 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
3965 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaId)
3966 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
3968 if (m_caster->GetAreaId()==35)
3969 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
3971 ShapeshiftForm form = m_caster->m_form;
3972 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
3973 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
3974 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
3975 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN )
3976 return SPELL_FAILED_NOT_SHAPESHIFT;
3978 break;
3980 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
3982 if(!m_targets.getUnitTarget())
3983 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3985 // can be casted at non-friendly unit or own pet/charm
3986 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
3987 return SPELL_FAILED_TARGET_FRIENDLY;
3988 };break;
3989 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
3990 case SPELL_AURA_FLY:
3992 // not allow cast fly spells at old maps by players (all spells is self target)
3993 if(m_caster->GetTypeId()==TYPEID_PLAYER)
3995 if( !((Player*)m_caster)->isGameMaster() &&
3996 GetVirtualMapForMapAndZone(m_caster->GetMapId(),m_caster->GetZoneId()) != 530)
3997 return SPELL_FAILED_NOT_HERE;
3999 };break;
4000 case SPELL_AURA_PERIODIC_MANA_LEECH:
4002 if (!m_targets.getUnitTarget())
4003 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4005 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4006 break;
4008 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4009 return SPELL_FAILED_BAD_TARGETS;
4010 break;
4012 default:break;
4016 // all ok
4017 return 0;
4020 int16 Spell::PetCanCast(Unit* target)
4022 if(!m_caster->isAlive())
4023 return SPELL_FAILED_CASTER_DEAD;
4025 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4026 return SPELL_FAILED_SPELL_IN_PROGRESS;
4027 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4028 return SPELL_FAILED_AFFECTING_COMBAT;
4030 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4032 //dead owner (pets still alive when owners ressed?)
4033 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4034 return SPELL_FAILED_CASTER_DEAD;
4036 if(!target && m_targets.getUnitTarget())
4037 target = m_targets.getUnitTarget();
4039 bool need = false;
4040 for(uint32 i = 0;i<3;i++)
4042 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)
4044 need = true;
4045 if(!target)
4046 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4047 break;
4050 if(need)
4051 m_targets.setUnitTarget(target);
4053 Unit* _target = m_targets.getUnitTarget();
4055 if(_target) //for target dead/target not valid
4057 if(!_target->isAlive())
4058 return SPELL_FAILED_BAD_TARGETS;
4060 if(IsPositiveSpell(m_spellInfo->Id))
4062 if(m_caster->IsHostileTo(_target))
4063 return SPELL_FAILED_BAD_TARGETS;
4065 else
4067 bool duelvsplayertar = false;
4068 for(int j=0;j<3;j++)
4070 //TARGET_DUELVSPLAYER is positive AND negative
4071 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4073 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4075 return SPELL_FAILED_BAD_TARGETS;
4079 //cooldown
4080 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4081 return SPELL_FAILED_NOT_READY;
4084 uint16 result = CanCast(true);
4085 if(result != 0)
4086 return result;
4087 else
4088 return -1; //this allows to check spell fail 0, in combat
4091 uint8 Spell::CheckCasterAuras() const
4093 // Flag drop spells totally immuned to caster auras
4094 // FIXME: find more nice check for all totally immuned spells
4095 // AttributesEx3 & 0x10000000?
4096 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4097 return 0;
4099 uint8 school_immune = 0;
4100 uint32 mechanic_immune = 0;
4101 uint32 dispel_immune = 0;
4103 //Check if the spell grants school or mechanic immunity.
4104 //We use bitmasks so the loop is done only once and not on every aura check below.
4105 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4107 for(int i = 0;i < 3; i ++)
4109 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4110 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4111 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4112 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4113 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4114 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4116 //immune movement impairment and loss of control
4117 if(m_spellInfo->Id==(uint32)42292)
4118 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4121 //Check whether the cast should be prevented by any state you might have.
4122 uint8 prevented_reason = 0;
4123 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4124 if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4125 prevented_reason = SPELL_FAILED_STUNNED;
4126 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4127 prevented_reason = SPELL_FAILED_CONFUSED;
4128 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4129 prevented_reason = SPELL_FAILED_FLEEING;
4130 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4131 prevented_reason = SPELL_FAILED_SILENCED;
4132 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4133 prevented_reason = SPELL_FAILED_PACIFIED;
4135 // Attr must make flag drop spell totally immuned from all effects
4136 if(prevented_reason)
4138 if(school_immune || mechanic_immune || dispel_immune)
4140 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4141 Unit::AuraMap const& auras = m_caster->GetAuras();
4142 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); itr++)
4144 if(itr->second)
4146 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4147 continue;
4148 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4149 continue;
4150 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4151 continue;
4153 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4154 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4155 switch(itr->second->GetModifier()->m_auraname)
4157 case SPELL_AURA_MOD_STUN:
4158 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4159 return SPELL_FAILED_STUNNED;
4160 break;
4161 case SPELL_AURA_MOD_CONFUSE:
4162 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4163 return SPELL_FAILED_CONFUSED;
4164 break;
4165 case SPELL_AURA_MOD_FEAR:
4166 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4167 return SPELL_FAILED_FLEEING;
4168 break;
4169 case SPELL_AURA_MOD_SILENCE:
4170 case SPELL_AURA_MOD_PACIFY:
4171 case SPELL_AURA_MOD_PACIFY_SILENCE:
4172 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4173 return SPELL_FAILED_PACIFIED;
4174 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4175 return SPELL_FAILED_SILENCED;
4176 break;
4181 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4182 else
4183 return prevented_reason;
4185 return 0; // all ok
4188 bool Spell::CanAutoCast(Unit* target)
4190 uint64 targetguid = target->GetGUID();
4192 for(uint32 j = 0;j<3;j++)
4194 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4196 if( m_spellInfo->StackAmount <= 1)
4198 if( target->HasAura(m_spellInfo->Id, j) )
4199 return false;
4201 else
4203 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4204 return false;
4207 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4209 if( target->HasAura(m_spellInfo->Id, j) )
4210 return false;
4214 int16 result = PetCanCast(target);
4216 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4218 FillTargetMap();
4219 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4220 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4221 if( ihit->targetGUID == targetguid )
4222 return true;
4224 return false; //target invalid
4227 uint8 Spell::CheckRange(bool strict)
4229 float range_mod;
4231 // self cast doesn't need range checking -- also for Starshards fix
4232 if (m_spellInfo->rangeIndex == 1) return 0;
4234 if (strict) //add radius of caster
4235 range_mod = 1.25;
4236 else //add radius of caster and ~5 yds "give"
4237 range_mod = 6.25;
4239 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4240 float max_range = GetSpellMaxRange(srange) + range_mod;
4241 float min_range = GetSpellMinRange(srange);
4243 if(Player* modOwner = m_caster->GetSpellModOwner())
4244 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4246 Unit *target = m_targets.getUnitTarget();
4248 if(target && target != m_caster)
4250 // distance from target center in checks
4251 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4252 if(dist > max_range)
4253 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4254 if(dist < min_range)
4255 return SPELL_FAILED_TOO_CLOSE;
4256 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4257 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4258 return SPELL_FAILED_UNIT_NOT_INFRONT;
4261 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4263 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4264 if(dist > max_range)
4265 return SPELL_FAILED_OUT_OF_RANGE;
4266 if(dist < min_range)
4267 return SPELL_FAILED_TOO_CLOSE;
4270 return 0; // ok
4273 int32 Spell::CalculatePowerCost()
4275 // item cast not used power
4276 if(m_CastItem)
4277 return 0;
4279 // Spell drain all exist power on cast (Only paladin lay of Hands)
4280 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4282 // If power type - health drain all
4283 if (m_spellInfo->powerType == POWER_HEALTH)
4284 return m_caster->GetHealth();
4285 // Else drain all power
4286 if (m_spellInfo->powerType < MAX_POWERS)
4287 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4288 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4289 return 0;
4292 // Base powerCost
4293 int32 powerCost = m_spellInfo->manaCost;
4294 // PCT cost from total amount
4295 if (m_spellInfo->ManaCostPercentage)
4297 switch (m_spellInfo->powerType)
4299 // health as power used
4300 case POWER_HEALTH:
4301 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4302 break;
4303 case POWER_MANA:
4304 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4305 break;
4306 case POWER_RAGE:
4307 case POWER_FOCUS:
4308 case POWER_ENERGY:
4309 case POWER_HAPPINESS:
4310 // case POWER_RUNES:
4311 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4312 break;
4313 default:
4314 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4315 return 0;
4318 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4319 // Flat mod from caster auras by spell school
4320 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4321 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4322 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4323 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4324 // Apply cost mod by spell
4325 if(Player* modOwner = m_caster->GetSpellModOwner())
4326 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4328 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4329 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4331 // PCT mod from user auras by school
4332 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4333 if (powerCost < 0)
4334 powerCost = 0;
4335 return powerCost;
4338 uint8 Spell::CheckPower()
4340 // item cast not used power
4341 if(m_CastItem)
4342 return 0;
4344 // health as power used - need check health amount
4345 if(m_spellInfo->powerType == POWER_HEALTH)
4347 if(m_caster->GetHealth() <= m_powerCost)
4348 return SPELL_FAILED_CASTER_AURASTATE;
4349 return 0;
4351 // Check valid power type
4352 if( m_spellInfo->powerType >= MAX_POWERS )
4354 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4355 return SPELL_FAILED_UNKNOWN;
4357 // Check power amount
4358 Powers powerType = Powers(m_spellInfo->powerType);
4359 if(m_caster->GetPower(powerType) < m_powerCost)
4360 return SPELL_FAILED_NO_POWER;
4361 else
4362 return 0;
4365 uint8 Spell::CheckItems()
4367 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4368 return 0;
4370 uint32 itemid, itemcount;
4371 Player* p_caster = (Player*)m_caster;
4373 if(m_CastItem)
4375 itemid = m_CastItem->GetEntry();
4376 if( !p_caster->HasItemCount(itemid,1) )
4377 return SPELL_FAILED_ITEM_NOT_READY;
4378 else
4380 ItemPrototype const *proto = m_CastItem->GetProto();
4381 if(!proto)
4382 return SPELL_FAILED_ITEM_NOT_READY;
4384 for (int i = 0; i<5; i++)
4386 if (proto->Spells[i].SpellCharges)
4388 if(m_CastItem->GetSpellCharges(i)==0)
4389 return SPELL_FAILED_NO_CHARGES_REMAIN;
4393 uint32 ItemClass = proto->Class;
4394 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4396 for (int i = 0; i < 3; i++)
4398 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4399 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4400 continue;
4402 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4403 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4404 return (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4406 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4407 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4409 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4410 return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4412 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4414 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4415 return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4422 if(m_targets.getItemTargetGUID())
4424 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4425 return SPELL_FAILED_BAD_TARGETS;
4427 if(!m_targets.getItemTarget())
4428 return SPELL_FAILED_ITEM_GONE;
4430 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4431 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4433 // if not item target then required item must be equipped
4434 else
4436 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4437 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4440 if(m_spellInfo->RequiresSpellFocus)
4442 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4443 Cell cell(p);
4444 cell.data.Part.reserved = ALL_DISTRICT;
4446 GameObject* ok = NULL;
4447 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4448 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(ok,go_check);
4450 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4451 CellLock<GridReadGuard> cell_lock(cell, p);
4452 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
4454 if(!ok)
4455 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4457 focusObject = ok; // game object found in range
4460 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
4461 m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION)))
4463 for(uint32 i=0;i<8;i++)
4465 if(m_spellInfo->Reagent[i] <= 0)
4466 continue;
4468 itemid = m_spellInfo->Reagent[i];
4469 itemcount = m_spellInfo->ReagentCount[i];
4471 // if CastItem is also spell reagent
4472 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4474 ItemPrototype const *proto = m_CastItem->GetProto();
4475 if(!proto)
4476 return SPELL_FAILED_ITEM_NOT_READY;
4477 for(int s=0;s<5;s++)
4479 // CastItem will be used up and does not count as reagent
4480 int32 charges = m_CastItem->GetSpellCharges(s);
4481 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4483 ++itemcount;
4484 break;
4488 if( !p_caster->HasItemCount(itemid,itemcount) )
4489 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
4493 uint32 totems = 2;
4494 for(int i=0;i<2;++i)
4496 if(m_spellInfo->Totem[i] != 0)
4498 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4500 totems -= 1;
4501 continue;
4503 }else
4504 totems -= 1;
4506 if(totems != 0)
4507 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
4509 //Check items for TotemCategory
4510 uint32 TotemCategory = 2;
4511 for(int i=0;i<2;++i)
4513 if(m_spellInfo->TotemCategory[i] != 0)
4515 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4517 TotemCategory -= 1;
4518 continue;
4521 else
4522 TotemCategory -= 1;
4524 if(TotemCategory != 0)
4525 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
4527 for(int i = 0; i < 3; i++)
4529 switch (m_spellInfo->Effect[i])
4531 case SPELL_EFFECT_CREATE_ITEM:
4533 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4535 ItemPosCountVec dest;
4536 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4537 if (msg != EQUIP_ERR_OK )
4539 p_caster->SendEquipError( msg, NULL, NULL );
4540 return SPELL_FAILED_DONT_REPORT;
4543 break;
4545 case SPELL_EFFECT_ENCHANT_ITEM:
4547 Item* targetItem = m_targets.getItemTarget();
4548 if(!targetItem)
4549 return SPELL_FAILED_ITEM_NOT_FOUND;
4551 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
4552 return SPELL_FAILED_LOWLEVEL;
4553 // Not allow enchant in trade slot for some enchant type
4554 if( targetItem->GetOwner() != m_caster )
4556 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4557 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4558 if(!pEnchant)
4559 return SPELL_FAILED_ERROR;
4560 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4561 return SPELL_FAILED_NOT_TRADEABLE;
4563 break;
4565 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
4567 Item *item = m_targets.getItemTarget();
4568 if(!item)
4569 return SPELL_FAILED_ITEM_NOT_FOUND;
4570 // Not allow enchant in trade slot for some enchant type
4571 if( item->GetOwner() != m_caster )
4573 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4574 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4575 if(!pEnchant)
4576 return SPELL_FAILED_ERROR;
4577 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4578 return SPELL_FAILED_NOT_TRADEABLE;
4580 break;
4582 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
4583 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
4584 break;
4585 case SPELL_EFFECT_DISENCHANT:
4587 if(!m_targets.getItemTarget())
4588 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4590 // prevent disenchanting in trade slot
4591 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4592 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4594 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
4595 if(!itemProto)
4596 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4598 uint32 item_quality = itemProto->Quality;
4599 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
4600 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
4601 if (item_disenchantskilllevel == uint32(-1))
4602 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4603 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
4604 return SPELL_FAILED_LOW_CASTLEVEL;
4605 if(item_quality > 4 || item_quality < 2)
4606 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4607 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
4608 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4609 if (!itemProto->DisenchantID)
4610 return SPELL_FAILED_CANT_BE_DISENCHANTED;
4611 break;
4613 case SPELL_EFFECT_PROSPECTING:
4615 if(!m_targets.getItemTarget())
4616 return SPELL_FAILED_CANT_BE_PROSPECTED;
4617 //ensure item is a prospectable ore
4618 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
4619 return SPELL_FAILED_CANT_BE_PROSPECTED;
4620 //prevent prospecting in trade slot
4621 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4622 return SPELL_FAILED_CANT_BE_PROSPECTED;
4623 //Check for enough skill in jewelcrafting
4624 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
4625 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
4626 return SPELL_FAILED_LOW_CASTLEVEL;
4627 //make sure the player has the required ores in inventory
4628 if(m_targets.getItemTarget()->GetCount() < 5)
4629 return SPELL_FAILED_PROSPECT_NEED_MORE;
4631 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
4632 return SPELL_FAILED_CANT_BE_PROSPECTED;
4634 break;
4636 case SPELL_EFFECT_WEAPON_DAMAGE:
4637 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
4639 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
4640 if( m_attackType != RANGED_ATTACK )
4641 break;
4642 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
4643 if(!pItem || pItem->IsBroken())
4644 return SPELL_FAILED_EQUIPPED_ITEM;
4646 switch(pItem->GetProto()->SubClass)
4648 case ITEM_SUBCLASS_WEAPON_THROWN:
4650 uint32 ammo = pItem->GetEntry();
4651 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4652 return SPELL_FAILED_NO_AMMO;
4653 }; break;
4654 case ITEM_SUBCLASS_WEAPON_GUN:
4655 case ITEM_SUBCLASS_WEAPON_BOW:
4656 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4658 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
4659 if(!ammo)
4661 // Requires No Ammo
4662 if(m_caster->GetDummyAura(46699))
4663 break; // skip other checks
4665 return SPELL_FAILED_NO_AMMO;
4668 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
4669 if(!ammoProto)
4670 return SPELL_FAILED_NO_AMMO;
4672 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
4673 return SPELL_FAILED_NO_AMMO;
4675 // check ammo ws. weapon compatibility
4676 switch(pItem->GetProto()->SubClass)
4678 case ITEM_SUBCLASS_WEAPON_BOW:
4679 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4680 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
4681 return SPELL_FAILED_NO_AMMO;
4682 break;
4683 case ITEM_SUBCLASS_WEAPON_GUN:
4684 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
4685 return SPELL_FAILED_NO_AMMO;
4686 break;
4687 default:
4688 return SPELL_FAILED_NO_AMMO;
4691 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4692 return SPELL_FAILED_NO_AMMO;
4693 }; break;
4694 case ITEM_SUBCLASS_WEAPON_WAND:
4695 default:
4696 break;
4698 break;
4700 default:break;
4704 return uint8(0);
4707 void Spell::Delayed()
4709 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
4710 return;
4712 if (m_spellState == SPELL_STATE_DELAYED)
4713 return; // spell is active and can't be time-backed
4715 // spells not loosing casting time ( slam, dynamites, bombs.. )
4716 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
4717 return;
4719 //check resist chance
4720 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
4721 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4722 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4723 if (roll_chance_i(resistChance))
4724 return;
4726 int32 delaytime = GetNextDelayAtDamageMsTime();
4728 if(int32(m_timer) + delaytime > m_casttime)
4730 delaytime = m_casttime - m_timer;
4731 m_timer = m_casttime;
4733 else
4734 m_timer += delaytime;
4736 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
4738 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
4739 data.append(m_caster->GetPackGUID());
4740 data << uint32(delaytime);
4742 m_caster->SendMessageToSet(&data,true);
4745 void Spell::DelayedChannel()
4747 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
4748 return;
4750 //check resist chance
4751 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
4752 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4753 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4754 if (roll_chance_i(resistChance))
4755 return;
4757 int32 delaytime = GetNextDelayAtDamageMsTime();
4759 if(int32(m_timer) < delaytime)
4761 delaytime = m_timer;
4762 m_timer = 0;
4764 else
4765 m_timer -= delaytime;
4767 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
4769 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4771 if ((*ihit).missCondition == SPELL_MISS_NONE)
4773 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
4774 if (unit)
4776 for (int j=0;j<3;j++)
4777 if( ihit->effectMask & (1<<j) )
4778 unit->DelayAura(m_spellInfo->Id, j, delaytime);
4784 for(int j = 0; j < 3; j++)
4786 // partially interrupt persistent area auras
4787 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
4788 if(dynObj)
4789 dynObj->Delay(delaytime);
4792 SendChannelUpdate(m_timer);
4795 void Spell::UpdatePointers()
4797 if(m_originalCasterGUID==m_caster->GetGUID())
4798 m_originalCaster = m_caster;
4799 else
4801 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
4802 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
4805 m_targets.Update(m_caster);
4808 bool Spell::IsAffectedBy(SpellEntry const *spellInfo, uint32 effectId)
4810 return spellmgr.IsAffectedBySpell(m_spellInfo,spellInfo->Id,effectId,spellInfo->EffectItemType[effectId]);
4813 bool Spell::CheckTargetCreatureType(Unit* target) const
4815 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
4817 // Curse of Doom : not find another way to fix spell target check :/
4818 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
4820 // not allow cast at player
4821 if(target->GetTypeId()==TYPEID_PLAYER)
4822 return false;
4824 spellCreatureTargetMask = 0x7FF;
4827 // Dismiss Pet and Taming Lesson skipped
4828 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
4829 spellCreatureTargetMask = 0;
4831 if (spellCreatureTargetMask)
4833 uint32 TargetCreatureType = target->GetCreatureTypeMask();
4835 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
4837 return true;
4840 CurrentSpellTypes Spell::GetCurrentContainer()
4842 if (IsNextMeleeSwingSpell())
4843 return(CURRENT_MELEE_SPELL);
4844 else if (IsAutoRepeat())
4845 return(CURRENT_AUTOREPEAT_SPELL);
4846 else if (IsChanneledSpell(m_spellInfo))
4847 return(CURRENT_CHANNELED_SPELL);
4848 else
4849 return(CURRENT_GENERIC_SPELL);
4852 bool Spell::CheckTarget( Unit* target, uint32 eff )
4854 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
4855 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
4857 if (!CheckTargetCreatureType(target))
4858 return false;
4861 // Check targets for not_selectable unit flag and remove
4862 // A player can cast spells on his pet (or other controlled unit) though in any state
4863 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
4865 // any unattackable target skipped
4866 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
4867 return false;
4869 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
4870 // in case TARGET_SCRIPT target selected by server always and can't be cheated
4871 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
4872 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
4873 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
4874 return false;
4877 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
4878 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
4880 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
4881 return false;
4883 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
4884 return false;
4887 //Check targets for LOS visibility (except spells without range limitations )
4888 switch(m_spellInfo->Effect[eff])
4890 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
4891 break;
4892 case SPELL_EFFECT_DUMMY:
4893 if(m_spellInfo->Id!=20577) // Cannibalize
4894 break;
4895 //fall through
4896 case SPELL_EFFECT_RESURRECT_NEW:
4897 // player far away, maybe his corpse near?
4898 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4900 if(!m_targets.getCorpseTargetGUID())
4901 return false;
4903 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
4904 if(!corpse)
4905 return false;
4907 if(target->GetGUID()!=corpse->GetOwnerGUID())
4908 return false;
4910 if(!corpse->IsWithinLOSInMap(m_caster))
4911 return false;
4914 // all ok by some way or another, skip normal check
4915 break;
4916 default: // normal case
4917 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4918 return false;
4919 break;
4922 return true;
4925 Unit* Spell::SelectMagnetTarget()
4927 Unit* target = m_targets.getUnitTarget();
4929 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
4931 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
4932 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
4934 if(Unit* magnet = (*itr)->GetCaster())
4936 if(magnet->IsWithinLOSInMap(m_caster))
4938 target = magnet;
4939 m_targets.setUnitTarget(target);
4940 break;
4946 return target;
4949 bool Spell::IsNeedSendToClient() const
4951 return m_spellInfo->SpellVisual!=0 || IsChanneledSpell(m_spellInfo) ||
4952 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
4955 bool Spell::HaveTargetsForEffect( uint8 effect ) const
4957 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
4958 if(itr->effectMask & (1<<effect))
4959 return true;
4961 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
4962 if(itr->effectMask & (1<<effect))
4963 return true;
4965 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
4966 if(itr->effectMask & (1<<effect))
4967 return true;
4969 return false;
4972 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
4974 m_Spell = spell;
4977 SpellEvent::~SpellEvent()
4979 if (m_Spell->getState() != SPELL_STATE_FINISHED)
4980 m_Spell->cancel();
4982 if (m_Spell->IsDeletable())
4984 delete m_Spell;
4986 else
4988 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
4989 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
4993 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
4995 // update spell if it is not finished
4996 if (m_Spell->getState() != SPELL_STATE_FINISHED)
4997 m_Spell->update(p_time);
4999 // check spell state to process
5000 switch (m_Spell->getState())
5002 case SPELL_STATE_FINISHED:
5004 // spell was finished, check deletable state
5005 if (m_Spell->IsDeletable())
5007 // check, if we do have unfinished triggered spells
5009 return(true); // spell is deletable, finish event
5011 // event will be re-added automatically at the end of routine)
5012 } break;
5014 case SPELL_STATE_CASTING:
5016 // this spell is in channeled state, process it on the next update
5017 // event will be re-added automatically at the end of routine)
5018 } break;
5020 case SPELL_STATE_DELAYED:
5022 // first, check, if we have just started
5023 if (m_Spell->GetDelayStart() != 0)
5025 // no, we aren't, do the typical update
5026 // check, if we have channeled spell on our hands
5027 if (IsChanneledSpell(m_Spell->m_spellInfo))
5029 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5030 // check, if we have casting anything else except this channeled spell and autorepeat
5031 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5033 // another non-melee non-delayed spell is casted now, abort
5034 m_Spell->cancel();
5036 else
5038 // do the action (pass spell to channeling state)
5039 m_Spell->handle_immediate();
5041 // event will be re-added automatically at the end of routine)
5043 else
5045 // run the spell handler and think about what we can do next
5046 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5047 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5048 if (n_offset)
5050 // re-add us to the queue
5051 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5052 return(false); // event not complete
5054 // event complete
5055 // finish update event will be re-added automatically at the end of routine)
5058 else
5060 // delaying had just started, record the moment
5061 m_Spell->SetDelayStart(e_time);
5062 // re-plan the event for the delay moment
5063 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5064 return(false); // event not complete
5066 } break;
5068 default:
5070 // all other states
5071 // event will be re-added automatically at the end of routine)
5072 } break;
5075 // spell processing not complete, plan event on the next update interval
5076 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5077 return(false); // event not complete
5080 void SpellEvent::Abort(uint64 /*e_time*/)
5082 // oops, the spell we try to do is aborted
5083 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5084 m_Spell->cancel();
5087 bool SpellEvent::IsDeletable() const
5089 return m_Spell->IsDeletable();