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

Revision 231, 197.0 kB (checked in by yumileroy, 17 years ago)

[svn] Add UNIT_STAT_CASTING, and use it to update attack timer as test.

Original author: megamage
Date: 2008-11-14 17:42:00-06:00

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