root/trunk/src/game/Creature.cpp @ 102

Revision 102, 69.3 kB (checked in by yumileroy, 17 years ago)

[svn] Fixed copyright notices to comply with GPL.

Original author: w12x
Date: 2008-10-23 03:29:52-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 "World.h"
26#include "ObjectMgr.h"
27#include "SpellMgr.h"
28#include "Creature.h"
29#include "QuestDef.h"
30#include "GossipDef.h"
31#include "Player.h"
32#include "Opcodes.h"
33#include "Log.h"
34#include "LootMgr.h"
35#include "MapManager.h"
36#include "CreatureAI.h"
37#include "CreatureAISelector.h"
38#include "Formulas.h"
39#include "SpellAuras.h"
40#include "WaypointMovementGenerator.h"
41#include "InstanceData.h"
42#include "BattleGround.h"
43#include "Util.h"
44#include "GridNotifiers.h"
45#include "GridNotifiersImpl.h"
46#include "CellImpl.h"
47#include "OutdoorPvPMgr.h"
48#include "GameEvent.h"
49// apply implementation of the singletons
50#include "Policies/SingletonImp.h"
51
52void TrainerSpellData::Clear()
53{
54    for (TrainerSpellList::iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
55        delete (*itr);
56    spellList.empty();
57}
58
59TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
60{
61    for(TrainerSpellList::const_iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
62        if((*itr)->spell == spell_id)
63            return *itr;
64
65    return NULL;
66}
67
68bool VendorItemData::RemoveItem( uint32 item_id )
69{
70    for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
71    {
72        if((*i)->item==item_id)
73        {
74            m_items.erase(i);
75            return true;
76        }
77    }
78    return false;
79}
80
81size_t VendorItemData::FindItemSlot(uint32 item_id) const
82{
83    for(size_t i = 0; i < m_items.size(); ++i )
84        if(m_items[i]->item==item_id)
85            return i;
86    return m_items.size();
87}
88
89VendorItem const* VendorItemData::FindItem(uint32 item_id) const
90{
91    for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
92        if((*i)->item==item_id)
93            return *i;
94    return NULL;
95}
96
97Creature::Creature() :
98Unit(), i_AI(NULL),
99lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
100m_lootMoney(0), m_lootRecipient(0),
101m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
102m_gossipOptionLoaded(false),m_emoteState(0), m_isPet(false), m_isTotem(false),
103m_regenTimer(2000), m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
104m_AlreadyCallAssistence(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
105m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),m_creatureInfo(NULL), m_DBTableGuid(0)
106{
107    m_valuesCount = UNIT_END;
108
109    for(int i =0; i<4; ++i)
110        m_spells[i] = 0;
111
112    m_CreatureSpellCooldowns.clear();
113    m_CreatureCategoryCooldowns.clear();
114    m_GlobalCooldown = 0;
115    m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
116}
117
118Creature::~Creature()
119{
120    CleanupsBeforeDelete();
121
122    m_vendorItemCounts.clear();
123
124    delete i_AI;
125    i_AI = NULL;
126}
127
128void Creature::AddToWorld()
129{
130    ///- Register the creature for guid lookup
131    if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
132    Unit::AddToWorld();
133}
134
135void Creature::RemoveFromWorld()
136{
137    ///- Remove the creature from the accessor
138    if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
139    Unit::RemoveFromWorld();
140}
141
142void Creature::RemoveCorpse()
143{
144    if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
145        return;
146
147    m_deathTimer = 0;
148    setDeathState(DEAD);
149    ObjectAccessor::UpdateObjectVisibility(this);
150    loot.clear();
151    m_respawnTime = time(NULL) + m_respawnDelay;
152
153    float x,y,z,o;
154    GetRespawnCoord(x, y, z, &o);
155    MapManager::Instance().GetMap(GetMapId(), this)->CreatureRelocation(this,x,y,z,o);
156}
157
158/**
159 * change the entry of creature until respawn
160 */
161bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
162{
163    CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
164    if(!normalInfo)
165    {
166        sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
167        return false;
168    }
169
170    // get heroic mode entry
171    uint32 actualEntry = Entry;
172    CreatureInfo const *cinfo = normalInfo;
173    if(normalInfo->HeroicEntry)
174    {
175        Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
176        if(map && map->IsHeroic())
177        {
178            cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
179            if(!cinfo)
180            {
181                sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
182                return false;
183            }
184        }
185    }
186
187    SetUInt32Value(OBJECT_FIELD_ENTRY, Entry);              // normal entry always
188    m_creatureInfo = cinfo;                                 // map mode related always
189
190    if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
191    {
192        sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
193        return false;
194    }
195
196    uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
197    CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
198    if (!minfo)
199    {
200        sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
201        return false;
202    }
203    else
204        display_id = minfo->modelid;                        // it can be different (for another gender)
205
206    SetDisplayId(display_id);
207    SetNativeDisplayId(display_id);
208    SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
209
210    // Load creature equipment
211    if(!data || data->equipmentId == 0)
212    {                                                       // use default from the template
213        LoadEquipment(cinfo->equipmentId);
214    }
215    else if(data && data->equipmentId != -1)
216    {                                                       // override, -1 means no equipment
217        LoadEquipment(data->equipmentId);
218    }
219
220    SetName(normalInfo->Name);                              // at normal entry always
221
222    SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
223    SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
224
225    SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
226
227    SetSpeed(MOVE_WALK,     cinfo->speed );
228    SetSpeed(MOVE_RUN,      cinfo->speed );
229    SetSpeed(MOVE_SWIM,     cinfo->speed );
230
231    SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
232
233    // checked at loading
234    m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
235    if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
236        m_defaultMovementType = IDLE_MOTION_TYPE;
237
238    return true;
239}
240
241bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
242{
243    if(!InitEntry(Entry,team,data))
244        return false;
245
246    m_regenHealth = GetCreatureInfo()->RegenHealth;
247
248    // creatures always have melee weapon ready if any
249    SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
250    SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_AURAS );
251
252    SelectLevel(GetCreatureInfo());
253    if (team == HORDE)
254        SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
255    else
256        SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
257
258    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT)
259        SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag | gameeventmgr.GetNPCFlag(this));
260    else
261        SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
262
263    SetAttackTime(BASE_ATTACK,  GetCreatureInfo()->baseattacktime);
264    SetAttackTime(OFF_ATTACK,   GetCreatureInfo()->baseattacktime);
265    SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
266
267    SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->Flags);
268    SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
269
270    SetModifierValue(UNIT_MOD_ARMOR,             BASE_VALUE, float(GetCreatureInfo()->armor));
271    SetModifierValue(UNIT_MOD_RESISTANCE_HOLY,   BASE_VALUE, float(GetCreatureInfo()->resistance1));
272    SetModifierValue(UNIT_MOD_RESISTANCE_FIRE,   BASE_VALUE, float(GetCreatureInfo()->resistance2));
273    SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
274    SetModifierValue(UNIT_MOD_RESISTANCE_FROST,  BASE_VALUE, float(GetCreatureInfo()->resistance4));
275    SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
276    SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
277
278    SetCanModifyStats(true);
279    UpdateAllStats();
280
281    FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
282    if (factionTemplate)                                    // check and error show at loading templates
283    {
284        FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
285        if (factionEntry)
286            if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
287                (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
288                SetPvP(true);
289    }
290
291    m_spells[0] = GetCreatureInfo()->spell1;
292    m_spells[1] = GetCreatureInfo()->spell2;
293    m_spells[2] = GetCreatureInfo()->spell3;
294    m_spells[3] = GetCreatureInfo()->spell4;
295
296    return true;
297}
298
299void Creature::Update(uint32 diff)
300{
301    if(m_GlobalCooldown <= diff)
302        m_GlobalCooldown = 0;
303    else
304        m_GlobalCooldown -= diff;
305
306    switch( m_deathState )
307    {
308        case JUST_ALIVED:
309            // Dont must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
310            sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
311            break;
312        case JUST_DIED:
313            // Dont must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
314            sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
315            break;
316        case DEAD:
317        {
318            if( m_respawnTime <= time(NULL) )
319            {
320                DEBUG_LOG("Respawning...");
321                m_respawnTime = 0;
322                lootForPickPocketed = false;
323                lootForBody         = false;
324
325                if(m_originalEntry != GetUInt32Value(OBJECT_FIELD_ENTRY))
326                    UpdateEntry(m_originalEntry);
327
328                CreatureInfo const *cinfo = GetCreatureInfo();
329
330                SelectLevel(cinfo);
331                SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
332                if (m_isDeadByDefault)
333                {
334                    setDeathState(JUST_DIED);
335                    SetHealth(0);
336                    i_motionMaster.Clear();
337                    clearUnitState(UNIT_STAT_ALL_STATE);
338                    LoadCreaturesAddon(true);
339                }
340                else
341                    setDeathState( JUST_ALIVED );
342
343                //Call AI respawn virtual function
344                i_AI->JustRespawned();
345
346                MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
347            }
348            break;
349        }
350        case CORPSE:
351        {
352            if (m_isDeadByDefault)
353                break;
354
355            if( m_deathTimer <= diff )
356            {
357                RemoveCorpse();
358                DEBUG_LOG("Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY));
359            }
360            else
361            {
362                m_deathTimer -= diff;
363                if (m_groupLootTimer && lootingGroupLeaderGUID)
364                {
365                    if(diff <= m_groupLootTimer)
366                    {
367                        m_groupLootTimer -= diff;
368                    }
369                    else
370                    {
371                        Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
372                        if (group)
373                            group->EndRoll();
374                        m_groupLootTimer = 0;
375                        lootingGroupLeaderGUID = 0;
376                    }
377                }
378            }
379
380            break;
381        }
382        case ALIVE:
383        {
384            if (m_isDeadByDefault)
385            {
386                if( m_deathTimer <= diff )
387                {
388                    RemoveCorpse();
389                    DEBUG_LOG("Removing alive corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY));
390                }
391                else
392                {
393                    m_deathTimer -= diff;
394                }
395            }
396
397            Unit::Update( diff );
398
399            // creature can be dead after Unit::Update call
400            // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
401            if(!isAlive())
402                break;
403
404            if(!IsInEvadeMode())
405            {
406                // do not allow the AI to be changed during update
407                m_AI_locked = true;
408                i_AI->UpdateAI(diff);
409                m_AI_locked = false;
410            }
411
412            // creature can be dead after UpdateAI call
413            // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
414            if(!isAlive())
415                break;
416            if(m_regenTimer > 0)
417            {
418                if(diff >= m_regenTimer)
419                    m_regenTimer = 0;
420                else
421                    m_regenTimer -= diff;
422            }
423            if (m_regenTimer != 0)
424                break;
425
426            if (!isInCombat() || IsPolymorphed())
427                RegenerateHealth();
428
429            RegenerateMana();
430
431            m_regenTimer = 2000;
432            break;
433        }
434        default:
435            break;
436    }
437}
438
439void Creature::RegenerateMana()
440{
441    uint32 curValue = GetPower(POWER_MANA);
442    uint32 maxValue = GetMaxPower(POWER_MANA);
443
444    if (curValue >= maxValue)
445        return;
446
447    uint32 addvalue = 0;
448
449    // Combat and any controlled creature
450    if (isInCombat() || GetCharmerOrOwnerGUID())
451    {
452        if(!IsUnderLastManaUseEffect())
453        {
454            float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
455            float Spirit = GetStat(STAT_SPIRIT);
456
457            addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
458        }
459    }
460    else
461        addvalue = maxValue/3;
462
463    ModifyPower(POWER_MANA, addvalue);
464}
465
466void Creature::RegenerateHealth()
467{
468    if (!isRegeneratingHealth())
469        return;
470
471    uint32 curValue = GetHealth();
472    uint32 maxValue = GetMaxHealth();
473
474    if (curValue >= maxValue)
475        return;
476
477    uint32 addvalue = 0;
478
479    // Not only pet, but any controelled creature
480    if(GetCharmerOrOwnerGUID())
481    {
482        float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
483        float Spirit = GetStat(STAT_SPIRIT);
484
485        if( GetPower(POWER_MANA) > 0 )
486            addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
487        else
488            addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
489    }
490    else
491        addvalue = maxValue/3;
492
493    ModifyHealth(addvalue);
494}
495
496bool Creature::AIM_Initialize()
497{
498    // make sure nothing can change the AI during AI update
499    if(m_AI_locked)
500    {
501        sLog.outDebug("AIM_Initialize: failed to init, locked.");
502        return false;
503    }
504
505    CreatureAI * oldAI = i_AI;
506    i_motionMaster.Initialize();
507    i_AI = FactorySelector::selectAI(this);
508    if (oldAI)
509        delete oldAI;
510    return true;
511}
512
513bool Creature::Create (uint32 guidlow, Map *map, uint32 Entry, uint32 team, const CreatureData *data)
514{
515    SetMapId(map->GetId());
516    SetInstanceId(map->GetInstanceId());
517
518    //oX = x;     oY = y;    dX = x;    dY = y;    m_moveTime = 0;    m_startMove = 0;
519    const bool bResult = CreateFromProto(guidlow, Entry, team, data);
520
521    if (bResult)
522    {
523        switch (GetCreatureInfo()->rank)
524        {
525            case CREATURE_ELITE_RARE:
526                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
527                break;
528            case CREATURE_ELITE_ELITE:
529                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
530                break;
531            case CREATURE_ELITE_RAREELITE:
532                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
533                break;
534            case CREATURE_ELITE_WORLDBOSS:
535                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
536                break;
537            default:
538                m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
539                break;
540        }
541        LoadCreaturesAddon();
542    }
543
544    return bResult;
545}
546
547bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
548{
549    if(!isTrainer())
550        return false;
551
552    TrainerSpellData const* trainer_spells = GetTrainerSpells();
553
554
555    if(!trainer_spells || trainer_spells->spellList.empty())
556    {
557        sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
558            GetGUIDLow(),GetEntry());
559        return false;
560    }
561
562    switch(GetCreatureInfo()->trainer_type)
563    {
564        case TRAINER_TYPE_CLASS:
565            if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
566            {
567                if(msg)
568                {
569                    pPlayer->PlayerTalkClass->ClearMenus();
570                    switch(GetCreatureInfo()->classNum)
571                    {
572                        case CLASS_DRUID:  pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
573                        case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
574                        case CLASS_MAGE:   pPlayer->PlayerTalkClass->SendGossipMenu(  328,GetGUID()); break;
575                        case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
576                        case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
577                        case CLASS_ROGUE:  pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
578                        case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
579                        case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
580                        case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
581                    }
582                }
583                return false;
584            }
585            break;
586        case TRAINER_TYPE_PETS:
587            if(pPlayer->getClass()!=CLASS_HUNTER)
588            {
589                pPlayer->PlayerTalkClass->ClearMenus();
590                pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
591                return false;
592            }
593            break;
594        case TRAINER_TYPE_MOUNTS:
595            if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
596            {
597                if(msg)
598                {
599                    pPlayer->PlayerTalkClass->ClearMenus();
600                    switch(GetCreatureInfo()->classNum)
601                    {
602                        case RACE_DWARF:        pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
603                        case RACE_GNOME:        pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
604                        case RACE_HUMAN:        pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
605                        case RACE_NIGHTELF:     pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
606                        case RACE_ORC:          pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
607                        case RACE_TAUREN:       pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
608                        case RACE_TROLL:        pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
609                        case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
610                        case RACE_BLOODELF:     pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
611                        case RACE_DRAENEI:      pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
612                    }
613                }
614                return false;
615            }
616            break;
617        case TRAINER_TYPE_TRADESKILLS:
618            if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
619            {
620                if(msg)
621                {
622                    pPlayer->PlayerTalkClass->ClearMenus();
623                    pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
624                }
625                return false;
626            }
627            break;
628        default:
629            return false;                                   // checked and error output at creature_template loading
630    }
631    return true;
632}
633
634bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
635{
636    if(!isBattleMaster())
637        return false;
638
639    uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
640    if(!msg)
641        return pPlayer->GetBGAccessByLevel(bgTypeId);
642
643    if(!pPlayer->GetBGAccessByLevel(bgTypeId))
644    {
645        pPlayer->PlayerTalkClass->ClearMenus();
646        switch(bgTypeId)
647        {
648            case BATTLEGROUND_AV:  pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
649            case BATTLEGROUND_WS:  pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
650            case BATTLEGROUND_AB:  pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
651            case BATTLEGROUND_EY:
652            case BATTLEGROUND_NA:
653            case BATTLEGROUND_BE:
654            case BATTLEGROUND_AA:
655            case BATTLEGROUND_RL:  pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
656            break;
657        }
658        return false;
659    }
660    return true;
661}
662
663bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
664{
665    return pPlayer->getLevel() >= 10
666        && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
667        && pPlayer->getClass() == GetCreatureInfo()->classNum;
668}
669
670void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
671{
672    PlayerMenu* pm=pPlayer->PlayerTalkClass;
673    pm->ClearMenus();
674
675    // lazy loading single time at use
676    LoadGossipOptions();
677
678    GossipOption* gso;
679    GossipOption* ingso;
680
681    for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
682    {
683        gso=&*i;
684        if(gso->GossipId == gossipid)
685        {
686            bool cantalking=true;
687            if(gso->Id==1)
688            {
689                uint32 textid=GetNpcTextId();
690                GossipText * gossiptext=objmgr.GetGossipText(textid);
691                if(!gossiptext)
692                    cantalking=false;
693            }
694            else
695            {
696                switch (gso->Action)
697                {
698                    case GOSSIP_OPTION_QUESTGIVER:
699                        pPlayer->PrepareQuestMenu(GetGUID());
700                        //if (pm->GetQuestMenu()->MenuItemCount() == 0)
701                        cantalking=false;
702                        //pm->GetQuestMenu()->ClearMenu();
703                        break;
704                    case GOSSIP_OPTION_ARMORER:
705                        cantalking=false;                   // added in special mode
706                        break;
707                    case GOSSIP_OPTION_SPIRITHEALER:
708                        if( !pPlayer->isDead() )
709                            cantalking=false;
710                        break;
711                    case GOSSIP_OPTION_VENDOR:
712                    {
713                        VendorItemData const* vItems = GetVendorItems();
714                        if(!vItems || vItems->Empty())
715                        {
716                            sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
717                                GetGUIDLow(),GetEntry());
718                            cantalking=false;
719                        }
720                        break;
721                    }
722                    case GOSSIP_OPTION_TRAINER:
723                        if(!isCanTrainingOf(pPlayer,false))
724                            cantalking=false;
725                        break;
726                    case GOSSIP_OPTION_UNLEARNTALENTS:
727                        if(!isCanTrainingAndResetTalentsOf(pPlayer))
728                            cantalking=false;
729                        break;
730                    case GOSSIP_OPTION_UNLEARNPETSKILLS:
731                        if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
732                            cantalking=false;
733                        break;
734                    case GOSSIP_OPTION_TAXIVENDOR:
735                        if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
736                            return;
737                        break;
738                    case GOSSIP_OPTION_BATTLEFIELD:
739                        if(!isCanIneractWithBattleMaster(pPlayer,false))
740                            cantalking=false;
741                        break;
742                    case GOSSIP_OPTION_SPIRITGUIDE:
743                    case GOSSIP_OPTION_INNKEEPER:
744                    case GOSSIP_OPTION_BANKER:
745                    case GOSSIP_OPTION_PETITIONER:
746                    case GOSSIP_OPTION_STABLEPET:
747                    case GOSSIP_OPTION_TABARDDESIGNER:
748                    case GOSSIP_OPTION_AUCTIONEER:
749                        break;                              // no checks
750                    case GOSSIP_OPTION_OUTDOORPVP:
751                        if ( !sOutdoorPvPMgr.CanTalkTo(pPlayer,this,(*gso)) )
752                            cantalking = false;
753                        break;
754                    default:
755                        sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetGUIDLow(),GetEntry(),gso->Action);
756                        break;
757                }
758            }
759
760            if(!gso->Option.empty() && cantalking )
761            {                                               //note for future dev: should have database fields for BoxMessage & BoxMoney
762                pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,gso->Option, gossipid,gso->Action,"",0,false);
763                ingso=gso;
764            }
765        }
766    }
767
768    ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
769    if(pm->Empty())
770    {
771        if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
772        {
773            isCanTrainingOf(pPlayer,true);                  // output error message if need
774        }
775        if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
776        {
777            isCanIneractWithBattleMaster(pPlayer,true);     // output error message if need
778        }
779    }
780}
781
782void Creature::sendPreparedGossip(Player* player)
783{
784    if(!player)
785        return;
786
787    GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
788
789    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT) // if world event npc then
790        gameeventmgr.HandleWorldEventGossip(player, this);      // update world state with progress
791
792    // in case empty gossip menu open quest menu if any
793    if (gossipmenu.Empty() && GetNpcTextId() == 0)
794    {
795        player->SendPreparedQuest(GetGUID());
796        return;
797    }
798
799    // in case non empty gossip menu (that not included quests list size) show it
800    // (quest entries from quest menu wiill be included in list)
801    player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
802}
803
804void Creature::OnGossipSelect(Player* player, uint32 option)
805{
806    GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
807
808    if(option >= gossipmenu.MenuItemCount())
809        return;
810
811    uint32 action=gossipmenu.GetItem(option).m_gAction;
812    uint32 zoneid=GetZoneId();
813    uint64 guid=GetGUID();
814    GossipOption const *gossip=GetGossipOption( action );
815    uint32 textid;
816    if(!gossip)
817    {
818        zoneid=0;
819        gossip=GetGossipOption( action );
820        if(!gossip)
821            return;
822    }
823    textid=GetGossipTextId( action, zoneid);
824    if(textid==0)
825        textid=GetNpcTextId();
826
827    switch (gossip->Action)
828    {
829        case GOSSIP_OPTION_GOSSIP:
830            player->PlayerTalkClass->CloseGossip();
831            player->PlayerTalkClass->SendTalking( textid );
832            break;
833        case GOSSIP_OPTION_OUTDOORPVP:
834            sOutdoorPvPMgr.HandleGossipOption(player, GetGUID(), option);
835            break;
836        case GOSSIP_OPTION_SPIRITHEALER:
837            if( player->isDead() )
838                CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
839            break;
840        case GOSSIP_OPTION_QUESTGIVER:
841            player->PrepareQuestMenu( guid );
842            player->SendPreparedQuest( guid );
843            break;
844        case GOSSIP_OPTION_VENDOR:
845        case GOSSIP_OPTION_ARMORER:
846            player->GetSession()->SendListInventory(guid);
847            break;
848        case GOSSIP_OPTION_STABLEPET:
849            player->GetSession()->SendStablePet(guid);
850            break;
851        case GOSSIP_OPTION_TRAINER:
852            player->GetSession()->SendTrainerList(guid);
853            break;
854        case GOSSIP_OPTION_UNLEARNTALENTS:
855            player->PlayerTalkClass->CloseGossip();
856            player->SendTalentWipeConfirm(guid);
857            break;
858        case GOSSIP_OPTION_UNLEARNPETSKILLS:
859            player->PlayerTalkClass->CloseGossip();
860            player->SendPetSkillWipeConfirm();
861            break;
862        case GOSSIP_OPTION_TAXIVENDOR:
863            player->GetSession()->SendTaxiMenu(this);
864            break;
865        case GOSSIP_OPTION_INNKEEPER:
866            player->PlayerTalkClass->CloseGossip();
867            player->SetBindPoint( guid );
868            break;
869        case GOSSIP_OPTION_BANKER:
870            player->GetSession()->SendShowBank( guid );
871            break;
872        case GOSSIP_OPTION_PETITIONER:
873            player->PlayerTalkClass->CloseGossip();
874            player->GetSession()->SendPetitionShowList( guid );
875            break;
876        case GOSSIP_OPTION_TABARDDESIGNER:
877            player->PlayerTalkClass->CloseGossip();
878            player->GetSession()->SendTabardVendorActivate( guid );
879            break;
880        case GOSSIP_OPTION_AUCTIONEER:
881            player->GetSession()->SendAuctionHello( guid, this );
882            break;
883        case GOSSIP_OPTION_SPIRITGUIDE:
884        case GOSSIP_GUARD_SPELLTRAINER:
885        case GOSSIP_GUARD_SKILLTRAINER:
886            prepareGossipMenu( player,gossip->Id );
887            sendPreparedGossip( player );
888            break;
889        case GOSSIP_OPTION_BATTLEFIELD:
890        {
891            uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
892            player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
893            break;
894        }
895        default:
896            OnPoiSelect( player, gossip );
897            break;
898    }
899
900}
901
902void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
903{
904    if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
905    {
906        //float x,y;
907        //bool findnpc=false;
908        Poi_Icon icon = ICON_POI_0;
909        //QueryResult *result;
910        //Field *fields;
911        uint32 mapid=GetMapId();
912        Map const* map=MapManager::Instance().GetBaseMap( mapid );
913        uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
914        uint32 zoneid=Map::GetZoneId(areaflag,mapid);
915        std::string areaname= gossip->Option;
916        /*
917        uint16 pflag;
918
919        // use the action relate to creaturetemplate.trainer_type ?
920        result= WorldDatabase.PQuery("SELECT creature.position_x,creature.position_y FROM creature,creature_template WHERE creature.map = '%u' AND creature.id = creature_template.entry AND creature_template.trainer_type = '%u'", mapid, gossip->Action );
921        if(!result)
922            return;
923        do
924        {
925            fields = result->Fetch();
926            x=fields[0].GetFloat();
927            y=fields[1].GetFloat();
928            pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
929            if(pflag==areaflag)
930            {
931                findnpc=true;
932                break;
933            }
934        }while(result->NextRow());
935
936        delete result;
937
938        if(!findnpc)
939        {
940            player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
941            return;
942        }*/
943
944        //need add more case.
945        switch(gossip->Action)
946        {
947            case GOSSIP_GUARD_BANK:
948                icon=ICON_POI_HOUSE;
949                break;
950            case GOSSIP_GUARD_RIDE:
951                icon=ICON_POI_RWHORSE;
952                break;
953            case GOSSIP_GUARD_GUILD:
954                icon=ICON_POI_BLUETOWER;
955                break;
956            default:
957                icon=ICON_POI_TOWER;
958                break;
959        }
960        uint32 textid=GetGossipTextId( gossip->Action, zoneid );
961        player->PlayerTalkClass->SendTalking( textid );
962        // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
963    }
964}
965
966uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
967{
968    QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
969
970    if(!result)
971        return 0;
972
973    Field *fields = result->Fetch();
974    uint32 id = fields[0].GetUInt32();
975
976    delete result;
977
978    return id;
979}
980
981uint32 Creature::GetNpcTextId()
982{
983    // don't cache / use cache in case it's a world event announcer
984    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT)
985        if(uint32 textid = gameeventmgr.GetNpcTextId(m_DBTableGuid))
986            return textid;
987
988    if (!m_DBTableGuid)
989        return DEFAULT_GOSSIP_MESSAGE;
990
991    if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
992        return pos;
993
994    return DEFAULT_GOSSIP_MESSAGE;
995}
996
997GossipOption const* Creature::GetGossipOption( uint32 id ) const
998{
999    for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
1000    {
1001        if(i->Action==id )
1002            return &*i;
1003    }
1004    return NULL;
1005}
1006
1007void Creature::ResetGossipOptions()
1008{
1009    m_gossipOptionLoaded = false;
1010    m_goptions.clear();
1011}
1012
1013void Creature::LoadGossipOptions()
1014{
1015    if(m_gossipOptionLoaded)
1016        return;
1017
1018    uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1019
1020    QueryResult *result = WorldDatabase.PQuery( "SELECT id,gossip_id,npcflag,icon,action,option_text FROM npc_option WHERE (npcflag & %u)<>0", npcflags );
1021
1022    if(!result)
1023        return;
1024
1025    GossipOption go;
1026    do
1027    {
1028        Field *fields = result->Fetch();
1029        go.Id= fields[0].GetUInt32();
1030        go.GossipId = fields[1].GetUInt32();
1031        go.NpcFlag=fields[2].GetUInt32();
1032        go.Icon=fields[3].GetUInt32();
1033        go.Action=fields[4].GetUInt32();
1034        go.Option=fields[5].GetCppString();
1035        addGossipOption(go);
1036    }while( result->NextRow() );
1037    delete result;
1038
1039    m_gossipOptionLoaded = true;
1040}
1041
1042void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1043{
1044    /*    uint32 timeElap = getMSTime();
1045        if ((timeElap - m_startMove) < m_moveTime)
1046        {
1047            oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1048            oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1049        }
1050        else
1051        {
1052            oX = dX;
1053            oY = dY;
1054        }
1055
1056        dX = x;
1057        dY = y;
1058        m_orientation = atan2((oY - dY), (oX - dX));
1059
1060        m_startMove = getMSTime();
1061        m_moveTime = time;*/
1062    SendMonsterMove(x, y, z, type, MovementFlags, time);
1063}
1064
1065Player *Creature::GetLootRecipient() const
1066{
1067    if (!m_lootRecipient) return NULL;
1068    else return ObjectAccessor::FindPlayer(m_lootRecipient);
1069}
1070
1071void Creature::SetLootRecipient(Unit *unit)
1072{
1073    // set the player whose group should receive the right
1074    // to loot the creature after it dies
1075    // should be set to NULL after the loot disappears
1076
1077    if (!unit)
1078    {
1079        m_lootRecipient = 0;
1080        RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1081        return;
1082    }
1083
1084    Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1085    if(!player)                                             // normal creature, no player involved
1086        return;
1087
1088    m_lootRecipient = player->GetGUID();
1089    SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1090}
1091
1092void Creature::SaveToDB()
1093{
1094    // this should only be used when the creature has already been loaded
1095    // perferably after adding to map, because mapid may not be valid otherwise
1096    CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1097    if(!data)
1098    {
1099        sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1100        return;
1101    }
1102
1103    SaveToDB(GetMapId(), data->spawnMask);
1104}
1105
1106void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1107{
1108    // update in loaded data
1109    if (!m_DBTableGuid)
1110        m_DBTableGuid = GetGUIDLow();
1111    CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1112
1113    uint32 displayId = GetNativeDisplayId();
1114
1115    // check if it's a custom model and if not, use 0 for displayId
1116    CreatureInfo const *cinfo = GetCreatureInfo();
1117    if(cinfo)
1118    {
1119        if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1120        {
1121            CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1122            if(!minfo || displayId != minfo->modelid_other_gender)
1123            {
1124                minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1125                if(minfo && displayId == minfo->modelid_other_gender)
1126                    displayId = 0;
1127            }
1128            else
1129                displayId = 0;
1130        }
1131        else
1132            displayId = 0;
1133    }
1134
1135    // data->guid = guid don't must be update at save
1136    data.id = GetEntry();
1137    data.mapid = mapid;
1138    data.displayid = displayId;
1139    data.equipmentId = GetEquipmentId();
1140    data.posX = GetPositionX();
1141    data.posY = GetPositionY();
1142    data.posZ = GetPositionZ();
1143    data.orientation = GetOrientation();
1144    data.spawntimesecs = m_respawnDelay;
1145    // prevent add data integrity problems
1146    data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1147    data.currentwaypoint = 0;
1148    data.curhealth = GetHealth();
1149    data.curmana = GetPower(POWER_MANA);
1150    data.is_dead = m_isDeadByDefault;
1151    // prevent add data integrity problems
1152    data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1153        ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1154    data.spawnMask = spawnMask;
1155
1156    // updated in DB
1157    WorldDatabase.BeginTransaction();
1158
1159    WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1160
1161    std::ostringstream ss;
1162    ss << "INSERT INTO creature VALUES ("
1163        << m_DBTableGuid << ","
1164        << GetEntry() << ","
1165        << mapid <<","
1166        << (uint32)spawnMask << ","
1167        << displayId <<","
1168        << GetEquipmentId() <<","
1169        << GetPositionX() << ","
1170        << GetPositionY() << ","
1171        << GetPositionZ() << ","
1172        << GetOrientation() << ","
1173        << m_respawnDelay << ","                            //respawn time
1174        << (float) m_respawnradius << ","                   //spawn distance (float)
1175        << (uint32) (0) << ","                              //currentwaypoint
1176        << GetHealth() << ","                               //curhealth
1177        << GetPower(POWER_MANA) << ","                      //curmana
1178        << (m_isDeadByDefault ? 1 : 0) << ","               //is_dead
1179        << GetDefaultMovementType() << ")";                 //default movement generator type
1180
1181    WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1182
1183    WorldDatabase.CommitTransaction();
1184}
1185
1186void Creature::SelectLevel(const CreatureInfo *cinfo)
1187{
1188    uint32 rank = isPet()? 0 : cinfo->rank;
1189
1190    // level
1191    uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1192    uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1193    uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1194    SetLevel(level);
1195
1196    float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1197
1198    // health
1199    float healthmod = _GetHealthMod(rank);
1200
1201    uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1202    uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1203    uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1204
1205    SetCreateHealth(health);
1206    SetMaxHealth(health);
1207    SetHealth(health);
1208
1209    // mana
1210    uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1211    uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1212    uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1213
1214    SetCreateMana(mana);
1215    SetMaxPower(POWER_MANA, mana);                          //MAX Mana
1216    SetPower(POWER_MANA, mana);
1217
1218    SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1219    SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1220
1221    // damage
1222    float damagemod = _GetDamageMod(rank);
1223
1224    SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1225    SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1226
1227    SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1228    SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1229
1230    SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1231}
1232
1233float Creature::_GetHealthMod(int32 Rank)
1234{
1235    switch (Rank)                                           // define rates for each elite rank
1236    {
1237        case CREATURE_ELITE_NORMAL:
1238            return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1239        case CREATURE_ELITE_ELITE:
1240            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1241        case CREATURE_ELITE_RAREELITE:
1242            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1243        case CREATURE_ELITE_WORLDBOSS:
1244            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1245        case CREATURE_ELITE_RARE:
1246            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1247        default:
1248            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1249    }
1250}
1251
1252float Creature::_GetDamageMod(int32 Rank)
1253{
1254    switch (Rank)                                           // define rates for each elite rank
1255    {
1256        case CREATURE_ELITE_NORMAL:
1257            return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1258        case CREATURE_ELITE_ELITE:
1259            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1260        case CREATURE_ELITE_RAREELITE:
1261            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1262        case CREATURE_ELITE_WORLDBOSS:
1263            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1264        case CREATURE_ELITE_RARE:
1265            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1266        default:
1267            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1268    }
1269}
1270
1271float Creature::GetSpellDamageMod(int32 Rank)
1272{
1273    switch (Rank)                                           // define rates for each elite rank
1274    {
1275        case CREATURE_ELITE_NORMAL:
1276            return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1277        case CREATURE_ELITE_ELITE:
1278            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1279        case CREATURE_ELITE_RAREELITE:
1280            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1281        case CREATURE_ELITE_WORLDBOSS:
1282            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1283        case CREATURE_ELITE_RARE:
1284            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1285        default:
1286            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1287    }
1288}
1289
1290bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1291{
1292    CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1293    if(!cinfo)
1294    {
1295        sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1296        return false;
1297    }
1298    m_originalEntry = Entry;
1299
1300    Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1301
1302    if(!UpdateEntry(Entry, team, data))
1303        return false;
1304
1305    //Notify the map's instance data.
1306    //Only works if you create the object in it, not if it is moves to that map.
1307    //Normally non-players do not teleport to other maps.
1308    Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1309    if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1310    {
1311        ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1312    }
1313
1314    return true;
1315}
1316
1317bool Creature::LoadFromDB(uint32 guid, Map *map)
1318{
1319    CreatureData const* data = objmgr.GetCreatureData(guid);
1320
1321    if(!data)
1322    {
1323        sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1324        return false;
1325    }
1326
1327    m_DBTableGuid = guid;
1328    if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1329
1330    uint16 team = 0;
1331    if(!Create(guid,map,data->id,team,data))
1332        return false;
1333
1334    Relocate(data->posX,data->posY,data->posZ,data->orientation);
1335
1336    if(!IsPositionValid())
1337    {
1338        sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1339        return false;
1340    }
1341
1342    m_respawnradius = data->spawndist;
1343
1344    m_respawnDelay = data->spawntimesecs;
1345    m_isDeadByDefault = data->is_dead;
1346    m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1347
1348    m_respawnTime  = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1349    if(m_respawnTime > time(NULL))                          // not ready to respawn
1350        m_deathState = DEAD;
1351    else if(m_respawnTime)                                  // respawn time set but expired
1352    {
1353        m_respawnTime = 0;
1354        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1355    }
1356
1357    uint32 curhealth = data->curhealth;
1358    if(curhealth)
1359    {
1360        curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1361        if(curhealth < 1)
1362            curhealth = 1;
1363    }
1364
1365    SetHealth(m_deathState == ALIVE ? curhealth : 0);
1366    SetPower(POWER_MANA,data->curmana);
1367
1368    SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1369
1370    // checked at creature_template loading
1371    m_defaultMovementType = MovementGeneratorType(data->movementType);
1372
1373    AIM_Initialize();
1374    return true;
1375}
1376
1377void Creature::LoadEquipment(uint32 equip_entry, bool force)
1378{
1379    if(equip_entry == 0)
1380    {
1381        if (force)
1382        {
1383            for (uint8 i=0;i<3;i++)
1384            {
1385                SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1386                SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1387                SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1388            }
1389            m_equipmentId = 0;
1390        }
1391        return;
1392    }
1393
1394    EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1395    if (!einfo)
1396        return;
1397
1398    m_equipmentId = equip_entry;
1399    for (uint8 i=0;i<3;i++)
1400    {
1401        SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1402        SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1403        SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1404    }
1405}
1406
1407bool Creature::hasQuest(uint32 quest_id) const
1408{
1409    QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1410    for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1411    {
1412        if(itr->second==quest_id)
1413            return true;
1414    }
1415    return false;
1416}
1417
1418bool Creature::hasInvolvedQuest(uint32 quest_id) const
1419{
1420    QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1421    for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1422    {
1423        if(itr->second==quest_id)
1424            return true;
1425    }
1426    return false;
1427}
1428
1429void Creature::DeleteFromDB()
1430{
1431    if (!m_DBTableGuid)
1432    {
1433        sLog.outDebug("Trying to delete not saved creature!");
1434        return;
1435    }
1436
1437    objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1438    objmgr.DeleteCreatureData(m_DBTableGuid);
1439
1440    WorldDatabase.BeginTransaction();
1441    WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1442    WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1443    WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1444    WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1445    WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1446    WorldDatabase.CommitTransaction();
1447}
1448
1449float Creature::GetAttackDistance(Unit const* pl) const
1450{
1451    float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1452    if(aggroRate==0)
1453        return 0.0f;
1454
1455    int32 playerlevel   = pl->getLevelForTarget(this);
1456    int32 creaturelevel = getLevelForTarget(pl);
1457
1458    int32 leveldif       = playerlevel - creaturelevel;
1459
1460    // "The maximum Aggro Radius has a cap of 25 levels under. Example: A level 30 char has the same Aggro Radius of a level 5 char on a level 60 mob."
1461    if ( leveldif < - 25)
1462        leveldif = -25;
1463
1464    // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1465    float RetDistance = 20;
1466
1467    // "Aggro Radius varries with level difference at a rate of roughly 1 yard/level"
1468    // radius grow if playlevel < creaturelevel
1469    RetDistance -= (float)leveldif;
1470
1471    if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1472    {
1473        // detect range auras
1474        RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1475
1476        // detected range auras
1477        RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1478    }
1479
1480    // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1481    if(RetDistance < 5)
1482        RetDistance = 5;
1483
1484    return (RetDistance*aggroRate);
1485}
1486
1487void Creature::setDeathState(DeathState s)
1488{
1489    if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1490    {
1491        m_deathTimer = m_corpseDelay*1000;
1492
1493        // always save boss respawn time at death to prevent crash cheating
1494        if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1495            SaveRespawnTime();
1496
1497        if(!IsStopped())
1498            StopMoving();
1499    }
1500    Unit::setDeathState(s);
1501
1502    if(s == JUST_DIED)
1503    {
1504        SetUInt64Value (UNIT_FIELD_TARGET,0);               // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1505        SetUInt32Value(UNIT_NPC_FLAGS, 0);
1506
1507        if(!isPet() && GetCreatureInfo()->SkinLootId)
1508            if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1509                SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1510
1511        Unit::setDeathState(CORPSE);
1512    }
1513    if(s == JUST_ALIVED)
1514    {
1515        SetHealth(GetMaxHealth());
1516        SetLootRecipient(NULL);
1517        Unit::setDeathState(ALIVE);
1518        CreatureInfo const *cinfo = GetCreatureInfo();
1519        SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1520        RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1521        AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1522        SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1523        clearUnitState(UNIT_STAT_ALL_STATE);
1524        i_motionMaster.Clear();
1525        SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1526        LoadCreaturesAddon(true);
1527    }
1528}
1529
1530void Creature::Respawn()
1531{
1532    RemoveCorpse();
1533
1534    // forced recreate creature object at clients
1535    UnitVisibility currentVis = GetVisibility();
1536    SetVisibility(VISIBILITY_RESPAWN);
1537    ObjectAccessor::UpdateObjectVisibility(this);
1538    SetVisibility(currentVis);                              // restore visibility state
1539    ObjectAccessor::UpdateObjectVisibility(this);
1540
1541    if(getDeathState()==DEAD)
1542    {
1543        if (m_DBTableGuid)
1544            objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1545        m_respawnTime = time(NULL);                         // respawn at next tick
1546    }
1547}
1548
1549bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1550{
1551    if (!spellInfo)
1552        return false;
1553
1554    if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1555        return true;
1556
1557    return Unit::IsImmunedToSpell(spellInfo, useCharges);
1558}
1559
1560bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1561{
1562    if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1563        return true;
1564
1565    return Unit::IsImmunedToSpellEffect(effect, mechanic);
1566}
1567
1568SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1569{
1570    if(!pVictim)
1571        return NULL;
1572
1573    for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1574    {
1575        if(!m_spells[i])
1576            continue;
1577        SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1578        if(!spellInfo)
1579        {
1580            sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1581            continue;
1582        }
1583
1584        bool bcontinue = true;
1585        for(uint32 j=0;j<3;j++)
1586        {
1587            if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE )       ||
1588                (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL)            ||
1589                (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1590                (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1591                )
1592            {
1593                bcontinue = false;
1594                break;
1595            }
1596        }
1597        if(bcontinue) continue;
1598
1599        if(spellInfo->manaCost > GetPower(POWER_MANA))
1600            continue;
1601        SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1602        float range = GetSpellMaxRange(srange);
1603        float minrange = GetSpellMinRange(srange);
1604        float dist = GetDistance(pVictim);
1605        //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1606        //    continue;
1607        if( dist > range || dist < minrange )
1608            continue;
1609        if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1610            continue;
1611        return spellInfo;
1612    }
1613    return NULL;
1614}
1615
1616SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1617{
1618    if(!pVictim)
1619        return NULL;
1620
1621    for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1622    {
1623        if(!m_spells[i])
1624            continue;
1625        SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1626        if(!spellInfo)
1627        {
1628            sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1629            continue;
1630        }
1631
1632        bool bcontinue = true;
1633        for(uint32 j=0;j<3;j++)
1634        {
1635            if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1636            {
1637                bcontinue = false;
1638                break;
1639            }
1640        }
1641        if(bcontinue) continue;
1642
1643        if(spellInfo->manaCost > GetPower(POWER_MANA))
1644            continue;
1645        SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1646        float range = GetSpellMaxRange(srange);
1647        float minrange = GetSpellMinRange(srange);
1648        float dist = GetDistance(pVictim);
1649        //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1650        //    continue;
1651        if( dist > range || dist < minrange )
1652            continue;
1653        if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1654            continue;
1655        return spellInfo;
1656    }
1657    return NULL;
1658}
1659
1660bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1661{
1662    // gamemaster in GM mode see all, including ghosts
1663    if(pl->isGameMaster())
1664        return true;
1665
1666    // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1667    if(pl->isAlive() || pl->GetDeathTimer() > 0)
1668    {
1669        if( GetEntry() == VISUAL_WAYPOINT && !pl->isGameMaster() )
1670            return false;
1671        return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1672    }
1673
1674    // Dead player see live creatures near own corpse
1675    if(isAlive())
1676    {
1677        Corpse *corpse = pl->GetCorpse();
1678        if(corpse)
1679        {
1680            // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1681            if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1682                return true;
1683        }
1684    }
1685
1686    // Dead player see Spirit Healer or Spirit Guide
1687    if(isSpiritService())
1688        return true;
1689
1690    // and not see any other
1691    return false;
1692}
1693
1694void Creature::DoFleeToGetAssistance(float radius) // Optional parameter
1695{
1696    if (!getVictim())
1697        return;
1698
1699    Creature* pCreature = NULL;
1700
1701    CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
1702    Cell cell(p);
1703    cell.data.Part.reserved = ALL_DISTRICT;
1704    cell.SetNoCreate();
1705
1706    Trinity::NearestAssistCreatureInCreatureRangeCheck u_check(this,getVictim(),radius);
1707    Trinity::CreatureLastSearcher<Trinity::NearestAssistCreatureInCreatureRangeCheck> searcher(pCreature, u_check);
1708
1709    TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1710
1711    CellLock<GridReadGuard> cell_lock(cell, p);
1712    cell_lock->Visit(cell_lock, grid_creature_searcher, *(GetMap()));
1713
1714    if(!GetMotionMaster()->empty() && (GetMotionMaster()->GetCurrentMovementGeneratorType() != POINT_MOTION_TYPE))
1715        GetMotionMaster()->Clear(false);
1716    if(pCreature == NULL)
1717    {
1718        GetMotionMaster()->MoveIdle();
1719        GetMotionMaster()->MoveFleeing(getVictim());
1720    }
1721    else
1722    {
1723        GetMotionMaster()->MoveIdle();
1724        GetMotionMaster()->MovePoint(0,pCreature->GetPositionX(),pCreature->GetPositionY(),pCreature->GetPositionZ());
1725    }
1726}
1727
1728void Creature::CallAssistence()
1729{
1730    if( !m_AlreadyCallAssistence && getVictim() && !isPet() && !isCharmed())
1731    {
1732        SetNoCallAssistence(true);
1733
1734        float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS);
1735        if(radius > 0)
1736        {
1737            std::list<Creature*> assistList;
1738
1739            {
1740                CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
1741                Cell cell(p);
1742                cell.data.Part.reserved = ALL_DISTRICT;
1743                cell.SetNoCreate();
1744
1745                Trinity::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1746                Trinity::CreatureListSearcher<Trinity::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1747
1748                TypeContainerVisitor<Trinity::CreatureListSearcher<Trinity::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1749
1750                CellLock<GridReadGuard> cell_lock(cell, p);
1751                cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
1752            }
1753
1754            for(std::list<Creature*>::iterator iter = assistList.begin(); iter != assistList.end(); ++iter)
1755            {
1756                (*iter)->SetNoCallAssistence(true);
1757                if((*iter)->AI())
1758                    (*iter)->AI()->AttackStart(getVictim());
1759            }
1760        }
1761    }
1762}
1763
1764void Creature::SaveRespawnTime()
1765{
1766    if(isPet() || !m_DBTableGuid)
1767        return;
1768
1769    if(m_respawnTime > time(NULL))                          // dead (no corpse)
1770        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1771    else if(m_deathTimer > 0)                               // dead (corpse)
1772        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1773}
1774
1775bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1776{
1777    if(!pVictim)
1778        return true;
1779
1780    if(!pVictim->IsInMap(this))
1781        return true;
1782
1783    if(!pVictim->isTargetableForAttack())
1784        return true;
1785
1786    if(!pVictim->isInAccessablePlaceFor(this))
1787        return true;
1788
1789    if(sMapStore.LookupEntry(GetMapId())->Instanceable())
1790        return false;
1791
1792    float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1793    float AttackDist = GetAttackDistance(pVictim);
1794    uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1795
1796    //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and ouf of combat every update tick.
1797    return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1798}
1799
1800CreatureDataAddon const* Creature::GetCreatureAddon() const
1801{
1802    if (m_DBTableGuid)
1803    {
1804        if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1805            return addon;
1806    }
1807
1808    // dependent from heroic mode entry
1809    return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1810}
1811
1812//creature_addon table
1813bool Creature::LoadCreaturesAddon(bool reload)
1814{
1815    CreatureDataAddon const *cainfo = GetCreatureAddon();
1816    if(!cainfo)
1817        return false;
1818
1819    if (cainfo->mount != 0)
1820        Mount(cainfo->mount);
1821
1822    if (cainfo->bytes0 != 0)
1823        SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1824
1825    if (cainfo->bytes1 != 0)
1826        SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1827
1828    if (cainfo->bytes2 != 0)
1829        SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1830
1831    if (cainfo->emote != 0)
1832        SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1833
1834    if (cainfo->move_flags != 0)
1835        SetUnitMovementFlags(cainfo->move_flags);
1836
1837    if(cainfo->auras)
1838    {
1839        for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1840        {
1841            SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1842            if (!AdditionalSpellInfo)
1843            {
1844                sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1845                continue;
1846            }
1847
1848            // skip already applied aura
1849            if(HasAura(cAura->spell_id,cAura->effect_idx))
1850            {
1851                if(!reload)
1852                    sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has duplicate aura (spell %u effect %u) in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id,cAura->effect_idx);
1853
1854                continue;
1855            }
1856
1857            Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1858            AddAura(AdditionalAura);
1859            sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1860        }
1861    }
1862    return true;
1863}
1864
1865/// Send a message to LocalDefense channel for players oposition team in the zone
1866void Creature::SendZoneUnderAttackMessage(Player* attacker)
1867{
1868    uint32 enemy_team = attacker->GetTeam();
1869
1870    WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1871    data << (uint32)GetZoneId();
1872    sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1873}
1874
1875void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1876{
1877    m_CreatureSpellCooldowns[spell_id] = end_time;
1878}
1879
1880void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1881{
1882    m_CreatureCategoryCooldowns[category] = apply_time;
1883}
1884
1885void Creature::AddCreatureSpellCooldown(uint32 spellid)
1886{
1887    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1888    if(!spellInfo)
1889        return;
1890
1891    uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1892    if(cooldown)
1893        _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1894
1895    if(spellInfo->Category)
1896        _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1897
1898    m_GlobalCooldown = spellInfo->StartRecoveryTime;
1899}
1900
1901bool Creature::HasCategoryCooldown(uint32 spell_id) const
1902{
1903    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1904    if(!spellInfo)
1905        return false;
1906
1907    // check global cooldown if spell affected by it
1908    if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1909        return true;
1910
1911    CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1912    return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1913}
1914
1915bool Creature::HasSpellCooldown(uint32 spell_id) const
1916{
1917    CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1918    return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1919}
1920
1921bool Creature::IsInEvadeMode() const
1922{
1923    return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1924}
1925
1926bool Creature::HasSpell(uint32 spellID) const
1927{
1928    uint8 i;
1929    for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1930        if(spellID == m_spells[i])
1931            break;
1932    return i < CREATURE_MAX_SPELLS;                         //broke before end of iteration of known spells
1933}
1934
1935time_t Creature::GetRespawnTimeEx() const
1936{
1937    time_t now = time(NULL);
1938    if(m_respawnTime > now)                                 // dead (no corpse)
1939        return m_respawnTime;
1940    else if(m_deathTimer > 0)                               // dead (corpse)
1941        return now+m_respawnDelay+m_deathTimer/1000;
1942    else
1943        return now;
1944}
1945
1946void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1947{
1948    if (m_DBTableGuid)
1949    {
1950        if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1951        {
1952            x = data->posX;
1953            y = data->posY;
1954            z = data->posZ;
1955            if(ori)
1956                *ori = data->orientation;
1957            if(dist)
1958                *dist = data->spawndist;
1959
1960            return;
1961        }
1962    }
1963
1964    x = GetPositionX();
1965    y = GetPositionY();
1966    z = GetPositionZ();
1967    if(ori)
1968        *ori = GetOrientation();
1969    if(dist)
1970        *dist = 0;
1971}
1972
1973void Creature::AllLootRemovedFromCorpse()
1974{
1975    if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1976    {
1977        uint32 nDeathTimer;
1978
1979        CreatureInfo const *cinfo = GetCreatureInfo();
1980
1981        // corpse was not skinnable -> apply corpse looted timer
1982        if (!cinfo || !cinfo->SkinLootId)
1983            nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1984        // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1985        else
1986            nDeathTimer = 0;
1987
1988        // update death timer only if looted timer is shorter
1989        if (m_deathTimer > nDeathTimer)
1990            m_deathTimer = nDeathTimer;
1991    }
1992}
1993
1994uint32 Creature::getLevelForTarget( Unit const* target ) const
1995{
1996    if(!isWorldBoss())
1997        return Unit::getLevelForTarget(target);
1998
1999    uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2000    if(level < 1)
2001        return 1;
2002    if(level > 255)
2003        return 255;
2004    return level;
2005}
2006
2007char const* Creature::GetScriptName() const
2008{
2009    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptName;
2010}
2011
2012
2013VendorItemData const* Creature::GetVendorItems() const
2014{
2015    return objmgr.GetNpcVendorItemList(GetEntry());
2016}
2017
2018uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2019{
2020    if(!vItem->maxcount)
2021        return vItem->maxcount;
2022
2023    VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2024    for(; itr != m_vendorItemCounts.end(); ++itr)
2025        if(itr->itemId==vItem->item)
2026            break;
2027
2028    if(itr == m_vendorItemCounts.end())
2029        return vItem->maxcount;
2030
2031    VendorItemCount* vCount = &*itr;
2032
2033    time_t ptime = time(NULL);
2034
2035    if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2036    {
2037        ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2038
2039        uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2040        if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2041        {
2042            m_vendorItemCounts.erase(itr);       
2043            return vItem->maxcount;
2044        }
2045
2046        vCount->count += diff * pProto->BuyCount;
2047        vCount->lastIncrementTime = ptime;
2048    }
2049
2050    return vCount->count;
2051}
2052
2053uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2054{
2055    if(!vItem->maxcount)
2056        return 0;
2057
2058    VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2059    for(; itr != m_vendorItemCounts.end(); ++itr)
2060        if(itr->itemId==vItem->item)
2061            break;
2062
2063    if(itr == m_vendorItemCounts.end())
2064    {
2065        uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2066        m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2067        return new_count;
2068    }
2069
2070    VendorItemCount* vCount = &*itr;
2071
2072    time_t ptime = time(NULL);
2073
2074    if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2075    {
2076        ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2077
2078        uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2079        if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2080            vCount->count += diff * pProto->BuyCount;
2081        else
2082            vCount->count = vItem->maxcount;
2083    }
2084
2085    vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2086    vCount->lastIncrementTime = ptime;
2087    return vCount->count;
2088}
2089
2090TrainerSpellData const* Creature::GetTrainerSpells() const
2091{
2092    return objmgr.GetNpcTrainerSpells(GetEntry());
2093}
Note: See TracBrowser for help on using the browser.