root/trunk/src/game/Spell.cpp @ 186

Revision 186, 196.5 kB (checked in by yumileroy, 17 years ago)

[svn] Remove isVisible function. Check stealth and invisible in canAttack();
Use new remove aura by interrupt flag function.

Original author: megamage
Date: 2008-11-07 09:36:46-06:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 */
20
21#include "Common.h"
22#include "Database/DatabaseEnv.h"
23#include "WorldPacket.h"
24#include "WorldSession.h"
25#include "GridNotifiers.h"
26#include "GridNotifiersImpl.h"
27#include "Opcodes.h"
28#include "Log.h"
29#include "UpdateMask.h"
30#include "World.h"
31#include "ObjectMgr.h"
32#include "SpellMgr.h"
33#include "Player.h"
34#include "Pet.h"
35#include "Unit.h"
36#include "Spell.h"
37#include "DynamicObject.h"
38#include "SpellAuras.h"
39#include "Group.h"
40#include "UpdateData.h"
41#include "MapManager.h"
42#include "ObjectAccessor.h"
43#include "CellImpl.h"
44#include "Policies/SingletonImp.h"
45#include "SharedDefines.h"
46#include "Tools.h"
47#include "LootMgr.h"
48#include "VMapFactory.h"
49#include "BattleGround.h"
50#include "Util.h"
51
52#define SPELL_CHANNEL_UPDATE_INTERVAL 1000
53
54extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
55
56bool IsQuestTameSpell(uint32 spellId)
57{
58    SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
59    if (!spellproto) return false;
60
61    return spellproto->Effect[0] == SPELL_EFFECT_THREAT
62        && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
63}
64
65SpellCastTargets::SpellCastTargets()
66{
67    m_unitTarget = NULL;
68    m_itemTarget = NULL;
69    m_GOTarget   = NULL;
70
71    m_unitTargetGUID   = 0;
72    m_GOTargetGUID     = 0;
73    m_CorpseTargetGUID = 0;
74    m_itemTargetGUID   = 0;
75    m_itemTargetEntry  = 0;
76
77    m_srcX = m_srcY = m_srcZ = m_destX = m_destY = m_destZ = 0;
78    m_hasDest = false;
79    m_strTarget = "";
80    m_targetMask = 0;
81}
82
83SpellCastTargets::~SpellCastTargets()
84{
85}
86
87void SpellCastTargets::setUnitTarget(Unit *target)
88{
89    if (!target)
90        return;
91
92    m_unitTarget = target;
93    m_unitTargetGUID = target->GetGUID();
94    m_targetMask |= TARGET_FLAG_UNIT;
95}
96
97void SpellCastTargets::setDestination(float x, float y, float z, bool send, int32 mapId)
98{
99    m_destX = x;
100    m_destY = y;
101    m_destZ = z;
102    m_hasDest = true;
103    if(send)
104        m_targetMask |= TARGET_FLAG_DEST_LOCATION;
105    if(mapId >= 0)
106        m_mapId = mapId;
107}
108
109void SpellCastTargets::setDestination(Unit *target, bool send)
110{
111    if(!target)
112        return;
113
114    m_destX = target->GetPositionX();
115    m_destY = target->GetPositionY();
116    m_destZ = target->GetPositionZ();
117    m_hasDest = true;
118    if(send)
119        m_targetMask |= TARGET_FLAG_DEST_LOCATION;
120}
121
122void SpellCastTargets::setGOTarget(GameObject *target)
123{
124    m_GOTarget = target;
125    m_GOTargetGUID = target->GetGUID();
126    //    m_targetMask |= TARGET_FLAG_OBJECT;
127}
128
129void SpellCastTargets::setItemTarget(Item* item)
130{
131    if(!item)
132        return;
133
134    m_itemTarget = item;
135    m_itemTargetGUID = item->GetGUID();
136    m_itemTargetEntry = item->GetEntry();
137    m_targetMask |= TARGET_FLAG_ITEM;
138}
139
140void SpellCastTargets::setCorpseTarget(Corpse* corpse)
141{
142    m_CorpseTargetGUID = corpse->GetGUID();
143}
144
145void SpellCastTargets::Update(Unit* caster)
146{
147    m_GOTarget   = m_GOTargetGUID ? ObjectAccessor::GetGameObject(*caster,m_GOTargetGUID) : NULL;
148    m_unitTarget = m_unitTargetGUID ?
149        ( m_unitTargetGUID==caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
150    NULL;
151
152    m_itemTarget = NULL;
153    if(caster->GetTypeId()==TYPEID_PLAYER)
154    {
155        if(m_targetMask & TARGET_FLAG_ITEM)
156            m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
157        else
158        {
159            Player* pTrader = ((Player*)caster)->GetTrader();
160            if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
161                m_itemTarget = pTrader->GetItemByPos(pTrader->GetItemPosByTradeSlot(m_itemTargetGUID));
162        }
163        if(m_itemTarget)
164            m_itemTargetEntry = m_itemTarget->GetEntry();
165    }
166}
167
168bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
169{
170    if(data->rpos()+4 > data->size())
171        return false;
172
173    *data >> m_targetMask;
174
175    if(m_targetMask == TARGET_FLAG_SELF)
176    {
177        //m_destX = caster->GetPositionX();
178        //m_destY = caster->GetPositionY();
179        //m_destZ = caster->GetPositionZ();
180        m_unitTarget = caster;
181        m_unitTargetGUID = caster->GetGUID();
182        return true;
183    }
184    // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
185    if( m_targetMask & (TARGET_FLAG_UNIT|TARGET_FLAG_UNK2) )
186        if(!readGUID(*data, m_unitTargetGUID))
187            return false;
188
189    if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ))
190        if(!readGUID(*data, m_GOTargetGUID))
191            return false;
192
193    if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
194        if(!readGUID(*data, m_itemTargetGUID))
195            return false;
196
197    /*if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
198    {
199        if(data->rpos()+4+4+4 > data->size())
200            return false;
201
202        *data >> m_srcX >> m_srcY >> m_srcZ;
203        if(!Trinity::IsValidMapCoord(m_srcX, m_srcY, m_srcZ))
204            return false;
205    }*/
206
207    if( m_targetMask & (TARGET_FLAG_SOURCE_LOCATION | TARGET_FLAG_DEST_LOCATION) )
208    {
209        if(data->rpos()+4+4+4 > data->size())
210            return false;
211
212        *data >> m_destX >> m_destY >> m_destZ;
213        m_hasDest = true;
214        if(!Trinity::IsValidMapCoord(m_destX, m_destY, m_destZ))
215            return false;
216    }
217
218    if( m_targetMask & TARGET_FLAG_STRING )
219    {
220        if(data->rpos()+1 > data->size())
221            return false;
222
223        *data >> m_strTarget;
224    }
225
226    if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
227        if(!readGUID(*data, m_CorpseTargetGUID))
228            return false;
229
230    // find real units/GOs
231    Update(caster);
232    return true;
233}
234
235void SpellCastTargets::write ( WorldPacket * data )
236{
237    *data << uint32(m_targetMask);
238
239    if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
240    {
241        if(m_targetMask & TARGET_FLAG_UNIT)
242        {
243            if(m_unitTarget)
244                data->append(m_unitTarget->GetPackGUID());
245            else
246                *data << uint8(0);
247        }
248        else if( m_targetMask & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK ) )
249        {
250            if(m_GOTarget)
251                data->append(m_GOTarget->GetPackGUID());
252            else
253                *data << uint8(0);
254        }
255        else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
256            data->appendPackGUID(m_CorpseTargetGUID);
257        else
258            *data << uint8(0);
259    }
260
261    if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
262    {
263        if(m_itemTarget)
264            data->append(m_itemTarget->GetPackGUID());
265        else
266            *data << uint8(0);
267    }
268
269    if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
270        *data << m_srcX << m_srcY << m_srcZ;
271
272    if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
273        *data << m_destX << m_destY << m_destZ;
274
275    if( m_targetMask & TARGET_FLAG_STRING )
276        *data << m_strTarget;
277}
278
279Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer )
280{
281    ASSERT( Caster != NULL && info != NULL );
282    ASSERT( info == sSpellStore.LookupEntry( info->Id ) && "`info` must be pointer to sSpellStore element");
283
284    m_spellInfo = info;
285    m_caster = Caster;
286    m_selfContainer = NULL;
287    m_triggeringContainer = triggeringContainer;
288    m_magnetPair.first = false;
289    m_magnetPair.second = NULL;
290    m_referencedFromCurrentSpell = false;
291    m_executedCurrently = false;
292    m_delayAtDamageCount = 0;
293
294    m_applyMultiplierMask = 0;
295
296    // Get data for type of attack
297    switch (m_spellInfo->DmgClass)
298    {
299        case SPELL_DAMAGE_CLASS_MELEE:
300            if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
301                m_attackType = OFF_ATTACK;
302            else
303                m_attackType = BASE_ATTACK;
304            break;
305        case SPELL_DAMAGE_CLASS_RANGED:
306            m_attackType = RANGED_ATTACK;
307            break;
308        default:
309                                                            // Wands
310            if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_WAND)
311                m_attackType = RANGED_ATTACK;
312            else
313                m_attackType = BASE_ATTACK;
314            break;
315    }
316
317    m_spellSchoolMask = GetSpellSchoolMask(info);           // Can be override for some spell (wand shoot for example)
318
319    if(m_attackType == RANGED_ATTACK)
320    {
321        // wand case
322        if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId()==TYPEID_PLAYER)
323        {
324            if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
325                m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage->DamageType);
326        }
327    }
328
329    if(originalCasterGUID)
330        m_originalCasterGUID = originalCasterGUID;
331    else
332        m_originalCasterGUID = m_caster->GetGUID();
333
334    if(m_originalCasterGUID==m_caster->GetGUID())
335        m_originalCaster = m_caster;
336    else
337    {
338        m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
339        if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
340    }
341
342    for(int i=0; i <3; ++i)
343        m_currentBasePoints[i] = m_spellInfo->EffectBasePoints[i];
344
345    m_spellState = SPELL_STATE_NULL;
346
347    m_castPositionX = m_castPositionY = m_castPositionZ = 0;
348    m_TriggerSpells.clear();
349    m_IsTriggeredSpell = triggered;
350    //m_AreaAura = false;
351    m_CastItem = NULL;
352
353    unitTarget = NULL;
354    itemTarget = NULL;
355    gameObjTarget = NULL;
356    focusObject = NULL;
357    m_cast_count = 0;
358    m_triggeredByAuraSpell  = NULL;
359
360    //Auto Shot & Shoot
361    if( m_spellInfo->AttributesEx2 == 0x000020 && !triggered )
362        m_autoRepeat = true;
363    else
364        m_autoRepeat = false;
365
366    m_powerCost = 0;                                        // setup to correct value in Spell::prepare, don't must be used before.
367    m_casttime = 0;                                         // setup to correct value in Spell::prepare, don't must be used before.
368    m_timer = 0;                                            // will set to castime in preper
369
370    m_needAliveTargetMask = 0;
371
372    // determine reflection
373    m_canReflect = false;
374
375    if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && (m_spellInfo->AttributesEx2 & 0x4)==0)
376    {
377        for(int j=0;j<3;j++)
378        {
379            if (m_spellInfo->Effect[j]==0)
380                continue;
381
382            if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j],m_spellInfo->EffectImplicitTargetB[j]))
383                m_canReflect = true;
384            else
385                m_canReflect = (m_spellInfo->AttributesEx & (1<<7)) ? true : false;
386
387            if(m_canReflect)
388                continue;
389            else
390                break;
391        }
392    }
393
394    CleanupTargetList();
395}
396
397Spell::~Spell()
398{
399}
400
401void Spell::FillTargetMap()
402{
403    // TODO: ADD the correct target FILLS!!!!!!
404
405    for(uint32 i=0;i<3;i++)
406    {
407        // not call for empty effect.
408        // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
409        if(m_spellInfo->Effect[i]==0)
410            continue;
411
412        // TODO: find a way so this is not needed?
413        // for area auras always add caster as target (needed for totems for example)
414        if(IsAreaAuraEffect(m_spellInfo->Effect[i]))
415            AddUnitTarget(m_caster, i);
416
417        std::list<Unit*> tmpUnitMap;
418
419        SetTargetMap(i,m_spellInfo->EffectImplicitTargetA[i],tmpUnitMap);
420        SetTargetMap(i,m_spellInfo->EffectImplicitTargetB[i],tmpUnitMap);
421
422        if(m_targets.HasDest())
423        {
424            switch(m_spellInfo->Effect[i])
425            {
426                case SPELL_EFFECT_SUMMON:
427                case SPELL_EFFECT_SUMMON_WILD:
428                case SPELL_EFFECT_SUMMON_GUARDIAN:
429                case SPELL_EFFECT_TRANS_DOOR: //summon object
430                case SPELL_EFFECT_SUMMON_PET:
431                case SPELL_EFFECT_SUMMON_POSSESSED:
432                case SPELL_EFFECT_SUMMON_TOTEM:
433                case SPELL_EFFECT_SUMMON_OBJECT_WILD:
434                case SPELL_EFFECT_SUMMON_TOTEM_SLOT1:
435                case SPELL_EFFECT_SUMMON_TOTEM_SLOT2:
436                case SPELL_EFFECT_SUMMON_TOTEM_SLOT3:
437                case SPELL_EFFECT_SUMMON_TOTEM_SLOT4:
438                case SPELL_EFFECT_SUMMON_CRITTER:
439                case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
440                case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
441                case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
442                case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
443                case SPELL_EFFECT_SUMMON_DEAD_PET:
444                case SPELL_EFFECT_SUMMON_DEMON:
445                case SPELL_EFFECT_ADD_FARSIGHT:
446                case SPELL_EFFECT_TRIGGER_SPELL_2: //ritual of summon
447                {
448                    tmpUnitMap.clear();
449                    tmpUnitMap.push_back(m_caster);
450                    break;
451                }
452            }
453        }
454
455        if(!m_spellInfo->EffectImplicitTargetA[i])
456        {
457            switch(m_spellInfo->Effect[i])
458            {
459                case SPELL_EFFECT_PARRY:
460                case SPELL_EFFECT_BLOCK:
461                case SPELL_EFFECT_SKILL: // always with dummy 3 as A
462                case SPELL_EFFECT_LEARN_SPELL:
463                    tmpUnitMap.push_back(m_caster);
464                    break;
465            }
466        }
467
468        if(tmpUnitMap.empty())
469        {
470            /*if( m_spellInfo->EffectImplicitTargetA[i]==TARGET_SCRIPT ||
471                m_spellInfo->EffectImplicitTargetB[i]==TARGET_SCRIPT ||
472                m_spellInfo->EffectImplicitTargetA[i]==TARGET_SCRIPT_COORDINATES ||
473                m_spellInfo->EffectImplicitTargetB[i]==TARGET_SCRIPT_COORDINATES )
474            {
475                if(!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION))
476                    continue;
477            }*/
478
479            // add here custom effects that need default target.
480            // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
481            switch(m_spellInfo->Effect[i])
482            {
483                case SPELL_EFFECT_DUMMY:
484                {
485                    switch(m_spellInfo->Id)
486                    {
487                        case 20577:                         // Cannibalize
488                        {
489                            // non-standard target selection
490                            SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
491                            float max_range = GetSpellMaxRange(srange);
492
493                            CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
494                            Cell cell(p);
495                            cell.data.Part.reserved = ALL_DISTRICT;
496                            cell.SetNoCreate();
497
498                            WorldObject* result = NULL;
499
500                            Trinity::CannibalizeObjectCheck u_check(m_caster, max_range);
501                            Trinity::WorldObjectSearcher<Trinity::CannibalizeObjectCheck > searcher(result, u_check);
502
503                            TypeContainerVisitor<Trinity::WorldObjectSearcher<Trinity::CannibalizeObjectCheck >, GridTypeMapContainer > grid_searcher(searcher);
504                            CellLock<GridReadGuard> cell_lock(cell, p);
505                            cell_lock->Visit(cell_lock, grid_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
506
507                            if(!result)
508                            {
509                                TypeContainerVisitor<Trinity::WorldObjectSearcher<Trinity::CannibalizeObjectCheck >, WorldTypeMapContainer > world_searcher(searcher);
510                                cell_lock->Visit(cell_lock, world_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
511                            }
512
513                            if(result)
514                            {
515                                switch(result->GetTypeId())
516                                {
517                                    case TYPEID_UNIT:
518                                    case TYPEID_PLAYER:
519                                        tmpUnitMap.push_back((Unit*)result);
520                                        break;
521                                    case TYPEID_CORPSE:
522                                        m_targets.setCorpseTarget((Corpse*)result);
523                                        if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
524                                            tmpUnitMap.push_back(owner);
525                                        break;
526                                }
527                            }
528                            else
529                            {
530                                // clear cooldown at fail
531                                if(m_caster->GetTypeId()==TYPEID_PLAYER)
532                                {
533                                    ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id);
534
535                                    WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
536                                    data << uint32(m_spellInfo->Id);
537                                    data << uint64(m_caster->GetGUID());
538                                    ((Player*)m_caster)->GetSession()->SendPacket(&data);
539                                }
540
541                                SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
542                                finish(false);
543                            }
544                            break;
545                        }
546                        default:
547                            if(m_targets.getUnitTarget())
548                                tmpUnitMap.push_back(m_targets.getUnitTarget());
549                            break;
550                    }
551                    break;
552                }
553                case SPELL_EFFECT_RESURRECT:
554                case SPELL_EFFECT_CREATE_ITEM:
555                case SPELL_EFFECT_TRIGGER_SPELL:
556                case SPELL_EFFECT_TRIGGER_MISSILE:
557                case SPELL_EFFECT_SKILL_STEP:
558                case SPELL_EFFECT_PROFICIENCY:
559                case SPELL_EFFECT_SELF_RESURRECT:
560                case SPELL_EFFECT_REPUTATION:
561                    if(m_targets.getUnitTarget())
562                        tmpUnitMap.push_back(m_targets.getUnitTarget());
563                    break;
564                case SPELL_EFFECT_SUMMON_PLAYER:
565                    if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
566                    {
567                        Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
568                        if(target)
569                            tmpUnitMap.push_back(target);
570                    }
571                    break;
572                case SPELL_EFFECT_RESURRECT_NEW:
573                    if(m_targets.getUnitTarget())
574                        tmpUnitMap.push_back(m_targets.getUnitTarget());
575                    if(m_targets.getCorpseTargetGUID())
576                    {
577                        Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
578                        if(corpse)
579                        {
580                            Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
581                            if(owner)
582                                tmpUnitMap.push_back(owner);
583                        }
584                    }
585                    break;
586                case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
587                case SPELL_EFFECT_ADD_FARSIGHT:
588                case SPELL_EFFECT_STUCK:
589                case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
590                    tmpUnitMap.push_back(m_caster);
591                    break;
592                case SPELL_EFFECT_LEARN_PET_SPELL:
593                    if(Pet* pet = m_caster->GetPet())
594                        tmpUnitMap.push_back(pet);
595                    break;
596                case SPELL_EFFECT_ENCHANT_ITEM:
597                case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
598                case SPELL_EFFECT_DISENCHANT:
599                case SPELL_EFFECT_FEED_PET:
600                case SPELL_EFFECT_PROSPECTING:
601                    if(m_targets.getItemTarget())
602                        AddItemTarget(m_targets.getItemTarget(), i);
603                    break;
604                case SPELL_EFFECT_APPLY_AURA:
605                    switch(m_spellInfo->EffectApplyAuraName[i])
606                    {
607                        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)
608                        case SPELL_AURA_ADD_PCT_MODIFIER:
609                            tmpUnitMap.push_back(m_caster);
610                            break;
611                        default:                            // apply to target in other case
612                            break;
613                    }
614                    break;
615                case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
616                                                            // AreaAura
617                    if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
618                        SetTargetMap(i,TARGET_AREAEFFECT_PARTY,tmpUnitMap);
619                    break;
620                case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
621                    if(m_targets.getUnitTarget())
622                    {
623                        tmpUnitMap.push_back(m_targets.getUnitTarget());
624                    }
625                    else if (m_targets.getCorpseTargetGUID())
626                    {
627                        Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
628                        if(corpse)
629                        {
630                            Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
631                            if(owner)
632                                tmpUnitMap.push_back(owner);
633                        }
634                    }
635                    break;
636                default:
637                    break;
638            }
639        }
640        if(IsChanneledSpell(m_spellInfo) && !tmpUnitMap.empty())
641            m_needAliveTargetMask  |= (1<<i);
642
643        if(m_caster->GetTypeId() == TYPEID_PLAYER)
644        {
645            Player *me = (Player*)m_caster;
646            for (std::list<Unit*>::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); itr++)
647            {
648                Unit *owner = (*itr)->GetOwner();
649                Unit *u = owner ? owner : (*itr);
650                if(u!=m_caster && u->IsPvP() && (!me->duel || me->duel->opponent != u))
651                {
652                    me->UpdatePvP(true);
653                    me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
654                    break;
655                }
656            }
657        }
658
659        for (std::list<Unit*>::iterator itr = tmpUnitMap.begin() ; itr != tmpUnitMap.end();)
660        {
661            if(!CheckTarget(*itr, i, false ))
662            {
663                itr = tmpUnitMap.erase(itr);
664                continue;
665            }
666            else
667                ++itr;
668        }
669
670        for(std::list<Unit*>::iterator iunit= tmpUnitMap.begin();iunit != tmpUnitMap.end();++iunit)
671            AddUnitTarget((*iunit), i);
672    }
673}
674
675void Spell::CleanupTargetList()
676{
677    m_UniqueTargetInfo.clear();
678    m_UniqueGOTargetInfo.clear();
679    m_UniqueItemInfo.clear();
680    m_countOfHit = 0;
681    m_countOfMiss = 0;
682    m_delayMoment = 0;
683}
684
685void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
686{
687    if( m_spellInfo->Effect[effIndex]==0 )
688        return;
689
690    uint64 targetGUID = pVictim->GetGUID();
691
692    // Lookup target in already in list
693    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
694    {
695        if (targetGUID == ihit->targetGUID)                 // Found in list
696        {
697            ihit->effectMask |= 1<<effIndex;                // Add only effect mask
698            return;
699        }
700    }
701
702    // This is new target calculate data for him
703
704    // Get spell hit result on target
705    TargetInfo target;
706    target.targetGUID = targetGUID;                         // Store target GUID
707    target.effectMask = 1<<effIndex;                        // Store index of effect
708    target.processed  = false;                              // Effects not apply on target
709
710    // Calculate hit result
711    if(m_originalCaster)
712        target.missCondition = m_originalCaster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
713    else
714        target.missCondition = SPELL_MISS_NONE;
715    if (target.missCondition == SPELL_MISS_NONE)
716        ++m_countOfHit;
717    else
718        ++m_countOfMiss;
719
720    // Spell have speed - need calculate incoming time
721    if (m_spellInfo->speed > 0.0f)
722    {
723        // calculate spell incoming interval
724        float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
725        if (dist < 5.0f) dist = 5.0f;
726        target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
727
728        // Calculate minimum incoming time
729        if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
730            m_delayMoment = target.timeDelay;
731    }
732    else
733        target.timeDelay = 0LL;
734
735    // If target reflect spell back to caster
736    if (target.missCondition==SPELL_MISS_REFLECT)
737    {
738        // Calculate reflected spell result on caster
739        target.reflectResult =  m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
740
741        if (target.reflectResult == SPELL_MISS_REFLECT)     // Impossible reflect again, so simply deflect spell
742            target.reflectResult = SPELL_MISS_PARRY;
743
744        // Increase time interval for reflected spells by 1.5
745        target.timeDelay+=target.timeDelay>>1;
746    }
747    else
748        target.reflectResult = SPELL_MISS_NONE;
749
750    // Add target to list
751    m_UniqueTargetInfo.push_back(target);
752}
753
754void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
755{
756    Unit* unit = m_caster->GetGUID()==unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID);
757    if (unit)
758        AddUnitTarget(unit, effIndex);
759}
760
761void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
762{
763    if( m_spellInfo->Effect[effIndex]==0 )
764        return;
765
766    uint64 targetGUID = pVictim->GetGUID();
767
768    // Lookup target in already in list
769    for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
770    {
771        if (targetGUID == ihit->targetGUID)                 // Found in list
772        {
773            ihit->effectMask |= 1<<effIndex;                // Add only effect mask
774            return;
775        }
776    }
777
778    // This is new target calculate data for him
779
780    GOTargetInfo target;
781    target.targetGUID = targetGUID;
782    target.effectMask = 1<<effIndex;
783    target.processed  = false;                              // Effects not apply on target
784
785    // Spell have speed - need calculate incoming time
786    if (m_spellInfo->speed > 0.0f)
787    {
788        // calculate spell incoming interval
789        float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
790        if (dist < 5.0f) dist = 5.0f;
791        target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
792        if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
793            m_delayMoment = target.timeDelay;
794    }
795    else
796        target.timeDelay = 0LL;
797
798    ++m_countOfHit;
799
800    // Add target to list
801    m_UniqueGOTargetInfo.push_back(target);
802}
803
804void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
805{
806    GameObject* go = ObjectAccessor::GetGameObject(*m_caster, goGUID);
807    if (go)
808        AddGOTarget(go, effIndex);
809}
810
811void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
812{
813    if( m_spellInfo->Effect[effIndex]==0 )
814        return;
815
816    // Lookup target in already in list
817    for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
818    {
819        if (pitem == ihit->item)                            // Found in list
820        {
821            ihit->effectMask |= 1<<effIndex;                // Add only effect mask
822            return;
823        }
824    }
825
826    // This is new target add data
827
828    ItemTargetInfo target;
829    target.item       = pitem;
830    target.effectMask = 1<<effIndex;
831    m_UniqueItemInfo.push_back(target);
832}
833
834void Spell::doTriggers(SpellMissInfo missInfo, uint32 damage, SpellSchoolMask damageSchoolMask, uint32 block, uint32 absorb, bool crit)
835{
836    // Do triggers depends from hit result (triggers on hit do in effects)
837    // Set aura states depends from hit result
838    if (missInfo!=SPELL_MISS_NONE)
839    {
840        // Miss/dodge/parry/block only for melee based spells
841        // Resist only for magic based spells
842        switch (missInfo)
843        {
844            case SPELL_MISS_MISS:
845                if(m_caster->GetTypeId()== TYPEID_PLAYER)
846                    ((Player*)m_caster)->UpdateWeaponSkill(BASE_ATTACK);
847
848                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_MISS, m_spellInfo, m_IsTriggeredSpell);
849                break;
850            case SPELL_MISS_RESIST:
851                m_caster->ProcDamageAndSpell(unitTarget, PROC_FLAG_TARGET_RESISTS, PROC_FLAG_RESIST_SPELL, 0, damageSchoolMask, m_spellInfo, m_IsTriggeredSpell);
852                break;
853            case SPELL_MISS_DODGE:
854                if(unitTarget->GetTypeId() == TYPEID_PLAYER)
855                    ((Player*)unitTarget)->UpdateDefense();
856
857                // Overpower
858                if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARRIOR)
859                {
860                    ((Player*) m_caster)->AddComboPoints(unitTarget, 1);
861                    m_caster->StartReactiveTimer( REACTIVE_OVERPOWER );
862                }
863
864                // Riposte
865                if (unitTarget->getClass() != CLASS_ROGUE)
866                {
867                    unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
868                    unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
869                }
870
871                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_DODGE, m_spellInfo, m_IsTriggeredSpell);
872                break;
873            case SPELL_MISS_PARRY:
874                // Update victim defense ?
875                if(unitTarget->GetTypeId() == TYPEID_PLAYER)
876                    ((Player*)unitTarget)->UpdateDefense();
877                // Mongoose bite - set only Counterattack here
878                if (unitTarget->getClass() == CLASS_HUNTER)
879                {
880                    unitTarget->ModifyAuraState(AURA_STATE_HUNTER_PARRY,true);
881                    unitTarget->StartReactiveTimer( REACTIVE_HUNTER_PARRY );
882                }
883                else
884                {
885                    unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
886                    unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
887                }
888                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_PARRY, m_spellInfo, m_IsTriggeredSpell);
889                break;
890            case SPELL_MISS_BLOCK:
891                unitTarget->ModifyAuraState(AURA_STATE_DEFENSE, true);
892                unitTarget->StartReactiveTimer( REACTIVE_DEFENSE );
893
894                m_caster->CastMeleeProcDamageAndSpell(unitTarget, 0, damageSchoolMask, m_attackType, MELEE_HIT_BLOCK, m_spellInfo, m_IsTriggeredSpell);
895                break;
896                // Trigger from this events not supported
897            case SPELL_MISS_EVADE:
898            case SPELL_MISS_IMMUNE:
899            case SPELL_MISS_IMMUNE2:
900            case SPELL_MISS_DEFLECT:
901            case SPELL_MISS_ABSORB:
902                // Trigger from reflects need do after get reflect result
903            case SPELL_MISS_REFLECT:
904                break;
905            default:
906                break;
907        }
908    }
909}
910
911void Spell::DoAllEffectOnTarget(TargetInfo *target)
912{
913    if (target->processed)                                  // Check target
914        return;
915    target->processed = true;                               // Target checked in apply effects procedure
916
917    // Get mask of effects for target
918    uint32 mask = target->effectMask;
919    if (mask == 0)                                          // No effects
920        return;
921
922    Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
923    if (!unit)
924        return;
925
926    SpellMissInfo missInfo = target->missCondition;
927    // Need init unitTarget by default unit (can changed in code on reflect)
928    // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
929    unitTarget = unit;
930
931    if (missInfo==SPELL_MISS_NONE)                          // In case spell hit target, do all effect on that target
932        DoSpellHitOnUnit(unit, mask);
933    else if (missInfo == SPELL_MISS_REFLECT)                // In case spell reflect from target, do all effect on caster (if hit)
934    {
935        if (target->reflectResult == SPELL_MISS_NONE)       // If reflected spell hit caster -> do all effect on him
936            DoSpellHitOnUnit(m_caster, mask);
937    }
938
939    // Do triggers only on miss/resist/parry/dodge
940    if (missInfo!=SPELL_MISS_NONE)
941        doTriggers(missInfo);
942
943    // Call scripted function for AI if this spell is casted upon a creature (except pets)
944    if(IS_CREATURE_GUID(target->targetGUID))
945    {
946        // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
947        // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
948        if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
949            ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
950    }
951
952    if( !m_caster->IsFriendlyTo(unit) && !IsPositiveSpell(m_spellInfo->Id))
953    {
954        if( !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
955        {
956            if(!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED))
957                unit->SetStandState(PLAYER_STATE_NONE);
958
959            if(!unit->isInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI())
960                ((Creature*)unit)->AI()->AttackStart(m_caster);
961
962            unit->SetInCombatWith(m_caster);
963            m_caster->SetInCombatWith(unit);
964
965            if(Player *attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself())
966                m_caster->SetContestedPvP(attackedPlayer);
967        }
968    }
969}
970
971void Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask)
972{
973    if(!unit || !effectMask)
974        return;
975
976    // remove spell_magnet aura after first spell redirect and destroy target if its totem
977    if(m_magnetPair.first && m_magnetPair.second && m_magnetPair.second == unit)
978    {
979        if(unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->isTotem())
980            unit->DealDamage(unit,unit->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
981        return;
982    }
983
984    // Recheck immune (only for delayed spells)
985    if( m_spellInfo->speed && 
986        !(m_spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
987        && (unit->IsImmunedToDamage(GetSpellSchoolMask(m_spellInfo),true) ||
988        unit->IsImmunedToSpell(m_spellInfo,true) ))
989    {
990        m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE);
991        return;
992    }
993
994    if( m_caster != unit )
995    {
996        if( !m_caster->IsFriendlyTo(unit) )
997        {
998            // for delayed spells ignore not visible explicit target
999            if(m_spellInfo->speed > 0.0f && unit==m_targets.getUnitTarget() && !unit->isVisibleForOrDetect(m_caster,false))
1000            {
1001                m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1002                return;
1003            }
1004
1005            //if(!IsPositiveSpell(m_spellInfo->Id))
1006            {
1007                //do not remove feign death
1008                unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_STEALTH + AURA_INTERRUPT_FLAG_DAMAGE);
1009            }
1010        }
1011        else
1012        {
1013            // for delayed spells ignore negative spells (after duel end) for friendly targets
1014            // TODO: this cause soul transfer bugged
1015            if(m_spellInfo->speed > 0.0f && !IsPositiveSpell(m_spellInfo->Id))
1016            {
1017                m_caster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_EVADE);
1018                return;
1019            }
1020
1021            // assisting case, healing and resurrection
1022            if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
1023                m_caster->SetContestedPvP();
1024            if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
1025            {
1026                m_caster->SetInCombatState(unit->GetCombatTimer() > 0);
1027                unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
1028            }
1029        }
1030    }
1031
1032    // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
1033    m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell);
1034    m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
1035    // Increase Diminishing on unit, current informations for actually casts will use values above
1036    if((GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(m_diminishGroup) == DRTYPE_ALL)
1037        unit->IncrDiminishing(m_diminishGroup);
1038
1039    for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1040    {
1041        if (effectMask & (1<<effectNumber))
1042        {
1043            HandleEffects(unit,NULL,NULL,effectNumber,m_damageMultipliers[effectNumber]);
1044            if ( m_applyMultiplierMask & (1 << effectNumber) )
1045            {
1046                // Get multiplier
1047                float multiplier = m_spellInfo->DmgMultiplier[effectNumber];
1048                // Apply multiplier mods
1049                if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1050                    modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier,this);
1051                m_damageMultipliers[effectNumber] *= multiplier;
1052            }
1053        }
1054    }
1055
1056    if(unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->AI())
1057        ((Creature*)unit)->AI()->SpellHit(m_caster, m_spellInfo);
1058
1059    if(m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI())
1060        ((Creature*)m_caster)->AI()->SpellHitTarget(unit, m_spellInfo);
1061
1062    if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id + 1000000))
1063    {
1064        for(std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
1065        {
1066            if(spell_triggered < 0)
1067                unit->RemoveAurasDueToSpell(-(*i));
1068            else
1069                unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID());
1070        }
1071    }
1072}
1073
1074void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
1075{
1076    if (target->processed)                                  // Check target
1077        return;
1078    target->processed = true;                               // Target checked in apply effects procedure
1079
1080    uint32 effectMask = target->effectMask;
1081    if(!effectMask)
1082        return;
1083
1084    GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
1085    if(!go)
1086        return;
1087
1088    for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1089        if (effectMask & (1<<effectNumber))
1090            HandleEffects(NULL,NULL,go,effectNumber);
1091
1092    // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
1093    // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
1094    if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
1095        ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
1096}
1097
1098void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
1099{
1100    uint32 effectMask = target->effectMask;
1101    if(!target->item || !effectMask)
1102        return;
1103
1104    for(uint32 effectNumber=0;effectNumber<3;effectNumber++)
1105        if (effectMask & (1<<effectNumber))
1106            HandleEffects(NULL, target->item, NULL, effectNumber);
1107}
1108
1109bool Spell::IsAliveUnitPresentInTargetList()
1110{
1111    // Not need check return true
1112    if (m_needAliveTargetMask == 0)
1113        return true;
1114
1115    uint8 needAliveTargetMask = m_needAliveTargetMask;
1116
1117    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
1118    {
1119        if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
1120        {
1121            Unit *unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
1122
1123            if (unit && unit->isAlive())
1124                needAliveTargetMask &= ~ihit->effectMask;   // remove from need alive mask effect that have alive target
1125        }
1126    }
1127
1128    // is all effects from m_needAliveTargetMask have alive targets
1129    return needAliveTargetMask==0;
1130}
1131
1132// Helper for Chain Healing
1133// Spell target first
1134// Raidmates then descending by injury suffered (MaxHealth - Health)
1135// Other players/mobs then descending by injury suffered (MaxHealth - Health)
1136struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
1137{
1138    const Unit* MainTarget;
1139    ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
1140    // functor for operator ">"
1141    bool operator()(Unit const* _Left, Unit const* _Right) const
1142    {
1143        return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
1144    }
1145    int32 ChainHealingHash(Unit const* Target) const
1146    {
1147        if (Target == MainTarget)
1148            return 0;
1149        else if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
1150            ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
1151        {
1152            if (Target->GetHealth() == Target->GetMaxHealth())
1153                return 40000;
1154            else
1155                return 20000 - Target->GetMaxHealth() + Target->GetHealth();
1156        }
1157        else
1158            return 40000 - Target->GetMaxHealth() + Target->GetHealth();
1159    }
1160};
1161
1162class ChainHealingFullHealth: std::unary_function<const Unit*, bool>
1163{
1164    public:
1165        const Unit* MainTarget;
1166        ChainHealingFullHealth(const Unit* Target) : MainTarget(Target) {};
1167
1168        bool operator()(const Unit* Target)
1169        {
1170            return (Target != MainTarget && Target->GetHealth() == Target->GetMaxHealth());
1171        }
1172};
1173
1174// Helper for targets nearest to the spell target
1175// The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
1176struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
1177{
1178    const Unit* MainTarget;
1179    TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
1180    // functor for operator ">"
1181    bool operator()(const Unit* _Left, const Unit* _Right) const
1182    {
1183        return (MainTarget->GetDistance(_Left) < MainTarget->GetDistance(_Right));
1184    }
1185};
1186
1187void Spell::SearchChainTarget(std::list<Unit*> &TagUnitMap, Unit* pUnitTarget, float max_range, uint32 unMaxTargets)
1188{
1189    if(!pUnitTarget)
1190        return;
1191
1192    //FIXME: This very like horrible hack and wrong for most spells
1193    if(m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE)
1194        max_range += unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1195
1196    CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1197    Cell cell(p);
1198    cell.data.Part.reserved = ALL_DISTRICT;
1199    cell.SetNoCreate();
1200
1201    std::list<Unit *> tempUnitMap;
1202
1203    {
1204        Trinity::AnyAoETargetUnitInObjectRangeCheck u_check(pUnitTarget, m_caster, max_range);
1205        Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck> searcher(tempUnitMap, u_check);
1206
1207        TypeContainerVisitor<Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1208        TypeContainerVisitor<Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1209
1210        CellLock<GridReadGuard> cell_lock(cell, p);
1211        cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1212        cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1213    }
1214
1215    tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1216
1217    if(tempUnitMap.empty())
1218        return;
1219
1220    uint32 t = unMaxTargets;
1221    if(pUnitTarget != m_caster)
1222    {
1223        if(*tempUnitMap.begin() == pUnitTarget)
1224            tempUnitMap.erase(tempUnitMap.begin());
1225        TagUnitMap.push_back(pUnitTarget);
1226        --t;
1227    }
1228    Unit *prev = pUnitTarget;
1229
1230    std::list<Unit*>::iterator next = tempUnitMap.begin();
1231
1232    while(t && next != tempUnitMap.end())
1233    {
1234        if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1235            break;
1236
1237        if(!prev->IsWithinLOSInMap(*next)
1238            || m_spellInfo->DmgClass==SPELL_DAMAGE_CLASS_MELEE && !m_caster->isInFront(*next, max_range))
1239        {
1240            ++next;
1241            continue;
1242        }
1243
1244        prev = *next;
1245        TagUnitMap.push_back(prev);
1246        tempUnitMap.erase(next);
1247        tempUnitMap.sort(TargetDistanceOrder(prev));
1248        next = tempUnitMap.begin();
1249        --t;
1250    }
1251}
1252
1253void Spell::SearchAreaTarget(std::list<Unit*> &TagUnitMap, float radius, const uint32 &type, SpellTargets TargetType, uint32 entry)
1254{
1255    float x, y;
1256    if(type == PUSH_DEST_CENTER)
1257    {
1258        if(!m_targets.HasDest())
1259        {
1260            sLog.outError( "SPELL: cannot find destination for spell ID %u\n", m_spellInfo->Id );
1261            return;
1262        }
1263        x = m_targets.m_destX;
1264        y = m_targets.m_destY;
1265    }
1266    else
1267    {
1268        x = m_caster->GetPositionX();
1269        y = m_caster->GetPositionY();
1270    }
1271
1272    CellPair p(Trinity::ComputeCellPair(x, y));
1273    Cell cell(p);
1274    cell.data.Part.reserved = ALL_DISTRICT;
1275    cell.SetNoCreate();
1276    CellLock<GridReadGuard> cell_lock(cell, p);
1277
1278    Trinity::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, type, TargetType, entry);
1279   
1280    if(TargetType != SPELL_TARGETS_ENTRY)
1281    {
1282        TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1283        cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1284    }
1285    if(!spellmgr.GetSpellExtraAttr(m_spellInfo->Id, SPELL_EXTRA_ATTR_MAX_TARGETS))
1286    {
1287        TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, GridTypeMapContainer >  grid_object_notifier(notifier);
1288        cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1289    }
1290}
1291
1292Unit* Spell::SearchNearbyTarget(float radius, SpellTargets TargetType, uint32 entry)
1293{
1294    CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1295    Cell cell(p);
1296    cell.data.Part.reserved = ALL_DISTRICT;
1297    cell.SetNoCreate();
1298    CellLock<GridReadGuard> cell_lock(cell, p);
1299
1300    Unit* target = NULL;
1301    switch(TargetType)
1302    {
1303        case SPELL_TARGETS_ENTRY:
1304        {
1305            Creature* target = NULL;
1306            Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster, entry, true, radius);
1307            Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(target, u_check);
1308            TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1309            cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1310            return target;
1311        }break;
1312        default:
1313        case SPELL_TARGETS_AOE_DAMAGE:
1314        {
1315            Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, radius);
1316            Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(target, u_check);
1317            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1318            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1319            cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1320            cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1321        }break;
1322        case SPELL_TARGETS_FRIENDLY:
1323        {
1324            Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, radius);
1325            Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(target, u_check);
1326            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
1327            TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
1328            cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1329            cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1330        }break;
1331    }
1332    return target;
1333}
1334
1335void Spell::SetTargetMap(uint32 i,uint32 cur,std::list<Unit*> &TagUnitMap)
1336{
1337    float radius;
1338    if (m_spellInfo->EffectRadiusIndex[i])
1339        radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1340    else
1341        radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex));
1342
1343    uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[i];
1344    uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
1345    if(!unMaxTargets)
1346        unMaxTargets = spellmgr.GetSpellExtraAttr(m_spellInfo->Id, SPELL_EXTRA_ATTR_MAX_TARGETS);
1347    if(m_originalCaster)
1348    {
1349        if(Player* modOwner = m_originalCaster->GetSpellModOwner())
1350        {
1351            modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius,this);
1352            modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
1353        }
1354    }
1355
1356    switch(cur)
1357    {
1358        // specific unit
1359        case TARGET_SELF:
1360        case TARGET_SELF_FISHING:
1361        {
1362            TagUnitMap.push_back(m_caster);
1363        }break;
1364        case TARGET_MASTER:
1365        {
1366            if(Unit* owner = m_caster->GetCharmerOrOwner())
1367                TagUnitMap.push_back(owner);
1368        }break;
1369        case TARGET_PET:
1370        {
1371            if(Pet* tmpUnit = m_caster->GetPet())
1372                TagUnitMap.push_back(tmpUnit);
1373        }break;
1374        case TARGET_NONCOMBAT_PET:
1375        {
1376            if(Unit* target = m_targets.getUnitTarget())
1377                if( target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->isPet() && ((Pet*)target)->getPetType() == MINI_PET)
1378                    TagUnitMap.push_back(target);
1379        }break;
1380        case TARGET_SINGLE_FRIEND: // ally
1381        case TARGET_SINGLE_FRIEND_2: // raid member
1382        case TARGET_DUELVSPLAYER: // all (SelectMagnetTarget()?)
1383        case TARGET_UNIT_SINGLE_UNKNOWN:
1384        {
1385            if(m_targets.getUnitTarget())
1386                TagUnitMap.push_back(m_targets.getUnitTarget());
1387        }break;
1388        case TARGET_CHAIN_DAMAGE:
1389        {
1390            if(Unit* pUnitTarget = SelectMagnetTarget())
1391            {
1392                if(EffectChainTarget <= 1)
1393                    TagUnitMap.push_back(pUnitTarget);
1394                else //TODO: chain target should also use magnet target
1395                    SearchChainTarget(TagUnitMap, pUnitTarget, radius, EffectChainTarget);
1396            }
1397        }break;
1398        case TARGET_GAMEOBJECT:
1399        {
1400            if(m_targets.getGOTarget())
1401                AddGOTarget(m_targets.getGOTarget(), i);
1402        }break;
1403        case TARGET_GAMEOBJECT_ITEM:
1404        {
1405            if(m_targets.getGOTargetGUID())
1406                AddGOTarget(m_targets.getGOTarget(), i);
1407            else if(m_targets.getItemTarget())
1408                AddItemTarget(m_targets.getItemTarget(), i);
1409        }break;
1410
1411        // channel
1412        case TARGET_SINGLE_ENEMY:
1413            if(m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1414            {
1415                if(Unit* target = m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->m_targets.getUnitTarget())
1416                    TagUnitMap.push_back(target);
1417                else
1418                    sLog.outError( "SPELL: cannot find channel spell target for spell ID %u\n", m_spellInfo->Id );
1419            }
1420            else
1421                sLog.outError( "SPELL: no current channeled spell for spell ID %u\n", m_spellInfo->Id );
1422            break;
1423        case TARGET_DEST_CHANNEL:
1424            if(m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1425            {
1426                if(m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->m_targets.HasDest())
1427                    m_targets = m_caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->m_targets;
1428                else
1429                    sLog.outError( "SPELL: cannot find channel spell destination for spell ID %u\n", m_spellInfo->Id );
1430            }
1431            else
1432                sLog.outError( "SPELL: no current channeled spell for spell ID %u\n", m_spellInfo->Id );
1433            break;
1434
1435        // reference dest
1436        case TARGET_EFFECT_SELECT:
1437            m_targets.setDestination(m_caster, true);
1438            break;
1439        case TARGET_ALL_AROUND_CASTER:
1440            m_targets.setDestination(m_caster, false);
1441            break;
1442        case TARGET_CURRENT_ENEMY_COORDINATES:
1443            m_targets.setDestination(m_targets.getUnitTarget(), true);
1444            break;
1445        case TARGET_DUELVSPLAYER_COORDINATES: // no ground?
1446            m_targets.setDestination(m_targets.getUnitTarget(), false);
1447            break;
1448        case TARGET_DEST_TABLE_UNKNOWN2:
1449        case TARGET_TABLE_X_Y_Z_COORDINATES:
1450            if(SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id))
1451            {
1452                //TODO: fix this check
1453                if(m_spellInfo->Effect[0] == SPELL_EFFECT_TELEPORT_UNITS
1454                    || m_spellInfo->Effect[1] == SPELL_EFFECT_TELEPORT_UNITS
1455                    || m_spellInfo->Effect[2] == SPELL_EFFECT_TELEPORT_UNITS)
1456                    m_targets.setDestination(st->target_X, st->target_Y, st->target_Z, true, (int32)st->target_mapId);
1457                else if(st->target_mapId == m_caster->GetMapId())
1458                    m_targets.setDestination(st->target_X, st->target_Y, st->target_Z);
1459            }
1460            else
1461                sLog.outError( "SPELL: unknown target coordinates for spell ID %u\n", m_spellInfo->Id );
1462            break;
1463        case TARGET_INNKEEPER_COORDINATES:
1464            if(m_caster->GetTypeId() == TYPEID_PLAYER)
1465                m_targets.setDestination(((Player*)m_caster)->m_homebindX,((Player*)m_caster)->m_homebindY,((Player*)m_caster)->m_homebindZ, true, ((Player*)m_caster)->m_homebindMapId);
1466            break;
1467
1468        // area targets
1469        case TARGET_ALL_ENEMY_IN_AREA_INSTANT:
1470            if(m_spellInfo->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
1471                break;
1472            m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
1473        case TARGET_ALL_ENEMY_IN_AREA:
1474            SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1475            break;
1476        case TARGET_ALL_FRIENDLY_UNITS_IN_AREA:
1477            m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
1478        case TARGET_ALL_FRIENDLY_UNITS_AROUND_CASTER:
1479            SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_FRIENDLY);
1480            break;
1481        case TARGET_AREAEFFECT_CUSTOM:
1482            m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
1483        case TARGET_UNIT_AREA_ENTRY:
1484        {
1485            SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
1486            SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
1487            if(lower==upper)
1488            {
1489                SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE);
1490                //sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT, but does not have record in `spell_script_target`",m_spellInfo->Id);
1491                break;
1492            }
1493            // let it be done in one check?
1494            for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
1495            {
1496                if(i_spellST->second.type != SPELL_TARGET_TYPE_CREATURE)
1497                {
1498                    sLog.outError( "SPELL: spell ID %u requires non-creature target\n", m_spellInfo->Id );
1499                    continue;
1500                }
1501                SearchAreaTarget(TagUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_ENTRY, i_spellST->second.targetEntry);
1502            }
1503        }break;
1504        case TARGET_IN_FRONT_OF_CASTER:
1505        case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
1506            switch(spellmgr.GetSpellExtraAttr(m_spellInfo->Id, SPELL_EXTRA_ATTR_CONE_TYPE))
1507            {
1508                default:
1509                case 0:
1510                    SearchAreaTarget(TagUnitMap, radius, PUSH_IN_FRONT, SPELL_TARGETS_AOE_DAMAGE);
1511                    break;
1512                case 1:
1513                    SearchAreaTarget(TagUnitMap, radius, PUSH_IN_BACK, SPELL_TARGETS_AOE_DAMAGE);
1514                    break;
1515                case 2:
1516                    SearchAreaTarget(TagUnitMap, radius, PUSH_IN_LINE, SPELL_TARGETS_AOE_DAMAGE);
1517                    break;
1518            }break;
1519        case TARGET_UNIT_CONE_ALLY:
1520            SearchAreaTarget(TagUnitMap, radius, PUSH_IN_FRONT, SPELL_TARGETS_FRIENDLY);
1521            break;
1522
1523        // nearby target
1524        case TARGET_UNIT_NEARBY_ALLY:
1525        {
1526            if(Unit* pUnitTarget = SearchNearbyTarget(radius, SPELL_TARGETS_FRIENDLY))
1527                TagUnitMap.push_back(pUnitTarget);
1528        }break;
1529        case TARGET_RANDOM_ENEMY_CHAIN_IN_AREA:
1530        {
1531            if(EffectChainTarget <= 1)
1532            {
1533                if(Unit* pUnitTarget = SearchNearbyTarget(radius, SPELL_TARGETS_AOE_DAMAGE))
1534                    TagUnitMap.push_back(pUnitTarget);
1535            }
1536            else
1537                SearchChainTarget(TagUnitMap, m_caster, radius, EffectChainTarget);
1538        }break;
1539        case TARGET_SCRIPT:
1540        case TARGET_SCRIPT_COORDINATES:
1541        {
1542            SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
1543            SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
1544            if(lower==upper)
1545                sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT or TARGET_SCRIPT_COORDINATES, but does not have record in `spell_script_target`",m_spellInfo->Id);
1546
1547            SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
1548            float range = GetSpellMaxRange(srange);
1549
1550            Creature* creatureScriptTarget = NULL;
1551            GameObject* goScriptTarget = NULL;
1552
1553            for(SpellScriptTarget::const_iterator i_spellST = lower; i_spellST != upper; ++i_spellST)
1554            {
1555                switch(i_spellST->second.type)
1556                {
1557                case SPELL_TARGET_TYPE_GAMEOBJECT:
1558                    {
1559                        GameObject* p_GameObject = NULL;
1560
1561                        if(i_spellST->second.targetEntry)
1562                        {
1563                            CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1564                            Cell cell(p);
1565                            cell.data.Part.reserved = ALL_DISTRICT;
1566
1567                            Trinity::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
1568                            Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> checker(p_GameObject,go_check);
1569
1570                            TypeContainerVisitor<Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
1571                            CellLock<GridReadGuard> cell_lock(cell, p);
1572                            cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1573
1574                            if(p_GameObject)
1575                            {
1576                                // remember found target and range, next attempt will find more near target with another entry
1577                                creatureScriptTarget = NULL;
1578                                goScriptTarget = p_GameObject;
1579                                range = go_check.GetLastRange();
1580                            }
1581                        }
1582                        else if( focusObject )          //Focus Object
1583                        {
1584                            float frange = m_caster->GetDistance(focusObject);
1585                            if(range >= frange)
1586                            {
1587                                creatureScriptTarget = NULL;
1588                                goScriptTarget = focusObject;
1589                                range = frange;
1590                            }
1591                        }
1592                        break;
1593                    }
1594                case SPELL_TARGET_TYPE_CREATURE:
1595                case SPELL_TARGET_TYPE_DEAD:
1596                default:
1597                    {
1598                        Creature *p_Creature = NULL;
1599
1600                        CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1601                        Cell cell(p);
1602                        cell.data.Part.reserved = ALL_DISTRICT;
1603                        cell.SetNoCreate();             // Really don't know what is that???
1604
1605                        Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
1606                        Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(p_Creature, u_check);
1607
1608                        TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1609
1610                        CellLock<GridReadGuard> cell_lock(cell, p);
1611                        cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1612
1613                        if(p_Creature )
1614                        {
1615                            creatureScriptTarget = p_Creature;
1616                            goScriptTarget = NULL;
1617                            range = u_check.GetLastRange();
1618                        }
1619                        break;
1620                    }
1621                }
1622            }
1623
1624            if(cur == TARGET_SCRIPT_COORDINATES)
1625            {
1626                if(creatureScriptTarget)
1627                    m_targets.setDestination(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
1628                else if(goScriptTarget)
1629                    m_targets.setDestination(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
1630            }
1631            else
1632            {
1633                if(creatureScriptTarget)
1634                    TagUnitMap.push_back(creatureScriptTarget);
1635                else if(goScriptTarget)
1636                    AddGOTarget(goScriptTarget, i);
1637            }
1638        }break;
1639
1640        // dummy
1641        case TARGET_AREAEFFECT_CUSTOM_2:
1642        {
1643            TagUnitMap.push_back(m_caster);
1644            break;
1645        }
1646
1647        case TARGET_ALL_PARTY_AROUND_CASTER:
1648        case TARGET_ALL_PARTY_AROUND_CASTER_2:
1649        case TARGET_ALL_PARTY:
1650        {
1651            Player *pTarget = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself();
1652            Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
1653
1654            if(pGroup)
1655            {
1656                uint8 subgroup = pTarget->GetSubGroup();
1657
1658                for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1659                {
1660                    Player* Target = itr->getSource();
1661
1662                    // IsHostileTo check duel and controlled by enemy
1663                    if( Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target) )
1664                    {
1665                        if( m_caster->IsWithinDistInMap(Target, radius) )
1666                            TagUnitMap.push_back(Target);
1667
1668                        if(Pet* pet = Target->GetPet())
1669                            if( m_caster->IsWithinDistInMap(pet, radius) )
1670                                TagUnitMap.push_back(pet);
1671                    }
1672                }
1673            }
1674            else
1675            {
1676                Unit* ownerOrSelf = pTarget ? pTarget : m_caster->GetCharmerOrOwnerOrSelf();
1677                if(ownerOrSelf==m_caster || m_caster->IsWithinDistInMap(ownerOrSelf, radius))
1678                    TagUnitMap.push_back(ownerOrSelf);
1679                if(Pet* pet = ownerOrSelf->GetPet())
1680                    if( m_caster->IsWithinDistInMap(pet, radius) )
1681                        TagUnitMap.push_back(pet);
1682            }
1683        }break;
1684        case TARGET_RANDOM_RAID_MEMBER:
1685        {
1686            if (m_caster->GetTypeId() == TYPEID_PLAYER)
1687                if(Player* target = ((Player*)m_caster)->GetNextRandomRaidMember(radius))
1688                    TagUnitMap.push_back(target);
1689        }break;
1690        // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some sceals, fire shield from imp, etc..)
1691        case TARGET_SINGLE_PARTY:
1692        {
1693            Unit *target = m_targets.getUnitTarget();
1694            // Thoses spells apparently can't be casted on the caster.
1695            if( target && target != m_caster)
1696            {
1697                // Can only be casted on group's members or its pets
1698                Group  *pGroup = NULL;
1699
1700                Unit* owner = m_caster->GetCharmerOrOwner();
1701                Unit *targetOwner = target->GetCharmerOrOwner();
1702                if(owner)
1703                {
1704                    if(owner->GetTypeId() == TYPEID_PLAYER)
1705                    {
1706                        if( target == owner )
1707                        {
1708                            TagUnitMap.push_back(target);
1709                            break;
1710                        }
1711                        pGroup = ((Player*)owner)->GetGroup();
1712                    }
1713                }
1714                else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1715                {
1716                    if( targetOwner == m_caster && target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isPet())
1717                    {
1718                        TagUnitMap.push_back(target);
1719                        break;
1720                    }
1721                    pGroup = ((Player*)m_caster)->GetGroup();
1722                }
1723
1724                if(pGroup)
1725                {
1726                    // Our target can also be a player's pet who's grouped with us or our pet. But can't be controlled player
1727                    if(targetOwner)
1728                    {
1729                        if( targetOwner->GetTypeId() == TYPEID_PLAYER &&
1730                            target->GetTypeId()==TYPEID_UNIT && (((Creature*)target)->isPet()) &&
1731                            target->GetOwnerGUID()==targetOwner->GetGUID() &&
1732                            pGroup->IsMember(((Player*)targetOwner)->GetGUID()))
1733                        {
1734                            TagUnitMap.push_back(target);
1735                        }
1736                    }
1737                    // 1Our target can be a player who is on our group
1738                    else if (target->GetTypeId() == TYPEID_PLAYER && pGroup->IsMember(((Player*)target)->GetGUID()))
1739                    {
1740                        TagUnitMap.push_back(target);
1741                    }
1742                }
1743            }
1744        }break;
1745        case TARGET_ALL_ENEMY_IN_AREA_CHANNELED:
1746        {
1747            // targets the ground, not the units in the area
1748            if (m_spellInfo->Effect[i]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
1749            {
1750                CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1751                Cell cell(p);
1752                cell.data.Part.reserved = ALL_DISTRICT;
1753                cell.SetNoCreate();
1754
1755                Trinity::SpellNotifierCreatureAndPlayer notifier(*this, TagUnitMap, radius, PUSH_DEST_CENTER,SPELL_TARGETS_AOE_DAMAGE);
1756
1757                TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1758                TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, GridTypeMapContainer >  grid_object_notifier(notifier);
1759
1760                CellLock<GridReadGuard> cell_lock(cell, p);
1761                cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1762                cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1763            }
1764        }break;
1765        case TARGET_AREAEFFECT_PARTY:
1766        {
1767            Unit* owner = m_caster->GetCharmerOrOwner();
1768            Player *pTarget = NULL;
1769
1770            if(owner)
1771            {
1772                TagUnitMap.push_back(m_caster);
1773                if(owner->GetTypeId() == TYPEID_PLAYER)
1774                    pTarget = (Player*)owner;
1775            }
1776            else if (m_caster->GetTypeId() == TYPEID_PLAYER)
1777            {
1778                if(Unit* target = m_targets.getUnitTarget())
1779                {
1780                    if( target->GetTypeId() != TYPEID_PLAYER)
1781                    {
1782                        if(((Creature*)target)->isPet())
1783                        {
1784                            Unit *targetOwner = target->GetOwner();
1785                            if(targetOwner->GetTypeId() == TYPEID_PLAYER)
1786                                pTarget = (Player*)targetOwner;
1787                        }
1788                    }
1789                    else
1790                        pTarget = (Player*)target;
1791                }
1792            }
1793
1794            Group* pGroup = pTarget ? pTarget->GetGroup() : NULL;
1795
1796            if(pGroup)
1797            {
1798                uint8 subgroup = pTarget->GetSubGroup();
1799
1800                for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1801                {
1802                    Player* Target = itr->getSource();
1803
1804                    // IsHostileTo check duel and controlled by enemy
1805                    if(Target && Target->GetSubGroup()==subgroup && !m_caster->IsHostileTo(Target))
1806                    {
1807                        if( pTarget->IsWithinDistInMap(Target, radius) )
1808                            TagUnitMap.push_back(Target);
1809
1810                        if(Pet* pet = Target->GetPet())
1811                            if( pTarget->IsWithinDistInMap(pet, radius) )
1812                                TagUnitMap.push_back(pet);
1813                    }
1814                }
1815            }
1816            else if (owner)
1817            {
1818                if(m_caster->IsWithinDistInMap(owner, radius))
1819                    TagUnitMap.push_back(owner);
1820            }
1821            else if(pTarget)
1822            {
1823                TagUnitMap.push_back(pTarget);
1824
1825                if(Pet* pet = pTarget->GetPet())
1826                    if( m_caster->IsWithinDistInMap(pet, radius) )
1827                        TagUnitMap.push_back(pet);
1828            }
1829
1830        }break;
1831        case TARGET_CHAIN_HEAL:
1832        {
1833            Unit* pUnitTarget = m_targets.getUnitTarget();
1834            if(!pUnitTarget)
1835                break;
1836
1837            if (EffectChainTarget <= 1)
1838                TagUnitMap.push_back(pUnitTarget);
1839            else
1840            {
1841                unMaxTargets = EffectChainTarget;
1842                float max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS;
1843
1844                std::list<Unit *> tempUnitMap;
1845
1846                {
1847                    CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
1848                    Cell cell(p);
1849                    cell.data.Part.reserved = ALL_DISTRICT;
1850                    cell.SetNoCreate();
1851
1852                    Trinity::SpellNotifierCreatureAndPlayer notifier(*this, tempUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY);
1853
1854                    TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, WorldTypeMapContainer > world_object_notifier(notifier);
1855                    TypeContainerVisitor<Trinity::SpellNotifierCreatureAndPlayer, GridTypeMapContainer >  grid_object_notifier(notifier);
1856
1857                    CellLock<GridReadGuard> cell_lock(cell, p);
1858                    cell_lock->Visit(cell_lock, world_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1859                    cell_lock->Visit(cell_lock, grid_object_notifier, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
1860
1861                }
1862
1863                if(m_caster != pUnitTarget && std::find(tempUnitMap.begin(),tempUnitMap.end(),m_caster) == tempUnitMap.end() )
1864                    tempUnitMap.push_front(m_caster);
1865
1866                tempUnitMap.sort(TargetDistanceOrder(pUnitTarget));
1867
1868                if(tempUnitMap.empty())
1869                    break;
1870
1871                if(*tempUnitMap.begin() == pUnitTarget)
1872                    tempUnitMap.erase(tempUnitMap.begin());
1873
1874                TagUnitMap.push_back(pUnitTarget);
1875                uint32 t = unMaxTargets - 1;
1876                Unit *prev = pUnitTarget;
1877                std::list<Unit*>::iterator next = tempUnitMap.begin();
1878
1879                while(t && next != tempUnitMap.end() )
1880                {
1881                    if(prev->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
1882                        break;
1883
1884                    if(!prev->IsWithinLOSInMap(*next))
1885                    {
1886                        ++next;
1887                        continue;
1888                    }
1889
1890                    if((*next)->GetHealth() == (*next)->GetMaxHealth())
1891                    {
1892                        next = tempUnitMap.erase(next);
1893                        continue;
1894                    }
1895
1896                    prev = *next;
1897                    TagUnitMap.push_back(prev);
1898                    tempUnitMap.erase(next);
1899                    tempUnitMap.sort(TargetDistanceOrder(prev));
1900                    next = tempUnitMap.begin();
1901
1902                    --t;
1903                }
1904            }
1905        }break;
1906        case TARGET_AREAEFFECT_PARTY_AND_CLASS:
1907        {
1908            Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
1909                ? (Player*)m_targets.getUnitTarget() : NULL;
1910
1911            Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
1912            if(pGroup)
1913            {
1914                for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
1915                {
1916                    Player* Target = itr->getSource();
1917
1918                    // IsHostileTo check duel and controlled by enemy
1919                    if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
1920                        targetPlayer->getClass() == Target->getClass() &&
1921                        !m_caster->IsHostileTo(Target) )
1922                    {
1923                        TagUnitMap.push_back(Target);
1924                    }
1925                }
1926            }
1927            else if(m_targets.getUnitTarget())
1928                TagUnitMap.push_back(m_targets.getUnitTarget());
1929            break;
1930        }
1931
1932        // destination around caster
1933        case TARGET_DEST_CASTER_FRONT_LEFT:
1934        case TARGET_DEST_CASTER_BACK_LEFT:
1935        case TARGET_DEST_CASTER_BACK_RIGHT:
1936        case TARGET_DEST_CASTER_FRONT_RIGHT:
1937        case TARGET_DEST_CASTER_FRONT:
1938        case TARGET_MINION:
1939        case TARGET_DEST_CASTER_FRONT_LEAP:
1940        case TARGET_DEST_CASTER_FRONT_UNKNOWN:
1941        case TARGET_DEST_CASTER_BACK:
1942        case TARGET_DEST_CASTER_RIGHT:
1943        case TARGET_DEST_CASTER_LEFT:
1944        case TARGET_DEST_CASTER_RANDOM:
1945        case TARGET_DEST_CASTER_RADIUS:
1946        {
1947            float x, y, z, angle, dist;
1948
1949            if (m_spellInfo->EffectRadiusIndex[i])
1950                dist = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1951            else
1952                dist = 3.0f;//do we need this?
1953            if (cur == TARGET_DEST_CASTER_RANDOM)
1954                dist *= rand_norm(); // This case we need to consider caster size
1955            else
1956                dist -= m_caster->GetObjectSize(); // Size is calculated in GetNearPoint(), but we do not need it
1957            //need a new function to remove this repeated work
1958
1959            switch(cur)
1960            {
1961                case TARGET_DEST_CASTER_FRONT_LEFT: angle = -M_PI/4;    break;
1962                case TARGET_DEST_CASTER_BACK_LEFT:  angle = -3*M_PI/4;  break;
1963                case TARGET_DEST_CASTER_BACK_RIGHT: angle = 3*M_PI/4;   break;
1964                case TARGET_DEST_CASTER_FRONT_RIGHT:angle = M_PI/4;     break;
1965                case TARGET_MINION:
1966                case TARGET_DEST_CASTER_FRONT_LEAP:
1967                case TARGET_DEST_CASTER_FRONT_UNKNOWN:
1968                case TARGET_DEST_CASTER_FRONT:      angle = 0.0f;       break;
1969                case TARGET_DEST_CASTER_BACK:       angle = M_PI;       break;
1970                case TARGET_DEST_CASTER_RIGHT:      angle = M_PI/2;     break;
1971                case TARGET_DEST_CASTER_LEFT:       angle = -M_PI/2;    break;
1972                default:                            angle = rand_norm()*2*M_PI; break;
1973            }
1974
1975            m_caster->GetClosePoint(x, y, z, 0, dist, angle);
1976            m_targets.setDestination(x, y, z); // do not know if has ground visual
1977        }break;
1978
1979        // destination around target
1980        case TARGET_DEST_TARGET_FRONT:
1981        case TARGET_DEST_TARGET_BACK:
1982        case TARGET_DEST_TARGET_RIGHT:
1983        case TARGET_DEST_TARGET_LEFT:
1984        case TARGET_DEST_TARGET_RANDOM:
1985        case TARGET_DEST_TARGET_RADIUS:
1986        {
1987            Unit *target = m_targets.getUnitTarget();
1988            if(!target)
1989            {
1990                sLog.outError("SPELL: no unit target for spell ID %u\n", m_spellInfo->Id);
1991                break;
1992            }
1993
1994            float x, y, z, angle, dist;
1995
1996            if (m_spellInfo->EffectRadiusIndex[i])
1997                dist = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
1998            else
1999                dist = 3.0f;//do we need this?
2000            if (cur == TARGET_DEST_TARGET_RANDOM)
2001                dist *= rand_norm(); // This case we need to consider caster size
2002            else
2003                dist -= target->GetObjectSize(); // Size is calculated in GetNearPoint(), but we do not need it
2004            //need a new function to remove this repeated work
2005
2006            switch(cur)
2007            {
2008                case TARGET_DEST_TARGET_FRONT:      angle = 0.0f;       break;
2009                case TARGET_DEST_TARGET_BACK:       angle = M_PI;       break;
2010                case TARGET_DEST_TARGET_RIGHT:      angle = M_PI/2;     break;
2011                case TARGET_DEST_TARGET_LEFT:       angle = -M_PI/2;    break;
2012                default:                            angle = rand_norm()*2*M_PI; break;
2013            }
2014
2015            target->GetClosePoint(x, y, z, 0, dist, angle);
2016            m_targets.setDestination(x, y, z); // do not know if has ground visual
2017        }break;
2018
2019        // destination around destination
2020        case TARGET_DEST_DEST_RANDOM:
2021        {
2022            if(!m_targets.HasDest())
2023            {
2024                sLog.outError("SPELL: no destination for spell ID %u\n", m_spellInfo->Id);
2025                break;
2026            }
2027            float x, y, z, dist, px, py, pz;
2028            dist = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
2029            x = m_targets.m_destX;
2030            y = m_targets.m_destY;
2031            z = m_targets.m_destZ;
2032            m_caster->GetRandomPoint(x, y, z, dist, px, py, pz);
2033            m_targets.setDestination(px, py, pz);
2034        }break;
2035        case TARGET_SELF2:
2036            if(!m_targets.HasDest())
2037            {
2038                sLog.outError("SPELL: no destination for spell ID %u\n", m_spellInfo->Id);
2039                break;
2040            }
2041            break;
2042        default:
2043            break;
2044    }
2045
2046    if (unMaxTargets && TagUnitMap.size() > unMaxTargets)
2047    {
2048        // make sure one unit is always removed per iteration
2049        uint32 removed_utarget = 0;
2050        for (std::list<Unit*>::iterator itr = TagUnitMap.begin(), next; itr != TagUnitMap.end(); itr = next)
2051        {
2052            next = itr;
2053            ++next;
2054            if (!*itr) continue;
2055            if ((*itr) == m_targets.getUnitTarget())
2056            {
2057                TagUnitMap.erase(itr);
2058                removed_utarget = 1;
2059                //        break;
2060            }
2061        }
2062        // remove random units from the map
2063        while (TagUnitMap.size() > unMaxTargets - removed_utarget)
2064        {
2065            uint32 poz = urand(0, TagUnitMap.size()-1);
2066            for (std::list<Unit*>::iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end(); ++itr, --poz)
2067            {
2068                if (!*itr) continue;
2069                if (!poz)
2070                {
2071                    TagUnitMap.erase(itr);
2072                    break;
2073                }
2074            }
2075        }
2076        // the player's target will always be added to the map
2077        if (removed_utarget && m_targets.getUnitTarget())
2078            TagUnitMap.push_back(m_targets.getUnitTarget());
2079    }
2080}
2081
2082void Spell::prepare(SpellCastTargets * targets, Aura* triggeredByAura)
2083{
2084    m_targets = *targets;
2085
2086    m_spellState = SPELL_STATE_PREPARING;
2087
2088    m_caster->GetPosition(m_castPositionX, m_castPositionY, m_castPositionZ);
2089    m_castOrientation = m_caster->GetOrientation();
2090
2091    if(triggeredByAura)
2092        m_triggeredByAuraSpell  = triggeredByAura->GetSpellProto();
2093
2094    // create and add update event for this spell
2095    SpellEvent* Event = new SpellEvent(this);
2096    m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
2097
2098    //Prevent casting at cast another spell (ServerSide check)
2099    if(m_caster->IsNonMeleeSpellCasted(false, true) && m_cast_count)
2100    {
2101        SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
2102        finish(false);
2103        return;
2104    }
2105
2106    if(m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet()))
2107    {
2108        if(objmgr.IsPlayerSpellDisabled(m_spellInfo->Id))
2109        {
2110            SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
2111            finish(false);
2112            return;
2113        }
2114    }
2115    else
2116    {
2117        if(objmgr.IsCreatureSpellDisabled(m_spellInfo->Id))
2118        {
2119            finish(false);
2120            return;
2121        }
2122    }
2123
2124    // Fill cost data
2125    m_powerCost = CalculatePowerCost();
2126
2127    uint8 result = CanCast(true);
2128    if(result != 0 && !IsAutoRepeat())                      //always cast autorepeat dummy for triggering
2129    {
2130        if(triggeredByAura)
2131        {
2132            SendChannelUpdate(0);
2133            triggeredByAura->SetAuraDuration(0);
2134        }
2135        SendCastResult(result);
2136        finish(false);
2137        return;
2138    }
2139
2140    // calculate cast time (calculated after first CanCast check to prevent charge counting for first CanCast fail)
2141    m_casttime = GetSpellCastTime(m_spellInfo, this);
2142
2143    // set timer base at cast time
2144    ReSetTimer();
2145
2146    // stealth must be removed at cast starting (at show channel bar)
2147    // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
2148    if ( !m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
2149    {
2150        m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_STEALTH);
2151    }
2152
2153    if(m_IsTriggeredSpell)
2154        cast(true);
2155    else
2156    {
2157        m_caster->SetCurrentCastedSpell( this );
2158        m_selfContainer = &(m_caster->m_currentSpells[GetCurrentContainer()]);
2159        SendSpellStart();
2160    }
2161}
2162
2163void Spell::cancel()
2164{
2165    if(m_spellState == SPELL_STATE_FINISHED)
2166        return;
2167
2168    m_autoRepeat = false;
2169    switch (m_spellState)
2170    {
2171        case SPELL_STATE_PREPARING:
2172        case SPELL_STATE_DELAYED:
2173        {
2174            SendInterrupted(0);
2175            SendCastResult(SPELL_FAILED_INTERRUPTED);
2176        } break;
2177
2178        case SPELL_STATE_CASTING:
2179        {
2180            for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2181            {
2182                if( ihit->missCondition == SPELL_MISS_NONE )
2183                {
2184                    Unit* unit = m_caster->GetGUID()==(*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2185                    if( unit && unit->isAlive() )
2186                        unit->RemoveAurasDueToSpell(m_spellInfo->Id);
2187                }
2188            }
2189
2190            m_caster->RemoveAurasDueToSpell(m_spellInfo->Id);
2191            SendChannelUpdate(0);
2192            SendInterrupted(0);
2193            SendCastResult(SPELL_FAILED_INTERRUPTED);
2194        } break;
2195
2196        default:
2197        {
2198        } break;
2199    }
2200
2201    finish(false);
2202    m_caster->RemoveDynObject(m_spellInfo->Id);
2203    m_caster->RemoveGameObject(m_spellInfo->Id,true);
2204}
2205
2206void Spell::cast(bool skipCheck)
2207{
2208    SetExecutedCurrently(true);
2209
2210    uint8 castResult = 0;
2211
2212    // update pointers base at GUIDs to prevent access to non-existed already object
2213    UpdatePointers();
2214
2215    // cancel at lost main target unit
2216    if(!m_targets.getUnitTarget() && m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
2217    {
2218        cancel();
2219        SetExecutedCurrently(false);
2220        return;
2221    }
2222
2223    if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
2224        m_caster->SetInFront(m_targets.getUnitTarget());
2225
2226    castResult = CheckPower();
2227    if(castResult != 0)
2228    {
2229        SendCastResult(castResult);
2230        finish(false);
2231        SetExecutedCurrently(false);
2232        return;
2233    }
2234
2235    // triggered cast called from Spell::prepare where it was already checked
2236    if(!skipCheck)
2237    {
2238        castResult = CanCast(false);
2239        if(castResult != 0)
2240        {
2241            SendCastResult(castResult);
2242            finish(false);
2243            SetExecutedCurrently(false);
2244            return;
2245        }
2246    }
2247
2248    FillTargetMap();
2249
2250    // who did this hack?
2251    // Conflagrate - consumes immolate
2252    if ((m_spellInfo->TargetAuraState == AURA_STATE_IMMOLATE) && m_targets.getUnitTarget())
2253    {
2254        // for caster applied auras only
2255        Unit::AuraList const &mPeriodic = m_targets.getUnitTarget()->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
2256        for(Unit::AuraList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
2257        {
2258            if( (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && ((*i)->GetSpellProto()->SpellFamilyFlags & 4) &&
2259                (*i)->GetCasterGUID()==m_caster->GetGUID() )
2260            {
2261                m_targets.getUnitTarget()->RemoveAura((*i)->GetId(), (*i)->GetEffIndex());
2262                break;
2263            }
2264        }
2265    }
2266
2267    if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id))
2268    {
2269        for(std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
2270        {
2271            if(spell_triggered < 0)
2272                m_caster->RemoveAurasDueToSpell(-(*i));
2273            else
2274                m_caster->CastSpell(m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster, *i, true);
2275        }
2276    }
2277
2278    // traded items have trade slot instead of guid in m_itemTargetGUID
2279    // set to real guid to be sent later to the client
2280    m_targets.updateTradeSlotItem();
2281
2282    // CAST SPELL
2283    SendSpellCooldown();
2284
2285    TakePower();
2286    TakeReagents();                                         // we must remove reagents before HandleEffects to allow place crafted item in same slot
2287
2288    if(m_spellState == SPELL_STATE_FINISHED)                // stop cast if spell marked as finish somewhere in Take*/FillTargetMap
2289    {
2290        SetExecutedCurrently(false);
2291        return;
2292    }
2293
2294    SendCastResult(castResult);
2295    SendSpellGo();                                          // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
2296
2297    // Pass cast spell event to handler (not send triggered by aura spells)
2298    if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE && m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_RANGED && !m_triggeredByAuraSpell)
2299    {
2300        m_caster->ProcDamageAndSpell(m_targets.getUnitTarget(), PROC_FLAG_CAST_SPELL, PROC_FLAG_NONE, 0, SPELL_SCHOOL_MASK_NONE, m_spellInfo, m_IsTriggeredSpell);
2301
2302        // update pointers base at GUIDs to prevent access to non-existed already object
2303        UpdatePointers();                                   // pointers can be invalidate at triggered spell casting
2304    }
2305
2306    // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
2307    if (m_spellInfo->speed > 0.0f)
2308    {
2309
2310        // Remove used for cast item if need (it can be already NULL after TakeReagents call
2311        // in case delayed spell remove item at cast delay start
2312        TakeCastItem();
2313
2314        // Okay, maps created, now prepare flags
2315        m_immediateHandled = false;
2316        m_spellState = SPELL_STATE_DELAYED;
2317        SetDelayStart(0);
2318    }
2319    else
2320    {
2321        // Immediate spell, no big deal
2322        handle_immediate();
2323    }
2324
2325    SetExecutedCurrently(false);
2326}
2327
2328void Spell::handle_immediate()
2329{
2330    // start channeling if applicable
2331    if(IsChanneledSpell(m_spellInfo))
2332    {
2333        m_spellState = SPELL_STATE_CASTING;
2334        SendChannelStart(GetSpellDuration(m_spellInfo));
2335    }
2336
2337    // process immediate effects (items, ground, etc.) also initialize some variables
2338    _handle_immediate_phase();
2339
2340    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2341        DoAllEffectOnTarget(&(*ihit));
2342
2343    for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2344        DoAllEffectOnTarget(&(*ihit));
2345
2346    // spell is finished, perform some last features of the spell here
2347    _handle_finish_phase();
2348
2349    // Remove used for cast item if need (it can be already NULL after TakeReagents call
2350    TakeCastItem();
2351
2352    if(m_spellState != SPELL_STATE_CASTING)
2353        finish(true);                                       // successfully finish spell cast (not last in case autorepeat or channel spell)
2354}
2355
2356uint64 Spell::handle_delayed(uint64 t_offset)
2357{
2358    uint64 next_time = 0;
2359
2360    if (!m_immediateHandled)
2361    {
2362        _handle_immediate_phase();
2363        m_immediateHandled = true;
2364    }
2365
2366    // 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)
2367    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();++ihit)
2368    {
2369        if (ihit->processed == false)
2370        {
2371            if ( ihit->timeDelay <= t_offset )
2372                DoAllEffectOnTarget(&(*ihit));
2373            else if( next_time == 0 || ihit->timeDelay < next_time )
2374                next_time = ihit->timeDelay;
2375        }
2376    }
2377
2378    // now recheck gameobject targeting correctness
2379    for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end();++ighit)
2380    {
2381        if (ighit->processed == false)
2382        {
2383            if ( ighit->timeDelay <= t_offset )
2384                DoAllEffectOnTarget(&(*ighit));
2385            else if( next_time == 0 || ighit->timeDelay < next_time )
2386                next_time = ighit->timeDelay;
2387        }
2388    }
2389    // All targets passed - need finish phase
2390    if (next_time == 0)
2391    {
2392        // spell is finished, perform some last features of the spell here
2393        _handle_finish_phase();
2394
2395        finish(true);                                       // successfully finish spell cast
2396
2397        // return zero, spell is finished now
2398        return 0;
2399    }
2400    else
2401    {
2402        // spell is unfinished, return next execution time
2403        return next_time;
2404    }
2405}
2406
2407void Spell::_handle_immediate_phase()
2408{
2409    // handle some immediate features of the spell here
2410    HandleThreatSpells(m_spellInfo->Id);
2411
2412    m_needSpellLog = IsNeedSendToClient();
2413    for(uint32 j = 0;j<3;j++)
2414    {
2415        if(m_spellInfo->Effect[j]==0)
2416            continue;
2417
2418        // apply Send Event effect to ground in case empty target lists
2419        if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
2420        {
2421            HandleEffects(NULL,NULL,NULL, j);
2422            continue;
2423        }
2424
2425        // Don't do spell log, if is school damage spell
2426        if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
2427            m_needSpellLog = false;
2428
2429        uint32 EffectChainTarget = m_spellInfo->EffectChainTarget[j];
2430        if(m_originalCaster)
2431            if(Player* modOwner = m_originalCaster->GetSpellModOwner())
2432                modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this);
2433
2434        // initialize multipliers
2435        m_damageMultipliers[j] = 1.0f;
2436        if( (m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_HEAL) &&
2437            (EffectChainTarget > 1) )
2438            m_applyMultiplierMask |= 1 << j;
2439    }
2440
2441    // initialize Diminishing Returns Data
2442    m_diminishLevel = DIMINISHING_LEVEL_1;
2443    m_diminishGroup = DIMINISHING_NONE;
2444
2445    // process items
2446    for(std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin();ihit != m_UniqueItemInfo.end();++ihit)
2447        DoAllEffectOnTarget(&(*ihit));
2448
2449    // process ground
2450    for(uint32 j = 0;j<3;j++)
2451    {
2452        // persistent area auras target only the ground
2453        if(m_spellInfo->Effect[j] == SPELL_EFFECT_PERSISTENT_AREA_AURA)
2454            HandleEffects(NULL,NULL,NULL, j);
2455    }
2456}
2457
2458void Spell::_handle_finish_phase()
2459{
2460    // spell log
2461    if(m_needSpellLog)
2462        SendLogExecute();
2463}
2464
2465void Spell::SendSpellCooldown()
2466{
2467    if(m_caster->GetTypeId() != TYPEID_PLAYER)
2468        return;
2469
2470    Player* _player = (Player*)m_caster;
2471    // Add cooldown for max (disable spell)
2472    // Cooldown started on SendCooldownEvent call
2473    if (m_spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
2474    {
2475        _player->AddSpellCooldown(m_spellInfo->Id, 0, time(NULL) - 1);
2476        return;
2477    }
2478
2479    // init cooldown values
2480    uint32 cat   = 0;
2481    int32 rec    = -1;
2482    int32 catrec = -1;
2483
2484    // some special item spells without correct cooldown in SpellInfo
2485    // cooldown information stored in item prototype
2486    // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
2487
2488    if(m_CastItem)
2489    {
2490        ItemPrototype const* proto = m_CastItem->GetProto();
2491        if(proto)
2492        {
2493            for(int idx = 0; idx < 5; ++idx)
2494            {
2495                if(proto->Spells[idx].SpellId == m_spellInfo->Id)
2496                {
2497                    cat    = proto->Spells[idx].SpellCategory;
2498                    rec    = proto->Spells[idx].SpellCooldown;
2499                    catrec = proto->Spells[idx].SpellCategoryCooldown;
2500                    break;
2501                }
2502            }
2503        }
2504    }
2505
2506    // if no cooldown found above then base at DBC data
2507    if(rec < 0 && catrec < 0)
2508    {
2509        cat = m_spellInfo->Category;
2510        rec = m_spellInfo->RecoveryTime;
2511        catrec = m_spellInfo->CategoryRecoveryTime;
2512    }
2513
2514    // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
2515    // prevent 0 cooldowns set by another way
2516    if (rec <= 0 && catrec <= 0 && (cat == 76 || cat == 351))
2517        rec = _player->GetAttackTime(RANGED_ATTACK);
2518
2519    // Now we have cooldown data (if found any), time to apply mods
2520    if(rec > 0)
2521        _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, rec, this);
2522
2523    if(catrec > 0)
2524        _player->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COOLDOWN, catrec, this);
2525
2526    // replace negative cooldowns by 0
2527    if (rec < 0) rec = 0;
2528    if (catrec < 0) catrec = 0;
2529
2530    // no cooldown after applying spell mods
2531    if( rec == 0 && catrec == 0)
2532        return;
2533
2534    time_t curTime = time(NULL);
2535
2536    time_t catrecTime = catrec ? curTime+catrec/1000 : 0;   // in secs
2537    time_t recTime    = rec ? curTime+rec/1000 : catrecTime;// in secs
2538
2539    // self spell cooldown
2540    if(recTime > 0)
2541        _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, recTime);
2542
2543    // category spells
2544    if (catrec > 0)
2545    {
2546        SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
2547        if(i_scstore != sSpellCategoryStore.end())
2548        {
2549            for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
2550            {
2551                if(*i_scset == m_spellInfo->Id)             // skip main spell, already handled above
2552                    continue;
2553
2554                _player->AddSpellCooldown(m_spellInfo->Id, m_CastItem ? m_CastItem->GetEntry() : 0, catrecTime);
2555            }
2556        }
2557    }
2558}
2559
2560void Spell::update(uint32 difftime)
2561{
2562    // update pointers based at it's GUIDs
2563    UpdatePointers();
2564
2565    if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
2566    {
2567        cancel();
2568        return;
2569    }
2570
2571    // check if the player caster has moved before the spell finished
2572    if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
2573        (m_castPositionX != m_caster->GetPositionX() || m_castPositionY != m_caster->GetPositionY() || m_castPositionZ != m_caster->GetPositionZ()) &&
2574        (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
2575    {
2576        // always cancel for channeled spells
2577        if( m_spellState == SPELL_STATE_CASTING )
2578            cancel();
2579        // don't cancel for melee, autorepeat, triggered and instant spells
2580        else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT))
2581            cancel();
2582    }
2583
2584    switch(m_spellState)
2585    {
2586        case SPELL_STATE_PREPARING:
2587        {
2588            if(m_timer)
2589            {
2590                if(difftime >= m_timer)
2591                    m_timer = 0;
2592                else
2593                    m_timer -= difftime;
2594            }
2595
2596            if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
2597                cast();
2598        } break;
2599        case SPELL_STATE_CASTING:
2600        {
2601            if(m_timer > 0)
2602            {
2603                if( m_caster->GetTypeId() == TYPEID_PLAYER )
2604                {
2605                    // check if player has jumped before the channeling finished
2606                    if(m_caster->HasUnitMovementFlag(MOVEMENTFLAG_JUMPING))
2607                        cancel();
2608
2609                    // check for incapacitating player states
2610                    if( m_caster->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
2611                        cancel();
2612
2613                    // check if player has turned if flag is set
2614                    if( m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_TURNING && m_castOrientation != m_caster->GetOrientation() )
2615                        cancel();
2616                }
2617
2618                // check if there are alive targets left
2619                if (!IsAliveUnitPresentInTargetList())
2620                {
2621                    SendChannelUpdate(0);
2622                    finish();
2623                }
2624
2625                if(difftime >= m_timer)
2626                    m_timer = 0;
2627                else
2628                    m_timer -= difftime;
2629            }
2630
2631            if(m_timer == 0)
2632            {
2633                SendChannelUpdate(0);
2634
2635                // channeled spell processed independently for quest targeting
2636                // cast at creature (or GO) quest objectives update at successful cast channel finished
2637                // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
2638                if( m_caster->GetTypeId() == TYPEID_PLAYER && !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
2639                {
2640                    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2641                    {
2642                        TargetInfo* target = &*ihit;
2643                        if(!IS_CREATURE_GUID(target->targetGUID))
2644                            continue;
2645
2646                        Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
2647                        if (unit==NULL)
2648                            continue;
2649
2650                        ((Player*)m_caster)->CastedCreatureOrGO(unit->GetEntry(),unit->GetGUID(),m_spellInfo->Id);
2651                    }
2652
2653                    for(std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin();ihit != m_UniqueGOTargetInfo.end();++ihit)
2654                    {
2655                        GOTargetInfo* target = &*ihit;
2656
2657                        GameObject* go = ObjectAccessor::GetGameObject(*m_caster, target->targetGUID);
2658                        if(!go)
2659                            continue;
2660
2661                        ((Player*)m_caster)->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
2662                    }
2663                }
2664
2665                finish();
2666            }
2667        } break;
2668        default:
2669        {
2670        }break;
2671    }
2672}
2673
2674void Spell::finish(bool ok)
2675{
2676    if(!m_caster)
2677        return;
2678
2679    if(m_spellState == SPELL_STATE_FINISHED)
2680        return;
2681
2682    m_spellState = SPELL_STATE_FINISHED;
2683
2684    //remove spell mods
2685    if (m_caster->GetTypeId() == TYPEID_PLAYER)
2686        ((Player*)m_caster)->RemoveSpellMods(this);
2687
2688    // other code related only to successfully finished spells
2689    if(!ok)
2690        return;
2691
2692    //handle SPELL_AURA_ADD_TARGET_TRIGGER auras
2693    Unit::AuraList const& targetTriggers = m_caster->GetAurasByType(SPELL_AURA_ADD_TARGET_TRIGGER);
2694    for(Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
2695    {
2696        SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
2697        uint32 auraSpellIdx = (*i)->GetEffIndex();
2698        if (IsAffectedBy(auraSpellInfo, auraSpellIdx))
2699        {
2700            for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2701                if( ihit->effectMask & (1<<auraSpellIdx) )
2702            {
2703                // check m_caster->GetGUID() let load auras at login and speedup most often case
2704                Unit *unit = m_caster->GetGUID()== ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
2705                if (unit && unit->isAlive())
2706                {
2707                    // Calculate chance at that moment (can be depend for example from combo points)
2708                    int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBasePoints(),unit);
2709
2710                    if(roll_chance_i(chance))
2711                        m_caster->CastSpell(unit, auraSpellInfo->EffectTriggerSpell[auraSpellIdx], true, NULL, (*i));
2712                }
2713            }
2714        }
2715    }
2716
2717    if (IsMeleeAttackResetSpell())
2718    {
2719        m_caster->resetAttackTimer(BASE_ATTACK);
2720        if(m_caster->haveOffhandWeapon())
2721            m_caster->resetAttackTimer(OFF_ATTACK);
2722    }
2723
2724    /*if (IsRangedAttackResetSpell())
2725        m_caster->resetAttackTimer(RANGED_ATTACK);*/
2726
2727    // Clear combo at finish state
2728    if(m_caster->GetTypeId() == TYPEID_PLAYER && NeedsComboPoints(m_spellInfo))
2729        ((Player*)m_caster)->ClearComboPoints();
2730
2731    // call triggered spell only at successful cast (after clear combo points -> for add some if need)
2732    if(!m_TriggerSpells.empty())
2733        TriggerSpell();
2734
2735    // Stop Attack for some spells
2736    if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
2737        m_caster->AttackStop();
2738}
2739
2740void Spell::SendCastResult(uint8 result)
2741{
2742    if (m_caster->GetTypeId() != TYPEID_PLAYER)
2743        return;
2744
2745    if(((Player*)m_caster)->GetSession()->PlayerLoading())  // don't send cast results at loading time
2746        return;
2747
2748    if(result != 0)
2749    {
2750        WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
2751        data << uint32(m_spellInfo->Id);
2752        data << uint8(result);                              // problem
2753        data << uint8(m_cast_count);                        // single cast or multi 2.3 (0/1)
2754        switch (result)
2755        {
2756            case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
2757                data << uint32(m_spellInfo->RequiresSpellFocus);
2758                break;
2759            case SPELL_FAILED_REQUIRES_AREA:
2760                // hardcode areas limitation case
2761                if( m_spellInfo->Id==41618 || m_spellInfo->Id==41620 )
2762                    data << uint32(3842);
2763                else if( m_spellInfo->Id==41617 || m_spellInfo->Id==41619 )
2764                    data << uint32(3905);
2765                // normal case
2766                else
2767                    data << uint32(m_spellInfo->AreaId);
2768                break;
2769            case SPELL_FAILED_TOTEMS:
2770                if(m_spellInfo->Totem[0])
2771                    data << uint32(m_spellInfo->Totem[0]);
2772                if(m_spellInfo->Totem[1])
2773                    data << uint32(m_spellInfo->Totem[1]);
2774                break;
2775            case SPELL_FAILED_TOTEM_CATEGORY:
2776                if(m_spellInfo->TotemCategory[0])
2777                    data << uint32(m_spellInfo->TotemCategory[0]);
2778                if(m_spellInfo->TotemCategory[1])
2779                    data << uint32(m_spellInfo->TotemCategory[1]);
2780                break;
2781            case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
2782                data << uint32(m_spellInfo->EquippedItemClass);
2783                data << uint32(m_spellInfo->EquippedItemSubClassMask);
2784                data << uint32(m_spellInfo->EquippedItemInventoryTypeMask);
2785                break;
2786        }
2787        ((Player*)m_caster)->GetSession()->SendPacket(&data);
2788    }
2789    else
2790    {
2791        WorldPacket data(SMSG_CLEAR_EXTRA_AURA_INFO, (8+4));
2792        data.append(m_caster->GetPackGUID());
2793        data << uint32(m_spellInfo->Id);
2794        ((Player*)m_caster)->GetSession()->SendPacket(&data);
2795    }
2796}
2797
2798void Spell::SendSpellStart()
2799{
2800    if(!IsNeedSendToClient())
2801        return;
2802
2803    sLog.outDebug("Sending SMSG_SPELL_START id=%u",m_spellInfo->Id);
2804
2805    uint16 castFlags = CAST_FLAG_UNKNOWN1;
2806    if(IsRangedSpell())
2807        castFlags |= CAST_FLAG_AMMO;
2808
2809    Unit * target;
2810    if(!m_targets.getUnitTarget())
2811        target = m_caster;
2812    else
2813        target = m_targets.getUnitTarget();
2814
2815    WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
2816    if(m_CastItem)
2817        data.append(m_CastItem->GetPackGUID());
2818    else
2819        data.append(m_caster->GetPackGUID());
2820
2821    data.append(m_caster->GetPackGUID());
2822    data << uint32(m_spellInfo->Id);
2823    data << uint8(m_cast_count);                            // single cast or multi 2.3 (0/1)
2824    data << uint16(castFlags);
2825    data << uint32(m_timer);
2826
2827    m_targets.write(&data);
2828
2829    if( castFlags & CAST_FLAG_AMMO )
2830        WriteAmmoToPacket(&data);
2831
2832    m_caster->SendMessageToSet(&data, true);
2833}
2834
2835void Spell::SendSpellGo()
2836{
2837    // not send invisible spell casting
2838    if(!IsNeedSendToClient())
2839        return;
2840
2841    sLog.outDebug("Sending SMSG_SPELL_GO id=%u",m_spellInfo->Id);
2842
2843    Unit * target;
2844    if(!m_targets.getUnitTarget())
2845        target = m_caster;
2846    else
2847        target = m_targets.getUnitTarget();
2848
2849    uint16 castFlags = CAST_FLAG_UNKNOWN3;
2850    if(IsRangedSpell())
2851        castFlags |= CAST_FLAG_AMMO;
2852
2853    WorldPacket data(SMSG_SPELL_GO, 50);                    // guess size
2854    if(m_CastItem)
2855        data.append(m_CastItem->GetPackGUID());
2856    else
2857        data.append(m_caster->GetPackGUID());
2858
2859    data.append(m_caster->GetPackGUID());
2860    data << uint32(m_spellInfo->Id);
2861    data << uint16(castFlags);
2862    data << uint32(getMSTime());                            // timestamp
2863
2864    WriteSpellGoTargets(&data);
2865
2866    m_targets.write(&data);
2867
2868    if( castFlags & CAST_FLAG_AMMO )
2869        WriteAmmoToPacket(&data);
2870
2871    m_caster->SendMessageToSet(&data, true);
2872}
2873
2874void Spell::WriteAmmoToPacket( WorldPacket * data )
2875{
2876    uint32 ammoInventoryType = 0;
2877    uint32 ammoDisplayID = 0;
2878
2879    if (m_caster->GetTypeId() == TYPEID_PLAYER)
2880    {
2881        Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
2882        if(pItem)
2883        {
2884            ammoInventoryType = pItem->GetProto()->InventoryType;
2885            if( ammoInventoryType == INVTYPE_THROWN )
2886                ammoDisplayID = pItem->GetProto()->DisplayInfoID;
2887            else
2888            {
2889                uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
2890                if(ammoID)
2891                {
2892                    ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
2893                    if(pProto)
2894                    {
2895                        ammoDisplayID = pProto->DisplayInfoID;
2896                        ammoInventoryType = pProto->InventoryType;
2897                    }
2898                }
2899                else if(m_caster->GetDummyAura(46699))      // Requires No Ammo
2900                {
2901                    ammoDisplayID = 5996;                   // normal arrow
2902                    ammoInventoryType = INVTYPE_AMMO;
2903                }
2904            }
2905        }
2906    }
2907    // TODO: implement selection ammo data based at ranged weapon stored in equipmodel/equipinfo/equipslot fields
2908
2909    *data << uint32(ammoDisplayID);
2910    *data << uint32(ammoInventoryType);
2911}
2912
2913void Spell::WriteSpellGoTargets( WorldPacket * data )
2914{
2915    *data << (uint8)m_countOfHit;
2916    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2917        if ((*ihit).missCondition == SPELL_MISS_NONE)       // Add only hits
2918            *data << uint64(ihit->targetGUID);
2919
2920    for(std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin();ighit != m_UniqueGOTargetInfo.end();++ighit)
2921        *data << uint64(ighit->targetGUID);                 // Always hits
2922
2923    *data << (uint8)m_countOfMiss;
2924    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
2925    {
2926        if( ihit->missCondition != SPELL_MISS_NONE )        // Add only miss
2927        {
2928            *data << uint64(ihit->targetGUID);
2929            *data << uint8(ihit->missCondition);
2930            if( ihit->missCondition == SPELL_MISS_REFLECT )
2931                *data << uint8(ihit->reflectResult);
2932        }
2933    }
2934}
2935
2936void Spell::SendLogExecute()
2937{
2938    Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
2939
2940    WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
2941
2942    if(m_caster->GetTypeId() == TYPEID_PLAYER)
2943        data.append(m_caster->GetPackGUID());
2944    else
2945        data.append(target->GetPackGUID());
2946
2947    data << uint32(m_spellInfo->Id);
2948    uint32 count1 = 1;
2949    data << uint32(count1);                                 // count1 (effect count?)
2950    for(uint32 i = 0; i < count1; ++i)
2951    {
2952        data << uint32(m_spellInfo->Effect[0]);             // spell effect?
2953        uint32 count2 = 1;
2954        data << uint32(count2);                             // count2 (target count?)
2955        for(uint32 j = 0; j < count2; ++j)
2956        {
2957            switch(m_spellInfo->Effect[0])
2958            {
2959                case SPELL_EFFECT_POWER_DRAIN:
2960                    if(Unit *unit = m_targets.getUnitTarget())
2961                        data.append(unit->GetPackGUID());
2962                    else
2963                        data << uint8(0);
2964                    data << uint32(0);
2965                    data << uint32(0);
2966                    data << float(0);
2967                    break;
2968                case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
2969                    if(Unit *unit = m_targets.getUnitTarget())
2970                        data.append(unit->GetPackGUID());
2971                    else
2972                        data << uint8(0);
2973                    data << uint32(0);                      // count?
2974                    break;
2975                case SPELL_EFFECT_INTERRUPT_CAST:
2976                    if(Unit *unit = m_targets.getUnitTarget())
2977                        data.append(unit->GetPackGUID());
2978                    else
2979                        data << uint8(0);
2980                    data << uint32(0);                      // spellid
2981                    break;
2982                case SPELL_EFFECT_DURABILITY_DAMAGE:
2983                    if(Unit *unit = m_targets.getUnitTarget())
2984                        data.append(unit->GetPackGUID());
2985                    else
2986                        data << uint8(0);
2987                    data << uint32(0);
2988                    data << uint32(0);
2989                    break;
2990                case SPELL_EFFECT_OPEN_LOCK:
2991                case SPELL_EFFECT_OPEN_LOCK_ITEM:
2992                    if(Item *item = m_targets.getItemTarget())
2993                        data.append(item->GetPackGUID());
2994                    else
2995                        data << uint8(0);
2996                    break;
2997                case SPELL_EFFECT_CREATE_ITEM:
2998                    data << uint32(m_spellInfo->EffectItemType[0]);
2999                    break;
3000                case SPELL_EFFECT_SUMMON:
3001                case SPELL_EFFECT_SUMMON_WILD:
3002                case SPELL_EFFECT_SUMMON_GUARDIAN:
3003                case SPELL_EFFECT_TRANS_DOOR:
3004                case SPELL_EFFECT_SUMMON_PET:
3005                case SPELL_EFFECT_SUMMON_POSSESSED:
3006                case SPELL_EFFECT_SUMMON_TOTEM:
3007                case SPELL_EFFECT_SUMMON_OBJECT_WILD:
3008                case SPELL_EFFECT_CREATE_HOUSE:
3009                case SPELL_EFFECT_DUEL:
3010                case SPELL_EFFECT_SUMMON_TOTEM_SLOT1:
3011                case SPELL_EFFECT_SUMMON_TOTEM_SLOT2:
3012                case SPELL_EFFECT_SUMMON_TOTEM_SLOT3:
3013                case SPELL_EFFECT_SUMMON_TOTEM_SLOT4:
3014                case SPELL_EFFECT_SUMMON_PHANTASM:
3015                case SPELL_EFFECT_SUMMON_CRITTER:
3016                case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
3017                case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
3018                case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
3019                case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
3020                case SPELL_EFFECT_SUMMON_DEMON:
3021                case SPELL_EFFECT_150:
3022                    if(Unit *unit = m_targets.getUnitTarget())
3023                        data.append(unit->GetPackGUID());
3024                    else if(m_targets.getItemTargetGUID())
3025                        data.appendPackGUID(m_targets.getItemTargetGUID());
3026                    else if(GameObject *go = m_targets.getGOTarget())
3027                        data.append(go->GetPackGUID());
3028                    else
3029                        data << uint8(0);                   // guid
3030                    break;
3031                case SPELL_EFFECT_FEED_PET:
3032                    data << uint32(m_targets.getItemTargetEntry());
3033                    break;
3034                case SPELL_EFFECT_DISMISS_PET:
3035                    if(Unit *unit = m_targets.getUnitTarget())
3036                        data.append(unit->GetPackGUID());
3037                    else
3038                        data << uint8(0);
3039                    break;
3040                default:
3041                    return;
3042            }
3043        }
3044    }
3045
3046    m_caster->SendMessageToSet(&data, true);
3047}
3048
3049void Spell::SendInterrupted(uint8 result)
3050{
3051    WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
3052    data.append(m_caster->GetPackGUID());
3053    data << m_spellInfo->Id;
3054    data << result;
3055    m_caster->SendMessageToSet(&data, true);
3056
3057    data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
3058    data.append(m_caster->GetPackGUID());
3059    data << m_spellInfo->Id;
3060    m_caster->SendMessageToSet(&data, true);
3061}
3062
3063void Spell::SendChannelUpdate(uint32 time)
3064{
3065    if(time == 0)
3066    {
3067        m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,0);
3068        m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL,0);
3069    }
3070
3071    if (m_caster->GetTypeId() != TYPEID_PLAYER)
3072        return;
3073
3074    WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
3075    data.append(m_caster->GetPackGUID());
3076    data << time;
3077
3078    ((Player*)m_caster)->GetSession()->SendPacket( &data );
3079}
3080
3081void Spell::SendChannelStart(uint32 duration)
3082{
3083    WorldObject* target = NULL;
3084
3085    // select first not resisted target from target list for _0_ effect
3086    if(!m_UniqueTargetInfo.empty())
3087    {
3088        for(std::list<TargetInfo>::iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
3089        {
3090            if( (itr->effectMask & (1<<0)) && itr->reflectResult==SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
3091            {
3092                target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
3093                break;
3094            }
3095        }
3096    }
3097    else if(!m_UniqueGOTargetInfo.empty())
3098    {
3099        for(std::list<GOTargetInfo>::iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
3100        {
3101            if(itr->effectMask & (1<<0) )
3102            {
3103                target = ObjectAccessor::GetGameObject(*m_caster, itr->targetGUID);
3104                break;
3105            }
3106        }
3107    }
3108
3109    if (m_caster->GetTypeId() == TYPEID_PLAYER)
3110    {
3111        WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
3112        data.append(m_caster->GetPackGUID());
3113        data << m_spellInfo->Id;
3114        data << duration;
3115
3116        ((Player*)m_caster)->GetSession()->SendPacket( &data );
3117    }
3118
3119    m_timer = duration;
3120    if(target)
3121        m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
3122    m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
3123}
3124
3125void Spell::SendResurrectRequest(Player* target)
3126{
3127    WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+2+4));
3128    data << m_caster->GetGUID();
3129    data << uint32(1) << uint16(0) << uint32(1);
3130
3131    target->GetSession()->SendPacket(&data);
3132}
3133
3134void Spell::SendPlaySpellVisual(uint32 SpellID)
3135{
3136    if (m_caster->GetTypeId() != TYPEID_PLAYER)
3137        return;
3138
3139    WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
3140    data << m_caster->GetGUID();
3141    data << SpellID;
3142    ((Player*)m_caster)->GetSession()->SendPacket(&data);
3143}
3144
3145void Spell::TakeCastItem()
3146{
3147    if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
3148        return;
3149
3150    // not remove cast item at triggered spell (equipping, weapon damage, etc)
3151    if(m_IsTriggeredSpell)
3152        return;
3153
3154    ItemPrototype const *proto = m_CastItem->GetProto();
3155
3156    if(!proto)
3157    {
3158        // This code is to avoid a crash
3159        // I'm not sure, if this is really an error, but I guess every item needs a prototype
3160        sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
3161        return;
3162    }
3163
3164    bool expendable = false;
3165    bool withoutCharges = false;
3166
3167    for (int i = 0; i<5; i++)
3168    {
3169        if (proto->Spells[i].SpellId)
3170        {
3171            // item has limited charges
3172            if (proto->Spells[i].SpellCharges)
3173            {
3174                if (proto->Spells[i].SpellCharges < 0)
3175                    expendable = true;
3176
3177                int32 charges = m_CastItem->GetSpellCharges(i);
3178
3179                // item has charges left
3180                if (charges)
3181                {
3182                    (charges > 0) ? --charges : ++charges;  // abs(charges) less at 1 after use
3183                    if (proto->Stackable < 2)
3184                        m_CastItem->SetSpellCharges(i, charges);
3185                    m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
3186                }
3187
3188                // all charges used
3189                withoutCharges = (charges == 0);
3190            }
3191        }
3192    }
3193
3194    if (expendable && withoutCharges)
3195    {
3196        uint32 count = 1;
3197        ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
3198
3199        // prevent crash at access to deleted m_targets.getItemTarget
3200        if(m_CastItem==m_targets.getItemTarget())
3201            m_targets.setItemTarget(NULL);
3202
3203        m_CastItem = NULL;
3204    }
3205}
3206
3207void Spell::TakePower()
3208{
3209    if(m_CastItem || m_triggeredByAuraSpell)
3210        return;
3211
3212    // health as power used
3213    if(m_spellInfo->powerType == POWER_HEALTH)
3214    {
3215        m_caster->ModifyHealth( -(int32)m_powerCost );
3216        return;
3217    }
3218
3219    if(m_spellInfo->powerType >= MAX_POWERS)
3220    {
3221        sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
3222        return;
3223    }
3224
3225    Powers powerType = Powers(m_spellInfo->powerType);
3226
3227    m_caster->ModifyPower(powerType, -(int32)m_powerCost);
3228
3229    // Set the five second timer
3230    if (powerType == POWER_MANA && m_powerCost > 0)
3231        m_caster->SetLastManaUse(getMSTime());
3232}
3233
3234void Spell::TakeReagents()
3235{
3236    if(m_IsTriggeredSpell)                                  // reagents used in triggered spell removed by original spell or don't must be removed.
3237        return;
3238
3239    if (m_caster->GetTypeId() != TYPEID_PLAYER)
3240        return;
3241
3242    if (m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
3243        m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
3244        return;
3245
3246    Player* p_caster = (Player*)m_caster;
3247
3248    for(uint32 x=0;x<8;x++)
3249    {
3250        if(m_spellInfo->Reagent[x] <= 0)
3251            continue;
3252
3253        uint32 itemid = m_spellInfo->Reagent[x];
3254        uint32 itemcount = m_spellInfo->ReagentCount[x];
3255
3256        // if CastItem is also spell reagent
3257        if (m_CastItem)
3258        {
3259            ItemPrototype const *proto = m_CastItem->GetProto();
3260            if( proto && proto->ItemId == itemid )
3261            {
3262                for(int s=0;s<5;s++)
3263                {
3264                    // CastItem will be used up and does not count as reagent
3265                    int32 charges = m_CastItem->GetSpellCharges(s);
3266                    if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
3267                    {
3268                        ++itemcount;
3269                        break;
3270                    }
3271                }
3272
3273                m_CastItem = NULL;
3274            }
3275        }
3276
3277        // if getItemTarget is also spell reagent
3278        if (m_targets.getItemTargetEntry()==itemid)
3279            m_targets.setItemTarget(NULL);
3280
3281        p_caster->DestroyItemCount(itemid, itemcount, true);
3282    }
3283}
3284
3285void Spell::HandleThreatSpells(uint32 spellId)
3286{
3287    if(!m_targets.getUnitTarget() || !spellId)
3288        return;
3289
3290    if(!m_targets.getUnitTarget()->CanHaveThreatList())
3291        return;
3292
3293    SpellThreatEntry const *threatSpell = sSpellThreatStore.LookupEntry<SpellThreatEntry>(spellId);
3294    if(!threatSpell)
3295        return;
3296
3297    m_targets.getUnitTarget()->AddThreat(m_caster, float(threatSpell->threat));
3298
3299    DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threatSpell->threat);
3300}
3301
3302void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i, float DamageMultiplier)
3303{
3304    unitTarget = pUnitTarget;
3305    itemTarget = pItemTarget;
3306    gameObjTarget = pGOTarget;
3307
3308    uint8 eff = m_spellInfo->Effect[i];
3309    uint32 mechanic = m_spellInfo->EffectMechanic[i];
3310
3311    damage = int32(CalculateDamage((uint8)i,unitTarget)*DamageMultiplier);
3312
3313    sLog.outDebug( "Spell: Effect : %u", eff);
3314
3315    //Simply return. Do not display "immune" in red text on client
3316    if(unitTarget && unitTarget->IsImmunedToSpellEffect(eff, mechanic))
3317        return;
3318
3319    if(eff<TOTAL_SPELL_EFFECTS)
3320    {
3321        //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
3322        (*this.*SpellEffects[eff])(i);
3323    }
3324    /*
3325    else
3326    {
3327        sLog.outDebug( "WORLD: Spell FX %d > TOTAL_SPELL_EFFECTS ", eff);
3328        if (m_CastItem)
3329            EffectEnchantItemTmp(i);
3330        else
3331        {
3332            sLog.outError("SPELL: unknown effect %u spell id %u\n",
3333                eff, m_spellInfo->Id);
3334        }
3335    }
3336    */
3337}
3338
3339void Spell::TriggerSpell()
3340{
3341    for(TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
3342    {
3343        Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer);
3344        spell->prepare(&m_targets);                         // use original spell original targets
3345    }
3346}
3347
3348uint8 Spell::CanCast(bool strict)
3349{
3350    // check cooldowns to prevent cheating
3351    if(m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
3352    {
3353        if(m_triggeredByAuraSpell)
3354            return SPELL_FAILED_DONT_REPORT;
3355        else
3356            return SPELL_FAILED_NOT_READY;
3357    }
3358
3359    // only allow triggered spells if at an ended battleground
3360    if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
3361        if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
3362            if(bg->GetStatus() == STATUS_WAIT_LEAVE)
3363                return SPELL_FAILED_DONT_REPORT;
3364
3365    // only check at first call, Stealth auras are already removed at second call
3366    // for now, ignore triggered spells
3367    if( strict && !m_IsTriggeredSpell)
3368    {
3369        // Cannot be used in this stance/form
3370        if(uint8 shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form))
3371            return shapeError;
3372
3373        if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
3374            return SPELL_FAILED_ONLY_STEALTHED;
3375    }
3376
3377    // caster state requirements
3378    if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState)))
3379        return SPELL_FAILED_CASTER_AURASTATE;
3380    if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot)))
3381        return SPELL_FAILED_CASTER_AURASTATE;
3382
3383    // cancel autorepeat spells if cast start when moving
3384    // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
3385    if( m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
3386    {
3387        // skip stuck spell to allow use it in falling case and apply spell limitations at movement
3388        if( (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
3389            (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
3390            return SPELL_FAILED_MOVING;
3391    }
3392
3393    Unit *target = m_targets.getUnitTarget();
3394
3395    if(target)
3396    {
3397        // target state requirements (not allowed state), apply to self also
3398        if(m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot)))
3399            return SPELL_FAILED_TARGET_AURASTATE;
3400
3401        if(target != m_caster)
3402        {
3403            // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
3404            if(m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState)))
3405                return SPELL_FAILED_TARGET_AURASTATE;
3406
3407            // Not allow casting on flying player
3408            if (target->isInFlight())
3409                return SPELL_FAILED_BAD_TARGETS;
3410
3411            if(VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
3412                return SPELL_FAILED_LINE_OF_SIGHT;
3413
3414            // auto selection spell rank implemented in WorldSession::HandleCastSpellOpcode
3415            // this case can be triggered if rank not found (too low-level target for first rank)
3416            if(m_caster->GetTypeId() == TYPEID_PLAYER && !IsPassiveSpell(m_spellInfo->Id) && !m_CastItem)
3417            {
3418                for(int i=0;i<3;i++)
3419                {
3420                    if(IsPositiveEffect(m_spellInfo->Id, i) && m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
3421                        if(target->getLevel() + 10 < m_spellInfo->spellLevel)
3422                            return SPELL_FAILED_LOWLEVEL;
3423                }
3424            }
3425        }
3426
3427        // check pet presents
3428        for(int j=0;j<3;j++)
3429        {
3430            if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_PET)
3431            {
3432                target = m_caster->GetPet();
3433                if(!target)
3434                {
3435                    if(m_triggeredByAuraSpell)              // not report pet not existence for triggered spells
3436                        return SPELL_FAILED_DONT_REPORT;
3437                    else
3438                        return SPELL_FAILED_NO_PET;
3439                }
3440                break;
3441            }
3442        }
3443
3444        //check creature type
3445        //ignore self casts (including area casts when caster selected as target)
3446        if(target != m_caster)
3447        {
3448            if(!CheckTargetCreatureType(target))
3449            {
3450                if(target->GetTypeId()==TYPEID_PLAYER)
3451                    return SPELL_FAILED_TARGET_IS_PLAYER;
3452                else
3453                    return SPELL_FAILED_BAD_TARGETS;
3454            }
3455        }
3456
3457        // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
3458        // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
3459        if(m_caster != target && m_caster->GetTypeId()==TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
3460        {
3461            // check correctness positive/negative cast target (pet cast real check and cheating check)
3462            if(IsPositiveSpell(m_spellInfo->Id))
3463            {
3464                if(m_caster->IsHostileTo(target))
3465                    return SPELL_FAILED_BAD_TARGETS;
3466            }
3467            else
3468            {
3469                if(m_caster->IsFriendlyTo(target))
3470                    return SPELL_FAILED_BAD_TARGETS;
3471            }
3472        }
3473
3474        if(IsPositiveSpell(m_spellInfo->Id))
3475        {
3476            if(target->IsImmunedToSpell(m_spellInfo,false))
3477                return SPELL_FAILED_TARGET_AURASTATE;
3478        }
3479
3480        //Must be behind the target.
3481        if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster) )
3482        {
3483            SendInterrupted(2);
3484            return SPELL_FAILED_NOT_BEHIND;
3485        }
3486
3487        //Target must be facing you.
3488        if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
3489        {
3490            SendInterrupted(2);
3491            return SPELL_FAILED_NOT_INFRONT;
3492        }
3493
3494        // check if target is in combat
3495        if (target != m_caster && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
3496        {
3497            return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
3498        }
3499    }
3500    // Spell casted only on battleground
3501    if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) &&  m_caster->GetTypeId()==TYPEID_PLAYER)
3502        if(!((Player*)m_caster)->InBattleGround())
3503            return SPELL_FAILED_ONLY_BATTLEGROUNDS;
3504
3505    // do not allow spells to be cast in arenas
3506    // - with greater than 15 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
3507    // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
3508    if( (m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
3509        GetSpellRecoveryTime(m_spellInfo) > 15 * MINUTE * 1000 && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA) )
3510        if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
3511            if(mapEntry->IsBattleArena())
3512                return SPELL_FAILED_NOT_IN_ARENA;
3513
3514    // zone check
3515    if(!IsSpellAllowedInLocation(m_spellInfo,m_caster->GetMapId(),m_caster->GetZoneId(),m_caster->GetAreaId()))
3516        return SPELL_FAILED_REQUIRES_AREA;
3517
3518    // not let players cast spells at mount (and let do it to creatures)
3519    if( m_caster->IsMounted() && m_caster->GetTypeId()==TYPEID_PLAYER && !m_IsTriggeredSpell &&
3520        !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED) )
3521    {
3522        if(m_caster->isInFlight())
3523            return SPELL_FAILED_NOT_FLYING;
3524        else
3525            return SPELL_FAILED_NOT_MOUNTED;
3526    }
3527
3528    // always (except passive spells) check items (focus object can be required for any type casts)
3529    if(!IsPassiveSpell(m_spellInfo->Id))
3530        if(uint8 castResult = CheckItems())
3531            return castResult;
3532
3533    if(uint8 castResult = CheckRange(strict))
3534        return castResult;
3535
3536    {
3537        if(uint8 castResult = CheckPower())
3538            return castResult;
3539    }
3540
3541    if(!m_triggeredByAuraSpell)                             // triggered spell not affected by stun/etc
3542        if(uint8 castResult = CheckCasterAuras())
3543            return castResult;
3544
3545    for (int i = 0; i < 3; i++)
3546    {
3547        // for effects of spells that have only one target
3548        switch(m_spellInfo->Effect[i])
3549        {
3550            case SPELL_EFFECT_DUMMY:
3551            {
3552                if(m_spellInfo->SpellIconID == 1648)        // Execute
3553                {
3554                    if(!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3555                        return SPELL_FAILED_BAD_TARGETS;
3556                }
3557                else if (m_spellInfo->Id == 51582)          // Rocket Boots Engaged
3558                {
3559                    if(m_caster->IsInWater())
3560                        return SPELL_FAILED_ONLY_ABOVEWATER;
3561                }
3562                else if(m_spellInfo->SpellIconID==156)      // Holy Shock
3563                {
3564                    // spell different for friends and enemies
3565                    // hart version required facing
3566                    if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, target ))
3567                        return SPELL_FAILED_UNIT_NOT_INFRONT;
3568                }
3569                break;
3570            }
3571            case SPELL_EFFECT_SCHOOL_DAMAGE:
3572            {
3573                // Hammer of Wrath
3574                if(m_spellInfo->SpellVisual == 7250)
3575                {
3576                    if (!m_targets.getUnitTarget())
3577                        return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3578
3579                    if(m_targets.getUnitTarget()->GetHealth() > m_targets.getUnitTarget()->GetMaxHealth()*0.2)
3580                        return SPELL_FAILED_BAD_TARGETS;
3581                }
3582                break;
3583            }
3584            case SPELL_EFFECT_LEARN_SPELL:
3585            {
3586                if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_PET)
3587                    break;
3588
3589                Pet* pet = m_caster->GetPet();
3590
3591                if(!pet)
3592                    return SPELL_FAILED_NO_PET;
3593
3594                SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3595
3596                if(!learn_spellproto)
3597                    return SPELL_FAILED_NOT_KNOWN;
3598
3599                if(!pet->CanTakeMoreActiveSpells(learn_spellproto->Id))
3600                    return SPELL_FAILED_TOO_MANY_SKILLS;
3601
3602                if(m_spellInfo->spellLevel > pet->getLevel())
3603                    return SPELL_FAILED_LOWLEVEL;
3604
3605                if(!pet->HasTPForSpell(learn_spellproto->Id))
3606                    return SPELL_FAILED_TRAINING_POINTS;
3607
3608                break;
3609            }
3610            case SPELL_EFFECT_LEARN_PET_SPELL:
3611            {
3612                Pet* pet = m_caster->GetPet();
3613
3614                if(!pet)
3615                    return SPELL_FAILED_NO_PET;
3616
3617                SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
3618
3619                if(!learn_spellproto)
3620                    return SPELL_FAILED_NOT_KNOWN;
3621
3622                if(!pet->CanTakeMoreActiveSpells(learn_spellproto->Id))
3623                    return SPELL_FAILED_TOO_MANY_SKILLS;
3624
3625                if(m_spellInfo->spellLevel > pet->getLevel())
3626                    return SPELL_FAILED_LOWLEVEL;
3627
3628                if(!pet->HasTPForSpell(learn_spellproto->Id))
3629                    return SPELL_FAILED_TRAINING_POINTS;
3630
3631                break;
3632            }
3633            case SPELL_EFFECT_FEED_PET:
3634            {
3635                if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getItemTarget() )
3636                    return SPELL_FAILED_BAD_TARGETS;
3637
3638                Pet* pet = m_caster->GetPet();
3639
3640                if(!pet)
3641                    return SPELL_FAILED_NO_PET;
3642
3643                if(!pet->HaveInDiet(m_targets.getItemTarget()->GetProto()))
3644                    return SPELL_FAILED_WRONG_PET_FOOD;
3645
3646                if(!pet->GetCurrentFoodBenefitLevel(m_targets.getItemTarget()->GetProto()->ItemLevel))
3647                    return SPELL_FAILED_FOOD_LOWLEVEL;
3648
3649                if(m_caster->isInCombat() || pet->isInCombat())
3650                    return SPELL_FAILED_AFFECTING_COMBAT;
3651
3652                break;
3653            }
3654            case SPELL_EFFECT_POWER_BURN:
3655            case SPELL_EFFECT_POWER_DRAIN:
3656            {
3657                // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
3658                if(m_caster->GetTypeId() == TYPEID_PLAYER)
3659                    if(Unit* target = m_targets.getUnitTarget())
3660                        if(target!=m_caster && target->getPowerType()!=m_spellInfo->EffectMiscValue[i])
3661                            return SPELL_FAILED_BAD_TARGETS;
3662                break;
3663            }
3664            case SPELL_EFFECT_CHARGE:
3665            {
3666                if (m_caster->hasUnitState(UNIT_STAT_ROOT))
3667                    return SPELL_FAILED_ROOTED;
3668
3669                break;
3670            }
3671            case SPELL_EFFECT_SKINNING:
3672            {
3673                if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
3674                    return SPELL_FAILED_BAD_TARGETS;
3675
3676                if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
3677                    return SPELL_FAILED_TARGET_UNSKINNABLE;
3678
3679                Creature* creature = (Creature*)m_targets.getUnitTarget();
3680                if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
3681                {
3682                    return SPELL_FAILED_TARGET_NOT_LOOTED;
3683                }
3684
3685                uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
3686
3687                int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
3688                int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
3689                int32 ReqValue = (skillValue < 100 ? (TargetLevel-10)*10 : TargetLevel*5);
3690                if (ReqValue > skillValue)
3691                    return SPELL_FAILED_LOW_CASTLEVEL;
3692
3693                // chance for fail at orange skinning attempt
3694                if( (m_selfContainer && (*m_selfContainer) == this) &&
3695                    skillValue < sWorld.GetConfigMaxSkillValue() &&
3696                    (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue-25, skillValue+37) )
3697                    return SPELL_FAILED_TRY_AGAIN;
3698
3699                break;
3700            }
3701            case SPELL_EFFECT_OPEN_LOCK_ITEM:
3702            case SPELL_EFFECT_OPEN_LOCK:
3703            {
3704                if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
3705                    m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
3706                    break;
3707
3708                if( m_caster->GetTypeId() != TYPEID_PLAYER  // only players can open locks, gather etc.
3709                    // we need a go target in case of TARGET_GAMEOBJECT
3710                    || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
3711                    // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
3712                    || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
3713                    (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
3714                    return SPELL_FAILED_BAD_TARGETS;
3715
3716                // In BattleGround players can use only flags and banners
3717                if( ((Player*)m_caster)->InBattleGround() &&
3718                    !((Player*)m_caster)->isAllowUseBattleGroundObject() )
3719                    return SPELL_FAILED_TRY_AGAIN;
3720
3721                // get the lock entry
3722                LockEntry const *lockInfo = NULL;
3723                if (GameObject* go=m_targets.getGOTarget())
3724                    lockInfo = sLockStore.LookupEntry(go->GetLockId());
3725                else if(Item* itm=m_targets.getItemTarget())
3726                    lockInfo = sLockStore.LookupEntry(itm->GetProto()->LockID);
3727
3728                // check lock compatibility
3729                if (lockInfo)
3730                {
3731                    // check for lock - key pair (checked by client also, just prevent cheating
3732                    bool ok_key = false;
3733                    for(int it = 0; it < 5; ++it)
3734                    {
3735                        switch(lockInfo->keytype[it])
3736                        {
3737                            case LOCK_KEY_NONE:
3738                                break;
3739                            case LOCK_KEY_ITEM:
3740                            {
3741                                if(lockInfo->key[it])
3742                                {
3743                                    if(m_CastItem && m_CastItem->GetEntry()==lockInfo->key[it])
3744                                        ok_key =true;
3745                                    break;
3746                                }
3747                            }
3748                            case LOCK_KEY_SKILL:
3749                            {
3750                                if(uint32(m_spellInfo->EffectMiscValue[i])!=lockInfo->key[it])
3751                                    break;
3752
3753                                switch(lockInfo->key[it])
3754                                {
3755                                    case LOCKTYPE_HERBALISM:
3756                                        if(((Player*)m_caster)->HasSkill(SKILL_HERBALISM))
3757                                            ok_key =true;
3758                                        break;
3759                                    case LOCKTYPE_MINING:
3760                                        if(((Player*)m_caster)->HasSkill(SKILL_MINING))
3761                                            ok_key =true;
3762                                        break;
3763                                    default:
3764                                        ok_key =true;
3765                                        break;
3766                                }
3767                            }
3768                        }
3769                        if(ok_key)
3770                            break;
3771                    }
3772
3773                    if(!ok_key)
3774                        return SPELL_FAILED_BAD_TARGETS;
3775                }
3776
3777                // chance for fail at orange mining/herb/LockPicking gathering attempt
3778                if (!m_selfContainer || ((*m_selfContainer) != this))
3779                    break;
3780
3781                // get the skill value of the player
3782                int32 SkillValue = 0;
3783                bool canFailAtMax = true;
3784                if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_HERBALISM)
3785                {
3786                    SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_HERBALISM);
3787                    canFailAtMax = false;
3788                }
3789                else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_MINING)
3790                {
3791                    SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_MINING);
3792                    canFailAtMax = false;
3793                }
3794                else if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3795                    SkillValue = ((Player*)m_caster)->GetSkillValue(SKILL_LOCKPICKING);
3796
3797                // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
3798                if(m_CastItem)
3799                    SkillValue = 0;
3800
3801                // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
3802                SkillValue += m_currentBasePoints[i]+1;
3803
3804                // get the required lock value
3805                int32 ReqValue=0;
3806                if (lockInfo)
3807                {
3808                    // check for lock - key pair
3809                    bool ok = false;
3810                    for(int it = 0; it < 5; ++it)
3811                    {
3812                        if(lockInfo->keytype[it]==LOCK_KEY_ITEM && lockInfo->key[it] && m_CastItem && m_CastItem->GetEntry()==lockInfo->key[it])
3813                        {
3814                            // if so, we're good to go
3815                            ok = true;
3816                            break;
3817                        }
3818                    }
3819                    if(ok)
3820                        break;
3821
3822                    if (m_spellInfo->EffectMiscValue[i] == LOCKTYPE_PICKLOCK)
3823                        ReqValue = lockInfo->requiredlockskill;
3824                    else
3825                        ReqValue = lockInfo->requiredminingskill;
3826                }
3827
3828                // skill doesn't meet the required value
3829                if (ReqValue > SkillValue)
3830                    return SPELL_FAILED_LOW_CASTLEVEL;
3831
3832                // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
3833                if((canFailAtMax || SkillValue < sWorld.GetConfigMaxSkillValue()) && ReqValue > irand(SkillValue-25, SkillValue+37))
3834                    return SPELL_FAILED_TRY_AGAIN;
3835
3836                break;
3837            }
3838            case SPELL_EFFECT_SUMMON_DEAD_PET:
3839            {
3840                Creature *pet = m_caster->GetPet();
3841                if(!pet)
3842                    return SPELL_FAILED_NO_PET;
3843
3844                if(pet->isAlive())
3845                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3846
3847                break;
3848            }
3849            // This is generic summon effect now and don't make this check for summon types similar
3850            // SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3851            // These won't show up in m_caster->GetPetGUID()
3852            case SPELL_EFFECT_SUMMON:
3853            {
3854                switch(m_spellInfo->EffectMiscValueB[i])
3855                {
3856                    case SUMMON_TYPE_POSESSED:
3857                    case SUMMON_TYPE_POSESSED2:
3858                    case SUMMON_TYPE_DEMON:
3859                    case SUMMON_TYPE_SUMMON:
3860                    {
3861                        if(m_caster->GetPetGUID())
3862                            return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3863
3864                        if(m_caster->GetCharmGUID())
3865                            return SPELL_FAILED_ALREADY_HAVE_CHARM;
3866                        break;
3867                    }
3868                }
3869                break;
3870            }
3871            // Don't make this check for SPELL_EFFECT_SUMMON_CRITTER, SPELL_EFFECT_SUMMON_WILD or SPELL_EFFECT_SUMMON_GUARDIAN.
3872            // These won't show up in m_caster->GetPetGUID()
3873            case SPELL_EFFECT_SUMMON_POSSESSED:
3874            case SPELL_EFFECT_SUMMON_PHANTASM:
3875            case SPELL_EFFECT_SUMMON_DEMON:
3876            {
3877                if(m_caster->GetPetGUID())
3878                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3879
3880                if(m_caster->GetCharmGUID())
3881                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3882
3883                break;
3884            }
3885            case SPELL_EFFECT_SUMMON_PET:
3886            {
3887                if(m_caster->GetPetGUID())                  //let warlock do a replacement summon
3888                {
3889
3890                    Pet* pet = ((Player*)m_caster)->GetPet();
3891
3892                    if (m_caster->GetTypeId()==TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
3893                    {
3894                        if (strict)                         //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
3895                            pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
3896                    }
3897                    else
3898                        return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3899                }
3900
3901                if(m_caster->GetCharmGUID())
3902                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3903
3904                break;
3905            }
3906            case SPELL_EFFECT_SUMMON_PLAYER:
3907            {
3908                if(m_caster->GetTypeId()!=TYPEID_PLAYER)
3909                    return SPELL_FAILED_BAD_TARGETS;
3910                if(!((Player*)m_caster)->GetSelection())
3911                    return SPELL_FAILED_BAD_TARGETS;
3912
3913                Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
3914                if( !target || ((Player*)m_caster)==target || !target->IsInSameRaidWith((Player*)m_caster) )
3915                    return SPELL_FAILED_BAD_TARGETS;
3916
3917                // check if our map is dungeon
3918                if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
3919                {
3920                    InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
3921                    if(!instance)
3922                        return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
3923                    if ( instance->levelMin > target->getLevel() )
3924                        return SPELL_FAILED_LOWLEVEL;
3925                    if ( instance->levelMax && instance->levelMax < target->getLevel() )
3926                        return SPELL_FAILED_HIGHLEVEL;
3927                }
3928                break;
3929            }
3930            case SPELL_EFFECT_LEAP:
3931            case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
3932            {
3933                float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
3934                float fx = m_caster->GetPositionX() + dis * cos(m_caster->GetOrientation());
3935                float fy = m_caster->GetPositionY() + dis * sin(m_caster->GetOrientation());
3936                // teleport a bit above terrain level to avoid falling below it
3937                float fz = MapManager::Instance().GetBaseMap(m_caster->GetMapId())->GetHeight(fx,fy,m_caster->GetPositionZ(),true);
3938                if(fz <= INVALID_HEIGHT)                    // note: this also will prevent use effect in instances without vmaps height enabled
3939                    return SPELL_FAILED_TRY_AGAIN;
3940
3941                float caster_pos_z = m_caster->GetPositionZ();
3942                // Control the caster to not climb or drop when +-fz > 8
3943                if(!(fz<=caster_pos_z+8 && fz>=caster_pos_z-8))
3944                    return SPELL_FAILED_TRY_AGAIN;
3945
3946                // not allow use this effect at battleground until battleground start
3947                if(m_caster->GetTypeId()==TYPEID_PLAYER)
3948                    if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
3949                        if(bg->GetStatus() != STATUS_IN_PROGRESS)
3950                            return SPELL_FAILED_TRY_AGAIN;
3951                break;
3952            }
3953            case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
3954            {
3955                if (m_targets.getUnitTarget()==m_caster)
3956                    return SPELL_FAILED_BAD_TARGETS;
3957                break;
3958            }
3959            default:break;
3960        }
3961    }
3962
3963    for (int i = 0; i < 3; i++)
3964    {
3965        switch(m_spellInfo->EffectApplyAuraName[i])
3966        {
3967            case SPELL_AURA_DUMMY:
3968            {
3969                if(m_spellInfo->Id == 1515)
3970                {
3971                    if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
3972                        return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
3973
3974                    if (m_targets.getUnitTarget()->getLevel() > m_caster->getLevel())
3975                        return SPELL_FAILED_HIGHLEVEL;
3976
3977                    // use SMSG_PET_TAME_FAILURE?
3978                    if (!((Creature*)m_targets.getUnitTarget())->GetCreatureInfo()->isTameable ())
3979                        return SPELL_FAILED_BAD_TARGETS;
3980
3981                    if(m_caster->GetPetGUID())
3982                        return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3983
3984                    if(m_caster->GetCharmGUID())
3985                        return SPELL_FAILED_ALREADY_HAVE_CHARM;
3986                }
3987            }break;
3988            case SPELL_AURA_MOD_POSSESS:
3989            case SPELL_AURA_MOD_CHARM:
3990            {
3991                if(m_caster->GetPetGUID())
3992                    return SPELL_FAILED_ALREADY_HAVE_SUMMON;
3993
3994                if(m_caster->GetCharmGUID())
3995                    return SPELL_FAILED_ALREADY_HAVE_CHARM;
3996
3997                if(m_caster->GetCharmerGUID())
3998                    return SPELL_FAILED_CHARMED;
3999
4000                if(!m_targets.getUnitTarget())
4001                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4002
4003                if(m_targets.getUnitTarget()->GetCharmerGUID())
4004                    return SPELL_FAILED_CHARMED;
4005
4006                if(int32(m_targets.getUnitTarget()->getLevel()) > CalculateDamage(i,m_targets.getUnitTarget()))
4007                    return SPELL_FAILED_HIGHLEVEL;
4008            };break;
4009            case SPELL_AURA_MOUNTED:
4010            {
4011                if (m_caster->IsInWater())
4012                    return SPELL_FAILED_ONLY_ABOVEWATER;
4013
4014                if (m_caster->GetTypeId()==TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
4015                    return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4016
4017                // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
4018                if (m_caster->GetTypeId()==TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaId)
4019                    return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4020
4021                if (m_caster->GetAreaId()==35)
4022                    return SPELL_FAILED_NO_MOUNTS_ALLOWED;
4023
4024                ShapeshiftForm form = m_caster->m_form;
4025                if( form == FORM_CAT          || form == FORM_TREE      || form == FORM_TRAVEL   ||
4026                    form == FORM_AQUA         || form == FORM_BEAR      || form == FORM_DIREBEAR ||
4027                    form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT   ||
4028                    form == FORM_FLIGHT_EPIC  || form == FORM_MOONKIN )
4029                    return SPELL_FAILED_NOT_SHAPESHIFT;
4030
4031                break;
4032            }
4033            case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
4034            {
4035                if(!m_targets.getUnitTarget())
4036                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4037
4038                // can be casted at non-friendly unit or own pet/charm
4039                if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
4040                    return SPELL_FAILED_TARGET_FRIENDLY;
4041            };break;
4042            case SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED:
4043            case SPELL_AURA_FLY:
4044            {
4045                // not allow cast fly spells at old maps by players (all spells is self target)
4046                if(m_caster->GetTypeId()==TYPEID_PLAYER)
4047                {
4048                    if( !((Player*)m_caster)->isGameMaster() &&
4049                        GetVirtualMapForMapAndZone(m_caster->GetMapId(),m_caster->GetZoneId()) != 530)
4050                        return SPELL_FAILED_NOT_HERE;
4051                }
4052            };break;
4053            case SPELL_AURA_PERIODIC_MANA_LEECH:
4054            {
4055                if (!m_targets.getUnitTarget())
4056                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4057
4058                if (m_caster->GetTypeId()!=TYPEID_PLAYER || m_CastItem)
4059                    break;
4060
4061                if(m_targets.getUnitTarget()->getPowerType()!=POWER_MANA)
4062                    return SPELL_FAILED_BAD_TARGETS;
4063                break;
4064            }
4065            default:break;
4066        }
4067    }
4068
4069    // all ok
4070    return 0;
4071}
4072
4073int16 Spell::PetCanCast(Unit* target)
4074{
4075    if(!m_caster->isAlive())
4076        return SPELL_FAILED_CASTER_DEAD;
4077
4078    if(m_caster->IsNonMeleeSpellCasted(false))              //prevent spellcast interruption by another spellcast
4079        return SPELL_FAILED_SPELL_IN_PROGRESS;
4080    if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
4081        return SPELL_FAILED_AFFECTING_COMBAT;
4082
4083    if(m_caster->GetTypeId()==TYPEID_UNIT && (((Creature*)m_caster)->isPet() || m_caster->isCharmed()))
4084    {
4085                                                            //dead owner (pets still alive when owners ressed?)
4086        if(m_caster->GetCharmerOrOwner() && !m_caster->GetCharmerOrOwner()->isAlive())
4087            return SPELL_FAILED_CASTER_DEAD;
4088
4089        if(!target && m_targets.getUnitTarget())
4090            target = m_targets.getUnitTarget();
4091
4092        bool need = false;
4093        for(uint32 i = 0;i<3;i++)
4094        {
4095            if(m_spellInfo->EffectImplicitTargetA[i] == TARGET_CHAIN_DAMAGE || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_FRIEND || m_spellInfo->EffectImplicitTargetA[i] == TARGET_DUELVSPLAYER || m_spellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_PARTY || m_spellInfo->EffectImplicitTargetA[i] == TARGET_CURRENT_ENEMY_COORDINATES)
4096            {
4097                need = true;
4098                if(!target)
4099                    return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
4100                break;
4101            }
4102        }
4103        if(need)
4104            m_targets.setUnitTarget(target);
4105
4106        Unit* _target = m_targets.getUnitTarget();
4107
4108        if(_target)                                         //for target dead/target not valid
4109        {
4110            if(!_target->isAlive())
4111                return SPELL_FAILED_BAD_TARGETS;
4112
4113            if(IsPositiveSpell(m_spellInfo->Id))
4114            {
4115                if(m_caster->IsHostileTo(_target))
4116                    return SPELL_FAILED_BAD_TARGETS;
4117            }
4118            else
4119            {
4120                bool duelvsplayertar = false;
4121                for(int j=0;j<3;j++)
4122                {
4123                                                            //TARGET_DUELVSPLAYER is positive AND negative
4124                    duelvsplayertar |= (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER);
4125                }
4126                // AoE spells have the caster as their target
4127                if(m_caster->IsFriendlyTo(target) && m_caster != target && !duelvsplayertar)
4128                {
4129                    return SPELL_FAILED_BAD_TARGETS;
4130                }
4131            }
4132        }
4133                                                            //cooldown
4134        if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
4135            return SPELL_FAILED_NOT_READY;
4136    }
4137
4138    uint16 result = CanCast(true);
4139    if(result != 0)
4140        return result;
4141    else
4142        return -1;                                          //this allows to check spell fail 0, in combat
4143}
4144
4145uint8 Spell::CheckCasterAuras() const
4146{
4147    // Flag drop spells totally immuned to caster auras
4148    // FIXME: find more nice check for all totally immuned spells
4149    // AttributesEx3 & 0x10000000?
4150    if(m_spellInfo->Id==23336 || m_spellInfo->Id==23334 || m_spellInfo->Id==34991)
4151        return 0;
4152
4153    uint8 school_immune = 0;
4154    uint32 mechanic_immune = 0;
4155    uint32 dispel_immune = 0;
4156
4157    //Check if the spell grants school or mechanic immunity.
4158    //We use bitmasks so the loop is done only once and not on every aura check below.
4159    if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
4160    {
4161        for(int i = 0;i < 3; i ++)
4162        {
4163            if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
4164                school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
4165            else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
4166                mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
4167            else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
4168                dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
4169        }
4170        //immune movement impairment and loss of control
4171        if(m_spellInfo->Id==(uint32)42292)
4172            mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
4173    }
4174
4175    //Check whether the cast should be prevented by any state you might have.
4176    uint8 prevented_reason = 0;
4177    // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
4178    if(!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED) && m_caster->HasAuraType(SPELL_AURA_MOD_STUN))
4179        prevented_reason = SPELL_FAILED_STUNNED;
4180    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4181        prevented_reason = SPELL_FAILED_CONFUSED;
4182    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING) && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4183        prevented_reason = SPELL_FAILED_FLEEING;
4184    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4185        prevented_reason = SPELL_FAILED_SILENCED;
4186    else if(m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) && m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4187        prevented_reason = SPELL_FAILED_PACIFIED;
4188
4189    // Attr must make flag drop spell totally immuned from all effects
4190    if(prevented_reason)
4191    {
4192        if(school_immune || mechanic_immune || dispel_immune)
4193        {
4194            //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
4195            Unit::AuraMap const& auras = m_caster->GetAuras();
4196            for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); itr++)
4197            {
4198                if(itr->second)
4199                {
4200                    if( GetSpellMechanicMask(itr->second->GetSpellProto(), itr->second->GetEffIndex()) & mechanic_immune )
4201                        continue;
4202                    if( GetSpellSchoolMask(itr->second->GetSpellProto()) & school_immune )
4203                        continue;
4204                    if( (1<<(itr->second->GetSpellProto()->Dispel)) & dispel_immune)
4205                        continue;
4206
4207                    //Make a second check for spell failed so the right SPELL_FAILED message is returned.
4208                    //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
4209                    switch(itr->second->GetModifier()->m_auraname)
4210                    {
4211                        case SPELL_AURA_MOD_STUN:
4212                            if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
4213                                return SPELL_FAILED_STUNNED;
4214                            break;
4215                        case SPELL_AURA_MOD_CONFUSE:
4216                            if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
4217                                return SPELL_FAILED_CONFUSED;
4218                            break;
4219                        case SPELL_AURA_MOD_FEAR:
4220                            if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
4221                                return SPELL_FAILED_FLEEING;
4222                            break;
4223                        case SPELL_AURA_MOD_SILENCE:
4224                        case SPELL_AURA_MOD_PACIFY:
4225                        case SPELL_AURA_MOD_PACIFY_SILENCE:
4226                            if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
4227                                return SPELL_FAILED_PACIFIED;
4228                            else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
4229                                return SPELL_FAILED_SILENCED;
4230                            break;
4231                    }
4232                }
4233            }
4234        }
4235        //You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
4236        else
4237            return prevented_reason;
4238    }
4239    return 0;                                               // all ok
4240}
4241
4242bool Spell::CanAutoCast(Unit* target)
4243{
4244    uint64 targetguid = target->GetGUID();
4245
4246    for(uint32 j = 0;j<3;j++)
4247    {
4248        if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
4249        {
4250            if( m_spellInfo->StackAmount <= 1)
4251            {
4252                if( target->HasAura(m_spellInfo->Id, j) )
4253                    return false;
4254            }
4255            else
4256            {
4257                if( target->GetAuras().count(Unit::spellEffectPair(m_spellInfo->Id, j)) >= m_spellInfo->StackAmount)
4258                    return false;
4259            }
4260        }
4261        else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
4262        {
4263                if( target->HasAura(m_spellInfo->Id, j) )
4264                    return false;
4265        }
4266    }
4267
4268    int16 result = PetCanCast(target);
4269
4270    if(result == -1 || result == SPELL_FAILED_UNIT_NOT_INFRONT)
4271    {
4272        FillTargetMap();
4273        //check if among target units, our WANTED target is as well (->only self cast spells return false)
4274        for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4275            if( ihit->targetGUID == targetguid )
4276                return true;
4277    }
4278    return false;                                           //target invalid
4279}
4280
4281uint8 Spell::CheckRange(bool strict)
4282{
4283    float range_mod;
4284
4285    // self cast doesn't need range checking -- also for Starshards fix
4286    if (m_spellInfo->rangeIndex == 1) return 0;
4287
4288    if (strict)                                             //add radius of caster
4289        range_mod = 1.25;
4290    else                                                    //add radius of caster and ~5 yds "give"
4291        range_mod = 6.25;
4292
4293    SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
4294    float max_range = GetSpellMaxRange(srange) + range_mod;
4295    float min_range = GetSpellMinRange(srange);
4296
4297    if(Player* modOwner = m_caster->GetSpellModOwner())
4298        modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
4299
4300    Unit *target = m_targets.getUnitTarget();
4301
4302    if(target && target != m_caster)
4303    {
4304        // distance from target center in checks
4305        if(!m_caster->IsWithinCombatDist(target, max_range))
4306            return SPELL_FAILED_OUT_OF_RANGE;               //0x5A;
4307        if(min_range && m_caster->IsWithinCombatDist(target, min_range)) // skip this check if min_range = 0
4308            return SPELL_FAILED_TOO_CLOSE;
4309        if( m_caster->GetTypeId() == TYPEID_PLAYER &&
4310            (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
4311            return SPELL_FAILED_UNIT_NOT_INFRONT;
4312    }
4313
4314    if(m_targets.m_targetMask == TARGET_FLAG_DEST_LOCATION && m_targets.m_destX != 0 && m_targets.m_destY != 0 && m_targets.m_destZ != 0)
4315    {
4316        float dist = m_caster->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ);
4317        if(dist > max_range)
4318            return SPELL_FAILED_OUT_OF_RANGE;
4319        if(dist < min_range)
4320            return SPELL_FAILED_TOO_CLOSE;
4321    }
4322
4323    return 0;                                               // ok
4324}
4325
4326int32 Spell::CalculatePowerCost()
4327{
4328    // item cast not used power
4329    if(m_CastItem)
4330        return 0;
4331
4332    // Spell drain all exist power on cast (Only paladin lay of Hands)
4333    if (m_spellInfo->AttributesEx & SPELL_ATTR_EX_DRAIN_ALL_POWER)
4334    {
4335        // If power type - health drain all
4336        if (m_spellInfo->powerType == POWER_HEALTH)
4337            return m_caster->GetHealth();
4338        // Else drain all power
4339        if (m_spellInfo->powerType < MAX_POWERS)
4340            return m_caster->GetPower(Powers(m_spellInfo->powerType));
4341        sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4342        return 0;
4343    }
4344
4345    // Base powerCost
4346    int32 powerCost = m_spellInfo->manaCost;
4347    // PCT cost from total amount
4348    if (m_spellInfo->ManaCostPercentage)
4349    {
4350        switch (m_spellInfo->powerType)
4351        {
4352            // health as power used
4353            case POWER_HEALTH:
4354                powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateHealth() / 100;
4355                break;
4356            case POWER_MANA:
4357                powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100;
4358                break;
4359            case POWER_RAGE:
4360            case POWER_FOCUS:
4361            case POWER_ENERGY:
4362            case POWER_HAPPINESS:
4363                //            case POWER_RUNES:
4364                powerCost += m_spellInfo->ManaCostPercentage * m_caster->GetMaxPower(Powers(m_spellInfo->powerType)) / 100;
4365                break;
4366            default:
4367                sLog.outError("Spell::CalculateManaCost: Unknown power type '%d' in spell %d", m_spellInfo->powerType, m_spellInfo->Id);
4368                return 0;
4369        }
4370    }
4371    SpellSchools school = GetFirstSchoolInMask(m_spellSchoolMask);
4372    // Flat mod from caster auras by spell school
4373    powerCost += m_caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
4374    // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
4375    if ( m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST )
4376        powerCost += m_caster->GetAttackTime(OFF_ATTACK)/100;
4377    // Apply cost mod by spell
4378    if(Player* modOwner = m_caster->GetSpellModOwner())
4379        modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, powerCost, this);
4380
4381    if(m_spellInfo->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)
4382        powerCost = int32(powerCost/ (1.117f* m_spellInfo->spellLevel / m_caster->getLevel() -0.1327f));
4383
4384    // PCT mod from user auras by school
4385    powerCost = int32(powerCost * (1.0f+m_caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
4386    if (powerCost < 0)
4387        powerCost = 0;
4388    return powerCost;
4389}
4390
4391uint8 Spell::CheckPower()
4392{
4393    // item cast not used power
4394    if(m_CastItem)
4395        return 0;
4396
4397    // health as power used - need check health amount
4398    if(m_spellInfo->powerType == POWER_HEALTH)
4399    {
4400        if(m_caster->GetHealth() <= m_powerCost)
4401            return SPELL_FAILED_CASTER_AURASTATE;
4402        return 0;
4403    }
4404    // Check valid power type
4405    if( m_spellInfo->powerType >= MAX_POWERS )
4406    {
4407        sLog.outError("Spell::CheckMana: Unknown power type '%d'", m_spellInfo->powerType);
4408        return SPELL_FAILED_UNKNOWN;
4409    }
4410    // Check power amount
4411    Powers powerType = Powers(m_spellInfo->powerType);
4412    if(m_caster->GetPower(powerType) < m_powerCost)
4413        return SPELL_FAILED_NO_POWER;
4414    else
4415        return 0;
4416}
4417
4418uint8 Spell::CheckItems()
4419{
4420    if (m_caster->GetTypeId() != TYPEID_PLAYER)
4421        return 0;
4422
4423    uint32 itemid, itemcount;
4424    Player* p_caster = (Player*)m_caster;
4425
4426    if(m_CastItem)
4427    {
4428        itemid = m_CastItem->GetEntry();
4429        if( !p_caster->HasItemCount(itemid,1) )
4430            return SPELL_FAILED_ITEM_NOT_READY;
4431        else
4432        {
4433            ItemPrototype const *proto = m_CastItem->GetProto();
4434            if(!proto)
4435                return SPELL_FAILED_ITEM_NOT_READY;
4436
4437            for (int i = 0; i<5; i++)
4438            {
4439                if (proto->Spells[i].SpellCharges)
4440                {
4441                    if(m_CastItem->GetSpellCharges(i)==0)
4442                        return SPELL_FAILED_NO_CHARGES_REMAIN;
4443                }
4444            }
4445
4446            uint32 ItemClass = proto->Class;
4447            if (ItemClass == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
4448            {
4449                for (int i = 0; i < 3; i++)
4450                {
4451                    // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster
4452                    if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_PET)
4453                        continue;
4454
4455                    if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
4456                        if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
4457                            return (uint8)SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
4458
4459                    // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
4460                    if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
4461                    {
4462                        if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
4463                            return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4464
4465                        Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
4466
4467                        if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
4468                            return (uint8)SPELL_FAILED_ALREADY_AT_FULL_POWER;
4469                    }
4470                }
4471            }
4472        }
4473    }
4474
4475    if(m_targets.getItemTargetGUID())
4476    {
4477        if(m_caster->GetTypeId() != TYPEID_PLAYER)
4478            return SPELL_FAILED_BAD_TARGETS;
4479
4480        if(!m_targets.getItemTarget())
4481            return SPELL_FAILED_ITEM_GONE;
4482
4483        if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
4484            return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4485    }
4486    // if not item target then required item must be equipped
4487    else
4488    {
4489        if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
4490            return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
4491    }
4492
4493    if(m_spellInfo->RequiresSpellFocus)
4494    {
4495        CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
4496        Cell cell(p);
4497        cell.data.Part.reserved = ALL_DISTRICT;
4498
4499        GameObject* ok = NULL;
4500        Trinity::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
4501        Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> checker(ok,go_check);
4502
4503        TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
4504        CellLock<GridReadGuard> cell_lock(cell, p);
4505        cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster));
4506
4507        if(!ok)
4508            return (uint8)SPELL_FAILED_REQUIRES_SPELL_FOCUS;
4509
4510        focusObject = ok;                                   // game object found in range
4511    }
4512
4513    if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
4514        m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION)))
4515    {
4516        for(uint32 i=0;i<8;i++)
4517        {
4518            if(m_spellInfo->Reagent[i] <= 0)
4519                continue;
4520
4521            itemid    = m_spellInfo->Reagent[i];
4522            itemcount = m_spellInfo->ReagentCount[i];
4523
4524            // if CastItem is also spell reagent
4525            if( m_CastItem && m_CastItem->GetEntry() == itemid )
4526            {
4527                ItemPrototype const *proto = m_CastItem->GetProto();
4528                if(!proto)
4529                    return SPELL_FAILED_ITEM_NOT_READY;
4530                for(int s=0;s<5;s++)
4531                {
4532                    // CastItem will be used up and does not count as reagent
4533                    int32 charges = m_CastItem->GetSpellCharges(s);
4534                    if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
4535                    {
4536                        ++itemcount;
4537                        break;
4538                    }
4539                }
4540            }
4541            if( !p_caster->HasItemCount(itemid,itemcount) )
4542                return (uint8)SPELL_FAILED_ITEM_NOT_READY;      //0x54
4543        }
4544    }
4545
4546    uint32 totems = 2;
4547    for(int i=0;i<2;++i)
4548    {
4549        if(m_spellInfo->Totem[i] != 0)
4550        {
4551            if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
4552            {
4553                totems -= 1;
4554                continue;
4555            }
4556        }else
4557        totems -= 1;
4558    }
4559    if(totems != 0)
4560        return (uint8)SPELL_FAILED_TOTEMS;                  //0x7C
4561
4562    //Check items for TotemCategory
4563    uint32 TotemCategory = 2;
4564    for(int i=0;i<2;++i)
4565    {
4566        if(m_spellInfo->TotemCategory[i] != 0)
4567        {
4568            if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
4569            {
4570                TotemCategory -= 1;
4571                continue;
4572            }
4573        }
4574        else
4575            TotemCategory -= 1;
4576    }
4577    if(TotemCategory != 0)
4578        return (uint8)SPELL_FAILED_TOTEM_CATEGORY;          //0x7B
4579
4580    for(int i = 0; i < 3; i++)
4581    {
4582        switch (m_spellInfo->Effect[i])
4583        {
4584            case SPELL_EFFECT_CREATE_ITEM:
4585            {
4586                if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
4587                {
4588                    ItemPosCountVec dest;
4589                    uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
4590                    if (msg != EQUIP_ERR_OK )
4591                    {
4592                        p_caster->SendEquipError( msg, NULL, NULL );
4593                        return SPELL_FAILED_DONT_REPORT;
4594                    }
4595                }
4596                break;
4597            }
4598            case SPELL_EFFECT_ENCHANT_ITEM:
4599            {
4600                Item* targetItem = m_targets.getItemTarget();
4601                if(!targetItem)
4602                    return SPELL_FAILED_ITEM_NOT_FOUND;
4603
4604                if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
4605                    return SPELL_FAILED_LOWLEVEL;
4606                // Not allow enchant in trade slot for some enchant type
4607                if( targetItem->GetOwner() != m_caster )
4608                {
4609                    uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4610                    SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4611                    if(!pEnchant)
4612                        return SPELL_FAILED_ERROR;
4613                    if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4614                        return SPELL_FAILED_NOT_TRADEABLE;
4615                }
4616                break;
4617            }
4618            case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
4619            {
4620                Item *item = m_targets.getItemTarget();
4621                if(!item)
4622                    return SPELL_FAILED_ITEM_NOT_FOUND;
4623                // Not allow enchant in trade slot for some enchant type
4624                if( item->GetOwner() != m_caster )
4625                {
4626                    uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
4627                    SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
4628                    if(!pEnchant)
4629                        return SPELL_FAILED_ERROR;
4630                    if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
4631                        return SPELL_FAILED_NOT_TRADEABLE;
4632                }
4633                break;
4634            }
4635            case SPELL_EFFECT_ENCHANT_HELD_ITEM:
4636                // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
4637                break;
4638            case SPELL_EFFECT_DISENCHANT:
4639            {
4640                if(!m_targets.getItemTarget())
4641                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4642
4643                // prevent disenchanting in trade slot
4644                if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4645                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4646
4647                ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
4648                if(!itemProto)
4649                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4650
4651                uint32 item_quality = itemProto->Quality;
4652                // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
4653                uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
4654                if (item_disenchantskilllevel == uint32(-1))
4655                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4656                if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
4657                    return SPELL_FAILED_LOW_CASTLEVEL;
4658                if(item_quality > 4 || item_quality < 2)
4659                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4660                if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
4661                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4662                if (!itemProto->DisenchantID)
4663                    return SPELL_FAILED_CANT_BE_DISENCHANTED;
4664                break;
4665            }
4666            case SPELL_EFFECT_PROSPECTING:
4667            {
4668                if(!m_targets.getItemTarget())
4669                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4670                //ensure item is a prospectable ore
4671                if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
4672                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4673                //prevent prospecting in trade slot
4674                if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
4675                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4676                //Check for enough skill in jewelcrafting
4677                uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
4678                if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
4679                    return SPELL_FAILED_LOW_CASTLEVEL;
4680                //make sure the player has the required ores in inventory
4681                if(m_targets.getItemTarget()->GetCount() < 5)
4682                    return SPELL_FAILED_PROSPECT_NEED_MORE;
4683
4684                if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
4685                    return SPELL_FAILED_CANT_BE_PROSPECTED;
4686
4687                break;
4688            }
4689            case SPELL_EFFECT_WEAPON_DAMAGE:
4690            case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
4691            {
4692                if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
4693                if( m_attackType != RANGED_ATTACK )
4694                    break;
4695                Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
4696                if(!pItem || pItem->IsBroken())
4697                    return SPELL_FAILED_EQUIPPED_ITEM;
4698
4699                switch(pItem->GetProto()->SubClass)
4700                {
4701                    case ITEM_SUBCLASS_WEAPON_THROWN:
4702                    {
4703                        uint32 ammo = pItem->GetEntry();
4704                        if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4705                            return SPELL_FAILED_NO_AMMO;
4706                    };  break;
4707                    case ITEM_SUBCLASS_WEAPON_GUN:
4708                    case ITEM_SUBCLASS_WEAPON_BOW:
4709                    case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4710                    {
4711                        uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
4712                        if(!ammo)
4713                        {
4714                            // Requires No Ammo
4715                            if(m_caster->GetDummyAura(46699))
4716                                break;                      // skip other checks
4717
4718                            return SPELL_FAILED_NO_AMMO;
4719                        }
4720
4721                        ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
4722                        if(!ammoProto)
4723                            return SPELL_FAILED_NO_AMMO;
4724
4725                        if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
4726                            return SPELL_FAILED_NO_AMMO;
4727
4728                        // check ammo ws. weapon compatibility
4729                        switch(pItem->GetProto()->SubClass)
4730                        {
4731                            case ITEM_SUBCLASS_WEAPON_BOW:
4732                            case ITEM_SUBCLASS_WEAPON_CROSSBOW:
4733                                if(ammoProto->SubClass!=ITEM_SUBCLASS_ARROW)
4734                                    return SPELL_FAILED_NO_AMMO;
4735                                break;
4736                            case ITEM_SUBCLASS_WEAPON_GUN:
4737                                if(ammoProto->SubClass!=ITEM_SUBCLASS_BULLET)
4738                                    return SPELL_FAILED_NO_AMMO;
4739                                break;
4740                            default:
4741                                return SPELL_FAILED_NO_AMMO;
4742                        }
4743
4744                        if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
4745                            return SPELL_FAILED_NO_AMMO;
4746                    };  break;
4747                    case ITEM_SUBCLASS_WEAPON_WAND:
4748                    default:
4749                        break;
4750                }
4751                break;
4752            }
4753            default:break;
4754        }
4755    }
4756
4757    return uint8(0);
4758}
4759
4760void Spell::Delayed()
4761{
4762    if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER)
4763        return;
4764
4765    if (m_spellState == SPELL_STATE_DELAYED)
4766        return;                                             // spell is active and can't be time-backed
4767
4768    // spells not loosing casting time ( slam, dynamites, bombs.. )
4769    if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
4770        return;
4771
4772    //check resist chance
4773    int32 resistChance = 100;                               //must be initialized to 100 for percent modifiers
4774    ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4775    resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4776    if (roll_chance_i(resistChance))
4777        return;
4778
4779    int32 delaytime = GetNextDelayAtDamageMsTime();
4780
4781    if(int32(m_timer) + delaytime > m_casttime)
4782    {
4783        delaytime = m_casttime - m_timer;
4784        m_timer = m_casttime;
4785    }
4786    else
4787        m_timer += delaytime;
4788
4789    sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage",m_spellInfo->Id,delaytime);
4790
4791    WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
4792    data.append(m_caster->GetPackGUID());
4793    data << uint32(delaytime);
4794
4795    m_caster->SendMessageToSet(&data,true);
4796}
4797
4798void Spell::DelayedChannel()
4799{
4800    if(!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
4801        return;
4802
4803    //check resist chance
4804    int32 resistChance = 100;                               //must be initialized to 100 for percent modifiers
4805    ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id,SPELLMOD_NOT_LOSE_CASTING_TIME,resistChance, this);
4806    resistChance += m_caster->GetTotalAuraModifier(SPELL_AURA_RESIST_PUSHBACK) - 100;
4807    if (roll_chance_i(resistChance))
4808        return;
4809
4810    int32 delaytime = GetNextDelayAtDamageMsTime();
4811
4812    if(int32(m_timer) < delaytime)
4813    {
4814        delaytime = m_timer;
4815        m_timer = 0;
4816    }
4817    else
4818        m_timer -= delaytime;
4819
4820    sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
4821
4822    for(std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin();ihit != m_UniqueTargetInfo.end();++ihit)
4823    {
4824        if ((*ihit).missCondition == SPELL_MISS_NONE)
4825        {
4826            Unit* unit = m_caster->GetGUID()==ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
4827            if (unit)
4828            {
4829                for (int j=0;j<3;j++)
4830                    if( ihit->effectMask & (1<<j) )
4831                        unit->DelayAura(m_spellInfo->Id, j, delaytime);
4832            }
4833
4834        }
4835    }
4836
4837    for(int j = 0; j < 3; j++)
4838    {
4839        // partially interrupt persistent area auras
4840        DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, j);
4841        if(dynObj)
4842            dynObj->Delay(delaytime);
4843    }
4844
4845    SendChannelUpdate(m_timer);
4846}
4847
4848void Spell::UpdatePointers()
4849{
4850    if(m_originalCasterGUID==m_caster->GetGUID())
4851        m_originalCaster = m_caster;
4852    else
4853    {
4854        m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
4855        if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
4856    }
4857
4858    m_targets.Update(m_caster);
4859}
4860
4861bool Spell::IsAffectedBy(SpellEntry const *spellInfo, uint32 effectId)
4862{
4863    return spellmgr.IsAffectedBySpell(m_spellInfo,spellInfo->Id,effectId,spellInfo->EffectItemType[effectId]);
4864}
4865
4866bool Spell::CheckTargetCreatureType(Unit* target) const
4867{
4868    uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
4869
4870    // Curse of Doom : not find another way to fix spell target check :/
4871    if(m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags == 0x0200000000LL)
4872    {
4873        // not allow cast at player
4874        if(target->GetTypeId()==TYPEID_PLAYER)
4875            return false;
4876
4877        spellCreatureTargetMask = 0x7FF;
4878    }
4879
4880    // Dismiss Pet and Taming Lesson skipped
4881    if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
4882        spellCreatureTargetMask =  0;
4883
4884    if (spellCreatureTargetMask)
4885    {
4886        uint32 TargetCreatureType = target->GetCreatureTypeMask();
4887
4888        return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
4889    }
4890    return true;
4891}
4892
4893CurrentSpellTypes Spell::GetCurrentContainer()
4894{
4895    if (IsNextMeleeSwingSpell())
4896        return(CURRENT_MELEE_SPELL);
4897    else if (IsAutoRepeat())
4898        return(CURRENT_AUTOREPEAT_SPELL);
4899    else if (IsChanneledSpell(m_spellInfo))
4900        return(CURRENT_CHANNELED_SPELL);
4901    else
4902        return(CURRENT_GENERIC_SPELL);
4903}
4904
4905bool Spell::CheckTarget( Unit* target, uint32 eff, bool hitPhase )
4906{
4907    // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
4908    if(m_spellInfo->EffectImplicitTargetA[eff]!=TARGET_SELF && !m_magnetPair.first)
4909    {
4910        if (!CheckTargetCreatureType(target))
4911            return false;
4912    }
4913
4914    // Check targets for not_selectable unit flag and remove
4915    // A player can cast spells on his pet (or other controlled unit) though in any state
4916    if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
4917    {
4918        // any unattackable target skipped
4919        if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
4920            return false;
4921
4922        // unselectable targets skipped in all cases except TARGET_SCRIPT targeting
4923        // in case TARGET_SCRIPT target selected by server always and can't be cheated
4924        if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
4925            m_spellInfo->EffectImplicitTargetA[eff] != TARGET_SCRIPT &&
4926            m_spellInfo->EffectImplicitTargetB[eff] != TARGET_SCRIPT )
4927            return false;
4928    }
4929
4930    //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
4931    if( target != m_caster && target->GetTypeId()==TYPEID_PLAYER)
4932    {
4933        if(((Player*)target)->GetVisibility()==VISIBILITY_OFF)
4934            return false;
4935
4936        if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
4937            return false;
4938    }
4939
4940    //Check targets for LOS visibility (except spells without range limitations )
4941    switch(m_spellInfo->Effect[eff])
4942    {
4943        case SPELL_EFFECT_SUMMON_PLAYER:                    // from anywhere
4944            break;
4945        case SPELL_EFFECT_DUMMY:
4946            if(m_spellInfo->Id!=20577)                      // Cannibalize
4947                break;
4948            //fall through
4949        case SPELL_EFFECT_RESURRECT_NEW:
4950            // player far away, maybe his corpse near?
4951            if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4952            {
4953                if(!m_targets.getCorpseTargetGUID())
4954                    return false;
4955
4956                Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
4957                if(!corpse)
4958                    return false;
4959
4960                if(target->GetGUID()!=corpse->GetOwnerGUID())
4961                    return false;
4962
4963                if(!corpse->IsWithinLOSInMap(m_caster))
4964                    return false;
4965            }
4966
4967            // all ok by some way or another, skip normal check
4968            break;
4969        default:                                            // normal case
4970            if(target!=m_caster && !target->IsWithinLOSInMap(m_caster))
4971                return false;
4972            break;
4973    }
4974
4975    return true;
4976}
4977
4978Unit* Spell::SelectMagnetTarget()
4979{
4980    Unit* target = m_targets.getUnitTarget();
4981
4982    if(target && target->HasAuraType(SPELL_AURA_SPELL_MAGNET) && !(m_spellInfo->Attributes & 0x10))
4983    {
4984        Unit::AuraList const& magnetAuras = target->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
4985        for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
4986        {
4987            if(Unit* magnet = (*itr)->GetCaster())
4988            {
4989                if((*itr)->m_procCharges>0 && magnet->IsWithinLOSInMap(m_caster))
4990                {
4991                    (*itr)->SetAuraProcCharges((*itr)->m_procCharges-1);
4992                    m_magnetPair.first = true;
4993                    m_magnetPair.second = magnet;
4994
4995                    target = magnet;
4996                    m_targets.setUnitTarget(target);
4997                    break;
4998                }
4999            }
5000        }
5001    }
5002
5003    return target;
5004}
5005
5006bool Spell::IsNeedSendToClient() const
5007{
5008    return m_spellInfo->SpellVisual!=0 || IsChanneledSpell(m_spellInfo) ||
5009        m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
5010}
5011
5012bool Spell::HaveTargetsForEffect( uint8 effect ) const
5013{
5014    for(std::list<TargetInfo>::const_iterator itr= m_UniqueTargetInfo.begin();itr != m_UniqueTargetInfo.end();++itr)
5015        if(itr->effectMask & (1<<effect))
5016            return true;
5017
5018    for(std::list<GOTargetInfo>::const_iterator itr= m_UniqueGOTargetInfo.begin();itr != m_UniqueGOTargetInfo.end();++itr)
5019        if(itr->effectMask & (1<<effect))
5020            return true;
5021
5022    for(std::list<ItemTargetInfo>::const_iterator itr= m_UniqueItemInfo.begin();itr != m_UniqueItemInfo.end();++itr)
5023        if(itr->effectMask & (1<<effect))
5024            return true;
5025
5026    return false;
5027}
5028
5029SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
5030{
5031    m_Spell = spell;
5032}
5033
5034SpellEvent::~SpellEvent()
5035{
5036    if (m_Spell->getState() != SPELL_STATE_FINISHED)
5037        m_Spell->cancel();
5038
5039    if (m_Spell->IsDeletable())
5040    {
5041        delete m_Spell;
5042    }
5043    else
5044    {
5045        sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
5046            (m_Spell->GetCaster()->GetTypeId()==TYPEID_PLAYER?"Player":"Creature"), m_Spell->GetCaster()->GetGUIDLow(),m_Spell->m_spellInfo->Id);
5047    }
5048}
5049
5050bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
5051{
5052    // update spell if it is not finished
5053    if (m_Spell->getState() != SPELL_STATE_FINISHED)
5054        m_Spell->update(p_time);
5055
5056    // check spell state to process
5057    switch (m_Spell->getState())
5058    {
5059        case SPELL_STATE_FINISHED:
5060        {
5061            // spell was finished, check deletable state
5062            if (m_Spell->IsDeletable())
5063            {
5064                // check, if we do have unfinished triggered spells
5065
5066                return(true);                               // spell is deletable, finish event
5067            }
5068            // event will be re-added automatically at the end of routine)
5069        } break;
5070
5071        case SPELL_STATE_CASTING:
5072        {
5073            // this spell is in channeled state, process it on the next update
5074            // event will be re-added automatically at the end of routine)
5075        } break;
5076
5077        case SPELL_STATE_DELAYED:
5078        {
5079            // first, check, if we have just started
5080            if (m_Spell->GetDelayStart() != 0)
5081            {
5082                // no, we aren't, do the typical update
5083                // check, if we have channeled spell on our hands
5084                if (IsChanneledSpell(m_Spell->m_spellInfo))
5085                {
5086                    // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
5087                    // check, if we have casting anything else except this channeled spell and autorepeat
5088                    if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
5089                    {
5090                        // another non-melee non-delayed spell is casted now, abort
5091                        m_Spell->cancel();
5092                    }
5093                    else
5094                    {
5095                        // do the action (pass spell to channeling state)
5096                        m_Spell->handle_immediate();
5097                    }
5098                    // event will be re-added automatically at the end of routine)
5099                }
5100                else
5101                {
5102                    // run the spell handler and think about what we can do next
5103                    uint64 t_offset = e_time - m_Spell->GetDelayStart();
5104                    uint64 n_offset = m_Spell->handle_delayed(t_offset);
5105                    if (n_offset)
5106                    {
5107                        // re-add us to the queue
5108                        m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
5109                        return(false);                      // event not complete
5110                    }
5111                    // event complete
5112                    // finish update event will be re-added automatically at the end of routine)
5113                }
5114            }
5115            else
5116            {
5117                // delaying had just started, record the moment
5118                m_Spell->SetDelayStart(e_time);
5119                // re-plan the event for the delay moment
5120                m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
5121                return(false);                              // event not complete
5122            }
5123        } break;
5124
5125        default:
5126        {
5127            // all other states
5128            // event will be re-added automatically at the end of routine)
5129        } break;
5130    }
5131
5132    // spell processing not complete, plan event on the next update interval
5133    m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
5134    return(false);                                          // event not complete
5135}
5136
5137void SpellEvent::Abort(uint64 /*e_time*/)
5138{
5139    // oops, the spell we try to do is aborted
5140    if (m_Spell->getState() != SPELL_STATE_FINISHED)
5141        m_Spell->cancel();
5142}
5143
5144bool SpellEvent::IsDeletable() const
5145{
5146    return m_Spell->IsDeletable();
5147}
Note: See TracBrowser for help on using the browser.