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

Revision 180, 196.4 kB (checked in by yumileroy, 17 years ago)

[svn] Fix hunter's trap (let original caster summon dynamic object).
Fix black temple boss 1's hurl spine.

Original author: megamage
Date: 2008-11-06 12:24:56-06:00

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