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

Revision 287, 198.4 kB (checked in by yumileroy, 17 years ago)

Added more calls for searching the world object containers for spell scripted targets.

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