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

Revision 147, 196.0 kB (checked in by yumileroy, 17 years ago)

[svn] Fix eagle eye (and other far sight spells).

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