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

Revision 136, 69.7 kB (checked in by yumileroy, 17 years ago)

[svn] Provide creature dual wield support.
Update glancing damage formula.
Do not daze creatures when other creatures attack from the back (need to find a better way).
Fix the damage calculation of +damage aura.

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