[9362] Make specs work at least for action bars
[getmangos.git] / src / game / Creature.cpp
blobcd135875337631179373cab64099a0b227b920ad
1 /*
2 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "World.h"
23 #include "ObjectMgr.h"
24 #include "ObjectDefines.h"
25 #include "SpellMgr.h"
26 #include "Creature.h"
27 #include "QuestDef.h"
28 #include "GossipDef.h"
29 #include "Player.h"
30 #include "PoolManager.h"
31 #include "Opcodes.h"
32 #include "Log.h"
33 #include "LootMgr.h"
34 #include "MapManager.h"
35 #include "CreatureAI.h"
36 #include "CreatureAISelector.h"
37 #include "Formulas.h"
38 #include "WaypointMovementGenerator.h"
39 #include "InstanceData.h"
40 #include "BattleGroundMgr.h"
41 #include "Spell.h"
42 #include "Util.h"
43 #include "GridNotifiers.h"
44 #include "GridNotifiersImpl.h"
45 #include "CellImpl.h"
47 // apply implementation of the singletons
48 #include "Policies/SingletonImp.h"
50 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
52 TrainerSpellMap::const_iterator itr = spellList.find(spell_id);
53 if (itr != spellList.end())
54 return &itr->second;
56 return NULL;
59 bool VendorItemData::RemoveItem( uint32 item_id )
61 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
63 if((*i)->item == item_id)
65 m_items.erase(i);
66 return true;
69 return false;
72 size_t VendorItemData::FindItemSlot(uint32 item_id) const
74 for(size_t i = 0; i < m_items.size(); ++i )
75 if(m_items[i]->item == item_id)
76 return i;
77 return m_items.size();
80 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
82 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
83 if((*i)->item == item_id)
84 return *i;
85 return NULL;
88 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
90 if(Unit* victim = Unit::GetUnit(m_owner, m_victim))
92 while (!m_assistants.empty())
94 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
95 m_assistants.pop_front();
97 if (assistant && assistant->CanAssistTo(&m_owner, victim))
99 assistant->SetNoCallAssistance(true);
100 if(assistant->AI())
101 assistant->AI()->AttackStart(victim);
105 return true;
108 bool ForcedDespawnDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
110 m_owner.ForcedDespawn();
111 return true;
114 Creature::Creature(CreatureSubtype subtype) :
115 Unit(), i_AI(NULL),
116 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), m_groupLootId(0),
117 m_lootMoney(0), m_lootRecipient(0),
118 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
119 m_subtype(subtype), m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0),
120 m_AlreadyCallAssistance(false), m_AlreadySearchedAssistance(false),
121 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
122 m_creatureInfo(NULL), m_isActiveObject(false), m_splineFlags(SPLINEFLAG_WALKMODE)
124 m_regenTimer = 200;
125 m_valuesCount = UNIT_END;
127 for(int i = 0; i < 4; ++i)
128 m_spells[i] = 0;
130 m_CreatureSpellCooldowns.clear();
131 m_CreatureCategoryCooldowns.clear();
132 m_GlobalCooldown = 0;
134 m_splineFlags = SPLINEFLAG_WALKMODE;
137 Creature::~Creature()
139 CleanupsBeforeDelete();
141 m_vendorItemCounts.clear();
143 delete i_AI;
144 i_AI = NULL;
147 void Creature::AddToWorld()
149 ///- Register the creature for guid lookup
150 if(!IsInWorld() && GetGUIDHigh() == HIGHGUID_UNIT)
151 GetMap()->GetObjectsStore().insert<Creature>(GetGUID(), (Creature*)this);
153 Unit::AddToWorld();
156 void Creature::RemoveFromWorld()
158 ///- Remove the creature from the accessor
159 if(IsInWorld() && GetGUIDHigh() == HIGHGUID_UNIT)
160 GetMap()->GetObjectsStore().erase<Creature>(GetGUID(), (Creature*)NULL);
162 Unit::RemoveFromWorld();
165 void Creature::RemoveCorpse()
167 if ((getDeathState() != CORPSE && !m_isDeadByDefault) || (getDeathState() != ALIVE && m_isDeadByDefault))
168 return;
170 m_deathTimer = 0;
171 setDeathState(DEAD);
172 UpdateObjectVisibility();
173 loot.clear();
174 uint32 respawnDelay = m_respawnDelay;
175 if (AI())
176 AI()->CorpseRemoved(respawnDelay);
178 m_respawnTime = time(NULL) + respawnDelay;
180 float x, y, z, o;
181 GetRespawnCoord(x, y, z, &o);
182 GetMap()->CreatureRelocation(this, x, y, z, o);
186 * change the entry of creature until respawn
188 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
190 CreatureInfo const *normalInfo = ObjectMgr::GetCreatureTemplate(Entry);
191 if(!normalInfo)
193 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
194 return false;
197 // get difficulty 1 mode entry
198 uint32 actualEntry = Entry;
199 CreatureInfo const *cinfo = normalInfo;
200 // TODO correctly implement spawnmodes for non-bg maps
201 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
203 if (normalInfo->DifficultyEntry[diff])
205 // we already have valid Map pointer for current creature!
206 if (GetMap()->GetSpawnMode() > diff)
208 cinfo = ObjectMgr::GetCreatureTemplate(normalInfo->DifficultyEntry[diff]);
209 if (!cinfo)
211 // maybe check such things already at startup
212 sLog.outErrorDb("Creature::UpdateEntry creature difficulty %u entry %u does not exist.", diff + 1, actualEntry);
213 return false;
219 SetEntry(Entry); // normal entry always
220 m_creatureInfo = cinfo; // map mode related always
222 // equal to player Race field, but creature does not have race
223 SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
225 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
226 SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
228 uint32 display_id = sObjectMgr.ChooseDisplayId(team, GetCreatureInfo(), data);
229 if (!display_id) // Cancel load if no display id
231 sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load.", Entry);
232 return false;
235 CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
236 if (!minfo) // Cancel load if no model defined
238 sLog.outErrorDb("Creature (Entry: %u) has no model info defined in table `creature_model_info`, can't load.", Entry);
239 return false;
242 display_id = minfo->modelid; // it can be different (for another gender)
244 SetDisplayId(display_id);
245 SetNativeDisplayId(display_id);
246 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
248 // Load creature equipment
249 if(!data || data->equipmentId == 0)
250 { // use default from the template
251 LoadEquipment(cinfo->equipmentId);
253 else if(data && data->equipmentId != -1)
254 { // override, -1 means no equipment
255 LoadEquipment(data->equipmentId);
258 SetName(normalInfo->Name); // at normal entry always
260 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, minfo->bounding_radius);
261 SetFloatValue(UNIT_FIELD_COMBATREACH, minfo->combat_reach);
263 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
265 SetSpeedRate(MOVE_WALK, cinfo->speed);
266 SetSpeedRate(MOVE_RUN, cinfo->speed);
267 SetSpeedRate(MOVE_SWIM, cinfo->speed);
269 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
271 // checked at loading
272 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
273 if(!m_respawnradius && m_defaultMovementType == RANDOM_MOTION_TYPE)
274 m_defaultMovementType = IDLE_MOTION_TYPE;
276 return true;
279 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
281 if(!InitEntry(Entry, team, data))
282 return false;
284 m_regenHealth = GetCreatureInfo()->RegenHealth;
286 // creatures always have melee weapon ready if any
287 SetSheath(SHEATH_STATE_MELEE);
289 SelectLevel(GetCreatureInfo());
290 if (team == HORDE)
291 setFaction(GetCreatureInfo()->faction_H);
292 else
293 setFaction(GetCreatureInfo()->faction_A);
295 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
297 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
298 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
299 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
301 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
302 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
304 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
305 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
306 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
307 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
308 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
309 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
310 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
312 SetCanModifyStats(true);
313 UpdateAllStats();
315 // checked and error show at loading templates
316 if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A))
318 if (factionTemplate->factionFlags & FACTION_TEMPLATE_FLAG_PVP)
319 SetPvP(true);
320 else
321 SetPvP(false);
324 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
325 m_spells[i] = GetCreatureInfo()->spells[i];
327 return true;
330 void Creature::Update(uint32 diff)
332 if(m_GlobalCooldown <= diff)
333 m_GlobalCooldown = 0;
334 else
335 m_GlobalCooldown -= diff;
337 switch( m_deathState )
339 case JUST_ALIVED:
340 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
341 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
342 break;
343 case JUST_DIED:
344 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
345 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
346 break;
347 case DEAD:
349 if( m_respawnTime <= time(NULL) )
351 DEBUG_LOG("Respawning...");
352 m_respawnTime = 0;
353 lootForPickPocketed = false;
354 lootForBody = false;
356 if(m_originalEntry != GetEntry())
357 UpdateEntry(m_originalEntry);
359 CreatureInfo const *cinfo = GetCreatureInfo();
361 SelectLevel(cinfo);
362 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
363 if (m_isDeadByDefault)
365 setDeathState(JUST_DIED);
366 SetHealth(0);
367 i_motionMaster.Clear();
368 clearUnitState(UNIT_STAT_ALL_STATE);
369 LoadCreaturesAddon(true);
371 else
372 setDeathState( JUST_ALIVED );
374 //Call AI respawn virtual function
375 i_AI->JustRespawned();
377 uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<Creature>(GetDBTableGUIDLow()) : 0;
378 if (poolid)
379 sPoolMgr.UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
380 else
381 GetMap()->Add(this);
383 break;
385 case CORPSE:
387 if (m_isDeadByDefault)
388 break;
390 if( m_deathTimer <= diff )
392 RemoveCorpse();
393 DEBUG_LOG("Removing corpse... %u ", GetEntry());
395 else
397 m_deathTimer -= diff;
398 if (m_groupLootTimer && m_groupLootId)
400 if(diff <= m_groupLootTimer)
402 m_groupLootTimer -= diff;
404 else
406 if (Group* group = sObjectMgr.GetGroupById(m_groupLootId))
407 group->EndRoll();
408 m_groupLootTimer = 0;
409 m_groupLootId = 0;
414 break;
416 case ALIVE:
418 if (m_isDeadByDefault)
420 if( m_deathTimer <= diff )
422 RemoveCorpse();
423 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
425 else
427 m_deathTimer -= diff;
431 Unit::Update( diff );
433 // creature can be dead after Unit::Update call
434 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
435 if(!isAlive())
436 break;
438 if(!IsInEvadeMode())
440 // do not allow the AI to be changed during update
441 m_AI_locked = true;
442 i_AI->UpdateAI(diff);
443 m_AI_locked = false;
446 // creature can be dead after UpdateAI call
447 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
448 if(!isAlive())
449 break;
450 if(m_regenTimer > 0)
452 if(diff >= m_regenTimer)
453 m_regenTimer = 0;
454 else
455 m_regenTimer -= diff;
457 if (m_regenTimer != 0)
458 break;
460 if (!isInCombat() || IsPolymorphed())
461 RegenerateHealth();
463 RegenerateMana();
465 m_regenTimer = REGEN_TIME_FULL;
466 break;
468 case DEAD_FALLING:
470 if (!FallGround())
471 setDeathState(JUST_DIED);
473 default:
474 break;
478 void Creature::RegenerateMana()
480 uint32 curValue = GetPower(POWER_MANA);
481 uint32 maxValue = GetMaxPower(POWER_MANA);
483 if (curValue >= maxValue)
484 return;
486 uint32 addvalue = 0;
488 // Combat and any controlled creature
489 if (isInCombat() || GetCharmerOrOwnerGUID())
491 if(!IsUnderLastManaUseEffect())
493 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
494 float Spirit = GetStat(STAT_SPIRIT);
496 addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate);
499 else
500 addvalue = maxValue / 3;
502 ModifyPower(POWER_MANA, addvalue);
505 void Creature::RegenerateHealth()
507 if (!isRegeneratingHealth())
508 return;
510 uint32 curValue = GetHealth();
511 uint32 maxValue = GetMaxHealth();
513 if (curValue >= maxValue)
514 return;
516 uint32 addvalue = 0;
518 // Not only pet, but any controlled creature
519 if(GetCharmerOrOwnerGUID())
521 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
522 float Spirit = GetStat(STAT_SPIRIT);
524 if( GetPower(POWER_MANA) > 0 )
525 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
526 else
527 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
529 else
530 addvalue = maxValue/3;
532 ModifyHealth(addvalue);
535 void Creature::DoFleeToGetAssistance()
537 if (!getVictim())
538 return;
540 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
541 if (radius >0)
543 Creature* pCreature = NULL;
545 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
546 Cell cell(p);
547 cell.data.Part.reserved = ALL_DISTRICT;
548 cell.SetNoCreate();
549 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
550 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
552 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
554 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
556 SetNoSearchAssistance(true);
557 UpdateSpeed(MOVE_RUN, false);
559 if(!pCreature)
560 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
561 else
562 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
566 bool Creature::AIM_Initialize()
568 // make sure nothing can change the AI during AI update
569 if(m_AI_locked)
571 sLog.outDebug("AIM_Initialize: failed to init, locked.");
572 return false;
575 CreatureAI * oldAI = i_AI;
576 i_motionMaster.Initialize();
577 i_AI = FactorySelector::selectAI(this);
578 if (oldAI)
579 delete oldAI;
580 return true;
583 bool Creature::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
585 ASSERT(map);
586 SetMap(map);
587 SetPhaseMask(phaseMask,false);
589 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
590 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
592 if (bResult)
594 //Notify the map's instance data.
595 //Only works if you create the object in it, not if it is moves to that map.
596 //Normally non-players do not teleport to other maps.
597 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
598 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
600 switch (GetCreatureInfo()->rank)
602 case CREATURE_ELITE_RARE:
603 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
604 break;
605 case CREATURE_ELITE_ELITE:
606 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
607 break;
608 case CREATURE_ELITE_RAREELITE:
609 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
610 break;
611 case CREATURE_ELITE_WORLDBOSS:
612 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
613 break;
614 default:
615 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
616 break;
618 LoadCreaturesAddon();
621 return bResult;
624 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
626 if(!isTrainer())
627 return false;
629 TrainerSpellData const* trainer_spells = GetTrainerSpells();
631 if(!trainer_spells || trainer_spells->spellList.empty())
633 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
634 GetGUIDLow(),GetEntry());
635 return false;
638 switch(GetCreatureInfo()->trainer_type)
640 case TRAINER_TYPE_CLASS:
641 if(pPlayer->getClass() != GetCreatureInfo()->trainer_class)
643 if(msg)
645 pPlayer->PlayerTalkClass->ClearMenus();
646 switch(GetCreatureInfo()->trainer_class)
648 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
649 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
650 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
651 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
652 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
653 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
654 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
655 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
656 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
659 return false;
661 break;
662 case TRAINER_TYPE_PETS:
663 if(pPlayer->getClass() != CLASS_HUNTER)
665 pPlayer->PlayerTalkClass->ClearMenus();
666 pPlayer->PlayerTalkClass->SendGossipMenu(3620, GetGUID());
667 return false;
669 break;
670 case TRAINER_TYPE_MOUNTS:
671 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
673 if(msg)
675 pPlayer->PlayerTalkClass->ClearMenus();
676 switch(GetCreatureInfo()->trainer_class)
678 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
679 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
680 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
681 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
682 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
683 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
684 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
685 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
686 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
687 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
690 return false;
692 break;
693 case TRAINER_TYPE_TRADESKILLS:
694 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
696 if(msg)
698 pPlayer->PlayerTalkClass->ClearMenus();
699 pPlayer->PlayerTalkClass->SendGossipMenu(11031, GetGUID());
701 return false;
703 break;
704 default:
705 return false; // checked and error output at creature_template loading
707 return true;
710 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
712 if(!isBattleMaster())
713 return false;
715 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
716 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
717 return false;
719 if(!msg)
720 return pPlayer->GetBGAccessByLevel(bgTypeId);
722 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
724 pPlayer->PlayerTalkClass->ClearMenus();
725 switch(bgTypeId)
727 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616, GetGUID()); break;
728 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599, GetGUID()); break;
729 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642, GetGUID()); break;
730 case BATTLEGROUND_EY:
731 case BATTLEGROUND_NA:
732 case BATTLEGROUND_BE:
733 case BATTLEGROUND_AA:
734 case BATTLEGROUND_RL:
735 case BATTLEGROUND_SA:
736 case BATTLEGROUND_DS:
737 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024, GetGUID()); break;
738 default: break;
740 return false;
742 return true;
745 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
747 return pPlayer->getLevel() >= 10
748 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
749 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
752 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, SplineFlags flags, uint8 type)
754 /* uint32 timeElap = getMSTime();
755 if ((timeElap - m_startMove) < m_moveTime)
757 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
758 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
760 else
762 oX = dX;
763 oY = dY;
766 dX = x;
767 dY = y;
768 m_orientation = atan2((oY - dY), (oX - dX));
770 m_startMove = getMSTime();
771 m_moveTime = time;*/
772 SendMonsterMove(x, y, z, type, flags, time);
775 Player *Creature::GetLootRecipient() const
777 if (!m_lootRecipient)
778 return NULL;
779 else return ObjectAccessor::FindPlayer(m_lootRecipient);
782 void Creature::SetLootRecipient(Unit *unit)
784 // set the player whose group should receive the right
785 // to loot the creature after it dies
786 // should be set to NULL after the loot disappears
788 if (!unit)
790 m_lootRecipient = 0;
791 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
792 return;
795 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
796 if(!player) // normal creature, no player involved
797 return;
799 m_lootRecipient = player->GetGUID();
800 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
803 void Creature::SaveToDB()
805 // this should only be used when the creature has already been loaded
806 // preferably after adding to map, because mapid may not be valid otherwise
807 CreatureData const *data = sObjectMgr.GetCreatureData(m_DBTableGuid);
808 if(!data)
810 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
811 return;
814 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
817 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
819 // update in loaded data
820 if (!m_DBTableGuid)
821 m_DBTableGuid = GetGUIDLow();
822 CreatureData& data = sObjectMgr.NewOrExistCreatureData(m_DBTableGuid);
824 uint32 displayId = GetNativeDisplayId();
826 // check if it's a custom model and if not, use 0 for displayId
827 CreatureInfo const *cinfo = GetCreatureInfo();
828 if (cinfo)
830 if (displayId != cinfo->DisplayID_A[0] && displayId != cinfo->DisplayID_A[1] &&
831 displayId != cinfo->DisplayID_H[0] && displayId != cinfo->DisplayID_H[1])
833 if (cinfo->DisplayID_A[0])
834 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[0]))
835 if(displayId == minfo->modelid_other_gender)
836 displayId = 0;
838 if (displayId && cinfo->DisplayID_A[1])
839 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_A[1]))
840 if(displayId == minfo->modelid_other_gender)
841 displayId = 0;
843 if (displayId && cinfo->DisplayID_H[0])
844 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[0]))
845 if(displayId == minfo->modelid_other_gender)
846 displayId = 0;
848 if (displayId && cinfo->DisplayID_H[1])
849 if (CreatureModelInfo const *minfo = sObjectMgr.GetCreatureModelInfo(cinfo->DisplayID_H[1]))
850 if(displayId == minfo->modelid_other_gender)
851 displayId = 0;
853 else
854 displayId = 0;
857 // data->guid = guid don't must be update at save
858 data.id = GetEntry();
859 data.mapid = mapid;
860 data.phaseMask = phaseMask;
861 data.displayid = displayId;
862 data.equipmentId = GetEquipmentId();
863 data.posX = GetPositionX();
864 data.posY = GetPositionY();
865 data.posZ = GetPositionZ();
866 data.orientation = GetOrientation();
867 data.spawntimesecs = m_respawnDelay;
868 // prevent add data integrity problems
869 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
870 data.currentwaypoint = 0;
871 data.curhealth = GetHealth();
872 data.curmana = GetPower(POWER_MANA);
873 data.is_dead = m_isDeadByDefault;
874 // prevent add data integrity problems
875 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
876 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
877 data.spawnMask = spawnMask;
879 // updated in DB
880 WorldDatabase.BeginTransaction();
882 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
884 std::ostringstream ss;
885 ss << "INSERT INTO creature VALUES ("
886 << m_DBTableGuid << ","
887 << GetEntry() << ","
888 << mapid <<","
889 << uint32(spawnMask) << "," // cast to prevent save as symbol
890 << uint16(GetPhaseMask()) << "," // prevent out of range error
891 << displayId <<","
892 << GetEquipmentId() <<","
893 << GetPositionX() << ","
894 << GetPositionY() << ","
895 << GetPositionZ() << ","
896 << GetOrientation() << ","
897 << m_respawnDelay << "," //respawn time
898 << (float) m_respawnradius << "," //spawn distance (float)
899 << (uint32) (0) << "," //currentwaypoint
900 << GetHealth() << "," //curhealth
901 << GetPower(POWER_MANA) << "," //curmana
902 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
903 << GetDefaultMovementType() << ")"; //default movement generator type
905 WorldDatabase.PExecuteLog("%s", ss.str().c_str());
907 WorldDatabase.CommitTransaction();
910 void Creature::SelectLevel(const CreatureInfo *cinfo)
912 uint32 rank = isPet()? 0 : cinfo->rank;
914 // level
915 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
916 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
917 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
918 SetLevel(level);
920 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
922 // health
923 float healthmod = _GetHealthMod(rank);
925 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
926 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
927 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
929 SetCreateHealth(health);
930 SetMaxHealth(health);
931 SetHealth(health);
933 // mana
934 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
935 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
936 uint32 mana = minmana + uint32(rellevel * (maxmana - minmana));
938 SetCreateMana(mana);
939 SetMaxPower(POWER_MANA, mana); //MAX Mana
940 SetPower(POWER_MANA, mana);
942 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
944 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
945 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
947 // damage
948 float damagemod = _GetDamageMod(rank);
950 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
951 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
953 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
954 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
956 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
959 float Creature::_GetHealthMod(int32 Rank)
961 switch (Rank) // define rates for each elite rank
963 case CREATURE_ELITE_NORMAL:
964 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
965 case CREATURE_ELITE_ELITE:
966 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
967 case CREATURE_ELITE_RAREELITE:
968 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
969 case CREATURE_ELITE_WORLDBOSS:
970 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
971 case CREATURE_ELITE_RARE:
972 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
973 default:
974 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
978 float Creature::_GetDamageMod(int32 Rank)
980 switch (Rank) // define rates for each elite rank
982 case CREATURE_ELITE_NORMAL:
983 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
984 case CREATURE_ELITE_ELITE:
985 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
986 case CREATURE_ELITE_RAREELITE:
987 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
988 case CREATURE_ELITE_WORLDBOSS:
989 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
990 case CREATURE_ELITE_RARE:
991 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
992 default:
993 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
997 float Creature::GetSpellDamageMod(int32 Rank)
999 switch (Rank) // define rates for each elite rank
1001 case CREATURE_ELITE_NORMAL:
1002 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1003 case CREATURE_ELITE_ELITE:
1004 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1005 case CREATURE_ELITE_RAREELITE:
1006 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1007 case CREATURE_ELITE_WORLDBOSS:
1008 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1009 case CREATURE_ELITE_RARE:
1010 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1011 default:
1012 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1016 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1018 CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
1019 if(!cinfo)
1021 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1022 return false;
1024 m_originalEntry = Entry;
1026 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1028 if(!UpdateEntry(Entry, team, data))
1029 return false;
1031 return true;
1034 bool Creature::LoadFromDB(uint32 guid, Map *map)
1036 CreatureData const* data = sObjectMgr.GetCreatureData(guid);
1038 if(!data)
1040 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1041 return false;
1044 m_DBTableGuid = guid;
1045 if (map->GetInstanceId() == 0)
1047 // Creature can be loaded already in map if grid has been unloaded while creature walk to another grid
1048 // FIXME: until creature guids is global and for instances used dynamic generated guids
1049 // in instance possible load creature duplicates with same DB guid but different in game guids
1050 // This will be until implementing per-map creature guids
1051 if (map->GetCreature(MAKE_NEW_GUID(guid, data->id, HIGHGUID_UNIT)))
1052 return false;
1054 else
1055 guid = sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT);
1057 uint16 team = 0;
1058 if(!Create(guid, map, data->phaseMask, data->id, team, data))
1059 return false;
1061 Relocate(data->posX, data->posY, data->posZ, data->orientation);
1063 if(!IsPositionValid())
1065 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)", GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
1066 return false;
1069 m_respawnradius = data->spawndist;
1071 m_respawnDelay = data->spawntimesecs;
1072 m_isDeadByDefault = data->is_dead;
1073 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1075 m_respawnTime = sObjectMgr.GetCreatureRespawnTime(m_DBTableGuid, GetInstanceId());
1076 if(m_respawnTime > time(NULL)) // not ready to respawn
1078 m_deathState = DEAD;
1079 if(canFly())
1081 float tz = GetMap()->GetHeight(data->posX, data->posY, data->posZ, false);
1082 if(data->posZ - tz > 0.1)
1083 Relocate(data->posX, data->posY, tz);
1086 else if(m_respawnTime) // respawn time set but expired
1088 m_respawnTime = 0;
1089 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1092 uint32 curhealth = data->curhealth;
1093 if(curhealth)
1095 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1096 if(curhealth < 1)
1097 curhealth = 1;
1100 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1101 SetPower(POWER_MANA, data->curmana);
1103 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1105 // checked at creature_template loading
1106 m_defaultMovementType = MovementGeneratorType(data->movementType);
1108 AIM_Initialize();
1109 return true;
1112 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1114 if(equip_entry == 0)
1116 if (force)
1118 for (uint8 i = 0; i < 3; ++i)
1119 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1120 m_equipmentId = 0;
1122 return;
1125 EquipmentInfo const *einfo = sObjectMgr.GetEquipmentInfo(equip_entry);
1126 if (!einfo)
1127 return;
1129 m_equipmentId = equip_entry;
1130 for (uint8 i = 0; i < 3; ++i)
1131 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1134 bool Creature::hasQuest(uint32 quest_id) const
1136 QuestRelations const& qr = sObjectMgr.mCreatureQuestRelations;
1137 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1139 if(itr->second==quest_id)
1140 return true;
1142 return false;
1145 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1147 QuestRelations const& qr = sObjectMgr.mCreatureQuestInvolvedRelations;
1148 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1150 if(itr->second == quest_id)
1151 return true;
1153 return false;
1156 void Creature::DeleteFromDB()
1158 if (!m_DBTableGuid)
1160 sLog.outDebug("Trying to delete not saved creature!");
1161 return;
1164 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1165 sObjectMgr.DeleteCreatureData(m_DBTableGuid);
1167 WorldDatabase.BeginTransaction();
1168 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1169 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1170 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1171 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1172 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1173 WorldDatabase.PExecuteLog("DELETE FROM creature_battleground WHERE guid = '%u'", m_DBTableGuid);
1174 WorldDatabase.CommitTransaction();
1177 float Creature::GetAttackDistance(Unit const* pl) const
1179 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1180 if(aggroRate == 0)
1181 return 0.0f;
1183 uint32 playerlevel = pl->getLevelForTarget(this);
1184 uint32 creaturelevel = getLevelForTarget(pl);
1186 int32 leveldif = int32(playerlevel) - int32(creaturelevel);
1188 // "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."
1189 if ( leveldif < - 25)
1190 leveldif = -25;
1192 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1193 float RetDistance = 20;
1195 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1196 // radius grow if playlevel < creaturelevel
1197 RetDistance -= (float)leveldif;
1199 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1201 // detect range auras
1202 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1204 // detected range auras
1205 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1208 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1209 if(RetDistance < 5)
1210 RetDistance = 5;
1212 return (RetDistance*aggroRate);
1215 void Creature::setDeathState(DeathState s)
1217 if ((s == JUST_DIED && !m_isDeadByDefault) || (s == JUST_ALIVED && m_isDeadByDefault))
1219 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1221 // always save boss respawn time at death to prevent crash cheating
1222 if (sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1223 SaveRespawnTime();
1225 if (canFly() && FallGround())
1226 return;
1228 if (!IsStopped())
1229 StopMoving();
1231 Unit::setDeathState(s);
1233 if (s == JUST_DIED)
1235 SetTargetGUID(0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1236 SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
1238 if (!isPet() && GetCreatureInfo()->SkinLootId)
1239 if (LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId))
1240 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1242 if (canFly() && FallGround())
1243 return;
1245 if (HasSearchedAssistance())
1247 SetNoSearchAssistance(false);
1248 UpdateSpeed(MOVE_RUN, false);
1251 Unit::setDeathState(CORPSE);
1253 if (s == JUST_ALIVED)
1255 SetHealth(GetMaxHealth());
1256 SetLootRecipient(NULL);
1257 CreatureInfo const *cinfo = GetCreatureInfo();
1258 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1259 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1260 AddSplineFlag(SPLINEFLAG_WALKMODE);
1261 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1262 Unit::setDeathState(ALIVE);
1263 clearUnitState(UNIT_STAT_ALL_STATE);
1264 i_motionMaster.Clear();
1265 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1266 LoadCreaturesAddon(true);
1270 bool Creature::FallGround()
1272 // Let's abort after we called this function one time
1273 if (getDeathState() == DEAD_FALLING)
1274 return false;
1276 // Let's do with no vmap because no way to get far distance with vmap high call
1277 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1279 // Abort too if the ground is very near
1280 if (fabs(GetPositionZ() - tz) < 0.1f)
1281 return false;
1283 Unit::setDeathState(DEAD_FALLING);
1284 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1285 Relocate(GetPositionX(), GetPositionY(), tz);
1286 return true;
1289 void Creature::Respawn()
1291 RemoveCorpse();
1293 // forced recreate creature object at clients
1294 UnitVisibility currentVis = GetVisibility();
1295 SetVisibility(VISIBILITY_RESPAWN);
1296 UpdateObjectVisibility();
1297 SetVisibility(currentVis); // restore visibility state
1298 UpdateObjectVisibility();
1300 if(getDeathState() == DEAD)
1302 if (m_DBTableGuid)
1303 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(), 0);
1304 m_respawnTime = time(NULL); // respawn at next tick
1308 void Creature::ForcedDespawn(uint32 timeMSToDespawn)
1310 if (timeMSToDespawn)
1312 ForcedDespawnDelayEvent *pEvent = new ForcedDespawnDelayEvent(*this);
1314 m_Events.AddEvent(pEvent, m_Events.CalculateTime(timeMSToDespawn));
1315 return;
1318 if (isAlive())
1319 setDeathState(JUST_DIED);
1321 RemoveCorpse();
1322 SetHealth(0); // just for nice GM-mode view
1325 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1327 if (!spellInfo)
1328 return false;
1330 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1331 return true;
1333 return Unit::IsImmunedToSpell(spellInfo);
1336 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1338 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1339 return true;
1341 // Taunt immunity special flag check
1342 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1344 // Taunt aura apply check
1345 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1347 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1348 return true;
1350 // Spell effect taunt check
1351 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1352 return true;
1355 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1358 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1360 if(!pVictim)
1361 return NULL;
1363 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
1365 if(!m_spells[i])
1366 continue;
1367 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1368 if(!spellInfo)
1370 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1371 continue;
1374 bool bcontinue = true;
1375 for(uint32 j = 0; j < 3; ++j)
1377 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1378 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1379 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1380 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1383 bcontinue = false;
1384 break;
1387 if(bcontinue) continue;
1389 if(spellInfo->manaCost > GetPower(POWER_MANA))
1390 continue;
1391 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1392 float range = GetSpellMaxRange(srange);
1393 float minrange = GetSpellMinRange(srange);
1395 float dist = GetCombatDistance(pVictim);
1397 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1398 // continue;
1399 if( dist > range || dist < minrange )
1400 continue;
1401 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1402 continue;
1403 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1404 continue;
1405 return spellInfo;
1407 return NULL;
1410 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1412 if(!pVictim)
1413 return NULL;
1415 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
1417 if(!m_spells[i])
1418 continue;
1419 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1420 if(!spellInfo)
1422 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1423 continue;
1426 bool bcontinue = true;
1427 for(uint32 j = 0; j < 3; ++j)
1429 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1431 bcontinue = false;
1432 break;
1435 if(bcontinue)
1436 continue;
1438 if(spellInfo->manaCost > GetPower(POWER_MANA))
1439 continue;
1440 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1441 float range = GetSpellMaxRange(srange);
1442 float minrange = GetSpellMinRange(srange);
1444 float dist = GetCombatDistance(pVictim);
1446 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1447 // continue;
1448 if( dist > range || dist < minrange )
1449 continue;
1450 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1451 continue;
1452 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1453 continue;
1454 return spellInfo;
1456 return NULL;
1459 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1461 // gamemaster in GM mode see all, including ghosts
1462 if(pl->isGameMaster())
1463 return true;
1465 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1466 return false;
1468 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1469 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1471 return (isAlive() || m_deathTimer > 0 || (m_isDeadByDefault && m_deathState == CORPSE));
1474 // Dead player see live creatures near own corpse
1475 if(isAlive())
1477 Corpse *corpse = pl->GetCorpse();
1478 if(corpse)
1480 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1481 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1482 return true;
1486 // Dead player can see ghosts
1487 if (GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_GHOST_VISIBLE)
1488 return true;
1490 // and not see any other
1491 return false;
1494 void Creature::SendAIReaction(AiReaction reactionType)
1496 WorldPacket data(SMSG_AI_REACTION, 12);
1498 data << uint64(GetGUID());
1499 data << uint32(reactionType);
1501 ((WorldObject*)this)->SendMessageToSet(&data, true);
1503 sLog.outDebug("WORLD: Sent SMSG_AI_REACTION, type %u.", reactionType);
1506 void Creature::CallAssistance()
1508 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1510 SetNoCallAssistance(true);
1512 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1513 if(radius > 0)
1515 std::list<Creature*> assistList;
1518 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1519 Cell cell(p);
1520 cell.data.Part.reserved = ALL_DISTRICT;
1521 cell.SetNoCreate();
1523 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1524 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1526 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1528 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
1531 if (!assistList.empty())
1533 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1534 while (!assistList.empty())
1536 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1537 e->AddAssistant((*assistList.begin())->GetGUID());
1538 assistList.pop_front();
1540 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1546 void Creature::CallForHelp(float fRadius)
1548 if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
1549 return;
1551 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1552 Cell cell(p);
1553 cell.data.Part.reserved = ALL_DISTRICT;
1554 cell.SetNoCreate();
1556 MaNGOS::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
1557 MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo> worker(this, u_do);
1559 TypeContainerVisitor<MaNGOS::CreatureWorker<MaNGOS::CallOfHelpCreatureInRangeDo>, GridTypeMapContainer > grid_creature_searcher(worker);
1561 cell.Visit(p, grid_creature_searcher, *GetMap(), *this, fRadius);
1564 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1566 // we don't need help from zombies :)
1567 if (!isAlive())
1568 return false;
1570 // we don't need help from non-combatant ;)
1571 if (isCivilian())
1572 return false;
1574 // skip fighting creature
1575 if (isInCombat())
1576 return false;
1578 // only free creature
1579 if (GetCharmerOrOwnerGUID())
1580 return false;
1582 // only from same creature faction
1583 if (checkfaction)
1585 if (getFaction() != u->getFaction())
1586 return false;
1588 else
1590 if (!IsFriendlyTo(u))
1591 return false;
1594 // skip non hostile to caster enemy creatures
1595 if (!IsHostileTo(enemy))
1596 return false;
1598 return true;
1601 void Creature::SaveRespawnTime()
1603 if(isPet() || !m_DBTableGuid)
1604 return;
1606 if(m_respawnTime > time(NULL)) // dead (no corpse)
1607 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(), m_respawnTime);
1608 else if(m_deathTimer > 0) // dead (corpse)
1609 sObjectMgr.SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(), time(NULL) + m_respawnDelay + m_deathTimer / IN_MILISECONDS);
1612 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1614 if (!pVictim)
1615 return true;
1617 if (!pVictim->IsInMap(this))
1618 return true;
1620 if (!pVictim->isTargetableForAttack())
1621 return true;
1623 if (!pVictim->isInAccessablePlaceFor(this))
1624 return true;
1626 if (!pVictim->isVisibleForOrDetect(this,this,false))
1627 return true;
1629 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1630 return false;
1632 float AttackDist = GetAttackDistance(pVictim);
1633 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1635 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1636 return !pVictim->IsWithinDist3d(CombatStartX, CombatStartY, CombatStartZ,
1637 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1640 CreatureDataAddon const* Creature::GetCreatureAddon() const
1642 if (m_DBTableGuid)
1644 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1645 return addon;
1648 // dependent from difficulty mode entry
1649 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1652 //creature_addon table
1653 bool Creature::LoadCreaturesAddon(bool reload)
1655 CreatureDataAddon const *cainfo = GetCreatureAddon();
1656 if(!cainfo)
1657 return false;
1659 if (cainfo->mount != 0)
1660 Mount(cainfo->mount);
1662 if (cainfo->bytes1 != 0)
1664 // 0 StandState
1665 // 1 FreeTalentPoints Pet only, so always 0 for default creature
1666 // 2 StandFlags
1667 // 3 StandMiscFlags
1669 SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
1670 //SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
1671 SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
1672 SetByteValue(UNIT_FIELD_BYTES_1, 2, uint8((cainfo->bytes1 >> 16) & 0xFF));
1673 SetByteValue(UNIT_FIELD_BYTES_1, 3, uint8((cainfo->bytes1 >> 24) & 0xFF));
1676 if (cainfo->bytes2 != 0)
1678 // 0 SheathState
1679 // 1 UnitPVPStateFlags Set at Creature::UpdateEntry (SetPvp())
1680 // 2 UnitRename Pet only, so always 0 for default creature
1681 // 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
1683 SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
1684 //SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
1685 //SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
1686 SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
1687 //SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
1688 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
1691 if (cainfo->emote != 0)
1692 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1694 if (cainfo->splineFlags != 0)
1695 SetSplineFlags(SplineFlags(cainfo->splineFlags));
1697 if(cainfo->auras)
1699 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1701 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1702 if (!AdditionalSpellInfo)
1704 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1705 continue;
1708 // skip already applied aura
1709 if(HasAura(cAura->spell_id,cAura->effect_idx))
1711 if(!reload)
1712 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);
1714 continue;
1717 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1718 AddAura(AdditionalAura);
1719 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1722 return true;
1725 /// Send a message to LocalDefense channel for players opposition team in the zone
1726 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1728 uint32 enemy_team = attacker->GetTeam();
1730 WorldPacket data(SMSG_ZONE_UNDER_ATTACK, 4);
1731 data << uint32(GetZoneId());
1732 sWorld.SendGlobalMessage(&data, NULL, (enemy_team == ALLIANCE ? HORDE : ALLIANCE));
1735 void Creature::SetInCombatWithZone()
1737 if (!CanHaveThreatList())
1739 sLog.outError("Creature entry %u call SetInCombatWithZone but creature cannot have threat list.", GetEntry());
1740 return;
1743 Map* pMap = GetMap();
1745 if (!pMap->IsDungeon())
1747 sLog.outError("Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.", GetEntry(), pMap->GetId());
1748 return;
1751 Map::PlayerList const &PlList = pMap->GetPlayers();
1753 if (PlList.isEmpty())
1754 return;
1756 for(Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
1758 if (Player* pPlayer = i->getSource())
1760 if (pPlayer->isGameMaster())
1761 continue;
1763 if (pPlayer->isAlive())
1765 pPlayer->SetInCombatWith(this);
1766 AddThreat(pPlayer);
1772 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1774 m_CreatureSpellCooldowns[spell_id] = end_time;
1777 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1779 m_CreatureCategoryCooldowns[category] = apply_time;
1782 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1784 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1785 if(!spellInfo)
1786 return;
1788 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1789 if(cooldown)
1790 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1792 if(spellInfo->Category)
1793 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1795 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1798 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1800 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1801 if(!spellInfo)
1802 return false;
1804 // check global cooldown if spell affected by it
1805 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1806 return true;
1808 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1809 return (itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1812 bool Creature::HasSpellCooldown(uint32 spell_id) const
1814 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1815 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1818 bool Creature::IsInEvadeMode() const
1820 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1823 bool Creature::HasSpell(uint32 spellID) const
1825 uint8 i;
1826 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1827 if(spellID == m_spells[i])
1828 break;
1829 return i < CREATURE_MAX_SPELLS; // break before end of iteration of known spells
1832 time_t Creature::GetRespawnTimeEx() const
1834 time_t now = time(NULL);
1835 if(m_respawnTime > now) // dead (no corpse)
1836 return m_respawnTime;
1837 else if(m_deathTimer > 0) // dead (corpse)
1838 return now + m_respawnDelay + m_deathTimer / IN_MILISECONDS;
1839 else
1840 return now;
1843 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1845 if (m_DBTableGuid)
1847 if (CreatureData const* data = sObjectMgr.GetCreatureData(GetDBTableGUIDLow()))
1849 x = data->posX;
1850 y = data->posY;
1851 z = data->posZ;
1852 if (ori)
1853 *ori = data->orientation;
1854 if (dist)
1855 *dist = data->spawndist;
1857 return;
1861 float orient;
1863 GetSummonPoint(x, y, z, orient);
1865 if (ori)
1866 *ori = orient;
1867 if (dist)
1868 *dist = GetRespawnRadius();
1871 void Creature::AllLootRemovedFromCorpse()
1873 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1875 uint32 nDeathTimer;
1877 CreatureInfo const *cinfo = GetCreatureInfo();
1879 // corpse was not skinnable -> apply corpse looted timer
1880 if (!cinfo || !cinfo->SkinLootId)
1881 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1882 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1883 else
1884 nDeathTimer = 0;
1886 // update death timer only if looted timer is shorter
1887 if (m_deathTimer > nDeathTimer)
1888 m_deathTimer = nDeathTimer;
1892 uint32 Creature::getLevelForTarget( Unit const* target ) const
1894 if(!isWorldBoss())
1895 return Unit::getLevelForTarget(target);
1897 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1898 if(level < 1)
1899 return 1;
1900 if(level > 255)
1901 return 255;
1902 return level;
1905 std::string Creature::GetAIName() const
1907 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
1910 std::string Creature::GetScriptName() const
1912 return sObjectMgr.GetScriptName(GetScriptId());
1915 uint32 Creature::GetScriptId() const
1917 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
1920 VendorItemData const* Creature::GetVendorItems() const
1922 return sObjectMgr.GetNpcVendorItemList(GetEntry());
1925 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
1927 if(!vItem->maxcount)
1928 return vItem->maxcount;
1930 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1931 for(; itr != m_vendorItemCounts.end(); ++itr)
1932 if(itr->itemId==vItem->item)
1933 break;
1935 if(itr == m_vendorItemCounts.end())
1936 return vItem->maxcount;
1938 VendorItemCount* vCount = &*itr;
1940 time_t ptime = time(NULL);
1942 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1944 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
1946 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1947 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
1949 m_vendorItemCounts.erase(itr);
1950 return vItem->maxcount;
1953 vCount->count += diff * pProto->BuyCount;
1954 vCount->lastIncrementTime = ptime;
1957 return vCount->count;
1960 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
1962 if(!vItem->maxcount)
1963 return 0;
1965 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1966 for(; itr != m_vendorItemCounts.end(); ++itr)
1967 if(itr->itemId==vItem->item)
1968 break;
1970 if(itr == m_vendorItemCounts.end())
1972 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
1973 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
1974 return new_count;
1977 VendorItemCount* vCount = &*itr;
1979 time_t ptime = time(NULL);
1981 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1983 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
1985 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1986 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
1987 vCount->count += diff * pProto->BuyCount;
1988 else
1989 vCount->count = vItem->maxcount;
1992 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
1993 vCount->lastIncrementTime = ptime;
1994 return vCount->count;
1997 TrainerSpellData const* Creature::GetTrainerSpells() const
1999 return sObjectMgr.GetNpcTrainerSpells(GetEntry());
2002 // overwrite WorldObject function for proper name localization
2003 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2005 if (loc_idx >= 0)
2007 CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(GetEntry());
2008 if (cl)
2010 if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
2011 return cl->Name[loc_idx].c_str();
2015 return GetName();
2018 void Creature::SetActiveObjectState( bool on )
2020 if(m_isActiveObject==on)
2021 return;
2023 bool world = IsInWorld();
2025 Map* map;
2026 if(world)
2028 map = GetMap();
2029 map->Remove(this,false);
2032 m_isActiveObject = on;
2034 if(world)
2035 map->Add(this);
2038 void Creature::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
2040 float x, y, z;
2041 if(GetMotionMaster()->GetDestination(x, y, z))
2042 SendMonsterMoveWithSpeed(x, y, z, 0, player);
2045 void Creature::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
2047 if (!transitTime)
2049 if(GetTypeId()==TYPEID_PLAYER)
2051 Traveller<Player> traveller(*(Player*)this);
2052 transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
2054 else
2056 Traveller<Creature> traveller(*(Creature*)this);
2057 transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
2060 //float orientation = (float)atan2((double)dy, (double)dx);
2061 SendMonsterMove(x, y, z, 0, GetSplineFlags(), transitTime, player);
2064 void Creature::SendAreaSpiritHealerQueryOpcode(Player *pl)
2066 uint32 next_resurrect = 0;
2067 if (Spell* pcurSpell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
2068 next_resurrect = pcurSpell->GetCastedTime();
2069 WorldPacket data(SMSG_AREA_SPIRIT_HEALER_TIME, 8 + 4);
2070 data << GetGUID() << next_resurrect;
2071 pl->SendDirectMessage(&data);