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

Revision 176, 196.3 kB (checked in by yumileroy, 17 years ago)

[svn] Fix a bug that summon spells may summon incorrect number of creatures (will find a better way later).

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