Phase system development continue.
[getmangos.git] / src / game / Creature.cpp
blob25cf16b124ca96d09dd0e316e61cd85560b0e118
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 "WorldSession.h"
23 #include "World.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "Creature.h"
27 #include "QuestDef.h"
28 #include "GossipDef.h"
29 #include "Player.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 "SpellAuras.h"
38 #include "WaypointMovementGenerator.h"
39 #include "InstanceData.h"
40 #include "BattleGround.h"
41 #include "Util.h"
42 #include "GridNotifiers.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
46 // apply implementation of the singletons
47 #include "Policies/SingletonImp.h"
49 void TrainerSpellData::Clear()
51 for (TrainerSpellList::iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
52 delete (*itr);
53 spellList.empty();
56 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
58 for(TrainerSpellList::const_iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
59 if((*itr)->spell == spell_id)
60 return *itr;
62 return NULL;
65 bool VendorItemData::RemoveItem( uint32 item_id )
67 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
69 if((*i)->item==item_id)
71 m_items.erase(i);
72 return true;
75 return false;
78 size_t VendorItemData::FindItemSlot(uint32 item_id) const
80 for(size_t i = 0; i < m_items.size(); ++i )
81 if(m_items[i]->item==item_id)
82 return i;
83 return m_items.size();
86 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
88 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
89 if((*i)->item==item_id)
90 return *i;
91 return NULL;
94 bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
96 Unit* victim = Unit::GetUnit(m_owner, m_victim);
97 if (victim)
99 while (!m_assistants.empty())
101 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
102 m_assistants.pop_front();
104 if (assistant && assistant->CanAssistTo(&m_owner, victim))
106 assistant->SetNoCallAssistance(true);
107 if(assistant->AI())
108 assistant->AI()->AttackStart(victim);
112 return true;
115 Creature::Creature() :
116 Unit(), i_AI(NULL),
117 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
118 m_lootMoney(0), m_lootRecipient(0),
119 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
120 m_gossipOptionLoaded(false), m_emoteState(0), m_isPet(false), m_isTotem(false), m_isVehicle(false),
121 m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
122 m_AlreadyCallAssistance(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
123 m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),m_creatureInfo(NULL), m_DBTableGuid(0)
125 m_regenTimer = 200;
126 m_valuesCount = UNIT_END;
128 for(int i =0; i<4; ++i)
129 m_spells[i] = 0;
131 m_CreatureSpellCooldowns.clear();
132 m_CreatureCategoryCooldowns.clear();
133 m_GlobalCooldown = 0;
134 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
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()) ObjectAccessor::Instance().AddObject(this);
151 Unit::AddToWorld();
154 void Creature::RemoveFromWorld()
156 ///- Remove the creature from the accessor
157 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
158 Unit::RemoveFromWorld();
161 void Creature::RemoveCorpse()
163 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
164 return;
166 m_deathTimer = 0;
167 setDeathState(DEAD);
168 ObjectAccessor::UpdateObjectVisibility(this);
169 loot.clear();
170 m_respawnTime = time(NULL) + m_respawnDelay;
172 float x,y,z,o;
173 GetRespawnCoord(x, y, z, &o);
174 GetMap()->CreatureRelocation(this,x,y,z,o);
178 * change the entry of creature until respawn
180 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
182 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
183 if(!normalInfo)
185 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
186 return false;
189 // get heroic mode entry
190 uint32 actualEntry = Entry;
191 CreatureInfo const *cinfo = normalInfo;
192 if(normalInfo->HeroicEntry)
194 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
195 if(map && map->IsHeroic())
197 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
198 if(!cinfo)
200 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
201 return false;
206 SetEntry(Entry); // normal entry always
207 m_creatureInfo = cinfo; // map mode related always
209 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
211 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
212 return false;
215 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
216 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
217 if (!minfo)
219 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
220 return false;
222 else
223 display_id = minfo->modelid; // it can be different (for another gender)
225 SetDisplayId(display_id);
226 SetNativeDisplayId(display_id);
227 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
229 // Load creature equipment
230 if(!data || data->equipmentId == 0)
231 { // use default from the template
232 LoadEquipment(cinfo->equipmentId);
234 else if(data && data->equipmentId != -1)
235 { // override, -1 means no equipment
236 LoadEquipment(data->equipmentId);
239 SetName(normalInfo->Name); // at normal entry always
241 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
242 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
244 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
246 SetSpeed(MOVE_WALK, cinfo->speed );
247 SetSpeed(MOVE_RUN, cinfo->speed );
248 SetSpeed(MOVE_SWIM, cinfo->speed );
250 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
252 // checked at loading
253 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
254 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
255 m_defaultMovementType = IDLE_MOTION_TYPE;
257 return true;
260 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
262 if(!InitEntry(Entry,team,data))
263 return false;
265 m_regenHealth = GetCreatureInfo()->RegenHealth;
267 // creatures always have melee weapon ready if any
268 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
270 SelectLevel(GetCreatureInfo());
271 if (team == HORDE)
272 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
273 else
274 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
276 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
278 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
279 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
280 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
282 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
283 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
285 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
286 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
287 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
288 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
289 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
290 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
291 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
293 SetCanModifyStats(true);
294 UpdateAllStats();
296 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
297 if (factionTemplate) // check and error show at loading templates
299 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
300 if (factionEntry)
301 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
302 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
303 SetPvP(true);
306 m_spells[0] = GetCreatureInfo()->spell1;
307 m_spells[1] = GetCreatureInfo()->spell2;
308 m_spells[2] = GetCreatureInfo()->spell3;
309 m_spells[3] = GetCreatureInfo()->spell4;
311 return true;
314 void Creature::Update(uint32 diff)
316 if(m_GlobalCooldown <= diff)
317 m_GlobalCooldown = 0;
318 else
319 m_GlobalCooldown -= diff;
321 switch( m_deathState )
323 case JUST_ALIVED:
324 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
325 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
326 break;
327 case JUST_DIED:
328 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
329 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
330 break;
331 case DEAD:
333 if( m_respawnTime <= time(NULL) )
335 DEBUG_LOG("Respawning...");
336 m_respawnTime = 0;
337 lootForPickPocketed = false;
338 lootForBody = false;
340 if(m_originalEntry != GetEntry())
341 UpdateEntry(m_originalEntry);
343 CreatureInfo const *cinfo = GetCreatureInfo();
345 SelectLevel(cinfo);
346 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
347 if (m_isDeadByDefault)
349 setDeathState(JUST_DIED);
350 SetHealth(0);
351 i_motionMaster.Clear();
352 clearUnitState(UNIT_STAT_ALL_STATE);
353 LoadCreaturesAddon(true);
355 else
356 setDeathState( JUST_ALIVED );
358 //Call AI respawn virtual function
359 i_AI->JustRespawned();
361 GetMap()->Add(this);
363 break;
365 case CORPSE:
367 if (m_isDeadByDefault)
368 break;
370 if( m_deathTimer <= diff )
372 RemoveCorpse();
373 DEBUG_LOG("Removing corpse... %u ", GetEntry());
375 else
377 m_deathTimer -= diff;
378 if (m_groupLootTimer && lootingGroupLeaderGUID)
380 if(diff <= m_groupLootTimer)
382 m_groupLootTimer -= diff;
384 else
386 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
387 if (group)
388 group->EndRoll();
389 m_groupLootTimer = 0;
390 lootingGroupLeaderGUID = 0;
395 break;
397 case ALIVE:
399 if (m_isDeadByDefault)
401 if( m_deathTimer <= diff )
403 RemoveCorpse();
404 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
406 else
408 m_deathTimer -= diff;
412 Unit::Update( diff );
414 // creature can be dead after Unit::Update call
415 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
416 if(!isAlive())
417 break;
419 if(!IsInEvadeMode())
421 // do not allow the AI to be changed during update
422 m_AI_locked = true;
423 i_AI->UpdateAI(diff);
424 m_AI_locked = false;
427 // creature can be dead after UpdateAI call
428 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
429 if(!isAlive())
430 break;
431 if(m_regenTimer > 0)
433 if(diff >= m_regenTimer)
434 m_regenTimer = 0;
435 else
436 m_regenTimer -= diff;
438 if (m_regenTimer != 0)
439 break;
441 if (!isInCombat() || IsPolymorphed())
442 RegenerateHealth();
444 RegenerateMana();
446 m_regenTimer = 2000;
447 break;
449 case DEAD_FALLING:
451 if (!FallGround())
452 setDeathState(JUST_DIED);
454 default:
455 break;
459 void Creature::RegenerateMana()
461 uint32 curValue = GetPower(POWER_MANA);
462 uint32 maxValue = GetMaxPower(POWER_MANA);
464 if (curValue >= maxValue)
465 return;
467 uint32 addvalue = 0;
469 // Combat and any controlled creature
470 if (isInCombat() || GetCharmerOrOwnerGUID())
472 if(!IsUnderLastManaUseEffect())
474 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
475 float Spirit = GetStat(STAT_SPIRIT);
477 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
480 else
481 addvalue = maxValue/3;
483 ModifyPower(POWER_MANA, addvalue);
486 void Creature::RegenerateHealth()
488 if (!isRegeneratingHealth())
489 return;
491 uint32 curValue = GetHealth();
492 uint32 maxValue = GetMaxHealth();
494 if (curValue >= maxValue)
495 return;
497 uint32 addvalue = 0;
499 // Not only pet, but any controlled creature
500 if(GetCharmerOrOwnerGUID())
502 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
503 float Spirit = GetStat(STAT_SPIRIT);
505 if( GetPower(POWER_MANA) > 0 )
506 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
507 else
508 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
510 else
511 addvalue = maxValue/3;
513 ModifyHealth(addvalue);
516 bool Creature::AIM_Initialize()
518 // make sure nothing can change the AI during AI update
519 if(m_AI_locked)
521 sLog.outDebug("AIM_Initialize: failed to init, locked.");
522 return false;
525 CreatureAI * oldAI = i_AI;
526 i_motionMaster.Initialize();
527 i_AI = FactorySelector::selectAI(this);
528 if (oldAI)
529 delete oldAI;
530 return true;
533 bool Creature::Create (uint32 guidlow, Map *map, uint32 Entry, uint32 team, const CreatureData *data)
535 SetMapId(map->GetId());
536 SetInstanceId(map->GetInstanceId());
538 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
539 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
541 if (bResult)
543 switch (GetCreatureInfo()->rank)
545 case CREATURE_ELITE_RARE:
546 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
547 break;
548 case CREATURE_ELITE_ELITE:
549 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
550 break;
551 case CREATURE_ELITE_RAREELITE:
552 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
553 break;
554 case CREATURE_ELITE_WORLDBOSS:
555 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
556 break;
557 default:
558 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
559 break;
561 LoadCreaturesAddon();
564 return bResult;
567 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
569 if(!isTrainer())
570 return false;
572 TrainerSpellData const* trainer_spells = GetTrainerSpells();
574 if(!trainer_spells || trainer_spells->spellList.empty())
576 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
577 GetGUIDLow(),GetEntry());
578 return false;
581 switch(GetCreatureInfo()->trainer_type)
583 case TRAINER_TYPE_CLASS:
584 if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
586 if(msg)
588 pPlayer->PlayerTalkClass->ClearMenus();
589 switch(GetCreatureInfo()->classNum)
591 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
592 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
593 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
594 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
595 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
596 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
597 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
598 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
599 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
602 return false;
604 break;
605 case TRAINER_TYPE_PETS:
606 if(pPlayer->getClass()!=CLASS_HUNTER)
608 pPlayer->PlayerTalkClass->ClearMenus();
609 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
610 return false;
612 break;
613 case TRAINER_TYPE_MOUNTS:
614 if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
616 if(msg)
618 pPlayer->PlayerTalkClass->ClearMenus();
619 switch(GetCreatureInfo()->classNum)
621 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
622 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
623 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
624 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
625 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
626 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
627 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
628 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
629 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
630 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
633 return false;
635 break;
636 case TRAINER_TYPE_TRADESKILLS:
637 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
639 if(msg)
641 pPlayer->PlayerTalkClass->ClearMenus();
642 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
644 return false;
646 break;
647 default:
648 return false; // checked and error output at creature_template loading
650 return true;
653 bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
655 if(!isBattleMaster())
656 return false;
658 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
659 if(!msg)
660 return pPlayer->GetBGAccessByLevel(bgTypeId);
662 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
664 pPlayer->PlayerTalkClass->ClearMenus();
665 switch(bgTypeId)
667 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
668 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
669 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
670 case BATTLEGROUND_EY:
671 case BATTLEGROUND_NA:
672 case BATTLEGROUND_BE:
673 case BATTLEGROUND_AA:
674 case BATTLEGROUND_RL:
675 case BATTLEGROUND_SA:
676 case BATTLEGROUND_DS:
677 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
678 default: break;
680 return false;
682 return true;
685 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
687 return pPlayer->getLevel() >= 10
688 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
689 && pPlayer->getClass() == GetCreatureInfo()->classNum;
692 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
694 PlayerMenu* pm=pPlayer->PlayerTalkClass;
695 pm->ClearMenus();
697 // lazy loading single time at use
698 LoadGossipOptions();
700 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
702 GossipOption* gso=&*i;
703 if(gso->GossipId == gossipid)
705 bool cantalking=true;
706 if(gso->Id==1)
708 uint32 textid=GetNpcTextId();
709 GossipText * gossiptext=objmgr.GetGossipText(textid);
710 if(!gossiptext)
711 cantalking=false;
713 else
715 switch (gso->Action)
717 case GOSSIP_OPTION_QUESTGIVER:
718 pPlayer->PrepareQuestMenu(GetGUID());
719 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
720 cantalking=false;
721 //pm->GetQuestMenu()->ClearMenu();
722 break;
723 case GOSSIP_OPTION_ARMORER:
724 cantalking=false; // added in special mode
725 break;
726 case GOSSIP_OPTION_SPIRITHEALER:
727 if( !pPlayer->isDead() )
728 cantalking=false;
729 break;
730 case GOSSIP_OPTION_VENDOR:
732 VendorItemData const* vItems = GetVendorItems();
733 if(!vItems || vItems->Empty())
735 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
736 GetGUIDLow(),GetEntry());
737 cantalking=false;
739 break;
741 case GOSSIP_OPTION_TRAINER:
742 if(!isCanTrainingOf(pPlayer,false))
743 cantalking=false;
744 break;
745 case GOSSIP_OPTION_UNLEARNTALENTS:
746 if(!isCanTrainingAndResetTalentsOf(pPlayer))
747 cantalking=false;
748 break;
749 case GOSSIP_OPTION_UNLEARNPETSKILLS:
750 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
751 cantalking=false;
752 break;
753 case GOSSIP_OPTION_TAXIVENDOR:
754 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
755 return;
756 break;
757 case GOSSIP_OPTION_BATTLEFIELD:
758 if(!isCanIneractWithBattleMaster(pPlayer,false))
759 cantalking=false;
760 break;
761 case GOSSIP_OPTION_SPIRITGUIDE:
762 case GOSSIP_OPTION_INNKEEPER:
763 case GOSSIP_OPTION_BANKER:
764 case GOSSIP_OPTION_PETITIONER:
765 case GOSSIP_OPTION_STABLEPET:
766 case GOSSIP_OPTION_TABARDDESIGNER:
767 case GOSSIP_OPTION_AUCTIONEER:
768 break; // no checks
769 default:
770 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
771 break;
775 //note for future dev: should have database fields for BoxMessage & BoxMoney
776 if(!gso->OptionText.empty() && cantalking)
778 std::string OptionText = gso->OptionText;
779 std::string BoxText = gso->BoxText;
780 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
781 if (loc_idx >= 0)
783 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
784 if (no)
786 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
787 OptionText=no->OptionText[loc_idx];
788 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
789 BoxText=no->BoxText[loc_idx];
792 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
797 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
798 if(pm->Empty())
800 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
802 isCanTrainingOf(pPlayer,true); // output error message if need
804 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
806 isCanIneractWithBattleMaster(pPlayer,true); // output error message if need
811 void Creature::sendPreparedGossip(Player* player)
813 if(!player)
814 return;
816 // in case empty gossip menu open quest menu if any
817 if (player->PlayerTalkClass->GetGossipMenu().Empty() && !player->PlayerTalkClass->GetQuestMenu().Empty())
819 player->SendPreparedQuest(GetGUID());
820 return;
823 // in case non empty gossip menu (that not included quests list size) show it
824 // (quest entries from quest menu will be included in list)
825 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
828 void Creature::OnGossipSelect(Player* player, uint32 option)
830 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
832 if(option >= gossipmenu.MenuItemCount())
833 return;
835 uint32 action=gossipmenu.GetItem(option).m_gAction;
836 uint32 zoneid=GetZoneId();
837 uint64 guid=GetGUID();
839 GossipOption const *gossip=GetGossipOption( action );
840 if(!gossip)
842 zoneid=0;
843 gossip=GetGossipOption( action );
844 if(!gossip)
845 return;
848 switch (gossip->Action)
850 case GOSSIP_OPTION_GOSSIP:
852 uint32 textid = GetGossipTextId(action, zoneid);
853 if (textid == 0)
854 textid=GetNpcTextId();
856 player->PlayerTalkClass->CloseGossip();
857 player->PlayerTalkClass->SendTalking(textid);
858 break;
860 case GOSSIP_OPTION_SPIRITHEALER:
861 if (player->isDead())
862 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
863 break;
864 case GOSSIP_OPTION_QUESTGIVER:
865 player->PrepareQuestMenu( guid );
866 player->SendPreparedQuest( guid );
867 break;
868 case GOSSIP_OPTION_VENDOR:
869 case GOSSIP_OPTION_ARMORER:
870 player->GetSession()->SendListInventory(guid);
871 break;
872 case GOSSIP_OPTION_STABLEPET:
873 player->GetSession()->SendStablePet(guid);
874 break;
875 case GOSSIP_OPTION_TRAINER:
876 player->GetSession()->SendTrainerList(guid);
877 break;
878 case GOSSIP_OPTION_UNLEARNTALENTS:
879 player->PlayerTalkClass->CloseGossip();
880 player->SendTalentWipeConfirm(guid);
881 break;
882 case GOSSIP_OPTION_UNLEARNPETSKILLS:
883 player->PlayerTalkClass->CloseGossip();
884 player->SendPetSkillWipeConfirm();
885 break;
886 case GOSSIP_OPTION_TAXIVENDOR:
887 player->GetSession()->SendTaxiMenu(this);
888 break;
889 case GOSSIP_OPTION_INNKEEPER:
890 player->PlayerTalkClass->CloseGossip();
891 player->SetBindPoint( guid );
892 break;
893 case GOSSIP_OPTION_BANKER:
894 player->GetSession()->SendShowBank( guid );
895 break;
896 case GOSSIP_OPTION_PETITIONER:
897 player->PlayerTalkClass->CloseGossip();
898 player->GetSession()->SendPetitionShowList( guid );
899 break;
900 case GOSSIP_OPTION_TABARDDESIGNER:
901 player->PlayerTalkClass->CloseGossip();
902 player->GetSession()->SendTabardVendorActivate( guid );
903 break;
904 case GOSSIP_OPTION_AUCTIONEER:
905 player->GetSession()->SendAuctionHello( guid, this );
906 break;
907 case GOSSIP_OPTION_SPIRITGUIDE:
908 case GOSSIP_GUARD_SPELLTRAINER:
909 case GOSSIP_GUARD_SKILLTRAINER:
910 prepareGossipMenu( player,gossip->Id );
911 sendPreparedGossip( player );
912 break;
913 case GOSSIP_OPTION_BATTLEFIELD:
915 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
916 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
917 break;
919 default:
920 OnPoiSelect( player, gossip );
921 break;
926 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
928 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
930 Poi_Icon icon = ICON_POI_0;
931 //need add more case.
932 switch(gossip->Action)
934 case GOSSIP_GUARD_BANK:
935 icon=ICON_POI_HOUSE;
936 break;
937 case GOSSIP_GUARD_RIDE:
938 icon=ICON_POI_RWHORSE;
939 break;
940 case GOSSIP_GUARD_GUILD:
941 icon=ICON_POI_BLUETOWER;
942 break;
943 default:
944 icon=ICON_POI_TOWER;
945 break;
947 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
948 player->PlayerTalkClass->SendTalking(textid);
949 // std::string areaname= gossip->OptionText;
950 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
954 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
956 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
958 if(!result)
959 return 0;
961 Field *fields = result->Fetch();
962 uint32 id = fields[0].GetUInt32();
964 delete result;
966 return id;
969 uint32 Creature::GetNpcTextId()
971 if (!m_DBTableGuid)
972 return DEFAULT_GOSSIP_MESSAGE;
974 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
975 return pos;
977 return DEFAULT_GOSSIP_MESSAGE;
980 GossipOption const* Creature::GetGossipOption( uint32 id ) const
982 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
984 if(i->Action==id )
985 return &*i;
987 return NULL;
990 void Creature::LoadGossipOptions()
992 if(m_gossipOptionLoaded)
993 return;
995 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
997 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
998 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
999 if(i->NpcFlag & npcflags)
1000 addGossipOption(*i);
1002 m_gossipOptionLoaded = true;
1005 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1007 /* uint32 timeElap = getMSTime();
1008 if ((timeElap - m_startMove) < m_moveTime)
1010 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1011 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1013 else
1015 oX = dX;
1016 oY = dY;
1019 dX = x;
1020 dY = y;
1021 m_orientation = atan2((oY - dY), (oX - dX));
1023 m_startMove = getMSTime();
1024 m_moveTime = time;*/
1025 SendMonsterMove(x, y, z, type, MovementFlags, time);
1028 Player *Creature::GetLootRecipient() const
1030 if (!m_lootRecipient) return NULL;
1031 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1034 void Creature::SetLootRecipient(Unit *unit)
1036 // set the player whose group should receive the right
1037 // to loot the creature after it dies
1038 // should be set to NULL after the loot disappears
1040 if (!unit)
1042 m_lootRecipient = 0;
1043 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1044 return;
1047 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1048 if(!player) // normal creature, no player involved
1049 return;
1051 m_lootRecipient = player->GetGUID();
1052 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1055 void Creature::SaveToDB()
1057 // this should only be used when the creature has already been loaded
1058 // preferably after adding to map, because mapid may not be valid otherwise
1059 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1060 if(!data)
1062 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1063 return;
1066 SaveToDB(GetMapId(), data->spawnMask);
1069 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1071 // update in loaded data
1072 if (!m_DBTableGuid)
1073 m_DBTableGuid = GetGUIDLow();
1074 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1076 uint32 displayId = GetNativeDisplayId();
1078 // check if it's a custom model and if not, use 0 for displayId
1079 CreatureInfo const *cinfo = GetCreatureInfo();
1080 if(cinfo)
1082 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1084 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1085 if(!minfo || displayId != minfo->modelid_other_gender)
1087 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1088 if(minfo && displayId == minfo->modelid_other_gender)
1089 displayId = 0;
1091 else
1092 displayId = 0;
1094 else
1095 displayId = 0;
1098 // data->guid = guid don't must be update at save
1099 data.id = GetEntry();
1100 data.mapid = mapid;
1101 data.displayid = displayId;
1102 data.equipmentId = GetEquipmentId();
1103 data.posX = GetPositionX();
1104 data.posY = GetPositionY();
1105 data.posZ = GetPositionZ();
1106 data.orientation = GetOrientation();
1107 data.spawntimesecs = m_respawnDelay;
1108 // prevent add data integrity problems
1109 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1110 data.currentwaypoint = 0;
1111 data.curhealth = GetHealth();
1112 data.curmana = GetPower(POWER_MANA);
1113 data.is_dead = m_isDeadByDefault;
1114 // prevent add data integrity problems
1115 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1116 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1117 data.spawnMask = spawnMask;
1119 // updated in DB
1120 WorldDatabase.BeginTransaction();
1122 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1124 std::ostringstream ss;
1125 ss << "INSERT INTO creature VALUES ("
1126 << m_DBTableGuid << ","
1127 << GetEntry() << ","
1128 << mapid <<","
1129 << (uint32)spawnMask << ","
1130 << displayId <<","
1131 << GetEquipmentId() <<","
1132 << GetPositionX() << ","
1133 << GetPositionY() << ","
1134 << GetPositionZ() << ","
1135 << GetOrientation() << ","
1136 << m_respawnDelay << "," //respawn time
1137 << (float) m_respawnradius << "," //spawn distance (float)
1138 << (uint32) (0) << "," //currentwaypoint
1139 << GetHealth() << "," //curhealth
1140 << GetPower(POWER_MANA) << "," //curmana
1141 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1142 << GetDefaultMovementType() << ")"; //default movement generator type
1144 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1146 WorldDatabase.CommitTransaction();
1149 void Creature::SelectLevel(const CreatureInfo *cinfo)
1151 uint32 rank = isPet()? 0 : cinfo->rank;
1153 // level
1154 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1155 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1156 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1157 SetLevel(level);
1159 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1161 // health
1162 float healthmod = _GetHealthMod(rank);
1164 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1165 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1166 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1168 SetCreateHealth(health);
1169 SetMaxHealth(health);
1170 SetHealth(health);
1172 // mana
1173 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1174 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1175 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1177 SetCreateMana(mana);
1178 SetMaxPower(POWER_MANA, mana); //MAX Mana
1179 SetPower(POWER_MANA, mana);
1181 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1182 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1184 // damage
1185 float damagemod = _GetDamageMod(rank);
1187 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1188 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1190 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1191 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1193 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1196 float Creature::_GetHealthMod(int32 Rank)
1198 switch (Rank) // define rates for each elite rank
1200 case CREATURE_ELITE_NORMAL:
1201 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1202 case CREATURE_ELITE_ELITE:
1203 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1204 case CREATURE_ELITE_RAREELITE:
1205 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1206 case CREATURE_ELITE_WORLDBOSS:
1207 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1208 case CREATURE_ELITE_RARE:
1209 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1210 default:
1211 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1215 float Creature::_GetDamageMod(int32 Rank)
1217 switch (Rank) // define rates for each elite rank
1219 case CREATURE_ELITE_NORMAL:
1220 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1221 case CREATURE_ELITE_ELITE:
1222 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1223 case CREATURE_ELITE_RAREELITE:
1224 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1225 case CREATURE_ELITE_WORLDBOSS:
1226 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1227 case CREATURE_ELITE_RARE:
1228 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1229 default:
1230 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1234 float Creature::GetSpellDamageMod(int32 Rank)
1236 switch (Rank) // define rates for each elite rank
1238 case CREATURE_ELITE_NORMAL:
1239 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1240 case CREATURE_ELITE_ELITE:
1241 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1242 case CREATURE_ELITE_RAREELITE:
1243 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1244 case CREATURE_ELITE_WORLDBOSS:
1245 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1246 case CREATURE_ELITE_RARE:
1247 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1248 default:
1249 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1253 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1255 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1256 if(!cinfo)
1258 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1259 return false;
1261 m_originalEntry = Entry;
1263 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1265 if(!UpdateEntry(Entry, team, data))
1266 return false;
1268 //Notify the map's instance data.
1269 //Only works if you create the object in it, not if it is moves to that map.
1270 //Normally non-players do not teleport to other maps.
1271 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1272 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1274 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1277 return true;
1280 bool Creature::LoadFromDB(uint32 guid, Map *map)
1282 CreatureData const* data = objmgr.GetCreatureData(guid);
1284 if(!data)
1286 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1287 return false;
1290 m_DBTableGuid = guid;
1291 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1293 uint16 team = 0;
1294 if(!Create(guid,map,data->id,team,data))
1295 return false;
1297 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1299 if(!IsPositionValid())
1301 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1302 return false;
1305 m_respawnradius = data->spawndist;
1307 m_respawnDelay = data->spawntimesecs;
1308 m_isDeadByDefault = data->is_dead;
1309 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1311 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1312 if(m_respawnTime > time(NULL)) // not ready to respawn
1314 m_deathState = DEAD;
1315 if(canFly())
1317 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1318 if(data->posZ - tz > 0.1)
1319 Relocate(data->posX,data->posY,tz);
1322 else if(m_respawnTime) // respawn time set but expired
1324 m_respawnTime = 0;
1325 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1328 uint32 curhealth = data->curhealth;
1329 if(curhealth)
1331 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1332 if(curhealth < 1)
1333 curhealth = 1;
1336 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1337 SetPower(POWER_MANA,data->curmana);
1339 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1341 // checked at creature_template loading
1342 m_defaultMovementType = MovementGeneratorType(data->movementType);
1344 AIM_Initialize();
1345 return true;
1348 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1350 if(equip_entry == 0)
1352 if (force)
1354 for (uint8 i = 0; i < 3; i++)
1355 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1356 m_equipmentId = 0;
1358 return;
1361 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1362 if (!einfo)
1363 return;
1365 m_equipmentId = equip_entry;
1366 for (uint8 i = 0; i < 3; i++)
1367 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1370 bool Creature::hasQuest(uint32 quest_id) const
1372 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1373 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1375 if(itr->second==quest_id)
1376 return true;
1378 return false;
1381 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1383 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1384 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1386 if(itr->second==quest_id)
1387 return true;
1389 return false;
1392 void Creature::DeleteFromDB()
1394 if (!m_DBTableGuid)
1396 sLog.outDebug("Trying to delete not saved creature!");
1397 return;
1400 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1401 objmgr.DeleteCreatureData(m_DBTableGuid);
1403 WorldDatabase.BeginTransaction();
1404 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1405 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1406 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1407 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1408 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1409 WorldDatabase.CommitTransaction();
1412 float Creature::GetAttackDistance(Unit const* pl) const
1414 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1415 if(aggroRate==0)
1416 return 0.0f;
1418 int32 playerlevel = pl->getLevelForTarget(this);
1419 int32 creaturelevel = getLevelForTarget(pl);
1421 int32 leveldif = playerlevel - creaturelevel;
1423 // "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."
1424 if ( leveldif < - 25)
1425 leveldif = -25;
1427 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1428 float RetDistance = 20;
1430 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1431 // radius grow if playlevel < creaturelevel
1432 RetDistance -= (float)leveldif;
1434 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1436 // detect range auras
1437 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1439 // detected range auras
1440 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1443 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1444 if(RetDistance < 5)
1445 RetDistance = 5;
1447 return (RetDistance*aggroRate);
1450 void Creature::setDeathState(DeathState s)
1452 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1454 m_deathTimer = m_corpseDelay*1000;
1456 // always save boss respawn time at death to prevent crash cheating
1457 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1458 SaveRespawnTime();
1460 if (canFly() && FallGround())
1461 return;
1463 if(!IsStopped())
1464 StopMoving();
1466 Unit::setDeathState(s);
1468 if(s == JUST_DIED)
1470 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1471 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1473 if(!isPet() && GetCreatureInfo()->SkinLootId)
1474 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1475 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1477 if (canFly() && FallGround())
1478 return;
1480 Unit::setDeathState(CORPSE);
1482 if(s == JUST_ALIVED)
1484 SetHealth(GetMaxHealth());
1485 SetLootRecipient(NULL);
1486 Unit::setDeathState(ALIVE);
1487 CreatureInfo const *cinfo = GetCreatureInfo();
1488 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1489 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1490 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1491 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1492 clearUnitState(UNIT_STAT_ALL_STATE);
1493 i_motionMaster.Clear();
1494 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1495 LoadCreaturesAddon(true);
1499 bool Creature::FallGround()
1501 // Let's abort after we called this function one time
1502 if (getDeathState() == DEAD_FALLING)
1503 return false;
1505 // Let's do with no vmap because no way to get far distance with vmap high call
1506 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1508 // Abort too if the ground is very near
1509 if (fabs(GetPositionZ() - tz) < 0.1f)
1510 return false;
1512 Unit::setDeathState(DEAD_FALLING);
1513 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1514 Relocate(GetPositionX(), GetPositionY(), tz);
1515 return true;
1518 void Creature::Respawn()
1520 RemoveCorpse();
1522 // forced recreate creature object at clients
1523 UnitVisibility currentVis = GetVisibility();
1524 SetVisibility(VISIBILITY_RESPAWN);
1525 ObjectAccessor::UpdateObjectVisibility(this);
1526 SetVisibility(currentVis); // restore visibility state
1527 ObjectAccessor::UpdateObjectVisibility(this);
1529 if(getDeathState()==DEAD)
1531 if (m_DBTableGuid)
1532 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1533 m_respawnTime = time(NULL); // respawn at next tick
1537 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1539 if (!spellInfo)
1540 return false;
1542 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1543 return true;
1545 return Unit::IsImmunedToSpell(spellInfo);
1548 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1550 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1551 return true;
1553 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1556 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1558 if(!pVictim)
1559 return NULL;
1561 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1563 if(!m_spells[i])
1564 continue;
1565 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1566 if(!spellInfo)
1568 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1569 continue;
1572 bool bcontinue = true;
1573 for(uint32 j=0;j<3;j++)
1575 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1576 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1577 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1578 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1581 bcontinue = false;
1582 break;
1585 if(bcontinue) continue;
1587 if(spellInfo->manaCost > GetPower(POWER_MANA))
1588 continue;
1589 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1590 float range = GetSpellMaxRange(srange);
1591 float minrange = GetSpellMinRange(srange);
1592 float dist = GetDistance(pVictim);
1593 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1594 // continue;
1595 if( dist > range || dist < minrange )
1596 continue;
1597 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1598 continue;
1599 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1600 continue;
1601 return spellInfo;
1603 return NULL;
1606 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1608 if(!pVictim)
1609 return NULL;
1611 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1613 if(!m_spells[i])
1614 continue;
1615 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1616 if(!spellInfo)
1618 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1619 continue;
1622 bool bcontinue = true;
1623 for(uint32 j=0;j<3;j++)
1625 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1627 bcontinue = false;
1628 break;
1631 if(bcontinue) continue;
1633 if(spellInfo->manaCost > GetPower(POWER_MANA))
1634 continue;
1635 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1636 float range = GetSpellMaxRange(srange);
1637 float minrange = GetSpellMinRange(srange);
1638 float dist = GetDistance(pVictim);
1639 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1640 // continue;
1641 if( dist > range || dist < minrange )
1642 continue;
1643 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1644 continue;
1645 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1646 continue;
1647 return spellInfo;
1649 return NULL;
1652 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1654 // gamemaster in GM mode see all, including ghosts
1655 if(pl->isGameMaster())
1656 return true;
1658 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1659 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1661 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1662 return false;
1663 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1666 // Dead player see live creatures near own corpse
1667 if(isAlive())
1669 Corpse *corpse = pl->GetCorpse();
1670 if(corpse)
1672 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1673 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1674 return true;
1678 // Dead player see Spirit Healer or Spirit Guide
1679 if(isSpiritService())
1680 return true;
1682 // and not see any other
1683 return false;
1686 void Creature::CallAssistance()
1688 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1690 SetNoCallAssistance(true);
1692 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1693 if(radius > 0)
1695 std::list<Creature*> assistList;
1698 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1699 Cell cell(p);
1700 cell.data.Part.reserved = ALL_DISTRICT;
1701 cell.SetNoCreate();
1703 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1704 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1706 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1708 CellLock<GridReadGuard> cell_lock(cell, p);
1709 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1712 if (!assistList.empty())
1714 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1715 while (!assistList.empty())
1717 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1718 e->AddAssistant((*assistList.begin())->GetGUID());
1719 assistList.pop_front();
1721 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1727 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1729 // we don't need help from zombies :)
1730 if( !isAlive() )
1731 return false;
1733 // skip fighting creature
1734 if( isInCombat() )
1735 return false;
1737 // only from same creature faction
1738 if(getFaction() != u->getFaction() )
1739 return false;
1741 // only free creature
1742 if( GetCharmerOrOwnerGUID() )
1743 return false;
1745 // skip non hostile to caster enemy creatures
1746 if( !IsHostileTo(enemy) )
1747 return false;
1749 return true;
1752 void Creature::SaveRespawnTime()
1754 if(isPet() || !m_DBTableGuid)
1755 return;
1757 if(m_respawnTime > time(NULL)) // dead (no corpse)
1758 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1759 else if(m_deathTimer > 0) // dead (corpse)
1760 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1763 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1765 if(!pVictim)
1766 return true;
1768 if(!pVictim->IsInMap(this))
1769 return true;
1771 if(!pVictim->isTargetableForAttack())
1772 return true;
1774 if(!pVictim->isInAccessablePlaceFor(this))
1775 return true;
1777 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1778 return false;
1780 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1781 float AttackDist = GetAttackDistance(pVictim);
1782 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1784 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1785 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1788 CreatureDataAddon const* Creature::GetCreatureAddon() const
1790 if (m_DBTableGuid)
1792 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1793 return addon;
1796 // dependent from heroic mode entry
1797 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1800 //creature_addon table
1801 bool Creature::LoadCreaturesAddon(bool reload)
1803 CreatureDataAddon const *cainfo = GetCreatureAddon();
1804 if(!cainfo)
1805 return false;
1807 if (cainfo->mount != 0)
1808 Mount(cainfo->mount);
1810 if (cainfo->bytes0 != 0)
1811 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1813 if (cainfo->bytes1 != 0)
1814 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1816 if (cainfo->bytes2 != 0)
1817 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1819 if (cainfo->emote != 0)
1820 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1822 if (cainfo->move_flags != 0)
1823 SetUnitMovementFlags(cainfo->move_flags);
1825 if(cainfo->auras)
1827 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1829 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1830 if (!AdditionalSpellInfo)
1832 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1833 continue;
1836 // skip already applied aura
1837 if(HasAura(cAura->spell_id,cAura->effect_idx))
1839 if(!reload)
1840 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);
1842 continue;
1845 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1846 AddAura(AdditionalAura);
1847 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1850 return true;
1853 /// Send a message to LocalDefense channel for players opposition team in the zone
1854 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1856 uint32 enemy_team = attacker->GetTeam();
1858 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1859 data << (uint32)GetZoneId();
1860 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1863 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1865 m_CreatureSpellCooldowns[spell_id] = end_time;
1868 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1870 m_CreatureCategoryCooldowns[category] = apply_time;
1873 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1875 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1876 if(!spellInfo)
1877 return;
1879 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1880 if(cooldown)
1881 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1883 if(spellInfo->Category)
1884 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1886 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1889 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1891 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1892 if(!spellInfo)
1893 return false;
1895 // check global cooldown if spell affected by it
1896 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1897 return true;
1899 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1900 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1903 bool Creature::HasSpellCooldown(uint32 spell_id) const
1905 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1906 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1909 bool Creature::IsInEvadeMode() const
1911 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1914 bool Creature::HasSpell(uint32 spellID) const
1916 uint8 i;
1917 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1918 if(spellID == m_spells[i])
1919 break;
1920 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1923 time_t Creature::GetRespawnTimeEx() const
1925 time_t now = time(NULL);
1926 if(m_respawnTime > now) // dead (no corpse)
1927 return m_respawnTime;
1928 else if(m_deathTimer > 0) // dead (corpse)
1929 return now+m_respawnDelay+m_deathTimer/1000;
1930 else
1931 return now;
1934 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1936 if (m_DBTableGuid)
1938 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1940 x = data->posX;
1941 y = data->posY;
1942 z = data->posZ;
1943 if(ori)
1944 *ori = data->orientation;
1945 if(dist)
1946 *dist = data->spawndist;
1948 return;
1952 x = GetPositionX();
1953 y = GetPositionY();
1954 z = GetPositionZ();
1955 if(ori)
1956 *ori = GetOrientation();
1957 if(dist)
1958 *dist = 0;
1961 void Creature::AllLootRemovedFromCorpse()
1963 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1965 uint32 nDeathTimer;
1967 CreatureInfo const *cinfo = GetCreatureInfo();
1969 // corpse was not skinnable -> apply corpse looted timer
1970 if (!cinfo || !cinfo->SkinLootId)
1971 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1972 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1973 else
1974 nDeathTimer = 0;
1976 // update death timer only if looted timer is shorter
1977 if (m_deathTimer > nDeathTimer)
1978 m_deathTimer = nDeathTimer;
1982 uint32 Creature::getLevelForTarget( Unit const* target ) const
1984 if(!isWorldBoss())
1985 return Unit::getLevelForTarget(target);
1987 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1988 if(level < 1)
1989 return 1;
1990 if(level > 255)
1991 return 255;
1992 return level;
1995 std::string Creature::GetScriptName()
1997 return objmgr.GetScriptName(GetScriptId());
2000 uint32 Creature::GetScriptId()
2002 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2005 VendorItemData const* Creature::GetVendorItems() const
2007 return objmgr.GetNpcVendorItemList(GetEntry());
2010 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2012 if(!vItem->maxcount)
2013 return vItem->maxcount;
2015 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2016 for(; itr != m_vendorItemCounts.end(); ++itr)
2017 if(itr->itemId==vItem->item)
2018 break;
2020 if(itr == m_vendorItemCounts.end())
2021 return vItem->maxcount;
2023 VendorItemCount* vCount = &*itr;
2025 time_t ptime = time(NULL);
2027 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2029 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2031 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2032 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2034 m_vendorItemCounts.erase(itr);
2035 return vItem->maxcount;
2038 vCount->count += diff * pProto->BuyCount;
2039 vCount->lastIncrementTime = ptime;
2042 return vCount->count;
2045 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2047 if(!vItem->maxcount)
2048 return 0;
2050 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2051 for(; itr != m_vendorItemCounts.end(); ++itr)
2052 if(itr->itemId==vItem->item)
2053 break;
2055 if(itr == m_vendorItemCounts.end())
2057 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2058 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2059 return new_count;
2062 VendorItemCount* vCount = &*itr;
2064 time_t ptime = time(NULL);
2066 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2068 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2070 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2071 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2072 vCount->count += diff * pProto->BuyCount;
2073 else
2074 vCount->count = vItem->maxcount;
2077 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2078 vCount->lastIncrementTime = ptime;
2079 return vCount->count;
2082 TrainerSpellData const* Creature::GetTrainerSpells() const
2084 return objmgr.GetNpcTrainerSpells(GetEntry());
2087 // overwrite WorldObject function for proper name localization
2088 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2090 if (loc_idx >= 0)
2092 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2093 if (cl)
2095 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2096 return cl->Name[loc_idx].c_str();
2100 return GetName();