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

Revision 284, 197.2 kB (checked in by yumileroy, 17 years ago)

Merge with 284 (54b0e67d97fe).

Original author: megamage
Date: 2008-11-21 19:49:54-06:00

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