[7958] Disable targeting hidden units for TARGET_CHAIN_DAMAGE.
[getmangos.git] / src / game / Spell.cpp
blob319ad16dc976ddfd070af3db8239a05789a6ed56
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "Group.h"
37 #include "UpdateData.h"
38 #include "MapManager.h"
39 #include "ObjectAccessor.h"
40 #include "CellImpl.h"
41 #include "Policies/SingletonImp.h"
42 #include "SharedDefines.h"
43 #include "LootMgr.h"
44 #include "VMapFactory.h"
45 #include "BattleGround.h"
46 #include "Util.h"
48 #define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILISECONDS)
50 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
52 class PrioritizeManaPlayerWraper
54 friend struct PrioritizeMana;
56 public:
57 explicit PrioritizeManaPlayerWraper(Player* player) : player(player)
59 uint32 maxmana = player->GetMaxPower(POWER_MANA);
60 percentMana = maxmana ? player->GetPower(POWER_MANA) * 100 / maxmana : 101;
62 Player* getPlayer() const { return player; }
63 private:
64 Player* player;
65 uint32 percentMana;
68 struct PrioritizeMana
70 int operator()( PrioritizeManaPlayerWraper const& x, PrioritizeManaPlayerWraper const& y ) const
72 return x.percentMana < y.percentMana;
77 bool IsQuestTameSpell(uint32 spellId)
79 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
80 if (!spellproto) return false;
82 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
83 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
86 SpellCastTargets::SpellCastTargets()
88 m_unitTarget = NULL;
89 m_itemTarget = NULL;
90 m_GOTarget = NULL;
92 m_unitTargetGUID = 0;
93 m_GOTargetGUID = 0;
94 m_CorpseTargetGUID = 0;
95 m_itemTargetGUID = 0;
96 m_itemTargetEntry = 0;
98 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
99 m_strTarget = "";
100 m_targetMask = 0;
103 SpellCastTargets::~SpellCastTargets()
107 void SpellCastTargets::setUnitTarget(Unit *target)
109 if (!target)
110 return;
112 m_destX = target->GetPositionX();
113 m_destY = target->GetPositionY();
114 m_destZ = target->GetPositionZ();
115 m_unitTarget = target;
116 m_unitTargetGUID = target->GetGUID();
117 m_targetMask |= TARGET_FLAG_UNIT;
120 void SpellCastTargets::setDestination(float x, float y, float z)
122 m_destX = x;
123 m_destY = y;
124 m_destZ = z;
125 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
128 void SpellCastTargets::setSource(float x, float y, float z)
130 m_srcX = x;
131 m_srcY = y;
132 m_srcZ = z;
133 m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
136 void SpellCastTargets::setGOTarget(GameObject *target)
138 m_GOTarget = target;
139 m_GOTargetGUID = target->GetGUID();
140 // m_targetMask |= TARGET_FLAG_OBJECT;
143 void SpellCastTargets::setItemTarget(Item* item)
145 if(!item)
146 return;
148 m_itemTarget = item;
149 m_itemTargetGUID = item->GetGUID();
150 m_itemTargetEntry = item->GetEntry();
151 m_targetMask |= TARGET_FLAG_ITEM;
154 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
156 m_CorpseTargetGUID = corpse->GetGUID();
159 void SpellCastTargets::Update(Unit* caster)
161 m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL;
162 m_unitTarget = m_unitTargetGUID ?
163 ( m_unitTargetGUID == caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
164 NULL;
166 m_itemTarget = NULL;
167 if(caster->GetTypeId() == TYPEID_PLAYER)
169 if(m_targetMask & TARGET_FLAG_ITEM)
170 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
171 else
173 Player* pTrader = ((Player*)caster)->GetTrader();
174 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
175 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
177 if(m_itemTarget)
178 m_itemTargetEntry = m_itemTarget->GetEntry();
182 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
184 if(data->rpos() + 4 > data->size())
185 return false;
187 *data >> m_targetMask;
189 if(m_targetMask == TARGET_FLAG_SELF)
191 m_destX = caster->GetPositionX();
192 m_destY = caster->GetPositionY();
193 m_destZ = caster->GetPositionZ();
194 m_unitTarget = caster;
195 m_unitTargetGUID = caster->GetGUID();
196 return true;
199 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
200 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
201 if(!data->readPackGUID(m_unitTargetGUID))
202 return false;
204 if( m_targetMask & ( TARGET_FLAG_OBJECT ))
205 if(!data->readPackGUID(m_GOTargetGUID))
206 return false;
208 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
209 if(!data->readPackGUID(m_itemTargetGUID))
210 return false;
212 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
213 if(!data->readPackGUID(m_CorpseTargetGUID))
214 return false;
216 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
218 if(data->rpos() + 4 + 4 + 4 > data->size())
219 return false;
221 *data >> m_srcX >> m_srcY >> m_srcZ;
222 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
223 return false;
226 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
228 if(data->rpos() + 1 + 4 + 4 + 4 > data->size())
229 return false;
231 if(!data->readPackGUID(m_unitTargetGUID))
232 return false;
234 *data >> m_destX >> m_destY >> m_destZ;
235 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
236 return false;
239 if( m_targetMask & TARGET_FLAG_STRING )
241 if(data->rpos() + 1 > data->size())
242 return false;
244 *data >> m_strTarget;
247 // find real units/GOs
248 Update(caster);
249 return true;
252 void SpellCastTargets::write ( WorldPacket * data )
254 *data << uint32(m_targetMask);
256 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
258 if(m_targetMask & TARGET_FLAG_UNIT)
260 if(m_unitTarget)
261 data->append(m_unitTarget->GetPackGUID());
262 else
263 *data << uint8(0);
265 else if( m_targetMask & TARGET_FLAG_OBJECT )
267 if(m_GOTarget)
268 data->append(m_GOTarget->GetPackGUID());
269 else
270 *data << uint8(0);
272 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
273 data->appendPackGUID(m_CorpseTargetGUID);
274 else
275 *data << uint8(0);
278 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
280 if(m_itemTarget)
281 data->append(m_itemTarget->GetPackGUID());
282 else
283 *data << uint8(0);
286 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
287 *data << m_srcX << m_srcY << m_srcZ;
289 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
291 if(m_unitTarget)
292 data->append(m_unitTarget->GetPackGUID());
293 else
294 *data << uint8(0);
296 *data << m_destX << m_destY << m_destZ;
299 if( m_targetMask & TARGET_FLAG_STRING )
300 *data << m_strTarget;
303 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
305 ASSERT( Caster != NULL && info != NULL );
306 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
308 m_spellInfo = info;
309 m_caster = Caster;
310 m_selfContainer = NULL;
311 m_triggeringContainer = triggeringContainer;
312 m_referencedFromCurrentSpell = false;
313 m_executedCurrently = false;
314 m_delayStart = 0;
315 m_delayAtDamageCount = 0;
317 m_applyMultiplierMask = 0;
319 // Get data for type of attack
320 switch (m_spellInfo->DmgClass)
322 case SPELL_DAMAGE_CLASS_MELEE:
323 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
324 m_attackType = OFF_ATTACK;
325 else
326 m_attackType = BASE_ATTACK;
327 break;
328 case SPELL_DAMAGE_CLASS_RANGED:
329 m_attackType = RANGED_ATTACK;
330 break;
331 default:
332 // Wands
333 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
334 m_attackType = RANGED_ATTACK;
335 else
336 m_attackType = BASE_ATTACK;
337 break;
340 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
342 if(m_attackType == RANGED_ATTACK)
344 // wand case
345 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
347 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
348 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage[0].DamageType);
351 // Set health leech amount to zero
352 m_healthLeech = 0;
354 if(originalCasterGUID)
355 m_originalCasterGUID = originalCasterGUID;
356 else
357 m_originalCasterGUID = m_caster->GetGUID();
359 if(m_originalCasterGUID == m_caster->GetGUID())
360 m_originalCaster = m_caster;
361 else
363 m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
364 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
367 for(int i=0; i <3; ++i)
368 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
370 m_spellState = SPELL_STATE_NULL;
372 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
373 m_TriggerSpells.clear();
374 m_IsTriggeredSpell = triggered;
375 //m_AreaAura = false;
376 m_CastItem = NULL;
378 unitTarget = NULL;
379 itemTarget = NULL;
380 gameObjTarget = NULL;
381 focusObject = NULL;
382 m_cast_count = 0;
383 m_glyphIndex = 0;
384 m_preCastSpell = 0;
385 m_triggeredByAuraSpell = NULL;
387 //Auto Shot & Shoot (wand)
388 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
390 m_runesState = 0;
391 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
392 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
393 m_timer = 0; // will set to castime in prepare
395 m_needAliveTargetMask = 0;
397 // determine reflection
398 m_canReflect = false;
400 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
402 for(int j = 0;j < 3; ++j)
404 if (m_spellInfo->Effect[j] == 0)
405 continue;
407 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j], m_spellInfo->EffectImplicitTargetB[j]))
408 m_canReflect = true;
409 else
410 m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
412 if(m_canReflect)
413 continue;
414 else
415 break;
419 CleanupTargetList();
422 Spell::~Spell()
426 template<typename T>
427 WorldObject* Spell::FindCorpseUsing()
429 // non-standard target selection
430 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
431 float max_range = GetSpellMaxRange(srange);
433 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
434 Cell cell(p);
435 cell.data.Part.reserved = ALL_DISTRICT;
436 cell.SetNoCreate();
438 WorldObject* result = NULL;
440 T u_check(m_caster, max_range);
441 MaNGOS::WorldObjectSearcher<T> searcher(m_caster, result, u_check);
443 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<T>, GridTypeMapContainer > grid_searcher(searcher);
444 CellLock<GridReadGuard> cell_lock(cell, p);
445 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
447 if (!result)
449 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<T>, WorldTypeMapContainer > world_searcher(searcher);
450 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
453 return result;
456 void Spell::FillTargetMap()
458 // TODO: ADD the correct target FILLS!!!!!!
460 for(uint32 i = 0; i < 3; ++i)
462 // not call for empty effect.
463 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
464 if(m_spellInfo->Effect[i] == 0)
465 continue;
467 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::CheckCast call
468 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
469 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
470 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
471 continue;
473 // TODO: find a way so this is not needed?
474 // for area auras always add caster as target (needed for totems for example)
475 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
476 AddUnitTarget(m_caster, i);
478 std::list<Unit*> tmpUnitMap;
480 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
481 // but need it support in some know cases
482 switch(m_spellInfo->EffectImplicitTargetA[i])
484 case TARGET_SELF:
485 switch(m_spellInfo->EffectImplicitTargetB[i])
487 case 0:
488 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
489 break;
490 case TARGET_AREAEFFECT_INSTANT: // use B case that not dependent from from A in fact
491 if((m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) == 0)
492 m_targets.setDestination(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ());
493 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
494 break;
495 case TARGET_BEHIND_VICTIM: // use B case that not dependent from from A in fact
496 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
497 break;
498 default:
499 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
500 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
501 break;
503 break;
504 case TARGET_CASTER_COORDINATES:
505 // Note: this hack with search required until GO casting not implemented
506 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
507 // currently each enemy selected explicitly and self cast damage
508 if(m_spellInfo->EffectImplicitTargetB[i] == TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
510 if(m_targets.getUnitTarget())
511 tmpUnitMap.push_back(m_targets.getUnitTarget());
513 else
515 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
516 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
518 break;
519 case TARGET_TABLE_X_Y_Z_COORDINATES:
520 switch(m_spellInfo->EffectImplicitTargetB[i])
522 case 0:
523 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
525 // need some target for proccesing
526 if(m_targets.getUnitTarget())
527 tmpUnitMap.push_back(m_targets.getUnitTarget());
528 else
529 tmpUnitMap.push_back(m_caster);
530 break;
531 case TARGET_AREAEFFECT_INSTANT: // All 17/7 pairs used for dest teleportation, A processed in effect code
532 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
533 break;
534 default:
535 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
536 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
537 break;
539 break;
540 default:
541 switch(m_spellInfo->EffectImplicitTargetB[i])
543 case 0:
544 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
545 break;
546 case TARGET_SCRIPT_COORDINATES: // B case filled in CheckCast but we need fill unit list base at A case
547 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
548 break;
549 default:
550 SetTargetMap(i, m_spellInfo->EffectImplicitTargetA[i], tmpUnitMap);
551 SetTargetMap(i, m_spellInfo->EffectImplicitTargetB[i], tmpUnitMap);
552 break;
554 break;
557 if( (m_spellInfo->EffectImplicitTargetA[i] == 0 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_EFFECT_SELECT) &&
558 (m_spellInfo->EffectImplicitTargetB[i] == 0 || m_spellInfo->EffectImplicitTargetB[i] == TARGET_EFFECT_SELECT) )
560 // add here custom effects that need default target.
561 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
562 switch(m_spellInfo->Effect[i])
564 case SPELL_EFFECT_DUMMY:
566 switch(m_spellInfo->Id)
568 case 20577: // Cannibalize
570 WorldObject* result = FindCorpseUsing<MaNGOS::CannibalizeObjectCheck> ();
572 if(result)
574 switch(result->GetTypeId())
576 case TYPEID_UNIT:
577 case TYPEID_PLAYER:
578 tmpUnitMap.push_back((Unit*)result);
579 break;
580 case TYPEID_CORPSE:
581 m_targets.setCorpseTarget((Corpse*)result);
582 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
583 tmpUnitMap.push_back(owner);
584 break;
587 else
589 // clear cooldown at fail
590 if(m_caster->GetTypeId() == TYPEID_PLAYER)
591 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id, true);
592 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
593 finish(false);
595 break;
597 default:
598 if(m_targets.getUnitTarget())
599 tmpUnitMap.push_back(m_targets.getUnitTarget());
600 break;
602 break;
604 case SPELL_EFFECT_RESURRECT:
605 case SPELL_EFFECT_PARRY:
606 case SPELL_EFFECT_BLOCK:
607 case SPELL_EFFECT_CREATE_ITEM:
608 case SPELL_EFFECT_TRIGGER_SPELL:
609 case SPELL_EFFECT_TRIGGER_MISSILE:
610 case SPELL_EFFECT_LEARN_SPELL:
611 case SPELL_EFFECT_SKILL_STEP:
612 case SPELL_EFFECT_PROFICIENCY:
613 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
614 case SPELL_EFFECT_SELF_RESURRECT:
615 case SPELL_EFFECT_REPUTATION:
616 case SPELL_EFFECT_SEND_TAXI:
617 if(m_targets.getUnitTarget())
618 tmpUnitMap.push_back(m_targets.getUnitTarget());
619 // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
620 else if(m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL)
621 tmpUnitMap.push_back(m_caster);
622 break;
623 case SPELL_EFFECT_SUMMON_PLAYER:
624 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
626 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
627 if(target)
628 tmpUnitMap.push_back(target);
630 break;
631 case SPELL_EFFECT_RESURRECT_NEW:
632 if(m_targets.getUnitTarget())
633 tmpUnitMap.push_back(m_targets.getUnitTarget());
634 if(m_targets.getCorpseTargetGUID())
636 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
637 if(corpse)
639 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
640 if(owner)
641 tmpUnitMap.push_back(owner);
644 break;
645 case SPELL_EFFECT_SUMMON:
646 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
648 if(m_targets.getUnitTarget())
649 tmpUnitMap.push_back(m_targets.getUnitTarget());
651 else
652 tmpUnitMap.push_back(m_caster);
653 break;
654 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
655 case SPELL_EFFECT_TRANS_DOOR:
656 case SPELL_EFFECT_ADD_FARSIGHT:
657 case SPELL_EFFECT_APPLY_GLYPH:
658 case SPELL_EFFECT_STUCK:
659 case SPELL_EFFECT_FEED_PET:
660 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
661 case SPELL_EFFECT_SKILL:
662 tmpUnitMap.push_back(m_caster);
663 break;
664 case SPELL_EFFECT_LEARN_PET_SPELL:
665 if(Pet* pet = m_caster->GetPet())
666 tmpUnitMap.push_back(pet);
667 break;
668 case SPELL_EFFECT_ENCHANT_ITEM:
669 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
670 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
671 case SPELL_EFFECT_DISENCHANT:
672 case SPELL_EFFECT_PROSPECTING:
673 case SPELL_EFFECT_MILLING:
674 if(m_targets.getItemTarget())
675 AddItemTarget(m_targets.getItemTarget(), i);
676 break;
677 case SPELL_EFFECT_APPLY_AURA:
678 switch(m_spellInfo->EffectApplyAuraName[i])
680 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)
681 case SPELL_AURA_ADD_PCT_MODIFIER:
682 tmpUnitMap.push_back(m_caster);
683 break;
684 default: // apply to target in other case
685 if(m_targets.getUnitTarget())
686 tmpUnitMap.push_back(m_targets.getUnitTarget());
687 break;
689 break;
690 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
691 // AreaAura
692 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
693 SetTargetMap(i,TARGET_AREAEFFECT_PARTY, tmpUnitMap);
694 break;
695 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
696 if(m_targets.getUnitTarget())
698 tmpUnitMap.push_back(m_targets.getUnitTarget());
700 else if (m_targets.getCorpseTargetGUID())
702 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
703 if(corpse)
705 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
706 if(owner)
707 tmpUnitMap.push_back(owner);
710 break;
711 default:
712 break;
716 if(m_caster->GetTypeId() == TYPEID_PLAYER)
718 Player *me = (Player*)m_caster;
719 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
721 Unit *owner = (*itr)->GetOwner();
722 Unit *u = owner ? owner : (*itr);
723 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
725 me->UpdatePvP(true);
726 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
727 break;
732 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end();)
734 if (!CheckTarget (*itr, i))
736 itr = tmpUnitMap.erase(itr);
737 continue;
739 else
740 ++itr;
743 for(std::list<Unit*>::const_iterator iunit = tmpUnitMap.begin(); iunit != tmpUnitMap.end(); ++iunit)
744 AddUnitTarget((*iunit), i);
748 void Spell::prepareDataForTriggerSystem()
750 //==========================================================================================
751 // Now fill data for trigger system, need know:
752 // an spell trigger another or not ( m_canTrigger )
753 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
754 //==========================================================================================
755 // Fill flag can spell trigger or not
756 // TODO: possible exist spell attribute for this
757 m_canTrigger = false;
759 if (m_CastItem)
760 m_canTrigger = false; // Do not trigger from item cast spell
761 else if (!m_IsTriggeredSpell)
762 m_canTrigger = true; // Normal cast - can trigger
763 else if (!m_triggeredByAuraSpell)
764 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
766 if (!m_canTrigger) // Exceptions (some periodic triggers)
768 switch (m_spellInfo->SpellFamilyName)
770 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
771 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0000000000200080))
772 m_canTrigger = true;
773 break;
774 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
775 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0000800000000060))
776 m_canTrigger = true;
777 break;
778 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
779 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0001800000000000))
780 m_canTrigger = true;
781 break;
782 case SPELLFAMILY_ROGUE: // For poisons need do it
783 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x000000101001E000))
784 m_canTrigger = true;
785 break;
786 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot
787 if ((m_spellInfo->SpellFamilyFlags & UI64LIT(0x0100200000000214)) ||
788 m_spellInfo->SpellFamilyFlags2 & 0x200)
789 m_canTrigger = true;
790 break;
791 case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it
792 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0001000900B80400))
793 m_canTrigger = true;
794 break;
795 default:
796 break;
800 // Get data for type of attack and fill base info for trigger
801 switch (m_spellInfo->DmgClass)
803 case SPELL_DAMAGE_CLASS_MELEE:
804 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
805 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
806 break;
807 case SPELL_DAMAGE_CLASS_RANGED:
808 // Auto attack
809 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
811 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
812 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
814 else // Ranged spell attack
816 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
817 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
819 break;
820 default:
821 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
823 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
824 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
826 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
828 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
829 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
831 else // Negative spell
833 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
834 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
836 break;
838 // Hunter traps spells (for Entrapment trigger)
839 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
840 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && (m_spellInfo->SpellFamilyFlags & UI64LIT(0x000020000000001C)))
841 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
844 void Spell::CleanupTargetList()
846 m_UniqueTargetInfo.clear();
847 m_UniqueGOTargetInfo.clear();
848 m_UniqueItemInfo.clear();
849 m_delayMoment = 0;
852 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
854 if( m_spellInfo->Effect[effIndex] == 0 )
855 return;
857 // Check for effect immune skip if immuned
858 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
860 uint64 targetGUID = pVictim->GetGUID();
862 // Lookup target in already in list
863 for(std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
865 if (targetGUID == ihit->targetGUID) // Found in list
867 if (!immuned)
868 ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned
869 return;
873 // This is new target calculate data for him
875 // Get spell hit result on target
876 TargetInfo target;
877 target.targetGUID = targetGUID; // Store target GUID
878 target.effectMask = immuned ? 0 : 1 << effIndex; // Store index of effect if not immuned
879 target.processed = false; // Effects not apply on target
881 // Calculate hit result
882 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
884 // Spell have speed - need calculate incoming time
885 if (m_spellInfo->speed > 0.0f)
887 // calculate spell incoming interval
888 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
889 if (dist < 5.0f) dist = 5.0f;
890 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
892 // Calculate minimum incoming time
893 if (m_delayMoment == 0 || m_delayMoment>target.timeDelay)
894 m_delayMoment = target.timeDelay;
896 else
897 target.timeDelay = UI64LIT(0);
899 // If target reflect spell back to caster
900 if (target.missCondition == SPELL_MISS_REFLECT)
902 // Calculate reflected spell result on caster
903 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
905 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
906 target.reflectResult = SPELL_MISS_PARRY;
908 // Increase time interval for reflected spells by 1.5
909 target.timeDelay += target.timeDelay >> 1;
911 else
912 target.reflectResult = SPELL_MISS_NONE;
914 // Add target to list
915 m_UniqueTargetInfo.push_back(target);
918 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
920 Unit* unit = m_caster->GetGUID() == unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
921 if (unit)
922 AddUnitTarget(unit, effIndex);
925 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
927 if( m_spellInfo->Effect[effIndex] == 0 )
928 return;
930 uint64 targetGUID = pVictim->GetGUID();
932 // Lookup target in already in list
933 for(std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
935 if (targetGUID == ihit->targetGUID) // Found in list
937 ihit->effectMask |= 1 << effIndex; // Add only effect mask
938 return;
942 // This is new target calculate data for him
944 GOTargetInfo target;
945 target.targetGUID = targetGUID;
946 target.effectMask = 1 << effIndex;
947 target.processed = false; // Effects not apply on target
949 // Spell have speed - need calculate incoming time
950 if (m_spellInfo->speed > 0.0f)
952 // calculate spell incoming interval
953 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
954 if (dist < 5.0f) dist = 5.0f;
955 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
956 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
957 m_delayMoment = target.timeDelay;
959 else
960 target.timeDelay = UI64LIT(0);
962 // Add target to list
963 m_UniqueGOTargetInfo.push_back(target);
966 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
968 GameObject* go = m_caster->GetMap()->GetGameObject(goGUID);
969 if (go)
970 AddGOTarget(go, effIndex);
973 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
975 if( m_spellInfo->Effect[effIndex] == 0 )
976 return;
978 // Lookup target in already in list
979 for(std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
981 if (pitem == ihit->item) // Found in list
983 ihit->effectMask |= 1<<effIndex; // Add only effect mask
984 return;
988 // This is new target add data
990 ItemTargetInfo target;
991 target.item = pitem;
992 target.effectMask = 1 << effIndex;
993 m_UniqueItemInfo.push_back(target);
996 void Spell::DoAllEffectOnTarget(TargetInfo *target)
998 if (target->processed) // Check target
999 return;
1000 target->processed = true; // Target checked in apply effects procedure
1002 // Get mask of effects for target
1003 uint32 mask = target->effectMask;
1005 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
1006 if (!unit)
1007 return;
1009 // Get original caster (if exist) and calculate damage/healing from him data
1010 Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
1012 // Skip if m_originalCaster not available
1013 if (!caster)
1014 return;
1016 SpellMissInfo missInfo = target->missCondition;
1017 // Need init unitTarget by default unit (can changed in code on reflect)
1018 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
1019 unitTarget = unit;
1021 // Reset damage/healing counter
1022 m_damage = 0;
1023 m_healing = 0;
1025 // Fill base trigger info
1026 uint32 procAttacker = m_procAttacker;
1027 uint32 procVictim = m_procVictim;
1028 uint32 procEx = PROC_EX_NONE;
1030 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
1031 DoSpellHitOnUnit(unit, mask);
1032 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
1034 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
1035 DoSpellHitOnUnit(m_caster, mask);
1038 // All calculated do it!
1039 // Do healing and triggers
1040 if (m_healing)
1042 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
1043 uint32 addhealth = m_healing;
1044 if (crit)
1046 procEx |= PROC_EX_CRITICAL_HIT;
1047 addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
1049 else
1050 procEx |= PROC_EX_NORMAL_HIT;
1052 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1053 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1054 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
1056 int32 gain = caster->DealHeal(unitTarget, addhealth, m_spellInfo, crit);
1057 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
1059 // Do damage and triggers
1060 else if (m_damage)
1062 // Fill base damage struct (unitTarget - is real spell target)
1063 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1065 // Add bonuses and fill damageInfo struct
1066 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
1067 caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
1069 // Send log damage message to client
1070 caster->SendSpellNonMeleeDamageLog(&damageInfo);
1072 procEx = createProcExtendMask(&damageInfo, missInfo);
1073 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1075 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1076 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1077 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
1079 caster->DealSpellDamage(&damageInfo, true);
1081 // Judgement of Blood
1082 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0000000800000000)) && m_spellInfo->SpellIconID==153)
1084 int32 damagePoint = damageInfo.damage * 33 / 100;
1085 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1088 // Passive spell hits/misses or active spells only misses (only triggers)
1089 else
1091 // Fill base damage struct (unitTarget - is real spell target)
1092 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1093 procEx = createProcExtendMask(&damageInfo, missInfo);
1094 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1095 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1096 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1099 // Call scripted function for AI if this spell is casted upon a creature
1100 if(unit->GetTypeId()==TYPEID_UNIT)
1102 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1103 // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... )
1104 if( !((Creature*)unit)->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1106 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
1107 p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
1110 if(((Creature*)unit)->AI())
1111 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1114 // Call scripted function for AI if this spell is casted by a creature
1115 if(m_caster->GetTypeId()==TYPEID_UNIT && ((Creature*)m_caster)->AI())
1116 ((Creature*)m_caster)->AI()->SpellHitTarget(unit, m_spellInfo);
1119 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1121 if(!unit || !effectMask)
1122 return;
1124 // Recheck immune (only for delayed spells)
1125 if( m_spellInfo->speed && (
1126 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1127 unit->IsImmunedToSpell(m_spellInfo)))
1129 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1130 return;
1133 if (unit->GetTypeId() == TYPEID_PLAYER)
1135 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1136 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1139 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1141 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1144 if( m_caster != unit )
1146 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1147 if (m_spellInfo->speed > 0.0f &&
1148 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1149 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1151 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1152 return;
1155 if( !m_caster->IsFriendlyTo(unit) )
1157 // for delayed spells ignore not visible explicit target
1158 if(m_spellInfo->speed > 0.0f && unit == m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1160 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1161 return;
1164 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1166 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1168 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1169 unit->SetStandState(UNIT_STAND_STATE_STAND);
1171 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1172 ((Creature*)unit)->AI()->AttackedBy(m_caster);
1174 unit->AddThreat(m_caster, 0.0f);
1175 unit->SetInCombatWith(m_caster);
1176 m_caster->SetInCombatWith(unit);
1178 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1180 m_caster->SetContestedPvP(attackedPlayer);
1184 else
1186 // for delayed spells ignore negative spells (after duel end) for friendly targets
1187 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1189 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1190 return;
1193 // assisting case, healing and resurrection
1194 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1195 m_caster->SetContestedPvP();
1196 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1198 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1199 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1204 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1205 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1206 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1207 // Increase Diminishing on unit, current informations for actually casts will use values above
1208 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1209 unit->IncrDiminishing(m_diminishGroup);
1211 // Apply additional spell effects to target
1212 if (m_preCastSpell)
1213 m_caster->CastSpell(unit, m_preCastSpell, true, m_CastItem);
1215 for(uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
1217 if (effectMask & (1 << effectNumber))
1219 HandleEffects(unit, NULL, NULL, effectNumber, m_damageMultipliers[effectNumber]);
1220 if ( m_applyMultiplierMask & (1 << effectNumber) )
1222 // Get multiplier
1223 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1224 // Apply multiplier mods
1225 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1226 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier, this);
1227 m_damageMultipliers[effectNumber] *= multiplier;
1233 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1235 if (target->processed) // Check target
1236 return;
1237 target->processed = true; // Target checked in apply effects procedure
1239 uint32 effectMask = target->effectMask;
1240 if(!effectMask)
1241 return;
1243 GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
1244 if(!go)
1245 return;
1247 for(uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
1248 if (effectMask & (1 << effectNumber))
1249 HandleEffects(NULL, NULL, go, effectNumber);
1251 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1252 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1253 if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1255 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
1256 p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
1260 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1262 uint32 effectMask = target->effectMask;
1263 if(!target->item || !effectMask)
1264 return;
1266 for(uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
1267 if (effectMask & (1 << effectNumber))
1268 HandleEffects(NULL, target->item, NULL, effectNumber);
1271 bool Spell::IsAliveUnitPresentInTargetList()
1273 // Not need check return true
1274 if (m_needAliveTargetMask == 0)
1275 return true;
1277 uint8 needAliveTargetMask = m_needAliveTargetMask;
1279 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
1281 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1283 Unit *unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1285 if (unit && unit->isAlive())
1286 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1290 // is all effects from m_needAliveTargetMask have alive targets
1291 return needAliveTargetMask == 0;
1294 // Helper for Chain Healing
1295 // Spell target first
1296 // Raidmates then descending by injury suffered (MaxHealth - Health)
1297 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1298 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1300 const Unit* MainTarget;
1301 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1302 // functor for operator ">"
1303 bool operator()(Unit const* _Left, Unit const* _Right) const
1305 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1307 int32 ChainHealingHash(Unit const* Target) const
1309 if (Target == MainTarget)
1310 return 0;
1311 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1312 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1314 if (Target->GetHealth() == Target->GetMaxHealth())
1315 return 40000;
1316 else
1317 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1319 else
1320 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1324 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1326 public:
1327 const Unit* MainTarget;
1328 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1330 bool operator()(const Unit* Target)
1332 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1336 // Helper for targets nearest to the spell target
1337 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1338 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1340 const Unit* MainTarget;
1341 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1342 // functor for operator ">"
1343 bool operator()(const Unit* _Left, const Unit* _Right) const
1345 return MainTarget->GetDistanceOrder(_Left,_Right);
1349 void Spell::SetTargetMap(uint32 i,uint32 cur,UnitList& TagUnitMap)
1351 float radius;
1352 if (m_spellInfo->EffectRadiusIndex[i])
1353 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1354 else
1355 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1357 if(m_originalCaster)
1358 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1359 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this);
1361 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1362 if(m_originalCaster)
1363 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1364 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1366 // Get spell max affected targets
1367 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1369 // custom target amount cases
1370 switch(m_spellInfo->SpellFamilyName)
1372 case SPELLFAMILY_DRUID:
1373 // Starfall
1374 if (m_spellInfo->SpellFamilyFlags2 & UI64LIT(0x00000100))
1375 unMaxTargets = 2;
1376 break;
1377 default:
1378 break;
1381 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1382 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1384 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1385 continue;
1386 unMaxTargets+=(*m)->GetModifier()->m_amount;
1389 switch(cur)
1391 case TARGET_TOTEM_EARTH:
1392 case TARGET_TOTEM_WATER:
1393 case TARGET_TOTEM_AIR:
1394 case TARGET_TOTEM_FIRE:
1395 case TARGET_SELF:
1396 case TARGET_SELF2:
1397 case TARGET_DYNAMIC_OBJECT:
1398 case TARGET_AREAEFFECT_CUSTOM:
1399 case TARGET_AREAEFFECT_CUSTOM_2:
1400 case TARGET_SUMMON:
1402 TagUnitMap.push_back(m_caster);
1403 break;
1405 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1407 m_targets.m_targetMask = 0;
1408 unMaxTargets = EffectChainTarget;
1409 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1411 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1412 Cell cell(p);
1413 cell.data.Part.reserved = ALL_DISTRICT;
1414 cell.SetNoCreate();
1416 std::list<Unit *> tempUnitMap;
1419 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1420 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1422 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1423 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1425 CellLock<GridReadGuard> cell_lock(cell, p);
1426 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1427 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1430 if(tempUnitMap.empty())
1431 break;
1433 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1435 //Now to get us a random target that's in the initial range of the spell
1436 uint32 t = 0;
1437 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1438 while(itr!= tempUnitMap.end() && (*itr)->IsWithinDist(m_caster,radius))
1439 ++t, ++itr;
1441 if(!t)
1442 break;
1444 itr = tempUnitMap.begin();
1445 std::advance(itr, rand()%t);
1446 Unit *pUnitTarget = *itr;
1447 TagUnitMap.push_back(pUnitTarget);
1449 tempUnitMap.erase(itr);
1451 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1453 t = unMaxTargets - 1;
1454 Unit *prev = pUnitTarget;
1455 std::list<Unit*>::iterator next = tempUnitMap.begin();
1457 while(t && next != tempUnitMap.end() )
1459 if(!prev->IsWithinDist(*next,CHAIN_SPELL_JUMP_RADIUS))
1460 break;
1462 if(!prev->IsWithinLOSInMap(*next))
1464 ++next;
1465 continue;
1468 prev = *next;
1469 TagUnitMap.push_back(prev);
1470 tempUnitMap.erase(next);
1471 tempUnitMap.sort(TargetDistanceOrder(prev));
1472 next = tempUnitMap.begin();
1474 --t;
1476 }break;
1477 case TARGET_RANDOM_FRIEND_CHAIN_IN_AREA:
1479 m_targets.m_targetMask = 0;
1480 unMaxTargets = EffectChainTarget;
1481 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1482 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1483 Cell cell(p);
1484 cell.data.Part.reserved = ALL_DISTRICT;
1485 cell.SetNoCreate();
1486 std::list<Unit *> tempUnitMap;
1488 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1489 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1491 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1492 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1494 CellLock<GridReadGuard> cell_lock(cell, p);
1495 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1496 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1499 if(tempUnitMap.empty())
1500 break;
1502 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1504 //Now to get us a random target that's in the initial range of the spell
1505 uint32 t = 0;
1506 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1507 while(itr!= tempUnitMap.end() && (*itr)->IsWithinDist(m_caster,radius))
1508 ++t, ++itr;
1510 if(!t)
1511 break;
1513 itr = tempUnitMap.begin();
1514 std::advance(itr, rand()%t);
1515 Unit *pUnitTarget = *itr;
1516 TagUnitMap.push_back(pUnitTarget);
1518 tempUnitMap.erase(itr);
1520 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1522 t = unMaxTargets - 1;
1523 Unit *prev = pUnitTarget;
1524 std::list<Unit*>::iterator next = tempUnitMap.begin();
1526 while(t && next != tempUnitMap.end() )
1528 if(!prev->IsWithinDist(*next,CHAIN_SPELL_JUMP_RADIUS))
1529 break;
1531 if(!prev->IsWithinLOSInMap(*next))
1533 ++next;
1534 continue;
1536 prev = *next;
1537 TagUnitMap.push_back(prev);
1538 tempUnitMap.erase(next);
1539 tempUnitMap.sort(TargetDistanceOrder(prev));
1540 next = tempUnitMap.begin();
1541 --t;
1543 }break;
1544 case TARGET_PET:
1546 Pet* tmpUnit = m_caster->GetPet();
1547 if (!tmpUnit) break;
1548 TagUnitMap.push_back(tmpUnit);
1549 break;
1551 case TARGET_CHAIN_DAMAGE:
1553 if (EffectChainTarget <= 1)
1555 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1557 m_targets.setUnitTarget(pUnitTarget);
1558 TagUnitMap.push_back(pUnitTarget);
1561 else
1563 Unit* pUnitTarget = m_targets.getUnitTarget();
1564 if(!pUnitTarget)
1565 break;
1567 unMaxTargets = EffectChainTarget;
1569 float max_range;
1570 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1571 max_range = radius; //
1572 else
1573 //FIXME: This very like horrible hack and wrong for most spells
1574 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1576 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1577 Cell cell(p);
1578 cell.data.Part.reserved = ALL_DISTRICT;
1579 cell.SetNoCreate();
1581 Unit* originalCaster = GetOriginalCaster();
1582 if(originalCaster)
1584 std::list<Unit *> tempUnitMap;
1587 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range, false);
1588 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(m_caster, tempUnitMap, u_check);
1590 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1591 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1593 CellLock<GridReadGuard> cell_lock(cell, p);
1594 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1595 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1598 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1600 if(tempUnitMap.empty())
1601 break;
1603 if(*tempUnitMap.begin() == pUnitTarget)
1604 tempUnitMap.erase(tempUnitMap.begin());
1606 TagUnitMap.push_back(pUnitTarget);
1607 uint32 t = unMaxTargets - 1;
1608 Unit *prev = pUnitTarget;
1609 std::list<Unit*>::iterator next = tempUnitMap.begin();
1611 while(t && next != tempUnitMap.end() )
1613 if(!prev->IsWithinDist(*next,CHAIN_SPELL_JUMP_RADIUS))
1614 break;
1616 if(!prev->IsWithinLOSInMap(*next))
1618 ++next;
1619 continue;
1622 prev = *next;
1623 TagUnitMap.push_back(prev);
1624 tempUnitMap.erase(next);
1625 tempUnitMap.sort(TargetDistanceOrder(prev));
1626 next = tempUnitMap.begin();
1628 --t;
1632 }break;
1633 case TARGET_ALL_ENEMY_IN_AREA:
1635 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1636 break;
1638 case TARGET_AREAEFFECT_INSTANT:
1640 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1641 // Select friendly targets for positive effect
1642 if (IsPositiveEffect(m_spellInfo->Id, i))
1643 targetB = SPELL_TARGETS_FRIENDLY;
1645 FillAreaTargets(TagUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),radius, PUSH_DEST_CENTER, targetB);
1647 // exclude caster
1648 TagUnitMap.remove(m_caster);
1650 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1652 // targets the ground, not the units in the area
1653 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1655 FillAreaTargets(TagUnitMap,m_targets.m_destX, m_targets.m_destY,radius,PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1657 // exclude caster (this can be important if this not original caster)
1658 TagUnitMap.remove(m_caster);
1660 }break;
1661 case TARGET_DUELVSPLAYER_COORDINATES:
1663 if(Unit* currentTarget = m_targets.getUnitTarget())
1665 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1666 TagUnitMap.push_back(currentTarget);
1668 }break;
1669 case TARGET_ALL_PARTY_AROUND_CASTER:
1670 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1671 case TARGET_ALL_PARTY:
1673 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1674 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1676 if(pGroup)
1678 uint8 subgroup = pTarget->GetSubGroup();
1680 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1682 Player* Target = itr->getSource();
1684 // IsHostileTo check duel and controlled by enemy
1685 if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1687 if( m_caster->IsWithinDistInMap(Target, radius) )
1688 TagUnitMap.push_back(Target);
1690 if(Pet* pet = Target->GetPet())
1691 if( m_caster->IsWithinDistInMap(pet, radius) )
1692 TagUnitMap.push_back(pet);
1696 else
1698 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1699 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1700 TagUnitMap.push_back(ownerOrSelf);
1701 if(Pet* pet = ownerOrSelf->GetPet())
1702 if( m_caster->IsWithinDistInMap(pet, radius) )
1703 TagUnitMap.push_back(pet);
1705 break;
1707 case TARGET_ALL_RAID_AROUND_CASTER:
1709 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1710 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1712 if(m_spellInfo->Id == 57669) // Replenishment (special target selection)
1714 if(pGroup)
1716 typedef std::priority_queue<PrioritizeManaPlayerWraper, std::vector<PrioritizeManaPlayerWraper>, PrioritizeMana> Top10;
1717 Top10 manaUsers;
1719 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL && manaUsers.size() < 10; itr = itr->next())
1721 Player* Target = itr->getSource();
1722 if (m_caster->GetGUID() != Target->GetGUID() && Target->getPowerType() == POWER_MANA &&
1723 !Target->isDead() && m_caster->IsWithinDistInMap(Target, radius))
1725 PrioritizeManaPlayerWraper WTarget(Target);
1726 manaUsers.push(WTarget);
1730 while(!manaUsers.empty())
1732 TagUnitMap.push_back(manaUsers.top().getPlayer());
1733 manaUsers.pop();
1736 else
1738 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1739 if ((ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius)) &&
1740 ownerOrSelf->getPowerType() == POWER_MANA)
1741 TagUnitMap.push_back(ownerOrSelf);
1743 if(Pet* pet = ownerOrSelf->GetPet())
1744 if( m_caster->IsWithinDistInMap(pet, radius) && pet->getPowerType() == POWER_MANA )
1745 TagUnitMap.push_back(pet);
1748 if (m_spellInfo->Id==52759) //Ancestral Awakening (special target selection)
1750 float lowestPerc = (float)m_caster->GetHealth() / (float)m_caster->GetMaxHealth();
1751 Unit* lowestTarget = m_caster;
1753 if (pGroup)
1755 Group::MemberSlotList const& members = pGroup->GetMemberSlots();
1756 Group::MemberSlotList::const_iterator itr = members.begin();
1757 for(; itr != members.end(); ++itr)
1759 if (Unit* member = ObjectAccessor::GetPlayer(*m_caster, (*itr).guid))
1761 if (member == m_caster || member->isDead() || m_caster->IsHostileTo(member) || !m_caster->IsWithinDistInMap(member, radius))
1762 continue;
1764 float perc = (float)member->GetHealth() / (float)member->GetMaxHealth();
1765 if (perc <= lowestPerc)
1767 lowestPerc = perc;
1768 lowestTarget = member;
1773 TagUnitMap.push_back(lowestTarget);
1775 else
1777 if(pGroup)
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 && !m_caster->IsHostileTo(Target) )
1786 if( m_caster->IsWithinDistInMap(Target, radius) )
1787 TagUnitMap.push_back(Target);
1789 if(Pet* pet = Target->GetPet())
1790 if( m_caster->IsWithinDistInMap(pet, radius) )
1791 TagUnitMap.push_back(pet);
1795 else
1797 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1798 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1799 TagUnitMap.push_back(ownerOrSelf);
1800 if(Pet* pet = ownerOrSelf->GetPet())
1801 if( m_caster->IsWithinDistInMap(pet, radius) )
1802 TagUnitMap.push_back(pet);
1805 break;
1807 case TARGET_SINGLE_FRIEND:
1808 case TARGET_SINGLE_FRIEND_2:
1810 if(m_targets.getUnitTarget())
1811 TagUnitMap.push_back(m_targets.getUnitTarget());
1812 }break;
1813 case TARGET_NONCOMBAT_PET:
1815 if(Unit* target = m_targets.getUnitTarget())
1816 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1817 TagUnitMap.push_back(target);
1818 }break;
1819 case TARGET_CASTER_COORDINATES:
1821 // Check original caster is GO - set its coordinates as dst cast
1822 WorldObject *caster = NULL;
1823 if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
1824 caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
1825 if (!caster)
1826 caster = m_caster;
1827 // Set dest for targets
1828 m_targets.setDestination(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ());
1829 }break;
1830 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1831 FillAreaTargets(TagUnitMap, m_targets.m_destX, m_targets.m_destY, radius, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1832 break;
1833 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1834 FillAreaTargets(TagUnitMap, m_targets.m_destX, m_targets.m_destY, radius, PUSH_DEST_CENTER, SPELL_TARGETS_FRIENDLY);
1835 break;
1836 // 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..)
1837 case TARGET_SINGLE_PARTY:
1839 Unit *target = m_targets.getUnitTarget();
1840 // Thoses spells apparently can't be casted on the caster.
1841 if( target && target != m_caster)
1843 // Can only be casted on group's members or its pets
1844 Group *pGroup = NULL;
1846 Unit* owner = m_caster->GetCharmerOrOwner();
1847 Unit *targetOwner = target->GetCharmerOrOwner();
1848 if(owner)
1850 if(owner->GetTypeId() == TYPEID_PLAYER)
1852 if( target == owner )
1854 TagUnitMap.push_back(target);
1855 break;
1857 pGroup = ((Player*)owner)->GetGroup();
1860 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1862 if( targetOwner == m_caster && target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet())
1864 TagUnitMap.push_back(target);
1865 break;
1867 pGroup = ((Player*)m_caster)->GetGroup();
1870 if(pGroup)
1872 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1873 if(targetOwner)
1875 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1876 target->GetTypeId() == TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1877 target->GetOwnerGUID() == targetOwner->GetGUID() &&
1878 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1880 TagUnitMap.push_back(target);
1883 // 1Our target can be a player who is on our group
1884 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1886 TagUnitMap.push_back(target);
1890 }break;
1891 case TARGET_GAMEOBJECT:
1893 if(m_targets.getGOTarget())
1894 AddGOTarget(m_targets.getGOTarget(), i);
1895 }break;
1896 case TARGET_IN_FRONT_OF_CASTER:
1898 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1899 FillAreaTargets(TagUnitMap,m_caster->GetPositionX(), m_caster->GetPositionY(),radius,inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1900 break;
1902 case TARGET_DUELVSPLAYER:
1904 Unit *target = m_targets.getUnitTarget();
1905 if(target)
1907 if(m_caster->IsFriendlyTo(target))
1909 TagUnitMap.push_back(target);
1911 else
1913 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1915 m_targets.setUnitTarget(pUnitTarget);
1916 TagUnitMap.push_back(pUnitTarget);
1920 }break;
1921 case TARGET_GAMEOBJECT_ITEM:
1923 if(m_targets.getGOTargetGUID())
1924 AddGOTarget(m_targets.getGOTarget(), i);
1925 else if(m_targets.getItemTarget())
1926 AddItemTarget(m_targets.getItemTarget(), i);
1927 break;
1929 case TARGET_MASTER:
1931 if(Unit* owner = m_caster->GetCharmerOrOwner())
1932 TagUnitMap.push_back(owner);
1933 break;
1935 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1937 // targets the ground, not the units in the area
1938 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1939 FillAreaTargets(TagUnitMap, m_targets.m_destX, m_targets.m_destY, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1940 break;
1942 case TARGET_MINION:
1944 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1945 TagUnitMap.push_back(m_caster);
1946 }break;
1947 case TARGET_SINGLE_ENEMY:
1949 if(Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), m_spellInfo))
1951 m_targets.setUnitTarget(pUnitTarget);
1952 TagUnitMap.push_back(pUnitTarget);
1954 }break;
1955 case TARGET_AREAEFFECT_PARTY:
1957 Unit* owner = m_caster->GetCharmerOrOwner();
1958 Player *pTarget = NULL;
1960 if(owner)
1962 TagUnitMap.push_back(m_caster);
1963 if(owner->GetTypeId() == TYPEID_PLAYER)
1964 pTarget = (Player*)owner;
1966 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1968 if(Unit* target = m_targets.getUnitTarget())
1970 if( target->GetTypeId() != TYPEID_PLAYER)
1972 if(((Creature*)target)->isPet())
1974 Unit *targetOwner = target->GetOwner();
1975 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1976 pTarget = (Player*)targetOwner;
1979 else
1980 pTarget = (Player*)target;
1984 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1986 if(pGroup)
1988 uint8 subgroup = pTarget->GetSubGroup();
1990 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1992 Player* Target = itr->getSource();
1994 // IsHostileTo check duel and controlled by enemy
1995 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1997 if( pTarget->IsWithinDistInMap(Target, radius) )
1998 TagUnitMap.push_back(Target);
2000 if(Pet* pet = Target->GetPet())
2001 if( pTarget->IsWithinDistInMap(pet, radius) )
2002 TagUnitMap.push_back(pet);
2006 else if (owner)
2008 if(m_caster->IsWithinDistInMap(owner, radius))
2009 TagUnitMap.push_back(owner);
2011 else if(pTarget)
2013 TagUnitMap.push_back(pTarget);
2015 if(Pet* pet = pTarget->GetPet())
2016 if( m_caster->IsWithinDistInMap(pet, radius) )
2017 TagUnitMap.push_back(pet);
2020 }break;
2021 case TARGET_SCRIPT:
2023 if(m_targets.getUnitTarget())
2024 TagUnitMap.push_back(m_targets.getUnitTarget());
2025 if(m_targets.getItemTarget())
2026 AddItemTarget(m_targets.getItemTarget(), i);
2027 }break;
2028 case TARGET_SELF_FISHING:
2030 TagUnitMap.push_back(m_caster);
2031 }break;
2032 case TARGET_CHAIN_HEAL:
2034 Unit* pUnitTarget = m_targets.getUnitTarget();
2035 if(!pUnitTarget)
2036 break;
2038 if (EffectChainTarget <= 1)
2039 TagUnitMap.push_back(pUnitTarget);
2040 else
2042 unMaxTargets = EffectChainTarget;
2043 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
2045 UnitList tempUnitMap;
2047 FillAreaTargets(tempUnitMap, m_caster->GetPositionX(), m_caster->GetPositionY(), max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
2049 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(), m_caster) == tempUnitMap.end() )
2050 tempUnitMap.push_front(m_caster);
2052 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
2054 if(tempUnitMap.empty())
2055 break;
2057 if(*tempUnitMap.begin() == pUnitTarget)
2058 tempUnitMap.erase(tempUnitMap.begin());
2060 TagUnitMap.push_back(pUnitTarget);
2061 uint32 t = unMaxTargets - 1;
2062 Unit *prev = pUnitTarget;
2063 std::list<Unit*>::iterator next = tempUnitMap.begin();
2065 while(t && next != tempUnitMap.end() )
2067 if(!prev->IsWithinDist(*next, CHAIN_SPELL_JUMP_RADIUS))
2068 break;
2070 if(!prev->IsWithinLOSInMap(*next))
2072 ++next;
2073 continue;
2076 if((*next)->GetHealth() == (*next)->GetMaxHealth())
2078 next = tempUnitMap.erase(next);
2079 continue;
2082 prev = *next;
2083 TagUnitMap.push_back(prev);
2084 tempUnitMap.erase(next);
2085 tempUnitMap.sort(TargetDistanceOrder(prev));
2086 next = tempUnitMap.begin();
2088 --t;
2091 }break;
2092 case TARGET_CURRENT_ENEMY_COORDINATES:
2094 Unit* currentTarget = m_targets.getUnitTarget();
2095 if(currentTarget)
2097 TagUnitMap.push_back(currentTarget);
2098 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
2099 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
2100 FillAreaTargets(TagUnitMap, currentTarget->GetPositionX(), currentTarget->GetPositionY(), radius, PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
2102 break;
2104 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
2106 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
2107 ? (Player*)m_targets.getUnitTarget() : NULL;
2109 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
2110 if(pGroup)
2112 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
2114 Player* Target = itr->getSource();
2116 // IsHostileTo check duel and controlled by enemy
2117 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
2118 targetPlayer->getClass() == Target->getClass() &&
2119 !m_caster->IsHostileTo(Target) )
2121 TagUnitMap.push_back(Target);
2125 else if(m_targets.getUnitTarget())
2126 TagUnitMap.push_back(m_targets.getUnitTarget());
2127 break;
2129 case TARGET_TABLE_X_Y_Z_COORDINATES:
2131 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
2132 if(st)
2134 if (st->target_mapId == m_caster->GetMapId())
2135 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
2136 else
2137 sLog.outError( "SPELL: wrong map (%u instead %u) target coordinates for spell ID %u", st->target_mapId, m_caster->GetMapId(), m_spellInfo->Id );
2139 else
2140 sLog.outError( "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id );
2141 }break;
2142 case TARGET_BEHIND_VICTIM:
2144 Unit *pTarget = NULL;
2146 // explicit cast data from client or server-side cast
2147 // some spell at client send caster
2148 if(m_targets.getUnitTarget() && m_targets.getUnitTarget()!=m_caster)
2149 pTarget = m_targets.getUnitTarget();
2150 else if(m_caster->getVictim())
2151 pTarget = m_caster->getVictim();
2152 else if(m_caster->GetTypeId() == TYPEID_PLAYER)
2153 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
2155 if(pTarget)
2157 float _target_x, _target_y, _target_z;
2158 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
2159 if(pTarget->IsWithinLOS(_target_x, _target_y, _target_z))
2161 TagUnitMap.push_back(m_caster);
2162 m_targets.setDestination(_target_x, _target_y, _target_z);
2165 break;
2167 case TARGET_DYNAMIC_OBJECT_COORDINATES:
2169 // if parent spell create dynamic object extract area from it
2170 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
2171 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
2172 break;
2174 case TARGET_DIRECTLY_FORWARD:
2176 if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION))
2178 SpellRangeEntry const* rEntry = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
2179 float minRange = GetSpellMinRange(rEntry);
2180 float maxRange = GetSpellMaxRange(rEntry);
2181 float dist = minRange+ rand_norm()*(maxRange-minRange);
2183 float _target_x, _target_y, _target_z;
2184 m_caster->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), dist);
2185 m_targets.setDestination(_target_x, _target_y, _target_z);
2188 TagUnitMap.push_back(m_caster);
2189 break;
2191 default:
2192 break;
2195 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2197 // make sure one unit is always removed per iteration
2198 uint32 removed_utarget = 0;
2199 for (UnitList::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2201 next = itr;
2202 ++next;
2203 if (!*itr) continue;
2204 if ((*itr) == m_targets.getUnitTarget())
2206 TagUnitMap.erase(itr);
2207 removed_utarget = 1;
2208 // break;
2211 // remove random units from the map
2212 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2214 uint32 poz = urand(0, TagUnitMap.size()-1);
2215 for (UnitList::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2217 if (!*itr) continue;
2219 if (!poz)
2221 TagUnitMap.erase(itr);
2222 break;
2226 // the player's target will always be added to the map
2227 if (removed_utarget && m_targets.getUnitTarget())
2228 TagUnitMap.push_back(m_targets.getUnitTarget());
2232 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2234 m_targets = *targets;
2236 m_spellState = SPELL_STATE_PREPARING;
2238 m_castPositionX = m_caster->GetPositionX();
2239 m_castPositionY = m_caster->GetPositionY();
2240 m_castPositionZ = m_caster->GetPositionZ();
2241 m_castOrientation = m_caster->GetOrientation();
2243 if(triggeredByAura)
2244 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2246 // create and add update event for this spell
2247 SpellEvent* Event = new SpellEvent(this);
2248 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2250 //Prevent casting at cast another spell (ServerSide check)
2251 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2253 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2254 finish(false);
2255 return;
2258 // Fill cost data
2259 m_powerCost = CalculatePowerCost();
2261 SpellCastResult result = CheckCast(true);
2262 if(result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2264 if(triggeredByAura)
2266 SendChannelUpdate(0);
2267 triggeredByAura->SetAuraDuration(0);
2269 SendCastResult(result);
2270 finish(false);
2271 return;
2274 // Prepare data for triggers
2275 prepareDataForTriggerSystem();
2277 // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
2278 m_casttime = GetSpellCastTime(m_spellInfo, this);
2280 // set timer base at cast time
2281 ReSetTimer();
2283 // stealth must be removed at cast starting (at show channel bar)
2284 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2285 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2287 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2288 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2291 if(m_IsTriggeredSpell)
2292 cast(true);
2293 else
2295 m_caster->SetCurrentCastedSpell( this );
2296 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2297 SendSpellStart();
2301 void Spell::cancel()
2303 if(m_spellState == SPELL_STATE_FINISHED)
2304 return;
2306 m_autoRepeat = false;
2307 switch (m_spellState)
2309 case SPELL_STATE_PREPARING:
2310 case SPELL_STATE_DELAYED:
2312 SendInterrupted(0);
2313 SendCastResult(SPELL_FAILED_INTERRUPTED);
2314 } break;
2316 case SPELL_STATE_CASTING:
2318 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2320 if( ihit->missCondition == SPELL_MISS_NONE )
2322 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2323 if( unit && unit->isAlive() )
2324 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2328 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2329 SendChannelUpdate(0);
2330 SendInterrupted(0);
2331 SendCastResult(SPELL_FAILED_INTERRUPTED);
2332 } break;
2334 default:
2336 } break;
2339 finish(false);
2340 m_caster->RemoveDynObject(m_spellInfo->Id);
2341 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2344 void Spell::cast(bool skipCheck)
2346 SetExecutedCurrently(true);
2348 // update pointers base at GUIDs to prevent access to non-existed already object
2349 UpdatePointers();
2351 // cancel at lost main target unit
2352 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2354 cancel();
2355 SetExecutedCurrently(false);
2356 return;
2359 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2360 m_caster->SetInFront(m_targets.getUnitTarget());
2362 SpellCastResult castResult = CheckPower();
2363 if(castResult != SPELL_CAST_OK)
2365 SendCastResult(castResult);
2366 finish(false);
2367 SetExecutedCurrently(false);
2368 return;
2371 // triggered cast called from Spell::prepare where it was already checked
2372 if(!skipCheck)
2374 castResult = CheckCast(false);
2375 if(castResult != SPELL_CAST_OK)
2377 SendCastResult(castResult);
2378 finish(false);
2379 SetExecutedCurrently(false);
2380 return;
2384 switch(m_spellInfo->SpellFamilyName)
2386 case SPELLFAMILY_GENERIC:
2388 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2389 m_preCastSpell = 11196; // Recently Bandaged
2390 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2391 m_preCastSpell = 23230; // Blood Fury - Healing Reduction
2392 break;
2394 case SPELLFAMILY_MAGE:
2396 // Ice Block
2397 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0000008000000000))
2398 m_preCastSpell = 41425; // Hypothermia
2399 break;
2401 case SPELLFAMILY_PRIEST:
2403 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2404 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2405 m_preCastSpell = 6788; // Weakened Soul
2406 if (m_spellInfo->Id == 47585) // Dispersion (transform)
2407 m_preCastSpell = 60069; // Dispersion (mana regen)
2408 break;
2410 case SPELLFAMILY_PALADIN:
2412 // Divine Shield, Divine Protection or Hand of Protection
2413 if (m_spellInfo->SpellFamilyFlags & UI64LIT(0x0000000000400080))
2414 m_preCastSpell = 25771; // Forbearance
2415 break;
2417 case SPELLFAMILY_SHAMAN:
2419 if (m_spellInfo->Id == 2825) // Bloodlust
2420 m_preCastSpell = 57724; // Sated
2421 else if (m_spellInfo->Id == 32182) // Heroism
2422 m_preCastSpell = 57723; // Exhaustion
2423 break;
2425 default:
2426 break;
2429 // Conflagrate - consumes immolate
2430 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2432 // for caster applied auras only
2433 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2434 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2436 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2437 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2439 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2440 break;
2445 // traded items have trade slot instead of guid in m_itemTargetGUID
2446 // set to real guid to be sent later to the client
2447 m_targets.updateTradeSlotItem();
2449 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2451 if (!m_IsTriggeredSpell && m_CastItem)
2452 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2454 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2457 FillTargetMap();
2459 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in FillTargetMap
2461 SetExecutedCurrently(false);
2462 return;
2465 // CAST SPELL
2466 SendSpellCooldown();
2468 TakePower();
2469 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2471 SendCastResult(castResult);
2472 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2474 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2475 if (m_spellInfo->speed > 0.0f)
2478 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2479 // in case delayed spell remove item at cast delay start
2480 TakeCastItem();
2482 // Okay, maps created, now prepare flags
2483 m_immediateHandled = false;
2484 m_spellState = SPELL_STATE_DELAYED;
2485 SetDelayStart(0);
2487 else
2489 // Immediate spell, no big deal
2490 handle_immediate();
2493 SetExecutedCurrently(false);
2496 void Spell::handle_immediate()
2498 // start channeling if applicable
2499 if(IsChanneledSpell(m_spellInfo))
2501 int32 duration = GetSpellDuration(m_spellInfo);
2502 if (duration)
2504 // Apply duration mod
2505 if(Player* modOwner = m_caster->GetSpellModOwner())
2506 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
2507 m_spellState = SPELL_STATE_CASTING;
2508 SendChannelStart(duration);
2512 // process immediate effects (items, ground, etc.) also initialize some variables
2513 _handle_immediate_phase();
2515 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2516 DoAllEffectOnTarget(&(*ihit));
2518 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2519 DoAllEffectOnTarget(&(*ihit));
2521 // spell is finished, perform some last features of the spell here
2522 _handle_finish_phase();
2524 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2525 TakeCastItem();
2527 if(m_spellState != SPELL_STATE_CASTING)
2528 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2531 uint64 Spell::handle_delayed(uint64 t_offset)
2533 uint64 next_time = 0;
2535 if (!m_immediateHandled)
2537 _handle_immediate_phase();
2538 m_immediateHandled = true;
2541 // 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)
2542 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2544 if (ihit->processed == false)
2546 if ( ihit->timeDelay <= t_offset )
2547 DoAllEffectOnTarget(&(*ihit));
2548 else if( next_time == 0 || ihit->timeDelay < next_time )
2549 next_time = ihit->timeDelay;
2553 // now recheck gameobject targeting correctness
2554 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2556 if (ighit->processed == false)
2558 if ( ighit->timeDelay <= t_offset )
2559 DoAllEffectOnTarget(&(*ighit));
2560 else if( next_time == 0 || ighit->timeDelay < next_time )
2561 next_time = ighit->timeDelay;
2564 // All targets passed - need finish phase
2565 if (next_time == 0)
2567 // spell is finished, perform some last features of the spell here
2568 _handle_finish_phase();
2570 finish(true); // successfully finish spell cast
2572 // return zero, spell is finished now
2573 return 0;
2575 else
2577 // spell is unfinished, return next execution time
2578 return next_time;
2582 void Spell::_handle_immediate_phase()
2584 // handle some immediate features of the spell here
2585 HandleThreatSpells(m_spellInfo->Id);
2587 m_needSpellLog = IsNeedSendToClient();
2588 for(uint32 j = 0; j < 3; ++j)
2590 if(m_spellInfo->Effect[j] == 0)
2591 continue;
2593 // apply Send Event effect to ground in case empty target lists
2594 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2596 HandleEffects(NULL, NULL, NULL, j);
2597 continue;
2600 // Don't do spell log, if is school damage spell
2601 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2602 m_needSpellLog = false;
2604 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2605 if(m_originalCaster)
2606 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2607 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2609 // initialize multipliers
2610 m_damageMultipliers[j] = 1.0f;
2611 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2612 (EffectChainTarget > 1) )
2613 m_applyMultiplierMask |= 1 << j;
2616 // initialize Diminishing Returns Data
2617 m_diminishLevel = DIMINISHING_LEVEL_1;
2618 m_diminishGroup = DIMINISHING_NONE;
2620 // process items
2621 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2622 DoAllEffectOnTarget(&(*ihit));
2624 // process ground
2625 for(uint32 j = 0; j < 3; ++j)
2627 // persistent area auras target only the ground
2628 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2629 HandleEffects(NULL, NULL, NULL, j);
2633 void Spell::_handle_finish_phase()
2635 // spell log
2636 if(m_needSpellLog)
2637 SendLogExecute();
2640 void Spell::SendSpellCooldown()
2642 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2643 return;
2645 Player* _player = (Player*)m_caster;
2647 // mana/health/etc potions, disabled by client (until combat out as declarate)
2648 if (m_CastItem && m_CastItem->IsPotion())
2650 // need in some way provided data for Spell::finish SendCooldownEvent
2651 _player->SetLastPotionId(m_CastItem->GetEntry());
2652 return;
2655 // have infinity cooldown but set at aura apply
2656 if(m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2657 return;
2659 _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this);
2662 void Spell::update(uint32 difftime)
2664 // update pointers based at it's GUIDs
2665 UpdatePointers();
2667 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2669 cancel();
2670 return;
2673 // check if the player caster has moved before the spell finished
2674 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2675 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2676 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2678 // always cancel for channeled spells
2679 if( m_spellState == SPELL_STATE_CASTING )
2680 cancel();
2681 // don't cancel for melee, autorepeat, triggered and instant spells
2682 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2683 cancel();
2686 switch(m_spellState)
2688 case SPELL_STATE_PREPARING:
2690 if(m_timer)
2692 if(difftime >= m_timer)
2693 m_timer = 0;
2694 else
2695 m_timer -= difftime;
2698 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2699 cast();
2700 } break;
2701 case SPELL_STATE_CASTING:
2703 if(m_timer > 0)
2705 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2707 // check if player has jumped before the channeling finished
2708 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2709 cancel();
2711 // check for incapacitating player states
2712 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2713 cancel();
2715 // check if player has turned if flag is set
2716 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2717 cancel();
2720 // check if there are alive targets left
2721 if (!IsAliveUnitPresentInTargetList())
2723 SendChannelUpdate(0);
2724 finish();
2727 if(difftime >= m_timer)
2728 m_timer = 0;
2729 else
2730 m_timer -= difftime;
2733 if(m_timer == 0)
2735 SendChannelUpdate(0);
2737 // channeled spell processed independently for quest targeting
2738 // cast at creature (or GO) quest objectives update at successful cast channel finished
2739 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2740 if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2742 if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
2744 for(std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
2746 TargetInfo* target = &*ihit;
2747 if(!IS_CREATURE_GUID(target->targetGUID))
2748 continue;
2750 Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
2751 if (unit == NULL)
2752 continue;
2754 p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
2757 for(std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
2759 GOTargetInfo* target = &*ihit;
2761 GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
2762 if(!go)
2763 continue;
2765 p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
2770 finish();
2772 } break;
2773 default:
2775 }break;
2779 void Spell::finish(bool ok)
2781 if(!m_caster)
2782 return;
2784 if(m_spellState == SPELL_STATE_FINISHED)
2785 return;
2787 m_spellState = SPELL_STATE_FINISHED;
2789 // other code related only to successfully finished spells
2790 if(!ok)
2791 return;
2793 //remove spell mods
2794 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2795 ((Player*)m_caster)->RemoveSpellMods(this);
2797 // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2798 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2799 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2801 if (!(*i)->isAffectedOnSpell(m_spellInfo))
2802 continue;
2803 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2804 if( ihit->missCondition == SPELL_MISS_NONE )
2806 // check m_caster->GetGUID() let load auras at login and speedup most often case
2807 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2808 if (unit && unit->isAlive())
2810 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2811 uint32 auraSpellIdx = (*i)->GetEffIndex();
2812 // Calculate chance at that moment (can be depend for example from combo points)
2813 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2814 if(roll_chance_i(chance))
2815 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2820 // Heal caster for all health leech from all targets
2821 if (m_healthLeech)
2822 m_caster->DealHeal(m_caster, uint32(m_healthLeech), m_spellInfo);
2824 if (IsMeleeAttackResetSpell())
2826 m_caster->resetAttackTimer(BASE_ATTACK);
2827 if(m_caster->haveOffhandWeapon())
2828 m_caster->resetAttackTimer(OFF_ATTACK);
2831 /*if (IsRangedAttackResetSpell())
2832 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2834 // Clear combo at finish state
2835 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2837 // Not drop combopoints if negative spell and if any miss on enemy exist
2838 bool needDrop = true;
2839 if (!IsPositiveSpell(m_spellInfo->Id))
2840 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2841 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2843 needDrop = false;
2844 break;
2846 if (needDrop)
2847 ((Player*)m_caster)->ClearComboPoints();
2850 // potions disabled by client, send event "not in combat" if need
2851 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2852 ((Player*)m_caster)->UpdatePotionCooldown(this);
2854 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2855 if(!m_TriggerSpells.empty())
2856 TriggerSpell();
2858 // Stop Attack for some spells
2859 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2860 m_caster->AttackStop();
2863 void Spell::SendCastResult(SpellCastResult result)
2865 if(result == SPELL_CAST_OK)
2866 return;
2868 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2869 return;
2871 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2872 return;
2874 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2875 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2876 data << uint32(m_spellInfo->Id);
2877 data << uint8(result); // problem
2878 switch (result)
2880 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2881 data << uint32(m_spellInfo->RequiresSpellFocus);
2882 break;
2883 case SPELL_FAILED_REQUIRES_AREA:
2884 // hardcode areas limitation case
2885 switch(m_spellInfo->Id)
2887 case 41617: // Cenarion Mana Salve
2888 case 41619: // Cenarion Healing Salve
2889 data << uint32(3905);
2890 break;
2891 case 41618: // Bottled Nethergon Energy
2892 case 41620: // Bottled Nethergon Vapor
2893 data << uint32(3842);
2894 break;
2895 case 45373: // Bloodberry Elixir
2896 data << uint32(4075);
2897 break;
2898 default: // default case (don't must be)
2899 data << uint32(0);
2900 break;
2902 break;
2903 case SPELL_FAILED_TOTEMS:
2904 if(m_spellInfo->Totem[0])
2905 data << uint32(m_spellInfo->Totem[0]);
2906 if(m_spellInfo->Totem[1])
2907 data << uint32(m_spellInfo->Totem[1]);
2908 break;
2909 case SPELL_FAILED_TOTEM_CATEGORY:
2910 if(m_spellInfo->TotemCategory[0])
2911 data << uint32(m_spellInfo->TotemCategory[0]);
2912 if(m_spellInfo->TotemCategory[1])
2913 data << uint32(m_spellInfo->TotemCategory[1]);
2914 break;
2915 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2916 data << uint32(m_spellInfo->EquippedItemClass);
2917 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2918 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2919 break;
2920 default:
2921 break;
2923 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2926 void Spell::SendSpellStart()
2928 if(!IsNeedSendToClient())
2929 return;
2931 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2933 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2934 if(IsRangedSpell())
2935 castFlags |= CAST_FLAG_AMMO;
2937 if(m_spellInfo->runeCostID)
2938 castFlags |= CAST_FLAG_UNKNOWN10;
2940 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2941 if(m_CastItem)
2942 data.append(m_CastItem->GetPackGUID());
2943 else
2944 data.append(m_caster->GetPackGUID());
2946 data.append(m_caster->GetPackGUID());
2947 data << uint8(m_cast_count); // pending spell cast?
2948 data << uint32(m_spellInfo->Id); // spellId
2949 data << uint32(castFlags); // cast flags
2950 data << uint32(m_timer); // delay?
2952 m_targets.write(&data);
2954 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2955 data << uint32(0);
2957 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2959 uint8 v1 = 0;//m_runesState;
2960 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2961 data << uint8(v1); // runes state before
2962 data << uint8(v2); // runes state after
2963 for(uint8 i = 0; i < MAX_RUNES; ++i)
2965 uint8 m = (1 << i);
2966 if(m & v1) // usable before...
2967 if(!(m & v2)) // ...but on cooldown now...
2968 data << uint8(0); // some unknown byte (time?)
2972 if ( castFlags & CAST_FLAG_AMMO )
2973 WriteAmmoToPacket(&data);
2975 m_caster->SendMessageToSet(&data, true);
2978 void Spell::SendSpellGo()
2980 // not send invisible spell casting
2981 if(!IsNeedSendToClient())
2982 return;
2984 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2986 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2987 if(IsRangedSpell())
2988 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2990 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2992 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2993 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2994 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2997 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2999 if(m_CastItem)
3000 data.append(m_CastItem->GetPackGUID());
3001 else
3002 data.append(m_caster->GetPackGUID());
3004 data.append(m_caster->GetPackGUID());
3005 data << uint8(m_cast_count); // pending spell cast?
3006 data << uint32(m_spellInfo->Id); // spellId
3007 data << uint32(castFlags); // cast flags
3008 data << uint32(getMSTime()); // timestamp
3010 WriteSpellGoTargets(&data);
3012 m_targets.write(&data);
3014 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
3015 data << uint32(0);
3017 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
3019 uint8 v1 = m_runesState;
3020 uint8 v2 = ((Player*)m_caster)->GetRunesState();
3021 data << uint8(v1); // runes state before
3022 data << uint8(v2); // runes state after
3023 for(uint8 i = 0; i < MAX_RUNES; ++i)
3025 uint8 m = (1 << i);
3026 if(m & v1) // usable before...
3027 if(!(m & v2)) // ...but on cooldown now...
3028 data << uint8(0); // some unknown byte (time?)
3032 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
3034 data << float(0);
3035 data << uint32(0);
3038 if ( castFlags & CAST_FLAG_AMMO )
3039 WriteAmmoToPacket(&data);
3041 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
3043 data << uint32(0);
3044 data << uint32(0);
3047 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
3049 data << uint8(0);
3052 m_caster->SendMessageToSet(&data, true);
3055 void Spell::WriteAmmoToPacket( WorldPacket * data )
3057 uint32 ammoInventoryType = 0;
3058 uint32 ammoDisplayID = 0;
3060 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3062 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
3063 if(pItem)
3065 ammoInventoryType = pItem->GetProto()->InventoryType;
3066 if( ammoInventoryType == INVTYPE_THROWN )
3067 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
3068 else
3070 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
3071 if(ammoID)
3073 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
3074 if(pProto)
3076 ammoDisplayID = pProto->DisplayInfoID;
3077 ammoInventoryType = pProto->InventoryType;
3080 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
3082 ammoDisplayID = 5996; // normal arrow
3083 ammoInventoryType = INVTYPE_AMMO;
3088 else
3090 for (uint8 i = 0; i < 3; ++i)
3092 if(uint32 item_id = m_caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i))
3094 if(ItemEntry const * itemEntry = sItemStore.LookupEntry(item_id))
3096 if(itemEntry->Class==ITEM_CLASS_WEAPON)
3098 switch(itemEntry->SubClass)
3100 case ITEM_SUBCLASS_WEAPON_THROWN:
3101 ammoDisplayID = itemEntry->DisplayId;
3102 ammoInventoryType = itemEntry->InventoryType;
3103 break;
3104 case ITEM_SUBCLASS_WEAPON_BOW:
3105 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
3106 ammoDisplayID = 5996; // is this need fixing?
3107 ammoInventoryType = INVTYPE_AMMO;
3108 break;
3109 case ITEM_SUBCLASS_WEAPON_GUN:
3110 ammoDisplayID = 5998; // is this need fixing?
3111 ammoInventoryType = INVTYPE_AMMO;
3112 break;
3115 if(ammoDisplayID)
3116 break;
3123 *data << uint32(ammoDisplayID);
3124 *data << uint32(ammoInventoryType);
3127 void Spell::WriteSpellGoTargets( WorldPacket * data )
3129 // This function also fill data for channeled spells:
3130 // m_needAliveTargetMask req for stop channelig if one target die
3131 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
3132 uint32 miss = 0;
3133 for(std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
3135 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
3137 // possibly SPELL_MISS_IMMUNE2 for this??
3138 ihit->missCondition = SPELL_MISS_IMMUNE2;
3139 ++miss;
3141 else if ((*ihit).missCondition == SPELL_MISS_NONE)
3142 ++hit;
3143 else
3144 ++miss;
3147 *data << (uint8)hit;
3148 for(std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
3150 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3152 *data << uint64(ihit->targetGUID);
3153 m_needAliveTargetMask |=ihit->effectMask;
3157 for(std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
3158 *data << uint64(ighit->targetGUID); // Always hits
3160 *data << (uint8)miss;
3161 for(std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
3163 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3165 *data << uint64(ihit->targetGUID);
3166 *data << uint8(ihit->missCondition);
3167 if( ihit->missCondition == SPELL_MISS_REFLECT )
3168 *data << uint8(ihit->reflectResult);
3171 // Reset m_needAliveTargetMask for non channeled spell
3172 if(!IsChanneledSpell(m_spellInfo))
3173 m_needAliveTargetMask = 0;
3176 void Spell::SendLogExecute()
3178 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3180 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3182 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3183 data.append(m_caster->GetPackGUID());
3184 else
3185 data.append(target->GetPackGUID());
3187 data << uint32(m_spellInfo->Id);
3188 uint32 count1 = 1;
3189 data << uint32(count1); // count1 (effect count?)
3190 for(uint32 i = 0; i < count1; ++i)
3192 data << uint32(m_spellInfo->Effect[0]); // spell effect
3193 uint32 count2 = 1;
3194 data << uint32(count2); // count2 (target count?)
3195 for(uint32 j = 0; j < count2; ++j)
3197 switch(m_spellInfo->Effect[0])
3199 case SPELL_EFFECT_POWER_DRAIN:
3200 if(Unit *unit = m_targets.getUnitTarget())
3201 data.append(unit->GetPackGUID());
3202 else
3203 data << uint8(0);
3204 data << uint32(0);
3205 data << uint32(0);
3206 data << float(0);
3207 break;
3208 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3209 if(Unit *unit = m_targets.getUnitTarget())
3210 data.append(unit->GetPackGUID());
3211 else
3212 data << uint8(0);
3213 data << uint32(0); // count?
3214 break;
3215 case SPELL_EFFECT_INTERRUPT_CAST:
3216 if(Unit *unit = m_targets.getUnitTarget())
3217 data.append(unit->GetPackGUID());
3218 else
3219 data << uint8(0);
3220 data << uint32(0); // spellid
3221 break;
3222 case SPELL_EFFECT_DURABILITY_DAMAGE:
3223 if(Unit *unit = m_targets.getUnitTarget())
3224 data.append(unit->GetPackGUID());
3225 else
3226 data << uint8(0);
3227 data << uint32(0);
3228 data << uint32(0);
3229 break;
3230 case SPELL_EFFECT_OPEN_LOCK:
3231 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3232 if(Item *item = m_targets.getItemTarget())
3233 data.append(item->GetPackGUID());
3234 else
3235 data << uint8(0);
3236 break;
3237 case SPELL_EFFECT_CREATE_ITEM:
3238 case SPELL_EFFECT_CREATE_ITEM_2:
3239 data << uint32(m_spellInfo->EffectItemType[0]);
3240 break;
3241 case SPELL_EFFECT_SUMMON:
3242 case SPELL_EFFECT_TRANS_DOOR:
3243 case SPELL_EFFECT_SUMMON_PET:
3244 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3245 case SPELL_EFFECT_CREATE_HOUSE:
3246 case SPELL_EFFECT_DUEL:
3247 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3248 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3249 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3250 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3251 if(Unit *unit = m_targets.getUnitTarget())
3252 data.append(unit->GetPackGUID());
3253 else if(m_targets.getItemTargetGUID())
3254 data.appendPackGUID(m_targets.getItemTargetGUID());
3255 else if(GameObject *go = m_targets.getGOTarget())
3256 data.append(go->GetPackGUID());
3257 else
3258 data << uint8(0); // guid
3259 break;
3260 case SPELL_EFFECT_FEED_PET:
3261 data << uint32(m_targets.getItemTargetEntry());
3262 break;
3263 case SPELL_EFFECT_DISMISS_PET:
3264 if(Unit *unit = m_targets.getUnitTarget())
3265 data.append(unit->GetPackGUID());
3266 else
3267 data << uint8(0);
3268 break;
3269 case SPELL_EFFECT_RESURRECT:
3270 case SPELL_EFFECT_RESURRECT_NEW:
3271 if(Unit *unit = m_targets.getUnitTarget())
3272 data.append(unit->GetPackGUID());
3273 else
3274 data << uint8(0);
3275 break;
3276 default:
3277 return;
3282 m_caster->SendMessageToSet(&data, true);
3285 void Spell::SendInterrupted(uint8 result)
3287 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3288 data.append(m_caster->GetPackGUID());
3289 data << uint8(m_cast_count);
3290 data << uint32(m_spellInfo->Id);
3291 data << uint8(result);
3292 m_caster->SendMessageToSet(&data, true);
3294 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3295 data.append(m_caster->GetPackGUID());
3296 data << uint8(m_cast_count);
3297 data << uint32(m_spellInfo->Id);
3298 data << uint8(result);
3299 m_caster->SendMessageToSet(&data, true);
3302 void Spell::SendChannelUpdate(uint32 time)
3304 if(time == 0)
3306 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
3307 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
3310 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3311 return;
3313 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3314 data.append(m_caster->GetPackGUID());
3315 data << uint32(time);
3317 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3320 void Spell::SendChannelStart(uint32 duration)
3322 WorldObject* target = NULL;
3324 // select first not resisted target from target list for _0_ effect
3325 if(!m_UniqueTargetInfo.empty())
3327 for(std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
3329 if( (itr->effectMask & (1 << 0)) && itr->reflectResult == SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3331 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3332 break;
3336 else if(!m_UniqueGOTargetInfo.empty())
3338 for(std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
3340 if(itr->effectMask & (1 << 0) )
3342 target = m_caster->GetMap()->GetGameObject(itr->targetGUID);
3343 break;
3348 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3350 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3351 data.append(m_caster->GetPackGUID());
3352 data << uint32(m_spellInfo->Id);
3353 data << uint32(duration);
3355 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3358 m_timer = duration;
3359 if(target)
3360 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3361 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3364 void Spell::SendResurrectRequest(Player* target)
3366 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3367 // However, the packet structure differs slightly
3369 const char* sentName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3371 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3372 data << uint64(m_caster->GetGUID());
3373 data << uint32(strlen(sentName) + 1);
3375 data << sentName;
3376 data << uint8(0);
3378 data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1);
3379 target->GetSession()->SendPacket(&data);
3382 void Spell::SendPlaySpellVisual(uint32 SpellID)
3384 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3385 return;
3387 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 8 + 4);
3388 data << uint64(m_caster->GetGUID());
3389 data << uint32(SpellID); // spell visual id?
3390 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3393 void Spell::TakeCastItem()
3395 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3396 return;
3398 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3399 if(m_IsTriggeredSpell)
3400 return;
3402 ItemPrototype const *proto = m_CastItem->GetProto();
3404 if(!proto)
3406 // This code is to avoid a crash
3407 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3408 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3409 return;
3412 bool expendable = false;
3413 bool withoutCharges = false;
3415 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
3417 if (proto->Spells[i].SpellId)
3419 // item has limited charges
3420 if (proto->Spells[i].SpellCharges)
3422 if (proto->Spells[i].SpellCharges < 0)
3423 expendable = true;
3425 int32 charges = m_CastItem->GetSpellCharges(i);
3427 // item has charges left
3428 if (charges)
3430 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3431 if (proto->Stackable == 1)
3432 m_CastItem->SetSpellCharges(i, charges);
3433 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3436 // all charges used
3437 withoutCharges = (charges == 0);
3442 if (expendable && withoutCharges)
3444 uint32 count = 1;
3445 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3447 // prevent crash at access to deleted m_targets.getItemTarget
3448 if(m_CastItem==m_targets.getItemTarget())
3449 m_targets.setItemTarget(NULL);
3451 m_CastItem = NULL;
3455 void Spell::TakePower()
3457 if(m_CastItem || m_triggeredByAuraSpell)
3458 return;
3460 // health as power used
3461 if(m_spellInfo->powerType == POWER_HEALTH)
3463 m_caster->ModifyHealth( -(int32)m_powerCost );
3464 return;
3467 if(m_spellInfo->powerType >= MAX_POWERS)
3469 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3470 return;
3473 Powers powerType = Powers(m_spellInfo->powerType);
3475 if(powerType == POWER_RUNE)
3477 TakeRunePower();
3478 return;
3481 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3483 // Set the five second timer
3484 if (powerType == POWER_MANA && m_powerCost > 0)
3485 m_caster->SetLastManaUse(getMSTime());
3488 SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
3490 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3491 return SPELL_CAST_OK;
3493 Player *plr = (Player*)m_caster;
3495 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3496 return SPELL_CAST_OK;
3498 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3500 if(!src)
3501 return SPELL_CAST_OK;
3503 if(src->NoRuneCost())
3504 return SPELL_CAST_OK;
3506 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3508 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3509 runeCost[i] = src->RuneCost[i];
3511 runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
3513 for(uint32 i = 0; i < MAX_RUNES; ++i)
3515 uint8 rune = plr->GetCurrentRune(i);
3516 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3517 runeCost[rune]--;
3520 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3521 if(runeCost[i] > 0)
3522 runeCost[RUNE_DEATH] += runeCost[i];
3524 if(runeCost[RUNE_DEATH] > MAX_RUNES)
3525 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3527 return SPELL_CAST_OK;
3530 void Spell::TakeRunePower()
3532 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3533 return;
3535 Player *plr = (Player*)m_caster;
3537 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3538 return;
3540 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3542 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3543 return;
3545 m_runesState = plr->GetRunesState(); // store previous state
3547 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3549 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3551 runeCost[i] = src->RuneCost[i];
3554 runeCost[RUNE_DEATH] = 0; // calculated later
3556 for(uint32 i = 0; i < MAX_RUNES; ++i)
3558 uint8 rune = plr->GetCurrentRune(i);
3559 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3561 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3562 runeCost[rune]--;
3566 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3568 if(runeCost[RUNE_DEATH] > 0)
3570 for(uint32 i = 0; i < MAX_RUNES; ++i)
3572 uint8 rune = plr->GetCurrentRune(i);
3573 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3575 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3576 runeCost[rune]--;
3577 plr->ConvertRune(i, plr->GetBaseRune(i));
3578 if(runeCost[RUNE_DEATH] == 0)
3579 break;
3584 // you can gain some runic power when use runes
3585 float rp = src->runePowerGain;;
3586 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3587 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3590 void Spell::TakeReagents()
3592 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3593 return;
3595 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3596 return;
3598 Player* p_caster = (Player*)m_caster;
3599 if (p_caster->CanNoReagentCast(m_spellInfo))
3600 return;
3602 for(uint32 x = 0; x < 8; ++x)
3604 if(m_spellInfo->Reagent[x] <= 0)
3605 continue;
3607 uint32 itemid = m_spellInfo->Reagent[x];
3608 uint32 itemcount = m_spellInfo->ReagentCount[x];
3610 // if CastItem is also spell reagent
3611 if (m_CastItem)
3613 ItemPrototype const *proto = m_CastItem->GetProto();
3614 if( proto && proto->ItemId == itemid )
3616 for(int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
3618 // CastItem will be used up and does not count as reagent
3619 int32 charges = m_CastItem->GetSpellCharges(s);
3620 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3622 ++itemcount;
3623 break;
3627 m_CastItem = NULL;
3631 // if getItemTarget is also spell reagent
3632 if (m_targets.getItemTargetEntry() == itemid)
3633 m_targets.setItemTarget(NULL);
3635 p_caster->DestroyItemCount(itemid, itemcount, true);
3639 void Spell::HandleThreatSpells(uint32 spellId)
3641 if(!m_targets.getUnitTarget() || !spellId)
3642 return;
3644 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3645 return;
3647 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3648 if(!threatSpell)
3649 return;
3651 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3653 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3656 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3658 unitTarget = pUnitTarget;
3659 itemTarget = pItemTarget;
3660 gameObjTarget = pGOTarget;
3662 uint8 eff = m_spellInfo->Effect[i];
3664 damage = int32(CalculateDamage((uint8)i, unitTarget) * DamageMultiplier);
3666 sLog.outDebug( "Spell: Effect : %u", eff);
3668 if(eff<TOTAL_SPELL_EFFECTS)
3670 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3671 (*this.*SpellEffects[eff])(i);
3674 else
3676 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3677 if (m_CastItem)
3678 EffectEnchantItemTmp(i);
3679 else
3681 sLog.outError("SPELL: unknown effect %u spell id %u",
3682 eff, m_spellInfo->Id);
3688 void Spell::TriggerSpell()
3690 for(TriggerSpells::const_iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3692 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3693 spell->prepare(&m_targets); // use original spell original targets
3697 SpellCastResult Spell::CheckCast(bool strict)
3699 // check cooldowns to prevent cheating
3700 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3702 if(m_triggeredByAuraSpell)
3703 return SPELL_FAILED_DONT_REPORT;
3704 else
3705 return SPELL_FAILED_NOT_READY;
3708 // only allow triggered spells if at an ended battleground
3709 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3710 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3711 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3712 return SPELL_FAILED_DONT_REPORT;
3714 // only check at first call, Stealth auras are already removed at second call
3715 // for now, ignore triggered spells
3716 if( strict && !m_IsTriggeredSpell)
3718 bool checkForm = true;
3719 // Ignore form req aura
3720 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3721 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3723 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3724 continue;
3725 checkForm = false;
3726 break;
3728 if (checkForm)
3730 // Cannot be used in this stance/form
3731 SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form);
3732 if(shapeError != SPELL_CAST_OK)
3733 return shapeError;
3735 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3736 return SPELL_FAILED_ONLY_STEALTHED;
3740 // caster state requirements
3741 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3742 return SPELL_FAILED_CASTER_AURASTATE;
3743 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3744 return SPELL_FAILED_CASTER_AURASTATE;
3746 // Caster aura req check if need
3747 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3748 return SPELL_FAILED_CASTER_AURASTATE;
3749 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3750 return SPELL_FAILED_CASTER_AURASTATE;
3752 // cancel autorepeat spells if cast start when moving
3753 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3754 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3756 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3757 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3758 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3759 return SPELL_FAILED_MOVING;
3762 if(Unit *target = m_targets.getUnitTarget())
3764 // target state requirements (not allowed state), apply to self also
3765 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3766 return SPELL_FAILED_TARGET_AURASTATE;
3768 // Target aura req check if need
3769 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3770 return SPELL_FAILED_CASTER_AURASTATE;
3771 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3772 return SPELL_FAILED_CASTER_AURASTATE;
3774 if(target != m_caster)
3776 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3777 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3778 return SPELL_FAILED_TARGET_AURASTATE;
3780 // Not allow casting on flying player
3781 if (target->isInFlight())
3782 return SPELL_FAILED_BAD_TARGETS;
3784 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3785 return SPELL_FAILED_LINE_OF_SIGHT;
3787 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3788 // this case can be triggered if rank not found (too low-level target for first rank)
3789 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3790 for(int i=0;i<3;++i)
3791 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3792 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3793 return SPELL_FAILED_LOWLEVEL;
3795 else if (m_caster->GetTypeId() == TYPEID_PLAYER) // Target - is player caster
3797 // Additional check for some spells
3798 // If 0 spell effect empty - client not send target data (need use selection)
3799 // TODO: check it on next client version
3800 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3801 m_spellInfo->EffectImplicitTargetA[1] == TARGET_CHAIN_DAMAGE)
3803 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3804 m_targets.setUnitTarget(target);
3805 else
3806 return SPELL_FAILED_BAD_TARGETS;
3810 // check pet presents
3811 for(int j = 0; j < 3; ++j)
3813 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3815 target = m_caster->GetPet();
3816 if(!target)
3818 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3819 return SPELL_FAILED_DONT_REPORT;
3820 else
3821 return SPELL_FAILED_NO_PET;
3823 break;
3827 //check creature type
3828 //ignore self casts (including area casts when caster selected as target)
3829 if(target != m_caster)
3831 if(!CheckTargetCreatureType(target))
3833 if(target->GetTypeId() == TYPEID_PLAYER)
3834 return SPELL_FAILED_TARGET_IS_PLAYER;
3835 else
3836 return SPELL_FAILED_BAD_TARGETS;
3840 // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3841 // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3842 if(m_caster != target && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3844 // check correctness positive/negative cast target (pet cast real check and cheating check)
3845 if(IsPositiveSpell(m_spellInfo->Id))
3847 if(m_caster->IsHostileTo(target))
3848 return SPELL_FAILED_BAD_TARGETS;
3850 else
3852 if(m_caster->IsFriendlyTo(target))
3853 return SPELL_FAILED_BAD_TARGETS;
3857 if(IsPositiveSpell(m_spellInfo->Id))
3858 if(target->IsImmunedToSpell(m_spellInfo))
3859 return SPELL_FAILED_TARGET_AURASTATE;
3861 //Must be behind the target.
3862 if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3864 //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
3865 //Exclusion for Mutilate:Facing Limitation was removed in 2.0.1 and 3.0.3, but they still use the same, old Ex-Flags
3866 if ((m_spellInfo->SpellFamilyName != SPELLFAMILY_DRUID || (m_spellInfo->SpellFamilyFlags != UI64LIT(0x0000000000020000))) &&
3867 (m_spellInfo->SpellFamilyName != SPELLFAMILY_ROGUE || (m_spellInfo->SpellFamilyFlags != UI64LIT(0x0020000000000000))))
3869 SendInterrupted(2);
3870 return SPELL_FAILED_NOT_BEHIND;
3874 //Target must be facing you.
3875 if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3877 SendInterrupted(2);
3878 return SPELL_FAILED_NOT_INFRONT;
3881 // check if target is in combat
3882 if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3883 return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3886 // Spell casted only on battleground
3887 if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER)
3888 if(!((Player*)m_caster)->InBattleGround())
3889 return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3891 // do not allow spells to be cast in arenas
3892 // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3893 // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3894 if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3895 GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * IN_MILISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3896 if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3897 if(mapEntry->IsBattleArena())
3898 return SPELL_FAILED_NOT_IN_ARENA;
3900 // zone check
3901 uint32 zone, area;
3902 m_caster->GetZoneAndAreaId(zone, area);
3904 SpellCastResult locRes= spellmgr.GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area,
3905 m_caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)m_caster) : NULL);
3906 if(locRes != SPELL_CAST_OK)
3907 return locRes;
3909 // not let players cast spells at mount (and let do it to creatures)
3910 if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3911 !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3913 if(m_caster->isInFlight())
3914 return SPELL_FAILED_NOT_FLYING;
3915 else
3916 return SPELL_FAILED_NOT_MOUNTED;
3919 // always (except passive spells) check items (focus object can be required for any type casts)
3920 if(!IsPassiveSpell(m_spellInfo->Id))
3922 SpellCastResult castResult = CheckItems();
3923 if(castResult != SPELL_CAST_OK)
3924 return castResult;
3927 //ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
3928 if(m_UniqueTargetInfo.empty()) // skip second CheckCast apply (for delayed spells for example)
3930 for(uint8 j = 0; j < 3; ++j)
3932 if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT ||
3933 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[j] != TARGET_SELF ||
3934 m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
3935 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
3937 SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
3938 SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
3939 if(lower==upper)
3940 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);
3942 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
3943 float range = GetSpellMaxRange(srange);
3945 Creature* creatureScriptTarget = NULL;
3946 GameObject* goScriptTarget = NULL;
3948 for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
3950 switch(i_spellST->second.type)
3952 case SPELL_TARGET_TYPE_GAMEOBJECT:
3954 GameObject* p_GameObject = NULL;
3956 if(i_spellST->second.targetEntry)
3958 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3959 Cell cell(p);
3960 cell.data.Part.reserved = ALL_DISTRICT;
3962 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
3963 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
3965 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
3966 CellLock<GridReadGuard> cell_lock(cell, p);
3967 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
3969 if(p_GameObject)
3971 // remember found target and range, next attempt will find more near target with another entry
3972 creatureScriptTarget = NULL;
3973 goScriptTarget = p_GameObject;
3974 range = go_check.GetLastRange();
3977 else if( focusObject ) // Focus Object
3979 float frange = m_caster->GetDistance(focusObject);
3980 if(range >= frange)
3982 creatureScriptTarget = NULL;
3983 goScriptTarget = focusObject;
3984 range = frange;
3987 break;
3989 case SPELL_TARGET_TYPE_CREATURE:
3990 case SPELL_TARGET_TYPE_DEAD:
3991 default:
3993 Creature *p_Creature = NULL;
3995 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
3996 Cell cell(p);
3997 cell.data.Part.reserved = ALL_DISTRICT;
3998 cell.SetNoCreate(); // Really don't know what is that???
4000 MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
4001 MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
4003 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
4005 CellLock<GridReadGuard> cell_lock(cell, p);
4006 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap());
4008 if(p_Creature )
4010 creatureScriptTarget = p_Creature;
4011 goScriptTarget = NULL;
4012 range = u_check.GetLastRange();
4014 break;
4019 if(creatureScriptTarget)
4021 // store coordinates for TARGET_SCRIPT_COORDINATES
4022 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
4023 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
4025 m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
4027 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
4028 AddUnitTarget(creatureScriptTarget, j);
4030 // store explicit target for TARGET_SCRIPT
4031 else
4032 AddUnitTarget(creatureScriptTarget, j);
4034 else if(goScriptTarget)
4036 // store coordinates for TARGET_SCRIPT_COORDINATES
4037 if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES ||
4038 m_spellInfo->EffectImplicitTargetB[j] == TARGET_SCRIPT_COORDINATES )
4040 m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
4042 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_SCRIPT_COORDINATES && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
4043 AddGOTarget(goScriptTarget, j);
4045 // store explicit target for TARGET_SCRIPT
4046 else
4047 AddGOTarget(goScriptTarget, j);
4049 //Missing DB Entry or targets for this spellEffect.
4050 else
4052 // not report target not existence for triggered spells
4053 if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
4054 return SPELL_FAILED_DONT_REPORT;
4055 else
4056 return SPELL_FAILED_BAD_TARGETS;
4062 if(!m_IsTriggeredSpell)
4064 SpellCastResult castResult = CheckRange(strict);
4065 if(castResult != SPELL_CAST_OK)
4066 return castResult;
4070 SpellCastResult castResult = CheckPower();
4071 if(castResult != SPELL_CAST_OK)
4072 return castResult;
4075 if(!m_IsTriggeredSpell) // triggered spell not affected by stun/etc
4077 SpellCastResult castResult = CheckCasterAuras();
4078 if(castResult != SPELL_CAST_OK)
4079 return castResult;
4082 for (int i = 0; i < 3; ++i)
4084 // for effects of spells that have only one target
4085 switch(m_spellInfo->Effect[i])
4087 case SPELL_EFFECT_DUMMY:
4089 if(m_spellInfo->SpellIconID == 1648) // Execute
4091 if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4092 return SPELL_FAILED_BAD_TARGETS;
4094 else if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
4096 if(m_caster->IsInWater())
4097 return SPELL_FAILED_ONLY_ABOVEWATER;
4099 else if(m_spellInfo->SpellIconID == 156) // Holy Shock
4101 // spell different for friends and enemies
4102 // hart version required facing
4103 if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, m_targets.getUnitTarget() ))
4104 return SPELL_FAILED_UNIT_NOT_INFRONT;
4106 break;
4108 case SPELL_EFFECT_SCHOOL_DAMAGE:
4110 // Hammer of Wrath
4111 if(m_spellInfo->SpellVisual[0] == 7250)
4113 if (!m_targets.getUnitTarget())
4114 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4116 if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
4117 return SPELL_FAILED_BAD_TARGETS;
4119 break;
4121 case SPELL_EFFECT_TAMECREATURE:
4123 if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
4124 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4126 if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
4127 return SPELL_FAILED_HIGHLEVEL;
4129 // use SMSG_PET_TAME_FAILURE?
4130 if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
4131 return SPELL_FAILED_BAD_TARGETS;
4133 if(m_caster->GetPetGUID())
4134 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4136 if(m_caster->GetCharmGUID())
4137 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4139 break;
4141 case SPELL_EFFECT_LEARN_SPELL:
4143 if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
4144 break;
4146 Pet* pet = m_caster->GetPet();
4148 if(!pet)
4149 return SPELL_FAILED_NO_PET;
4151 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4153 if(!learn_spellproto)
4154 return SPELL_FAILED_NOT_KNOWN;
4156 if(m_spellInfo->spellLevel > pet->getLevel())
4157 return SPELL_FAILED_LOWLEVEL;
4159 break;
4161 case SPELL_EFFECT_LEARN_PET_SPELL:
4163 Pet* pet = m_caster->GetPet();
4165 if(!pet)
4166 return SPELL_FAILED_NO_PET;
4168 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
4170 if(!learn_spellproto)
4171 return SPELL_FAILED_NOT_KNOWN;
4173 if(m_spellInfo->spellLevel > pet->getLevel())
4174 return SPELL_FAILED_LOWLEVEL;
4176 break;
4178 case SPELL_EFFECT_FEED_PET:
4180 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4181 return SPELL_FAILED_BAD_TARGETS;
4183 Item* foodItem = m_targets.getItemTarget();
4184 if(!foodItem)
4185 return SPELL_FAILED_BAD_TARGETS;
4187 Pet* pet = m_caster->GetPet();
4189 if(!pet)
4190 return SPELL_FAILED_NO_PET;
4192 if(!pet->HaveInDiet(foodItem->GetProto()))
4193 return SPELL_FAILED_WRONG_PET_FOOD;
4195 if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
4196 return SPELL_FAILED_FOOD_LOWLEVEL;
4198 if(m_caster->isInCombat() || pet->isInCombat())
4199 return SPELL_FAILED_AFFECTING_COMBAT;
4201 break;
4203 case SPELL_EFFECT_POWER_BURN:
4204 case SPELL_EFFECT_POWER_DRAIN:
4206 // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
4207 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4208 if(Unit* target = m_targets.getUnitTarget())
4209 if(target != m_caster && target->getPowerType() != m_spellInfo->EffectMiscValue[i])
4210 return SPELL_FAILED_BAD_TARGETS;
4211 break;
4213 case SPELL_EFFECT_CHARGE:
4215 if (m_caster->hasUnitState(UNIT_STAT_ROOT))
4216 return SPELL_FAILED_ROOTED;
4218 break;
4220 case SPELL_EFFECT_SKINNING:
4222 if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
4223 return SPELL_FAILED_BAD_TARGETS;
4225 if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
4226 return SPELL_FAILED_TARGET_UNSKINNABLE;
4228 Creature* creature = (Creature*)m_targets.getUnitTarget();
4229 if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
4231 return SPELL_FAILED_TARGET_NOT_LOOTED;
4234 uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
4236 int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
4237 int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
4238 int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
4239 if (ReqValue > skillValue)
4240 return SPELL_FAILED_LOW_CASTLEVEL;
4242 // chance for fail at orange skinning attempt
4243 if( (m_selfContainer && (*m_selfContainer) == this) &&
4244 skillValue < sWorld.GetConfigMaxSkillValue() &&
4245 (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37) )
4246 return SPELL_FAILED_TRY_AGAIN;
4248 break;
4250 case SPELL_EFFECT_OPEN_LOCK_ITEM:
4251 case SPELL_EFFECT_OPEN_LOCK:
4253 if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
4254 m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
4255 break;
4257 if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
4258 // we need a go target in case of TARGET_GAMEOBJECT
4259 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
4260 // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
4261 || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
4262 (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
4263 return SPELL_FAILED_BAD_TARGETS;
4265 // In BattleGround players can use only flags and banners
4266 if( ((Player*)m_caster)->InBattleGround() &&
4267 !((Player*)m_caster)->CanUseBattleGroundObject() )
4268 return SPELL_FAILED_TRY_AGAIN;
4270 // get the lock entry
4271 uint32 lockId = 0;
4272 if (GameObject* go = m_targets.getGOTarget())
4273 lockId = go->GetLockId();
4274 else if(Item* itm = m_targets.getItemTarget())
4275 lockId = itm->GetProto()->LockID;
4277 SkillType skillId = SKILL_NONE;
4278 int32 reqSkillValue = 0;
4279 int32 skillValue = 0;
4281 // check lock compatibility
4282 SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue);
4283 if(res != SPELL_CAST_OK)
4284 return res;
4286 // chance for fail at orange mining/herb/LockPicking gathering attempt
4287 // second check prevent fail at rechecks
4288 if(skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
4290 bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
4292 // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
4293 if((canFailAtMax || skillValue < sWorld.GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37))
4294 return SPELL_FAILED_TRY_AGAIN;
4296 break;
4298 case SPELL_EFFECT_SUMMON_DEAD_PET:
4300 Creature *pet = m_caster->GetPet();
4301 if(!pet)
4302 return SPELL_FAILED_NO_PET;
4304 if(pet->isAlive())
4305 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4307 break;
4309 // This is generic summon effect
4310 case SPELL_EFFECT_SUMMON:
4312 switch(m_spellInfo->EffectMiscValueB[i])
4314 case SUMMON_TYPE_POSESSED:
4315 case SUMMON_TYPE_POSESSED2:
4316 case SUMMON_TYPE_DEMON:
4317 case SUMMON_TYPE_SUMMON:
4319 if(m_caster->GetPetGUID())
4320 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4322 if(m_caster->GetCharmGUID())
4323 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4324 break;
4327 break;
4329 // Not used for summon?
4330 case SPELL_EFFECT_SUMMON_PHANTASM:
4332 if(m_caster->GetPetGUID())
4333 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4335 if(m_caster->GetCharmGUID())
4336 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4338 break;
4340 case SPELL_EFFECT_SUMMON_PET:
4342 if(m_caster->GetPetGUID()) //let warlock do a replacement summon
4345 Pet* pet = ((Player*)m_caster)->GetPet();
4347 if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK)
4349 if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
4350 pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
4352 else
4353 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4356 if(m_caster->GetCharmGUID())
4357 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4359 break;
4361 case SPELL_EFFECT_SUMMON_PLAYER:
4363 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4364 return SPELL_FAILED_BAD_TARGETS;
4365 if(!((Player*)m_caster)->GetSelection())
4366 return SPELL_FAILED_BAD_TARGETS;
4368 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
4369 if( !target || ((Player*)m_caster) == target || !target->IsInSameRaidWith((Player*)m_caster) )
4370 return SPELL_FAILED_BAD_TARGETS;
4372 // check if our map is dungeon
4373 if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
4375 InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
4376 if(!instance)
4377 return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
4378 if ( instance->levelMin > target->getLevel() )
4379 return SPELL_FAILED_LOWLEVEL;
4380 if ( instance->levelMax && instance->levelMax < target->getLevel() )
4381 return SPELL_FAILED_HIGHLEVEL;
4383 break;
4385 case SPELL_EFFECT_LEAP:
4386 case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
4388 float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
4389 float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
4390 float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
4391 // teleport a bit above terrain level to avoid falling below it
4392 float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
4393 if(fz <= INVALID_HEIGHT) // note: this also will prevent use effect in instances without vmaps height enabled
4394 return SPELL_FAILED_TRY_AGAIN;
4396 float caster_pos_z = m_caster->GetPositionZ();
4397 // Control the caster to not climb or drop when +-fz > 8
4398 if(!(fz <= caster_pos_z + 8 && fz >= caster_pos_z - 8))
4399 return SPELL_FAILED_TRY_AGAIN;
4401 // not allow use this effect at battleground until battleground start
4402 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4403 if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
4404 if(bg->GetStatus() != STATUS_IN_PROGRESS)
4405 return SPELL_FAILED_TRY_AGAIN;
4406 break;
4408 case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
4410 if (m_targets.getUnitTarget() == m_caster)
4411 return SPELL_FAILED_BAD_TARGETS;
4412 break;
4414 default:break;
4418 for (int i = 0; i < 3; ++i)
4420 switch(m_spellInfo->EffectApplyAuraName[i])
4422 case SPELL_AURA_DUMMY:
4424 //custom check
4425 switch(m_spellInfo->Id)
4427 case 61336:
4428 if(m_caster->GetTypeId() != TYPEID_PLAYER || !((Player*)m_caster)->IsInFeralForm())
4429 return SPELL_FAILED_ONLY_SHAPESHIFT;
4430 break;
4431 default:
4432 break;
4434 break;
4436 case SPELL_AURA_MOD_POSSESS:
4437 case SPELL_AURA_MOD_CHARM:
4439 if(m_caster->GetPetGUID())
4440 return SPELL_FAILED_ALREADY_HAVE_SUMMON;
4442 if(m_caster->GetCharmGUID())
4443 return SPELL_FAILED_ALREADY_HAVE_CHARM;
4445 if(m_caster->GetCharmerGUID())
4446 return SPELL_FAILED_CHARMED;
4448 if(!m_targets.getUnitTarget())
4449 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4451 if(m_targets.getUnitTarget()->GetCharmerGUID())
4452 return SPELL_FAILED_CHARMED;
4454 if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4455 return SPELL_FAILED_HIGHLEVEL;
4457 break;
4459 case SPELL_AURA_MOUNTED:
4461 if (m_caster->IsInWater())
4462 return SPELL_FAILED_ONLY_ABOVEWATER;
4464 if (m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4465 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4467 // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4468 if (m_caster->GetTypeId() == TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
4469 return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4471 ShapeshiftForm form = m_caster->m_form;
4472 if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
4473 form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
4474 form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
4475 form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
4476 return SPELL_FAILED_NOT_SHAPESHIFT;
4478 break;
4480 case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4482 if(!m_targets.getUnitTarget())
4483 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4485 // can be casted at non-friendly unit or own pet/charm
4486 if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4487 return SPELL_FAILED_TARGET_FRIENDLY;
4489 break;
4491 case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4492 case SPELL_AURA_FLY:
4494 // not allow cast fly spells at old maps by players (all spells is self target)
4495 if(m_caster->GetTypeId() == TYPEID_PLAYER)
4497 if( !((Player*)m_caster)->IsAllowUseFlyMountsHere() )
4498 return SPELL_FAILED_NOT_HERE;
4501 break;
4503 case SPELL_AURA_PERIODIC_MANA_LEECH:
4505 if (!m_targets.getUnitTarget())
4506 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4508 if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
4509 break;
4511 if(m_targets.getUnitTarget()->getPowerType() != POWER_MANA)
4512 return SPELL_FAILED_BAD_TARGETS;
4514 break;
4516 default:
4517 break;
4521 // all ok
4522 return SPELL_CAST_OK;
4525 SpellCastResult Spell::CheckPetCast(Unit* target)
4527 if(!m_caster->isAlive())
4528 return SPELL_FAILED_CASTER_DEAD;
4530 if(m_caster->IsNonMeleeSpellCasted(false)) //prevent spellcast interruption by another spellcast
4531 return SPELL_FAILED_SPELL_IN_PROGRESS;
4532 if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4533 return SPELL_FAILED_AFFECTING_COMBAT;
4535 if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4537 //dead owner (pets still alive when owners ressed?)
4538 if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4539 return SPELL_FAILED_CASTER_DEAD;
4541 if(!target && m_targets.getUnitTarget())
4542 target = m_targets.getUnitTarget();
4544 bool need = false;
4545 for(uint32 i = 0; i < 3; ++i)
4547 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)
4549 need = true;
4550 if(!target)
4551 return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4552 break;
4555 if(need)
4556 m_targets.setUnitTarget(target);
4558 Unit* _target = m_targets.getUnitTarget();
4560 if(_target) //for target dead/target not valid
4562 if(!_target->isAlive())
4563 return SPELL_FAILED_BAD_TARGETS;
4565 if(IsPositiveSpell(m_spellInfo->Id))
4567 if(m_caster->IsHostileTo(_target))
4568 return SPELL_FAILED_BAD_TARGETS;
4570 else
4572 bool duelvsplayertar = false;
4573 for(int j = 0; j < 3; ++j)
4575 //TARGET_DUELVSPLAYER is positive AND negative
4576 duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4578 if(m_caster->IsFriendlyTo(target) && !duelvsplayertar)
4580 return SPELL_FAILED_BAD_TARGETS;
4584 //cooldown
4585 if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4586 return SPELL_FAILED_NOT_READY;
4589 return CheckCast(true);
4592 SpellCastResult Spell::CheckCasterAuras() const
4594 // Flag drop spells totally immuned to caster auras
4595 // FIXME: find more nice check for all totally immuned spells
4596 // AttributesEx3 & 0x10000000?
4597 if(m_spellInfo->Id == 23336 || m_spellInfo->Id == 23334 || m_spellInfo->Id == 34991)
4598 return SPELL_CAST_OK;
4600 uint8 school_immune = 0;
4601 uint32 mechanic_immune = 0;
4602 uint32 dispel_immune = 0;
4604 // Check if the spell grants school or mechanic immunity.
4605 // We use bitmasks so the loop is done only once and not on every aura check below.
4606 if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4608 for(int i = 0; i < 3; ++i)
4610 if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4611 school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4612 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4613 mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4614 else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4615 dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4617 // immune movement impairment and loss of control
4618 if(m_spellInfo->Id == 42292)
4619 mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4622 // Check whether the cast should be prevented by any state you might have.
4623 SpellCastResult prevented_reason = SPELL_CAST_OK;
4624 // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4625 uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
4626 if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4627 prevented_reason = SPELL_FAILED_STUNNED;
4628 else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4629 prevented_reason = SPELL_FAILED_CONFUSED;
4630 else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4631 prevented_reason = SPELL_FAILED_FLEEING;
4632 else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
4633 prevented_reason = SPELL_FAILED_SILENCED;
4634 else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
4635 prevented_reason = SPELL_FAILED_PACIFIED;
4637 // Attr must make flag drop spell totally immune from all effects
4638 if(prevented_reason != SPELL_CAST_OK)
4640 if(school_immune || mechanic_immune || dispel_immune)
4642 //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4643 Unit::AuraMap const& auras = m_caster->GetAuras();
4644 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
4646 if(itr->second)
4648 if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4649 continue;
4650 if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4651 continue;
4652 if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4653 continue;
4655 // Make a second check for spell failed so the right SPELL_FAILED message is returned.
4656 // That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4657 switch(itr->second->GetModifier()->m_auraname)
4659 case SPELL_AURA_MOD_STUN:
4660 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4661 return SPELL_FAILED_STUNNED;
4662 break;
4663 case SPELL_AURA_MOD_CONFUSE:
4664 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4665 return SPELL_FAILED_CONFUSED;
4666 break;
4667 case SPELL_AURA_MOD_FEAR:
4668 if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4669 return SPELL_FAILED_FLEEING;
4670 break;
4671 case SPELL_AURA_MOD_SILENCE:
4672 case SPELL_AURA_MOD_PACIFY:
4673 case SPELL_AURA_MOD_PACIFY_SILENCE:
4674 if( m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
4675 return SPELL_FAILED_PACIFIED;
4676 else if ( m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
4677 return SPELL_FAILED_SILENCED;
4678 break;
4683 // You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4684 else
4685 return prevented_reason;
4687 return SPELL_CAST_OK;
4690 bool Spell::CanAutoCast(Unit* target)
4692 uint64 targetguid = target->GetGUID();
4694 for(uint32 j = 0; j < 3; ++j)
4696 if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4698 if( m_spellInfo->StackAmount <= 1)
4700 if( target->HasAura(m_spellInfo->Id, j) )
4701 return false;
4703 else
4705 if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4706 return false;
4709 else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4711 if( target->HasAura(m_spellInfo->Id, j) )
4712 return false;
4716 SpellCastResult result = CheckPetCast(target);
4718 if(result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4720 FillTargetMap();
4721 //check if among target units, our WANTED target is as well (->only self cast spells return false)
4722 for(std::list<TargetInfo>::const_iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4723 if( ihit->targetGUID == targetguid )
4724 return true;
4726 return false; //target invalid
4729 SpellCastResult Spell::CheckRange(bool strict)
4731 float range_mod;
4733 // self cast doesn't need range checking -- also for Starshards fix
4734 if (m_spellInfo->rangeIndex == 1)
4735 return SPELL_CAST_OK;
4737 if (strict) //add radius of caster
4738 range_mod = 1.25;
4739 else //add radius of caster and ~5 yds "give"
4740 range_mod = 6.25;
4742 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4743 Unit *target = m_targets.getUnitTarget();
4744 bool friendly = target ? target->IsFriendlyTo(m_caster) : false;
4745 float max_range = GetSpellMaxRange(srange, friendly) + range_mod;
4746 float min_range = GetSpellMinRange(srange, friendly);
4748 if(Player* modOwner = m_caster->GetSpellModOwner())
4749 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4751 if(target && target != m_caster)
4753 // distance from target in checks
4754 float dist = m_caster->GetCombatDistance(target);
4756 if(dist > max_range)
4757 return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
4758 if(dist < min_range)
4759 return SPELL_FAILED_TOO_CLOSE;
4760 if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4761 (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4762 return SPELL_FAILED_UNIT_NOT_INFRONT;
4765 if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4767 if(!m_caster->IsWithinDist3d(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, max_range))
4768 return SPELL_FAILED_OUT_OF_RANGE;
4769 if(m_caster->IsWithinDist3d(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, min_range))
4770 return SPELL_FAILED_TOO_CLOSE;
4773 return SPELL_CAST_OK;
4776 int32 Spell::CalculatePowerCost()
4778 // item cast not used power
4779 if(m_CastItem)
4780 return 0;
4782 // Spell drain all exist power on cast (Only paladin lay of Hands)
4783 if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4785 // If power type - health drain all
4786 if (m_spellInfo->powerType == POWER_HEALTH)
4787 return m_caster->GetHealth();
4788 // Else drain all power
4789 if (m_spellInfo->powerType < MAX_POWERS)
4790 return m_caster->GetPower(Powers(m_spellInfo->powerType));
4791 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4792 return 0;
4795 // Base powerCost
4796 int32 powerCost = m_spellInfo->manaCost;
4797 // PCT cost from total amount
4798 if (m_spellInfo->ManaCostPercentage)
4800 switch (m_spellInfo->powerType)
4802 // health as power used
4803 case POWER_HEALTH:
4804 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4805 break;
4806 case POWER_MANA:
4807 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4808 break;
4809 case POWER_RAGE:
4810 case POWER_FOCUS:
4811 case POWER_ENERGY:
4812 case POWER_HAPPINESS:
4813 powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4814 break;
4815 case POWER_RUNE:
4816 case POWER_RUNIC_POWER:
4817 sLog.outDebug("Spell::CalculateManaCost: Not implemented yet!");
4818 break;
4819 default:
4820 sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4821 return 0;
4824 SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4825 // Flat mod from caster auras by spell school
4826 powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4827 // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4828 if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4829 powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4830 // Apply cost mod by spell
4831 if(Player* modOwner = m_caster->GetSpellModOwner())
4832 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4834 if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4835 powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4837 // PCT mod from user auras by school
4838 powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4839 if (powerCost < 0)
4840 powerCost = 0;
4841 return powerCost;
4844 SpellCastResult Spell::CheckPower()
4846 // item cast not used power
4847 if(m_CastItem)
4848 return SPELL_CAST_OK;
4850 // health as power used - need check health amount
4851 if(m_spellInfo->powerType == POWER_HEALTH)
4853 if(m_caster->GetHealth() <= m_powerCost)
4854 return SPELL_FAILED_CASTER_AURASTATE;
4855 return SPELL_CAST_OK;
4857 // Check valid power type
4858 if( m_spellInfo->powerType >= MAX_POWERS )
4860 sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4861 return SPELL_FAILED_UNKNOWN;
4864 SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID);
4865 if(failReason != SPELL_CAST_OK)
4866 return failReason;
4868 // Check power amount
4869 Powers powerType = Powers(m_spellInfo->powerType);
4870 if(m_caster->GetPower(powerType) < m_powerCost)
4871 return SPELL_FAILED_NO_POWER;
4872 else
4873 return SPELL_CAST_OK;
4876 SpellCastResult Spell::CheckItems()
4878 if (m_caster->GetTypeId() != TYPEID_PLAYER)
4879 return SPELL_CAST_OK;
4881 Player* p_caster = (Player*)m_caster;
4883 // cast item checks
4884 if(m_CastItem)
4886 uint32 itemid = m_CastItem->GetEntry();
4887 if( !p_caster->HasItemCount(itemid, 1) )
4888 return SPELL_FAILED_ITEM_NOT_READY;
4890 ItemPrototype const *proto = m_CastItem->GetProto();
4891 if(!proto)
4892 return SPELL_FAILED_ITEM_NOT_READY;
4894 for (int i = 0; i < 5; ++i)
4895 if (proto->Spells[i].SpellCharges)
4896 if(m_CastItem->GetSpellCharges(i) == 0)
4897 return SPELL_FAILED_NO_CHARGES_REMAIN;
4899 // consumable cast item checks
4900 if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4902 // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
4903 SpellCastResult failReason = SPELL_CAST_OK;
4904 for (int i = 0; i < 3; ++i)
4906 // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4907 if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4908 continue;
4910 if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4912 if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4914 failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4915 continue;
4917 else
4919 failReason = SPELL_CAST_OK;
4920 break;
4924 // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4925 if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4927 if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4929 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4930 continue;
4933 Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4934 if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4936 failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
4937 continue;
4939 else
4941 failReason = SPELL_CAST_OK;
4942 break;
4946 if (failReason != SPELL_CAST_OK)
4947 return failReason;
4951 // check target item
4952 if(m_targets.getItemTargetGUID())
4954 if(m_caster->GetTypeId() != TYPEID_PLAYER)
4955 return SPELL_FAILED_BAD_TARGETS;
4957 if(!m_targets.getItemTarget())
4958 return SPELL_FAILED_ITEM_GONE;
4960 if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4961 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4963 // if not item target then required item must be equipped
4964 else
4966 if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4967 return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4970 // check spell focus object
4971 if(m_spellInfo->RequiresSpellFocus)
4973 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4974 Cell cell(p);
4975 cell.data.Part.reserved = ALL_DISTRICT;
4977 GameObject* ok = NULL;
4978 MaNGOS::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4979 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck> checker(m_caster, ok, go_check);
4981 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4982 CellLock<GridReadGuard> cell_lock(cell, p);
4983 cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
4985 if(!ok)
4986 return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4988 focusObject = ok; // game object found in range
4991 // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
4992 if (!m_IsTriggeredSpell && !p_caster->CanNoReagentCast(m_spellInfo))
4994 for(uint32 i = 0; i < 8; ++i)
4996 if(m_spellInfo->Reagent[i] <= 0)
4997 continue;
4999 uint32 itemid = m_spellInfo->Reagent[i];
5000 uint32 itemcount = m_spellInfo->ReagentCount[i];
5002 // if CastItem is also spell reagent
5003 if( m_CastItem && m_CastItem->GetEntry() == itemid )
5005 ItemPrototype const *proto = m_CastItem->GetProto();
5006 if(!proto)
5007 return SPELL_FAILED_ITEM_NOT_READY;
5008 for(int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
5010 // CastItem will be used up and does not count as reagent
5011 int32 charges = m_CastItem->GetSpellCharges(s);
5012 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
5014 ++itemcount;
5015 break;
5019 if( !p_caster->HasItemCount(itemid, itemcount) )
5020 return SPELL_FAILED_ITEM_NOT_READY; //0x54
5024 // check totem-item requirements (items presence in inventory)
5025 uint32 totems = 2;
5026 for(int i = 0; i < 2 ; ++i)
5028 if(m_spellInfo->Totem[i] != 0)
5030 if( p_caster->HasItemCount(m_spellInfo->Totem[i], 1) )
5032 totems -= 1;
5033 continue;
5035 }else
5036 totems -= 1;
5038 if(totems != 0)
5039 return SPELL_FAILED_TOTEMS; //0x7C
5041 // Check items for TotemCategory (items presence in inventory)
5042 uint32 TotemCategory = 2;
5043 for(int i= 0; i < 2; ++i)
5045 if(m_spellInfo->TotemCategory[i] != 0)
5047 if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
5049 TotemCategory -= 1;
5050 continue;
5053 else
5054 TotemCategory -= 1;
5056 if(TotemCategory != 0)
5057 return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
5059 // special checks for spell effects
5060 for(int i = 0; i < 3; ++i)
5062 switch (m_spellInfo->Effect[i])
5064 case SPELL_EFFECT_CREATE_ITEM:
5066 if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
5068 ItemPosCountVec dest;
5069 uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
5070 if (msg != EQUIP_ERR_OK )
5072 p_caster->SendEquipError( msg, NULL, NULL );
5073 return SPELL_FAILED_DONT_REPORT;
5076 break;
5078 case SPELL_EFFECT_ENCHANT_ITEM:
5079 case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
5081 Item* targetItem = m_targets.getItemTarget();
5082 if(!targetItem)
5083 return SPELL_FAILED_ITEM_NOT_FOUND;
5085 if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
5086 return SPELL_FAILED_LOWLEVEL;
5087 // Not allow enchant in trade slot for some enchant type
5088 if( targetItem->GetOwner() != m_caster )
5090 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5091 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5092 if(!pEnchant)
5093 return SPELL_FAILED_ERROR;
5094 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5095 return SPELL_FAILED_NOT_TRADEABLE;
5097 break;
5099 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
5101 Item *item = m_targets.getItemTarget();
5102 if(!item)
5103 return SPELL_FAILED_ITEM_NOT_FOUND;
5104 // Not allow enchant in trade slot for some enchant type
5105 if( item->GetOwner() != m_caster )
5107 uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
5108 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
5109 if(!pEnchant)
5110 return SPELL_FAILED_ERROR;
5111 if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
5112 return SPELL_FAILED_NOT_TRADEABLE;
5114 break;
5116 case SPELL_EFFECT_ENCHANT_HELD_ITEM:
5117 // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
5118 break;
5119 case SPELL_EFFECT_DISENCHANT:
5121 if(!m_targets.getItemTarget())
5122 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5124 // prevent disenchanting in trade slot
5125 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5126 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5128 ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
5129 if(!itemProto)
5130 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5132 uint32 item_quality = itemProto->Quality;
5133 // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
5134 uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
5135 if (item_disenchantskilllevel == uint32(-1))
5136 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5137 if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
5138 return SPELL_FAILED_LOW_CASTLEVEL;
5139 if(item_quality > 4 || item_quality < 2)
5140 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5141 if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
5142 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5143 if (!itemProto->DisenchantID)
5144 return SPELL_FAILED_CANT_BE_DISENCHANTED;
5145 break;
5147 case SPELL_EFFECT_PROSPECTING:
5149 if(!m_targets.getItemTarget())
5150 return SPELL_FAILED_CANT_BE_PROSPECTED;
5151 //ensure item is a prospectable ore
5152 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5153 return SPELL_FAILED_CANT_BE_PROSPECTED;
5154 //prevent prospecting in trade slot
5155 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5156 return SPELL_FAILED_CANT_BE_PROSPECTED;
5157 //Check for enough skill in jewelcrafting
5158 uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5159 if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
5160 return SPELL_FAILED_LOW_CASTLEVEL;
5161 //make sure the player has the required ores in inventory
5162 if(m_targets.getItemTarget()->GetCount() < 5)
5163 return SPELL_FAILED_NEED_MORE_ITEMS;
5165 if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
5166 return SPELL_FAILED_CANT_BE_PROSPECTED;
5168 break;
5170 case SPELL_EFFECT_MILLING:
5172 if(!m_targets.getItemTarget())
5173 return SPELL_FAILED_CANT_BE_MILLED;
5174 //ensure item is a millable herb
5175 if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
5176 return SPELL_FAILED_CANT_BE_MILLED;
5177 //prevent milling in trade slot
5178 if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
5179 return SPELL_FAILED_CANT_BE_MILLED;
5180 //Check for enough skill in inscription
5181 uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
5182 if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
5183 return SPELL_FAILED_LOW_CASTLEVEL;
5184 //make sure the player has the required herbs in inventory
5185 if(m_targets.getItemTarget()->GetCount() < 5)
5186 return SPELL_FAILED_NEED_MORE_ITEMS;
5188 if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
5189 return SPELL_FAILED_CANT_BE_MILLED;
5191 break;
5193 case SPELL_EFFECT_WEAPON_DAMAGE:
5194 case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
5196 if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
5197 if( m_attackType != RANGED_ATTACK )
5198 break;
5199 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
5200 if(!pItem || pItem->IsBroken())
5201 return SPELL_FAILED_EQUIPPED_ITEM;
5203 switch(pItem->GetProto()->SubClass)
5205 case ITEM_SUBCLASS_WEAPON_THROWN:
5207 uint32 ammo = pItem->GetEntry();
5208 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5209 return SPELL_FAILED_NO_AMMO;
5210 }; break;
5211 case ITEM_SUBCLASS_WEAPON_GUN:
5212 case ITEM_SUBCLASS_WEAPON_BOW:
5213 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5215 uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
5216 if(!ammo)
5218 // Requires No Ammo
5219 if(m_caster->GetDummyAura(46699))
5220 break; // skip other checks
5222 return SPELL_FAILED_NO_AMMO;
5225 ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
5226 if(!ammoProto)
5227 return SPELL_FAILED_NO_AMMO;
5229 if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
5230 return SPELL_FAILED_NO_AMMO;
5232 // check ammo ws. weapon compatibility
5233 switch(pItem->GetProto()->SubClass)
5235 case ITEM_SUBCLASS_WEAPON_BOW:
5236 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
5237 if(ammoProto->SubClass != ITEM_SUBCLASS_ARROW)
5238 return SPELL_FAILED_NO_AMMO;
5239 break;
5240 case ITEM_SUBCLASS_WEAPON_GUN:
5241 if(ammoProto->SubClass != ITEM_SUBCLASS_BULLET)
5242 return SPELL_FAILED_NO_AMMO;
5243 break;
5244 default:
5245 return SPELL_FAILED_NO_AMMO;
5248 if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
5249 return SPELL_FAILED_NO_AMMO;
5250 }; break;
5251 case ITEM_SUBCLASS_WEAPON_WAND:
5252 break;
5253 default:
5254 break;
5256 break;
5258 default:break;
5262 return SPELL_CAST_OK;
5265 void Spell::Delayed()
5267 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
5268 return;
5270 if (m_spellState == SPELL_STATE_DELAYED)
5271 return; // spell is active and can't be time-backed
5273 if(isDelayableNoMore()) // Spells may only be delayed twice
5274 return;
5276 // spells not loosing casting time ( slam, dynamites, bombs.. )
5277 if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
5278 return;
5280 //check pushback reduce
5281 int32 delaytime = 500; // spellcasting delay is normally 500ms
5282 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5283 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5284 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5285 if(delayReduce >= 100)
5286 return;
5288 delaytime = delaytime * (100 - delayReduce) / 100;
5290 if(int32(m_timer) + delaytime > m_casttime)
5292 delaytime = m_casttime - m_timer;
5293 m_timer = m_casttime;
5295 else
5296 m_timer += delaytime;
5298 sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
5300 WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
5301 data.append(m_caster->GetPackGUID());
5302 data << uint32(delaytime);
5304 m_caster->SendMessageToSet(&data, true);
5307 void Spell::DelayedChannel()
5309 if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
5310 return;
5312 if(isDelayableNoMore()) // Spells may only be delayed twice
5313 return;
5315 //check pushback reduce
5316 int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
5317 int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
5318 ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
5319 delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
5320 if(delayReduce >= 100)
5321 return;
5323 delaytime = delaytime * (100 - delayReduce) / 100;
5325 if(int32(m_timer) < delaytime)
5327 delaytime = m_timer;
5328 m_timer = 0;
5330 else
5331 m_timer -= delaytime;
5333 sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
5335 for(std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
5337 if ((*ihit).missCondition == SPELL_MISS_NONE)
5339 Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
5340 if (unit)
5342 for (int j = 0; j < 3; ++j)
5343 if( ihit->effectMask & (1 << j) )
5344 unit->DelayAura(m_spellInfo->Id, j, delaytime);
5350 for(int j = 0; j < 3; ++j)
5352 // partially interrupt persistent area auras
5353 DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
5354 if(dynObj)
5355 dynObj->Delay(delaytime);
5358 SendChannelUpdate(m_timer);
5361 void Spell::UpdatePointers()
5363 if(m_originalCasterGUID==m_caster->GetGUID())
5364 m_originalCaster = m_caster;
5365 else
5367 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
5368 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
5371 m_targets.Update(m_caster);
5374 bool Spell::IsAffectedByAura(Aura *aura)
5376 return spellmgr.IsAffectedByMod(m_spellInfo, aura->getAuraSpellMod());
5379 bool Spell::CheckTargetCreatureType(Unit* target) const
5381 uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
5383 // Curse of Doom : not find another way to fix spell target check :/
5384 if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == UI64LIT(0x0200000000))
5386 // not allow cast at player
5387 if(target->GetTypeId()==TYPEID_PLAYER)
5388 return false;
5390 spellCreatureTargetMask = 0x7FF;
5393 // Dismiss Pet and Taming Lesson skipped
5394 if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
5395 spellCreatureTargetMask = 0;
5397 if (spellCreatureTargetMask)
5399 uint32 TargetCreatureType = target->GetCreatureTypeMask();
5401 return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
5403 return true;
5406 CurrentSpellTypes Spell::GetCurrentContainer()
5408 if (IsNextMeleeSwingSpell())
5409 return(CURRENT_MELEE_SPELL);
5410 else if (IsAutoRepeat())
5411 return(CURRENT_AUTOREPEAT_SPELL);
5412 else if (IsChanneledSpell(m_spellInfo))
5413 return(CURRENT_CHANNELED_SPELL);
5414 else
5415 return(CURRENT_GENERIC_SPELL);
5418 bool Spell::CheckTarget( Unit* target, uint32 eff )
5420 // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
5421 if(m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SELF )
5423 if (!CheckTargetCreatureType(target))
5424 return false;
5427 // Check Aura spell req (need for AoE spells)
5428 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
5429 return false;
5430 if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
5431 return false;
5433 // Check targets for not_selectable unit flag and remove
5434 // A player can cast spells on his pet (or other controlled unit) though in any state
5435 if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
5437 // any unattackable target skipped
5438 if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
5439 return false;
5441 // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
5442 // in case TARGET_SCRIPT target selected by server always and can't be cheated
5443 if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
5444 m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
5445 m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
5446 return false;
5449 //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
5450 if( target != m_caster && target->GetTypeId() == TYPEID_PLAYER)
5452 if(((Player*)target)->GetVisibility() == VISIBILITY_OFF)
5453 return false;
5455 if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
5456 return false;
5459 //Check targets for LOS visibility (except spells without range limitations )
5460 switch(m_spellInfo->Effect[eff])
5462 case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
5463 break;
5464 case SPELL_EFFECT_DUMMY:
5465 if(m_spellInfo->Id != 20577) // Cannibalize
5466 break;
5467 //fall through
5468 case SPELL_EFFECT_RESURRECT_NEW:
5469 // player far away, maybe his corpse near?
5470 if(target != m_caster && !target->IsWithinLOSInMap(m_caster))
5472 if(!m_targets.getCorpseTargetGUID())
5473 return false;
5475 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
5476 if(!corpse)
5477 return false;
5479 if(target->GetGUID() != corpse->GetOwnerGUID())
5480 return false;
5482 if(!corpse->IsWithinLOSInMap(m_caster))
5483 return false;
5486 // all ok by some way or another, skip normal check
5487 break;
5488 default: // normal case
5489 // Get GO cast coordinates if original caster -> GO
5490 WorldObject *caster = NULL;
5491 if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
5492 caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
5493 if (!caster)
5494 caster = m_caster;
5495 if(target != m_caster && !target->IsWithinLOSInMap(caster))
5496 return false;
5497 break;
5500 return true;
5503 bool Spell::IsNeedSendToClient() const
5505 return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
5506 m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5509 bool Spell::HaveTargetsForEffect( uint8 effect ) const
5511 for(std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
5512 if(itr->effectMask & (1 << effect))
5513 return true;
5515 for(std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
5516 if(itr->effectMask & (1 << effect))
5517 return true;
5519 for(std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
5520 if(itr->effectMask & (1 << effect))
5521 return true;
5523 return false;
5526 SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5528 m_Spell = spell;
5531 SpellEvent::~SpellEvent()
5533 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5534 m_Spell->cancel();
5536 if (m_Spell->IsDeletable())
5538 delete m_Spell;
5540 else
5542 sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5543 (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id);
5547 bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5549 // update spell if it is not finished
5550 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5551 m_Spell->update(p_time);
5553 // check spell state to process
5554 switch (m_Spell->getState())
5556 case SPELL_STATE_FINISHED:
5558 // spell was finished, check deletable state
5559 if (m_Spell->IsDeletable())
5561 // check, if we do have unfinished triggered spells
5562 return true; // spell is deletable, finish event
5564 // event will be re-added automatically at the end of routine)
5565 } break;
5567 case SPELL_STATE_CASTING:
5569 // this spell is in channeled state, process it on the next update
5570 // event will be re-added automatically at the end of routine)
5571 } break;
5573 case SPELL_STATE_DELAYED:
5575 // first, check, if we have just started
5576 if (m_Spell->GetDelayStart() != 0)
5578 // no, we aren't, do the typical update
5579 // check, if we have channeled spell on our hands
5580 if (IsChanneledSpell(m_Spell->m_spellInfo))
5582 // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5583 // check, if we have casting anything else except this channeled spell and autorepeat
5584 if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5586 // another non-melee non-delayed spell is casted now, abort
5587 m_Spell->cancel();
5589 else
5591 // do the action (pass spell to channeling state)
5592 m_Spell->handle_immediate();
5594 // event will be re-added automatically at the end of routine)
5596 else
5598 // run the spell handler and think about what we can do next
5599 uint64 t_offset = e_time - m_Spell->GetDelayStart();
5600 uint64 n_offset = m_Spell->handle_delayed(t_offset);
5601 if (n_offset)
5603 // re-add us to the queue
5604 m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5605 return false; // event not complete
5607 // event complete
5608 // finish update event will be re-added automatically at the end of routine)
5611 else
5613 // delaying had just started, record the moment
5614 m_Spell->SetDelayStart(e_time);
5615 // re-plan the event for the delay moment
5616 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5617 return false; // event not complete
5619 } break;
5621 default:
5623 // all other states
5624 // event will be re-added automatically at the end of routine)
5625 } break;
5628 // spell processing not complete, plan event on the next update interval
5629 m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5630 return false; // event not complete
5633 void SpellEvent::Abort(uint64 /*e_time*/)
5635 // oops, the spell we try to do is aborted
5636 if (m_Spell->getState() != SPELL_STATE_FINISHED)
5637 m_Spell->cancel();
5640 bool SpellEvent::IsDeletable() const
5642 return m_Spell->IsDeletable();
5645 SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
5647 if(!lockId) // possible case for GO and maybe for items.
5648 return SPELL_CAST_OK;
5650 // Get LockInfo
5651 LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
5653 if (!lockInfo)
5654 return SPELL_FAILED_BAD_TARGETS;
5656 bool reqKey = false; // some locks not have reqs
5658 for(int j = 0; j < 8; ++j)
5660 switch(lockInfo->Type[j])
5662 // check key item (many fit cases can be)
5663 case LOCK_KEY_ITEM:
5664 if(lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[j])
5665 return SPELL_CAST_OK;
5666 reqKey = true;
5667 break;
5668 // check key skill (only single first fit case can be)
5669 case LOCK_KEY_SKILL:
5671 reqKey = true;
5673 // wrong locktype, skip
5674 if(uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j])
5675 continue;
5677 skillId = SkillByLockType(LockType(lockInfo->Index[j]));
5679 if ( skillId != SKILL_NONE )
5681 // skill bonus provided by casting spell (mostly item spells)
5682 // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
5683 uint32 spellSkillBonus = uint32(m_currentBasePoints[effIndex]+1);
5684 reqSkillValue = lockInfo->Skill[j];
5686 // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
5687 skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
5688 0 : ((Player*)m_caster)->GetSkillValue(skillId);
5690 skillValue += spellSkillBonus;
5692 if (skillValue < reqSkillValue)
5693 return SPELL_FAILED_LOW_CASTLEVEL;
5696 return SPELL_CAST_OK;
5701 if(reqKey)
5702 return SPELL_FAILED_BAD_TARGETS;
5704 return SPELL_CAST_OK;
5707 void Spell::FillAreaTargets( UnitList& TagUnitMap, float x, float y, float radius, SpellNotifyPushType pushType, SpellTargets spellTargets )
5709 CellPair p(MaNGOS::ComputeCellPair(x, y));
5710 Cell cell(p);
5711 cell.data.Part.reserved = ALL_DISTRICT;
5712 cell.SetNoCreate();
5713 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, pushType, spellTargets);
5714 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
5715 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
5716 CellLock<GridReadGuard> cell_lock(cell, p);
5717 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
5718 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());