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

Revision 168, 70.0 kB (checked in by yumileroy, 17 years ago)

[svn] *** Source Mangos ***
*Load npc_options at server startup, use cached data at creature gossip menu init.
* Also new .reload table command added
*Implement npc_option localization support, also store in DB BoxText/BoxMoney/Coded?
* Use characters.guid instead low guid value from characters.data in charcter enum data prepering for client.
* Fixed crash at .pinfo command use from console.
* Fixed windows ad.exe build
*Creature related code and DB cleanups.
* Rename 2 creature_template fields to more clean names and related code update also.
* Use enum values instead raw values for type_flags, use halper functions instead code repeating.
* Move tamed pet creating code to new function.

** Small code changes to make things compliant with above changes.
** Another rev with big changes so test away.

Original author: KingPin?
Date: 2008-11-05 09:22:56-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// 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()->unit_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    if(!trainer_spells || trainer_spells->spellList.empty())
578    {
579        sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
580            GetGUIDLow(),GetEntry());
581        return false;
582    }
583
584    switch(GetCreatureInfo()->trainer_type)
585    {
586        case TRAINER_TYPE_CLASS:
587            if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
588            {
589                if(msg)
590                {
591                    pPlayer->PlayerTalkClass->ClearMenus();
592                    switch(GetCreatureInfo()->classNum)
593                    {
594                        case CLASS_DRUID:  pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
595                        case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
596                        case CLASS_MAGE:   pPlayer->PlayerTalkClass->SendGossipMenu(  328,GetGUID()); break;
597                        case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
598                        case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
599                        case CLASS_ROGUE:  pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
600                        case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
601                        case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
602                        case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
603                    }
604                }
605                return false;
606            }
607            break;
608        case TRAINER_TYPE_PETS:
609            if(pPlayer->getClass()!=CLASS_HUNTER)
610            {
611                pPlayer->PlayerTalkClass->ClearMenus();
612                pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
613                return false;
614            }
615            break;
616        case TRAINER_TYPE_MOUNTS:
617            if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
618            {
619                if(msg)
620                {
621                    pPlayer->PlayerTalkClass->ClearMenus();
622                    switch(GetCreatureInfo()->classNum)
623                    {
624                        case RACE_DWARF:        pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
625                        case RACE_GNOME:        pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
626                        case RACE_HUMAN:        pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
627                        case RACE_NIGHTELF:     pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
628                        case RACE_ORC:          pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
629                        case RACE_TAUREN:       pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
630                        case RACE_TROLL:        pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
631                        case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
632                        case RACE_BLOODELF:     pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
633                        case RACE_DRAENEI:      pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
634                    }
635                }
636                return false;
637            }
638            break;
639        case TRAINER_TYPE_TRADESKILLS:
640            if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
641            {
642                if(msg)
643                {
644                    pPlayer->PlayerTalkClass->ClearMenus();
645                    pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
646                }
647                return false;
648            }
649            break;
650        default:
651            return false;                                   // checked and error output at creature_template loading
652    }
653    return true;
654}
655
656bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
657{
658    if(!isBattleMaster())
659        return false;
660
661    uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
662    if(!msg)
663        return pPlayer->GetBGAccessByLevel(bgTypeId);
664
665    if(!pPlayer->GetBGAccessByLevel(bgTypeId))
666    {
667        pPlayer->PlayerTalkClass->ClearMenus();
668        switch(bgTypeId)
669        {
670            case BATTLEGROUND_AV:  pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
671            case BATTLEGROUND_WS:  pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
672            case BATTLEGROUND_AB:  pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
673            case BATTLEGROUND_EY:
674            case BATTLEGROUND_NA:
675            case BATTLEGROUND_BE:
676            case BATTLEGROUND_AA:
677            case BATTLEGROUND_RL:  pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
678            break;
679        }
680        return false;
681    }
682    return true;
683}
684
685bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
686{
687    return pPlayer->getLevel() >= 10
688        && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
689        && pPlayer->getClass() == GetCreatureInfo()->classNum;
690}
691
692void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
693{
694    PlayerMenu* pm=pPlayer->PlayerTalkClass;
695    pm->ClearMenus();
696
697    // lazy loading single time at use
698    LoadGossipOptions();
699
700    for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
701    {
702        GossipOption* gso=&*i;
703        if(gso->GossipId == gossipid)
704        {
705            bool cantalking=true;
706            if(gso->Id==1)
707            {
708                uint32 textid=GetNpcTextId();
709                GossipText * gossiptext=objmgr.GetGossipText(textid);
710                if(!gossiptext)
711                    cantalking=false;
712            }
713            else
714            {
715                switch (gso->Action)
716                {
717                    case GOSSIP_OPTION_QUESTGIVER:
718                        pPlayer->PrepareQuestMenu(GetGUID());
719                        //if (pm->GetQuestMenu()->MenuItemCount() == 0)
720                        cantalking=false;
721                        //pm->GetQuestMenu()->ClearMenu();
722                        break;
723                    case GOSSIP_OPTION_ARMORER:
724                        cantalking=false;                   // added in special mode
725                        break;
726                    case GOSSIP_OPTION_SPIRITHEALER:
727                        if( !pPlayer->isDead() )
728                            cantalking=false;
729                        break;
730                    case GOSSIP_OPTION_VENDOR:
731                    {
732                        VendorItemData const* vItems = GetVendorItems();
733                        if(!vItems || vItems->Empty())
734                        {
735                            sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
736                                GetGUIDLow(),GetEntry());
737                            cantalking=false;
738                        }
739                        break;
740                    }
741                    case GOSSIP_OPTION_TRAINER:
742                        if(!isCanTrainingOf(pPlayer,false))
743                            cantalking=false;
744                        break;
745                    case GOSSIP_OPTION_UNLEARNTALENTS:
746                        if(!isCanTrainingAndResetTalentsOf(pPlayer))
747                            cantalking=false;
748                        break;
749                    case GOSSIP_OPTION_UNLEARNPETSKILLS:
750                        if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
751                            cantalking=false;
752                        break;
753                    case GOSSIP_OPTION_TAXIVENDOR:
754                        if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
755                            return;
756                        break;
757                    case GOSSIP_OPTION_BATTLEFIELD:
758                        if(!isCanIneractWithBattleMaster(pPlayer,false))
759                            cantalking=false;
760                        break;
761                    case GOSSIP_OPTION_SPIRITGUIDE:
762                    case GOSSIP_OPTION_INNKEEPER:
763                    case GOSSIP_OPTION_BANKER:
764                    case GOSSIP_OPTION_PETITIONER:
765                    case GOSSIP_OPTION_STABLEPET:
766                    case GOSSIP_OPTION_TABARDDESIGNER:
767                    case GOSSIP_OPTION_AUCTIONEER:
768                        break;                              // no checks
769                    case GOSSIP_OPTION_OUTDOORPVP:
770                        if ( !sOutdoorPvPMgr.CanTalkTo(pPlayer,this,(*gso)) )
771                            cantalking = false;
772                        break;
773                    default:
774                        sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
775                        break;
776                }
777            }
778
779            //note for future dev: should have database fields for BoxMessage & BoxMoney
780            if(!gso->OptionText.empty() && cantalking)
781            {
782                std::string OptionText = gso->OptionText;
783                std::string BoxText = gso->BoxText;
784                int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
785                if (loc_idx >= 0)
786                {
787                    NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
788                    if (no)
789                    {
790                        if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
791                            OptionText=no->OptionText[loc_idx];
792                        if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
793                            BoxText=no->BoxText[loc_idx];
794                    }
795                }
796                pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
797            }
798        }
799    }
800
801    ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
802    if(pm->Empty())
803    {
804        if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
805        {
806            isCanTrainingOf(pPlayer,true);                  // output error message if need
807        }
808        if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
809        {
810            isCanIneractWithBattleMaster(pPlayer,true);     // output error message if need
811        }
812    }
813}
814
815void Creature::sendPreparedGossip(Player* player)
816{
817    if(!player)
818        return;
819
820    GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
821
822    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT) // if world event npc then
823        gameeventmgr.HandleWorldEventGossip(player, this);      // update world state with progress
824
825    // in case empty gossip menu open quest menu if any
826    if (gossipmenu.Empty() && GetNpcTextId() == 0)
827    {
828        player->SendPreparedQuest(GetGUID());
829        return;
830    }
831
832    // in case non empty gossip menu (that not included quests list size) show it
833    // (quest entries from quest menu wiill be included in list)
834    player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
835}
836
837void Creature::OnGossipSelect(Player* player, uint32 option)
838{
839    GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
840
841    if(option >= gossipmenu.MenuItemCount())
842        return;
843
844    uint32 action=gossipmenu.GetItem(option).m_gAction;
845    uint32 zoneid=GetZoneId();
846    uint64 guid=GetGUID();
847
848    GossipOption const *gossip=GetGossipOption( action );
849    if(!gossip)
850    {
851        zoneid=0;
852        gossip=GetGossipOption( action );
853        if(!gossip)
854            return;
855    }
856    uint32 textid=GetGossipTextId( action, zoneid);
857    if(textid==0)
858        textid=GetNpcTextId();
859
860    switch (gossip->Action)
861    {
862        case GOSSIP_OPTION_GOSSIP:
863            player->PlayerTalkClass->CloseGossip();
864            player->PlayerTalkClass->SendTalking(textid);
865            break;
866        case GOSSIP_OPTION_OUTDOORPVP:
867            sOutdoorPvPMgr.HandleGossipOption(player, GetGUID(), option);
868            break;
869        case GOSSIP_OPTION_SPIRITHEALER:
870            if (player->isDead())
871                CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
872            break;
873        case GOSSIP_OPTION_QUESTGIVER:
874            player->PrepareQuestMenu( guid );
875            player->SendPreparedQuest( guid );
876            break;
877        case GOSSIP_OPTION_VENDOR:
878        case GOSSIP_OPTION_ARMORER:
879            player->GetSession()->SendListInventory(guid);
880            break;
881        case GOSSIP_OPTION_STABLEPET:
882            player->GetSession()->SendStablePet(guid);
883            break;
884        case GOSSIP_OPTION_TRAINER:
885            player->GetSession()->SendTrainerList(guid);
886            break;
887        case GOSSIP_OPTION_UNLEARNTALENTS:
888            player->PlayerTalkClass->CloseGossip();
889            player->SendTalentWipeConfirm(guid);
890            break;
891        case GOSSIP_OPTION_UNLEARNPETSKILLS:
892            player->PlayerTalkClass->CloseGossip();
893            player->SendPetSkillWipeConfirm();
894            break;
895        case GOSSIP_OPTION_TAXIVENDOR:
896            player->GetSession()->SendTaxiMenu(this);
897            break;
898        case GOSSIP_OPTION_INNKEEPER:
899            player->PlayerTalkClass->CloseGossip();
900            player->SetBindPoint( guid );
901            break;
902        case GOSSIP_OPTION_BANKER:
903            player->GetSession()->SendShowBank( guid );
904            break;
905        case GOSSIP_OPTION_PETITIONER:
906            player->PlayerTalkClass->CloseGossip();
907            player->GetSession()->SendPetitionShowList( guid );
908            break;
909        case GOSSIP_OPTION_TABARDDESIGNER:
910            player->PlayerTalkClass->CloseGossip();
911            player->GetSession()->SendTabardVendorActivate( guid );
912            break;
913        case GOSSIP_OPTION_AUCTIONEER:
914            player->GetSession()->SendAuctionHello( guid, this );
915            break;
916        case GOSSIP_OPTION_SPIRITGUIDE:
917        case GOSSIP_GUARD_SPELLTRAINER:
918        case GOSSIP_GUARD_SKILLTRAINER:
919            prepareGossipMenu( player,gossip->Id );
920            sendPreparedGossip( player );
921            break;
922        case GOSSIP_OPTION_BATTLEFIELD:
923        {
924            uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
925            player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
926            break;
927        }
928        default:
929            OnPoiSelect( player, gossip );
930            break;
931    }
932
933}
934
935void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
936{
937    if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
938    {
939        //float x,y;
940        //bool findnpc=false;
941        Poi_Icon icon = ICON_POI_0;
942        //QueryResult *result;
943        //Field *fields;
944        uint32 mapid=GetMapId();
945        Map const* map=MapManager::Instance().GetBaseMap( mapid );
946        uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
947        uint32 zoneid=Map::GetZoneId(areaflag,mapid);
948        std::string areaname= gossip->OptionText;
949        /*
950        uint16 pflag;
951
952        // use the action relate to creaturetemplate.trainer_type ?
953        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 );
954        if(!result)
955            return;
956        do
957        {
958            fields = result->Fetch();
959            x=fields[0].GetFloat();
960            y=fields[1].GetFloat();
961            pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
962            if(pflag==areaflag)
963            {
964                findnpc=true;
965                break;
966            }
967        }while(result->NextRow());
968
969        delete result;
970
971        if(!findnpc)
972        {
973            player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
974            return;
975        }*/
976
977        //need add more case.
978        switch(gossip->Action)
979        {
980            case GOSSIP_GUARD_BANK:
981                icon=ICON_POI_HOUSE;
982                break;
983            case GOSSIP_GUARD_RIDE:
984                icon=ICON_POI_RWHORSE;
985                break;
986            case GOSSIP_GUARD_GUILD:
987                icon=ICON_POI_BLUETOWER;
988                break;
989            default:
990                icon=ICON_POI_TOWER;
991                break;
992        }
993        uint32 textid=GetGossipTextId( gossip->Action, zoneid );
994        player->PlayerTalkClass->SendTalking( textid );
995        // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
996    }
997}
998
999uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
1000{
1001    QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
1002
1003    if(!result)
1004        return 0;
1005
1006    Field *fields = result->Fetch();
1007    uint32 id = fields[0].GetUInt32();
1008
1009    delete result;
1010
1011    return id;
1012}
1013
1014uint32 Creature::GetNpcTextId()
1015{
1016    // don't cache / use cache in case it's a world event announcer
1017    if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT)
1018        if(uint32 textid = gameeventmgr.GetNpcTextId(m_DBTableGuid))
1019            return textid;
1020
1021    if (!m_DBTableGuid)
1022        return DEFAULT_GOSSIP_MESSAGE;
1023
1024    if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1025        return pos;
1026
1027    return DEFAULT_GOSSIP_MESSAGE;
1028}
1029
1030GossipOption const* Creature::GetGossipOption( uint32 id ) const
1031{
1032    for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
1033    {
1034        if(i->Action==id )
1035            return &*i;
1036    }
1037    return NULL;
1038}
1039
1040void Creature::ResetGossipOptions()
1041{
1042    m_gossipOptionLoaded = false;
1043    m_goptions.clear();
1044}
1045
1046void Creature::LoadGossipOptions()
1047{
1048    if(m_gossipOptionLoaded)
1049        return;
1050
1051    uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1052
1053    CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1054    for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1055        if(i->NpcFlag & npcflags)
1056            addGossipOption(*i);
1057
1058    m_gossipOptionLoaded = true;
1059}
1060
1061void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1062{
1063    /*    uint32 timeElap = getMSTime();
1064        if ((timeElap - m_startMove) < m_moveTime)
1065        {
1066            oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1067            oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1068        }
1069        else
1070        {
1071            oX = dX;
1072            oY = dY;
1073        }
1074
1075        dX = x;
1076        dY = y;
1077        m_orientation = atan2((oY - dY), (oX - dX));
1078
1079        m_startMove = getMSTime();
1080        m_moveTime = time;*/
1081    SendMonsterMove(x, y, z, type, MovementFlags, time);
1082}
1083
1084Player *Creature::GetLootRecipient() const
1085{
1086    if (!m_lootRecipient) return NULL;
1087    else return ObjectAccessor::FindPlayer(m_lootRecipient);
1088}
1089
1090void Creature::SetLootRecipient(Unit *unit)
1091{
1092    // set the player whose group should receive the right
1093    // to loot the creature after it dies
1094    // should be set to NULL after the loot disappears
1095
1096    if (!unit)
1097    {
1098        m_lootRecipient = 0;
1099        RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1100        return;
1101    }
1102
1103    Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1104    if(!player)                                             // normal creature, no player involved
1105        return;
1106
1107    m_lootRecipient = player->GetGUID();
1108    SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1109}
1110
1111void Creature::SaveToDB()
1112{
1113    // this should only be used when the creature has already been loaded
1114    // perferably after adding to map, because mapid may not be valid otherwise
1115    CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1116    if(!data)
1117    {
1118        sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1119        return;
1120    }
1121
1122    SaveToDB(GetMapId(), data->spawnMask);
1123}
1124
1125void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1126{
1127    // update in loaded data
1128    if (!m_DBTableGuid)
1129        m_DBTableGuid = GetGUIDLow();
1130    CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1131
1132    uint32 displayId = GetNativeDisplayId();
1133
1134    // check if it's a custom model and if not, use 0 for displayId
1135    CreatureInfo const *cinfo = GetCreatureInfo();
1136    if(cinfo)
1137    {
1138        if(displayId == cinfo->Modelid1 || displayId == cinfo->Modelid2 ||
1139            displayId == cinfo->Modelid3 || displayId == cinfo->Modelid4) displayId = 0;
1140    }
1141
1142    // data->guid = guid don't must be update at save
1143    data.id = GetEntry();
1144    data.mapid = mapid;
1145    data.displayid = displayId;
1146    data.equipmentId = GetEquipmentId();
1147    data.posX = GetPositionX();
1148    data.posY = GetPositionY();
1149    data.posZ = GetPositionZ();
1150    data.orientation = GetOrientation();
1151    data.spawntimesecs = m_respawnDelay;
1152    // prevent add data integrity problems
1153    data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1154    data.currentwaypoint = 0;
1155    data.curhealth = GetHealth();
1156    data.curmana = GetPower(POWER_MANA);
1157    data.is_dead = m_isDeadByDefault;
1158    // prevent add data integrity problems
1159    data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1160        ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1161    data.spawnMask = spawnMask;
1162
1163    // updated in DB
1164    WorldDatabase.BeginTransaction();
1165
1166    WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1167
1168    std::ostringstream ss;
1169    ss << "INSERT INTO creature VALUES ("
1170        << m_DBTableGuid << ","
1171        << GetEntry() << ","
1172        << mapid <<","
1173        << (uint32)spawnMask << ","
1174        << displayId <<","
1175        << GetEquipmentId() <<","
1176        << GetPositionX() << ","
1177        << GetPositionY() << ","
1178        << GetPositionZ() << ","
1179        << GetOrientation() << ","
1180        << m_respawnDelay << ","                            //respawn time
1181        << (float) m_respawnradius << ","                   //spawn distance (float)
1182        << (uint32) (0) << ","                              //currentwaypoint
1183        << GetHealth() << ","                               //curhealth
1184        << GetPower(POWER_MANA) << ","                      //curmana
1185        << (m_isDeadByDefault ? 1 : 0) << ","               //is_dead
1186        << GetDefaultMovementType() << ")";                 //default movement generator type
1187
1188    WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1189
1190    WorldDatabase.CommitTransaction();
1191}
1192
1193void Creature::SelectLevel(const CreatureInfo *cinfo)
1194{
1195    uint32 rank = isPet()? 0 : cinfo->rank;
1196
1197    // level
1198    uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1199    uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1200    uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1201    SetLevel(level);
1202
1203    float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1204
1205    // health
1206    float healthmod = _GetHealthMod(rank);
1207
1208    uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1209    uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1210    uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1211
1212    SetCreateHealth(health);
1213    SetMaxHealth(health);
1214    SetHealth(health);
1215
1216    // mana
1217    uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1218    uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1219    uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1220
1221    SetCreateMana(mana);
1222    SetMaxPower(POWER_MANA, mana);                          //MAX Mana
1223    SetPower(POWER_MANA, mana);
1224
1225    SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1226    SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1227
1228    // damage
1229    float damagemod = _GetDamageMod(rank);
1230
1231    SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1232    SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1233    SetBaseWeaponDamage(OFF_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1234    SetBaseWeaponDamage(OFF_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1235    SetBaseWeaponDamage(RANGED_ATTACK, MINDAMAGE, cinfo->minrangedmg * damagemod);
1236    SetBaseWeaponDamage(RANGED_ATTACK, MAXDAMAGE, cinfo->maxrangedmg * damagemod);
1237
1238    SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1239    SetModifierValue(UNIT_MOD_ATTACK_POWER_RANGED, BASE_VALUE, cinfo->rangedattackpower * damagemod);
1240}
1241
1242float Creature::_GetHealthMod(int32 Rank)
1243{
1244    switch (Rank)                                           // define rates for each elite rank
1245    {
1246        case CREATURE_ELITE_NORMAL:
1247            return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1248        case CREATURE_ELITE_ELITE:
1249            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1250        case CREATURE_ELITE_RAREELITE:
1251            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1252        case CREATURE_ELITE_WORLDBOSS:
1253            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1254        case CREATURE_ELITE_RARE:
1255            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1256        default:
1257            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1258    }
1259}
1260
1261float Creature::_GetDamageMod(int32 Rank)
1262{
1263    switch (Rank)                                           // define rates for each elite rank
1264    {
1265        case CREATURE_ELITE_NORMAL:
1266            return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1267        case CREATURE_ELITE_ELITE:
1268            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1269        case CREATURE_ELITE_RAREELITE:
1270            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1271        case CREATURE_ELITE_WORLDBOSS:
1272            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1273        case CREATURE_ELITE_RARE:
1274            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1275        default:
1276            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1277    }
1278}
1279
1280float Creature::GetSpellDamageMod(int32 Rank)
1281{
1282    switch (Rank)                                           // define rates for each elite rank
1283    {
1284        case CREATURE_ELITE_NORMAL:
1285            return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1286        case CREATURE_ELITE_ELITE:
1287            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1288        case CREATURE_ELITE_RAREELITE:
1289            return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1290        case CREATURE_ELITE_WORLDBOSS:
1291            return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1292        case CREATURE_ELITE_RARE:
1293            return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1294        default:
1295            return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1296    }
1297}
1298
1299bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1300{
1301    CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1302    if(!cinfo)
1303    {
1304        sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1305        return false;
1306    }
1307    m_originalEntry = Entry;
1308
1309    Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1310
1311    if(!UpdateEntry(Entry, team, data))
1312        return false;
1313
1314    //Notify the map's instance data.
1315    //Only works if you create the object in it, not if it is moves to that map.
1316    //Normally non-players do not teleport to other maps.
1317    Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1318    if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1319    {
1320        ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1321    }
1322
1323    return true;
1324}
1325
1326bool Creature::LoadFromDB(uint32 guid, Map *map)
1327{
1328    CreatureData const* data = objmgr.GetCreatureData(guid);
1329
1330    if(!data)
1331    {
1332        sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1333        return false;
1334    }
1335
1336    m_DBTableGuid = guid;
1337    if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1338
1339    uint16 team = 0;
1340    if(!Create(guid,map,data->id,team,data))
1341        return false;
1342
1343    Relocate(data->posX,data->posY,data->posZ,data->orientation);
1344
1345    if(!IsPositionValid())
1346    {
1347        sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1348        return false;
1349    }
1350
1351    m_respawnradius = data->spawndist;
1352
1353    m_respawnDelay = data->spawntimesecs;
1354    m_isDeadByDefault = data->is_dead;
1355    m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1356
1357    m_respawnTime  = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1358    if(m_respawnTime > time(NULL))                          // not ready to respawn
1359        m_deathState = DEAD;
1360    else if(m_respawnTime)                                  // respawn time set but expired
1361    {
1362        m_respawnTime = 0;
1363        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1364    }
1365
1366    uint32 curhealth = data->curhealth;
1367    if(curhealth)
1368    {
1369        curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1370        if(curhealth < 1)
1371            curhealth = 1;
1372    }
1373
1374    SetHealth(m_deathState == ALIVE ? curhealth : 0);
1375    SetPower(POWER_MANA,data->curmana);
1376
1377    SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1378
1379    // checked at creature_template loading
1380    m_defaultMovementType = MovementGeneratorType(data->movementType);
1381
1382    AIM_Initialize();
1383    return true;
1384}
1385
1386void Creature::LoadEquipment(uint32 equip_entry, bool force)
1387{
1388    if(equip_entry == 0)
1389    {
1390        if (force)
1391        {
1392            for (uint8 i = 0; i < 3; i++)
1393            {
1394                SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1395                SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1396                SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1397            }
1398            m_equipmentId = 0;
1399        }
1400        return;
1401    }
1402
1403    EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1404    if (!einfo)
1405        return;
1406
1407    m_equipmentId = equip_entry;
1408    for (uint8 i = 0; i < 3; i++)
1409    {
1410        SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1411        SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1412        SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1413    }
1414}
1415
1416bool Creature::hasQuest(uint32 quest_id) const
1417{
1418    QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1419    for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1420    {
1421        if(itr->second==quest_id)
1422            return true;
1423    }
1424    return false;
1425}
1426
1427bool Creature::hasInvolvedQuest(uint32 quest_id) const
1428{
1429    QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1430    for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1431    {
1432        if(itr->second==quest_id)
1433            return true;
1434    }
1435    return false;
1436}
1437
1438void Creature::DeleteFromDB()
1439{
1440    if (!m_DBTableGuid)
1441    {
1442        sLog.outDebug("Trying to delete not saved creature!");
1443        return;
1444    }
1445
1446    objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1447    objmgr.DeleteCreatureData(m_DBTableGuid);
1448
1449    WorldDatabase.BeginTransaction();
1450    WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1451    WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1452    WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1453    WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1454    WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1455    WorldDatabase.CommitTransaction();
1456}
1457
1458float Creature::GetAttackDistance(Unit const* pl) const
1459{
1460    float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1461    if(aggroRate==0)
1462        return 0.0f;
1463
1464    int32 playerlevel   = pl->getLevelForTarget(this);
1465    int32 creaturelevel = getLevelForTarget(pl);
1466
1467    int32 leveldif       = playerlevel - creaturelevel;
1468
1469    // "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."
1470    if ( leveldif < - 25)
1471        leveldif = -25;
1472
1473    // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1474    float RetDistance = 20;
1475
1476    // "Aggro Radius varries with level difference at a rate of roughly 1 yard/level"
1477    // radius grow if playlevel < creaturelevel
1478    RetDistance -= (float)leveldif;
1479
1480    if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1481    {
1482        // detect range auras
1483        RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1484
1485        // detected range auras
1486        RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1487    }
1488
1489    // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1490    if(RetDistance < 5)
1491        RetDistance = 5;
1492
1493    return (RetDistance*aggroRate);
1494}
1495
1496void Creature::setDeathState(DeathState s)
1497{
1498    if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1499    {
1500        m_deathTimer = m_corpseDelay*1000;
1501
1502        // always save boss respawn time at death to prevent crash cheating
1503        if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1504            SaveRespawnTime();
1505
1506        if(!IsStopped())
1507            StopMoving();
1508    }
1509    Unit::setDeathState(s);
1510
1511    if(s == JUST_DIED)
1512    {
1513        SetUInt64Value (UNIT_FIELD_TARGET,0);               // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1514        SetUInt32Value(UNIT_NPC_FLAGS, 0);
1515
1516        if(!isPet() && GetCreatureInfo()->SkinLootId)
1517            if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1518                SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1519
1520        Unit::setDeathState(CORPSE);
1521    }
1522    if(s == JUST_ALIVED)
1523    {
1524        SetHealth(GetMaxHealth());
1525        SetLootRecipient(NULL);
1526        Unit::setDeathState(ALIVE);
1527        CreatureInfo const *cinfo = GetCreatureInfo();
1528        SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1529        RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1530        AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1531        SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1532        clearUnitState(UNIT_STAT_ALL_STATE);
1533        i_motionMaster.Clear();
1534        SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1535        LoadCreaturesAddon(true);
1536    }
1537}
1538
1539void Creature::Respawn()
1540{
1541    RemoveCorpse();
1542
1543    // forced recreate creature object at clients
1544    UnitVisibility currentVis = GetVisibility();
1545    SetVisibility(VISIBILITY_RESPAWN);
1546    ObjectAccessor::UpdateObjectVisibility(this);
1547    SetVisibility(currentVis);                              // restore visibility state
1548    ObjectAccessor::UpdateObjectVisibility(this);
1549
1550    if(getDeathState()==DEAD)
1551    {
1552        if (m_DBTableGuid)
1553            objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1554        m_respawnTime = time(NULL);                         // respawn at next tick
1555    }
1556}
1557
1558bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1559{
1560    if (!spellInfo)
1561        return false;
1562
1563    if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1564        return true;
1565
1566    return Unit::IsImmunedToSpell(spellInfo, useCharges);
1567}
1568
1569bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1570{
1571    if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1572        return true;
1573
1574    return Unit::IsImmunedToSpellEffect(effect, mechanic);
1575}
1576
1577SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1578{
1579    if(!pVictim)
1580        return NULL;
1581
1582    for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1583    {
1584        if(!m_spells[i])
1585            continue;
1586        SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1587        if(!spellInfo)
1588        {
1589            sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1590            continue;
1591        }
1592
1593        bool bcontinue = true;
1594        for(uint32 j=0;j<3;j++)
1595        {
1596            if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE )       ||
1597                (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL)            ||
1598                (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1599                (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1600                )
1601            {
1602                bcontinue = false;
1603                break;
1604            }
1605        }
1606        if(bcontinue) continue;
1607
1608        if(spellInfo->manaCost > GetPower(POWER_MANA))
1609            continue;
1610        SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1611        float range = GetSpellMaxRange(srange);
1612        float minrange = GetSpellMinRange(srange);
1613        float dist = GetDistance(pVictim);
1614        //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1615        //    continue;
1616        if( dist > range || dist < minrange )
1617            continue;
1618        if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1619            continue;
1620        return spellInfo;
1621    }
1622    return NULL;
1623}
1624
1625SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1626{
1627    if(!pVictim)
1628        return NULL;
1629
1630    for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1631    {
1632        if(!m_spells[i])
1633            continue;
1634        SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1635        if(!spellInfo)
1636        {
1637            sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1638            continue;
1639        }
1640
1641        bool bcontinue = true;
1642        for(uint32 j=0;j<3;j++)
1643        {
1644            if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1645            {
1646                bcontinue = false;
1647                break;
1648            }
1649        }
1650        if(bcontinue) continue;
1651
1652        if(spellInfo->manaCost > GetPower(POWER_MANA))
1653            continue;
1654        SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1655        float range = GetSpellMaxRange(srange);
1656        float minrange = GetSpellMinRange(srange);
1657        float dist = GetDistance(pVictim);
1658        //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1659        //    continue;
1660        if( dist > range || dist < minrange )
1661            continue;
1662        if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1663            continue;
1664        return spellInfo;
1665    }
1666    return NULL;
1667}
1668
1669bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1670{
1671    // gamemaster in GM mode see all, including ghosts
1672    if(pl->isGameMaster())
1673        return true;
1674
1675    // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1676    if(pl->isAlive() || pl->GetDeathTimer() > 0)
1677    {
1678        if( GetEntry() == VISUAL_WAYPOINT && !pl->isGameMaster() )
1679            return false;
1680        return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1681    }
1682
1683    // Dead player see live creatures near own corpse
1684    if(isAlive())
1685    {
1686        Corpse *corpse = pl->GetCorpse();
1687        if(corpse)
1688        {
1689            // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1690            if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1691                return true;
1692        }
1693    }
1694
1695    // Dead player see Spirit Healer or Spirit Guide
1696    if(isSpiritService())
1697        return true;
1698
1699    // and not see any other
1700    return false;
1701}
1702
1703void Creature::DoFleeToGetAssistance(float radius) // Optional parameter
1704{
1705    if (!getVictim())
1706        return;
1707
1708    Creature* pCreature = NULL;
1709
1710    CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
1711    Cell cell(p);
1712    cell.data.Part.reserved = ALL_DISTRICT;
1713    cell.SetNoCreate();
1714
1715    Trinity::NearestAssistCreatureInCreatureRangeCheck u_check(this,getVictim(),radius);
1716    Trinity::CreatureLastSearcher<Trinity::NearestAssistCreatureInCreatureRangeCheck> searcher(pCreature, u_check);
1717
1718    TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1719
1720    CellLock<GridReadGuard> cell_lock(cell, p);
1721    cell_lock->Visit(cell_lock, grid_creature_searcher, *(GetMap()));
1722
1723    if(!GetMotionMaster()->empty() && (GetMotionMaster()->GetCurrentMovementGeneratorType() != POINT_MOTION_TYPE))
1724        GetMotionMaster()->Clear(false);
1725    if(pCreature == NULL)
1726    {
1727        GetMotionMaster()->MoveIdle();
1728        GetMotionMaster()->MoveFleeing(getVictim());
1729    }
1730    else
1731    {
1732        GetMotionMaster()->MoveIdle();
1733        GetMotionMaster()->MovePoint(0,pCreature->GetPositionX(),pCreature->GetPositionY(),pCreature->GetPositionZ());
1734    }
1735}
1736
1737void Creature::CallAssistence()
1738{
1739    if( !m_AlreadyCallAssistence && getVictim() && !isPet() && !isCharmed())
1740    {
1741        SetNoCallAssistence(true);
1742
1743        float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS);
1744        if(radius > 0)
1745        {
1746            std::list<Creature*> assistList;
1747
1748            {
1749                CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
1750                Cell cell(p);
1751                cell.data.Part.reserved = ALL_DISTRICT;
1752                cell.SetNoCreate();
1753
1754                Trinity::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1755                Trinity::CreatureListSearcher<Trinity::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1756
1757                TypeContainerVisitor<Trinity::CreatureListSearcher<Trinity::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer >  grid_creature_searcher(searcher);
1758
1759                CellLock<GridReadGuard> cell_lock(cell, p);
1760                cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
1761            }
1762
1763            for(std::list<Creature*>::iterator iter = assistList.begin(); iter != assistList.end(); ++iter)
1764            {
1765                (*iter)->SetNoCallAssistence(true);
1766                if((*iter)->AI())
1767                    (*iter)->AI()->AttackStart(getVictim());
1768            }
1769        }
1770    }
1771}
1772
1773void Creature::SaveRespawnTime()
1774{
1775    if(isPet() || !m_DBTableGuid)
1776        return;
1777
1778    if(m_respawnTime > time(NULL))                          // dead (no corpse)
1779        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1780    else if(m_deathTimer > 0)                               // dead (corpse)
1781        objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1782}
1783
1784bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1785{
1786    if(!pVictim)
1787        return true;
1788
1789    if(!pVictim->IsInMap(this))
1790        return true;
1791
1792    if(!pVictim->isTargetableForAttack())
1793        return true;
1794
1795    if(!pVictim->isInAccessablePlaceFor(this))
1796        return true;
1797
1798    if(sMapStore.LookupEntry(GetMapId())->Instanceable())
1799        return false;
1800
1801    float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1802    float AttackDist = GetAttackDistance(pVictim);
1803    uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1804
1805    //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and ouf of combat every update tick.
1806    return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1807}
1808
1809CreatureDataAddon const* Creature::GetCreatureAddon() const
1810{
1811    if (m_DBTableGuid)
1812    {
1813        if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1814            return addon;
1815    }
1816
1817    // dependent from heroic mode entry
1818    return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1819}
1820
1821//creature_addon table
1822bool Creature::LoadCreaturesAddon(bool reload)
1823{
1824    CreatureDataAddon const *cainfo = GetCreatureAddon();
1825    if(!cainfo)
1826        return false;
1827
1828    if (cainfo->mount != 0)
1829        Mount(cainfo->mount);
1830
1831    if (cainfo->bytes0 != 0)
1832        SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1833
1834    if (cainfo->bytes1 != 0)
1835        SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1836
1837    if (cainfo->bytes2 != 0)
1838        SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1839
1840    if (cainfo->emote != 0)
1841        SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1842
1843    if (cainfo->move_flags != 0)
1844        SetUnitMovementFlags(cainfo->move_flags);
1845
1846    if(cainfo->auras)
1847    {
1848        for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1849        {
1850            SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1851            if (!AdditionalSpellInfo)
1852            {
1853                sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1854                continue;
1855            }
1856
1857            // skip already applied aura
1858            if(HasAura(cAura->spell_id,cAura->effect_idx))
1859            {
1860                if(!reload)
1861                    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);
1862
1863                continue;
1864            }
1865
1866            Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1867            AddAura(AdditionalAura);
1868            sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1869        }
1870    }
1871    return true;
1872}
1873
1874/// Send a message to LocalDefense channel for players oposition team in the zone
1875void Creature::SendZoneUnderAttackMessage(Player* attacker)
1876{
1877    uint32 enemy_team = attacker->GetTeam();
1878
1879    WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1880    data << (uint32)GetZoneId();
1881    sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1882}
1883
1884void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1885{
1886    m_CreatureSpellCooldowns[spell_id] = end_time;
1887}
1888
1889void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1890{
1891    m_CreatureCategoryCooldowns[category] = apply_time;
1892}
1893
1894void Creature::AddCreatureSpellCooldown(uint32 spellid)
1895{
1896    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1897    if(!spellInfo)
1898        return;
1899
1900    uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1901    if(cooldown)
1902        _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1903
1904    if(spellInfo->Category)
1905        _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1906
1907    m_GlobalCooldown = spellInfo->StartRecoveryTime;
1908}
1909
1910bool Creature::HasCategoryCooldown(uint32 spell_id) const
1911{
1912    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1913    if(!spellInfo)
1914        return false;
1915
1916    // check global cooldown if spell affected by it
1917    if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1918        return true;
1919
1920    CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1921    return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1922}
1923
1924bool Creature::HasSpellCooldown(uint32 spell_id) const
1925{
1926    CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1927    return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1928}
1929
1930bool Creature::IsInEvadeMode() const
1931{
1932    return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1933}
1934
1935bool Creature::HasSpell(uint32 spellID) const
1936{
1937    uint8 i;
1938    for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1939        if(spellID == m_spells[i])
1940            break;
1941    return i < CREATURE_MAX_SPELLS;                         //broke before end of iteration of known spells
1942}
1943
1944time_t Creature::GetRespawnTimeEx() const
1945{
1946    time_t now = time(NULL);
1947    if(m_respawnTime > now)                                 // dead (no corpse)
1948        return m_respawnTime;
1949    else if(m_deathTimer > 0)                               // dead (corpse)
1950        return now+m_respawnDelay+m_deathTimer/1000;
1951    else
1952        return now;
1953}
1954
1955void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1956{
1957    if (m_DBTableGuid)
1958    {
1959        if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1960        {
1961            x = data->posX;
1962            y = data->posY;
1963            z = data->posZ;
1964            if(ori)
1965                *ori = data->orientation;
1966            if(dist)
1967                *dist = data->spawndist;
1968
1969            return;
1970        }
1971    }
1972
1973    x = GetPositionX();
1974    y = GetPositionY();
1975    z = GetPositionZ();
1976    if(ori)
1977        *ori = GetOrientation();
1978    if(dist)
1979        *dist = 0;
1980}
1981
1982void Creature::AllLootRemovedFromCorpse()
1983{
1984    if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1985    {
1986        uint32 nDeathTimer;
1987
1988        CreatureInfo const *cinfo = GetCreatureInfo();
1989
1990        // corpse was not skinnable -> apply corpse looted timer
1991        if (!cinfo || !cinfo->SkinLootId)
1992            nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1993        // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1994        else
1995            nDeathTimer = 0;
1996
1997        // update death timer only if looted timer is shorter
1998        if (m_deathTimer > nDeathTimer)
1999            m_deathTimer = nDeathTimer;
2000    }
2001}
2002
2003uint32 Creature::getLevelForTarget( Unit const* target ) const
2004{
2005    if(!isWorldBoss())
2006        return Unit::getLevelForTarget(target);
2007
2008    uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2009    if(level < 1)
2010        return 1;
2011    if(level > 255)
2012        return 255;
2013    return level;
2014}
2015
2016char const* Creature::GetScriptName() const
2017{
2018    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptName;
2019}
2020
2021VendorItemData const* Creature::GetVendorItems() const
2022{
2023    return objmgr.GetNpcVendorItemList(GetEntry());
2024}
2025
2026uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2027{
2028    if(!vItem->maxcount)
2029        return vItem->maxcount;
2030
2031    VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2032    for(; itr != m_vendorItemCounts.end(); ++itr)
2033        if(itr->itemId==vItem->item)
2034            break;
2035
2036    if(itr == m_vendorItemCounts.end())
2037        return vItem->maxcount;
2038
2039    VendorItemCount* vCount = &*itr;
2040
2041    time_t ptime = time(NULL);
2042
2043    if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2044    {
2045        ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2046
2047        uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2048        if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2049        {
2050            m_vendorItemCounts.erase(itr);
2051            return vItem->maxcount;
2052        }
2053
2054        vCount->count += diff * pProto->BuyCount;
2055        vCount->lastIncrementTime = ptime;
2056    }
2057
2058    return vCount->count;
2059}
2060
2061uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2062{
2063    if(!vItem->maxcount)
2064        return 0;
2065
2066    VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2067    for(; itr != m_vendorItemCounts.end(); ++itr)
2068        if(itr->itemId==vItem->item)
2069            break;
2070
2071    if(itr == m_vendorItemCounts.end())
2072    {
2073        uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2074        m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2075        return new_count;
2076    }
2077
2078    VendorItemCount* vCount = &*itr;
2079
2080    time_t ptime = time(NULL);
2081
2082    if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2083    {
2084        ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2085
2086        uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2087        if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2088            vCount->count += diff * pProto->BuyCount;
2089        else
2090            vCount->count = vItem->maxcount;
2091    }
2092
2093    vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2094    vCount->lastIncrementTime = ptime;
2095    return vCount->count;
2096}
2097
2098TrainerSpellData const* Creature::GetTrainerSpells() const
2099{
2100    return objmgr.GetNpcTrainerSpells(GetEntry());
2101}
Note: See TracBrowser for help on using the browser.