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

Revision 226, 196.7 kB (checked in by yumileroy, 17 years ago)

[svn] Some update on channeled spells.

Original author: megamage
Date: 2008-11-14 14:19:23-06:00

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