[7146] Trailing whitespace code cleanup
[getmangos.git] / src / game / Spell.cpp
blob6076308b09efceb3a325e108596ddd724bf5d58c
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "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 "LootMgr.h"
45 #include "VMapFactory.h"
46 #include "BattleGround.h"
47 #include "Util.h"
49 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
51 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
53 bool IsQuestTameSpell(uint32 spellId)
55 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
56 if (!spellproto) return false;
58 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
59 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
62 SpellCastTargets::SpellCastTargets()
64 m_unitTarget = NULL;
65 m_itemTarget = NULL;
66 m_GOTarget = NULL;
68 m_unitTargetGUID = 0;
69 m_GOTargetGUID = 0;
70 m_CorpseTargetGUID = 0;
71 m_itemTargetGUID = 0;
72 m_itemTargetEntry = 0;
74 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
75 m_strTarget = "";
76 m_targetMask = 0;
79 SpellCastTargets::~SpellCastTargets()
83 void SpellCastTargets::setUnitTarget(Unit *target)
85 if (!target)
86 return;
88 m_destX = target->GetPositionX();
89 m_destY = target->GetPositionY();
90 m_destZ = target->GetPositionZ();
91 m_unitTarget = target;
92 m_unitTargetGUID = target->GetGUID();
93 m_targetMask |= TARGET_FLAG_UNIT;
96 void SpellCastTargets::setDestination(float x, float y, float z)
98 m_destX = x;
99 m_destY = y;
100 m_destZ = z;
101 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
104 void SpellCastTargets::setGOTarget(GameObject *target)
106 m_GOTarget = target;
107 m_GOTargetGUID = target->GetGUID();
108 // m_targetMask |= TARGET_FLAG_OBJECT;
111 void SpellCastTargets::setItemTarget(Item* item)
113 if(!item)
114 return;
116 m_itemTarget = item;
117 m_itemTargetGUID = item->GetGUID();
118 m_itemTargetEntry = item->GetEntry();
119 m_targetMask |= TARGET_FLAG_ITEM;
122 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
124 m_CorpseTargetGUID = corpse->GetGUID();
127 void SpellCastTargets::Update(Unit* caster)
129 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
130 m_unitTarget = m_unitTargetGUID ?
131 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
132 NULL;
134 m_itemTarget = NULL;
135 if(caster->GetTypeId()==TYPEID_PLAYER)
137 if(m_targetMask & TARGET_FLAG_ITEM)
138 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
139 else
141 Player* pTrader = ((Player*)caster)->GetTrader();
142 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
143 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
145 if(m_itemTarget)
146 m_itemTargetEntry = m_itemTarget->GetEntry();
150 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
152 if(data->rpos()+4 > data->size())
153 return false;
155 *data >> m_targetMask;
157 if(m_targetMask == TARGET_FLAG_SELF)
159 m_destX = caster->GetPositionX();
160 m_destY = caster->GetPositionY();
161 m_destZ = caster->GetPositionZ();
162 m_unitTarget = caster;
163 m_unitTargetGUID = caster->GetGUID();
164 return true;
167 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
168 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
169 if(!data->readPackGUID(m_unitTargetGUID))
170 return false;
172 if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
173 if(!data->readPackGUID(m_GOTargetGUID))
174 return false;
176 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
177 if(!data->readPackGUID(m_itemTargetGUID))
178 return false;
180 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
182 if(data->rpos()+4+4+4 > data->size())
183 return false;
185 *data >> m_srcX >> m_srcY >> m_srcZ;
186 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
187 return false;
190 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
192 if(data->rpos()+4+4+4 > data->size())
193 return false;
195 *data >> m_destX >> m_destY >> m_destZ;
196 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
197 return false;
200 if( m_targetMask & TARGET_FLAG_STRING )
202 if(data->rpos()+1 > data->size())
203 return false;
205 *data >> m_strTarget;
208 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
209 if(!data->readPackGUID(m_CorpseTargetGUID))
210 return false;
212 // find real units/GOs
213 Update(caster);
214 return true;
217 void SpellCastTargets::write ( WorldPacket * data )
219 *data << uint32(m_targetMask);
221 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
223 if(m_targetMask & TARGET_FLAG_UNIT)
225 if(m_unitTarget)
226 data->append(m_unitTarget->GetPackGUID());
227 else
228 *data << uint8(0);
230 else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
232 if(m_GOTarget)
233 data->append(m_GOTarget->GetPackGUID());
234 else
235 *data << uint8(0);
237 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
238 data->appendPackGUID(m_CorpseTargetGUID);
239 else
240 *data << uint8(0);
243 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
245 if(m_itemTarget)
246 data->append(m_itemTarget->GetPackGUID());
247 else
248 *data << uint8(0);
251 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
252 *data << m_srcX << m_srcY << m_srcZ;
254 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
255 *data << m_destX << m_destY << m_destZ;
257 if( m_targetMask & TARGET_FLAG_STRING )
258 *data << m_strTarget;
261 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
263 ASSERT( Caster != NULL && info != NULL );
264 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
266 m_spellInfo = info;
267 m_caster = Caster;
268 m_selfContainer = NULL;
269 m_triggeringContainer = triggeringContainer;
270 m_referencedFromCurrentSpell = false;
271 m_executedCurrently = false;
272 m_delayStart = 0;
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->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
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);
309 // Set health leech amount to zero
310 m_healthLeech = 0;
312 if(originalCasterGUID)
313 m_originalCasterGUID = originalCasterGUID;
314 else
315 m_originalCasterGUID = m_caster->GetGUID();
317 if(m_originalCasterGUID==m_caster->GetGUID())
318 m_originalCaster = m_caster;
319 else
321 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
322 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
325 for(int i=0; i <3; ++i)
326 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
328 m_spellState = SPELL_STATE_NULL;
330 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
331 m_TriggerSpells.clear();
332 m_IsTriggeredSpell = triggered;
333 //m_AreaAura = false;
334 m_CastItem = NULL;
336 unitTarget = NULL;
337 itemTarget = NULL;
338 gameObjTarget = NULL;
339 focusObject = NULL;
340 m_cast_count = 0;
341 m_glyphIndex = 0;
342 m_triggeredByAuraSpell = NULL;
344 //Auto Shot & Shoot (wand)
345 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
347 m_runesState = 0;
348 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
349 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
350 m_timer = 0; // will set to castime in prepare
352 m_needAliveTargetMask = 0;
354 // determine reflection
355 m_canReflect = false;
357 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
359 for(int j=0;j<3;j++)
361 if (m_spellInfo->Effect[j]==0)
362 continue;
364 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
365 m_canReflect = true;
366 else
367 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
369 if(m_canReflect)
370 continue;
371 else
372 break;
376 CleanupTargetList();
379 Spell::~Spell()
383 void Spell::FillTargetMap()
385 // TODO: ADD the correct target FILLS!!!!!!
387 for(uint32 i=0;i<3;i++)
389 // not call for empty effect.
390 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
391 if(m_spellInfo->Effect[i]==0)
392 continue;
394 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
395 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
396 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
397 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
398 continue;
400 // TODO: find a way so this is not needed?
401 // for area auras always add caster as target (needed for totems for example)
402 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
403 AddUnitTarget(m_caster, i);
405 std::list<Unit*> tmpUnitMap;
407 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
408 // but need it support in some know cases
409 switch(m_spellInfo->EffectImplicitTargetA[i])
411 case TARGET_ALL_AROUND_CASTER:
412 if( m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_PARTY ||
413 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER ||
414 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_RAID_AROUND_CASTER )
416 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
418 // Note: this hack with search required until GO casting not implemented
419 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
420 // currently each enemy selected explicitly and self cast damage
421 else if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
423 if(m_targets.getUnitTarget())
424 tmpUnitMap.push_back(m_targets.getUnitTarget());
426 else
428 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
429 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
431 break;
432 case TARGET_TABLE_X_Y_Z_COORDINATES:
433 // Only if target A, for target B (used in teleports) dest select in effect
434 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
435 break;
436 default:
437 switch(m_spellInfo->EffectImplicitTargetB[i])
439 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
440 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
441 break;
442 default:
443 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
444 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
445 break;
447 break;
450 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
451 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
453 // add here custom effects that need default target.
454 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
455 switch(m_spellInfo->Effect[i])
457 case SPELL_EFFECT_DUMMY:
459 switch(m_spellInfo->Id)
461 case 20577: // Cannibalize
463 // non-standard target selection
464 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
465 float max_range = GetSpellMaxRange(srange);
467 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
468 Cell cell(p);
469 cell.data.Part.reserved = ALL_DISTRICT;
470 cell.SetNoCreate();
472 WorldObject* result = NULL;
474 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
475 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
477 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
478 CellLock<GridReadGuard> cell_lock(cell, p);
479 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
481 if(!result)
483 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
484 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
487 if(result)
489 switch(result->GetTypeId())
491 case TYPEID_UNIT:
492 case TYPEID_PLAYER:
493 tmpUnitMap.push_back((Unit*)result);
494 break;
495 case TYPEID_CORPSE:
496 m_targets.setCorpseTarget((Corpse*)result);
497 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
498 tmpUnitMap.push_back(owner);
499 break;
502 else
504 // clear cooldown at fail
505 if(m_caster->GetTypeId()==TYPEID_PLAYER)
507 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
509 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
510 data << uint32(m_spellInfo->Id);
511 data << uint64(m_caster->GetGUID());
512 ((Player*)m_caster)->GetSession()->SendPacket(&data);
515 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
516 finish(false);
518 break;
520 default:
521 if(m_targets.getUnitTarget())
522 tmpUnitMap.push_back(m_targets.getUnitTarget());
523 break;
525 break;
527 case SPELL_EFFECT_RESURRECT:
528 case SPELL_EFFECT_PARRY:
529 case SPELL_EFFECT_BLOCK:
530 case SPELL_EFFECT_CREATE_ITEM:
531 case SPELL_EFFECT_TRIGGER_SPELL:
532 case SPELL_EFFECT_TRIGGER_MISSILE:
533 case SPELL_EFFECT_LEARN_SPELL:
534 case SPELL_EFFECT_SKILL_STEP:
535 case SPELL_EFFECT_PROFICIENCY:
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_TRANS_DOOR:
575 case SPELL_EFFECT_ADD_FARSIGHT:
576 case SPELL_EFFECT_APPLY_GLYPH:
577 case SPELL_EFFECT_STUCK:
578 case SPELL_EFFECT_FEED_PET:
579 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
580 case SPELL_EFFECT_SKILL:
581 tmpUnitMap.push_back(m_caster);
582 break;
583 case SPELL_EFFECT_LEARN_PET_SPELL:
584 if(Pet* pet = m_caster->GetPet())
585 tmpUnitMap.push_back(pet);
586 break;
587 case SPELL_EFFECT_ENCHANT_ITEM:
588 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
589 case SPELL_EFFECT_DISENCHANT:
590 case SPELL_EFFECT_PROSPECTING:
591 case SPELL_EFFECT_MILLING:
592 if(m_targets.getItemTarget())
593 AddItemTarget(m_targets.getItemTarget(), i);
594 break;
595 case SPELL_EFFECT_APPLY_AURA:
596 switch(m_spellInfo->EffectApplyAuraName[i])
598 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)
599 case SPELL_AURA_ADD_PCT_MODIFIER:
600 tmpUnitMap.push_back(m_caster);
601 break;
602 default: // apply to target in other case
603 if(m_targets.getUnitTarget())
604 tmpUnitMap.push_back(m_targets.getUnitTarget());
605 break;
607 break;
608 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
609 // AreaAura
610 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
611 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
612 break;
613 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
614 if(m_targets.getUnitTarget())
616 tmpUnitMap.push_back(m_targets.getUnitTarget());
618 else if (m_targets.getCorpseTargetGUID())
620 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
621 if(corpse)
623 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
624 if(owner)
625 tmpUnitMap.push_back(owner);
628 break;
629 default:
630 break;
633 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
634 m_needAliveTargetMask |= (1<<i);
636 if(m_caster->GetTypeId() == TYPEID_PLAYER)
638 Player *me = (Player*)m_caster;
639 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
641 Unit *owner = (*itr)->GetOwner();
642 Unit *u = owner ? owner : (*itr);
643 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
645 me->UpdatePvP(true);
646 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
647 break;
652 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
654 if (!CheckTarget (*itr, i))
656 itr = tmpUnitMap.erase(itr);
657 continue;
659 else
660 ++itr;
663 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
664 AddUnitTarget((*iunit), i);
668 void Spell::prepareDataForTriggerSystem()
670 //==========================================================================================
671 // Now fill data for trigger system, need know:
672 // Ñan spell trigger another or not ( m_canTrigger )
673 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
674 //==========================================================================================
675 // Fill flag can spell trigger or not
676 // TODO: possible exist spell attribute for this
677 m_canTrigger = false;
679 if (m_CastItem)
680 m_canTrigger = false; // Do not trigger from item cast spell
681 else if (!m_IsTriggeredSpell)
682 m_canTrigger = true; // Normal cast - can trigger
683 else if (!m_triggeredByAuraSpell)
684 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
686 if (!m_canTrigger) // Exceptions (some periodic triggers)
688 switch (m_spellInfo->SpellFamilyName)
690 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
691 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
692 break;
693 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
694 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
695 break;
696 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
697 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
698 break;
699 case SPELLFAMILY_ROGUE: // For poisons need do it
700 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
701 break;
702 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect
703 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000014LL) m_canTrigger = true;
704 break;
705 case SPELLFAMILY_PALADIN: // For Holy Shock triggers need do it
706 if (m_spellInfo->SpellFamilyFlags & 0x0001000000200000LL) m_canTrigger = true;
707 break;
711 // Get data for type of attack and fill base info for trigger
712 switch (m_spellInfo->DmgClass)
714 case SPELL_DAMAGE_CLASS_MELEE:
715 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
716 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
717 break;
718 case SPELL_DAMAGE_CLASS_RANGED:
719 // Auto attack
720 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
722 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
723 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
725 else // Ranged spell attack
727 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
728 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
730 break;
731 default:
732 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
734 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
735 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
737 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
739 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
740 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
742 else // Negative spell
744 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
745 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
747 break;
749 // Hunter traps spells (for Entrapment trigger)
750 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
751 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x0000200000000014LL)
752 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
755 void Spell::CleanupTargetList()
757 m_UniqueTargetInfo.clear();
758 m_UniqueGOTargetInfo.clear();
759 m_UniqueItemInfo.clear();
760 m_delayMoment = 0;
763 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
765 if( m_spellInfo->Effect[effIndex]==0 )
766 return;
768 // Check for effect immune skip if immuned
769 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
771 uint64 targetGUID = pVictim->GetGUID();
773 // Lookup target in already in list
774 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
776 if (targetGUID == ihit->targetGUID) // Found in list
778 if (!immuned)
779 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
780 return;
784 // This is new target calculate data for him
786 // Get spell hit result on target
787 TargetInfo target;
788 target.targetGUID = targetGUID; // Store target GUID
789 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
790 target.processed = false; // Effects not apply on target
792 // Calculate hit result
793 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
795 // Spell have speed - need calculate incoming time
796 if (m_spellInfo->speed > 0.0f)
798 // calculate spell incoming interval
799 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
800 if (dist < 5.0f) dist = 5.0f;
801 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
803 // Calculate minimum incoming time
804 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
805 m_delayMoment = target.timeDelay;
807 else
808 target.timeDelay = 0LL;
810 // If target reflect spell back to caster
811 if (target.missCondition==SPELL_MISS_REFLECT)
813 // Calculate reflected spell result on caster
814 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
816 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
817 target.reflectResult = SPELL_MISS_PARRY;
819 // Increase time interval for reflected spells by 1.5
820 target.timeDelay+=target.timeDelay>>1;
822 else
823 target.reflectResult = SPELL_MISS_NONE;
825 // Add target to list
826 m_UniqueTargetInfo.push_back(target);
829 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
831 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
832 if (unit)
833 AddUnitTarget(unit, effIndex);
836 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
838 if( m_spellInfo->Effect[effIndex]==0 )
839 return;
841 uint64 targetGUID = pVictim->GetGUID();
843 // Lookup target in already in list
844 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
846 if (targetGUID == ihit->targetGUID) // Found in list
848 ihit->effectMask |= 1<<effIndex; // Add only effect mask
849 return;
853 // This is new target calculate data for him
855 GOTargetInfo target;
856 target.targetGUID = targetGUID;
857 target.effectMask = 1<<effIndex;
858 target.processed = false; // Effects not apply on target
860 // Spell have speed - need calculate incoming time
861 if (m_spellInfo->speed > 0.0f)
863 // calculate spell incoming interval
864 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
865 if (dist < 5.0f) dist = 5.0f;
866 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
867 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
868 m_delayMoment = target.timeDelay;
870 else
871 target.timeDelay = 0LL;
873 // Add target to list
874 m_UniqueGOTargetInfo.push_back(target);
877 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
879 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
880 if (go)
881 AddGOTarget(go, effIndex);
884 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
886 if( m_spellInfo->Effect[effIndex]==0 )
887 return;
889 // Lookup target in already in list
890 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
892 if (pitem == ihit->item) // Found in list
894 ihit->effectMask |= 1<<effIndex; // Add only effect mask
895 return;
899 // This is new target add data
901 ItemTargetInfo target;
902 target.item = pitem;
903 target.effectMask = 1<<effIndex;
904 m_UniqueItemInfo.push_back(target);
907 void Spell::DoAllEffectOnTarget(TargetInfo *target)
909 if (target->processed) // Check target
910 return;
911 target->processed = true; // Target checked in apply effects procedure
913 // Get mask of effects for target
914 uint32 mask = target->effectMask;
916 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
917 if (!unit)
918 return;
920 // Get original caster (if exist) and calculate damage/healing from him data
921 Unit *caster = m_originalCasterGUID ? m_originalCaster : m_caster;
923 // Skip if m_originalCaster not avaiable
924 if (!caster)
925 return;
927 SpellMissInfo missInfo = target->missCondition;
928 // Need init unitTarget by default unit (can changed in code on reflect)
929 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
930 unitTarget = unit;
932 // Reset damage/healing counter
933 m_damage = 0;
934 m_healing = 0;
936 // Fill base trigger info
937 uint32 procAttacker = m_procAttacker;
938 uint32 procVictim = m_procVictim;
939 uint32 procEx = PROC_EX_NONE;
941 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
942 DoSpellHitOnUnit(unit, mask);
943 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
945 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
946 DoSpellHitOnUnit(m_caster, mask);
949 // All calculated do it!
950 // Do healing and triggers
951 if (m_healing)
953 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
954 uint32 addhealth = m_healing;
955 if (crit)
957 procEx |= PROC_EX_CRITICAL_HIT;
958 addhealth = caster->SpellCriticalBonus(m_spellInfo, addhealth, NULL);
960 else
961 procEx |= PROC_EX_NORMAL_HIT;
963 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
965 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
966 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
967 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
969 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
971 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
972 if(caster->GetTypeId()==TYPEID_PLAYER)
973 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
974 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
976 // Do damage and triggers
977 else if (m_damage)
979 // Fill base damage struct (unitTarget - is real spell target)
980 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
982 // Add bonuses and fill damageInfo struct
983 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
985 // Send log damage message to client
986 caster->SendSpellNonMeleeDamageLog(&damageInfo);
988 procEx = createProcExtendMask(&damageInfo, missInfo);
989 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
991 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
992 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
993 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
995 caster->DealSpellDamage(&damageInfo, true);
997 // Judgement of Blood
998 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1000 int32 damagePoint = damageInfo.damage * 33 / 100;
1001 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1003 // Bloodthirst
1004 else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && m_spellInfo->SpellFamilyFlags & 0x40000000000LL)
1006 uint32 BTAura = 0;
1007 switch(m_spellInfo->Id)
1009 case 23881: BTAura = 23885; break;
1010 case 23892: BTAura = 23886; break;
1011 case 23893: BTAura = 23887; break;
1012 case 23894: BTAura = 23888; break;
1013 case 25251: BTAura = 25252; break;
1014 case 30335: BTAura = 30339; break;
1015 default:
1016 sLog.outError("Spell::EffectSchoolDMG: Spell %u not handled in BTAura",m_spellInfo->Id);
1017 break;
1019 if (BTAura)
1020 m_caster->CastSpell(m_caster,BTAura,true);
1023 // Passive spell hits/misses or active spells only misses (only triggers)
1024 else
1026 // Fill base damage struct (unitTarget - is real spell target)
1027 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1028 procEx = createProcExtendMask(&damageInfo, missInfo);
1029 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1030 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1031 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1034 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1035 if(IS_CREATURE_GUID(target->targetGUID))
1037 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1038 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1039 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1040 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1042 if(((Creature*)unit)->AI())
1043 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1047 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1049 if(!unit || !effectMask)
1050 return;
1052 // Recheck immune (only for delayed spells)
1053 if( m_spellInfo->speed && (
1054 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1055 unit->IsImmunedToSpell(m_spellInfo)))
1057 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1058 return;
1061 if (unit->GetTypeId() == TYPEID_PLAYER)
1063 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1064 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1067 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1069 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1072 if( m_caster != unit )
1074 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1075 if (m_spellInfo->speed > 0.0f &&
1076 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1077 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1079 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1080 return;
1083 if( !m_caster->IsFriendlyTo(unit) )
1085 // for delayed spells ignore not visible explicit target
1086 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1088 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1089 return;
1092 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1094 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1096 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1097 unit->SetStandState(PLAYER_STATE_NONE);
1099 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1100 ((Creature*)unit)->AI()->AttackStart(m_caster);
1102 unit->SetInCombatWith(m_caster);
1103 m_caster->SetInCombatWith(unit);
1105 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1107 m_caster->SetContestedPvP(attackedPlayer);
1109 unit->AddThreat(m_caster, 0.0f);
1112 else
1114 // for delayed spells ignore negative spells (after duel end) for friendly targets
1115 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1117 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1118 return;
1121 // assisting case, healing and resurrection
1122 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1123 m_caster->SetContestedPvP();
1124 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1126 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1127 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1132 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1133 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1134 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1135 // Increase Diminishing on unit, current informations for actually casts will use values above
1136 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1137 unit->IncrDiminishing(m_diminishGroup);
1139 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1141 if (effectMask & (1<<effectNumber))
1143 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1144 if ( m_applyMultiplierMask & (1 << effectNumber) )
1146 // Get multiplier
1147 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1148 // Apply multiplier mods
1149 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1150 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1151 m_damageMultipliers[effectNumber] *= multiplier;
1157 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1159 if (target->processed) // Check target
1160 return;
1161 target->processed = true; // Target checked in apply effects procedure
1163 uint32 effectMask = target->effectMask;
1164 if(!effectMask)
1165 return;
1167 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1168 if(!go)
1169 return;
1171 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1172 if (effectMask & (1<<effectNumber))
1173 HandleEffects(NULL,NULL,go,effectNumber);
1175 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1176 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1177 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1178 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1181 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1183 uint32 effectMask = target->effectMask;
1184 if(!target->item || !effectMask)
1185 return;
1187 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1188 if (effectMask & (1<<effectNumber))
1189 HandleEffects(NULL, target->item, NULL, effectNumber);
1192 bool Spell::IsAliveUnitPresentInTargetList()
1194 // Not need check return true
1195 if (m_needAliveTargetMask == 0)
1196 return true;
1198 uint8 needAliveTargetMask = m_needAliveTargetMask;
1200 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1202 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1204 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1206 if (unit && unit->isAlive())
1207 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1211 // is all effects from m_needAliveTargetMask have alive targets
1212 return needAliveTargetMask==0;
1215 // Helper for Chain Healing
1216 // Spell target first
1217 // Raidmates then descending by injury suffered (MaxHealth - Health)
1218 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1219 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1221 const Unit* MainTarget;
1222 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1223 // functor for operator ">"
1224 bool operator()(Unit const* _Left, Unit const* _Right) const
1226 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1228 int32 ChainHealingHash(Unit const* Target) const
1230 if (Target == MainTarget)
1231 return 0;
1232 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1233 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1235 if (Target->GetHealth() == Target->GetMaxHealth())
1236 return 40000;
1237 else
1238 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1240 else
1241 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1245 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1247 public:
1248 const Unit* MainTarget;
1249 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1251 bool operator()(const Unit* Target)
1253 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1257 // Helper for targets nearest to the spell target
1258 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1259 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1261 const Unit* MainTarget;
1262 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1263 // functor for operator ">"
1264 bool operator()(const Unit* _Left, const Unit* _Right) const
1266 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1270 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1272 float radius;
1273 if (m_spellInfo->EffectRadiusIndex[i])
1274 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1275 else
1276 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1278 if(m_originalCaster)
1279 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1280 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1282 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1283 if(m_originalCaster)
1284 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1285 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1287 // Get spell max affected targets
1288 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1289 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1290 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1292 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1293 continue;
1294 unMaxTargets+=(*m)->GetModifier()->m_amount;
1296 switch(cur)
1298 case TARGET_TOTEM_EARTH:
1299 case TARGET_TOTEM_WATER:
1300 case TARGET_TOTEM_AIR:
1301 case TARGET_TOTEM_FIRE:
1302 case TARGET_SELF:
1303 case TARGET_SELF2:
1304 case TARGET_DYNAMIC_OBJECT:
1305 case TARGET_AREAEFFECT_CUSTOM:
1306 case TARGET_AREAEFFECT_CUSTOM_2:
1307 case TARGET_SUMMON:
1309 TagUnitMap.push_back(m_caster);
1310 break;
1312 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1314 m_targets.m_targetMask = 0;
1315 unMaxTargets = EffectChainTarget;
1316 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1318 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1319 Cell cell(p);
1320 cell.data.Part.reserved = ALL_DISTRICT;
1321 cell.SetNoCreate();
1323 std::list<Unit *> tempUnitMap;
1326 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1327 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1329 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1330 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1332 CellLock<GridReadGuard> cell_lock(cell, p);
1333 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1334 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1337 if(tempUnitMap.empty())
1338 break;
1340 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1342 //Now to get us a random target that's in the initial range of the spell
1343 uint32 t = 0;
1344 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1345 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1346 ++t, ++itr;
1348 if(!t)
1349 break;
1351 itr = tempUnitMap.begin();
1352 std::advance(itr, rand()%t);
1353 Unit *pUnitTarget = *itr;
1354 TagUnitMap.push_back(pUnitTarget);
1356 tempUnitMap.erase(itr);
1358 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1360 t = unMaxTargets - 1;
1361 Unit *prev = pUnitTarget;
1362 std::list<Unit*>::iterator next = tempUnitMap.begin();
1364 while(t && next != tempUnitMap.end() )
1366 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1367 break;
1369 if(!prev->IsWithinLOSInMap(*next))
1371 ++next;
1372 continue;
1375 prev = *next;
1376 TagUnitMap.push_back(prev);
1377 tempUnitMap.erase(next);
1378 tempUnitMap.sort(TargetDistanceOrder(prev));
1379 next = tempUnitMap.begin();
1381 --t;
1383 }break;
1384 case TARGET_PET:
1386 Pet* tmpUnit = m_caster->GetPet();
1387 if (!tmpUnit) break;
1388 TagUnitMap.push_back(tmpUnit);
1389 break;
1391 case TARGET_CHAIN_DAMAGE:
1393 if (EffectChainTarget <= 1)
1395 Unit* pUnitTarget = SelectMagnetTarget();
1396 if(pUnitTarget)
1397 TagUnitMap.push_back(pUnitTarget);
1399 else
1401 Unit* pUnitTarget = m_targets.getUnitTarget();
1402 if(!pUnitTarget)
1403 break;
1405 unMaxTargets = EffectChainTarget;
1407 float max_range;
1408 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1409 max_range = radius; //
1410 else
1411 //FIXME: This very like horrible hack and wrong for most spells
1412 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1414 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1415 Cell cell(p);
1416 cell.data.Part.reserved = ALL_DISTRICT;
1417 cell.SetNoCreate();
1419 Unit* originalCaster = GetOriginalCaster();
1420 if(originalCaster)
1422 std::list<Unit *> tempUnitMap;
1425 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1426 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1428 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1429 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1431 CellLock<GridReadGuard> cell_lock(cell, p);
1432 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1433 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1436 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1438 if(tempUnitMap.empty())
1439 break;
1441 if(*tempUnitMap.begin() == pUnitTarget)
1442 tempUnitMap.erase(tempUnitMap.begin());
1444 TagUnitMap.push_back(pUnitTarget);
1445 uint32 t = unMaxTargets - 1;
1446 Unit *prev = pUnitTarget;
1447 std::list<Unit*>::iterator next = tempUnitMap.begin();
1449 while(t && next != tempUnitMap.end() )
1451 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1452 break;
1454 if(!prev->IsWithinLOSInMap(*next))
1456 ++next;
1457 continue;
1460 prev = *next;
1461 TagUnitMap.push_back(prev);
1462 tempUnitMap.erase(next);
1463 tempUnitMap.sort(TargetDistanceOrder(prev));
1464 next = tempUnitMap.begin();
1466 --t;
1470 }break;
1471 case TARGET_ALL_ENEMY_IN_AREA:
1473 }break;
1474 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1476 // targets the ground, not the units in the area
1477 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1479 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1480 Cell cell(p);
1481 cell.data.Part.reserved = ALL_DISTRICT;
1482 cell.SetNoCreate();
1484 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1486 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1487 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1489 CellLock<GridReadGuard> cell_lock(cell, p);
1490 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1491 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1493 // exclude caster (this can be important if this not original caster)
1494 TagUnitMap.remove(m_caster);
1496 }break;
1497 case TARGET_DUELVSPLAYER_COORDINATES:
1499 if(Unit* currentTarget = m_targets.getUnitTarget())
1501 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1502 TagUnitMap.push_back(currentTarget);
1504 }break;
1505 case TARGET_ALL_PARTY_AROUND_CASTER:
1506 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1507 case TARGET_ALL_PARTY:
1508 case TARGET_ALL_RAID_AROUND_CASTER:
1510 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1511 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1513 if(pGroup)
1515 uint8 subgroup = pTarget->GetSubGroup();
1517 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1519 Player* Target = itr->getSource();
1521 // IsHostileTo check duel and controlled by enemy
1522 if( Target &&
1523 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1524 !m_caster->IsHostileTo(Target) )
1526 if( m_caster->IsWithinDistInMap(Target, radius) )
1527 TagUnitMap.push_back(Target);
1529 if(Pet* pet = Target->GetPet())
1530 if( m_caster->IsWithinDistInMap(pet, radius) )
1531 TagUnitMap.push_back(pet);
1535 else
1537 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1538 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1539 TagUnitMap.push_back(ownerOrSelf);
1540 if(Pet* pet = ownerOrSelf->GetPet())
1541 if( m_caster->IsWithinDistInMap(pet, radius) )
1542 TagUnitMap.push_back(pet);
1544 }break;
1545 case TARGET_SINGLE_FRIEND:
1546 case TARGET_SINGLE_FRIEND_2:
1548 if(m_targets.getUnitTarget())
1549 TagUnitMap.push_back(m_targets.getUnitTarget());
1550 }break;
1551 case TARGET_NONCOMBAT_PET:
1553 if(Unit* target = m_targets.getUnitTarget())
1554 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1555 TagUnitMap.push_back(target);
1556 }break;
1557 case TARGET_ALL_AROUND_CASTER:
1559 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1560 Cell cell(p);
1561 cell.data.Part.reserved = ALL_DISTRICT;
1562 cell.SetNoCreate();
1564 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1566 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1567 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1569 CellLock<GridReadGuard> cell_lock(cell, p);
1570 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1571 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1572 }break;
1573 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1575 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1576 Cell cell(p);
1577 cell.data.Part.reserved = ALL_DISTRICT;
1578 cell.SetNoCreate();
1580 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1582 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1583 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1585 CellLock<GridReadGuard> cell_lock(cell, p);
1586 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1587 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1588 }break;
1589 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1591 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1592 Cell cell(p);
1593 cell.data.Part.reserved = ALL_DISTRICT;
1594 cell.SetNoCreate();
1596 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1598 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1599 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1601 CellLock<GridReadGuard> cell_lock(cell, p);
1602 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1603 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1604 }break;
1605 // 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..)
1606 case TARGET_SINGLE_PARTY:
1608 Unit *target = m_targets.getUnitTarget();
1609 // Thoses spells apparently can't be casted on the caster.
1610 if( target && target != m_caster)
1612 // Can only be casted on group's members or its pets
1613 Group *pGroup = NULL;
1615 Unit* owner = m_caster->GetCharmerOrOwner();
1616 Unit *targetOwner = target->GetCharmerOrOwner();
1617 if(owner)
1619 if(owner->GetTypeId() == TYPEID_PLAYER)
1621 if( target == owner )
1623 TagUnitMap.push_back(target);
1624 break;
1626 pGroup = ((Player*)owner)->GetGroup();
1629 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1631 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1633 TagUnitMap.push_back(target);
1634 break;
1636 pGroup = ((Player*)m_caster)->GetGroup();
1639 if(pGroup)
1641 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1642 if(targetOwner)
1644 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1645 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1646 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1647 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1649 TagUnitMap.push_back(target);
1652 // 1Our target can be a player who is on our group
1653 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1655 TagUnitMap.push_back(target);
1659 }break;
1660 case TARGET_GAMEOBJECT:
1662 if(m_targets.getGOTarget())
1663 AddGOTarget(m_targets.getGOTarget(), i);
1664 }break;
1665 case TARGET_IN_FRONT_OF_CASTER:
1667 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1668 Cell cell(p);
1669 cell.data.Part.reserved = ALL_DISTRICT;
1670 cell.SetNoCreate();
1672 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1673 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1675 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1676 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1678 CellLock<GridReadGuard> cell_lock(cell, p);
1679 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1680 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1681 }break;
1682 case TARGET_DUELVSPLAYER:
1684 Unit *target = m_targets.getUnitTarget();
1685 if(target)
1687 if(m_caster->IsFriendlyTo(target))
1689 TagUnitMap.push_back(target);
1691 else
1693 Unit* pUnitTarget = SelectMagnetTarget();
1694 if(pUnitTarget)
1695 TagUnitMap.push_back(pUnitTarget);
1698 }break;
1699 case TARGET_GAMEOBJECT_ITEM:
1701 if(m_targets.getGOTargetGUID())
1702 AddGOTarget(m_targets.getGOTarget(), i);
1703 else if(m_targets.getItemTarget())
1704 AddItemTarget(m_targets.getItemTarget(), i);
1705 break;
1707 case TARGET_MASTER:
1709 if(Unit* owner = m_caster->GetCharmerOrOwner())
1710 TagUnitMap.push_back(owner);
1711 break;
1713 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1715 // targets the ground, not the units in the area
1716 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
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, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
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, *m_caster->GetMap());
1730 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1732 }break;
1733 case TARGET_MINION:
1735 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1736 TagUnitMap.push_back(m_caster);
1737 }break;
1738 case TARGET_SINGLE_ENEMY:
1740 Unit* pUnitTarget = SelectMagnetTarget();
1741 if(pUnitTarget)
1742 TagUnitMap.push_back(pUnitTarget);
1743 }break;
1744 case TARGET_AREAEFFECT_PARTY:
1746 Unit* owner = m_caster->GetCharmerOrOwner();
1747 Player *pTarget = NULL;
1749 if(owner)
1751 TagUnitMap.push_back(m_caster);
1752 if(owner->GetTypeId() == TYPEID_PLAYER)
1753 pTarget = (Player*)owner;
1755 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1757 if(Unit* target = m_targets.getUnitTarget())
1759 if( target->GetTypeId() != TYPEID_PLAYER)
1761 if(((Creature*)target)->isPet())
1763 Unit *targetOwner = target->GetOwner();
1764 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1765 pTarget = (Player*)targetOwner;
1768 else
1769 pTarget = (Player*)target;
1773 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1775 if(pGroup)
1777 uint8 subgroup = pTarget->GetSubGroup();
1779 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1781 Player* Target = itr->getSource();
1783 // IsHostileTo check duel and controlled by enemy
1784 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1786 if( pTarget->IsWithinDistInMap(Target, radius) )
1787 TagUnitMap.push_back(Target);
1789 if(Pet* pet = Target->GetPet())
1790 if( pTarget->IsWithinDistInMap(pet, radius) )
1791 TagUnitMap.push_back(pet);
1795 else if (owner)
1797 if(m_caster->IsWithinDistInMap(owner, radius))
1798 TagUnitMap.push_back(owner);
1800 else if(pTarget)
1802 TagUnitMap.push_back(pTarget);
1804 if(Pet* pet = pTarget->GetPet())
1805 if( m_caster->IsWithinDistInMap(pet, radius) )
1806 TagUnitMap.push_back(pet);
1809 }break;
1810 case TARGET_SCRIPT:
1812 if(m_targets.getUnitTarget())
1813 TagUnitMap.push_back(m_targets.getUnitTarget());
1814 if(m_targets.getItemTarget())
1815 AddItemTarget(m_targets.getItemTarget(), i);
1816 }break;
1817 case TARGET_SELF_FISHING:
1819 TagUnitMap.push_back(m_caster);
1820 }break;
1821 case TARGET_CHAIN_HEAL:
1823 Unit* pUnitTarget = m_targets.getUnitTarget();
1824 if(!pUnitTarget)
1825 break;
1827 if (EffectChainTarget <= 1)
1828 TagUnitMap.push_back(pUnitTarget);
1829 else
1831 unMaxTargets = EffectChainTarget;
1832 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1834 std::list<Unit *> tempUnitMap;
1837 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1838 Cell cell(p);
1839 cell.data.Part.reserved = ALL_DISTRICT;
1840 cell.SetNoCreate();
1842 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1844 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1845 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1847 CellLock<GridReadGuard> cell_lock(cell, p);
1848 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1849 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1853 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1854 tempUnitMap.push_front(m_caster);
1856 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1858 if(tempUnitMap.empty())
1859 break;
1861 if(*tempUnitMap.begin() == pUnitTarget)
1862 tempUnitMap.erase(tempUnitMap.begin());
1864 TagUnitMap.push_back(pUnitTarget);
1865 uint32 t = unMaxTargets - 1;
1866 Unit *prev = pUnitTarget;
1867 std::list<Unit*>::iterator next = tempUnitMap.begin();
1869 while(t && next != tempUnitMap.end() )
1871 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1872 break;
1874 if(!prev->IsWithinLOSInMap(*next))
1876 ++next;
1877 continue;
1880 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1882 next = tempUnitMap.erase(next);
1883 continue;
1886 prev = *next;
1887 TagUnitMap.push_back(prev);
1888 tempUnitMap.erase(next);
1889 tempUnitMap.sort(TargetDistanceOrder(prev));
1890 next = tempUnitMap.begin();
1892 --t;
1895 }break;
1896 case TARGET_CURRENT_ENEMY_COORDINATES:
1898 Unit* currentTarget = m_targets.getUnitTarget();
1899 if(currentTarget)
1901 TagUnitMap.push_back(currentTarget);
1902 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1903 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1905 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1906 Cell cell(p);
1907 cell.data.Part.reserved = ALL_DISTRICT;
1908 cell.SetNoCreate();
1909 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1910 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1911 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1912 CellLock<GridReadGuard> cell_lock(cell, p);
1913 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1914 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1917 }break;
1918 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1920 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1921 ? (Player*)m_targets.getUnitTarget() : NULL;
1923 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1924 if(pGroup)
1926 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1928 Player* Target = itr->getSource();
1930 // IsHostileTo check duel and controlled by enemy
1931 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1932 targetPlayer->getClass() == Target->getClass() &&
1933 !m_caster->IsHostileTo(Target) )
1935 TagUnitMap.push_back(Target);
1939 else if(m_targets.getUnitTarget())
1940 TagUnitMap.push_back(m_targets.getUnitTarget());
1941 break;
1943 case TARGET_TABLE_X_Y_Z_COORDINATES:
1945 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1946 if(st)
1948 if (st->target_mapId == m_caster->GetMapId())
1949 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1951 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1952 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1954 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1955 Cell cell(p);
1956 cell.data.Part.reserved = ALL_DISTRICT;
1957 cell.SetNoCreate();
1959 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1960 // Select friendly targets for positive effect
1961 if (IsPositiveEffect(m_spellInfo->Id, i))
1962 targetB = SPELL_TARGETS_FRIENDLY;
1964 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1966 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1967 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1969 CellLock<GridReadGuard> cell_lock(cell, p);
1970 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1971 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1974 else
1975 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1976 }break;
1977 case TARGET_BEHIND_VICTIM:
1979 Unit *pTarget = m_caster->getVictim();
1980 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1981 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1983 if(pTarget)
1985 float _target_x, _target_y, _target_z;
1986 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1987 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1988 m_targets.setDestination(_target_x, _target_y, _target_z);
1990 }break;
1991 case TARGET_DYNAMIC_OBJECT_COORDINATES:
1993 // if parent spell create dynamic object extract area from it
1994 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
1995 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
1996 }break;
1997 default:
1998 break;
2001 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2003 // make sure one unit is always removed per iteration
2004 uint32 removed_utarget = 0;
2005 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2007 next = itr;
2008 ++next;
2009 if (!*itr) continue;
2010 if ((*itr) == m_targets.getUnitTarget())
2012 TagUnitMap.erase(itr);
2013 removed_utarget = 1;
2014 // break;
2017 // remove random units from the map
2018 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2020 uint32 poz = urand(0, TagUnitMap.size()-1);
2021 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2023 if (!*itr) continue;
2024 if (!poz)
2026 TagUnitMap.erase(itr);
2027 break;
2031 // the player's target will always be added to the map
2032 if (removed_utarget && m_targets.getUnitTarget())
2033 TagUnitMap.push_back(m_targets.getUnitTarget());
2037 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2039 m_targets = *targets;
2041 m_spellState = SPELL_STATE_PREPARING;
2043 m_castPositionX = m_caster->GetPositionX();
2044 m_castPositionY = m_caster->GetPositionY();
2045 m_castPositionZ = m_caster->GetPositionZ();
2046 m_castOrientation = m_caster->GetOrientation();
2048 if(triggeredByAura)
2049 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2051 // create and add update event for this spell
2052 SpellEvent* Event = new SpellEvent(this);
2053 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2055 //Prevent casting at cast another spell (ServerSide check)
2056 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2058 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2059 finish(false);
2060 return;
2063 // Fill cost data
2064 m_powerCost = CalculatePowerCost();
2066 uint8 result = CanCast(true);
2067 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2069 if(triggeredByAura)
2071 SendChannelUpdate(0);
2072 triggeredByAura->SetAuraDuration(0);
2074 SendCastResult(result);
2075 finish(false);
2076 return;
2079 // Prepare data for triggers
2080 prepareDataForTriggerSystem();
2082 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2083 m_casttime = GetSpellCastTime(m_spellInfo, this);
2085 // set timer base at cast time
2086 ReSetTimer();
2088 // stealth must be removed at cast starting (at show channel bar)
2089 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2090 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2092 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2093 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2096 if(m_IsTriggeredSpell)
2097 cast(true);
2098 else
2100 m_caster->SetCurrentCastedSpell( this );
2101 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2102 SendSpellStart();
2106 void Spell::cancel()
2108 if(m_spellState == SPELL_STATE_FINISHED)
2109 return;
2111 m_autoRepeat = false;
2112 switch (m_spellState)
2114 case SPELL_STATE_PREPARING:
2115 case SPELL_STATE_DELAYED:
2117 SendInterrupted(0);
2118 SendCastResult(SPELL_FAILED_INTERRUPTED);
2119 } break;
2121 case SPELL_STATE_CASTING:
2123 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2125 if( ihit->missCondition == SPELL_MISS_NONE )
2127 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2128 if( unit && unit->isAlive() )
2129 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2133 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2134 SendChannelUpdate(0);
2135 SendInterrupted(0);
2136 SendCastResult(SPELL_FAILED_INTERRUPTED);
2137 } break;
2139 default:
2141 } break;
2144 finish(false);
2145 m_caster->RemoveDynObject(m_spellInfo->Id);
2146 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2149 void Spell::cast(bool skipCheck)
2151 SetExecutedCurrently(true);
2153 uint8 castResult = 0;
2155 // update pointers base at GUIDs to prevent access to non-existed already object
2156 UpdatePointers();
2158 // cancel at lost main target unit
2159 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2161 cancel();
2162 SetExecutedCurrently(false);
2163 return;
2166 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2167 m_caster->SetInFront(m_targets.getUnitTarget());
2169 castResult = CheckPower();
2170 if(castResult != 0)
2172 SendCastResult(castResult);
2173 finish(false);
2174 SetExecutedCurrently(false);
2175 return;
2178 // triggered cast called from Spell::prepare where it was already checked
2179 if(!skipCheck)
2181 castResult = CanCast(false);
2182 if(castResult != 0)
2184 SendCastResult(castResult);
2185 finish(false);
2186 SetExecutedCurrently(false);
2187 return;
2191 // Conflagrate - consumes immolate
2192 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2194 // for caster applied auras only
2195 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2196 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2198 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2199 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2201 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2202 break;
2207 // traded items have trade slot instead of guid in m_itemTargetGUID
2208 // set to real guid to be sent later to the client
2209 m_targets.updateTradeSlotItem();
2211 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2213 if (m_CastItem)
2214 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2216 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2219 // CAST SPELL
2220 SendSpellCooldown();
2222 TakePower();
2223 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2224 FillTargetMap();
2226 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2228 SetExecutedCurrently(false);
2229 return;
2232 SendCastResult(castResult);
2233 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2235 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2236 if (m_spellInfo->speed > 0.0f)
2239 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2240 // in case delayed spell remove item at cast delay start
2241 TakeCastItem();
2243 // Okay, maps created, now prepare flags
2244 m_immediateHandled = false;
2245 m_spellState = SPELL_STATE_DELAYED;
2246 SetDelayStart(0);
2248 else
2250 // Immediate spell, no big deal
2251 handle_immediate();
2254 SetExecutedCurrently(false);
2257 void Spell::handle_immediate()
2259 // start channeling if applicable
2260 if(IsChanneledSpell(m_spellInfo))
2262 int32 duration = GetSpellDuration(m_spellInfo);
2263 if (duration)
2265 m_spellState = SPELL_STATE_CASTING;
2266 SendChannelStart(duration);
2270 // process immediate effects (items, ground, etc.) also initialize some variables
2271 _handle_immediate_phase();
2273 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2274 DoAllEffectOnTarget(&(*ihit));
2276 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2277 DoAllEffectOnTarget(&(*ihit));
2279 // spell is finished, perform some last features of the spell here
2280 _handle_finish_phase();
2282 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2283 TakeCastItem();
2285 if(m_spellState != SPELL_STATE_CASTING)
2286 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2289 uint64 Spell::handle_delayed(uint64 t_offset)
2291 uint64 next_time = 0;
2293 if (!m_immediateHandled)
2295 _handle_immediate_phase();
2296 m_immediateHandled = true;
2299 // 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)
2300 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2302 if (ihit->processed == false)
2304 if ( ihit->timeDelay <= t_offset )
2305 DoAllEffectOnTarget(&(*ihit));
2306 else if( next_time == 0 || ihit->timeDelay < next_time )
2307 next_time = ihit->timeDelay;
2311 // now recheck gameobject targeting correctness
2312 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2314 if (ighit->processed == false)
2316 if ( ighit->timeDelay <= t_offset )
2317 DoAllEffectOnTarget(&(*ighit));
2318 else if( next_time == 0 || ighit->timeDelay < next_time )
2319 next_time = ighit->timeDelay;
2322 // All targets passed - need finish phase
2323 if (next_time == 0)
2325 // spell is finished, perform some last features of the spell here
2326 _handle_finish_phase();
2328 finish(true); // successfully finish spell cast
2330 // return zero, spell is finished now
2331 return 0;
2333 else
2335 // spell is unfinished, return next execution time
2336 return next_time;
2340 void Spell::_handle_immediate_phase()
2342 // handle some immediate features of the spell here
2343 HandleThreatSpells(m_spellInfo->Id);
2345 m_needSpellLog = IsNeedSendToClient();
2346 for(uint32 j = 0;j<3;j++)
2348 if(m_spellInfo->Effect[j]==0)
2349 continue;
2351 // apply Send Event effect to ground in case empty target lists
2352 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2354 HandleEffects(NULL,NULL,NULL, j);
2355 continue;
2358 // Don't do spell log, if is school damage spell
2359 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2360 m_needSpellLog = false;
2362 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2363 if(m_originalCaster)
2364 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2365 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2367 // initialize multipliers
2368 m_damageMultipliers[j] = 1.0f;
2369 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2370 (EffectChainTarget > 1) )
2371 m_applyMultiplierMask |= 1 << j;
2374 // initialize Diminishing Returns Data
2375 m_diminishLevel = DIMINISHING_LEVEL_1;
2376 m_diminishGroup = DIMINISHING_NONE;
2378 // process items
2379 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2380 DoAllEffectOnTarget(&(*ihit));
2382 // process ground
2383 for(uint32 j = 0;j<3;j++)
2385 // persistent area auras target only the ground
2386 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2387 HandleEffects(NULL,NULL,NULL, j);
2391 void Spell::_handle_finish_phase()
2393 // spell log
2394 if(m_needSpellLog)
2395 SendLogExecute();
2398 void Spell::SendSpellCooldown()
2400 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2401 return;
2403 Player* _player = (Player*)m_caster;
2404 // Add cooldown for max (disable spell)
2405 // Cooldown started on SendCooldownEvent call
2406 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2408 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2409 return;
2412 // init cooldown values
2413 uint32 cat = 0;
2414 int32 rec = -1;
2415 int32 catrec = -1;
2417 // some special item spells without correct cooldown in SpellInfo
2418 // cooldown information stored in item prototype
2419 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2421 if(m_CastItem)
2423 ItemPrototype const* proto = m_CastItem->GetProto();
2424 if(proto)
2426 for(int idx = 0; idx < 5; ++idx)
2428 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2430 cat = proto->Spells[idx].SpellCategory;
2431 rec = proto->Spells[idx].SpellCooldown;
2432 catrec = proto->Spells[idx].SpellCategoryCooldown;
2433 break;
2439 // if no cooldown found above then base at DBC data
2440 if(rec < 0 && catrec < 0)
2442 cat = m_spellInfo->Category;
2443 rec = m_spellInfo->RecoveryTime;
2444 catrec = m_spellInfo->CategoryRecoveryTime;
2447 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2448 // prevent 0 cooldowns set by another way
2449 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2450 rec = _player->GetAttackTime(RANGED_ATTACK);
2452 // Now we have cooldown data (if found any), time to apply mods
2453 if(rec > 0)
2454 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2456 if(catrec > 0)
2457 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2459 // replace negative cooldowns by 0
2460 if (rec < 0) rec = 0;
2461 if (catrec < 0) catrec = 0;
2463 // no cooldown after applying spell mods
2464 if( rec == 0 && catrec == 0)
2465 return;
2467 time_t curTime = time(NULL);
2469 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2470 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2472 // self spell cooldown
2473 if(recTime > 0)
2474 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2476 // category spells
2477 if (catrec > 0)
2479 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2480 if(i_scstore != sSpellCategoryStore.end())
2482 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2484 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2485 continue;
2487 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2493 void Spell::update(uint32 difftime)
2495 // update pointers based at it's GUIDs
2496 UpdatePointers();
2498 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2500 cancel();
2501 return;
2504 // check if the player caster has moved before the spell finished
2505 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2506 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2507 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2509 // always cancel for channeled spells
2510 if( m_spellState == SPELL_STATE_CASTING )
2511 cancel();
2512 // don't cancel for melee, autorepeat, triggered and instant spells
2513 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2514 cancel();
2517 switch(m_spellState)
2519 case SPELL_STATE_PREPARING:
2521 if(m_timer)
2523 if(difftime >= m_timer)
2524 m_timer = 0;
2525 else
2526 m_timer -= difftime;
2529 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2530 cast();
2531 } break;
2532 case SPELL_STATE_CASTING:
2534 if(m_timer > 0)
2536 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2538 // check if player has jumped before the channeling finished
2539 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2540 cancel();
2542 // check for incapacitating player states
2543 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2544 cancel();
2546 // check if player has turned if flag is set
2547 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2548 cancel();
2551 // check if there are alive targets left
2552 if (!IsAliveUnitPresentInTargetList())
2554 SendChannelUpdate(0);
2555 finish();
2558 if(difftime >= m_timer)
2559 m_timer = 0;
2560 else
2561 m_timer -= difftime;
2564 if(m_timer == 0)
2566 SendChannelUpdate(0);
2568 // channeled spell processed independently for quest targeting
2569 // cast at creature (or GO) quest objectives update at successful cast channel finished
2570 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2571 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2573 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2575 TargetInfo* target = &*ihit;
2576 if(!IS_CREATURE_GUID(target->targetGUID))
2577 continue;
2579 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2580 if (unit==NULL)
2581 continue;
2583 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2586 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2588 GOTargetInfo* target = &*ihit;
2590 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2591 if(!go)
2592 continue;
2594 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2598 finish();
2600 } break;
2601 default:
2603 }break;
2607 void Spell::finish(bool ok)
2609 if(!m_caster)
2610 return;
2612 if(m_spellState == SPELL_STATE_FINISHED)
2613 return;
2615 m_spellState = SPELL_STATE_FINISHED;
2617 // other code related only to successfully finished spells
2618 if(!ok)
2619 return;
2621 //remove spell mods
2622 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2623 ((Player*)m_caster)->RemoveSpellMods(this);
2625 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2626 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2627 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2629 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2630 uint32 auraSpellIdx = (*i)->GetEffIndex();
2631 if (IsAffectedByAura((*i)))
2633 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2634 if( ihit->effectMask & (1<<auraSpellIdx) )
2636 // check m_caster->GetGUID() let load auras at login and speedup most often case
2637 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2638 if (unit && unit->isAlive())
2640 // Calculate chance at that moment (can be depend for example from combo points)
2641 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2643 if(roll_chance_i(chance))
2644 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2650 // Heal caster for all health leech from all targets
2651 if (m_healthLeech)
2653 m_caster->ModifyHealth(m_healthLeech);
2654 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2657 if (IsMeleeAttackResetSpell())
2659 m_caster->resetAttackTimer(BASE_ATTACK);
2660 if(m_caster->haveOffhandWeapon())
2661 m_caster->resetAttackTimer(OFF_ATTACK);
2664 /*if (IsRangedAttackResetSpell())
2665 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2667 // Clear combo at finish state
2668 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2670 // Not drop combopoints if negative spell and if any miss on enemy exist
2671 bool needDrop = true;
2672 if (!IsPositiveSpell(m_spellInfo->Id))
2673 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2674 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2676 needDrop = false;
2677 break;
2679 if (needDrop)
2680 ((Player*)m_caster)->ClearComboPoints();
2683 // Post effects apply on spell targets in some spells
2684 if(!m_UniqueTargetInfo.empty())
2686 uint32 spellId = 0;
2687 switch(m_spellInfo->SpellFamilyName)
2689 case SPELLFAMILY_GENERIC:
2691 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2692 spellId = 11196; // Recently Bandaged
2693 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2694 spellId = 23230; // Blood Fury - Healing Reduction
2695 break;
2697 case SPELLFAMILY_MAGE:
2699 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2700 spellId = 41425; // Hypothermia
2701 break;
2703 case SPELLFAMILY_PRIEST:
2705 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2706 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2707 spellId = 6788; // Weakened Soul
2708 break;
2710 case SPELLFAMILY_PALADIN:
2712 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2713 spellId = 25771; // Forbearance
2714 break;
2716 case SPELLFAMILY_SHAMAN:
2718 if (m_spellInfo->Id == 2825) // Bloodlust
2719 spellId = 57724; // Sated
2720 else if (m_spellInfo->Id == 32182) // Heroism
2721 spellId = 57723; // Exhaustion
2722 break;
2724 default:
2725 break;
2727 if (spellId)
2729 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2731 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2732 if (unit)
2734 // TODO: fix me use cast spell (now post spell can immune by this spell)
2735 // m_caster->CastSpell(unit, spellId, true, m_CastItem);
2736 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(spellId);
2737 if (!AdditionalSpellInfo)
2738 continue;
2739 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, 0, &m_currentBasePoints[0], unit, m_caster, m_CastItem);
2740 unit->AddAura(AdditionalAura);
2745 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2746 if(!m_TriggerSpells.empty())
2747 TriggerSpell();
2749 // Stop Attack for some spells
2750 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2751 m_caster->AttackStop();
2754 void Spell::SendCastResult(uint8 result)
2756 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2757 return;
2759 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2760 return;
2762 if(result != 0)
2764 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2765 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2766 data << uint32(m_spellInfo->Id);
2767 data << uint8(result); // problem
2768 switch (result)
2770 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2771 data << uint32(m_spellInfo->RequiresSpellFocus);
2772 break;
2773 case SPELL_FAILED_REQUIRES_AREA:
2774 // hardcode areas limitation case
2775 switch(m_spellInfo->Id)
2777 case 41617: // Cenarion Mana Salve
2778 case 41619: // Cenarion Healing Salve
2779 data << uint32(3905);
2780 break;
2781 case 41618: // Bottled Nethergon Energy
2782 case 41620: // Bottled Nethergon Vapor
2783 data << uint32(3842);
2784 break;
2785 case 45373: // Bloodberry Elixir
2786 data << uint32(4075);
2787 break;
2788 default: // default case (don't must be)
2789 data << uint32(0);
2790 break;
2792 break;
2793 case SPELL_FAILED_TOTEMS:
2794 if(m_spellInfo->Totem[0])
2795 data << uint32(m_spellInfo->Totem[0]);
2796 if(m_spellInfo->Totem[1])
2797 data << uint32(m_spellInfo->Totem[1]);
2798 break;
2799 case SPELL_FAILED_TOTEM_CATEGORY:
2800 if(m_spellInfo->TotemCategory[0])
2801 data << uint32(m_spellInfo->TotemCategory[0]);
2802 if(m_spellInfo->TotemCategory[1])
2803 data << uint32(m_spellInfo->TotemCategory[1]);
2804 break;
2805 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2806 data << uint32(m_spellInfo->EquippedItemClass);
2807 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2808 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2809 break;
2811 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2815 void Spell::SendSpellStart()
2817 if(!IsNeedSendToClient())
2818 return;
2820 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2822 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2823 if(IsRangedSpell())
2824 castFlags |= CAST_FLAG_AMMO;
2826 if(m_spellInfo->runeCostID)
2827 castFlags |= CAST_FLAG_UNKNOWN10;
2829 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2831 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2832 if(m_CastItem)
2833 data.append(m_CastItem->GetPackGUID());
2834 else
2835 data.append(m_caster->GetPackGUID());
2837 data.append(m_caster->GetPackGUID());
2838 data << uint8(m_cast_count); // pending spell cast?
2839 data << uint32(m_spellInfo->Id); // spellId
2840 data << uint32(castFlags); // cast flags
2841 data << uint32(m_timer); // delay?
2843 m_targets.write(&data);
2845 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2846 data << uint32(0);
2848 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2850 uint8 v1 = 0;//m_runesState;
2851 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2852 data << uint8(v1); // runes state before
2853 data << uint8(v2); // runes state after
2854 for(uint8 i = 0; i < MAX_RUNES; ++i)
2856 uint8 m = (1 << i);
2857 if(m & v1) // usable before...
2858 if(!(m & v2)) // ...but on cooldown now...
2859 data << uint8(0); // some unknown byte (time?)
2863 if ( castFlags & CAST_FLAG_AMMO )
2864 WriteAmmoToPacket(&data);
2866 m_caster->SendMessageToSet(&data, true);
2869 void Spell::SendSpellGo()
2871 // not send invisible spell casting
2872 if(!IsNeedSendToClient())
2873 return;
2875 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2877 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2879 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2880 if(IsRangedSpell())
2881 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2883 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2885 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2886 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2887 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2890 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2891 if(m_CastItem)
2892 data.append(m_CastItem->GetPackGUID());
2893 else
2894 data.append(m_caster->GetPackGUID());
2896 data.append(m_caster->GetPackGUID());
2897 data << uint8(m_cast_count); // pending spell cast?
2898 data << uint32(m_spellInfo->Id); // spellId
2899 data << uint32(castFlags); // cast flags
2900 data << uint32(getMSTime()); // timestamp
2902 WriteSpellGoTargets(&data);
2904 m_targets.write(&data);
2906 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2907 data << uint32(0);
2909 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2911 uint8 v1 = m_runesState;
2912 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2913 data << uint8(v1); // runes state before
2914 data << uint8(v2); // runes state after
2915 for(uint8 i = 0; i < MAX_RUNES; ++i)
2917 uint8 m = (1 << i);
2918 if(m & v1) // usable before...
2919 if(!(m & v2)) // ...but on cooldown now...
2920 data << uint8(0); // some unknown byte (time?)
2924 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2926 data << float(0);
2927 data << uint32(0);
2930 if ( castFlags & CAST_FLAG_AMMO )
2931 WriteAmmoToPacket(&data);
2933 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2935 data << uint32(0);
2936 data << uint32(0);
2939 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2941 data << uint8(0);
2944 m_caster->SendMessageToSet(&data, true);
2947 void Spell::WriteAmmoToPacket( WorldPacket * data )
2949 uint32 ammoInventoryType = 0;
2950 uint32 ammoDisplayID = 0;
2952 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2954 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2955 if(pItem)
2957 ammoInventoryType = pItem->GetProto()->InventoryType;
2958 if( ammoInventoryType == INVTYPE_THROWN )
2959 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2960 else
2962 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2963 if(ammoID)
2965 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2966 if(pProto)
2968 ammoDisplayID = pProto->DisplayInfoID;
2969 ammoInventoryType = pProto->InventoryType;
2972 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2974 ammoDisplayID = 5996; // normal arrow
2975 ammoInventoryType = INVTYPE_AMMO;
2980 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2982 *data << uint32(ammoDisplayID);
2983 *data << uint32(ammoInventoryType);
2986 void Spell::WriteSpellGoTargets( WorldPacket * data )
2988 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
2989 uint32 miss = 0;
2990 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2992 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
2994 // possibly SPELL_MISS_IMMUNE2 for this??
2995 ihit->missCondition = SPELL_MISS_IMMUNE2;
2996 miss++;
2998 else if ((*ihit).missCondition == SPELL_MISS_NONE)
2999 hit++;
3000 else
3001 miss++;
3004 *data << (uint8)hit;
3005 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3006 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3007 *data << uint64(ihit->targetGUID);
3009 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3010 *data << uint64(ighit->targetGUID); // Always hits
3012 *data << (uint8)miss;
3013 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3015 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3017 *data << uint64(ihit->targetGUID);
3018 *data << uint8(ihit->missCondition);
3019 if( ihit->missCondition == SPELL_MISS_REFLECT )
3020 *data << uint8(ihit->reflectResult);
3025 void Spell::SendLogExecute()
3027 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3029 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3031 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3032 data.append(m_caster->GetPackGUID());
3033 else
3034 data.append(target->GetPackGUID());
3036 data << uint32(m_spellInfo->Id);
3037 uint32 count1 = 1;
3038 data << uint32(count1); // count1 (effect count?)
3039 for(uint32 i = 0; i < count1; ++i)
3041 data << uint32(m_spellInfo->Effect[0]); // spell effect
3042 uint32 count2 = 1;
3043 data << uint32(count2); // count2 (target count?)
3044 for(uint32 j = 0; j < count2; ++j)
3046 switch(m_spellInfo->Effect[0])
3048 case SPELL_EFFECT_POWER_DRAIN:
3049 if(Unit *unit = m_targets.getUnitTarget())
3050 data.append(unit->GetPackGUID());
3051 else
3052 data << uint8(0);
3053 data << uint32(0);
3054 data << uint32(0);
3055 data << float(0);
3056 break;
3057 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3058 if(Unit *unit = m_targets.getUnitTarget())
3059 data.append(unit->GetPackGUID());
3060 else
3061 data << uint8(0);
3062 data << uint32(0); // count?
3063 break;
3064 case SPELL_EFFECT_INTERRUPT_CAST:
3065 if(Unit *unit = m_targets.getUnitTarget())
3066 data.append(unit->GetPackGUID());
3067 else
3068 data << uint8(0);
3069 data << uint32(0); // spellid
3070 break;
3071 case SPELL_EFFECT_DURABILITY_DAMAGE:
3072 if(Unit *unit = m_targets.getUnitTarget())
3073 data.append(unit->GetPackGUID());
3074 else
3075 data << uint8(0);
3076 data << uint32(0);
3077 data << uint32(0);
3078 break;
3079 case SPELL_EFFECT_OPEN_LOCK:
3080 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3081 if(Item *item = m_targets.getItemTarget())
3082 data.append(item->GetPackGUID());
3083 else
3084 data << uint8(0);
3085 break;
3086 case SPELL_EFFECT_CREATE_ITEM:
3087 case SPELL_EFFECT_CREATE_ITEM_2:
3088 data << uint32(m_spellInfo->EffectItemType[0]);
3089 break;
3090 case SPELL_EFFECT_SUMMON:
3091 case SPELL_EFFECT_TRANS_DOOR:
3092 case SPELL_EFFECT_SUMMON_PET:
3093 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3094 case SPELL_EFFECT_CREATE_HOUSE:
3095 case SPELL_EFFECT_DUEL:
3096 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3097 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3098 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3099 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3100 if(Unit *unit = m_targets.getUnitTarget())
3101 data.append(unit->GetPackGUID());
3102 else if(m_targets.getItemTargetGUID())
3103 data.appendPackGUID(m_targets.getItemTargetGUID());
3104 else if(GameObject *go = m_targets.getGOTarget())
3105 data.append(go->GetPackGUID());
3106 else
3107 data << uint8(0); // guid
3108 break;
3109 case SPELL_EFFECT_FEED_PET:
3110 data << uint32(m_targets.getItemTargetEntry());
3111 break;
3112 case SPELL_EFFECT_DISMISS_PET:
3113 if(Unit *unit = m_targets.getUnitTarget())
3114 data.append(unit->GetPackGUID());
3115 else
3116 data << uint8(0);
3117 break;
3118 case SPELL_EFFECT_RESURRECT:
3119 case SPELL_EFFECT_RESURRECT_NEW:
3120 if(Unit *unit = m_targets.getUnitTarget())
3121 data.append(unit->GetPackGUID());
3122 else
3123 data << uint8(0);
3124 break;
3125 default:
3126 return;
3131 m_caster->SendMessageToSet(&data, true);
3134 void Spell::SendInterrupted(uint8 result)
3136 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3137 data.append(m_caster->GetPackGUID());
3138 data << uint8(m_cast_count);
3139 data << uint32(m_spellInfo->Id);
3140 data << uint8(result);
3141 m_caster->SendMessageToSet(&data, true);
3143 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3144 data.append(m_caster->GetPackGUID());
3145 data << uint8(m_cast_count);
3146 data << uint32(m_spellInfo->Id);
3147 data << uint8(result);
3148 m_caster->SendMessageToSet(&data, true);
3151 void Spell::SendChannelUpdate(uint32 time)
3153 if(time == 0)
3155 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3156 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3159 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3160 return;
3162 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3163 data.append(m_caster->GetPackGUID());
3164 data << uint32(time);
3166 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3169 void Spell::SendChannelStart(uint32 duration)
3171 WorldObject* target = NULL;
3173 // select first not resisted target from target list for _0_ effect
3174 if(!m_UniqueTargetInfo.empty())
3176 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3178 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3180 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3181 break;
3185 else if(!m_UniqueGOTargetInfo.empty())
3187 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3189 if(itr->effectMask & (1<<0) )
3191 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3192 break;
3197 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3199 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3200 data.append(m_caster->GetPackGUID());
3201 data << uint32(m_spellInfo->Id);
3202 data << uint32(duration);
3204 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3207 m_timer = duration;
3208 if(target)
3209 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3210 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3213 void Spell::SendResurrectRequest(Player* target)
3215 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3216 // However, the packet structure differs slightly
3218 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3220 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3221 data << uint64(m_caster->GetGUID());
3222 data << uint32(strlen(sentName)+1);
3224 data << sentName;
3225 data << uint8(0);
3227 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3228 target->GetSession()->SendPacket(&data);
3231 void Spell::SendPlaySpellVisual(uint32 SpellID)
3233 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3234 return;
3236 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3237 data << uint64(m_caster->GetGUID());
3238 data << uint32(SpellID); // spell visual id?
3239 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3242 void Spell::TakeCastItem()
3244 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3245 return;
3247 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3248 if(m_IsTriggeredSpell)
3249 return;
3251 ItemPrototype const *proto = m_CastItem->GetProto();
3253 if(!proto)
3255 // This code is to avoid a crash
3256 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3257 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3258 return;
3261 bool expendable = false;
3262 bool withoutCharges = false;
3264 for (int i = 0; i<5; i++)
3266 if (proto->Spells[i].SpellId)
3268 // item has limited charges
3269 if (proto->Spells[i].SpellCharges)
3271 if (proto->Spells[i].SpellCharges < 0)
3272 expendable = true;
3274 int32 charges = m_CastItem->GetSpellCharges(i);
3276 // item has charges left
3277 if (charges)
3279 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3280 if (proto->Stackable == 1)
3281 m_CastItem->SetSpellCharges(i, charges);
3282 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3285 // all charges used
3286 withoutCharges = (charges == 0);
3291 if (expendable && withoutCharges)
3293 uint32 count = 1;
3294 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3296 // prevent crash at access to deleted m_targets.getItemTarget
3297 if(m_CastItem==m_targets.getItemTarget())
3298 m_targets.setItemTarget(NULL);
3300 m_CastItem = NULL;
3304 void Spell::TakePower()
3306 if(m_CastItem || m_triggeredByAuraSpell)
3307 return;
3309 // health as power used
3310 if(m_spellInfo->powerType == POWER_HEALTH)
3312 m_caster->ModifyHealth( -(int32)m_powerCost );
3313 return;
3316 if(m_spellInfo->powerType >= MAX_POWERS)
3318 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3319 return;
3322 Powers powerType = Powers(m_spellInfo->powerType);
3324 if(powerType == POWER_RUNE)
3326 TakeRunePower();
3327 return;
3330 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3332 // Set the five second timer
3333 if (powerType == POWER_MANA && m_powerCost > 0)
3334 m_caster->SetLastManaUse(getMSTime());
3337 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3339 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3340 return 0;
3342 Player *plr = (Player*)m_caster;
3344 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3345 return 0;
3347 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3349 if(!src)
3350 return 0;
3352 if(src->NoRuneCost())
3353 return 0;
3355 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3357 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3359 runeCost[i] = src->RuneCost[i];
3362 runeCost[RUNE_DEATH] = 0; // calculated later
3364 for(uint32 i = 0; i < MAX_RUNES; ++i)
3366 uint8 rune = plr->GetCurrentRune(i);
3367 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3369 runeCost[rune]--;
3373 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3375 if(runeCost[i] > 0)
3377 runeCost[RUNE_DEATH] += runeCost[i];
3381 if(runeCost[RUNE_DEATH] > 0)
3382 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3384 return 0;
3387 void Spell::TakeRunePower()
3389 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3390 return;
3392 Player *plr = (Player*)m_caster;
3394 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3395 return;
3397 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3399 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3400 return;
3402 m_runesState = plr->GetRunesState(); // store previous state
3404 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3406 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3408 runeCost[i] = src->RuneCost[i];
3411 runeCost[RUNE_DEATH] = 0; // calculated later
3413 for(uint32 i = 0; i < MAX_RUNES; ++i)
3415 uint8 rune = plr->GetCurrentRune(i);
3416 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3418 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3419 runeCost[rune]--;
3423 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3425 if(runeCost[RUNE_DEATH] > 0)
3427 for(uint32 i = 0; i < MAX_RUNES; ++i)
3429 uint8 rune = plr->GetCurrentRune(i);
3430 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3432 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3433 runeCost[rune]--;
3434 plr->ConvertRune(i, plr->GetBaseRune(i));
3435 if(runeCost[RUNE_DEATH] == 0)
3436 break;
3441 // you can gain some runic power when use runes
3442 float rp = src->runePowerGain;;
3443 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3444 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3447 void Spell::TakeReagents()
3449 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3450 return;
3452 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3453 return;
3455 Player* p_caster = (Player*)m_caster;
3456 if (p_caster->CanNoReagentCast(m_spellInfo))
3457 return;
3459 for(uint32 x=0;x<8;x++)
3461 if(m_spellInfo->Reagent[x] <= 0)
3462 continue;
3464 uint32 itemid = m_spellInfo->Reagent[x];
3465 uint32 itemcount = m_spellInfo->ReagentCount[x];
3467 // if CastItem is also spell reagent
3468 if (m_CastItem)
3470 ItemPrototype const *proto = m_CastItem->GetProto();
3471 if( proto && proto->ItemId == itemid )
3473 for(int s=0;s<5;s++)
3475 // CastItem will be used up and does not count as reagent
3476 int32 charges = m_CastItem->GetSpellCharges(s);
3477 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3479 ++itemcount;
3480 break;
3484 m_CastItem = NULL;
3488 // if getItemTarget is also spell reagent
3489 if (m_targets.getItemTargetEntry()==itemid)
3490 m_targets.setItemTarget(NULL);
3492 p_caster->DestroyItemCount(itemid, itemcount, true);
3496 void Spell::HandleThreatSpells(uint32 spellId)
3498 if(!m_targets.getUnitTarget() || !spellId)
3499 return;
3501 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3502 return;
3504 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3505 if(!threatSpell)
3506 return;
3508 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3510 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3513 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3515 unitTarget = pUnitTarget;
3516 itemTarget = pItemTarget;
3517 gameObjTarget = pGOTarget;
3519 uint8 eff = m_spellInfo->Effect[i];
3521 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3523 sLog.outDebug( "Spell: Effect : %u", eff);
3525 if(eff<TOTAL_SPELL_EFFECTS)
3527 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3528 (*this.*SpellEffects[eff])(i);
3531 else
3533 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3534 if (m_CastItem)
3535 EffectEnchantItemTmp(i);
3536 else
3538 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3539 eff, m_spellInfo->Id);
3545 void Spell::TriggerSpell()
3547 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3549 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3550 spell->prepare(&m_targets); // use original spell original targets
3554 uint8 Spell::CanCast(bool strict)
3556 // check cooldowns to prevent cheating
3557 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3559 if(m_triggeredByAuraSpell)
3560 return SPELL_FAILED_DONT_REPORT;
3561 else
3562 return SPELL_FAILED_NOT_READY;
3565 // only allow triggered spells if at an ended battleground
3566 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3567 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3568 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3569 return SPELL_FAILED_DONT_REPORT;
3571 // only check at first call, Stealth auras are already removed at second call
3572 // for now, ignore triggered spells
3573 if( strict && !m_IsTriggeredSpell)
3575 bool checkForm = true;
3576 // Ignore form req aura
3577 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3578 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3580 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3581 continue;
3582 checkForm = false;
3583 break;
3585 if (checkForm)
3587 // Cannot be used in this stance/form
3588 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3589 return shapeError;
3591 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3592 return SPELL_FAILED_ONLY_STEALTHED;
3596 // caster state requirements
3597 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3598 return SPELL_FAILED_CASTER_AURASTATE;
3599 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3600 return SPELL_FAILED_CASTER_AURASTATE;
3602 // Caster aura req check if need
3603 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3604 return SPELL_FAILED_CASTER_AURASTATE;
3605 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3606 return SPELL_FAILED_CASTER_AURASTATE;
3608 // cancel autorepeat spells if cast start when moving
3609 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3610 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3612 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3613 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3614 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3615 return SPELL_FAILED_MOVING;
3618 Unit *target = m_targets.getUnitTarget();
3620 if(target)
3622 // target state requirements (not allowed state), apply to self also
3623 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3624 return SPELL_FAILED_TARGET_AURASTATE;
3626 // Target aura req check if need
3627 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3628 return SPELL_FAILED_CASTER_AURASTATE;
3629 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3630 return SPELL_FAILED_CASTER_AURASTATE;
3632 if(target != m_caster)
3634 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3635 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3636 return SPELL_FAILED_TARGET_AURASTATE;
3638 // Not allow casting on flying player
3639 if (target->isInFlight())
3640 return SPELL_FAILED_BAD_TARGETS;
3642 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3643 return SPELL_FAILED_LINE_OF_SIGHT;
3645 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3646 // this case can be triggered if rank not found (too low-level target for first rank)
3647 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3649 for(int i=0;i<3;i++)
3651 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3652 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3653 return SPELL_FAILED_LOWLEVEL;
3657 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3659 // Additional check for some spells
3660 // If 0 spell effect empty - client not send target data (need use selection)
3661 // TODO: check it on next client version
3662 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3663 m_spellInfo->Effect[0] == 0 && m_spellInfo->EffectImplicitTargetA[1] != TARGET_SELF)
3665 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3666 m_targets.setUnitTarget(target);
3667 else
3668 return SPELL_FAILED_BAD_TARGETS;
3672 // check pet presents
3673 for(int j=0;j<3;j++)
3675 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3677 target = m_caster->GetPet();
3678 if(!target)
3680 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3681 return SPELL_FAILED_DONT_REPORT;
3682 else
3683 return SPELL_FAILED_NO_PET;
3685 break;
3689 //check creature type
3690 //ignore self casts (including area casts when caster selected as target)
3691 if(target != m_caster)
3693 if(!CheckTargetCreatureType(target))
3695 if(target->GetTypeId()==TYPEID_PLAYER)
3696 return SPELL_FAILED_TARGET_IS_PLAYER;
3697 else
3698 return SPELL_FAILED_BAD_TARGETS;
3702 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3703 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3704 if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3706 // check correctness positive/negative cast target (pet cast real check and cheating check)
3707 if(IsPositiveSpell(m_spellInfo->Id))
3709 if(m_caster->IsHostileTo(target))
3710 return SPELL_FAILED_BAD_TARGETS;
3712 else
3714 if(m_caster->IsFriendlyTo(target))
3715 return SPELL_FAILED_BAD_TARGETS;
3719 if(IsPositiveSpell(m_spellInfo->Id))
3721 if(target->IsImmunedToSpell(m_spellInfo))
3722 return SPELL_FAILED_TARGET_AURASTATE;
3725 //Must be behind the target.
3726 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3728 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3729 if( m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || m_spellInfo->SpellFamilyFlags != 0x0000000000020000LL )
3731 SendInterrupted(2);
3732 return SPELL_FAILED_NOT_BEHIND;
3736 //Target must be facing you.
3737 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3739 SendInterrupted(2);
3740 return SPELL_FAILED_NOT_INFRONT;
3743 // check if target is in combat
3744 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3746 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3749 // Spell casted only on battleground
3750 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId()==TYPEID_PLAYER)
3751 if(!((Player*)m_caster)->InBattleGround())
3752 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3754 // do not allow spells to be cast in arenas
3755 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3756 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3757 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3758 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3759 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3760 if(mapEntry->IsBattleArena())
3761 return SPELL_FAILED_NOT_IN_ARENA;
3763 // zone check
3764 if(uint8 res= GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3765 return res;
3767 // not let players cast spells at mount (and let do it to creatures)
3768 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3769 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3771 if(m_caster->isInFlight())
3772 return SPELL_FAILED_NOT_FLYING;
3773 else
3774 return SPELL_FAILED_NOT_MOUNTED;
3777 // always (except passive spells) check items (focus object can be required for any type casts)
3778 if(!IsPassiveSpell(m_spellInfo->Id))
3779 if(uint8 castResult = CheckItems())
3780 return castResult;
3782 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3783 if(m_UniqueTargetInfo.empty()) // skip second canCast apply (for delayed spells for example)
3785 for(uint8 j = 0; j < 3; j++)
3787 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3788 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3789 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3790 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3792 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3793 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3794 if(lower==upper)
3795 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);
3797 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3798 float range = GetSpellMaxRange(srange);
3800 Creature* creatureScriptTarget = NULL;
3801 GameObject* goScriptTarget = NULL;
3803 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3805 switch(i_spellST->second.type)
3807 case SPELL_TARGET_TYPE_GAMEOBJECT:
3809 GameObject* p_GameObject = NULL;
3811 if(i_spellST->second.targetEntry)
3813 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3814 Cell cell(p);
3815 cell.data.Part.reserved = ALL_DISTRICT;
3817 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3818 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
3820 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3821 CellLock<GridReadGuard> cell_lock(cell, p);
3822 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3824 if(p_GameObject)
3826 // remember found target and range, next attempt will find more near target with another entry
3827 creatureScriptTarget = NULL;
3828 goScriptTarget = p_GameObject;
3829 range = go_check.GetLastRange();
3832 else if( focusObject ) //Focus Object
3834 float frange = m_caster->GetDistance(focusObject);
3835 if(range >= frange)
3837 creatureScriptTarget = NULL;
3838 goScriptTarget = focusObject;
3839 range = frange;
3842 break;
3844 case SPELL_TARGET_TYPE_CREATURE:
3845 case SPELL_TARGET_TYPE_DEAD:
3846 default:
3848 Creature *p_Creature = NULL;
3850 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3851 Cell cell(p);
3852 cell.data.Part.reserved = ALL_DISTRICT;
3853 cell.SetNoCreate(); // Really don't know what is that???
3855 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
3856 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
3858 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
3860 CellLock<GridReadGuard> cell_lock(cell, p);
3861 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
3863 if(p_Creature )
3865 creatureScriptTarget = p_Creature;
3866 goScriptTarget = NULL;
3867 range = u_check.GetLastRange();
3869 break;
3874 if(creatureScriptTarget)
3876 // store coordinates for TARGET_SCRIPT_COORDINATES
3877 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3878 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3880 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
3882 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3883 AddUnitTarget(creatureScriptTarget, j);
3885 // store explicit target for TARGET_SCRIPT
3886 else
3887 AddUnitTarget(creatureScriptTarget, j);
3889 else if(goScriptTarget)
3891 // store coordinates for TARGET_SCRIPT_COORDINATES
3892 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3893 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3895 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
3897 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
3898 AddGOTarget(goScriptTarget, j);
3900 // store explicit target for TARGET_SCRIPT
3901 else
3902 AddGOTarget(goScriptTarget, j);
3904 //Missing DB Entry or targets for this spellEffect.
3905 else
3907 // not report target not existence for triggered spells
3908 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
3909 return SPELL_FAILED_DONT_REPORT;
3910 else
3911 return SPELL_FAILED_BAD_TARGETS;
3917 if(!m_IsTriggeredSpell)
3918 if(uint8 castResult = CheckRange(strict))
3919 return castResult;
3922 if(uint8 castResult = CheckPower())
3923 return castResult;
3926 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
3927 if(uint8 castResult = CheckCasterAuras())
3928 return castResult;
3930 for (int i = 0; i < 3; i++)
3932 // for effects of spells that have only one target
3933 switch(m_spellInfo->Effect[i])
3935 case SPELL_EFFECT_DUMMY:
3937 if(m_spellInfo->SpellIconID == 1648) // Execute
3939 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3940 return SPELL_FAILED_BAD_TARGETS;
3942 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
3944 if(m_caster->IsInWater())
3945 return SPELL_FAILED_ONLY_ABOVEWATER;
3947 else if(m_spellInfo->SpellIconID==156) // Holy Shock
3949 // spell different for friends and enemies
3950 // hart version required facing
3951 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3952 return SPELL_FAILED_UNIT_NOT_INFRONT;
3954 break;
3956 case SPELL_EFFECT_SCHOOL_DAMAGE:
3958 // Hammer of Wrath
3959 if(m_spellInfo->SpellVisual[0] == 7250)
3961 if (!m_targets.getUnitTarget())
3962 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3964 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3965 return SPELL_FAILED_BAD_TARGETS;
3967 break;
3969 case SPELL_EFFECT_TAMECREATURE:
3971 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3972 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3974 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3975 return SPELL_FAILED_HIGHLEVEL;
3977 // use SMSG_PET_TAME_FAILURE?
3978 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3979 return SPELL_FAILED_BAD_TARGETS;
3981 if(m_caster->GetPetGUID())
3982 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3984 if(m_caster->GetCharmGUID())
3985 return SPELL_FAILED_ALREADY_HAVE_CHARM;
3987 break;
3989 case SPELL_EFFECT_LEARN_SPELL:
3991 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3992 break;
3994 Pet* pet = m_caster->GetPet();
3996 if(!pet)
3997 return SPELL_FAILED_NO_PET;
3999 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4001 if(!learn_spellproto)
4002 return SPELL_FAILED_NOT_KNOWN;
4004 if(m_spellInfo->spellLevel > pet->getLevel())
4005 return SPELL_FAILED_LOWLEVEL;
4007 break;
4009 case SPELL_EFFECT_LEARN_PET_SPELL:
4011 Pet* pet = m_caster->GetPet();
4013 if(!pet)
4014 return SPELL_FAILED_NO_PET;
4016 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4018 if(!learn_spellproto)
4019 return SPELL_FAILED_NOT_KNOWN;
4021 if(m_spellInfo->spellLevel > pet->getLevel())
4022 return SPELL_FAILED_LOWLEVEL;
4024 break;
4026 case SPELL_EFFECT_FEED_PET:
4028 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4029 return SPELL_FAILED_BAD_TARGETS;
4031 Item* foodItem = m_targets.getItemTarget();
4032 if(!foodItem)
4033 return SPELL_FAILED_BAD_TARGETS;
4035 Pet* pet = m_caster->GetPet();
4037 if(!pet)
4038 return SPELL_FAILED_NO_PET;
4040 if(!pet->HaveInDiet(foodItem->GetProto()))
4041 return SPELL_FAILED_WRONG_PET_FOOD;
4043 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4044 return SPELL_FAILED_FOOD_LOWLEVEL;
4046 if(m_caster->isInCombat() || pet->isInCombat())
4047 return SPELL_FAILED_AFFECTING_COMBAT;
4049 break;
4051 case SPELL_EFFECT_POWER_BURN:
4052 case SPELL_EFFECT_POWER_DRAIN:
4054 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4055 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4056 if(Unit* target = m_targets.getUnitTarget())
4057 if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
4058 return SPELL_FAILED_BAD_TARGETS;
4059 break;
4061 case SPELL_EFFECT_CHARGE:
4063 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4064 return SPELL_FAILED_ROOTED;
4066 break;
4068 case SPELL_EFFECT_SKINNING:
4070 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4071 return SPELL_FAILED_BAD_TARGETS;
4073 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4074 return SPELL_FAILED_TARGET_UNSKINNABLE;
4076 Creature* creature = (Creature*)m_targets.getUnitTarget();
4077 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4079 return SPELL_FAILED_TARGET_NOT_LOOTED;
4082 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4084 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4085 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4086 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
4087 if (ReqValue > skillValue)
4088 return SPELL_FAILED_LOW_CASTLEVEL;
4090 // chance for fail at orange skinning attempt
4091 if( (m_selfContainer && (*m_selfContainer) == this) &&
4092 skillValue < sWorld.GetConfigMaxSkillValue() &&
4093 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
4094 return SPELL_FAILED_TRY_AGAIN;
4096 break;
4098 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4099 case SPELL_EFFECT_OPEN_LOCK:
4101 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4102 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4103 break;
4105 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4106 // we need a go target in case of TARGET_GAMEOBJECT
4107 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4108 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4109 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4110 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4111 return SPELL_FAILED_BAD_TARGETS;
4113 // In BattleGround players can use only flags and banners
4114 if( ((Player*)m_caster)->InBattleGround() &&
4115 !((Player*)m_caster)->isAllowUseBattleGroundObject() )
4116 return SPELL_FAILED_TRY_AGAIN;
4118 // get the lock entry
4119 LockEntry const *lockInfo = NULL;
4120 if (GameObject* go=m_targets.getGOTarget())
4121 lockInfo = sLockStore.LookupEntry(go->GetLockId());
4122 else if(Item* itm=m_targets.getItemTarget())
4123 lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
4125 // check lock compatibility
4126 if (lockInfo)
4128 // check for lock - key pair (checked by client also, just prevent cheating
4129 bool ok_key = false;
4130 for(int it = 0; it < 8; ++it)
4132 switch(lockInfo->Type[it])
4134 case LOCK_KEY_NONE:
4135 break;
4136 case LOCK_KEY_ITEM:
4138 if(lockInfo->Index[it])
4140 if(m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4141 ok_key =true;
4142 break;
4145 case LOCK_KEY_SKILL:
4147 if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->Index[it])
4148 break;
4150 switch(lockInfo->Index[it])
4152 case LOCKTYPE_HERBALISM:
4153 if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
4154 ok_key =true;
4155 break;
4156 case LOCKTYPE_MINING:
4157 if(((Player*)m_caster)->HasSkill(SKILL_MINING))
4158 ok_key =true;
4159 break;
4160 default:
4161 ok_key =true;
4162 break;
4166 if(ok_key)
4167 break;
4170 if(!ok_key)
4171 return SPELL_FAILED_BAD_TARGETS;
4174 // chance for fail at orange mining/herb/LockPicking gathering attempt
4175 if (!m_selfContainer || ((*m_selfContainer) != this))
4176 break;
4178 // get the skill value of the player
4179 int32 SkillValue = 0;
4180 bool canFailAtMax = true;
4181 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
4183 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
4184 canFailAtMax = false;
4186 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
4188 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
4189 canFailAtMax = false;
4191 else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4192 SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
4194 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
4195 if(m_CastItem)
4196 SkillValue = 0;
4198 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
4199 SkillValue += m_currentBasePoints[i]+1;
4201 // get the required lock value
4202 int32 ReqValue=0;
4203 if (lockInfo)
4205 // check for lock - key pair
4206 bool ok = false;
4207 for(int it = 0; it < 8; ++it)
4209 if(lockInfo->Type[it]==LOCK_KEY_ITEM && lockInfo->Index[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[it])
4211 // if so, we're good to go
4212 ok = true;
4213 break;
4216 if(ok)
4217 break;
4219 if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
4220 ReqValue = lockInfo->Skill[1];
4221 else
4222 ReqValue = lockInfo->Skill[0];
4225 // skill doesn't meet the required value
4226 if (ReqValue > SkillValue)
4227 return SPELL_FAILED_LOW_CASTLEVEL;
4229 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4230 if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
4231 return SPELL_FAILED_TRY_AGAIN;
4233 break;
4235 case SPELL_EFFECT_SUMMON_DEAD_PET:
4237 Creature *pet = m_caster->GetPet();
4238 if(!pet)
4239 return SPELL_FAILED_NO_PET;
4241 if(pet->isAlive())
4242 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4244 break;
4246 // This is generic summon effect
4247 case SPELL_EFFECT_SUMMON:
4249 switch(m_spellInfo->EffectMiscValueB[i])
4251 case SUMMON_TYPE_POSESSED:
4252 case SUMMON_TYPE_POSESSED2:
4253 case SUMMON_TYPE_DEMON:
4254 case SUMMON_TYPE_SUMMON:
4256 if(m_caster->GetPetGUID())
4257 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4259 if(m_caster->GetCharmGUID())
4260 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4261 break;
4264 break;
4266 // Not used for summon?
4267 case SPELL_EFFECT_SUMMON_PHANTASM:
4269 if(m_caster->GetPetGUID())
4270 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4272 if(m_caster->GetCharmGUID())
4273 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4275 break;
4277 case SPELL_EFFECT_SUMMON_PET:
4279 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4282 Pet* pet = ((Player*)m_caster)->GetPet();
4284 if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
4286 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4287 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4289 else
4290 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4293 if(m_caster->GetCharmGUID())
4294 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4296 break;
4298 case SPELL_EFFECT_SUMMON_PLAYER:
4300 if(m_caster->GetTypeId()!=TYPEID_PLAYER)
4301 return SPELL_FAILED_BAD_TARGETS;
4302 if(!((Player*)m_caster)->GetSelection())
4303 return SPELL_FAILED_BAD_TARGETS;
4305 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4306 if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
4307 return SPELL_FAILED_BAD_TARGETS;
4309 // check if our map is dungeon
4310 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4312 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4313 if(!instance)
4314 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4315 if ( instance->levelMin > target->getLevel() )
4316 return SPELL_FAILED_LOWLEVEL;
4317 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4318 return SPELL_FAILED_HIGHLEVEL;
4320 break;
4322 case SPELL_EFFECT_LEAP:
4323 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4325 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4326 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4327 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4328 // teleport a bit above terrain level to avoid falling below it
4329 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4330 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4331 return SPELL_FAILED_TRY_AGAIN;
4333 float caster_pos_z = m_caster->GetPositionZ();
4334 // Control the caster to not climb or drop when +-fz > 8
4335 if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
4336 return SPELL_FAILED_TRY_AGAIN;
4338 // not allow use this effect at battleground until battleground start
4339 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4340 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4341 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4342 return SPELL_FAILED_TRY_AGAIN;
4343 break;
4345 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4347 if (m_targets.getUnitTarget()==m_caster)
4348 return SPELL_FAILED_BAD_TARGETS;
4349 break;
4351 default:break;
4355 for (int i = 0; i < 3; i++)
4357 switch(m_spellInfo->EffectApplyAuraName[i])
4359 case SPELL_AURA_MOD_POSSESS:
4360 case SPELL_AURA_MOD_CHARM:
4362 if(m_caster->GetPetGUID())
4363 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4365 if(m_caster->GetCharmGUID())
4366 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4368 if(m_caster->GetCharmerGUID())
4369 return SPELL_FAILED_CHARMED;
4371 if(!m_targets.getUnitTarget())
4372 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4374 if(m_targets.getUnitTarget()->GetCharmerGUID())
4375 return SPELL_FAILED_CHARMED;
4377 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4378 return SPELL_FAILED_HIGHLEVEL;
4380 break;
4382 case SPELL_AURA_MOUNTED:
4384 if (m_caster->IsInWater())
4385 return SPELL_FAILED_ONLY_ABOVEWATER;
4387 if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4388 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4390 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4391 if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4392 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4394 ShapeshiftForm form = m_caster->m_form;
4395 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4396 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4397 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4398 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4399 return SPELL_FAILED_NOT_SHAPESHIFT;
4401 break;
4403 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4405 if(!m_targets.getUnitTarget())
4406 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4408 // can be casted at non-friendly unit or own pet/charm
4409 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4410 return SPELL_FAILED_TARGET_FRIENDLY;
4412 break;
4414 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4415 case SPELL_AURA_FLY:
4417 // not allow cast fly spells at old maps by players (all spells is self target)
4418 if(m_caster->GetTypeId()==TYPEID_PLAYER)
4420 uint32 v_map = GetVirtualMapForMapAndZone(m_caster->GetMapId(), m_caster->GetZoneId());
4421 if( !((Player*)m_caster)->isGameMaster() && v_map != 530 && !(v_map == 571 && ((Player*)m_caster)->HasSpell(54197)))
4422 return SPELL_FAILED_NOT_HERE;
4425 break;
4427 case SPELL_AURA_PERIODIC_MANA_LEECH:
4429 if (!m_targets.getUnitTarget())
4430 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4432 if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4433 break;
4435 if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4436 return SPELL_FAILED_BAD_TARGETS;
4438 break;
4440 default:
4441 break;
4445 // all ok
4446 return 0;
4449 int16 Spell::PetCanCast(Unit* target)
4451 if(!m_caster->isAlive())
4452 return SPELL_FAILED_CASTER_DEAD;
4454 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4455 return SPELL_FAILED_SPELL_IN_PROGRESS;
4456 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4457 return SPELL_FAILED_AFFECTING_COMBAT;
4459 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4461 //dead owner (pets still alive when owners ressed?)
4462 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4463 return SPELL_FAILED_CASTER_DEAD;
4465 if(!target && m_targets.getUnitTarget())
4466 target = m_targets.getUnitTarget();
4468 bool need = false;
4469 for(uint32 i = 0;i<3;i++)
4471 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)
4473 need = true;
4474 if(!target)
4475 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4476 break;
4479 if(need)
4480 m_targets.setUnitTarget(target);
4482 Unit* _target = m_targets.getUnitTarget();
4484 if(_target) //for target dead/target not valid
4486 if(!_target->isAlive())
4487 return SPELL_FAILED_BAD_TARGETS;
4489 if(IsPositiveSpell(m_spellInfo->Id))
4491 if(m_caster->IsHostileTo(_target))
4492 return SPELL_FAILED_BAD_TARGETS;
4494 else
4496 bool duelvsplayertar = false;
4497 for(int j=0;j<3;j++)
4499 //TARGET_DUELVSPLAYER is positive AND negative
4500 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4502 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4504 return SPELL_FAILED_BAD_TARGETS;
4508 //cooldown
4509 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4510 return SPELL_FAILED_NOT_READY;
4513 uint16 result = CanCast(true);
4514 if(result != 0)
4515 return result;
4516 else
4517 return -1; //this allows to check spell fail 0, in combat
4520 uint8 Spell::CheckCasterAuras() const
4522 // Flag drop spells totally immuned to caster auras
4523 // FIXME: find more nice check for all totally immuned spells
4524 // AttributesEx3 & 0x10000000?
4525 if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4526 return 0;
4528 uint8 school_immune = 0;
4529 uint32 mechanic_immune = 0;
4530 uint32 dispel_immune = 0;
4532 //Check if the spell grants school or mechanic immunity.
4533 //We use bitmasks so the loop is done only once and not on every aura check below.
4534 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4536 for(int i = 0;i < 3; i ++)
4538 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4539 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4540 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4541 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4542 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4543 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4545 //immune movement impairment and loss of control
4546 if(m_spellInfo->Id==(uint32)42292)
4547 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4550 //Check whether the cast should be prevented by any state you might have.
4551 uint8 prevented_reason = 0;
4552 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4553 if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4554 prevented_reason = SPELL_FAILED_STUNNED;
4555 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4556 prevented_reason = SPELL_FAILED_CONFUSED;
4557 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4558 prevented_reason = SPELL_FAILED_FLEEING;
4559 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4560 prevented_reason = SPELL_FAILED_SILENCED;
4561 else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4562 prevented_reason = SPELL_FAILED_PACIFIED;
4564 // Attr must make flag drop spell totally immune from all effects
4565 if(prevented_reason)
4567 if(school_immune || mechanic_immune || dispel_immune)
4569 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4570 Unit::AuraMap const& auras = m_caster->GetAuras();
4571 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4573 if(itr->second)
4575 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4576 continue;
4577 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4578 continue;
4579 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4580 continue;
4582 //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4583 //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4584 switch(itr->second->GetModifier()->m_auraname)
4586 case SPELL_AURA_MOD_STUN:
4587 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4588 return SPELL_FAILED_STUNNED;
4589 break;
4590 case SPELL_AURA_MOD_CONFUSE:
4591 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4592 return SPELL_FAILED_CONFUSED;
4593 break;
4594 case SPELL_AURA_MOD_FEAR:
4595 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4596 return SPELL_FAILED_FLEEING;
4597 break;
4598 case SPELL_AURA_MOD_SILENCE:
4599 case SPELL_AURA_MOD_PACIFY:
4600 case SPELL_AURA_MOD_PACIFY_SILENCE:
4601 if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4602 return SPELL_FAILED_PACIFIED;
4603 else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4604 return SPELL_FAILED_SILENCED;
4605 break;
4610 //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4611 else
4612 return prevented_reason;
4614 return 0; // all ok
4617 bool Spell::CanAutoCast(Unit* target)
4619 uint64 targetguid = target->GetGUID();
4621 for(uint32 j = 0;j<3;j++)
4623 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4625 if( m_spellInfo->StackAmount <= 1)
4627 if( target->HasAura(m_spellInfo->Id, j) )
4628 return false;
4630 else
4632 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4633 return false;
4636 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4638 if( target->HasAura(m_spellInfo->Id, j) )
4639 return false;
4643 int16 result = PetCanCast(target);
4645 if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4647 FillTargetMap();
4648 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4649 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4650 if( ihit->targetGUID == targetguid )
4651 return true;
4653 return false; //target invalid
4656 uint8 Spell::CheckRange(bool strict)
4658 float range_mod;
4660 // self cast doesn't need range checking -- also for Starshards fix
4661 if (m_spellInfo->rangeIndex == 1) return 0;
4663 if (strict) //add radius of caster
4664 range_mod = 1.25;
4665 else //add radius of caster and ~5 yds "give"
4666 range_mod = 6.25;
4668 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4669 float max_range = GetSpellMaxRange(srange) + range_mod;
4670 float min_range = GetSpellMinRange(srange);
4672 if(Player* modOwner = m_caster->GetSpellModOwner())
4673 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4675 Unit *target = m_targets.getUnitTarget();
4677 if(target && target != m_caster)
4679 // distance from target center in checks
4680 float dist = m_caster->GetDistance(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ());
4681 if(dist > max_range)
4682 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4683 if(dist < min_range)
4684 return SPELL_FAILED_TOO_CLOSE;
4685 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4686 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4687 return SPELL_FAILED_UNIT_NOT_INFRONT;
4690 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4692 float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4693 if(dist > max_range)
4694 return SPELL_FAILED_OUT_OF_RANGE;
4695 if(dist < min_range)
4696 return SPELL_FAILED_TOO_CLOSE;
4699 return 0; // ok
4702 int32 Spell::CalculatePowerCost()
4704 // item cast not used power
4705 if(m_CastItem)
4706 return 0;
4708 // Spell drain all exist power on cast (Only paladin lay of Hands)
4709 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4711 // If power type - health drain all
4712 if (m_spellInfo->powerType == POWER_HEALTH)
4713 return m_caster->GetHealth();
4714 // Else drain all power
4715 if (m_spellInfo->powerType < MAX_POWERS)
4716 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4717 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4718 return 0;
4721 // Base powerCost
4722 int32 powerCost = m_spellInfo->manaCost;
4723 // PCT cost from total amount
4724 if (m_spellInfo->ManaCostPercentage)
4726 switch (m_spellInfo->powerType)
4728 // health as power used
4729 case POWER_HEALTH:
4730 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4731 break;
4732 case POWER_MANA:
4733 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4734 break;
4735 case POWER_RAGE:
4736 case POWER_FOCUS:
4737 case POWER_ENERGY:
4738 case POWER_HAPPINESS:
4739 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4740 break;
4741 case POWER_RUNE:
4742 case POWER_RUNIC_POWER:
4743 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4744 break;
4745 default:
4746 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4747 return 0;
4750 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4751 // Flat mod from caster auras by spell school
4752 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4753 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4754 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4755 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4756 // Apply cost mod by spell
4757 if(Player* modOwner = m_caster->GetSpellModOwner())
4758 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4760 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4761 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4763 // PCT mod from user auras by school
4764 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4765 if (powerCost < 0)
4766 powerCost = 0;
4767 return powerCost;
4770 uint8 Spell::CheckPower()
4772 // item cast not used power
4773 if(m_CastItem)
4774 return 0;
4776 // health as power used - need check health amount
4777 if(m_spellInfo->powerType == POWER_HEALTH)
4779 if(m_caster->GetHealth() <= m_powerCost)
4780 return SPELL_FAILED_CASTER_AURASTATE;
4781 return 0;
4783 // Check valid power type
4784 if( m_spellInfo->powerType >= MAX_POWERS )
4786 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4787 return SPELL_FAILED_UNKNOWN;
4790 uint8 failReason = CheckRuneCost(m_spellInfo->runeCostID);
4791 if(failReason)
4792 return failReason;
4794 // Check power amount
4795 Powers powerType = Powers(m_spellInfo->powerType);
4796 if(m_caster->GetPower(powerType) < m_powerCost)
4797 return SPELL_FAILED_NO_POWER;
4798 else
4799 return 0;
4802 uint8 Spell::CheckItems()
4804 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4805 return 0;
4807 uint32 itemid, itemcount;
4808 Player* p_caster = (Player*)m_caster;
4810 if(m_CastItem)
4812 itemid = m_CastItem->GetEntry();
4813 if( !p_caster->HasItemCount(itemid,1) )
4814 return SPELL_FAILED_ITEM_NOT_READY;
4815 else
4817 ItemPrototype const *proto = m_CastItem->GetProto();
4818 if(!proto)
4819 return SPELL_FAILED_ITEM_NOT_READY;
4821 for (int i = 0; i<5; i++)
4823 if (proto->Spells[i].SpellCharges)
4825 if(m_CastItem->GetSpellCharges(i)==0)
4826 return SPELL_FAILED_NO_CHARGES_REMAIN;
4830 uint32 ItemClass = proto->Class;
4831 if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4833 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4834 uint8 failReason = 0;
4835 for (int i = 0; i < 3; i++)
4837 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4838 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4839 continue;
4841 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4843 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4845 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4846 continue;
4848 else
4850 failReason = 0;
4851 break;
4855 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4856 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4858 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4860 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4861 continue;
4864 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4865 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4867 failReason = (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4868 continue;
4870 else
4872 failReason = 0;
4873 break;
4877 if (failReason)
4878 return failReason;
4883 if(m_targets.getItemTargetGUID())
4885 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4886 return SPELL_FAILED_BAD_TARGETS;
4888 if(!m_targets.getItemTarget())
4889 return SPELL_FAILED_ITEM_GONE;
4891 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4892 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4894 // if not item target then required item must be equipped
4895 else
4897 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4898 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4901 if(m_spellInfo->RequiresSpellFocus)
4903 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4904 Cell cell(p);
4905 cell.data.Part.reserved = ALL_DISTRICT;
4907 GameObject* ok = NULL;
4908 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4909 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(ok,go_check);
4911 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4912 CellLock<GridReadGuard> cell_lock(cell, p);
4913 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4915 if(!ok)
4916 return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4918 focusObject = ok; // game object found in range
4921 if (!p_caster->CanNoReagentCast(m_spellInfo))
4923 for(uint32 i=0;i<8;i++)
4925 if(m_spellInfo->Reagent[i] <= 0)
4926 continue;
4928 itemid = m_spellInfo->Reagent[i];
4929 itemcount = m_spellInfo->ReagentCount[i];
4931 // if CastItem is also spell reagent
4932 if( m_CastItem && m_CastItem->GetEntry() == itemid )
4934 ItemPrototype const *proto = m_CastItem->GetProto();
4935 if(!proto)
4936 return SPELL_FAILED_ITEM_NOT_READY;
4937 for(int s=0;s<5;s++)
4939 // CastItem will be used up and does not count as reagent
4940 int32 charges = m_CastItem->GetSpellCharges(s);
4941 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4943 ++itemcount;
4944 break;
4948 if( !p_caster->HasItemCount(itemid,itemcount) )
4949 return (uint8)SPELL_FAILED_ITEM_NOT_READY; //0x54
4953 uint32 totems = 2;
4954 for(int i=0;i<2;++i)
4956 if(m_spellInfo->Totem[i] != 0)
4958 if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4960 totems -= 1;
4961 continue;
4963 }else
4964 totems -= 1;
4966 if(totems != 0)
4967 return (uint8)SPELL_FAILED_TOTEMS; //0x7C
4969 //Check items for TotemCategory
4970 uint32 TotemCategory = 2;
4971 for(int i=0;i<2;++i)
4973 if(m_spellInfo->TotemCategory[i] != 0)
4975 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4977 TotemCategory -= 1;
4978 continue;
4981 else
4982 TotemCategory -= 1;
4984 if(TotemCategory != 0)
4985 return (uint8)SPELL_FAILED_TOTEM_CATEGORY; //0x7B
4987 for(int i = 0; i < 3; i++)
4989 switch (m_spellInfo->Effect[i])
4991 case SPELL_EFFECT_CREATE_ITEM:
4993 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4995 ItemPosCountVec dest;
4996 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4997 if (msg != EQUIP_ERR_OK )
4999 p_caster->SendEquipError( msg, NULL, NULL );
5000 return SPELL_FAILED_DONT_REPORT;
5003 break;
5005 case SPELL_EFFECT_ENCHANT_ITEM:
5007 Item* targetItem = m_targets.getItemTarget();
5008 if(!targetItem)
5009 return SPELL_FAILED_ITEM_NOT_FOUND;
5011 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5012 return SPELL_FAILED_LOWLEVEL;
5013 // Not allow enchant in trade slot for some enchant type
5014 if( targetItem->GetOwner() != m_caster )
5016 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5017 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5018 if(!pEnchant)
5019 return SPELL_FAILED_ERROR;
5020 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5021 return SPELL_FAILED_NOT_TRADEABLE;
5023 break;
5025 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5027 Item *item = m_targets.getItemTarget();
5028 if(!item)
5029 return SPELL_FAILED_ITEM_NOT_FOUND;
5030 // Not allow enchant in trade slot for some enchant type
5031 if( item->GetOwner() != m_caster )
5033 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5034 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5035 if(!pEnchant)
5036 return SPELL_FAILED_ERROR;
5037 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5038 return SPELL_FAILED_NOT_TRADEABLE;
5040 break;
5042 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5043 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5044 break;
5045 case SPELL_EFFECT_DISENCHANT:
5047 if(!m_targets.getItemTarget())
5048 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5050 // prevent disenchanting in trade slot
5051 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5052 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5054 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5055 if(!itemProto)
5056 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5058 uint32 item_quality = itemProto->Quality;
5059 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5060 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5061 if (item_disenchantskilllevel == uint32(-1))
5062 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5063 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5064 return SPELL_FAILED_LOW_CASTLEVEL;
5065 if(item_quality > 4 || item_quality < 2)
5066 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5067 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5068 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5069 if (!itemProto->DisenchantID)
5070 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5071 break;
5073 case SPELL_EFFECT_PROSPECTING:
5075 if(!m_targets.getItemTarget())
5076 return SPELL_FAILED_CANT_BE_PROSPECTED;
5077 //ensure item is a prospectable ore
5078 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5079 return SPELL_FAILED_CANT_BE_PROSPECTED;
5080 //prevent prospecting in trade slot
5081 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5082 return SPELL_FAILED_CANT_BE_PROSPECTED;
5083 //Check for enough skill in jewelcrafting
5084 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5085 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5086 return SPELL_FAILED_LOW_CASTLEVEL;
5087 //make sure the player has the required ores in inventory
5088 if(m_targets.getItemTarget()->GetCount() < 5)
5089 return SPELL_FAILED_NEED_MORE_ITEMS;
5091 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5092 return SPELL_FAILED_CANT_BE_PROSPECTED;
5094 break;
5096 case SPELL_EFFECT_MILLING:
5098 if(!m_targets.getItemTarget())
5099 return SPELL_FAILED_CANT_BE_MILLED;
5100 //ensure item is a millable herb
5101 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5102 return SPELL_FAILED_CANT_BE_MILLED;
5103 //prevent milling in trade slot
5104 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5105 return SPELL_FAILED_CANT_BE_MILLED;
5106 //Check for enough skill in inscription
5107 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5108 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5109 return SPELL_FAILED_LOW_CASTLEVEL;
5110 //make sure the player has the required herbs in inventory
5111 if(m_targets.getItemTarget()->GetCount() < 5)
5112 return SPELL_FAILED_NEED_MORE_ITEMS;
5114 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5115 return SPELL_FAILED_CANT_BE_MILLED;
5117 break;
5119 case SPELL_EFFECT_WEAPON_DAMAGE:
5120 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5122 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5123 if( m_attackType != RANGED_ATTACK )
5124 break;
5125 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5126 if(!pItem || pItem->IsBroken())
5127 return SPELL_FAILED_EQUIPPED_ITEM;
5129 switch(pItem->GetProto()->SubClass)
5131 case ITEM_SUBCLASS_WEAPON_THROWN:
5133 uint32 ammo = pItem->GetEntry();
5134 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5135 return SPELL_FAILED_NO_AMMO;
5136 }; break;
5137 case ITEM_SUBCLASS_WEAPON_GUN:
5138 case ITEM_SUBCLASS_WEAPON_BOW:
5139 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5141 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5142 if(!ammo)
5144 // Requires No Ammo
5145 if(m_caster->GetDummyAura(46699))
5146 break; // skip other checks
5148 return SPELL_FAILED_NO_AMMO;
5151 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5152 if(!ammoProto)
5153 return SPELL_FAILED_NO_AMMO;
5155 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5156 return SPELL_FAILED_NO_AMMO;
5158 // check ammo ws. weapon compatibility
5159 switch(pItem->GetProto()->SubClass)
5161 case ITEM_SUBCLASS_WEAPON_BOW:
5162 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5163 if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
5164 return SPELL_FAILED_NO_AMMO;
5165 break;
5166 case ITEM_SUBCLASS_WEAPON_GUN:
5167 if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
5168 return SPELL_FAILED_NO_AMMO;
5169 break;
5170 default:
5171 return SPELL_FAILED_NO_AMMO;
5174 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5175 return SPELL_FAILED_NO_AMMO;
5176 }; break;
5177 case ITEM_SUBCLASS_WEAPON_WAND:
5178 default:
5179 break;
5181 break;
5183 default:break;
5187 return uint8(0);
5190 void Spell::Delayed()
5192 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5193 return;
5195 if (m_spellState == SPELL_STATE_DELAYED)
5196 return; // spell is active and can't be time-backed
5198 // spells not loosing casting time ( slam, dynamites, bombs.. )
5199 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5200 return;
5202 //check resist chance
5203 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5204 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5205 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5206 if (roll_chance_i(resistChance))
5207 return;
5209 int32 delaytime = GetNextDelayAtDamageMsTime();
5211 if(int32(m_timer) + delaytime > m_casttime)
5213 delaytime = m_casttime - m_timer;
5214 m_timer = m_casttime;
5216 else
5217 m_timer += delaytime;
5219 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
5221 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5222 data.append(m_caster->GetPackGUID());
5223 data << uint32(delaytime);
5225 m_caster->SendMessageToSet(&data,true);
5228 void Spell::DelayedChannel()
5230 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5231 return;
5233 //check resist chance
5234 int32 resistChance = 100; //must be initialized to 100 for percent modifiers
5235 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
5236 resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
5237 if (roll_chance_i(resistChance))
5238 return;
5240 int32 delaytime = GetNextDelayAtDamageMsTime();
5242 if(int32(m_timer) < delaytime)
5244 delaytime = m_timer;
5245 m_timer = 0;
5247 else
5248 m_timer -= delaytime;
5250 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5252 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
5254 if ((*ihit).missCondition == SPELL_MISS_NONE)
5256 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5257 if (unit)
5259 for (int j=0;j<3;j++)
5260 if( ihit->effectMask & (1<<j) )
5261 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5267 for(int j = 0; j < 3; j++)
5269 // partially interrupt persistent area auras
5270 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5271 if(dynObj)
5272 dynObj->Delay(delaytime);
5275 SendChannelUpdate(m_timer);
5278 void Spell::UpdatePointers()
5280 if(m_originalCasterGUID==m_caster->GetGUID())
5281 m_originalCaster = m_caster;
5282 else
5284 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5285 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5288 m_targets.Update(m_caster);
5291 bool Spell::IsAffectedByAura(Aura *aura)
5293 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5296 bool Spell::CheckTargetCreatureType(Unit* target) const
5298 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5300 // Curse of Doom : not find another way to fix spell target check :/
5301 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
5303 // not allow cast at player
5304 if(target->GetTypeId()==TYPEID_PLAYER)
5305 return false;
5307 spellCreatureTargetMask = 0x7FF;
5310 // Dismiss Pet and Taming Lesson skipped
5311 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5312 spellCreatureTargetMask = 0;
5314 if (spellCreatureTargetMask)
5316 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5318 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5320 return true;
5323 CurrentSpellTypes Spell::GetCurrentContainer()
5325 if (IsNextMeleeSwingSpell())
5326 return(CURRENT_MELEE_SPELL);
5327 else if (IsAutoRepeat())
5328 return(CURRENT_AUTOREPEAT_SPELL);
5329 else if (IsChanneledSpell(m_spellInfo))
5330 return(CURRENT_CHANNELED_SPELL);
5331 else
5332 return(CURRENT_GENERIC_SPELL);
5335 bool Spell::CheckTarget( Unit* target, uint32 eff )
5337 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5338 if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF )
5340 if (!CheckTargetCreatureType(target))
5341 return false;
5344 // Check Aura spell req (need for AoE spells)
5345 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5346 return false;
5347 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5348 return false;
5350 // Check targets for not_selectable unit flag and remove
5351 // A player can cast spells on his pet (or other controlled unit) though in any state
5352 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5354 // any unattackable target skipped
5355 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5356 return false;
5358 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5359 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5360 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5361 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5362 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5363 return false;
5366 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5367 if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
5369 if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
5370 return false;
5372 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5373 return false;
5376 //Check targets for LOS visibility (except spells without range limitations )
5377 switch(m_spellInfo->Effect[eff])
5379 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5380 break;
5381 case SPELL_EFFECT_DUMMY:
5382 if(m_spellInfo->Id!=20577) // Cannibalize
5383 break;
5384 //fall through
5385 case SPELL_EFFECT_RESURRECT_NEW:
5386 // player far away, maybe his corpse near?
5387 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5389 if(!m_targets.getCorpseTargetGUID())
5390 return false;
5392 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
5393 if(!corpse)
5394 return false;
5396 if(target->GetGUID()!=corpse->GetOwnerGUID())
5397 return false;
5399 if(!corpse->IsWithinLOSInMap(m_caster))
5400 return false;
5403 // all ok by some way or another, skip normal check
5404 break;
5405 default: // normal case
5406 if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
5407 return false;
5408 break;
5411 return true;
5414 Unit* Spell::SelectMagnetTarget()
5416 Unit* target = m_targets.getUnitTarget();
5418 if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
5420 Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
5421 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
5423 if(Unit* magnet = (*itr)->GetCaster())
5425 if(magnet->IsWithinLOSInMap(m_caster))
5427 target = magnet;
5428 m_targets.setUnitTarget(target);
5429 break;
5435 return target;
5438 bool Spell::IsNeedSendToClient() const
5440 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5441 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5444 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5446 for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5447 if(itr->effectMask & (1<<effect))
5448 return true;
5450 for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5451 if(itr->effectMask & (1<<effect))
5452 return true;
5454 for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5455 if(itr->effectMask & (1<<effect))
5456 return true;
5458 return false;
5461 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5463 m_Spell = spell;
5466 SpellEvent::~SpellEvent()
5468 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5469 m_Spell->cancel();
5471 if (m_Spell->IsDeletable())
5473 delete m_Spell;
5475 else
5477 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5478 (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5482 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5484 // update spell if it is not finished
5485 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5486 m_Spell->update(p_time);
5488 // check spell state to process
5489 switch (m_Spell->getState())
5491 case SPELL_STATE_FINISHED:
5493 // spell was finished, check deletable state
5494 if (m_Spell->IsDeletable())
5496 // check, if we do have unfinished triggered spells
5498 return(true); // spell is deletable, finish event
5500 // event will be re-added automatically at the end of routine)
5501 } break;
5503 case SPELL_STATE_CASTING:
5505 // this spell is in channeled state, process it on the next update
5506 // event will be re-added automatically at the end of routine)
5507 } break;
5509 case SPELL_STATE_DELAYED:
5511 // first, check, if we have just started
5512 if (m_Spell->GetDelayStart() != 0)
5514 // no, we aren't, do the typical update
5515 // check, if we have channeled spell on our hands
5516 if (IsChanneledSpell(m_Spell->m_spellInfo))
5518 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5519 // check, if we have casting anything else except this channeled spell and autorepeat
5520 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5522 // another non-melee non-delayed spell is casted now, abort
5523 m_Spell->cancel();
5525 else
5527 // do the action (pass spell to channeling state)
5528 m_Spell->handle_immediate();
5530 // event will be re-added automatically at the end of routine)
5532 else
5534 // run the spell handler and think about what we can do next
5535 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5536 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5537 if (n_offset)
5539 // re-add us to the queue
5540 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5541 return(false); // event not complete
5543 // event complete
5544 // finish update event will be re-added automatically at the end of routine)
5547 else
5549 // delaying had just started, record the moment
5550 m_Spell->SetDelayStart(e_time);
5551 // re-plan the event for the delay moment
5552 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5553 return(false); // event not complete
5555 } break;
5557 default:
5559 // all other states
5560 // event will be re-added automatically at the end of routine)
5561 } break;
5564 // spell processing not complete, plan event on the next update interval
5565 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5566 return(false); // event not complete
5569 void SpellEvent::Abort(uint64 /*e_time*/)
5571 // oops, the spell we try to do is aborted
5572 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5573 m_Spell->cancel();
5576 bool SpellEvent::IsDeletable() const
5578 return m_Spell->IsDeletable();