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

Revision 173, 196.2 kB (checked in by yumileroy, 17 years ago)

[svn] * Avoid access to bag item prototype for getting bag size, use related item update field instead as more fast source.
* Better check client inventory pos data received in some client packets to skip invalid cases.
* Removed some unnecessary database queries.
* Make guid lookup for adding ignore async.
* Added two parameter versions of the AsyncQuery? function
* Make queries for adding friends async. - Hunuza
* Replace some PQuery() calls with more simple Query() - Hunuza
* Mark spell as executed instead of deleteable to solve crash.
*** Source mangos.

**Its a big commit. so test with care... or without care.... whatever floats your boat.

Original author: KingPin?
Date: 2008-11-05 20:10:19-06:00

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