[7871] Drop unused second arg in InstanceData::OnCreatureCreate.
[getmangos.git] / src / game / Creature.cpp
blob6b941271a715e96f4337d410000cfe6760fea717
1 /*
2 * Copyright (C) 2005-2009 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 "SpellMgr.h"
25 #include "Creature.h"
26 #include "QuestDef.h"
27 #include "GossipDef.h"
28 #include "Player.h"
29 #include "PoolHandler.h"
30 #include "Opcodes.h"
31 #include "Log.h"
32 #include "LootMgr.h"
33 #include "MapManager.h"
34 #include "CreatureAI.h"
35 #include "CreatureAISelector.h"
36 #include "Formulas.h"
37 #include "WaypointMovementGenerator.h"
38 #include "InstanceData.h"
39 #include "BattleGroundMgr.h"
40 #include "Util.h"
41 #include "GridNotifiers.h"
42 #include "GridNotifiersImpl.h"
43 #include "CellImpl.h"
45 // apply implementation of the singletons
46 #include "Policies/SingletonImp.h"
48 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
50 TrainerSpellMap::const_iterator itr = spellList.find(spell_id);
51 if (itr != spellList.end())
52 return &itr->second;
54 return NULL;
57 bool VendorItemData::RemoveItem( uint32 item_id )
59 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
61 if((*i)->item==item_id)
63 m_items.erase(i);
64 return true;
67 return false;
70 size_t VendorItemData::FindItemSlot(uint32 item_id) const
72 for(size_t i = 0; i < m_items.size(); ++i )
73 if(m_items[i]->item==item_id)
74 return i;
75 return m_items.size();
78 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
80 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
81 if((*i)->item==item_id)
82 return *i;
83 return NULL;
86 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
88 if(Unit* victim = Unit::GetUnit(m_owner, m_victim))
90 while (!m_assistants.empty())
92 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
93 m_assistants.pop_front();
95 if (assistant && assistant->CanAssistTo(&m_owner, victim))
97 assistant->SetNoCallAssistance(true);
98 if(assistant->AI())
99 assistant->AI()->AttackStart(victim);
103 return true;
106 Creature::Creature() :
107 Unit(), i_AI(NULL),
108 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
109 m_lootMoney(0), m_lootRecipient(0),
110 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
111 m_gossipOptionLoaded(false), m_isPet(false), m_isVehicle(false), m_isTotem(false),
112 m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0), m_AlreadyCallAssistance(false),
113 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
114 m_creatureInfo(NULL), m_isActiveObject(false), m_AlreadySearchedAssistance(false)
116 m_regenTimer = 200;
117 m_valuesCount = UNIT_END;
119 for(int i =0; i<4; ++i)
120 m_spells[i] = 0;
122 m_CreatureSpellCooldowns.clear();
123 m_CreatureCategoryCooldowns.clear();
124 m_GlobalCooldown = 0;
125 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
128 Creature::~Creature()
130 CleanupsBeforeDelete();
132 m_vendorItemCounts.clear();
134 delete i_AI;
135 i_AI = NULL;
138 void Creature::AddToWorld()
140 ///- Register the creature for guid lookup
141 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
142 Unit::AddToWorld();
145 void Creature::RemoveFromWorld()
147 ///- Remove the creature from the accessor
148 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
149 Unit::RemoveFromWorld();
152 void Creature::RemoveCorpse()
154 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
155 return;
157 m_deathTimer = 0;
158 setDeathState(DEAD);
159 ObjectAccessor::UpdateObjectVisibility(this);
160 loot.clear();
161 m_respawnTime = time(NULL) + m_respawnDelay;
163 float x,y,z,o;
164 GetRespawnCoord(x, y, z, &o);
165 GetMap()->CreatureRelocation(this,x,y,z,o);
169 * change the entry of creature until respawn
171 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
173 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
174 if(!normalInfo)
176 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
177 return false;
180 // get heroic mode entry
181 uint32 actualEntry = Entry;
182 CreatureInfo const *cinfo = normalInfo;
183 if(normalInfo->HeroicEntry)
185 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
186 if(map && map->IsHeroic())
188 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
189 if(!cinfo)
191 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
192 return false;
197 SetEntry(Entry); // normal entry always
198 m_creatureInfo = cinfo; // map mode related always
200 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
202 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
203 return false;
206 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
207 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
208 if (!minfo)
210 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
211 return false;
213 else
214 display_id = minfo->modelid; // it can be different (for another gender)
216 SetDisplayId(display_id);
217 SetNativeDisplayId(display_id);
218 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
220 // Load creature equipment
221 if(!data || data->equipmentId == 0)
222 { // use default from the template
223 LoadEquipment(cinfo->equipmentId);
225 else if(data && data->equipmentId != -1)
226 { // override, -1 means no equipment
227 LoadEquipment(data->equipmentId);
230 SetName(normalInfo->Name); // at normal entry always
232 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
233 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
235 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
237 SetSpeed(MOVE_WALK, cinfo->speed );
238 SetSpeed(MOVE_RUN, cinfo->speed );
239 SetSpeed(MOVE_SWIM, cinfo->speed );
241 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
243 // checked at loading
244 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
245 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
246 m_defaultMovementType = IDLE_MOTION_TYPE;
248 return true;
251 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
253 if(!InitEntry(Entry,team,data))
254 return false;
256 m_regenHealth = GetCreatureInfo()->RegenHealth;
258 // creatures always have melee weapon ready if any
259 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
261 SelectLevel(GetCreatureInfo());
262 if (team == HORDE)
263 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
264 else
265 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
267 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
269 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
270 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
271 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
273 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
274 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
276 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
277 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
278 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
279 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
280 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
281 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
282 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
284 SetCanModifyStats(true);
285 UpdateAllStats();
287 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
288 if (factionTemplate) // check and error show at loading templates
290 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
291 if (factionEntry)
292 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
293 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
294 SetPvP(true);
297 for(int i=0; i < CREATURE_MAX_SPELLS; ++i)
298 m_spells[i] = GetCreatureInfo()->spells[i];
300 return true;
303 void Creature::Update(uint32 diff)
305 if(m_GlobalCooldown <= diff)
306 m_GlobalCooldown = 0;
307 else
308 m_GlobalCooldown -= diff;
310 switch( m_deathState )
312 case JUST_ALIVED:
313 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
314 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
315 break;
316 case JUST_DIED:
317 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
318 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
319 break;
320 case DEAD:
322 if( m_respawnTime <= time(NULL) )
324 DEBUG_LOG("Respawning...");
325 m_respawnTime = 0;
326 lootForPickPocketed = false;
327 lootForBody = false;
329 if(m_originalEntry != GetEntry())
330 UpdateEntry(m_originalEntry);
332 CreatureInfo const *cinfo = GetCreatureInfo();
334 SelectLevel(cinfo);
335 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
336 if (m_isDeadByDefault)
338 setDeathState(JUST_DIED);
339 SetHealth(0);
340 i_motionMaster.Clear();
341 clearUnitState(UNIT_STAT_ALL_STATE);
342 LoadCreaturesAddon(true);
344 else
345 setDeathState( JUST_ALIVED );
347 //Call AI respawn virtual function
348 i_AI->JustRespawned();
350 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), GetTypeId());
351 if (poolid)
352 poolhandler.UpdatePool(poolid, GetGUIDLow(), GetTypeId());
353 else
354 GetMap()->Add(this);
356 break;
358 case CORPSE:
360 if (m_isDeadByDefault)
361 break;
363 if( m_deathTimer <= diff )
365 RemoveCorpse();
366 DEBUG_LOG("Removing corpse... %u ", GetEntry());
368 else
370 m_deathTimer -= diff;
371 if (m_groupLootTimer && lootingGroupLeaderGUID)
373 if(diff <= m_groupLootTimer)
375 m_groupLootTimer -= diff;
377 else
379 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
380 if (group)
381 group->EndRoll();
382 m_groupLootTimer = 0;
383 lootingGroupLeaderGUID = 0;
388 break;
390 case ALIVE:
392 if (m_isDeadByDefault)
394 if( m_deathTimer <= diff )
396 RemoveCorpse();
397 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
399 else
401 m_deathTimer -= diff;
405 Unit::Update( diff );
407 // creature can be dead after Unit::Update call
408 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
409 if(!isAlive())
410 break;
412 if(!IsInEvadeMode())
414 // do not allow the AI to be changed during update
415 m_AI_locked = true;
416 i_AI->UpdateAI(diff);
417 m_AI_locked = false;
420 // creature can be dead after UpdateAI call
421 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
422 if(!isAlive())
423 break;
424 if(m_regenTimer > 0)
426 if(diff >= m_regenTimer)
427 m_regenTimer = 0;
428 else
429 m_regenTimer -= diff;
431 if (m_regenTimer != 0)
432 break;
434 if (!isInCombat() || IsPolymorphed())
435 RegenerateHealth();
437 RegenerateMana();
439 m_regenTimer = 2000;
440 break;
442 case DEAD_FALLING:
444 if (!FallGround())
445 setDeathState(JUST_DIED);
447 default:
448 break;
452 void Creature::RegenerateMana()
454 uint32 curValue = GetPower(POWER_MANA);
455 uint32 maxValue = GetMaxPower(POWER_MANA);
457 if (curValue >= maxValue)
458 return;
460 uint32 addvalue = 0;
462 // Combat and any controlled creature
463 if (isInCombat() || GetCharmerOrOwnerGUID())
465 if(!IsUnderLastManaUseEffect())
467 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
468 float Spirit = GetStat(STAT_SPIRIT);
470 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
473 else
474 addvalue = maxValue/3;
476 ModifyPower(POWER_MANA, addvalue);
479 void Creature::RegenerateHealth()
481 if (!isRegeneratingHealth())
482 return;
484 uint32 curValue = GetHealth();
485 uint32 maxValue = GetMaxHealth();
487 if (curValue >= maxValue)
488 return;
490 uint32 addvalue = 0;
492 // Not only pet, but any controlled creature
493 if(GetCharmerOrOwnerGUID())
495 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
496 float Spirit = GetStat(STAT_SPIRIT);
498 if( GetPower(POWER_MANA) > 0 )
499 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
500 else
501 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
503 else
504 addvalue = maxValue/3;
506 ModifyHealth(addvalue);
509 void Creature::DoFleeToGetAssistance()
511 if (!getVictim())
512 return;
514 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
515 if (radius >0)
517 Creature* pCreature = NULL;
519 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
520 Cell cell(p);
521 cell.data.Part.reserved = ALL_DISTRICT;
522 cell.SetNoCreate();
523 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
524 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
526 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
528 CellLock<GridReadGuard> cell_lock(cell, p);
529 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
531 SetNoSearchAssistance(true);
532 if(!pCreature)
533 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
534 else
535 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
539 bool Creature::AIM_Initialize()
541 // make sure nothing can change the AI during AI update
542 if(m_AI_locked)
544 sLog.outDebug("AIM_Initialize: failed to init, locked.");
545 return false;
548 CreatureAI * oldAI = i_AI;
549 i_motionMaster.Initialize();
550 i_AI = FactorySelector::selectAI(this);
551 if (oldAI)
552 delete oldAI;
553 return true;
556 bool Creature::Create (uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
558 SetMapId(map->GetId());
559 SetInstanceId(map->GetInstanceId());
560 SetPhaseMask(phaseMask,false);
562 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
563 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
565 if (bResult)
567 switch (GetCreatureInfo()->rank)
569 case CREATURE_ELITE_RARE:
570 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
571 break;
572 case CREATURE_ELITE_ELITE:
573 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
574 break;
575 case CREATURE_ELITE_RAREELITE:
576 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
577 break;
578 case CREATURE_ELITE_WORLDBOSS:
579 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
580 break;
581 default:
582 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
583 break;
585 LoadCreaturesAddon();
588 return bResult;
591 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
593 if(!isTrainer())
594 return false;
596 TrainerSpellData const* trainer_spells = GetTrainerSpells();
598 if(!trainer_spells || trainer_spells->spellList.empty())
600 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
601 GetGUIDLow(),GetEntry());
602 return false;
605 switch(GetCreatureInfo()->trainer_type)
607 case TRAINER_TYPE_CLASS:
608 if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
610 if(msg)
612 pPlayer->PlayerTalkClass->ClearMenus();
613 switch(GetCreatureInfo()->classNum)
615 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
616 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
617 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
618 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
619 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
620 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
621 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
622 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
623 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
626 return false;
628 break;
629 case TRAINER_TYPE_PETS:
630 if(pPlayer->getClass()!=CLASS_HUNTER)
632 pPlayer->PlayerTalkClass->ClearMenus();
633 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
634 return false;
636 break;
637 case TRAINER_TYPE_MOUNTS:
638 if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
640 if(msg)
642 pPlayer->PlayerTalkClass->ClearMenus();
643 switch(GetCreatureInfo()->classNum)
645 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
646 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
647 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
648 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
649 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
650 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
651 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
652 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
653 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
654 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
657 return false;
659 break;
660 case TRAINER_TYPE_TRADESKILLS:
661 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
663 if(msg)
665 pPlayer->PlayerTalkClass->ClearMenus();
666 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
668 return false;
670 break;
671 default:
672 return false; // checked and error output at creature_template loading
674 return true;
677 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
679 if(!isBattleMaster())
680 return false;
682 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
683 if(!msg)
684 return pPlayer->GetBGAccessByLevel(bgTypeId);
686 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
688 pPlayer->PlayerTalkClass->ClearMenus();
689 switch(bgTypeId)
691 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
692 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
693 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
694 case BATTLEGROUND_EY:
695 case BATTLEGROUND_NA:
696 case BATTLEGROUND_BE:
697 case BATTLEGROUND_AA:
698 case BATTLEGROUND_RL:
699 case BATTLEGROUND_SA:
700 case BATTLEGROUND_DS:
701 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
702 default: break;
704 return false;
706 return true;
709 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
711 return pPlayer->getLevel() >= 10
712 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
713 && pPlayer->getClass() == GetCreatureInfo()->classNum;
716 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
718 PlayerMenu* pm=pPlayer->PlayerTalkClass;
719 pm->ClearMenus();
721 // lazy loading single time at use
722 LoadGossipOptions();
724 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
726 GossipOption* gso=&*i;
727 if(gso->GossipId == gossipid)
729 bool cantalking=true;
730 if(gso->Id==1)
732 uint32 textid=GetNpcTextId();
733 GossipText const* gossiptext=objmgr.GetGossipText(textid);
734 if(!gossiptext)
735 cantalking=false;
737 else
739 switch (gso->Action)
741 case GOSSIP_OPTION_QUESTGIVER:
742 pPlayer->PrepareQuestMenu(GetGUID());
743 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
744 cantalking=false;
745 //pm->GetQuestMenu()->ClearMenu();
746 break;
747 case GOSSIP_OPTION_ARMORER:
748 cantalking=false; // added in special mode
749 break;
750 case GOSSIP_OPTION_SPIRITHEALER:
751 if( !pPlayer->isDead() )
752 cantalking=false;
753 break;
754 case GOSSIP_OPTION_VENDOR:
756 VendorItemData const* vItems = GetVendorItems();
757 if(!vItems || vItems->Empty())
759 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
760 GetGUIDLow(),GetEntry());
761 cantalking=false;
763 break;
765 case GOSSIP_OPTION_TRAINER:
766 if(!isCanTrainingOf(pPlayer,false))
767 cantalking=false;
768 break;
769 case GOSSIP_OPTION_UNLEARNTALENTS:
770 if(!isCanTrainingAndResetTalentsOf(pPlayer))
771 cantalking=false;
772 break;
773 case GOSSIP_OPTION_UNLEARNPETSKILLS:
774 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
775 cantalking=false;
776 break;
777 case GOSSIP_OPTION_TAXIVENDOR:
778 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
779 return;
780 break;
781 case GOSSIP_OPTION_BATTLEFIELD:
782 if(!isCanInteractWithBattleMaster(pPlayer,false))
783 cantalking=false;
784 break;
785 case GOSSIP_OPTION_SPIRITGUIDE:
786 case GOSSIP_OPTION_INNKEEPER:
787 case GOSSIP_OPTION_BANKER:
788 case GOSSIP_OPTION_PETITIONER:
789 case GOSSIP_OPTION_STABLEPET:
790 case GOSSIP_OPTION_TABARDDESIGNER:
791 case GOSSIP_OPTION_AUCTIONEER:
792 break; // no checks
793 default:
794 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
795 break;
799 //note for future dev: should have database fields for BoxMessage & BoxMoney
800 if(!gso->OptionText.empty() && cantalking)
802 std::string OptionText = gso->OptionText;
803 std::string BoxText = gso->BoxText;
804 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
805 if (loc_idx >= 0)
807 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
808 if (no)
810 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
811 OptionText=no->OptionText[loc_idx];
812 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
813 BoxText=no->BoxText[loc_idx];
816 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
821 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
822 if(pm->Empty())
824 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
826 isCanTrainingOf(pPlayer,true); // output error message if need
828 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
830 isCanInteractWithBattleMaster(pPlayer,true); // output error message if need
835 void Creature::sendPreparedGossip(Player* player)
837 if(!player)
838 return;
840 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
841 if (!HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !player->PlayerTalkClass->GetQuestMenu().Empty())
843 player->SendPreparedQuest(GetGUID());
844 return;
847 // in case non empty gossip menu (that not included quests list size) show it
848 // (quest entries from quest menu will be included in list)
849 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
852 void Creature::OnGossipSelect(Player* player, uint32 option)
854 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
856 if(option >= gossipmenu.MenuItemCount())
857 return;
859 uint32 action=gossipmenu.GetItem(option).m_gAction;
860 uint32 zoneid=GetZoneId();
861 uint64 guid=GetGUID();
863 GossipOption const *gossip=GetGossipOption( action );
864 if(!gossip)
866 zoneid=0;
867 gossip=GetGossipOption( action );
868 if(!gossip)
869 return;
872 switch (gossip->Action)
874 case GOSSIP_OPTION_GOSSIP:
876 uint32 textid = GetGossipTextId(action, zoneid);
877 if (textid == 0)
878 textid=GetNpcTextId();
880 player->PlayerTalkClass->CloseGossip();
881 player->PlayerTalkClass->SendTalking(textid);
882 break;
884 case GOSSIP_OPTION_SPIRITHEALER:
885 if (player->isDead())
886 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
887 break;
888 case GOSSIP_OPTION_QUESTGIVER:
889 player->PrepareQuestMenu( guid );
890 player->SendPreparedQuest( guid );
891 break;
892 case GOSSIP_OPTION_VENDOR:
893 case GOSSIP_OPTION_ARMORER:
894 player->GetSession()->SendListInventory(guid);
895 break;
896 case GOSSIP_OPTION_STABLEPET:
897 player->GetSession()->SendStablePet(guid);
898 break;
899 case GOSSIP_OPTION_TRAINER:
900 player->GetSession()->SendTrainerList(guid);
901 break;
902 case GOSSIP_OPTION_UNLEARNTALENTS:
903 player->PlayerTalkClass->CloseGossip();
904 player->SendTalentWipeConfirm(guid);
905 break;
906 case GOSSIP_OPTION_UNLEARNPETSKILLS:
907 player->PlayerTalkClass->CloseGossip();
908 player->SendPetSkillWipeConfirm();
909 break;
910 case GOSSIP_OPTION_TAXIVENDOR:
911 player->GetSession()->SendTaxiMenu(this);
912 break;
913 case GOSSIP_OPTION_INNKEEPER:
914 player->PlayerTalkClass->CloseGossip();
915 player->SetBindPoint( guid );
916 break;
917 case GOSSIP_OPTION_BANKER:
918 player->GetSession()->SendShowBank( guid );
919 break;
920 case GOSSIP_OPTION_PETITIONER:
921 player->PlayerTalkClass->CloseGossip();
922 player->GetSession()->SendPetitionShowList( guid );
923 break;
924 case GOSSIP_OPTION_TABARDDESIGNER:
925 player->PlayerTalkClass->CloseGossip();
926 player->GetSession()->SendTabardVendorActivate( guid );
927 break;
928 case GOSSIP_OPTION_AUCTIONEER:
929 player->GetSession()->SendAuctionHello( guid, this );
930 break;
931 case GOSSIP_OPTION_SPIRITGUIDE:
932 case GOSSIP_GUARD_SPELLTRAINER:
933 case GOSSIP_GUARD_SKILLTRAINER:
934 prepareGossipMenu( player,gossip->Id );
935 sendPreparedGossip( player );
936 break;
937 case GOSSIP_OPTION_BATTLEFIELD:
939 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
940 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
941 break;
943 default:
944 OnPoiSelect( player, gossip );
945 break;
950 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
952 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
954 Poi_Icon icon = ICON_POI_BLANK;
955 //need add more case.
956 switch(gossip->Action)
958 case GOSSIP_GUARD_BANK:
959 icon=ICON_POI_SMALL_HOUSE;
960 break;
961 case GOSSIP_GUARD_RIDE:
962 icon=ICON_POI_RWHORSE;
963 break;
964 case GOSSIP_GUARD_GUILD:
965 icon=ICON_POI_BLUETOWER;
966 break;
967 default:
968 icon=ICON_POI_GREYTOWER;
969 break;
971 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
972 player->PlayerTalkClass->SendTalking(textid);
973 // std::string areaname= gossip->OptionText;
974 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
978 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
980 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
982 if(!result)
983 return 0;
985 Field *fields = result->Fetch();
986 uint32 id = fields[0].GetUInt32();
988 delete result;
990 return id;
993 uint32 Creature::GetNpcTextId()
995 if (!m_DBTableGuid)
996 return DEFAULT_GOSSIP_MESSAGE;
998 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
999 return pos;
1001 return DEFAULT_GOSSIP_MESSAGE;
1004 GossipOption const* Creature::GetGossipOption( uint32 id ) const
1006 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
1008 if(i->Action==id )
1009 return &*i;
1011 return NULL;
1014 void Creature::LoadGossipOptions()
1016 if(m_gossipOptionLoaded)
1017 return;
1019 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1021 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1022 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1023 if(i->NpcFlag & npcflags)
1024 addGossipOption(*i);
1026 m_gossipOptionLoaded = true;
1029 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1031 /* uint32 timeElap = getMSTime();
1032 if ((timeElap - m_startMove) < m_moveTime)
1034 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1035 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1037 else
1039 oX = dX;
1040 oY = dY;
1043 dX = x;
1044 dY = y;
1045 m_orientation = atan2((oY - dY), (oX - dX));
1047 m_startMove = getMSTime();
1048 m_moveTime = time;*/
1049 SendMonsterMove(x, y, z, type, MovementFlags, time);
1052 Player *Creature::GetLootRecipient() const
1054 if (!m_lootRecipient) return NULL;
1055 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1058 void Creature::SetLootRecipient(Unit *unit)
1060 // set the player whose group should receive the right
1061 // to loot the creature after it dies
1062 // should be set to NULL after the loot disappears
1064 if (!unit)
1066 m_lootRecipient = 0;
1067 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1068 return;
1071 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1072 if(!player) // normal creature, no player involved
1073 return;
1075 m_lootRecipient = player->GetGUID();
1076 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1079 void Creature::SaveToDB()
1081 // this should only be used when the creature has already been loaded
1082 // preferably after adding to map, because mapid may not be valid otherwise
1083 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1084 if(!data)
1086 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1087 return;
1090 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
1093 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
1095 // update in loaded data
1096 if (!m_DBTableGuid)
1097 m_DBTableGuid = GetGUIDLow();
1098 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1100 uint32 displayId = GetNativeDisplayId();
1102 // check if it's a custom model and if not, use 0 for displayId
1103 CreatureInfo const *cinfo = GetCreatureInfo();
1104 if(cinfo)
1106 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1108 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1109 if(!minfo || displayId != minfo->modelid_other_gender)
1111 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1112 if(minfo && displayId == minfo->modelid_other_gender)
1113 displayId = 0;
1115 else
1116 displayId = 0;
1118 else
1119 displayId = 0;
1122 // data->guid = guid don't must be update at save
1123 data.id = GetEntry();
1124 data.mapid = mapid;
1125 data.phaseMask = phaseMask;
1126 data.displayid = displayId;
1127 data.equipmentId = GetEquipmentId();
1128 data.posX = GetPositionX();
1129 data.posY = GetPositionY();
1130 data.posZ = GetPositionZ();
1131 data.orientation = GetOrientation();
1132 data.spawntimesecs = m_respawnDelay;
1133 // prevent add data integrity problems
1134 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1135 data.currentwaypoint = 0;
1136 data.curhealth = GetHealth();
1137 data.curmana = GetPower(POWER_MANA);
1138 data.is_dead = m_isDeadByDefault;
1139 // prevent add data integrity problems
1140 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1141 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1142 data.spawnMask = spawnMask;
1144 // updated in DB
1145 WorldDatabase.BeginTransaction();
1147 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1149 std::ostringstream ss;
1150 ss << "INSERT INTO creature VALUES ("
1151 << m_DBTableGuid << ","
1152 << GetEntry() << ","
1153 << mapid <<","
1154 << uint32(spawnMask) << "," // cast to prevent save as symbol
1155 << uint16(GetPhaseMask()) << "," // prevent out of range error
1156 << displayId <<","
1157 << GetEquipmentId() <<","
1158 << GetPositionX() << ","
1159 << GetPositionY() << ","
1160 << GetPositionZ() << ","
1161 << GetOrientation() << ","
1162 << m_respawnDelay << "," //respawn time
1163 << (float) m_respawnradius << "," //spawn distance (float)
1164 << (uint32) (0) << "," //currentwaypoint
1165 << GetHealth() << "," //curhealth
1166 << GetPower(POWER_MANA) << "," //curmana
1167 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1168 << GetDefaultMovementType() << ")"; //default movement generator type
1170 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1172 WorldDatabase.CommitTransaction();
1175 void Creature::SelectLevel(const CreatureInfo *cinfo)
1177 uint32 rank = isPet()? 0 : cinfo->rank;
1179 // level
1180 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1181 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1182 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1183 SetLevel(level);
1185 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1187 // health
1188 float healthmod = _GetHealthMod(rank);
1190 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1191 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1192 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1194 SetCreateHealth(health);
1195 SetMaxHealth(health);
1196 SetHealth(health);
1198 // mana
1199 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1200 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1201 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1203 SetCreateMana(mana);
1204 SetMaxPower(POWER_MANA, mana); //MAX Mana
1205 SetPower(POWER_MANA, mana);
1207 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1208 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1210 // damage
1211 float damagemod = _GetDamageMod(rank);
1213 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1214 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1216 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1217 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1219 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1222 float Creature::_GetHealthMod(int32 Rank)
1224 switch (Rank) // define rates for each elite rank
1226 case CREATURE_ELITE_NORMAL:
1227 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1228 case CREATURE_ELITE_ELITE:
1229 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1230 case CREATURE_ELITE_RAREELITE:
1231 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1232 case CREATURE_ELITE_WORLDBOSS:
1233 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1234 case CREATURE_ELITE_RARE:
1235 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1236 default:
1237 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1241 float Creature::_GetDamageMod(int32 Rank)
1243 switch (Rank) // define rates for each elite rank
1245 case CREATURE_ELITE_NORMAL:
1246 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1247 case CREATURE_ELITE_ELITE:
1248 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1249 case CREATURE_ELITE_RAREELITE:
1250 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1251 case CREATURE_ELITE_WORLDBOSS:
1252 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1253 case CREATURE_ELITE_RARE:
1254 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1255 default:
1256 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1260 float Creature::GetSpellDamageMod(int32 Rank)
1262 switch (Rank) // define rates for each elite rank
1264 case CREATURE_ELITE_NORMAL:
1265 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1266 case CREATURE_ELITE_ELITE:
1267 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1268 case CREATURE_ELITE_RAREELITE:
1269 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1270 case CREATURE_ELITE_WORLDBOSS:
1271 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1272 case CREATURE_ELITE_RARE:
1273 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1274 default:
1275 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1279 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1281 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1282 if(!cinfo)
1284 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1285 return false;
1287 m_originalEntry = Entry;
1289 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1291 if(!UpdateEntry(Entry, team, data))
1292 return false;
1294 //Notify the map's instance data.
1295 //Only works if you create the object in it, not if it is moves to that map.
1296 //Normally non-players do not teleport to other maps.
1297 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1298 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1300 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
1303 return true;
1306 bool Creature::LoadFromDB(uint32 guid, Map *map)
1308 CreatureData const* data = objmgr.GetCreatureData(guid);
1310 if(!data)
1312 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1313 return false;
1316 m_DBTableGuid = guid;
1317 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1319 uint16 team = 0;
1320 if(!Create(guid,map,data->phaseMask,data->id,team,data))
1321 return false;
1323 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1325 if(!IsPositionValid())
1327 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1328 return false;
1331 m_respawnradius = data->spawndist;
1333 m_respawnDelay = data->spawntimesecs;
1334 m_isDeadByDefault = data->is_dead;
1335 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1337 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1338 if(m_respawnTime > time(NULL)) // not ready to respawn
1340 m_deathState = DEAD;
1341 if(canFly())
1343 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1344 if(data->posZ - tz > 0.1)
1345 Relocate(data->posX,data->posY,tz);
1348 else if(m_respawnTime) // respawn time set but expired
1350 m_respawnTime = 0;
1351 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1354 uint32 curhealth = data->curhealth;
1355 if(curhealth)
1357 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1358 if(curhealth < 1)
1359 curhealth = 1;
1362 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1363 SetPower(POWER_MANA,data->curmana);
1365 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1367 // checked at creature_template loading
1368 m_defaultMovementType = MovementGeneratorType(data->movementType);
1370 AIM_Initialize();
1371 return true;
1374 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1376 if(equip_entry == 0)
1378 if (force)
1380 for (uint8 i = 0; i < 3; ++i)
1381 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1382 m_equipmentId = 0;
1384 return;
1387 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1388 if (!einfo)
1389 return;
1391 m_equipmentId = equip_entry;
1392 for (uint8 i = 0; i < 3; ++i)
1393 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1396 bool Creature::hasQuest(uint32 quest_id) const
1398 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1399 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1401 if(itr->second==quest_id)
1402 return true;
1404 return false;
1407 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1409 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1410 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1412 if(itr->second==quest_id)
1413 return true;
1415 return false;
1418 void Creature::DeleteFromDB()
1420 if (!m_DBTableGuid)
1422 sLog.outDebug("Trying to delete not saved creature!");
1423 return;
1426 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1427 objmgr.DeleteCreatureData(m_DBTableGuid);
1429 WorldDatabase.BeginTransaction();
1430 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1431 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1432 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1433 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1434 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1435 WorldDatabase.CommitTransaction();
1438 float Creature::GetAttackDistance(Unit const* pl) const
1440 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1441 if(aggroRate==0)
1442 return 0.0f;
1444 int32 playerlevel = pl->getLevelForTarget(this);
1445 int32 creaturelevel = getLevelForTarget(pl);
1447 int32 leveldif = playerlevel - creaturelevel;
1449 // "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."
1450 if ( leveldif < - 25)
1451 leveldif = -25;
1453 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1454 float RetDistance = 20;
1456 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1457 // radius grow if playlevel < creaturelevel
1458 RetDistance -= (float)leveldif;
1460 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1462 // detect range auras
1463 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1465 // detected range auras
1466 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1469 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1470 if(RetDistance < 5)
1471 RetDistance = 5;
1473 return (RetDistance*aggroRate);
1476 void Creature::setDeathState(DeathState s)
1478 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1480 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1482 // always save boss respawn time at death to prevent crash cheating
1483 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1484 SaveRespawnTime();
1486 if (canFly() && FallGround())
1487 return;
1489 if(!IsStopped())
1490 StopMoving();
1492 Unit::setDeathState(s);
1494 if(s == JUST_DIED)
1496 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1497 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1499 if(!isPet() && GetCreatureInfo()->SkinLootId)
1500 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1501 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1503 if (canFly() && FallGround())
1504 return;
1506 SetNoSearchAssistance(false);
1507 Unit::setDeathState(CORPSE);
1509 if(s == JUST_ALIVED)
1511 SetHealth(GetMaxHealth());
1512 SetLootRecipient(NULL);
1513 Unit::setDeathState(ALIVE);
1514 CreatureInfo const *cinfo = GetCreatureInfo();
1515 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1516 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1517 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1518 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1519 clearUnitState(UNIT_STAT_ALL_STATE);
1520 i_motionMaster.Clear();
1521 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1522 LoadCreaturesAddon(true);
1526 bool Creature::FallGround()
1528 // Let's abort after we called this function one time
1529 if (getDeathState() == DEAD_FALLING)
1530 return false;
1532 // Let's do with no vmap because no way to get far distance with vmap high call
1533 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1535 // Abort too if the ground is very near
1536 if (fabs(GetPositionZ() - tz) < 0.1f)
1537 return false;
1539 Unit::setDeathState(DEAD_FALLING);
1540 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1541 Relocate(GetPositionX(), GetPositionY(), tz);
1542 return true;
1545 void Creature::Respawn()
1547 RemoveCorpse();
1549 // forced recreate creature object at clients
1550 UnitVisibility currentVis = GetVisibility();
1551 SetVisibility(VISIBILITY_RESPAWN);
1552 ObjectAccessor::UpdateObjectVisibility(this);
1553 SetVisibility(currentVis); // restore visibility state
1554 ObjectAccessor::UpdateObjectVisibility(this);
1556 if(getDeathState()==DEAD)
1558 if (m_DBTableGuid)
1559 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1560 m_respawnTime = time(NULL); // respawn at next tick
1564 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1566 if (!spellInfo)
1567 return false;
1569 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1570 return true;
1572 return Unit::IsImmunedToSpell(spellInfo);
1575 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1577 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1578 return true;
1580 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1583 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1585 if(!pVictim)
1586 return NULL;
1588 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1590 if(!m_spells[i])
1591 continue;
1592 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1593 if(!spellInfo)
1595 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1596 continue;
1599 bool bcontinue = true;
1600 for(uint32 j=0;j<3;j++)
1602 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1603 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1604 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1605 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1608 bcontinue = false;
1609 break;
1612 if(bcontinue) continue;
1614 if(spellInfo->manaCost > GetPower(POWER_MANA))
1615 continue;
1616 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1617 float range = GetSpellMaxRange(srange);
1618 float minrange = GetSpellMinRange(srange);
1620 float dist = GetCombatDistance(pVictim);
1622 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1623 // continue;
1624 if( dist > range || dist < minrange )
1625 continue;
1626 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1627 continue;
1628 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1629 continue;
1630 return spellInfo;
1632 return NULL;
1635 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1637 if(!pVictim)
1638 return NULL;
1640 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1642 if(!m_spells[i])
1643 continue;
1644 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1645 if(!spellInfo)
1647 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1648 continue;
1651 bool bcontinue = true;
1652 for(uint32 j=0;j<3;j++)
1654 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1656 bcontinue = false;
1657 break;
1660 if(bcontinue) continue;
1662 if(spellInfo->manaCost > GetPower(POWER_MANA))
1663 continue;
1664 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1665 float range = GetSpellMaxRange(srange);
1666 float minrange = GetSpellMinRange(srange);
1668 float dist = GetCombatDistance(pVictim);
1670 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1671 // continue;
1672 if( dist > range || dist < minrange )
1673 continue;
1674 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1675 continue;
1676 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1677 continue;
1678 return spellInfo;
1680 return NULL;
1683 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1685 // gamemaster in GM mode see all, including ghosts
1686 if(pl->isGameMaster())
1687 return true;
1689 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1690 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1692 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1693 return false;
1694 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1697 // Dead player see live creatures near own corpse
1698 if(isAlive())
1700 Corpse *corpse = pl->GetCorpse();
1701 if(corpse)
1703 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1704 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1705 return true;
1709 // Dead player see Spirit Healer or Spirit Guide
1710 if(isSpiritService())
1711 return true;
1713 // and not see any other
1714 return false;
1717 void Creature::CallAssistance()
1719 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1721 SetNoCallAssistance(true);
1723 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1724 if(radius > 0)
1726 std::list<Creature*> assistList;
1729 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1730 Cell cell(p);
1731 cell.data.Part.reserved = ALL_DISTRICT;
1732 cell.SetNoCreate();
1734 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1735 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1737 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1739 CellLock<GridReadGuard> cell_lock(cell, p);
1740 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1743 if (!assistList.empty())
1745 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1746 while (!assistList.empty())
1748 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1749 e->AddAssistant((*assistList.begin())->GetGUID());
1750 assistList.pop_front();
1752 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1758 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1760 // we don't need help from zombies :)
1761 if (!isAlive())
1762 return false;
1764 // skip fighting creature
1765 if (isInCombat())
1766 return false;
1768 // only free creature
1769 if (GetCharmerOrOwnerGUID())
1770 return false;
1772 // only from same creature faction
1773 if (checkfaction)
1775 if (getFaction() != u->getFaction())
1776 return false;
1778 else
1780 if (!IsFriendlyTo(u))
1781 return false;
1784 // skip non hostile to caster enemy creatures
1785 if (!IsHostileTo(enemy))
1786 return false;
1788 return true;
1791 void Creature::SaveRespawnTime()
1793 if(isPet() || !m_DBTableGuid)
1794 return;
1796 if(m_respawnTime > time(NULL)) // dead (no corpse)
1797 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1798 else if(m_deathTimer > 0) // dead (corpse)
1799 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/IN_MILISECONDS);
1802 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1804 if(!pVictim)
1805 return true;
1807 if(!pVictim->IsInMap(this))
1808 return true;
1810 if(!pVictim->isTargetableForAttack())
1811 return true;
1813 if(!pVictim->isInAccessablePlaceFor(this))
1814 return true;
1816 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1817 return false;
1819 float AttackDist = GetAttackDistance(pVictim);
1820 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1822 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1823 return !pVictim->IsWithinDist3d(CombatStartX,CombatStartY,CombatStartZ,
1824 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1827 CreatureDataAddon const* Creature::GetCreatureAddon() const
1829 if (m_DBTableGuid)
1831 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1832 return addon;
1835 // dependent from heroic mode entry
1836 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1839 //creature_addon table
1840 bool Creature::LoadCreaturesAddon(bool reload)
1842 CreatureDataAddon const *cainfo = GetCreatureAddon();
1843 if(!cainfo)
1844 return false;
1846 if (cainfo->mount != 0)
1847 Mount(cainfo->mount);
1849 if (cainfo->bytes0 != 0)
1850 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1852 if (cainfo->bytes1 != 0)
1853 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1855 if (cainfo->bytes2 != 0)
1856 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1858 if (cainfo->emote != 0)
1859 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1861 if (cainfo->move_flags != 0)
1862 SetUnitMovementFlags(cainfo->move_flags);
1864 if(cainfo->auras)
1866 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1868 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1869 if (!AdditionalSpellInfo)
1871 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1872 continue;
1875 // skip already applied aura
1876 if(HasAura(cAura->spell_id,cAura->effect_idx))
1878 if(!reload)
1879 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);
1881 continue;
1884 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1885 AddAura(AdditionalAura);
1886 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1889 return true;
1892 /// Send a message to LocalDefense channel for players opposition team in the zone
1893 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1895 uint32 enemy_team = attacker->GetTeam();
1897 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1898 data << (uint32)GetZoneId();
1899 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1902 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1904 m_CreatureSpellCooldowns[spell_id] = end_time;
1907 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1909 m_CreatureCategoryCooldowns[category] = apply_time;
1912 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1914 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1915 if(!spellInfo)
1916 return;
1918 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1919 if(cooldown)
1920 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1922 if(spellInfo->Category)
1923 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1925 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1928 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1930 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1931 if(!spellInfo)
1932 return false;
1934 // check global cooldown if spell affected by it
1935 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1936 return true;
1938 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1939 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1942 bool Creature::HasSpellCooldown(uint32 spell_id) const
1944 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1945 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1948 bool Creature::IsInEvadeMode() const
1950 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1953 bool Creature::HasSpell(uint32 spellID) const
1955 uint8 i;
1956 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1957 if(spellID == m_spells[i])
1958 break;
1959 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1962 time_t Creature::GetRespawnTimeEx() const
1964 time_t now = time(NULL);
1965 if(m_respawnTime > now) // dead (no corpse)
1966 return m_respawnTime;
1967 else if(m_deathTimer > 0) // dead (corpse)
1968 return now+m_respawnDelay+m_deathTimer/IN_MILISECONDS;
1969 else
1970 return now;
1973 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1975 if (m_DBTableGuid)
1977 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1979 x = data->posX;
1980 y = data->posY;
1981 z = data->posZ;
1982 if(ori)
1983 *ori = data->orientation;
1984 if(dist)
1985 *dist = data->spawndist;
1987 return;
1991 x = GetPositionX();
1992 y = GetPositionY();
1993 z = GetPositionZ();
1994 if(ori)
1995 *ori = GetOrientation();
1996 if(dist)
1997 *dist = 0;
2000 void Creature::AllLootRemovedFromCorpse()
2002 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
2004 uint32 nDeathTimer;
2006 CreatureInfo const *cinfo = GetCreatureInfo();
2008 // corpse was not skinnable -> apply corpse looted timer
2009 if (!cinfo || !cinfo->SkinLootId)
2010 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
2011 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
2012 else
2013 nDeathTimer = 0;
2015 // update death timer only if looted timer is shorter
2016 if (m_deathTimer > nDeathTimer)
2017 m_deathTimer = nDeathTimer;
2021 uint32 Creature::getLevelForTarget( Unit const* target ) const
2023 if(!isWorldBoss())
2024 return Unit::getLevelForTarget(target);
2026 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2027 if(level < 1)
2028 return 1;
2029 if(level > 255)
2030 return 255;
2031 return level;
2034 std::string Creature::GetAIName() const
2036 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
2039 std::string Creature::GetScriptName() const
2041 return objmgr.GetScriptName(GetScriptId());
2044 uint32 Creature::GetScriptId() const
2046 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2049 VendorItemData const* Creature::GetVendorItems() const
2051 return objmgr.GetNpcVendorItemList(GetEntry());
2054 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2056 if(!vItem->maxcount)
2057 return vItem->maxcount;
2059 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2060 for(; itr != m_vendorItemCounts.end(); ++itr)
2061 if(itr->itemId==vItem->item)
2062 break;
2064 if(itr == m_vendorItemCounts.end())
2065 return vItem->maxcount;
2067 VendorItemCount* vCount = &*itr;
2069 time_t ptime = time(NULL);
2071 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2073 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2075 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2076 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2078 m_vendorItemCounts.erase(itr);
2079 return vItem->maxcount;
2082 vCount->count += diff * pProto->BuyCount;
2083 vCount->lastIncrementTime = ptime;
2086 return vCount->count;
2089 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2091 if(!vItem->maxcount)
2092 return 0;
2094 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2095 for(; itr != m_vendorItemCounts.end(); ++itr)
2096 if(itr->itemId==vItem->item)
2097 break;
2099 if(itr == m_vendorItemCounts.end())
2101 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2102 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2103 return new_count;
2106 VendorItemCount* vCount = &*itr;
2108 time_t ptime = time(NULL);
2110 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2112 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2114 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2115 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2116 vCount->count += diff * pProto->BuyCount;
2117 else
2118 vCount->count = vItem->maxcount;
2121 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2122 vCount->lastIncrementTime = ptime;
2123 return vCount->count;
2126 TrainerSpellData const* Creature::GetTrainerSpells() const
2128 return objmgr.GetNpcTrainerSpells(GetEntry());
2131 // overwrite WorldObject function for proper name localization
2132 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2134 if (loc_idx >= 0)
2136 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2137 if (cl)
2139 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2140 return cl->Name[loc_idx].c_str();
2144 return GetName();
2147 void Creature::SetActiveObjectState( bool on )
2149 if(m_isActiveObject==on)
2150 return;
2152 bool world = IsInWorld();
2154 Map* map;
2155 if(world)
2157 map = GetMap();
2158 map->Remove(this,false);
2161 m_isActiveObject = on;
2163 if(world)
2164 map->Add(this);