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

Revision 265, 72.8 kB (checked in by yumileroy, 17 years ago)

*Add m_isAggressive. Only aggressive creatures will call AttackStart? and MoveInLineOfSight?.
*Set melee dmg school for summoned creatures.
*Fix some compiling errors.

Original author: megamage
Date: 2008-11-20 18:54:50-06:00

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