[7908] Extract class data from creature_*_addon bytes0 fields, drop its, amd add...
[getmangos.git] / src / game / Creature.cpp
blob47ad3e2ae0b7c6418fec850adab9d2d14825ae1d
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 // equal to player Race field, but creature does not have race
201 SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
203 // known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
204 SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
206 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
208 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
209 return false;
212 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
213 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
214 if (!minfo)
216 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
217 return false;
219 else
220 display_id = minfo->modelid; // it can be different (for another gender)
222 SetDisplayId(display_id);
223 SetNativeDisplayId(display_id);
224 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
226 // Load creature equipment
227 if(!data || data->equipmentId == 0)
228 { // use default from the template
229 LoadEquipment(cinfo->equipmentId);
231 else if(data && data->equipmentId != -1)
232 { // override, -1 means no equipment
233 LoadEquipment(data->equipmentId);
236 SetName(normalInfo->Name); // at normal entry always
238 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
239 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
241 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
243 SetSpeed(MOVE_WALK, cinfo->speed );
244 SetSpeed(MOVE_RUN, cinfo->speed );
245 SetSpeed(MOVE_SWIM, cinfo->speed );
247 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
249 // checked at loading
250 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
251 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
252 m_defaultMovementType = IDLE_MOTION_TYPE;
254 return true;
257 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
259 if(!InitEntry(Entry,team,data))
260 return false;
262 m_regenHealth = GetCreatureInfo()->RegenHealth;
264 // creatures always have melee weapon ready if any
265 SetSheath(SHEATH_STATE_MELEE);
267 SelectLevel(GetCreatureInfo());
268 if (team == HORDE)
269 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
270 else
271 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
273 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
275 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
276 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
277 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
279 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
280 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
282 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
283 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
284 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
285 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
286 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
287 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
288 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
290 SetCanModifyStats(true);
291 UpdateAllStats();
293 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
294 if (factionTemplate) // check and error show at loading templates
296 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
297 if (factionEntry)
298 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
299 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
300 SetPvP(true);
303 for(int i=0; i < CREATURE_MAX_SPELLS; ++i)
304 m_spells[i] = GetCreatureInfo()->spells[i];
306 return true;
309 void Creature::Update(uint32 diff)
311 if(m_GlobalCooldown <= diff)
312 m_GlobalCooldown = 0;
313 else
314 m_GlobalCooldown -= diff;
316 switch( m_deathState )
318 case JUST_ALIVED:
319 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
320 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
321 break;
322 case JUST_DIED:
323 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
324 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
325 break;
326 case DEAD:
328 if( m_respawnTime <= time(NULL) )
330 DEBUG_LOG("Respawning...");
331 m_respawnTime = 0;
332 lootForPickPocketed = false;
333 lootForBody = false;
335 if(m_originalEntry != GetEntry())
336 UpdateEntry(m_originalEntry);
338 CreatureInfo const *cinfo = GetCreatureInfo();
340 SelectLevel(cinfo);
341 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
342 if (m_isDeadByDefault)
344 setDeathState(JUST_DIED);
345 SetHealth(0);
346 i_motionMaster.Clear();
347 clearUnitState(UNIT_STAT_ALL_STATE);
348 LoadCreaturesAddon(true);
350 else
351 setDeathState( JUST_ALIVED );
353 //Call AI respawn virtual function
354 i_AI->JustRespawned();
356 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), GetTypeId());
357 if (poolid)
358 poolhandler.UpdatePool(poolid, GetGUIDLow(), GetTypeId());
359 else
360 GetMap()->Add(this);
362 break;
364 case CORPSE:
366 if (m_isDeadByDefault)
367 break;
369 if( m_deathTimer <= diff )
371 RemoveCorpse();
372 DEBUG_LOG("Removing corpse... %u ", GetEntry());
374 else
376 m_deathTimer -= diff;
377 if (m_groupLootTimer && lootingGroupLeaderGUID)
379 if(diff <= m_groupLootTimer)
381 m_groupLootTimer -= diff;
383 else
385 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
386 if (group)
387 group->EndRoll();
388 m_groupLootTimer = 0;
389 lootingGroupLeaderGUID = 0;
394 break;
396 case ALIVE:
398 if (m_isDeadByDefault)
400 if( m_deathTimer <= diff )
402 RemoveCorpse();
403 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
405 else
407 m_deathTimer -= diff;
411 Unit::Update( diff );
413 // creature can be dead after Unit::Update call
414 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
415 if(!isAlive())
416 break;
418 if(!IsInEvadeMode())
420 // do not allow the AI to be changed during update
421 m_AI_locked = true;
422 i_AI->UpdateAI(diff);
423 m_AI_locked = false;
426 // creature can be dead after UpdateAI call
427 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
428 if(!isAlive())
429 break;
430 if(m_regenTimer > 0)
432 if(diff >= m_regenTimer)
433 m_regenTimer = 0;
434 else
435 m_regenTimer -= diff;
437 if (m_regenTimer != 0)
438 break;
440 if (!isInCombat() || IsPolymorphed())
441 RegenerateHealth();
443 RegenerateMana();
445 m_regenTimer = 2000;
446 break;
448 case DEAD_FALLING:
450 if (!FallGround())
451 setDeathState(JUST_DIED);
453 default:
454 break;
458 void Creature::RegenerateMana()
460 uint32 curValue = GetPower(POWER_MANA);
461 uint32 maxValue = GetMaxPower(POWER_MANA);
463 if (curValue >= maxValue)
464 return;
466 uint32 addvalue = 0;
468 // Combat and any controlled creature
469 if (isInCombat() || GetCharmerOrOwnerGUID())
471 if(!IsUnderLastManaUseEffect())
473 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
474 float Spirit = GetStat(STAT_SPIRIT);
476 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
479 else
480 addvalue = maxValue/3;
482 ModifyPower(POWER_MANA, addvalue);
485 void Creature::RegenerateHealth()
487 if (!isRegeneratingHealth())
488 return;
490 uint32 curValue = GetHealth();
491 uint32 maxValue = GetMaxHealth();
493 if (curValue >= maxValue)
494 return;
496 uint32 addvalue = 0;
498 // Not only pet, but any controlled creature
499 if(GetCharmerOrOwnerGUID())
501 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
502 float Spirit = GetStat(STAT_SPIRIT);
504 if( GetPower(POWER_MANA) > 0 )
505 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
506 else
507 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
509 else
510 addvalue = maxValue/3;
512 ModifyHealth(addvalue);
515 void Creature::DoFleeToGetAssistance()
517 if (!getVictim())
518 return;
520 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
521 if (radius >0)
523 Creature* pCreature = NULL;
525 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
526 Cell cell(p);
527 cell.data.Part.reserved = ALL_DISTRICT;
528 cell.SetNoCreate();
529 MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
530 MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(this, pCreature, u_check);
532 TypeContainerVisitor<MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
534 CellLock<GridReadGuard> cell_lock(cell, p);
535 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
537 SetNoSearchAssistance(true);
538 if(!pCreature)
539 SetFeared(true, getVictim()->GetGUID(), 0 ,sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
540 else
541 GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
545 bool Creature::AIM_Initialize()
547 // make sure nothing can change the AI during AI update
548 if(m_AI_locked)
550 sLog.outDebug("AIM_Initialize: failed to init, locked.");
551 return false;
554 CreatureAI * oldAI = i_AI;
555 i_motionMaster.Initialize();
556 i_AI = FactorySelector::selectAI(this);
557 if (oldAI)
558 delete oldAI;
559 return true;
562 bool Creature::Create (uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
564 SetMapId(map->GetId());
565 SetInstanceId(map->GetInstanceId());
566 SetPhaseMask(phaseMask,false);
568 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
569 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
571 if (bResult)
573 switch (GetCreatureInfo()->rank)
575 case CREATURE_ELITE_RARE:
576 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
577 break;
578 case CREATURE_ELITE_ELITE:
579 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
580 break;
581 case CREATURE_ELITE_RAREELITE:
582 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
583 break;
584 case CREATURE_ELITE_WORLDBOSS:
585 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
586 break;
587 default:
588 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
589 break;
591 LoadCreaturesAddon();
594 return bResult;
597 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
599 if(!isTrainer())
600 return false;
602 TrainerSpellData const* trainer_spells = GetTrainerSpells();
604 if(!trainer_spells || trainer_spells->spellList.empty())
606 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
607 GetGUIDLow(),GetEntry());
608 return false;
611 switch(GetCreatureInfo()->trainer_type)
613 case TRAINER_TYPE_CLASS:
614 if(pPlayer->getClass()!=GetCreatureInfo()->trainer_class)
616 if(msg)
618 pPlayer->PlayerTalkClass->ClearMenus();
619 switch(GetCreatureInfo()->trainer_class)
621 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
622 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
623 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
624 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
625 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
626 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
627 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
628 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
629 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
632 return false;
634 break;
635 case TRAINER_TYPE_PETS:
636 if(pPlayer->getClass()!=CLASS_HUNTER)
638 pPlayer->PlayerTalkClass->ClearMenus();
639 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
640 return false;
642 break;
643 case TRAINER_TYPE_MOUNTS:
644 if(GetCreatureInfo()->trainer_race && pPlayer->getRace() != GetCreatureInfo()->trainer_race)
646 if(msg)
648 pPlayer->PlayerTalkClass->ClearMenus();
649 switch(GetCreatureInfo()->trainer_class)
651 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
652 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
653 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
654 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
655 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
656 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
657 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
658 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
659 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
660 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
663 return false;
665 break;
666 case TRAINER_TYPE_TRADESKILLS:
667 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
669 if(msg)
671 pPlayer->PlayerTalkClass->ClearMenus();
672 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
674 return false;
676 break;
677 default:
678 return false; // checked and error output at creature_template loading
680 return true;
683 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
685 if(!isBattleMaster())
686 return false;
688 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
689 if(!msg)
690 return pPlayer->GetBGAccessByLevel(bgTypeId);
692 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
694 pPlayer->PlayerTalkClass->ClearMenus();
695 switch(bgTypeId)
697 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
698 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
699 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
700 case BATTLEGROUND_EY:
701 case BATTLEGROUND_NA:
702 case BATTLEGROUND_BE:
703 case BATTLEGROUND_AA:
704 case BATTLEGROUND_RL:
705 case BATTLEGROUND_SA:
706 case BATTLEGROUND_DS:
707 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
708 default: break;
710 return false;
712 return true;
715 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
717 return pPlayer->getLevel() >= 10
718 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
719 && pPlayer->getClass() == GetCreatureInfo()->trainer_class;
722 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
724 PlayerMenu* pm=pPlayer->PlayerTalkClass;
725 pm->ClearMenus();
727 // lazy loading single time at use
728 LoadGossipOptions();
730 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
732 GossipOption* gso=&*i;
733 if(gso->GossipId == gossipid)
735 bool cantalking=true;
736 if(gso->Id==1)
738 uint32 textid=GetNpcTextId();
739 GossipText const* gossiptext=objmgr.GetGossipText(textid);
740 if(!gossiptext)
741 cantalking=false;
743 else
745 switch (gso->Action)
747 case GOSSIP_OPTION_QUESTGIVER:
748 pPlayer->PrepareQuestMenu(GetGUID());
749 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
750 cantalking=false;
751 //pm->GetQuestMenu()->ClearMenu();
752 break;
753 case GOSSIP_OPTION_ARMORER:
754 cantalking=false; // added in special mode
755 break;
756 case GOSSIP_OPTION_SPIRITHEALER:
757 if( !pPlayer->isDead() )
758 cantalking=false;
759 break;
760 case GOSSIP_OPTION_VENDOR:
762 VendorItemData const* vItems = GetVendorItems();
763 if(!vItems || vItems->Empty())
765 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
766 GetGUIDLow(),GetEntry());
767 cantalking=false;
769 break;
771 case GOSSIP_OPTION_TRAINER:
772 if(!isCanTrainingOf(pPlayer,false))
773 cantalking=false;
774 break;
775 case GOSSIP_OPTION_UNLEARNTALENTS:
776 if(!isCanTrainingAndResetTalentsOf(pPlayer))
777 cantalking=false;
778 break;
779 case GOSSIP_OPTION_UNLEARNPETSKILLS:
780 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->trainer_class != CLASS_HUNTER)
781 cantalking=false;
782 break;
783 case GOSSIP_OPTION_TAXIVENDOR:
784 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
785 return;
786 break;
787 case GOSSIP_OPTION_BATTLEFIELD:
788 if(!isCanInteractWithBattleMaster(pPlayer,false))
789 cantalking=false;
790 break;
791 case GOSSIP_OPTION_SPIRITGUIDE:
792 case GOSSIP_OPTION_INNKEEPER:
793 case GOSSIP_OPTION_BANKER:
794 case GOSSIP_OPTION_PETITIONER:
795 case GOSSIP_OPTION_STABLEPET:
796 case GOSSIP_OPTION_TABARDDESIGNER:
797 case GOSSIP_OPTION_AUCTIONEER:
798 break; // no checks
799 default:
800 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
801 break;
805 //note for future dev: should have database fields for BoxMessage & BoxMoney
806 if(!gso->OptionText.empty() && cantalking)
808 std::string OptionText = gso->OptionText;
809 std::string BoxText = gso->BoxText;
810 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
811 if (loc_idx >= 0)
813 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
814 if (no)
816 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
817 OptionText=no->OptionText[loc_idx];
818 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
819 BoxText=no->BoxText[loc_idx];
822 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
827 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
828 if(pm->Empty())
830 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
832 isCanTrainingOf(pPlayer,true); // output error message if need
834 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
836 isCanInteractWithBattleMaster(pPlayer,true); // output error message if need
841 void Creature::sendPreparedGossip(Player* player)
843 if(!player)
844 return;
846 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
847 if (!HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !player->PlayerTalkClass->GetQuestMenu().Empty())
849 player->SendPreparedQuest(GetGUID());
850 return;
853 // in case non empty gossip menu (that not included quests list size) show it
854 // (quest entries from quest menu will be included in list)
855 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
858 void Creature::OnGossipSelect(Player* player, uint32 option)
860 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
862 if(option >= gossipmenu.MenuItemCount())
863 return;
865 uint32 action=gossipmenu.GetItem(option).m_gAction;
866 uint32 zoneid=GetZoneId();
867 uint64 guid=GetGUID();
869 GossipOption const *gossip=GetGossipOption( action );
870 if(!gossip)
872 zoneid=0;
873 gossip=GetGossipOption( action );
874 if(!gossip)
875 return;
878 switch (gossip->Action)
880 case GOSSIP_OPTION_GOSSIP:
882 uint32 textid = GetGossipTextId(action, zoneid);
883 if (textid == 0)
884 textid=GetNpcTextId();
886 player->PlayerTalkClass->CloseGossip();
887 player->PlayerTalkClass->SendTalking(textid);
888 break;
890 case GOSSIP_OPTION_SPIRITHEALER:
891 if (player->isDead())
892 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
893 break;
894 case GOSSIP_OPTION_QUESTGIVER:
895 player->PrepareQuestMenu( guid );
896 player->SendPreparedQuest( guid );
897 break;
898 case GOSSIP_OPTION_VENDOR:
899 case GOSSIP_OPTION_ARMORER:
900 player->GetSession()->SendListInventory(guid);
901 break;
902 case GOSSIP_OPTION_STABLEPET:
903 player->GetSession()->SendStablePet(guid);
904 break;
905 case GOSSIP_OPTION_TRAINER:
906 player->GetSession()->SendTrainerList(guid);
907 break;
908 case GOSSIP_OPTION_UNLEARNTALENTS:
909 player->PlayerTalkClass->CloseGossip();
910 player->SendTalentWipeConfirm(guid);
911 break;
912 case GOSSIP_OPTION_UNLEARNPETSKILLS:
913 player->PlayerTalkClass->CloseGossip();
914 player->SendPetSkillWipeConfirm();
915 break;
916 case GOSSIP_OPTION_TAXIVENDOR:
917 player->GetSession()->SendTaxiMenu(this);
918 break;
919 case GOSSIP_OPTION_INNKEEPER:
920 player->PlayerTalkClass->CloseGossip();
921 player->SetBindPoint( guid );
922 break;
923 case GOSSIP_OPTION_BANKER:
924 player->GetSession()->SendShowBank( guid );
925 break;
926 case GOSSIP_OPTION_PETITIONER:
927 player->PlayerTalkClass->CloseGossip();
928 player->GetSession()->SendPetitionShowList( guid );
929 break;
930 case GOSSIP_OPTION_TABARDDESIGNER:
931 player->PlayerTalkClass->CloseGossip();
932 player->GetSession()->SendTabardVendorActivate( guid );
933 break;
934 case GOSSIP_OPTION_AUCTIONEER:
935 player->GetSession()->SendAuctionHello( guid, this );
936 break;
937 case GOSSIP_OPTION_SPIRITGUIDE:
938 case GOSSIP_GUARD_SPELLTRAINER:
939 case GOSSIP_GUARD_SKILLTRAINER:
940 prepareGossipMenu( player,gossip->Id );
941 sendPreparedGossip( player );
942 break;
943 case GOSSIP_OPTION_BATTLEFIELD:
945 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
946 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
947 break;
949 default:
950 OnPoiSelect( player, gossip );
951 break;
956 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
958 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
960 Poi_Icon icon = ICON_POI_BLANK;
961 //need add more case.
962 switch(gossip->Action)
964 case GOSSIP_GUARD_BANK:
965 icon=ICON_POI_SMALL_HOUSE;
966 break;
967 case GOSSIP_GUARD_RIDE:
968 icon=ICON_POI_RWHORSE;
969 break;
970 case GOSSIP_GUARD_GUILD:
971 icon=ICON_POI_BLUETOWER;
972 break;
973 default:
974 icon=ICON_POI_GREYTOWER;
975 break;
977 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
978 player->PlayerTalkClass->SendTalking(textid);
979 // std::string areaname= gossip->OptionText;
980 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
984 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
986 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
988 if(!result)
989 return 0;
991 Field *fields = result->Fetch();
992 uint32 id = fields[0].GetUInt32();
994 delete result;
996 return id;
999 uint32 Creature::GetNpcTextId()
1001 if (!m_DBTableGuid)
1002 return DEFAULT_GOSSIP_MESSAGE;
1004 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
1005 return pos;
1007 return DEFAULT_GOSSIP_MESSAGE;
1010 GossipOption const* Creature::GetGossipOption( uint32 id ) const
1012 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
1014 if(i->Action==id )
1015 return &*i;
1017 return NULL;
1020 void Creature::LoadGossipOptions()
1022 if(m_gossipOptionLoaded)
1023 return;
1025 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1027 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1028 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1029 if(i->NpcFlag & npcflags)
1030 addGossipOption(*i);
1032 m_gossipOptionLoaded = true;
1035 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1037 /* uint32 timeElap = getMSTime();
1038 if ((timeElap - m_startMove) < m_moveTime)
1040 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1041 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1043 else
1045 oX = dX;
1046 oY = dY;
1049 dX = x;
1050 dY = y;
1051 m_orientation = atan2((oY - dY), (oX - dX));
1053 m_startMove = getMSTime();
1054 m_moveTime = time;*/
1055 SendMonsterMove(x, y, z, type, MovementFlags, time);
1058 Player *Creature::GetLootRecipient() const
1060 if (!m_lootRecipient) return NULL;
1061 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1064 void Creature::SetLootRecipient(Unit *unit)
1066 // set the player whose group should receive the right
1067 // to loot the creature after it dies
1068 // should be set to NULL after the loot disappears
1070 if (!unit)
1072 m_lootRecipient = 0;
1073 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1074 return;
1077 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1078 if(!player) // normal creature, no player involved
1079 return;
1081 m_lootRecipient = player->GetGUID();
1082 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1085 void Creature::SaveToDB()
1087 // this should only be used when the creature has already been loaded
1088 // preferably after adding to map, because mapid may not be valid otherwise
1089 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1090 if(!data)
1092 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1093 return;
1096 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
1099 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
1101 // update in loaded data
1102 if (!m_DBTableGuid)
1103 m_DBTableGuid = GetGUIDLow();
1104 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1106 uint32 displayId = GetNativeDisplayId();
1108 // check if it's a custom model and if not, use 0 for displayId
1109 CreatureInfo const *cinfo = GetCreatureInfo();
1110 if(cinfo)
1112 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1114 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1115 if(!minfo || displayId != minfo->modelid_other_gender)
1117 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1118 if(minfo && displayId == minfo->modelid_other_gender)
1119 displayId = 0;
1121 else
1122 displayId = 0;
1124 else
1125 displayId = 0;
1128 // data->guid = guid don't must be update at save
1129 data.id = GetEntry();
1130 data.mapid = mapid;
1131 data.phaseMask = phaseMask;
1132 data.displayid = displayId;
1133 data.equipmentId = GetEquipmentId();
1134 data.posX = GetPositionX();
1135 data.posY = GetPositionY();
1136 data.posZ = GetPositionZ();
1137 data.orientation = GetOrientation();
1138 data.spawntimesecs = m_respawnDelay;
1139 // prevent add data integrity problems
1140 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1141 data.currentwaypoint = 0;
1142 data.curhealth = GetHealth();
1143 data.curmana = GetPower(POWER_MANA);
1144 data.is_dead = m_isDeadByDefault;
1145 // prevent add data integrity problems
1146 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1147 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1148 data.spawnMask = spawnMask;
1150 // updated in DB
1151 WorldDatabase.BeginTransaction();
1153 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1155 std::ostringstream ss;
1156 ss << "INSERT INTO creature VALUES ("
1157 << m_DBTableGuid << ","
1158 << GetEntry() << ","
1159 << mapid <<","
1160 << uint32(spawnMask) << "," // cast to prevent save as symbol
1161 << uint16(GetPhaseMask()) << "," // prevent out of range error
1162 << displayId <<","
1163 << GetEquipmentId() <<","
1164 << GetPositionX() << ","
1165 << GetPositionY() << ","
1166 << GetPositionZ() << ","
1167 << GetOrientation() << ","
1168 << m_respawnDelay << "," //respawn time
1169 << (float) m_respawnradius << "," //spawn distance (float)
1170 << (uint32) (0) << "," //currentwaypoint
1171 << GetHealth() << "," //curhealth
1172 << GetPower(POWER_MANA) << "," //curmana
1173 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1174 << GetDefaultMovementType() << ")"; //default movement generator type
1176 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1178 WorldDatabase.CommitTransaction();
1181 void Creature::SelectLevel(const CreatureInfo *cinfo)
1183 uint32 rank = isPet()? 0 : cinfo->rank;
1185 // level
1186 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1187 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1188 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1189 SetLevel(level);
1191 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1193 // health
1194 float healthmod = _GetHealthMod(rank);
1196 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1197 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1198 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1200 SetCreateHealth(health);
1201 SetMaxHealth(health);
1202 SetHealth(health);
1204 // mana
1205 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1206 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1207 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1209 SetCreateMana(mana);
1210 SetMaxPower(POWER_MANA, mana); //MAX Mana
1211 SetPower(POWER_MANA, mana);
1213 // TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
1215 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1216 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1218 // damage
1219 float damagemod = _GetDamageMod(rank);
1221 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1222 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1224 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1225 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1227 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1230 float Creature::_GetHealthMod(int32 Rank)
1232 switch (Rank) // define rates for each elite rank
1234 case CREATURE_ELITE_NORMAL:
1235 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1236 case CREATURE_ELITE_ELITE:
1237 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1238 case CREATURE_ELITE_RAREELITE:
1239 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1240 case CREATURE_ELITE_WORLDBOSS:
1241 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1242 case CREATURE_ELITE_RARE:
1243 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1244 default:
1245 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1249 float Creature::_GetDamageMod(int32 Rank)
1251 switch (Rank) // define rates for each elite rank
1253 case CREATURE_ELITE_NORMAL:
1254 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1255 case CREATURE_ELITE_ELITE:
1256 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1257 case CREATURE_ELITE_RAREELITE:
1258 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1259 case CREATURE_ELITE_WORLDBOSS:
1260 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1261 case CREATURE_ELITE_RARE:
1262 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1263 default:
1264 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1268 float Creature::GetSpellDamageMod(int32 Rank)
1270 switch (Rank) // define rates for each elite rank
1272 case CREATURE_ELITE_NORMAL:
1273 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1274 case CREATURE_ELITE_ELITE:
1275 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1276 case CREATURE_ELITE_RAREELITE:
1277 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1278 case CREATURE_ELITE_WORLDBOSS:
1279 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1280 case CREATURE_ELITE_RARE:
1281 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1282 default:
1283 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1287 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1289 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1290 if(!cinfo)
1292 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1293 return false;
1295 m_originalEntry = Entry;
1297 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1299 if(!UpdateEntry(Entry, team, data))
1300 return false;
1302 //Notify the map's instance data.
1303 //Only works if you create the object in it, not if it is moves to that map.
1304 //Normally non-players do not teleport to other maps.
1305 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1306 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1308 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this);
1311 return true;
1314 bool Creature::LoadFromDB(uint32 guid, Map *map)
1316 CreatureData const* data = objmgr.GetCreatureData(guid);
1318 if(!data)
1320 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1321 return false;
1324 m_DBTableGuid = guid;
1325 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1327 uint16 team = 0;
1328 if(!Create(guid,map,data->phaseMask,data->id,team,data))
1329 return false;
1331 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1333 if(!IsPositionValid())
1335 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1336 return false;
1339 m_respawnradius = data->spawndist;
1341 m_respawnDelay = data->spawntimesecs;
1342 m_isDeadByDefault = data->is_dead;
1343 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1345 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1346 if(m_respawnTime > time(NULL)) // not ready to respawn
1348 m_deathState = DEAD;
1349 if(canFly())
1351 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1352 if(data->posZ - tz > 0.1)
1353 Relocate(data->posX,data->posY,tz);
1356 else if(m_respawnTime) // respawn time set but expired
1358 m_respawnTime = 0;
1359 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1362 uint32 curhealth = data->curhealth;
1363 if(curhealth)
1365 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1366 if(curhealth < 1)
1367 curhealth = 1;
1370 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1371 SetPower(POWER_MANA,data->curmana);
1373 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1375 // checked at creature_template loading
1376 m_defaultMovementType = MovementGeneratorType(data->movementType);
1378 AIM_Initialize();
1379 return true;
1382 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1384 if(equip_entry == 0)
1386 if (force)
1388 for (uint8 i = 0; i < 3; ++i)
1389 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1390 m_equipmentId = 0;
1392 return;
1395 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1396 if (!einfo)
1397 return;
1399 m_equipmentId = equip_entry;
1400 for (uint8 i = 0; i < 3; ++i)
1401 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1404 bool Creature::hasQuest(uint32 quest_id) const
1406 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1407 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1409 if(itr->second==quest_id)
1410 return true;
1412 return false;
1415 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1417 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1418 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1420 if(itr->second==quest_id)
1421 return true;
1423 return false;
1426 void Creature::DeleteFromDB()
1428 if (!m_DBTableGuid)
1430 sLog.outDebug("Trying to delete not saved creature!");
1431 return;
1434 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1435 objmgr.DeleteCreatureData(m_DBTableGuid);
1437 WorldDatabase.BeginTransaction();
1438 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1439 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1440 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1441 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1442 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1443 WorldDatabase.CommitTransaction();
1446 float Creature::GetAttackDistance(Unit const* pl) const
1448 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1449 if(aggroRate==0)
1450 return 0.0f;
1452 int32 playerlevel = pl->getLevelForTarget(this);
1453 int32 creaturelevel = getLevelForTarget(pl);
1455 int32 leveldif = playerlevel - creaturelevel;
1457 // "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."
1458 if ( leveldif < - 25)
1459 leveldif = -25;
1461 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1462 float RetDistance = 20;
1464 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1465 // radius grow if playlevel < creaturelevel
1466 RetDistance -= (float)leveldif;
1468 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1470 // detect range auras
1471 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1473 // detected range auras
1474 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1477 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1478 if(RetDistance < 5)
1479 RetDistance = 5;
1481 return (RetDistance*aggroRate);
1484 void Creature::setDeathState(DeathState s)
1486 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1488 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1490 // always save boss respawn time at death to prevent crash cheating
1491 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1492 SaveRespawnTime();
1494 if (canFly() && FallGround())
1495 return;
1497 if(!IsStopped())
1498 StopMoving();
1500 Unit::setDeathState(s);
1502 if(s == JUST_DIED)
1504 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1505 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1507 if(!isPet() && GetCreatureInfo()->SkinLootId)
1508 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1509 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1511 if (canFly() && FallGround())
1512 return;
1514 SetNoSearchAssistance(false);
1515 Unit::setDeathState(CORPSE);
1517 if(s == JUST_ALIVED)
1519 SetHealth(GetMaxHealth());
1520 SetLootRecipient(NULL);
1521 Unit::setDeathState(ALIVE);
1522 CreatureInfo const *cinfo = GetCreatureInfo();
1523 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1524 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1525 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1526 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1527 clearUnitState(UNIT_STAT_ALL_STATE);
1528 i_motionMaster.Clear();
1529 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1530 LoadCreaturesAddon(true);
1534 bool Creature::FallGround()
1536 // Let's abort after we called this function one time
1537 if (getDeathState() == DEAD_FALLING)
1538 return false;
1540 // Let's do with no vmap because no way to get far distance with vmap high call
1541 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1543 // Abort too if the ground is very near
1544 if (fabs(GetPositionZ() - tz) < 0.1f)
1545 return false;
1547 Unit::setDeathState(DEAD_FALLING);
1548 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1549 Relocate(GetPositionX(), GetPositionY(), tz);
1550 return true;
1553 void Creature::Respawn()
1555 RemoveCorpse();
1557 // forced recreate creature object at clients
1558 UnitVisibility currentVis = GetVisibility();
1559 SetVisibility(VISIBILITY_RESPAWN);
1560 ObjectAccessor::UpdateObjectVisibility(this);
1561 SetVisibility(currentVis); // restore visibility state
1562 ObjectAccessor::UpdateObjectVisibility(this);
1564 if(getDeathState()==DEAD)
1566 if (m_DBTableGuid)
1567 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1568 m_respawnTime = time(NULL); // respawn at next tick
1572 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1574 if (!spellInfo)
1575 return false;
1577 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1578 return true;
1580 return Unit::IsImmunedToSpell(spellInfo);
1583 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1585 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1586 return true;
1588 // Taunt immunity special flag check
1589 if (GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NOT_TAUNTABLE)
1591 // Taunt aura apply check
1592 if (spellInfo->Effect[index] == SPELL_EFFECT_APPLY_AURA)
1594 if (spellInfo->EffectApplyAuraName[index] == SPELL_AURA_MOD_TAUNT)
1595 return true;
1597 // Spell effect taunt check
1598 else if (spellInfo->Effect[index] == SPELL_EFFECT_ATTACK_ME)
1599 return true;
1602 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1605 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1607 if(!pVictim)
1608 return NULL;
1610 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1612 if(!m_spells[i])
1613 continue;
1614 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1615 if(!spellInfo)
1617 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1618 continue;
1621 bool bcontinue = true;
1622 for(uint32 j=0;j<3;j++)
1624 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1625 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1626 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1627 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1630 bcontinue = false;
1631 break;
1634 if(bcontinue) continue;
1636 if(spellInfo->manaCost > GetPower(POWER_MANA))
1637 continue;
1638 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1639 float range = GetSpellMaxRange(srange);
1640 float minrange = GetSpellMinRange(srange);
1642 float dist = GetCombatDistance(pVictim);
1644 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1645 // continue;
1646 if( dist > range || dist < minrange )
1647 continue;
1648 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1649 continue;
1650 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1651 continue;
1652 return spellInfo;
1654 return NULL;
1657 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1659 if(!pVictim)
1660 return NULL;
1662 for(uint32 i=0; i < CREATURE_MAX_SPELLS; ++i)
1664 if(!m_spells[i])
1665 continue;
1666 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1667 if(!spellInfo)
1669 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1670 continue;
1673 bool bcontinue = true;
1674 for(uint32 j=0;j<3;j++)
1676 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1678 bcontinue = false;
1679 break;
1682 if(bcontinue) continue;
1684 if(spellInfo->manaCost > GetPower(POWER_MANA))
1685 continue;
1686 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1687 float range = GetSpellMaxRange(srange);
1688 float minrange = GetSpellMinRange(srange);
1690 float dist = GetCombatDistance(pVictim);
1692 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1693 // continue;
1694 if( dist > range || dist < minrange )
1695 continue;
1696 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1697 continue;
1698 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1699 continue;
1700 return spellInfo;
1702 return NULL;
1705 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1707 // gamemaster in GM mode see all, including ghosts
1708 if(pl->isGameMaster())
1709 return true;
1711 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1712 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1714 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1715 return false;
1716 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1719 // Dead player see live creatures near own corpse
1720 if(isAlive())
1722 Corpse *corpse = pl->GetCorpse();
1723 if(corpse)
1725 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1726 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1727 return true;
1731 // Dead player see Spirit Healer or Spirit Guide
1732 if(isSpiritService())
1733 return true;
1735 // and not see any other
1736 return false;
1739 void Creature::CallAssistance()
1741 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1743 SetNoCallAssistance(true);
1745 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1746 if(radius > 0)
1748 std::list<Creature*> assistList;
1751 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1752 Cell cell(p);
1753 cell.data.Part.reserved = ALL_DISTRICT;
1754 cell.SetNoCreate();
1756 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1757 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1759 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1761 CellLock<GridReadGuard> cell_lock(cell, p);
1762 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1765 if (!assistList.empty())
1767 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1768 while (!assistList.empty())
1770 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1771 e->AddAssistant((*assistList.begin())->GetGUID());
1772 assistList.pop_front();
1774 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1780 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const
1782 // we don't need help from zombies :)
1783 if (!isAlive())
1784 return false;
1786 // skip fighting creature
1787 if (isInCombat())
1788 return false;
1790 // only free creature
1791 if (GetCharmerOrOwnerGUID())
1792 return false;
1794 // only from same creature faction
1795 if (checkfaction)
1797 if (getFaction() != u->getFaction())
1798 return false;
1800 else
1802 if (!IsFriendlyTo(u))
1803 return false;
1806 // skip non hostile to caster enemy creatures
1807 if (!IsHostileTo(enemy))
1808 return false;
1810 return true;
1813 void Creature::SaveRespawnTime()
1815 if(isPet() || !m_DBTableGuid)
1816 return;
1818 if(m_respawnTime > time(NULL)) // dead (no corpse)
1819 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1820 else if(m_deathTimer > 0) // dead (corpse)
1821 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/IN_MILISECONDS);
1824 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1826 if(!pVictim)
1827 return true;
1829 if(!pVictim->IsInMap(this))
1830 return true;
1832 if(!pVictim->isTargetableForAttack())
1833 return true;
1835 if(!pVictim->isInAccessablePlaceFor(this))
1836 return true;
1838 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1839 return false;
1841 float AttackDist = GetAttackDistance(pVictim);
1842 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1844 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1845 return !pVictim->IsWithinDist3d(CombatStartX,CombatStartY,CombatStartZ,
1846 ThreatRadius > AttackDist ? ThreatRadius : AttackDist);
1849 CreatureDataAddon const* Creature::GetCreatureAddon() const
1851 if (m_DBTableGuid)
1853 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1854 return addon;
1857 // dependent from heroic mode entry
1858 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1861 //creature_addon table
1862 bool Creature::LoadCreaturesAddon(bool reload)
1864 CreatureDataAddon const *cainfo = GetCreatureAddon();
1865 if(!cainfo)
1866 return false;
1868 if (cainfo->mount != 0)
1869 Mount(cainfo->mount);
1871 if (cainfo->bytes1 != 0)
1872 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1874 if (cainfo->bytes2 != 0)
1875 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1877 if (cainfo->emote != 0)
1878 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1880 if (cainfo->move_flags != 0)
1881 SetUnitMovementFlags(cainfo->move_flags);
1883 if(cainfo->auras)
1885 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1887 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1888 if (!AdditionalSpellInfo)
1890 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1891 continue;
1894 // skip already applied aura
1895 if(HasAura(cAura->spell_id,cAura->effect_idx))
1897 if(!reload)
1898 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);
1900 continue;
1903 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1904 AddAura(AdditionalAura);
1905 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1908 return true;
1911 /// Send a message to LocalDefense channel for players opposition team in the zone
1912 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1914 uint32 enemy_team = attacker->GetTeam();
1916 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1917 data << (uint32)GetZoneId();
1918 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1921 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1923 m_CreatureSpellCooldowns[spell_id] = end_time;
1926 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1928 m_CreatureCategoryCooldowns[category] = apply_time;
1931 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1933 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1934 if(!spellInfo)
1935 return;
1937 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1938 if(cooldown)
1939 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1941 if(spellInfo->Category)
1942 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1944 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1947 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1949 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1950 if(!spellInfo)
1951 return false;
1953 // check global cooldown if spell affected by it
1954 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1955 return true;
1957 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1958 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1961 bool Creature::HasSpellCooldown(uint32 spell_id) const
1963 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1964 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1967 bool Creature::IsInEvadeMode() const
1969 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1972 bool Creature::HasSpell(uint32 spellID) const
1974 uint8 i;
1975 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1976 if(spellID == m_spells[i])
1977 break;
1978 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1981 time_t Creature::GetRespawnTimeEx() const
1983 time_t now = time(NULL);
1984 if(m_respawnTime > now) // dead (no corpse)
1985 return m_respawnTime;
1986 else if(m_deathTimer > 0) // dead (corpse)
1987 return now+m_respawnDelay+m_deathTimer/IN_MILISECONDS;
1988 else
1989 return now;
1992 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1994 if (m_DBTableGuid)
1996 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1998 x = data->posX;
1999 y = data->posY;
2000 z = data->posZ;
2001 if(ori)
2002 *ori = data->orientation;
2003 if(dist)
2004 *dist = data->spawndist;
2006 return;
2010 x = GetPositionX();
2011 y = GetPositionY();
2012 z = GetPositionZ();
2013 if(ori)
2014 *ori = GetOrientation();
2015 if(dist)
2016 *dist = 0;
2019 void Creature::AllLootRemovedFromCorpse()
2021 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
2023 uint32 nDeathTimer;
2025 CreatureInfo const *cinfo = GetCreatureInfo();
2027 // corpse was not skinnable -> apply corpse looted timer
2028 if (!cinfo || !cinfo->SkinLootId)
2029 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
2030 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
2031 else
2032 nDeathTimer = 0;
2034 // update death timer only if looted timer is shorter
2035 if (m_deathTimer > nDeathTimer)
2036 m_deathTimer = nDeathTimer;
2040 uint32 Creature::getLevelForTarget( Unit const* target ) const
2042 if(!isWorldBoss())
2043 return Unit::getLevelForTarget(target);
2045 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
2046 if(level < 1)
2047 return 1;
2048 if(level > 255)
2049 return 255;
2050 return level;
2053 std::string Creature::GetAIName() const
2055 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
2058 std::string Creature::GetScriptName() const
2060 return objmgr.GetScriptName(GetScriptId());
2063 uint32 Creature::GetScriptId() const
2065 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2068 VendorItemData const* Creature::GetVendorItems() const
2070 return objmgr.GetNpcVendorItemList(GetEntry());
2073 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2075 if(!vItem->maxcount)
2076 return vItem->maxcount;
2078 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2079 for(; itr != m_vendorItemCounts.end(); ++itr)
2080 if(itr->itemId==vItem->item)
2081 break;
2083 if(itr == m_vendorItemCounts.end())
2084 return vItem->maxcount;
2086 VendorItemCount* vCount = &*itr;
2088 time_t ptime = time(NULL);
2090 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2092 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2094 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2095 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2097 m_vendorItemCounts.erase(itr);
2098 return vItem->maxcount;
2101 vCount->count += diff * pProto->BuyCount;
2102 vCount->lastIncrementTime = ptime;
2105 return vCount->count;
2108 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2110 if(!vItem->maxcount)
2111 return 0;
2113 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2114 for(; itr != m_vendorItemCounts.end(); ++itr)
2115 if(itr->itemId==vItem->item)
2116 break;
2118 if(itr == m_vendorItemCounts.end())
2120 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2121 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2122 return new_count;
2125 VendorItemCount* vCount = &*itr;
2127 time_t ptime = time(NULL);
2129 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2131 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2133 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2134 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2135 vCount->count += diff * pProto->BuyCount;
2136 else
2137 vCount->count = vItem->maxcount;
2140 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2141 vCount->lastIncrementTime = ptime;
2142 return vCount->count;
2145 TrainerSpellData const* Creature::GetTrainerSpells() const
2147 return objmgr.GetNpcTrainerSpells(GetEntry());
2150 // overwrite WorldObject function for proper name localization
2151 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2153 if (loc_idx >= 0)
2155 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2156 if (cl)
2158 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2159 return cl->Name[loc_idx].c_str();
2163 return GetName();
2166 void Creature::SetActiveObjectState( bool on )
2168 if(m_isActiveObject==on)
2169 return;
2171 bool world = IsInWorld();
2173 Map* map;
2174 if(world)
2176 map = GetMap();
2177 map->Remove(this,false);
2180 m_isActiveObject = on;
2182 if(world)
2183 map->Add(this);