[7146] Trailing whitespace code cleanup
[getmangos.git] / src / game / Spell.cpp
blob6076308b09efceb3a325e108596ddd724bf5d58c
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "GridNotifiers.h"
24 #include "GridNotifiersImpl.h"
25 #include "Opcodes.h"
26 #include "Log.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "ObjectMgr.h"
30 #include "SpellMgr.h"
31 #include "Player.h"
32 #include "Pet.h"
33 #include "Unit.h"
34 #include "Spell.h"
35 #include "DynamicObject.h"
36 #include "SpellAuras.h"
37 #include "Group.h"
38 #include "UpdateData.h"
39 #include "MapManager.h"
40 #include "ObjectAccessor.h"
41 #include "CellImpl.h"
42 #include "Policies/SingletonImp.h"
43 #include "SharedDefines.h"
44 #include "LootMgr.h"
45 #include "VMapFactory.h"
46 #include "BattleGround.h"
47 #include "Util.h"
49 #define SPELL_CHANNEL_UPDATE_INTERVAL 1000
51 extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
53 bool IsQuestTameSpell(uint32 spellId)
55 SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
56 if (!spellproto) return false;
58 return spellproto->Effect[0] == SPELL_EFFECT_THREAT
59 && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
62 SpellCastTargets::SpellCastTargets()
64 m_unitTarget = NULL;
65 m_itemTarget = NULL;
66 m_GOTarget = NULL;
68 m_unitTargetGUID = 0;
69 m_GOTargetGUID = 0;
70 m_CorpseTargetGUID = 0;
71 m_itemTargetGUID = 0;
72 m_itemTargetEntry = 0;
74 m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
75 m_strTarget = "";
76 m_targetMask = 0;
79 SpellCastTargets::~SpellCastTargets()
83 void SpellCastTargets::setUnitTarget(Unit *target)
85 if (!target)
86 return;
88 m_destX = target->GetPositionX();
89 m_destY = target->GetPositionY();
90 m_destZ = target->GetPositionZ();
91 m_unitTarget = target;
92 m_unitTargetGUID = target->GetGUID();
93 m_targetMask |= TARGET_FLAG_UNIT;
96 void SpellCastTargets::setDestination(float x, float y, float z)
98 m_destX = x;
99 m_destY = y;
100 m_destZ = z;
101 m_targetMask |= TARGET_FLAG_DEST_LOCATION;
104 void SpellCastTargets::setGOTarget(GameObject *target)
106 m_GOTarget = target;
107 m_GOTargetGUID = target->GetGUID();
108 // m_targetMask |= TARGET_FLAG_OBJECT;
111 void SpellCastTargets::setItemTarget(Item* item)
113 if(!item)
114 return;
116 m_itemTarget = item;
117 m_itemTargetGUID = item->GetGUID();
118 m_itemTargetEntry = item->GetEntry();
119 m_targetMask |= TARGET_FLAG_ITEM;
122 void SpellCastTargets::setCorpseTarget(Corpse* corpse)
124 m_CorpseTargetGUID = corpse->GetGUID();
127 void SpellCastTargets::Update(Unit* caster)
129 m_GOTarget = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
130 m_unitTarget = m_unitTargetGUID ?
131 ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
132 NULL;
134 m_itemTarget = NULL;
135 if(caster->GetTypeId()==TYPEID_PLAYER)
137 if(m_targetMask & TARGET_FLAG_ITEM)
138 m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
139 else
141 Player* pTrader = ((Player*)caster)->GetTrader();
142 if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
143 m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
145 if(m_itemTarget)
146 m_itemTargetEntry = m_itemTarget->GetEntry();
150 bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
152 if(data->rpos()+4 > data->size())
153 return false;
155 *data >> m_targetMask;
157 if(m_targetMask == TARGET_FLAG_SELF)
159 m_destX = caster->GetPositionX();
160 m_destY = caster->GetPositionY();
161 m_destZ = caster->GetPositionZ();
162 m_unitTarget = caster;
163 m_unitTargetGUID = caster->GetGUID();
164 return true;
167 // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
168 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
169 if(!data->readPackGUID(m_unitTargetGUID))
170 return false;
172 if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
173 if(!data->readPackGUID(m_GOTargetGUID))
174 return false;
176 if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
177 if(!data->readPackGUID(m_itemTargetGUID))
178 return false;
180 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
182 if(data->rpos()+4+4+4 > data->size())
183 return false;
185 *data >> m_srcX >> m_srcY >> m_srcZ;
186 if(!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
187 return false;
190 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
192 if(data->rpos()+4+4+4 > data->size())
193 return false;
195 *data >> m_destX >> m_destY >> m_destZ;
196 if(!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ))
197 return false;
200 if( m_targetMask & TARGET_FLAG_STRING )
202 if(data->rpos()+1 > data->size())
203 return false;
205 *data >> m_strTarget;
208 if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
209 if(!data->readPackGUID(m_CorpseTargetGUID))
210 return false;
212 // find real units/GOs
213 Update(caster);
214 return true;
217 void SpellCastTargets::write ( WorldPacket * data )
219 *data << uint32(m_targetMask);
221 if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
223 if(m_targetMask & TARGET_FLAG_UNIT)
225 if(m_unitTarget)
226 data->append(m_unitTarget->GetPackGUID());
227 else
228 *data << uint8(0);
230 else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
232 if(m_GOTarget)
233 data->append(m_GOTarget->GetPackGUID());
234 else
235 *data << uint8(0);
237 else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
238 data->appendPackGUID(m_CorpseTargetGUID);
239 else
240 *data << uint8(0);
243 if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
245 if(m_itemTarget)
246 data->append(m_itemTarget->GetPackGUID());
247 else
248 *data << uint8(0);
251 if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
252 *data << m_srcX << m_srcY << m_srcZ;
254 if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
255 *data << m_destX << m_destY << m_destZ;
257 if( m_targetMask & TARGET_FLAG_STRING )
258 *data << m_strTarget;
261 Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
263 ASSERT( Caster != NULL && info != NULL );
264 ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
266 m_spellInfo = info;
267 m_caster = Caster;
268 m_selfContainer = NULL;
269 m_triggeringContainer = triggeringContainer;
270 m_referencedFromCurrentSpell = false;
271 m_executedCurrently = false;
272 m_delayStart = 0;
273 m_delayAtDamageCount = 0;
275 m_applyMultiplierMask = 0;
277 // Get data for type of attack
278 switch (m_spellInfo->DmgClass)
280 case SPELL_DAMAGE_CLASS_MELEE:
281 if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
282 m_attackType = OFF_ATTACK;
283 else
284 m_attackType = BASE_ATTACK;
285 break;
286 case SPELL_DAMAGE_CLASS_RANGED:
287 m_attackType = RANGED_ATTACK;
288 break;
289 default:
290 // Wands
291 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
292 m_attackType = RANGED_ATTACK;
293 else
294 m_attackType = BASE_ATTACK;
295 break;
298 m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
300 if(m_attackType == RANGED_ATTACK)
302 // wand case
303 if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
305 if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
306 m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
309 // Set health leech amount to zero
310 m_healthLeech = 0;
312 if(originalCasterGUID)
313 m_originalCasterGUID = originalCasterGUID;
314 else
315 m_originalCasterGUID = m_caster->GetGUID();
317 if(m_originalCasterGUID==m_caster->GetGUID())
318 m_originalCaster = m_caster;
319 else
321 m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
322 if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
325 for(int i=0; i <3; ++i)
326 m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
328 m_spellState = SPELL_STATE_NULL;
330 m_castPositionX = m_castPositionY = m_castPositionZ = 0;
331 m_TriggerSpells.clear();
332 m_IsTriggeredSpell = triggered;
333 //m_AreaAura = false;
334 m_CastItem = NULL;
336 unitTarget = NULL;
337 itemTarget = NULL;
338 gameObjTarget = NULL;
339 focusObject = NULL;
340 m_cast_count = 0;
341 m_glyphIndex = 0;
342 m_triggeredByAuraSpell = NULL;
344 //Auto Shot & Shoot (wand)
345 m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
347 m_runesState = 0;
348 m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
349 m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
350 m_timer = 0; // will set to castime in prepare
352 m_needAliveTargetMask = 0;
354 // determine reflection
355 m_canReflect = false;
357 if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
359 for(int j=0;j<3;j++)
361 if (m_spellInfo->Effect[j]==0)
362 continue;
364 if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
365 m_canReflect = true;
366 else
367 m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
369 if(m_canReflect)
370 continue;
371 else
372 break;
376 CleanupTargetList();
379 Spell::~Spell()
383 void Spell::FillTargetMap()
385 // TODO: ADD the correct target FILLS!!!!!!
387 for(uint32 i=0;i<3;i++)
389 // not call for empty effect.
390 // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
391 if(m_spellInfo->Effect[i]==0)
392 continue;
394 // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT filled in Spell::canCast call
395 if( m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT_COORDINATES ||
396 m_spellInfo->EffectImplicitTargetA[i] == TARGET_SCRIPT ||
397 m_spellInfo->EffectImplicitTargetB[i] == TARGET_SCRIPT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_SELF )
398 continue;
400 // TODO: find a way so this is not needed?
401 // for area auras always add caster as target (needed for totems for example)
402 if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
403 AddUnitTarget(m_caster, i);
405 std::list<Unit*> tmpUnitMap;
407 // TargetA/TargetB dependent from each other, we not switch to full support this dependences
408 // but need it support in some know cases
409 switch(m_spellInfo->EffectImplicitTargetA[i])
411 case TARGET_ALL_AROUND_CASTER:
412 if( m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_PARTY ||
413 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER ||
414 m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_RAID_AROUND_CASTER )
416 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
418 // Note: this hack with search required until GO casting not implemented
419 // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support
420 // currently each enemy selected explicitly and self cast damage
421 else if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA && m_spellInfo->Effect[i]==SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
423 if(m_targets.getUnitTarget())
424 tmpUnitMap.push_back(m_targets.getUnitTarget());
426 else
428 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
429 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
431 break;
432 case TARGET_TABLE_X_Y_Z_COORDINATES:
433 // Only if target A, for target B (used in teleports) dest select in effect
434 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
435 break;
436 default:
437 switch(m_spellInfo->EffectImplicitTargetB[i])
439 case TARGET_SCRIPT_COORDINATES: // B case filled in canCast but we need fill unit list base at A case
440 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
441 break;
442 default:
443 SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
444 SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
445 break;
447 break;
450 if( (m_spellInfo->EffectImplicitTargetA[i]==0 || m_spellInfo->EffectImplicitTargetA[i]==TARGET_EFFECT_SELECT) &&
451 (m_spellInfo->EffectImplicitTargetB[i]==0 || m_spellInfo->EffectImplicitTargetB[i]==TARGET_EFFECT_SELECT) )
453 // add here custom effects that need default target.
454 // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
455 switch(m_spellInfo->Effect[i])
457 case SPELL_EFFECT_DUMMY:
459 switch(m_spellInfo->Id)
461 case 20577: // Cannibalize
463 // non-standard target selection
464 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
465 float max_range = GetSpellMaxRange(srange);
467 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
468 Cell cell(p);
469 cell.data.Part.reserved = ALL_DISTRICT;
470 cell.SetNoCreate();
472 WorldObject* result = NULL;
474 MaNGOS::CannibalizeObjectCheck u_check(m_caster, max_range);
475 MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck > searcher(result, u_check);
477 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
478 CellLock<GridReadGuard> cell_lock(cell, p);
479 cell_lock->Visit(cell_lock, grid_searcher, *m_caster->GetMap());
481 if(!result)
483 TypeContainerVisitor<MaNGOS::WorldObjectSearcher<MaNGOS::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
484 cell_lock->Visit(cell_lock, world_searcher, *m_caster->GetMap());
487 if(result)
489 switch(result->GetTypeId())
491 case TYPEID_UNIT:
492 case TYPEID_PLAYER:
493 tmpUnitMap.push_back((Unit*)result);
494 break;
495 case TYPEID_CORPSE:
496 m_targets.setCorpseTarget((Corpse*)result);
497 if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
498 tmpUnitMap.push_back(owner);
499 break;
502 else
504 // clear cooldown at fail
505 if(m_caster->GetTypeId()==TYPEID_PLAYER)
507 ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
509 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
510 data << uint32(m_spellInfo->Id);
511 data << uint64(m_caster->GetGUID());
512 ((Player*)m_caster)->GetSession()->SendPacket(&data);
515 SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
516 finish(false);
518 break;
520 default:
521 if(m_targets.getUnitTarget())
522 tmpUnitMap.push_back(m_targets.getUnitTarget());
523 break;
525 break;
527 case SPELL_EFFECT_RESURRECT:
528 case SPELL_EFFECT_PARRY:
529 case SPELL_EFFECT_BLOCK:
530 case SPELL_EFFECT_CREATE_ITEM:
531 case SPELL_EFFECT_TRIGGER_SPELL:
532 case SPELL_EFFECT_TRIGGER_MISSILE:
533 case SPELL_EFFECT_LEARN_SPELL:
534 case SPELL_EFFECT_SKILL_STEP:
535 case SPELL_EFFECT_PROFICIENCY:
536 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
537 case SPELL_EFFECT_SELF_RESURRECT:
538 case SPELL_EFFECT_REPUTATION:
539 if(m_targets.getUnitTarget())
540 tmpUnitMap.push_back(m_targets.getUnitTarget());
541 break;
542 case SPELL_EFFECT_SUMMON_PLAYER:
543 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
545 Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
546 if(target)
547 tmpUnitMap.push_back(target);
549 break;
550 case SPELL_EFFECT_RESURRECT_NEW:
551 if(m_targets.getUnitTarget())
552 tmpUnitMap.push_back(m_targets.getUnitTarget());
553 if(m_targets.getCorpseTargetGUID())
555 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
556 if(corpse)
558 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
559 if(owner)
560 tmpUnitMap.push_back(owner);
563 break;
564 case SPELL_EFFECT_SUMMON:
565 if(m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED || m_spellInfo->EffectMiscValueB[i] == SUMMON_TYPE_POSESSED2)
567 if(m_targets.getUnitTarget())
568 tmpUnitMap.push_back(m_targets.getUnitTarget());
570 else
571 tmpUnitMap.push_back(m_caster);
572 break;
573 case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
574 case SPELL_EFFECT_TRANS_DOOR:
575 case SPELL_EFFECT_ADD_FARSIGHT:
576 case SPELL_EFFECT_APPLY_GLYPH:
577 case SPELL_EFFECT_STUCK:
578 case SPELL_EFFECT_FEED_PET:
579 case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
580 case SPELL_EFFECT_SKILL:
581 tmpUnitMap.push_back(m_caster);
582 break;
583 case SPELL_EFFECT_LEARN_PET_SPELL:
584 if(Pet* pet = m_caster->GetPet())
585 tmpUnitMap.push_back(pet);
586 break;
587 case SPELL_EFFECT_ENCHANT_ITEM:
588 case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
589 case SPELL_EFFECT_DISENCHANT:
590 case SPELL_EFFECT_PROSPECTING:
591 case SPELL_EFFECT_MILLING:
592 if(m_targets.getItemTarget())
593 AddItemTarget(m_targets.getItemTarget(), i);
594 break;
595 case SPELL_EFFECT_APPLY_AURA:
596 switch(m_spellInfo->EffectApplyAuraName[i])
598 case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_SELF(1) (and present for other ranks for same spell for example)
599 case SPELL_AURA_ADD_PCT_MODIFIER:
600 tmpUnitMap.push_back(m_caster);
601 break;
602 default: // apply to target in other case
603 if(m_targets.getUnitTarget())
604 tmpUnitMap.push_back(m_targets.getUnitTarget());
605 break;
607 break;
608 case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
609 // AreaAura
610 if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
611 SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
612 break;
613 case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
614 if(m_targets.getUnitTarget())
616 tmpUnitMap.push_back(m_targets.getUnitTarget());
618 else if (m_targets.getCorpseTargetGUID())
620 Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
621 if(corpse)
623 Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
624 if(owner)
625 tmpUnitMap.push_back(owner);
628 break;
629 default:
630 break;
633 if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
634 m_needAliveTargetMask |= (1<<i);
636 if(m_caster->GetTypeId() == TYPEID_PLAYER)
638 Player *me = (Player*)m_caster;
639 for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr)
641 Unit *owner = (*itr)->GetOwner();
642 Unit *u = owner ? owner : (*itr);
643 if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
645 me->UpdatePvP(true);
646 me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
647 break;
652 for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
654 if (!CheckTarget (*itr, i))
656 itr = tmpUnitMap.erase(itr);
657 continue;
659 else
660 ++itr;
663 for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
664 AddUnitTarget((*iunit), i);
668 void Spell::prepareDataForTriggerSystem()
670 //==========================================================================================
671 // Now fill data for trigger system, need know:
672 // √Ďan spell trigger another or not ( m_canTrigger )
673 // Create base triggers flags for Attacker and Victim ( m_procAttacker and m_procVictim)
674 //==========================================================================================
675 // Fill flag can spell trigger or not
676 // TODO: possible exist spell attribute for this
677 m_canTrigger = false;
679 if (m_CastItem)
680 m_canTrigger = false; // Do not trigger from item cast spell
681 else if (!m_IsTriggeredSpell)
682 m_canTrigger = true; // Normal cast - can trigger
683 else if (!m_triggeredByAuraSpell)
684 m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger
686 if (!m_canTrigger) // Exceptions (some periodic triggers)
688 switch (m_spellInfo->SpellFamilyName)
690 case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it
691 if (m_spellInfo->SpellFamilyFlags & 0x0000000000200080LL) m_canTrigger = true;
692 break;
693 case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it
694 if (m_spellInfo->SpellFamilyFlags & 0x0000800000000060LL) m_canTrigger = true;
695 break;
696 case SPELLFAMILY_PRIEST: // For Penance heal/damage triggers need do it
697 if (m_spellInfo->SpellFamilyFlags & 0x0001800000000000LL) m_canTrigger = true;
698 break;
699 case SPELLFAMILY_ROGUE: // For poisons need do it
700 if (m_spellInfo->SpellFamilyFlags & 0x000000101001E000LL) m_canTrigger = true;
701 break;
702 case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect
703 if (m_spellInfo->SpellFamilyFlags & 0x0100200000000014LL) m_canTrigger = true;
704 break;
705 case SPELLFAMILY_PALADIN: // For Holy Shock triggers need do it
706 if (m_spellInfo->SpellFamilyFlags & 0x0001000000200000LL) m_canTrigger = true;
707 break;
711 // Get data for type of attack and fill base info for trigger
712 switch (m_spellInfo->DmgClass)
714 case SPELL_DAMAGE_CLASS_MELEE:
715 m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
716 m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
717 break;
718 case SPELL_DAMAGE_CLASS_RANGED:
719 // Auto attack
720 if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
722 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
723 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
725 else // Ranged spell attack
727 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
728 m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
730 break;
731 default:
732 if (IsPositiveSpell(m_spellInfo->Id)) // Check for positive spell
734 m_procAttacker = PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL;
735 m_procVictim = PROC_FLAG_TAKEN_POSITIVE_SPELL;
737 else if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
739 m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
740 m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
742 else // Negative spell
744 m_procAttacker = PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
745 m_procVictim = PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
747 break;
749 // Hunter traps spells (for Entrapment trigger)
750 // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap ....
751 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellInfo->SpellFamilyFlags & 0x0000200000000014LL)
752 m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
755 void Spell::CleanupTargetList()
757 m_UniqueTargetInfo.clear();
758 m_UniqueGOTargetInfo.clear();
759 m_UniqueItemInfo.clear();
760 m_delayMoment = 0;
763 void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
765 if( m_spellInfo->Effect[effIndex]==0 )
766 return;
768 // Check for effect immune skip if immuned
769 bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
771 uint64 targetGUID = pVictim->GetGUID();
773 // Lookup target in already in list
774 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
776 if (targetGUID == ihit->targetGUID) // Found in list
778 if (!immuned)
779 ihit->effectMask |= 1<<effIndex; // Add only effect mask if not immuned
780 return;
784 // This is new target calculate data for him
786 // Get spell hit result on target
787 TargetInfo target;
788 target.targetGUID = targetGUID; // Store target GUID
789 target.effectMask = immuned ? 0 : 1<<effIndex; // Store index of effect if not immuned
790 target.processed = false; // Effects not apply on target
792 // Calculate hit result
793 target.missCondition = m_caster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
795 // Spell have speed - need calculate incoming time
796 if (m_spellInfo->speed > 0.0f)
798 // calculate spell incoming interval
799 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
800 if (dist < 5.0f) dist = 5.0f;
801 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
803 // Calculate minimum incoming time
804 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
805 m_delayMoment = target.timeDelay;
807 else
808 target.timeDelay = 0LL;
810 // If target reflect spell back to caster
811 if (target.missCondition==SPELL_MISS_REFLECT)
813 // Calculate reflected spell result on caster
814 target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
816 if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
817 target.reflectResult = SPELL_MISS_PARRY;
819 // Increase time interval for reflected spells by 1.5
820 target.timeDelay+=target.timeDelay>>1;
822 else
823 target.reflectResult = SPELL_MISS_NONE;
825 // Add target to list
826 m_UniqueTargetInfo.push_back(target);
829 void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
831 Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
832 if (unit)
833 AddUnitTarget(unit, effIndex);
836 void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
838 if( m_spellInfo->Effect[effIndex]==0 )
839 return;
841 uint64 targetGUID = pVictim->GetGUID();
843 // Lookup target in already in list
844 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
846 if (targetGUID == ihit->targetGUID) // Found in list
848 ihit->effectMask |= 1<<effIndex; // Add only effect mask
849 return;
853 // This is new target calculate data for him
855 GOTargetInfo target;
856 target.targetGUID = targetGUID;
857 target.effectMask = 1<<effIndex;
858 target.processed = false; // Effects not apply on target
860 // Spell have speed - need calculate incoming time
861 if (m_spellInfo->speed > 0.0f)
863 // calculate spell incoming interval
864 float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
865 if (dist < 5.0f) dist = 5.0f;
866 target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
867 if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
868 m_delayMoment = target.timeDelay;
870 else
871 target.timeDelay = 0LL;
873 // Add target to list
874 m_UniqueGOTargetInfo.push_back(target);
877 void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
879 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
880 if (go)
881 AddGOTarget(go, effIndex);
884 void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
886 if( m_spellInfo->Effect[effIndex]==0 )
887 return;
889 // Lookup target in already in list
890 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
892 if (pitem == ihit->item) // Found in list
894 ihit->effectMask |= 1<<effIndex; // Add only effect mask
895 return;
899 // This is new target add data
901 ItemTargetInfo target;
902 target.item = pitem;
903 target.effectMask = 1<<effIndex;
904 m_UniqueItemInfo.push_back(target);
907 void Spell::DoAllEffectOnTarget(TargetInfo *target)
909 if (target->processed) // Check target
910 return;
911 target->processed = true; // Target checked in apply effects procedure
913 // Get mask of effects for target
914 uint32 mask = target->effectMask;
916 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
917 if (!unit)
918 return;
920 // Get original caster (if exist) and calculate damage/healing from him data
921 Unit *caster = m_originalCasterGUID ? m_originalCaster : m_caster;
923 // Skip if m_originalCaster not avaiable
924 if (!caster)
925 return;
927 SpellMissInfo missInfo = target->missCondition;
928 // Need init unitTarget by default unit (can changed in code on reflect)
929 // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
930 unitTarget = unit;
932 // Reset damage/healing counter
933 m_damage = 0;
934 m_healing = 0;
936 // Fill base trigger info
937 uint32 procAttacker = m_procAttacker;
938 uint32 procVictim = m_procVictim;
939 uint32 procEx = PROC_EX_NONE;
941 if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
942 DoSpellHitOnUnit(unit, mask);
943 else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
945 if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
946 DoSpellHitOnUnit(m_caster, mask);
949 // All calculated do it!
950 // Do healing and triggers
951 if (m_healing)
953 bool crit = caster->isSpellCrit(NULL, m_spellInfo, m_spellSchoolMask);
954 uint32 addhealth = m_healing;
955 if (crit)
957 procEx |= PROC_EX_CRITICAL_HIT;
958 addhealth = caster->SpellCriticalBonus(m_spellInfo, addhealth, NULL);
960 else
961 procEx |= PROC_EX_NORMAL_HIT;
963 caster->SendHealSpellLog(unitTarget, m_spellInfo->Id, addhealth, crit);
965 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
966 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
967 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo);
969 int32 gain = unitTarget->ModifyHealth( int32(addhealth) );
971 unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
972 if(caster->GetTypeId()==TYPEID_PLAYER)
973 if(BattleGround *bg = ((Player*)caster)->GetBattleGround())
974 bg->UpdatePlayerScore(((Player*)caster), SCORE_HEALING_DONE, gain);
976 // Do damage and triggers
977 else if (m_damage)
979 // Fill base damage struct (unitTarget - is real spell target)
980 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
982 // Add bonuses and fill damageInfo struct
983 caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo);
985 // Send log damage message to client
986 caster->SendSpellNonMeleeDamageLog(&damageInfo);
988 procEx = createProcExtendMask(&damageInfo, missInfo);
989 procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
991 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
992 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
993 caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo);
995 caster->DealSpellDamage(&damageInfo, true);
997 // Judgement of Blood
998 if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags & 0x0000000800000000LL && m_spellInfo->SpellIconID==153)
1000 int32 damagePoint = damageInfo.damage * 33 / 100;
1001 m_caster->CastCustomSpell(m_caster, 32220, &damagePoint, NULL, NULL, true);
1003 // Bloodthirst
1004 else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && m_spellInfo->SpellFamilyFlags & 0x40000000000LL)
1006 uint32 BTAura = 0;
1007 switch(m_spellInfo->Id)
1009 case 23881: BTAura = 23885; break;
1010 case 23892: BTAura = 23886; break;
1011 case 23893: BTAura = 23887; break;
1012 case 23894: BTAura = 23888; break;
1013 case 25251: BTAura = 25252; break;
1014 case 30335: BTAura = 30339; break;
1015 default:
1016 sLog.outError("Spell::EffectSchoolDMG: Spell %u not handled in BTAura",m_spellInfo->Id);
1017 break;
1019 if (BTAura)
1020 m_caster->CastSpell(m_caster,BTAura,true);
1023 // Passive spell hits/misses or active spells only misses (only triggers)
1024 else
1026 // Fill base damage struct (unitTarget - is real spell target)
1027 SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
1028 procEx = createProcExtendMask(&damageInfo, missInfo);
1029 // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
1030 if (m_canTrigger && missInfo != SPELL_MISS_REFLECT)
1031 caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo);
1034 // Call scripted function for AI if this spell is casted upon a creature (except pets)
1035 if(IS_CREATURE_GUID(target->targetGUID))
1037 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1038 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1039 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1040 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
1042 if(((Creature*)unit)->AI())
1043 ((Creature*)unit)->AI()->SpellHit(m_caster ,m_spellInfo);
1047 void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
1049 if(!unit || !effectMask)
1050 return;
1052 // Recheck immune (only for delayed spells)
1053 if( m_spellInfo->speed && (
1054 unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo)) ||
1055 unit->IsImmunedToSpell(m_spellInfo)))
1057 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
1058 return;
1061 if (unit->GetTypeId() == TYPEID_PLAYER)
1063 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
1064 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
1067 if(m_caster->GetTypeId() == TYPEID_PLAYER)
1069 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
1072 if( m_caster != unit )
1074 // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
1075 if (m_spellInfo->speed > 0.0f &&
1076 unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
1077 unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
1079 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1080 return;
1083 if( !m_caster->IsFriendlyTo(unit) )
1085 // for delayed spells ignore not visible explicit target
1086 if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1088 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1089 return;
1092 unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1094 if( !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1096 if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
1097 unit->SetStandState(PLAYER_STATE_NONE);
1099 if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
1100 ((Creature*)unit)->AI()->AttackStart(m_caster);
1102 unit->SetInCombatWith(m_caster);
1103 m_caster->SetInCombatWith(unit);
1105 if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
1107 m_caster->SetContestedPvP(attackedPlayer);
1109 unit->AddThreat(m_caster, 0.0f);
1112 else
1114 // for delayed spells ignore negative spells (after duel end) for friendly targets
1115 if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1117 m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1118 return;
1121 // assisting case, healing and resurrection
1122 if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1123 m_caster->SetContestedPvP();
1124 if( unit->isInCombat() && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_INITIAL_AGGRO) )
1126 m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1127 unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1132 // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1133 m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1134 m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1135 // Increase Diminishing on unit, current informations for actually casts will use values above
1136 if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1137 unit->IncrDiminishing(m_diminishGroup);
1139 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1141 if (effectMask & (1<<effectNumber))
1143 HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1144 if ( m_applyMultiplierMask & (1 << effectNumber) )
1146 // Get multiplier
1147 float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1148 // Apply multiplier mods
1149 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1150 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1151 m_damageMultipliers[effectNumber] *= multiplier;
1157 void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1159 if (target->processed) // Check target
1160 return;
1161 target->processed = true; // Target checked in apply effects procedure
1163 uint32 effectMask = target->effectMask;
1164 if(!effectMask)
1165 return;
1167 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1168 if(!go)
1169 return;
1171 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1172 if (effectMask & (1<<effectNumber))
1173 HandleEffects(NULL,NULL,go,effectNumber);
1175 // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1176 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1177 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1178 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1181 void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1183 uint32 effectMask = target->effectMask;
1184 if(!target->item || !effectMask)
1185 return;
1187 for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1188 if (effectMask & (1<<effectNumber))
1189 HandleEffects(NULL, target->item, NULL, effectNumber);
1192 bool Spell::IsAliveUnitPresentInTargetList()
1194 // Not need check return true
1195 if (m_needAliveTargetMask == 0)
1196 return true;
1198 uint8 needAliveTargetMask = m_needAliveTargetMask;
1200 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1202 if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1204 Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1206 if (unit && unit->isAlive())
1207 needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
1211 // is all effects from m_needAliveTargetMask have alive targets
1212 return needAliveTargetMask==0;
1215 // Helper for Chain Healing
1216 // Spell target first
1217 // Raidmates then descending by injury suffered (MaxHealth - Health)
1218 // Other players/mobs then descending by injury suffered (MaxHealth - Health)
1219 struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1221 const Unit* MainTarget;
1222 ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1223 // functor for operator ">"
1224 bool operator()(Unit const* _Left, Unit const* _Right) const
1226 return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1228 int32 ChainHealingHash(Unit const* Target) const
1230 if (Target == MainTarget)
1231 return 0;
1232 else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1233 ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1235 if (Target->GetHealth() == Target->GetMaxHealth())
1236 return 40000;
1237 else
1238 return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1240 else
1241 return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1245 class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1247 public:
1248 const Unit* MainTarget;
1249 ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1251 bool operator()(const Unit* Target)
1253 return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1257 // Helper for targets nearest to the spell target
1258 // The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1259 struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1261 const Unit* MainTarget;
1262 TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1263 // functor for operator ">"
1264 bool operator()(const Unit* _Left, const Unit* _Right) const
1266 return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1270 void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1272 float radius;
1273 if (m_spellInfo->EffectRadiusIndex[i])
1274 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1275 else
1276 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1278 if(m_originalCaster)
1279 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1280 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1282 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1283 if(m_originalCaster)
1284 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1285 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1287 // Get spell max affected targets
1288 uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1289 Unit::AuraList const& mod = m_caster->GetAurasByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
1290 for(Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
1292 if (!(*m)->isAffectedOnSpell(m_spellInfo))
1293 continue;
1294 unMaxTargets+=(*m)->GetModifier()->m_amount;
1296 switch(cur)
1298 case TARGET_TOTEM_EARTH:
1299 case TARGET_TOTEM_WATER:
1300 case TARGET_TOTEM_AIR:
1301 case TARGET_TOTEM_FIRE:
1302 case TARGET_SELF:
1303 case TARGET_SELF2:
1304 case TARGET_DYNAMIC_OBJECT:
1305 case TARGET_AREAEFFECT_CUSTOM:
1306 case TARGET_AREAEFFECT_CUSTOM_2:
1307 case TARGET_SUMMON:
1309 TagUnitMap.push_back(m_caster);
1310 break;
1312 case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1314 m_targets.m_targetMask = 0;
1315 unMaxTargets = EffectChainTarget;
1316 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1318 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1319 Cell cell(p);
1320 cell.data.Part.reserved = ALL_DISTRICT;
1321 cell.SetNoCreate();
1323 std::list<Unit *> tempUnitMap;
1326 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(m_caster, m_caster, max_range);
1327 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1329 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1330 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1332 CellLock<GridReadGuard> cell_lock(cell, p);
1333 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1334 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1337 if(tempUnitMap.empty())
1338 break;
1340 tempUnitMap.sort(TargetDistanceOrder(m_caster));
1342 //Now to get us a random target that's in the initial range of the spell
1343 uint32 t = 0;
1344 std::list<Unit *>::iterator itr = tempUnitMap.begin();
1345 while(itr!= tempUnitMap.end() && (*itr)->GetDistance(m_caster) < radius)
1346 ++t, ++itr;
1348 if(!t)
1349 break;
1351 itr = tempUnitMap.begin();
1352 std::advance(itr, rand()%t);
1353 Unit *pUnitTarget = *itr;
1354 TagUnitMap.push_back(pUnitTarget);
1356 tempUnitMap.erase(itr);
1358 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1360 t = unMaxTargets - 1;
1361 Unit *prev = pUnitTarget;
1362 std::list<Unit*>::iterator next = tempUnitMap.begin();
1364 while(t && next != tempUnitMap.end() )
1366 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1367 break;
1369 if(!prev->IsWithinLOSInMap(*next))
1371 ++next;
1372 continue;
1375 prev = *next;
1376 TagUnitMap.push_back(prev);
1377 tempUnitMap.erase(next);
1378 tempUnitMap.sort(TargetDistanceOrder(prev));
1379 next = tempUnitMap.begin();
1381 --t;
1383 }break;
1384 case TARGET_PET:
1386 Pet* tmpUnit = m_caster->GetPet();
1387 if (!tmpUnit) break;
1388 TagUnitMap.push_back(tmpUnit);
1389 break;
1391 case TARGET_CHAIN_DAMAGE:
1393 if (EffectChainTarget <= 1)
1395 Unit* pUnitTarget = SelectMagnetTarget();
1396 if(pUnitTarget)
1397 TagUnitMap.push_back(pUnitTarget);
1399 else
1401 Unit* pUnitTarget = m_targets.getUnitTarget();
1402 if(!pUnitTarget)
1403 break;
1405 unMaxTargets = EffectChainTarget;
1407 float max_range;
1408 if(m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE)
1409 max_range = radius; //
1410 else
1411 //FIXME: This very like horrible hack and wrong for most spells
1412 max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1414 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1415 Cell cell(p);
1416 cell.data.Part.reserved = ALL_DISTRICT;
1417 cell.SetNoCreate();
1419 Unit* originalCaster = GetOriginalCaster();
1420 if(originalCaster)
1422 std::list<Unit *> tempUnitMap;
1425 MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, originalCaster, max_range);
1426 MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1428 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1429 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
1431 CellLock<GridReadGuard> cell_lock(cell, p);
1432 cell_lock->Visit(cell_lock, world_unit_searcher, *m_caster->GetMap());
1433 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_caster->GetMap());
1436 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1438 if(tempUnitMap.empty())
1439 break;
1441 if(*tempUnitMap.begin() == pUnitTarget)
1442 tempUnitMap.erase(tempUnitMap.begin());
1444 TagUnitMap.push_back(pUnitTarget);
1445 uint32 t = unMaxTargets - 1;
1446 Unit *prev = pUnitTarget;
1447 std::list<Unit*>::iterator next = tempUnitMap.begin();
1449 while(t && next != tempUnitMap.end() )
1451 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1452 break;
1454 if(!prev->IsWithinLOSInMap(*next))
1456 ++next;
1457 continue;
1460 prev = *next;
1461 TagUnitMap.push_back(prev);
1462 tempUnitMap.erase(next);
1463 tempUnitMap.sort(TargetDistanceOrder(prev));
1464 next = tempUnitMap.begin();
1466 --t;
1470 }break;
1471 case TARGET_ALL_ENEMY_IN_AREA:
1473 }break;
1474 case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1476 // targets the ground, not the units in the area
1477 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1479 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1480 Cell cell(p);
1481 cell.data.Part.reserved = ALL_DISTRICT;
1482 cell.SetNoCreate();
1484 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1486 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1487 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1489 CellLock<GridReadGuard> cell_lock(cell, p);
1490 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1491 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1493 // exclude caster (this can be important if this not original caster)
1494 TagUnitMap.remove(m_caster);
1496 }break;
1497 case TARGET_DUELVSPLAYER_COORDINATES:
1499 if(Unit* currentTarget = m_targets.getUnitTarget())
1501 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1502 TagUnitMap.push_back(currentTarget);
1504 }break;
1505 case TARGET_ALL_PARTY_AROUND_CASTER:
1506 case TARGET_ALL_PARTY_AROUND_CASTER_2:
1507 case TARGET_ALL_PARTY:
1508 case TARGET_ALL_RAID_AROUND_CASTER:
1510 Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1511 Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1513 if(pGroup)
1515 uint8 subgroup = pTarget->GetSubGroup();
1517 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1519 Player* Target = itr->getSource();
1521 // IsHostileTo check duel and controlled by enemy
1522 if( Target &&
1523 (cur==TARGET_ALL_RAID_AROUND_CASTER || Target->GetSubGroup()==subgroup) &&
1524 !m_caster->IsHostileTo(Target) )
1526 if( m_caster->IsWithinDistInMap(Target, radius) )
1527 TagUnitMap.push_back(Target);
1529 if(Pet* pet = Target->GetPet())
1530 if( m_caster->IsWithinDistInMap(pet, radius) )
1531 TagUnitMap.push_back(pet);
1535 else
1537 Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1538 if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1539 TagUnitMap.push_back(ownerOrSelf);
1540 if(Pet* pet = ownerOrSelf->GetPet())
1541 if( m_caster->IsWithinDistInMap(pet, radius) )
1542 TagUnitMap.push_back(pet);
1544 }break;
1545 case TARGET_SINGLE_FRIEND:
1546 case TARGET_SINGLE_FRIEND_2:
1548 if(m_targets.getUnitTarget())
1549 TagUnitMap.push_back(m_targets.getUnitTarget());
1550 }break;
1551 case TARGET_NONCOMBAT_PET:
1553 if(Unit* target = m_targets.getUnitTarget())
1554 if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1555 TagUnitMap.push_back(target);
1556 }break;
1557 case TARGET_ALL_AROUND_CASTER:
1559 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1560 Cell cell(p);
1561 cell.data.Part.reserved = ALL_DISTRICT;
1562 cell.SetNoCreate();
1564 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1566 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1567 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1569 CellLock<GridReadGuard> cell_lock(cell, p);
1570 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1571 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1572 }break;
1573 case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1575 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1576 Cell cell(p);
1577 cell.data.Part.reserved = ALL_DISTRICT;
1578 cell.SetNoCreate();
1580 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_SELF_CENTER,SPELL_TARGETS_FRIENDLY);
1582 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1583 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1585 CellLock<GridReadGuard> cell_lock(cell, p);
1586 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1587 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1588 }break;
1589 case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1591 CellPair p(MaNGOS::ComputeCellPair(m_targets.m_destX, m_targets.m_destY));
1592 Cell cell(p);
1593 cell.data.Part.reserved = ALL_DISTRICT;
1594 cell.SetNoCreate();
1596 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_FRIENDLY);
1598 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1599 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1601 CellLock<GridReadGuard> cell_lock(cell, p);
1602 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1603 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1604 }break;
1605 // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some seals, fire shield from imp, etc..)
1606 case TARGET_SINGLE_PARTY:
1608 Unit *target = m_targets.getUnitTarget();
1609 // Thoses spells apparently can't be casted on the caster.
1610 if( target && target != m_caster)
1612 // Can only be casted on group's members or its pets
1613 Group *pGroup = NULL;
1615 Unit* owner = m_caster->GetCharmerOrOwner();
1616 Unit *targetOwner = target->GetCharmerOrOwner();
1617 if(owner)
1619 if(owner->GetTypeId() == TYPEID_PLAYER)
1621 if( target == owner )
1623 TagUnitMap.push_back(target);
1624 break;
1626 pGroup = ((Player*)owner)->GetGroup();
1629 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1631 if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1633 TagUnitMap.push_back(target);
1634 break;
1636 pGroup = ((Player*)m_caster)->GetGroup();
1639 if(pGroup)
1641 // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1642 if(targetOwner)
1644 if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1645 target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1646 target->GetOwnerGUID()==targetOwner->GetGUID() &&
1647 pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1649 TagUnitMap.push_back(target);
1652 // 1Our target can be a player who is on our group
1653 else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1655 TagUnitMap.push_back(target);
1659 }break;
1660 case TARGET_GAMEOBJECT:
1662 if(m_targets.getGOTarget())
1663 AddGOTarget(m_targets.getGOTarget(), i);
1664 }break;
1665 case TARGET_IN_FRONT_OF_CASTER:
1667 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1668 Cell cell(p);
1669 cell.data.Part.reserved = ALL_DISTRICT;
1670 cell.SetNoCreate();
1672 bool inFront = m_spellInfo->SpellVisual[0] != 3879;
1673 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, inFront ? PUSH_IN_FRONT : PUSH_IN_BACK,SPELL_TARGETS_AOE_DAMAGE);
1675 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1676 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1678 CellLock<GridReadGuard> cell_lock(cell, p);
1679 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1680 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1681 }break;
1682 case TARGET_DUELVSPLAYER:
1684 Unit *target = m_targets.getUnitTarget();
1685 if(target)
1687 if(m_caster->IsFriendlyTo(target))
1689 TagUnitMap.push_back(target);
1691 else
1693 Unit* pUnitTarget = SelectMagnetTarget();
1694 if(pUnitTarget)
1695 TagUnitMap.push_back(pUnitTarget);
1698 }break;
1699 case TARGET_GAMEOBJECT_ITEM:
1701 if(m_targets.getGOTargetGUID())
1702 AddGOTarget(m_targets.getGOTarget(), i);
1703 else if(m_targets.getItemTarget())
1704 AddItemTarget(m_targets.getItemTarget(), i);
1705 break;
1707 case TARGET_MASTER:
1709 if(Unit* owner = m_caster->GetCharmerOrOwner())
1710 TagUnitMap.push_back(owner);
1711 break;
1713 case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1715 // targets the ground, not the units in the area
1716 if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1718 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1719 Cell cell(p);
1720 cell.data.Part.reserved = ALL_DISTRICT;
1721 cell.SetNoCreate();
1723 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1725 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1726 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1728 CellLock<GridReadGuard> cell_lock(cell, p);
1729 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1730 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1732 }break;
1733 case TARGET_MINION:
1735 if(m_spellInfo->Effect[i] != SPELL_EFFECT_DUEL)
1736 TagUnitMap.push_back(m_caster);
1737 }break;
1738 case TARGET_SINGLE_ENEMY:
1740 Unit* pUnitTarget = SelectMagnetTarget();
1741 if(pUnitTarget)
1742 TagUnitMap.push_back(pUnitTarget);
1743 }break;
1744 case TARGET_AREAEFFECT_PARTY:
1746 Unit* owner = m_caster->GetCharmerOrOwner();
1747 Player *pTarget = NULL;
1749 if(owner)
1751 TagUnitMap.push_back(m_caster);
1752 if(owner->GetTypeId() == TYPEID_PLAYER)
1753 pTarget = (Player*)owner;
1755 else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1757 if(Unit* target = m_targets.getUnitTarget())
1759 if( target->GetTypeId() != TYPEID_PLAYER)
1761 if(((Creature*)target)->isPet())
1763 Unit *targetOwner = target->GetOwner();
1764 if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1765 pTarget = (Player*)targetOwner;
1768 else
1769 pTarget = (Player*)target;
1773 Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1775 if(pGroup)
1777 uint8 subgroup = pTarget->GetSubGroup();
1779 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1781 Player* Target = itr->getSource();
1783 // IsHostileTo check duel and controlled by enemy
1784 if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1786 if( pTarget->IsWithinDistInMap(Target, radius) )
1787 TagUnitMap.push_back(Target);
1789 if(Pet* pet = Target->GetPet())
1790 if( pTarget->IsWithinDistInMap(pet, radius) )
1791 TagUnitMap.push_back(pet);
1795 else if (owner)
1797 if(m_caster->IsWithinDistInMap(owner, radius))
1798 TagUnitMap.push_back(owner);
1800 else if(pTarget)
1802 TagUnitMap.push_back(pTarget);
1804 if(Pet* pet = pTarget->GetPet())
1805 if( m_caster->IsWithinDistInMap(pet, radius) )
1806 TagUnitMap.push_back(pet);
1809 }break;
1810 case TARGET_SCRIPT:
1812 if(m_targets.getUnitTarget())
1813 TagUnitMap.push_back(m_targets.getUnitTarget());
1814 if(m_targets.getItemTarget())
1815 AddItemTarget(m_targets.getItemTarget(), i);
1816 }break;
1817 case TARGET_SELF_FISHING:
1819 TagUnitMap.push_back(m_caster);
1820 }break;
1821 case TARGET_CHAIN_HEAL:
1823 Unit* pUnitTarget = m_targets.getUnitTarget();
1824 if(!pUnitTarget)
1825 break;
1827 if (EffectChainTarget <= 1)
1828 TagUnitMap.push_back(pUnitTarget);
1829 else
1831 unMaxTargets = EffectChainTarget;
1832 float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1834 std::list<Unit *> tempUnitMap;
1837 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1838 Cell cell(p);
1839 cell.data.Part.reserved = ALL_DISTRICT;
1840 cell.SetNoCreate();
1842 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1844 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1845 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_object_notifier(notifier);
1847 CellLock<GridReadGuard> cell_lock(cell, p);
1848 cell_lock->Visit(cell_lock, world_object_notifier, *m_caster->GetMap());
1849 cell_lock->Visit(cell_lock, grid_object_notifier, *m_caster->GetMap());
1853 if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1854 tempUnitMap.push_front(m_caster);
1856 tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1858 if(tempUnitMap.empty())
1859 break;
1861 if(*tempUnitMap.begin() == pUnitTarget)
1862 tempUnitMap.erase(tempUnitMap.begin());
1864 TagUnitMap.push_back(pUnitTarget);
1865 uint32 t = unMaxTargets - 1;
1866 Unit *prev = pUnitTarget;
1867 std::list<Unit*>::iterator next = tempUnitMap.begin();
1869 while(t && next != tempUnitMap.end() )
1871 if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1872 break;
1874 if(!prev->IsWithinLOSInMap(*next))
1876 ++next;
1877 continue;
1880 if((*next)->GetHealth() == (*next)->GetMaxHealth())
1882 next = tempUnitMap.erase(next);
1883 continue;
1886 prev = *next;
1887 TagUnitMap.push_back(prev);
1888 tempUnitMap.erase(next);
1889 tempUnitMap.sort(TargetDistanceOrder(prev));
1890 next = tempUnitMap.begin();
1892 --t;
1895 }break;
1896 case TARGET_CURRENT_ENEMY_COORDINATES:
1898 Unit* currentTarget = m_targets.getUnitTarget();
1899 if(currentTarget)
1901 TagUnitMap.push_back(currentTarget);
1902 m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ());
1903 if(m_spellInfo->EffectImplicitTargetB[i]==TARGET_ALL_ENEMY_IN_AREA_INSTANT)
1905 CellPair p(MaNGOS::ComputeCellPair(currentTarget->GetPositionX(), currentTarget->GetPositionY()));
1906 Cell cell(p);
1907 cell.data.Part.reserved = ALL_DISTRICT;
1908 cell.SetNoCreate();
1909 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_TARGET_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1910 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1911 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1912 CellLock<GridReadGuard> cell_lock(cell, p);
1913 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1914 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1917 }break;
1918 case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1920 Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1921 ? (Player*)m_targets.getUnitTarget() : NULL;
1923 Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1924 if(pGroup)
1926 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1928 Player* Target = itr->getSource();
1930 // IsHostileTo check duel and controlled by enemy
1931 if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1932 targetPlayer->getClass() == Target->getClass() &&
1933 !m_caster->IsHostileTo(Target) )
1935 TagUnitMap.push_back(Target);
1939 else if(m_targets.getUnitTarget())
1940 TagUnitMap.push_back(m_targets.getUnitTarget());
1941 break;
1943 case TARGET_TABLE_X_Y_Z_COORDINATES:
1945 SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id);
1946 if(st)
1948 if (st->target_mapId == m_caster->GetMapId())
1949 m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1951 // if B==TARGET_TABLE_X_Y_Z_COORDINATES then A already fill all required targets
1952 if (m_spellInfo->EffectImplicitTargetB[i] && m_spellInfo->EffectImplicitTargetB[i]!=TARGET_TABLE_X_Y_Z_COORDINATES)
1954 CellPair p(MaNGOS::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1955 Cell cell(p);
1956 cell.data.Part.reserved = ALL_DISTRICT;
1957 cell.SetNoCreate();
1959 SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE;
1960 // Select friendly targets for positive effect
1961 if (IsPositiveEffect(m_spellInfo->Id, i))
1962 targetB = SPELL_TARGETS_FRIENDLY;
1964 MaNGOS::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius,PUSH_DEST_CENTER, targetB);
1966 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_notifier(notifier);
1967 TypeContainerVisitor<MaNGOS::SpellNotifierCreatureAndPlayer, GridTypeMapContainer > grid_notifier(notifier);
1969 CellLock<GridReadGuard> cell_lock(cell, p);
1970 cell_lock->Visit(cell_lock, world_notifier, *m_caster->GetMap());
1971 cell_lock->Visit(cell_lock, grid_notifier, *m_caster->GetMap());
1974 else
1975 sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1976 }break;
1977 case TARGET_BEHIND_VICTIM:
1979 Unit *pTarget = m_caster->getVictim();
1980 if(!pTarget && m_caster->GetTypeId() == TYPEID_PLAYER)
1981 pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
1983 if(pTarget)
1985 float _target_x, _target_y, _target_z;
1986 pTarget->GetClosePoint(_target_x, _target_y, _target_z, m_caster->GetObjectSize(), CONTACT_DISTANCE, M_PI);
1987 if(pTarget->IsWithinLOS(_target_x,_target_y,_target_z))
1988 m_targets.setDestination(_target_x, _target_y, _target_z);
1990 }break;
1991 case TARGET_DYNAMIC_OBJECT_COORDINATES:
1993 // if parent spell create dynamic object extract area from it
1994 if(DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id))
1995 m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ());
1996 }break;
1997 default:
1998 break;
2001 if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2003 // make sure one unit is always removed per iteration
2004 uint32 removed_utarget = 0;
2005 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2007 next = itr;
2008 ++next;
2009 if (!*itr) continue;
2010 if ((*itr) == m_targets.getUnitTarget())
2012 TagUnitMap.erase(itr);
2013 removed_utarget = 1;
2014 // break;
2017 // remove random units from the map
2018 while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2020 uint32 poz = urand(0, TagUnitMap.size()-1);
2021 for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2023 if (!*itr) continue;
2024 if (!poz)
2026 TagUnitMap.erase(itr);
2027 break;
2031 // the player's target will always be added to the map
2032 if (removed_utarget && m_targets.getUnitTarget())
2033 TagUnitMap.push_back(m_targets.getUnitTarget());
2037 void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura)
2039 m_targets = *targets;
2041 m_spellState = SPELL_STATE_PREPARING;
2043 m_castPositionX = m_caster->GetPositionX();
2044 m_castPositionY = m_caster->GetPositionY();
2045 m_castPositionZ = m_caster->GetPositionZ();
2046 m_castOrientation = m_caster->GetOrientation();
2048 if(triggeredByAura)
2049 m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
2051 // create and add update event for this spell
2052 SpellEvent* Event = new SpellEvent(this);
2053 m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2055 //Prevent casting at cast another spell (ServerSide check)
2056 if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
2058 SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2059 finish(false);
2060 return;
2063 // Fill cost data
2064 m_powerCost = CalculatePowerCost();
2066 uint8 result = CanCast(true);
2067 if(result != 0 && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
2069 if(triggeredByAura)
2071 SendChannelUpdate(0);
2072 triggeredByAura->SetAuraDuration(0);
2074 SendCastResult(result);
2075 finish(false);
2076 return;
2079 // Prepare data for triggers
2080 prepareDataForTriggerSystem();
2082 // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2083 m_casttime = GetSpellCastTime(m_spellInfo, this);
2085 // set timer base at cast time
2086 ReSetTimer();
2088 // stealth must be removed at cast starting (at show channel bar)
2089 // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2090 if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2092 m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
2093 m_caster->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
2096 if(m_IsTriggeredSpell)
2097 cast(true);
2098 else
2100 m_caster->SetCurrentCastedSpell( this );
2101 m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2102 SendSpellStart();
2106 void Spell::cancel()
2108 if(m_spellState == SPELL_STATE_FINISHED)
2109 return;
2111 m_autoRepeat = false;
2112 switch (m_spellState)
2114 case SPELL_STATE_PREPARING:
2115 case SPELL_STATE_DELAYED:
2117 SendInterrupted(0);
2118 SendCastResult(SPELL_FAILED_INTERRUPTED);
2119 } break;
2121 case SPELL_STATE_CASTING:
2123 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2125 if( ihit->missCondition == SPELL_MISS_NONE )
2127 Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2128 if( unit && unit->isAlive() )
2129 unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2133 m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2134 SendChannelUpdate(0);
2135 SendInterrupted(0);
2136 SendCastResult(SPELL_FAILED_INTERRUPTED);
2137 } break;
2139 default:
2141 } break;
2144 finish(false);
2145 m_caster->RemoveDynObject(m_spellInfo->Id);
2146 m_caster->RemoveGameObject(m_spellInfo->Id,true);
2149 void Spell::cast(bool skipCheck)
2151 SetExecutedCurrently(true);
2153 uint8 castResult = 0;
2155 // update pointers base at GUIDs to prevent access to non-existed already object
2156 UpdatePointers();
2158 // cancel at lost main target unit
2159 if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2161 cancel();
2162 SetExecutedCurrently(false);
2163 return;
2166 if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2167 m_caster->SetInFront(m_targets.getUnitTarget());
2169 castResult = CheckPower();
2170 if(castResult != 0)
2172 SendCastResult(castResult);
2173 finish(false);
2174 SetExecutedCurrently(false);
2175 return;
2178 // triggered cast called from Spell::prepare where it was already checked
2179 if(!skipCheck)
2181 castResult = CanCast(false);
2182 if(castResult != 0)
2184 SendCastResult(castResult);
2185 finish(false);
2186 SetExecutedCurrently(false);
2187 return;
2191 // Conflagrate - consumes immolate
2192 if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2194 // for caster applied auras only
2195 Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2196 for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2198 if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2199 (*i)->GetCasterGUID()==m_caster->GetGUID() )
2201 m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2202 break;
2207 // traded items have trade slot instead of guid in m_itemTargetGUID
2208 // set to real guid to be sent later to the client
2209 m_targets.updateTradeSlotItem();
2211 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2213 if (m_CastItem)
2214 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
2216 ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
2219 // CAST SPELL
2220 SendSpellCooldown();
2222 TakePower();
2223 TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
2224 FillTargetMap();
2226 if(m_spellState == SPELL_STATE_FINISHED) // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2228 SetExecutedCurrently(false);
2229 return;
2232 SendCastResult(castResult);
2233 SendSpellGo(); // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2235 // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2236 if (m_spellInfo->speed > 0.0f)
2239 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2240 // in case delayed spell remove item at cast delay start
2241 TakeCastItem();
2243 // Okay, maps created, now prepare flags
2244 m_immediateHandled = false;
2245 m_spellState = SPELL_STATE_DELAYED;
2246 SetDelayStart(0);
2248 else
2250 // Immediate spell, no big deal
2251 handle_immediate();
2254 SetExecutedCurrently(false);
2257 void Spell::handle_immediate()
2259 // start channeling if applicable
2260 if(IsChanneledSpell(m_spellInfo))
2262 int32 duration = GetSpellDuration(m_spellInfo);
2263 if (duration)
2265 m_spellState = SPELL_STATE_CASTING;
2266 SendChannelStart(duration);
2270 // process immediate effects (items, ground, etc.) also initialize some variables
2271 _handle_immediate_phase();
2273 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2274 DoAllEffectOnTarget(&(*ihit));
2276 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2277 DoAllEffectOnTarget(&(*ihit));
2279 // spell is finished, perform some last features of the spell here
2280 _handle_finish_phase();
2282 // Remove used for cast item if need (it can be already NULL after TakeReagents call
2283 TakeCastItem();
2285 if(m_spellState != SPELL_STATE_CASTING)
2286 finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
2289 uint64 Spell::handle_delayed(uint64 t_offset)
2291 uint64 next_time = 0;
2293 if (!m_immediateHandled)
2295 _handle_immediate_phase();
2296 m_immediateHandled = true;
2299 // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
2300 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2302 if (ihit->processed == false)
2304 if ( ihit->timeDelay <= t_offset )
2305 DoAllEffectOnTarget(&(*ihit));
2306 else if( next_time == 0 || ihit->timeDelay < next_time )
2307 next_time = ihit->timeDelay;
2311 // now recheck gameobject targeting correctness
2312 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2314 if (ighit->processed == false)
2316 if ( ighit->timeDelay <= t_offset )
2317 DoAllEffectOnTarget(&(*ighit));
2318 else if( next_time == 0 || ighit->timeDelay < next_time )
2319 next_time = ighit->timeDelay;
2322 // All targets passed - need finish phase
2323 if (next_time == 0)
2325 // spell is finished, perform some last features of the spell here
2326 _handle_finish_phase();
2328 finish(true); // successfully finish spell cast
2330 // return zero, spell is finished now
2331 return 0;
2333 else
2335 // spell is unfinished, return next execution time
2336 return next_time;
2340 void Spell::_handle_immediate_phase()
2342 // handle some immediate features of the spell here
2343 HandleThreatSpells(m_spellInfo->Id);
2345 m_needSpellLog = IsNeedSendToClient();
2346 for(uint32 j = 0;j<3;j++)
2348 if(m_spellInfo->Effect[j]==0)
2349 continue;
2351 // apply Send Event effect to ground in case empty target lists
2352 if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2354 HandleEffects(NULL,NULL,NULL, j);
2355 continue;
2358 // Don't do spell log, if is school damage spell
2359 if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2360 m_needSpellLog = false;
2362 uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2363 if(m_originalCaster)
2364 if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2365 modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2367 // initialize multipliers
2368 m_damageMultipliers[j] = 1.0f;
2369 if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2370 (EffectChainTarget > 1) )
2371 m_applyMultiplierMask |= 1 << j;
2374 // initialize Diminishing Returns Data
2375 m_diminishLevel = DIMINISHING_LEVEL_1;
2376 m_diminishGroup = DIMINISHING_NONE;
2378 // process items
2379 for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2380 DoAllEffectOnTarget(&(*ihit));
2382 // process ground
2383 for(uint32 j = 0;j<3;j++)
2385 // persistent area auras target only the ground
2386 if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2387 HandleEffects(NULL,NULL,NULL, j);
2391 void Spell::_handle_finish_phase()
2393 // spell log
2394 if(m_needSpellLog)
2395 SendLogExecute();
2398 void Spell::SendSpellCooldown()
2400 if(m_caster->GetTypeId() != TYPEID_PLAYER)
2401 return;
2403 Player* _player = (Player*)m_caster;
2404 // Add cooldown for max (disable spell)
2405 // Cooldown started on SendCooldownEvent call
2406 if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2408 _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2409 return;
2412 // init cooldown values
2413 uint32 cat = 0;
2414 int32 rec = -1;
2415 int32 catrec = -1;
2417 // some special item spells without correct cooldown in SpellInfo
2418 // cooldown information stored in item prototype
2419 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2421 if(m_CastItem)
2423 ItemPrototype const* proto = m_CastItem->GetProto();
2424 if(proto)
2426 for(int idx = 0; idx < 5; ++idx)
2428 if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2430 cat = proto->Spells[idx].SpellCategory;
2431 rec = proto->Spells[idx].SpellCooldown;
2432 catrec = proto->Spells[idx].SpellCategoryCooldown;
2433 break;
2439 // if no cooldown found above then base at DBC data
2440 if(rec < 0 && catrec < 0)
2442 cat = m_spellInfo->Category;
2443 rec = m_spellInfo->RecoveryTime;
2444 catrec = m_spellInfo->CategoryRecoveryTime;
2447 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2448 // prevent 0 cooldowns set by another way
2449 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(m_spellInfo) && m_spellInfo->Id != SPELL_ID_AUTOSHOT))
2450 rec = _player->GetAttackTime(RANGED_ATTACK);
2452 // Now we have cooldown data (if found any), time to apply mods
2453 if(rec > 0)
2454 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2456 if(catrec > 0)
2457 _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2459 // replace negative cooldowns by 0
2460 if (rec < 0) rec = 0;
2461 if (catrec < 0) catrec = 0;
2463 // no cooldown after applying spell mods
2464 if( rec == 0 && catrec == 0)
2465 return;
2467 time_t curTime = time(NULL);
2469 time_t catrecTime = catrec ? curTime+catrec/1000 : 0; // in secs
2470 time_t recTime = rec ? curTime+rec/1000 : catrecTime;// in secs
2472 // self spell cooldown
2473 if(recTime > 0)
2474 _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2476 // category spells
2477 if (catrec > 0)
2479 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2480 if(i_scstore != sSpellCategoryStore.end())
2482 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2484 if(*i_scset == m_spellInfo->Id) // skip main spell, already handled above
2485 continue;
2487 _player->AddSpellCooldown(*i_scset, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2493 void Spell::update(uint32 difftime)
2495 // update pointers based at it's GUIDs
2496 UpdatePointers();
2498 if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2500 cancel();
2501 return;
2504 // check if the player caster has moved before the spell finished
2505 if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2506 (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2507 (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2509 // always cancel for channeled spells
2510 if( m_spellState == SPELL_STATE_CASTING )
2511 cancel();
2512 // don't cancel for melee, autorepeat, triggered and instant spells
2513 else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2514 cancel();
2517 switch(m_spellState)
2519 case SPELL_STATE_PREPARING:
2521 if(m_timer)
2523 if(difftime >= m_timer)
2524 m_timer = 0;
2525 else
2526 m_timer -= difftime;
2529 if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2530 cast();
2531 } break;
2532 case SPELL_STATE_CASTING:
2534 if(m_timer > 0)
2536 if( m_caster->GetTypeId() == TYPEID_PLAYER )
2538 // check if player has jumped before the channeling finished
2539 if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2540 cancel();
2542 // check for incapacitating player states
2543 if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2544 cancel();
2546 // check if player has turned if flag is set
2547 if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2548 cancel();
2551 // check if there are alive targets left
2552 if (!IsAliveUnitPresentInTargetList())
2554 SendChannelUpdate(0);
2555 finish();
2558 if(difftime >= m_timer)
2559 m_timer = 0;
2560 else
2561 m_timer -= difftime;
2564 if(m_timer == 0)
2566 SendChannelUpdate(0);
2568 // channeled spell processed independently for quest targeting
2569 // cast at creature (or GO) quest objectives update at successful cast channel finished
2570 // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2571 if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2573 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2575 TargetInfo* target = &*ihit;
2576 if(!IS_CREATURE_GUID(target->targetGUID))
2577 continue;
2579 Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2580 if (unit==NULL)
2581 continue;
2583 ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2586 for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2588 GOTargetInfo* target = &*ihit;
2590 GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2591 if(!go)
2592 continue;
2594 ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2598 finish();
2600 } break;
2601 default:
2603 }break;
2607 void Spell::finish(bool ok)
2609 if(!m_caster)
2610 return;
2612 if(m_spellState == SPELL_STATE_FINISHED)
2613 return;
2615 m_spellState = SPELL_STATE_FINISHED;
2617 // other code related only to successfully finished spells
2618 if(!ok)
2619 return;
2621 //remove spell mods
2622 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2623 ((Player*)m_caster)->RemoveSpellMods(this);
2625 //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2626 Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2627 for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2629 SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2630 uint32 auraSpellIdx = (*i)->GetEffIndex();
2631 if (IsAffectedByAura((*i)))
2633 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2634 if( ihit->effectMask & (1<<auraSpellIdx) )
2636 // check m_caster->GetGUID() let load auras at login and speedup most often case
2637 Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2638 if (unit && unit->isAlive())
2640 // Calculate chance at that moment (can be depend for example from combo points)
2641 int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2643 if(roll_chance_i(chance))
2644 m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2650 // Heal caster for all health leech from all targets
2651 if (m_healthLeech)
2653 m_caster->ModifyHealth(m_healthLeech);
2654 m_caster->SendHealSpellLog(m_caster, m_spellInfo->Id, uint32(m_healthLeech));
2657 if (IsMeleeAttackResetSpell())
2659 m_caster->resetAttackTimer(BASE_ATTACK);
2660 if(m_caster->haveOffhandWeapon())
2661 m_caster->resetAttackTimer(OFF_ATTACK);
2664 /*if (IsRangedAttackResetSpell())
2665 m_caster->resetAttackTimer(RANGED_ATTACK);*/
2667 // Clear combo at finish state
2668 if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2670 // Not drop combopoints if negative spell and if any miss on enemy exist
2671 bool needDrop = true;
2672 if (!IsPositiveSpell(m_spellInfo->Id))
2673 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2674 if (ihit->missCondition != SPELL_MISS_NONE && ihit->targetGUID!=m_caster->GetGUID())
2676 needDrop = false;
2677 break;
2679 if (needDrop)
2680 ((Player*)m_caster)->ClearComboPoints();
2683 // Post effects apply on spell targets in some spells
2684 if(!m_UniqueTargetInfo.empty())
2686 uint32 spellId = 0;
2687 switch(m_spellInfo->SpellFamilyName)
2689 case SPELLFAMILY_GENERIC:
2691 if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
2692 spellId = 11196; // Recently Bandaged
2693 else if(m_spellInfo->SpellIconID == 1662 && m_spellInfo->AttributesEx & 0x20) // Blood Fury (Racial)
2694 spellId = 23230; // Blood Fury - Healing Reduction
2695 break;
2697 case SPELLFAMILY_MAGE:
2699 if (m_spellInfo->SpellFamilyFlags&0x0000008000000000LL) // Ice Block
2700 spellId = 41425; // Hypothermia
2701 break;
2703 case SPELLFAMILY_PRIEST:
2705 if (m_spellInfo->Mechanic == MECHANIC_SHIELD &&
2706 m_spellInfo->SpellIconID == 566) // Power Word: Shield
2707 spellId = 6788; // Weakened Soul
2708 break;
2710 case SPELLFAMILY_PALADIN:
2712 if (m_spellInfo->SpellFamilyFlags&0x0000000000400080LL) // Divine Shield, Divine Protection or Hand of Protection
2713 spellId = 25771; // Forbearance
2714 break;
2716 case SPELLFAMILY_SHAMAN:
2718 if (m_spellInfo->Id == 2825) // Bloodlust
2719 spellId = 57724; // Sated
2720 else if (m_spellInfo->Id == 32182) // Heroism
2721 spellId = 57723; // Exhaustion
2722 break;
2724 default:
2725 break;
2727 if (spellId)
2729 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2731 Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2732 if (unit)
2734 // TODO: fix me use cast spell (now post spell can immune by this spell)
2735 // m_caster->CastSpell(unit, spellId, true, m_CastItem);
2736 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(spellId);
2737 if (!AdditionalSpellInfo)
2738 continue;
2739 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, 0, &m_currentBasePoints[0], unit, m_caster, m_CastItem);
2740 unit->AddAura(AdditionalAura);
2745 // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2746 if(!m_TriggerSpells.empty())
2747 TriggerSpell();
2749 // Stop Attack for some spells
2750 if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2751 m_caster->AttackStop();
2754 void Spell::SendCastResult(uint8 result)
2756 if (m_caster->GetTypeId() != TYPEID_PLAYER)
2757 return;
2759 if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
2760 return;
2762 if(result != 0)
2764 WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2765 data << uint8(m_cast_count); // single cast or multi 2.3 (0/1)
2766 data << uint32(m_spellInfo->Id);
2767 data << uint8(result); // problem
2768 switch (result)
2770 case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2771 data << uint32(m_spellInfo->RequiresSpellFocus);
2772 break;
2773 case SPELL_FAILED_REQUIRES_AREA:
2774 // hardcode areas limitation case
2775 switch(m_spellInfo->Id)
2777 case 41617: // Cenarion Mana Salve
2778 case 41619: // Cenarion Healing Salve
2779 data << uint32(3905);
2780 break;
2781 case 41618: // Bottled Nethergon Energy
2782 case 41620: // Bottled Nethergon Vapor
2783 data << uint32(3842);
2784 break;
2785 case 45373: // Bloodberry Elixir
2786 data << uint32(4075);
2787 break;
2788 default: // default case (don't must be)
2789 data << uint32(0);
2790 break;
2792 break;
2793 case SPELL_FAILED_TOTEMS:
2794 if(m_spellInfo->Totem[0])
2795 data << uint32(m_spellInfo->Totem[0]);
2796 if(m_spellInfo->Totem[1])
2797 data << uint32(m_spellInfo->Totem[1]);
2798 break;
2799 case SPELL_FAILED_TOTEM_CATEGORY:
2800 if(m_spellInfo->TotemCategory[0])
2801 data << uint32(m_spellInfo->TotemCategory[0]);
2802 if(m_spellInfo->TotemCategory[1])
2803 data << uint32(m_spellInfo->TotemCategory[1]);
2804 break;
2805 case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2806 data << uint32(m_spellInfo->EquippedItemClass);
2807 data << uint32(m_spellInfo->EquippedItemSubClassMask);
2808 //data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2809 break;
2811 ((Player*)m_caster)->GetSession()->SendPacket(&data);
2815 void Spell::SendSpellStart()
2817 if(!IsNeedSendToClient())
2818 return;
2820 sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
2822 uint32 castFlags = CAST_FLAG_UNKNOWN1;
2823 if(IsRangedSpell())
2824 castFlags |= CAST_FLAG_AMMO;
2826 if(m_spellInfo->runeCostID)
2827 castFlags |= CAST_FLAG_UNKNOWN10;
2829 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2831 WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2832 if(m_CastItem)
2833 data.append(m_CastItem->GetPackGUID());
2834 else
2835 data.append(m_caster->GetPackGUID());
2837 data.append(m_caster->GetPackGUID());
2838 data << uint8(m_cast_count); // pending spell cast?
2839 data << uint32(m_spellInfo->Id); // spellId
2840 data << uint32(castFlags); // cast flags
2841 data << uint32(m_timer); // delay?
2843 m_targets.write(&data);
2845 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // predicted power?
2846 data << uint32(0);
2848 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2850 uint8 v1 = 0;//m_runesState;
2851 uint8 v2 = 0;//((Player*)m_caster)->GetRunesState();
2852 data << uint8(v1); // runes state before
2853 data << uint8(v2); // runes state after
2854 for(uint8 i = 0; i < MAX_RUNES; ++i)
2856 uint8 m = (1 << i);
2857 if(m & v1) // usable before...
2858 if(!(m & v2)) // ...but on cooldown now...
2859 data << uint8(0); // some unknown byte (time?)
2863 if ( castFlags & CAST_FLAG_AMMO )
2864 WriteAmmoToPacket(&data);
2866 m_caster->SendMessageToSet(&data, true);
2869 void Spell::SendSpellGo()
2871 // not send invisible spell casting
2872 if(!IsNeedSendToClient())
2873 return;
2875 sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
2877 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2879 uint32 castFlags = CAST_FLAG_UNKNOWN3;
2880 if(IsRangedSpell())
2881 castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
2883 if((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID)
2885 castFlags |= CAST_FLAG_UNKNOWN10; // same as in SMSG_SPELL_START
2886 castFlags |= CAST_FLAG_UNKNOWN6; // makes cooldowns visible
2887 castFlags |= CAST_FLAG_UNKNOWN7; // rune cooldowns list
2890 WorldPacket data(SMSG_SPELL_GO, 50); // guess size
2891 if(m_CastItem)
2892 data.append(m_CastItem->GetPackGUID());
2893 else
2894 data.append(m_caster->GetPackGUID());
2896 data.append(m_caster->GetPackGUID());
2897 data << uint8(m_cast_count); // pending spell cast?
2898 data << uint32(m_spellInfo->Id); // spellId
2899 data << uint32(castFlags); // cast flags
2900 data << uint32(getMSTime()); // timestamp
2902 WriteSpellGoTargets(&data);
2904 m_targets.write(&data);
2906 if ( castFlags & CAST_FLAG_UNKNOWN6 ) // unknown wotlk, predicted power?
2907 data << uint32(0);
2909 if ( castFlags & CAST_FLAG_UNKNOWN7 ) // rune cooldowns list
2911 uint8 v1 = m_runesState;
2912 uint8 v2 = ((Player*)m_caster)->GetRunesState();
2913 data << uint8(v1); // runes state before
2914 data << uint8(v2); // runes state after
2915 for(uint8 i = 0; i < MAX_RUNES; ++i)
2917 uint8 m = (1 << i);
2918 if(m & v1) // usable before...
2919 if(!(m & v2)) // ...but on cooldown now...
2920 data << uint8(0); // some unknown byte (time?)
2924 if ( castFlags & CAST_FLAG_UNKNOWN4 ) // unknown wotlk
2926 data << float(0);
2927 data << uint32(0);
2930 if ( castFlags & CAST_FLAG_AMMO )
2931 WriteAmmoToPacket(&data);
2933 if ( castFlags & CAST_FLAG_UNKNOWN5 ) // unknown wotlk
2935 data << uint32(0);
2936 data << uint32(0);
2939 if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
2941 data << uint8(0);
2944 m_caster->SendMessageToSet(&data, true);
2947 void Spell::WriteAmmoToPacket( WorldPacket * data )
2949 uint32 ammoInventoryType = 0;
2950 uint32 ammoDisplayID = 0;
2952 if (m_caster->GetTypeId() == TYPEID_PLAYER)
2954 Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2955 if(pItem)
2957 ammoInventoryType = pItem->GetProto()->InventoryType;
2958 if( ammoInventoryType == INVTYPE_THROWN )
2959 ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2960 else
2962 uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2963 if(ammoID)
2965 ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2966 if(pProto)
2968 ammoDisplayID = pProto->DisplayInfoID;
2969 ammoInventoryType = pProto->InventoryType;
2972 else if(m_caster->GetDummyAura(46699)) // Requires No Ammo
2974 ammoDisplayID = 5996; // normal arrow
2975 ammoInventoryType = INVTYPE_AMMO;
2980 // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2982 *data << uint32(ammoDisplayID);
2983 *data << uint32(ammoInventoryType);
2986 void Spell::WriteSpellGoTargets( WorldPacket * data )
2988 uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
2989 uint32 miss = 0;
2990 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2992 if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
2994 // possibly SPELL_MISS_IMMUNE2 for this??
2995 ihit->missCondition = SPELL_MISS_IMMUNE2;
2996 miss++;
2998 else if ((*ihit).missCondition == SPELL_MISS_NONE)
2999 hit++;
3000 else
3001 miss++;
3004 *data << (uint8)hit;
3005 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3006 if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
3007 *data << uint64(ihit->targetGUID);
3009 for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
3010 *data << uint64(ighit->targetGUID); // Always hits
3012 *data << (uint8)miss;
3013 for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
3015 if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
3017 *data << uint64(ihit->targetGUID);
3018 *data << uint8(ihit->missCondition);
3019 if( ihit->missCondition == SPELL_MISS_REFLECT )
3020 *data << uint8(ihit->reflectResult);
3025 void Spell::SendLogExecute()
3027 Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
3029 WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
3031 if(m_caster->GetTypeId() == TYPEID_PLAYER)
3032 data.append(m_caster->GetPackGUID());
3033 else
3034 data.append(target->GetPackGUID());
3036 data << uint32(m_spellInfo->Id);
3037 uint32 count1 = 1;
3038 data << uint32(count1); // count1 (effect count?)
3039 for(uint32 i = 0; i < count1; ++i)
3041 data << uint32(m_spellInfo->Effect[0]); // spell effect
3042 uint32 count2 = 1;
3043 data << uint32(count2); // count2 (target count?)
3044 for(uint32 j = 0; j < count2; ++j)
3046 switch(m_spellInfo->Effect[0])
3048 case SPELL_EFFECT_POWER_DRAIN:
3049 if(Unit *unit = m_targets.getUnitTarget())
3050 data.append(unit->GetPackGUID());
3051 else
3052 data << uint8(0);
3053 data << uint32(0);
3054 data << uint32(0);
3055 data << float(0);
3056 break;
3057 case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
3058 if(Unit *unit = m_targets.getUnitTarget())
3059 data.append(unit->GetPackGUID());
3060 else
3061 data << uint8(0);
3062 data << uint32(0); // count?
3063 break;
3064 case SPELL_EFFECT_INTERRUPT_CAST:
3065 if(Unit *unit = m_targets.getUnitTarget())
3066 data.append(unit->GetPackGUID());
3067 else
3068 data << uint8(0);
3069 data << uint32(0); // spellid
3070 break;
3071 case SPELL_EFFECT_DURABILITY_DAMAGE:
3072 if(Unit *unit = m_targets.getUnitTarget())
3073 data.append(unit->GetPackGUID());
3074 else
3075 data << uint8(0);
3076 data << uint32(0);
3077 data << uint32(0);
3078 break;
3079 case SPELL_EFFECT_OPEN_LOCK:
3080 case SPELL_EFFECT_OPEN_LOCK_ITEM:
3081 if(Item *item = m_targets.getItemTarget())
3082 data.append(item->GetPackGUID());
3083 else
3084 data << uint8(0);
3085 break;
3086 case SPELL_EFFECT_CREATE_ITEM:
3087 case SPELL_EFFECT_CREATE_ITEM_2:
3088 data << uint32(m_spellInfo->EffectItemType[0]);
3089 break;
3090 case SPELL_EFFECT_SUMMON:
3091 case SPELL_EFFECT_TRANS_DOOR:
3092 case SPELL_EFFECT_SUMMON_PET:
3093 case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3094 case SPELL_EFFECT_CREATE_HOUSE:
3095 case SPELL_EFFECT_DUEL:
3096 case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3097 case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3098 case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3099 case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3100 if(Unit *unit = m_targets.getUnitTarget())
3101 data.append(unit->GetPackGUID());
3102 else if(m_targets.getItemTargetGUID())
3103 data.appendPackGUID(m_targets.getItemTargetGUID());
3104 else if(GameObject *go = m_targets.getGOTarget())
3105 data.append(go->GetPackGUID());
3106 else
3107 data << uint8(0); // guid
3108 break;
3109 case SPELL_EFFECT_FEED_PET:
3110 data << uint32(m_targets.getItemTargetEntry());
3111 break;
3112 case SPELL_EFFECT_DISMISS_PET:
3113 if(Unit *unit = m_targets.getUnitTarget())
3114 data.append(unit->GetPackGUID());
3115 else
3116 data << uint8(0);
3117 break;
3118 case SPELL_EFFECT_RESURRECT:
3119 case SPELL_EFFECT_RESURRECT_NEW:
3120 if(Unit *unit = m_targets.getUnitTarget())
3121 data.append(unit->GetPackGUID());
3122 else
3123 data << uint8(0);
3124 break;
3125 default:
3126 return;
3131 m_caster->SendMessageToSet(&data, true);
3134 void Spell::SendInterrupted(uint8 result)
3136 WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3137 data.append(m_caster->GetPackGUID());
3138 data << uint8(m_cast_count);
3139 data << uint32(m_spellInfo->Id);
3140 data << uint8(result);
3141 m_caster->SendMessageToSet(&data, true);
3143 data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3144 data.append(m_caster->GetPackGUID());
3145 data << uint8(m_cast_count);
3146 data << uint32(m_spellInfo->Id);
3147 data << uint8(result);
3148 m_caster->SendMessageToSet(&data, true);
3151 void Spell::SendChannelUpdate(uint32 time)
3153 if(time == 0)
3155 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3156 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3159 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3160 return;
3162 WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3163 data.append(m_caster->GetPackGUID());
3164 data << uint32(time);
3166 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3169 void Spell::SendChannelStart(uint32 duration)
3171 WorldObject* target = NULL;
3173 // select first not resisted target from target list for _0_ effect
3174 if(!m_UniqueTargetInfo.empty())
3176 for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3178 if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3180 target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3181 break;
3185 else if(!m_UniqueGOTargetInfo.empty())
3187 for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3189 if(itr->effectMask & (1<<0) )
3191 target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3192 break;
3197 if (m_caster->GetTypeId() == TYPEID_PLAYER)
3199 WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3200 data.append(m_caster->GetPackGUID());
3201 data << uint32(m_spellInfo->Id);
3202 data << uint32(duration);
3204 ((Player*)m_caster)->GetSession()->SendPacket( &data );
3207 m_timer = duration;
3208 if(target)
3209 m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3210 m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3213 void Spell::SendResurrectRequest(Player* target)
3215 // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
3216 // However, the packet structure differs slightly
3218 const char* sentName = m_caster->GetTypeId()==TYPEID_PLAYER ?"":m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
3220 WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
3221 data << uint64(m_caster->GetGUID());
3222 data << uint32(strlen(sentName)+1);
3224 data << sentName;
3225 data << uint8(0);
3227 data << uint8(m_caster->GetTypeId()==TYPEID_PLAYER ?0:1);
3228 target->GetSession()->SendPacket(&data);
3231 void Spell::SendPlaySpellVisual(uint32 SpellID)
3233 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3234 return;
3236 WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3237 data << uint64(m_caster->GetGUID());
3238 data << uint32(SpellID); // spell visual id?
3239 ((Player*)m_caster)->GetSession()->SendPacket(&data);
3242 void Spell::TakeCastItem()
3244 if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3245 return;
3247 // not remove cast item at triggered spell (equipping, weapon damage, etc)
3248 if(m_IsTriggeredSpell)
3249 return;
3251 ItemPrototype const *proto = m_CastItem->GetProto();
3253 if(!proto)
3255 // This code is to avoid a crash
3256 // I'm not sure, if this is really an error, but I guess every item needs a prototype
3257 sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3258 return;
3261 bool expendable = false;
3262 bool withoutCharges = false;
3264 for (int i = 0; i<5; i++)
3266 if (proto->Spells[i].SpellId)
3268 // item has limited charges
3269 if (proto->Spells[i].SpellCharges)
3271 if (proto->Spells[i].SpellCharges < 0)
3272 expendable = true;
3274 int32 charges = m_CastItem->GetSpellCharges(i);
3276 // item has charges left
3277 if (charges)
3279 (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
3280 if (proto->Stackable == 1)
3281 m_CastItem->SetSpellCharges(i, charges);
3282 m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3285 // all charges used
3286 withoutCharges = (charges == 0);
3291 if (expendable && withoutCharges)
3293 uint32 count = 1;
3294 ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3296 // prevent crash at access to deleted m_targets.getItemTarget
3297 if(m_CastItem==m_targets.getItemTarget())
3298 m_targets.setItemTarget(NULL);
3300 m_CastItem = NULL;
3304 void Spell::TakePower()
3306 if(m_CastItem || m_triggeredByAuraSpell)
3307 return;
3309 // health as power used
3310 if(m_spellInfo->powerType == POWER_HEALTH)
3312 m_caster->ModifyHealth( -(int32)m_powerCost );
3313 return;
3316 if(m_spellInfo->powerType >= MAX_POWERS)
3318 sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3319 return;
3322 Powers powerType = Powers(m_spellInfo->powerType);
3324 if(powerType == POWER_RUNE)
3326 TakeRunePower();
3327 return;
3330 m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3332 // Set the five second timer
3333 if (powerType == POWER_MANA && m_powerCost > 0)
3334 m_caster->SetLastManaUse(getMSTime());
3337 uint8 Spell::CheckRuneCost(uint32 runeCostID)
3339 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3340 return 0;
3342 Player *plr = (Player*)m_caster;
3344 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3345 return 0;
3347 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
3349 if(!src)
3350 return 0;
3352 if(src->NoRuneCost())
3353 return 0;
3355 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3357 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3359 runeCost[i] = src->RuneCost[i];
3362 runeCost[RUNE_DEATH] = 0; // calculated later
3364 for(uint32 i = 0; i < MAX_RUNES; ++i)
3366 uint8 rune = plr->GetCurrentRune(i);
3367 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3369 runeCost[rune]--;
3373 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3375 if(runeCost[i] > 0)
3377 runeCost[RUNE_DEATH] += runeCost[i];
3381 if(runeCost[RUNE_DEATH] > 0)
3382 return SPELL_FAILED_NO_POWER; // not sure if result code is correct
3384 return 0;
3387 void Spell::TakeRunePower()
3389 if(m_caster->GetTypeId() != TYPEID_PLAYER)
3390 return;
3392 Player *plr = (Player*)m_caster;
3394 if(plr->getClass() != CLASS_DEATH_KNIGHT)
3395 return;
3397 SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
3399 if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
3400 return;
3402 m_runesState = plr->GetRunesState(); // store previous state
3404 int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
3406 for(uint32 i = 0; i < RUNE_DEATH; ++i)
3408 runeCost[i] = src->RuneCost[i];
3411 runeCost[RUNE_DEATH] = 0; // calculated later
3413 for(uint32 i = 0; i < MAX_RUNES; ++i)
3415 uint8 rune = plr->GetCurrentRune(i);
3416 if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
3418 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3419 runeCost[rune]--;
3423 runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
3425 if(runeCost[RUNE_DEATH] > 0)
3427 for(uint32 i = 0; i < MAX_RUNES; ++i)
3429 uint8 rune = plr->GetCurrentRune(i);
3430 if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
3432 plr->SetRuneCooldown(i, RUNE_COOLDOWN); // 5*2=10 sec
3433 runeCost[rune]--;
3434 plr->ConvertRune(i, plr->GetBaseRune(i));
3435 if(runeCost[RUNE_DEATH] == 0)
3436 break;
3441 // you can gain some runic power when use runes
3442 float rp = src->runePowerGain;;
3443 rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
3444 plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
3447 void Spell::TakeReagents()
3449 if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
3450 return;
3452 if (m_caster->GetTypeId() != TYPEID_PLAYER)
3453 return;
3455 Player* p_caster = (Player*)m_caster;
3456 if (p_caster->CanNoReagentCast(m_spellInfo))
3457 return;
3459 for(uint32 x=0;x<8;x++)
3461 if(m_spellInfo->Reagent[x] <= 0)
3462 continue;
3464 uint32 itemid = m_spellInfo->Reagent[x];
3465 uint32 itemcount = m_spellInfo->ReagentCount[x];
3467 // if CastItem is also spell reagent
3468 if (m_CastItem)
3470 ItemPrototype const *proto = m_CastItem->GetProto();
3471 if( proto && proto->ItemId == itemid )
3473 for(int s=0;s<5;s++)
3475 // CastItem will be used up and does not count as reagent
3476 int32 charges = m_CastItem->GetSpellCharges(s);
3477 if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3479 ++itemcount;
3480 break;
3484 m_CastItem = NULL;
3488 // if getItemTarget is also spell reagent
3489 if (m_targets.getItemTargetEntry()==itemid)
3490 m_targets.setItemTarget(NULL);
3492 p_caster->DestroyItemCount(itemid, itemcount, true);
3496 void Spell::HandleThreatSpells(uint32 spellId)
3498 if(!m_targets.getUnitTarget() || !spellId)
3499 return;
3501 if(!m_targets.getUnitTarget()->CanHaveThreatList())
3502 return;
3504 SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3505 if(!threatSpell)
3506 return;
3508 m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3510 DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3513 void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3515 unitTarget = pUnitTarget;
3516 itemTarget = pItemTarget;
3517 gameObjTarget = pGOTarget;
3519 uint8 eff = m_spellInfo->Effect[i];
3521 damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3523 sLog.outDebug( "Spell: Effect : %u", eff);
3525 if(eff<TOTAL_SPELL_EFFECTS)
3527 //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3528 (*this.*SpellEffects[eff])(i);
3531 else
3533 sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3534 if (m_CastItem)
3535 EffectEnchantItemTmp(i);
3536 else
3538 sLog.outError("SPELL: unknown effect %u spell id %u\n",
3539 eff, m_spellInfo->Id);
3545 void Spell::TriggerSpell()
3547 for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3549 Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3550 spell->prepare(&m_targets); // use original spell original targets
3554 uint8 Spell::CanCast(bool strict)
3556 // check cooldowns to prevent cheating
3557 if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3559 if(m_triggeredByAuraSpell)
3560 return SPELL_FAILED_DONT_REPORT;
3561 else
3562 return SPELL_FAILED_NOT_READY;
3565 // only allow triggered spells if at an ended battleground
3566 if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3567 if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3568 if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3569 return SPELL_FAILED_DONT_REPORT;
3571 // only check at first call, Stealth auras are already removed at second call
3572 // for now, ignore triggered spells
3573 if( strict && !m_IsTriggeredSpell)
3575 bool checkForm = true;
3576 // Ignore form req aura
3577 Unit::AuraList const& ignore = m_caster->GetAurasByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
3578 for(Unit::AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
3580 if (!(*i)->isAffectedOnSpell(m_spellInfo))
3581 continue;
3582 checkForm = false;
3583 break;
3585 if (checkForm)
3587 // Cannot be used in this stance/form
3588 if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3589 return shapeError;
3591 if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3592 return SPELL_FAILED_ONLY_STEALTHED;
3596 // caster state requirements
3597 if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3598 return SPELL_FAILED_CASTER_AURASTATE;
3599 if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3600 return SPELL_FAILED_CASTER_AURASTATE;
3602 // Caster aura req check if need
3603 if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
3604 return SPELL_FAILED_CASTER_AURASTATE;
3605 if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
3606 return SPELL_FAILED_CASTER_AURASTATE;
3608 // cancel autorepeat spells if cast start when moving
3609 // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3610 if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3612 // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3613 if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3614 (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3615 return SPELL_FAILED_MOVING;
3618 Unit *target = m_targets.getUnitTarget();
3620 if(target)
3622 // target state requirements (not allowed state), apply to self also
3623 if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3624 return SPELL_FAILED_TARGET_AURASTATE;
3626 // Target aura req check if need
3627 if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
3628 return SPELL_FAILED_CASTER_AURASTATE;
3629 if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
3630 return SPELL_FAILED_CASTER_AURASTATE;
3632 if(target != m_caster)
3634 // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3635 if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3636 return SPELL_FAILED_TARGET_AURASTATE;
3638 // Not allow casting on flying player
3639 if (target->isInFlight())
3640 return SPELL_FAILED_BAD_TARGETS;
3642 if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3643 return SPELL_FAILED_LINE_OF_SIGHT;
3645 // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3646 // this case can be triggered if rank not found (too low-level target for first rank)
3647 if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3649 for(int i=0;i<3;i++)
3651 if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3652 if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3653 return SPELL_FAILED_LOWLEVEL;
3657 else if (m_caster->GetTypeId()==TYPEID_PLAYER) // Target - is player caster
3659 // Additional check for some spells
3660 // If 0 spell effect empty - client not send target data (need use selection)
3661 // TODO: check it on next client version
3662 if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
3663 m_spellInfo->Effect[0] == 0 && m_spellInfo->EffectImplicitTargetA[1] != TARGET_SELF)
3665 if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
3666 m_targets.setUnitTarget(target);
3667 else
3668 return SPELL_FAILED_BAD_TARGETS;
3672 // check pet presents
3673 for(int j=0;j<3;j++)
3675 if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3677 target = m_caster->GetPet();
3678 if(!target)
3680 if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
3681 return SPELL_FAILED_DONT_REPORT;