[7717] Use more safe code in EventAI.
[AHbot.git] / src / game / Creature.cpp
blobca5fb4a133d2cf74308e3727ce7409da19d0815d
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 Unit* victim = Unit::GetUnit(m_owner, m_victim);
89 if (victim)
91 while (!m_assistants.empty())
93 Creature* assistant = (Creature*)Unit::GetUnit(m_owner, *m_assistants.begin());
94 m_assistants.pop_front();
96 if (assistant && assistant->CanAssistTo(&m_owner, victim))
98 assistant->SetNoCallAssistance(true);
99 if(assistant->AI())
100 assistant->AI()->AttackStart(victim);
104 return true;
107 Creature::Creature() :
108 Unit(), i_AI(NULL),
109 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
110 m_lootMoney(0), m_lootRecipient(0),
111 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
112 m_gossipOptionLoaded(false), m_isPet(false), m_isVehicle(false), m_isTotem(false),
113 m_defaultMovementType(IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0), m_AlreadyCallAssistance(false),
114 m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),
115 m_creatureInfo(NULL), m_isActiveObject(false)
117 m_regenTimer = 200;
118 m_valuesCount = UNIT_END;
120 for(int i =0; i<4; ++i)
121 m_spells[i] = 0;
123 m_CreatureSpellCooldowns.clear();
124 m_CreatureCategoryCooldowns.clear();
125 m_GlobalCooldown = 0;
126 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
129 Creature::~Creature()
131 CleanupsBeforeDelete();
133 m_vendorItemCounts.clear();
135 delete i_AI;
136 i_AI = NULL;
139 void Creature::AddToWorld()
141 ///- Register the creature for guid lookup
142 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
143 Unit::AddToWorld();
146 void Creature::RemoveFromWorld()
148 ///- Remove the creature from the accessor
149 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
150 Unit::RemoveFromWorld();
153 void Creature::RemoveCorpse()
155 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
156 return;
158 m_deathTimer = 0;
159 setDeathState(DEAD);
160 ObjectAccessor::UpdateObjectVisibility(this);
161 loot.clear();
162 m_respawnTime = time(NULL) + m_respawnDelay;
164 float x,y,z,o;
165 GetRespawnCoord(x, y, z, &o);
166 GetMap()->CreatureRelocation(this,x,y,z,o);
170 * change the entry of creature until respawn
172 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
174 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
175 if(!normalInfo)
177 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
178 return false;
181 // get heroic mode entry
182 uint32 actualEntry = Entry;
183 CreatureInfo const *cinfo = normalInfo;
184 if(normalInfo->HeroicEntry)
186 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
187 if(map && map->IsHeroic())
189 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
190 if(!cinfo)
192 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
193 return false;
198 SetEntry(Entry); // normal entry always
199 m_creatureInfo = cinfo; // map mode related always
201 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
203 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
204 return false;
207 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
208 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
209 if (!minfo)
211 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
212 return false;
214 else
215 display_id = minfo->modelid; // it can be different (for another gender)
217 SetDisplayId(display_id);
218 SetNativeDisplayId(display_id);
219 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
221 // Load creature equipment
222 if(!data || data->equipmentId == 0)
223 { // use default from the template
224 LoadEquipment(cinfo->equipmentId);
226 else if(data && data->equipmentId != -1)
227 { // override, -1 means no equipment
228 LoadEquipment(data->equipmentId);
231 SetName(normalInfo->Name); // at normal entry always
233 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
234 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
236 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
238 SetSpeed(MOVE_WALK, cinfo->speed );
239 SetSpeed(MOVE_RUN, cinfo->speed );
240 SetSpeed(MOVE_SWIM, cinfo->speed );
242 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
244 // checked at loading
245 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
246 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
247 m_defaultMovementType = IDLE_MOTION_TYPE;
249 return true;
252 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
254 if(!InitEntry(Entry,team,data))
255 return false;
257 m_regenHealth = GetCreatureInfo()->RegenHealth;
259 // creatures always have melee weapon ready if any
260 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
262 SelectLevel(GetCreatureInfo());
263 if (team == HORDE)
264 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
265 else
266 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
268 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
270 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
271 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
272 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
274 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
275 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
277 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
278 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
279 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
280 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
281 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
282 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
283 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
285 SetCanModifyStats(true);
286 UpdateAllStats();
288 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
289 if (factionTemplate) // check and error show at loading templates
291 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
292 if (factionEntry)
293 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
294 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
295 SetPvP(true);
298 for(int i=0; i < CREATURE_MAX_SPELLS; ++i)
299 m_spells[i] = GetCreatureInfo()->spells[i];
301 return true;
304 void Creature::Update(uint32 diff)
306 if(m_GlobalCooldown <= diff)
307 m_GlobalCooldown = 0;
308 else
309 m_GlobalCooldown -= diff;
311 switch( m_deathState )
313 case JUST_ALIVED:
314 // Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
315 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
316 break;
317 case JUST_DIED:
318 // Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
319 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
320 break;
321 case DEAD:
323 if( m_respawnTime <= time(NULL) )
325 DEBUG_LOG("Respawning...");
326 m_respawnTime = 0;
327 lootForPickPocketed = false;
328 lootForBody = false;
330 if(m_originalEntry != GetEntry())
331 UpdateEntry(m_originalEntry);
333 CreatureInfo const *cinfo = GetCreatureInfo();
335 SelectLevel(cinfo);
336 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
337 if (m_isDeadByDefault)
339 setDeathState(JUST_DIED);
340 SetHealth(0);
341 i_motionMaster.Clear();
342 clearUnitState(UNIT_STAT_ALL_STATE);
343 LoadCreaturesAddon(true);
345 else
346 setDeathState( JUST_ALIVED );
348 //Call AI respawn virtual function
349 i_AI->JustRespawned();
351 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), GetTypeId());
352 if (poolid)
353 poolhandler.UpdatePool(poolid, GetGUIDLow(), GetTypeId());
354 else
355 GetMap()->Add(this);
357 break;
359 case CORPSE:
361 if (m_isDeadByDefault)
362 break;
364 if( m_deathTimer <= diff )
366 RemoveCorpse();
367 DEBUG_LOG("Removing corpse... %u ", GetEntry());
369 else
371 m_deathTimer -= diff;
372 if (m_groupLootTimer && lootingGroupLeaderGUID)
374 if(diff <= m_groupLootTimer)
376 m_groupLootTimer -= diff;
378 else
380 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
381 if (group)
382 group->EndRoll();
383 m_groupLootTimer = 0;
384 lootingGroupLeaderGUID = 0;
389 break;
391 case ALIVE:
393 if (m_isDeadByDefault)
395 if( m_deathTimer <= diff )
397 RemoveCorpse();
398 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
400 else
402 m_deathTimer -= diff;
406 Unit::Update( diff );
408 // creature can be dead after Unit::Update call
409 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
410 if(!isAlive())
411 break;
413 if(!IsInEvadeMode())
415 // do not allow the AI to be changed during update
416 m_AI_locked = true;
417 i_AI->UpdateAI(diff);
418 m_AI_locked = false;
421 // creature can be dead after UpdateAI call
422 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
423 if(!isAlive())
424 break;
425 if(m_regenTimer > 0)
427 if(diff >= m_regenTimer)
428 m_regenTimer = 0;
429 else
430 m_regenTimer -= diff;
432 if (m_regenTimer != 0)
433 break;
435 if (!isInCombat() || IsPolymorphed())
436 RegenerateHealth();
438 RegenerateMana();
440 m_regenTimer = 2000;
441 break;
443 case DEAD_FALLING:
445 if (!FallGround())
446 setDeathState(JUST_DIED);
448 default:
449 break;
453 void Creature::RegenerateMana()
455 uint32 curValue = GetPower(POWER_MANA);
456 uint32 maxValue = GetMaxPower(POWER_MANA);
458 if (curValue >= maxValue)
459 return;
461 uint32 addvalue = 0;
463 // Combat and any controlled creature
464 if (isInCombat() || GetCharmerOrOwnerGUID())
466 if(!IsUnderLastManaUseEffect())
468 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
469 float Spirit = GetStat(STAT_SPIRIT);
471 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
474 else
475 addvalue = maxValue/3;
477 ModifyPower(POWER_MANA, addvalue);
480 void Creature::RegenerateHealth()
482 if (!isRegeneratingHealth())
483 return;
485 uint32 curValue = GetHealth();
486 uint32 maxValue = GetMaxHealth();
488 if (curValue >= maxValue)
489 return;
491 uint32 addvalue = 0;
493 // Not only pet, but any controlled creature
494 if(GetCharmerOrOwnerGUID())
496 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
497 float Spirit = GetStat(STAT_SPIRIT);
499 if( GetPower(POWER_MANA) > 0 )
500 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
501 else
502 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
504 else
505 addvalue = maxValue/3;
507 ModifyHealth(addvalue);
510 bool Creature::AIM_Initialize()
512 // make sure nothing can change the AI during AI update
513 if(m_AI_locked)
515 sLog.outDebug("AIM_Initialize: failed to init, locked.");
516 return false;
519 CreatureAI * oldAI = i_AI;
520 i_motionMaster.Initialize();
521 i_AI = FactorySelector::selectAI(this);
522 if (oldAI)
523 delete oldAI;
524 return true;
527 bool Creature::Create (uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 team, const CreatureData *data)
529 SetMapId(map->GetId());
530 SetInstanceId(map->GetInstanceId());
531 SetPhaseMask(phaseMask,false);
533 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
534 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
536 if (bResult)
538 switch (GetCreatureInfo()->rank)
540 case CREATURE_ELITE_RARE:
541 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
542 break;
543 case CREATURE_ELITE_ELITE:
544 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
545 break;
546 case CREATURE_ELITE_RAREELITE:
547 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
548 break;
549 case CREATURE_ELITE_WORLDBOSS:
550 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
551 break;
552 default:
553 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
554 break;
556 LoadCreaturesAddon();
559 return bResult;
562 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
564 if(!isTrainer())
565 return false;
567 TrainerSpellData const* trainer_spells = GetTrainerSpells();
569 if(!trainer_spells || trainer_spells->spellList.empty())
571 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
572 GetGUIDLow(),GetEntry());
573 return false;
576 switch(GetCreatureInfo()->trainer_type)
578 case TRAINER_TYPE_CLASS:
579 if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
581 if(msg)
583 pPlayer->PlayerTalkClass->ClearMenus();
584 switch(GetCreatureInfo()->classNum)
586 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
587 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
588 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
589 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
590 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
591 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
592 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
593 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
594 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
597 return false;
599 break;
600 case TRAINER_TYPE_PETS:
601 if(pPlayer->getClass()!=CLASS_HUNTER)
603 pPlayer->PlayerTalkClass->ClearMenus();
604 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
605 return false;
607 break;
608 case TRAINER_TYPE_MOUNTS:
609 if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
611 if(msg)
613 pPlayer->PlayerTalkClass->ClearMenus();
614 switch(GetCreatureInfo()->classNum)
616 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
617 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
618 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
619 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
620 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
621 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
622 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
623 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
624 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
625 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
628 return false;
630 break;
631 case TRAINER_TYPE_TRADESKILLS:
632 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
634 if(msg)
636 pPlayer->PlayerTalkClass->ClearMenus();
637 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
639 return false;
641 break;
642 default:
643 return false; // checked and error output at creature_template loading
645 return true;
648 bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const
650 if(!isBattleMaster())
651 return false;
653 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
654 if(!msg)
655 return pPlayer->GetBGAccessByLevel(bgTypeId);
657 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
659 pPlayer->PlayerTalkClass->ClearMenus();
660 switch(bgTypeId)
662 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
663 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
664 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
665 case BATTLEGROUND_EY:
666 case BATTLEGROUND_NA:
667 case BATTLEGROUND_BE:
668 case BATTLEGROUND_AA:
669 case BATTLEGROUND_RL:
670 case BATTLEGROUND_SA:
671 case BATTLEGROUND_DS:
672 case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
673 default: break;
675 return false;
677 return true;
680 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
682 return pPlayer->getLevel() >= 10
683 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
684 && pPlayer->getClass() == GetCreatureInfo()->classNum;
687 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
689 PlayerMenu* pm=pPlayer->PlayerTalkClass;
690 pm->ClearMenus();
692 // lazy loading single time at use
693 LoadGossipOptions();
695 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
697 GossipOption* gso=&*i;
698 if(gso->GossipId == gossipid)
700 bool cantalking=true;
701 if(gso->Id==1)
703 uint32 textid=GetNpcTextId();
704 GossipText const* gossiptext=objmgr.GetGossipText(textid);
705 if(!gossiptext)
706 cantalking=false;
708 else
710 switch (gso->Action)
712 case GOSSIP_OPTION_QUESTGIVER:
713 pPlayer->PrepareQuestMenu(GetGUID());
714 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
715 cantalking=false;
716 //pm->GetQuestMenu()->ClearMenu();
717 break;
718 case GOSSIP_OPTION_ARMORER:
719 cantalking=false; // added in special mode
720 break;
721 case GOSSIP_OPTION_SPIRITHEALER:
722 if( !pPlayer->isDead() )
723 cantalking=false;
724 break;
725 case GOSSIP_OPTION_VENDOR:
727 VendorItemData const* vItems = GetVendorItems();
728 if(!vItems || vItems->Empty())
730 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
731 GetGUIDLow(),GetEntry());
732 cantalking=false;
734 break;
736 case GOSSIP_OPTION_TRAINER:
737 if(!isCanTrainingOf(pPlayer,false))
738 cantalking=false;
739 break;
740 case GOSSIP_OPTION_UNLEARNTALENTS:
741 if(!isCanTrainingAndResetTalentsOf(pPlayer))
742 cantalking=false;
743 break;
744 case GOSSIP_OPTION_UNLEARNPETSKILLS:
745 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
746 cantalking=false;
747 break;
748 case GOSSIP_OPTION_TAXIVENDOR:
749 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
750 return;
751 break;
752 case GOSSIP_OPTION_BATTLEFIELD:
753 if(!isCanInteractWithBattleMaster(pPlayer,false))
754 cantalking=false;
755 break;
756 case GOSSIP_OPTION_SPIRITGUIDE:
757 case GOSSIP_OPTION_INNKEEPER:
758 case GOSSIP_OPTION_BANKER:
759 case GOSSIP_OPTION_PETITIONER:
760 case GOSSIP_OPTION_STABLEPET:
761 case GOSSIP_OPTION_TABARDDESIGNER:
762 case GOSSIP_OPTION_AUCTIONEER:
763 break; // no checks
764 default:
765 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
766 break;
770 //note for future dev: should have database fields for BoxMessage & BoxMoney
771 if(!gso->OptionText.empty() && cantalking)
773 std::string OptionText = gso->OptionText;
774 std::string BoxText = gso->BoxText;
775 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
776 if (loc_idx >= 0)
778 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
779 if (no)
781 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
782 OptionText=no->OptionText[loc_idx];
783 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
784 BoxText=no->BoxText[loc_idx];
787 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
792 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
793 if(pm->Empty())
795 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
797 isCanTrainingOf(pPlayer,true); // output error message if need
799 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
801 isCanInteractWithBattleMaster(pPlayer,true); // output error message if need
806 void Creature::sendPreparedGossip(Player* player)
808 if(!player)
809 return;
811 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
812 if (!HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !player->PlayerTalkClass->GetQuestMenu().Empty())
814 player->SendPreparedQuest(GetGUID());
815 return;
818 // in case non empty gossip menu (that not included quests list size) show it
819 // (quest entries from quest menu will be included in list)
820 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
823 void Creature::OnGossipSelect(Player* player, uint32 option)
825 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
827 if(option >= gossipmenu.MenuItemCount())
828 return;
830 uint32 action=gossipmenu.GetItem(option).m_gAction;
831 uint32 zoneid=GetZoneId();
832 uint64 guid=GetGUID();
834 GossipOption const *gossip=GetGossipOption( action );
835 if(!gossip)
837 zoneid=0;
838 gossip=GetGossipOption( action );
839 if(!gossip)
840 return;
843 switch (gossip->Action)
845 case GOSSIP_OPTION_GOSSIP:
847 uint32 textid = GetGossipTextId(action, zoneid);
848 if (textid == 0)
849 textid=GetNpcTextId();
851 player->PlayerTalkClass->CloseGossip();
852 player->PlayerTalkClass->SendTalking(textid);
853 break;
855 case GOSSIP_OPTION_SPIRITHEALER:
856 if (player->isDead())
857 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
858 break;
859 case GOSSIP_OPTION_QUESTGIVER:
860 player->PrepareQuestMenu( guid );
861 player->SendPreparedQuest( guid );
862 break;
863 case GOSSIP_OPTION_VENDOR:
864 case GOSSIP_OPTION_ARMORER:
865 player->GetSession()->SendListInventory(guid);
866 break;
867 case GOSSIP_OPTION_STABLEPET:
868 player->GetSession()->SendStablePet(guid);
869 break;
870 case GOSSIP_OPTION_TRAINER:
871 player->GetSession()->SendTrainerList(guid);
872 break;
873 case GOSSIP_OPTION_UNLEARNTALENTS:
874 player->PlayerTalkClass->CloseGossip();
875 player->SendTalentWipeConfirm(guid);
876 break;
877 case GOSSIP_OPTION_UNLEARNPETSKILLS:
878 player->PlayerTalkClass->CloseGossip();
879 player->SendPetSkillWipeConfirm();
880 break;
881 case GOSSIP_OPTION_TAXIVENDOR:
882 player->GetSession()->SendTaxiMenu(this);
883 break;
884 case GOSSIP_OPTION_INNKEEPER:
885 player->PlayerTalkClass->CloseGossip();
886 player->SetBindPoint( guid );
887 break;
888 case GOSSIP_OPTION_BANKER:
889 player->GetSession()->SendShowBank( guid );
890 break;
891 case GOSSIP_OPTION_PETITIONER:
892 player->PlayerTalkClass->CloseGossip();
893 player->GetSession()->SendPetitionShowList( guid );
894 break;
895 case GOSSIP_OPTION_TABARDDESIGNER:
896 player->PlayerTalkClass->CloseGossip();
897 player->GetSession()->SendTabardVendorActivate( guid );
898 break;
899 case GOSSIP_OPTION_AUCTIONEER:
900 player->GetSession()->SendAuctionHello( guid, this );
901 break;
902 case GOSSIP_OPTION_SPIRITGUIDE:
903 case GOSSIP_GUARD_SPELLTRAINER:
904 case GOSSIP_GUARD_SKILLTRAINER:
905 prepareGossipMenu( player,gossip->Id );
906 sendPreparedGossip( player );
907 break;
908 case GOSSIP_OPTION_BATTLEFIELD:
910 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
911 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
912 break;
914 default:
915 OnPoiSelect( player, gossip );
916 break;
921 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
923 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
925 Poi_Icon icon = ICON_POI_BLANK;
926 //need add more case.
927 switch(gossip->Action)
929 case GOSSIP_GUARD_BANK:
930 icon=ICON_POI_SMALL_HOUSE;
931 break;
932 case GOSSIP_GUARD_RIDE:
933 icon=ICON_POI_RWHORSE;
934 break;
935 case GOSSIP_GUARD_GUILD:
936 icon=ICON_POI_BLUETOWER;
937 break;
938 default:
939 icon=ICON_POI_GREYTOWER;
940 break;
942 uint32 textid = GetGossipTextId( gossip->Action, GetZoneId() );
943 player->PlayerTalkClass->SendTalking(textid);
944 // std::string areaname= gossip->OptionText;
945 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
949 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
951 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
953 if(!result)
954 return 0;
956 Field *fields = result->Fetch();
957 uint32 id = fields[0].GetUInt32();
959 delete result;
961 return id;
964 uint32 Creature::GetNpcTextId()
966 if (!m_DBTableGuid)
967 return DEFAULT_GOSSIP_MESSAGE;
969 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
970 return pos;
972 return DEFAULT_GOSSIP_MESSAGE;
975 GossipOption const* Creature::GetGossipOption( uint32 id ) const
977 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); ++i )
979 if(i->Action==id )
980 return &*i;
982 return NULL;
985 void Creature::LoadGossipOptions()
987 if(m_gossipOptionLoaded)
988 return;
990 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
992 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
993 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
994 if(i->NpcFlag & npcflags)
995 addGossipOption(*i);
997 m_gossipOptionLoaded = true;
1000 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1002 /* uint32 timeElap = getMSTime();
1003 if ((timeElap - m_startMove) < m_moveTime)
1005 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1006 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1008 else
1010 oX = dX;
1011 oY = dY;
1014 dX = x;
1015 dY = y;
1016 m_orientation = atan2((oY - dY), (oX - dX));
1018 m_startMove = getMSTime();
1019 m_moveTime = time;*/
1020 SendMonsterMove(x, y, z, type, MovementFlags, time);
1023 Player *Creature::GetLootRecipient() const
1025 if (!m_lootRecipient) return NULL;
1026 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1029 void Creature::SetLootRecipient(Unit *unit)
1031 // set the player whose group should receive the right
1032 // to loot the creature after it dies
1033 // should be set to NULL after the loot disappears
1035 if (!unit)
1037 m_lootRecipient = 0;
1038 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1039 return;
1042 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1043 if(!player) // normal creature, no player involved
1044 return;
1046 m_lootRecipient = player->GetGUID();
1047 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1050 void Creature::SaveToDB()
1052 // this should only be used when the creature has already been loaded
1053 // preferably after adding to map, because mapid may not be valid otherwise
1054 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1055 if(!data)
1057 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1058 return;
1061 SaveToDB(GetMapId(), data->spawnMask,GetPhaseMask());
1064 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
1066 // update in loaded data
1067 if (!m_DBTableGuid)
1068 m_DBTableGuid = GetGUIDLow();
1069 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1071 uint32 displayId = GetNativeDisplayId();
1073 // check if it's a custom model and if not, use 0 for displayId
1074 CreatureInfo const *cinfo = GetCreatureInfo();
1075 if(cinfo)
1077 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1079 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1080 if(!minfo || displayId != minfo->modelid_other_gender)
1082 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1083 if(minfo && displayId == minfo->modelid_other_gender)
1084 displayId = 0;
1086 else
1087 displayId = 0;
1089 else
1090 displayId = 0;
1093 // data->guid = guid don't must be update at save
1094 data.id = GetEntry();
1095 data.mapid = mapid;
1096 data.phaseMask = phaseMask;
1097 data.displayid = displayId;
1098 data.equipmentId = GetEquipmentId();
1099 data.posX = GetPositionX();
1100 data.posY = GetPositionY();
1101 data.posZ = GetPositionZ();
1102 data.orientation = GetOrientation();
1103 data.spawntimesecs = m_respawnDelay;
1104 // prevent add data integrity problems
1105 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1106 data.currentwaypoint = 0;
1107 data.curhealth = GetHealth();
1108 data.curmana = GetPower(POWER_MANA);
1109 data.is_dead = m_isDeadByDefault;
1110 // prevent add data integrity problems
1111 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1112 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1113 data.spawnMask = spawnMask;
1115 // updated in DB
1116 WorldDatabase.BeginTransaction();
1118 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1120 std::ostringstream ss;
1121 ss << "INSERT INTO creature VALUES ("
1122 << m_DBTableGuid << ","
1123 << GetEntry() << ","
1124 << mapid <<","
1125 << uint32(spawnMask) << "," // cast to prevent save as symbol
1126 << uint16(GetPhaseMask()) << "," // prevent out of range error
1127 << displayId <<","
1128 << GetEquipmentId() <<","
1129 << GetPositionX() << ","
1130 << GetPositionY() << ","
1131 << GetPositionZ() << ","
1132 << GetOrientation() << ","
1133 << m_respawnDelay << "," //respawn time
1134 << (float) m_respawnradius << "," //spawn distance (float)
1135 << (uint32) (0) << "," //currentwaypoint
1136 << GetHealth() << "," //curhealth
1137 << GetPower(POWER_MANA) << "," //curmana
1138 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1139 << GetDefaultMovementType() << ")"; //default movement generator type
1141 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1143 WorldDatabase.CommitTransaction();
1146 void Creature::SelectLevel(const CreatureInfo *cinfo)
1148 uint32 rank = isPet()? 0 : cinfo->rank;
1150 // level
1151 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1152 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1153 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1154 SetLevel(level);
1156 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1158 // health
1159 float healthmod = _GetHealthMod(rank);
1161 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1162 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1163 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1165 SetCreateHealth(health);
1166 SetMaxHealth(health);
1167 SetHealth(health);
1169 // mana
1170 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1171 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1172 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1174 SetCreateMana(mana);
1175 SetMaxPower(POWER_MANA, mana); //MAX Mana
1176 SetPower(POWER_MANA, mana);
1178 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1179 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1181 // damage
1182 float damagemod = _GetDamageMod(rank);
1184 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1185 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1187 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1188 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1190 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1193 float Creature::_GetHealthMod(int32 Rank)
1195 switch (Rank) // define rates for each elite rank
1197 case CREATURE_ELITE_NORMAL:
1198 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1199 case CREATURE_ELITE_ELITE:
1200 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1201 case CREATURE_ELITE_RAREELITE:
1202 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1203 case CREATURE_ELITE_WORLDBOSS:
1204 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1205 case CREATURE_ELITE_RARE:
1206 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1207 default:
1208 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1212 float Creature::_GetDamageMod(int32 Rank)
1214 switch (Rank) // define rates for each elite rank
1216 case CREATURE_ELITE_NORMAL:
1217 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1218 case CREATURE_ELITE_ELITE:
1219 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1220 case CREATURE_ELITE_RAREELITE:
1221 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1222 case CREATURE_ELITE_WORLDBOSS:
1223 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1224 case CREATURE_ELITE_RARE:
1225 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1226 default:
1227 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1231 float Creature::GetSpellDamageMod(int32 Rank)
1233 switch (Rank) // define rates for each elite rank
1235 case CREATURE_ELITE_NORMAL:
1236 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1237 case CREATURE_ELITE_ELITE:
1238 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1239 case CREATURE_ELITE_RAREELITE:
1240 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1241 case CREATURE_ELITE_WORLDBOSS:
1242 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1243 case CREATURE_ELITE_RARE:
1244 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1245 default:
1246 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1250 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1252 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1253 if(!cinfo)
1255 sLog.outErrorDb("Creature entry %u does not exist.", Entry);
1256 return false;
1258 m_originalEntry = Entry;
1260 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1262 if(!UpdateEntry(Entry, team, data))
1263 return false;
1265 //Notify the map's instance data.
1266 //Only works if you create the object in it, not if it is moves to that map.
1267 //Normally non-players do not teleport to other maps.
1268 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1269 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1271 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1274 return true;
1277 bool Creature::LoadFromDB(uint32 guid, Map *map)
1279 CreatureData const* data = objmgr.GetCreatureData(guid);
1281 if(!data)
1283 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1284 return false;
1287 m_DBTableGuid = guid;
1288 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1290 uint16 team = 0;
1291 if(!Create(guid,map,data->phaseMask,data->id,team,data))
1292 return false;
1294 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1296 if(!IsPositionValid())
1298 sLog.outError("Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1299 return false;
1302 m_respawnradius = data->spawndist;
1304 m_respawnDelay = data->spawntimesecs;
1305 m_isDeadByDefault = data->is_dead;
1306 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1308 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1309 if(m_respawnTime > time(NULL)) // not ready to respawn
1311 m_deathState = DEAD;
1312 if(canFly())
1314 float tz = GetMap()->GetHeight(data->posX,data->posY,data->posZ,false);
1315 if(data->posZ - tz > 0.1)
1316 Relocate(data->posX,data->posY,tz);
1319 else if(m_respawnTime) // respawn time set but expired
1321 m_respawnTime = 0;
1322 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1325 uint32 curhealth = data->curhealth;
1326 if(curhealth)
1328 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1329 if(curhealth < 1)
1330 curhealth = 1;
1333 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1334 SetPower(POWER_MANA,data->curmana);
1336 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1338 // checked at creature_template loading
1339 m_defaultMovementType = MovementGeneratorType(data->movementType);
1341 AIM_Initialize();
1342 return true;
1345 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1347 if(equip_entry == 0)
1349 if (force)
1351 for (uint8 i = 0; i < 3; i++)
1352 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
1353 m_equipmentId = 0;
1355 return;
1358 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1359 if (!einfo)
1360 return;
1362 m_equipmentId = equip_entry;
1363 for (uint8 i = 0; i < 3; i++)
1364 SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
1367 bool Creature::hasQuest(uint32 quest_id) const
1369 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1370 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1372 if(itr->second==quest_id)
1373 return true;
1375 return false;
1378 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1380 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1381 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1383 if(itr->second==quest_id)
1384 return true;
1386 return false;
1389 void Creature::DeleteFromDB()
1391 if (!m_DBTableGuid)
1393 sLog.outDebug("Trying to delete not saved creature!");
1394 return;
1397 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1398 objmgr.DeleteCreatureData(m_DBTableGuid);
1400 WorldDatabase.BeginTransaction();
1401 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1402 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1403 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1404 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1405 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1406 WorldDatabase.CommitTransaction();
1409 float Creature::GetAttackDistance(Unit const* pl) const
1411 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1412 if(aggroRate==0)
1413 return 0.0f;
1415 int32 playerlevel = pl->getLevelForTarget(this);
1416 int32 creaturelevel = getLevelForTarget(pl);
1418 int32 leveldif = playerlevel - creaturelevel;
1420 // "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."
1421 if ( leveldif < - 25)
1422 leveldif = -25;
1424 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1425 float RetDistance = 20;
1427 // "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
1428 // radius grow if playlevel < creaturelevel
1429 RetDistance -= (float)leveldif;
1431 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1433 // detect range auras
1434 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1436 // detected range auras
1437 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1440 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1441 if(RetDistance < 5)
1442 RetDistance = 5;
1444 return (RetDistance*aggroRate);
1447 void Creature::setDeathState(DeathState s)
1449 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1451 m_deathTimer = m_corpseDelay*IN_MILISECONDS;
1453 // always save boss respawn time at death to prevent crash cheating
1454 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1455 SaveRespawnTime();
1457 if (canFly() && FallGround())
1458 return;
1460 if(!IsStopped())
1461 StopMoving();
1463 Unit::setDeathState(s);
1465 if(s == JUST_DIED)
1467 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1468 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1470 if(!isPet() && GetCreatureInfo()->SkinLootId)
1471 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1472 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1474 if (canFly() && FallGround())
1475 return;
1477 Unit::setDeathState(CORPSE);
1479 if(s == JUST_ALIVED)
1481 SetHealth(GetMaxHealth());
1482 SetLootRecipient(NULL);
1483 Unit::setDeathState(ALIVE);
1484 CreatureInfo const *cinfo = GetCreatureInfo();
1485 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1486 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1487 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1488 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1489 clearUnitState(UNIT_STAT_ALL_STATE);
1490 i_motionMaster.Clear();
1491 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1492 LoadCreaturesAddon(true);
1496 bool Creature::FallGround()
1498 // Let's abort after we called this function one time
1499 if (getDeathState() == DEAD_FALLING)
1500 return false;
1502 // Let's do with no vmap because no way to get far distance with vmap high call
1503 float tz = GetMap()->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), false);
1505 // Abort too if the ground is very near
1506 if (fabs(GetPositionZ() - tz) < 0.1f)
1507 return false;
1509 Unit::setDeathState(DEAD_FALLING);
1510 GetMotionMaster()->MovePoint(0, GetPositionX(), GetPositionY(), tz);
1511 Relocate(GetPositionX(), GetPositionY(), tz);
1512 return true;
1515 void Creature::Respawn()
1517 RemoveCorpse();
1519 // forced recreate creature object at clients
1520 UnitVisibility currentVis = GetVisibility();
1521 SetVisibility(VISIBILITY_RESPAWN);
1522 ObjectAccessor::UpdateObjectVisibility(this);
1523 SetVisibility(currentVis); // restore visibility state
1524 ObjectAccessor::UpdateObjectVisibility(this);
1526 if(getDeathState()==DEAD)
1528 if (m_DBTableGuid)
1529 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1530 m_respawnTime = time(NULL); // respawn at next tick
1534 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo)
1536 if (!spellInfo)
1537 return false;
1539 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1540 return true;
1542 return Unit::IsImmunedToSpell(spellInfo);
1545 bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
1547 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1)))
1548 return true;
1550 return Unit::IsImmunedToSpellEffect(spellInfo, index);
1553 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1555 if(!pVictim)
1556 return NULL;
1558 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1560 if(!m_spells[i])
1561 continue;
1562 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1563 if(!spellInfo)
1565 sLog.outError("WORLD: unknown spell id %i", m_spells[i]);
1566 continue;
1569 bool bcontinue = true;
1570 for(uint32 j=0;j<3;j++)
1572 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1573 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1574 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1575 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1578 bcontinue = false;
1579 break;
1582 if(bcontinue) continue;
1584 if(spellInfo->manaCost > GetPower(POWER_MANA))
1585 continue;
1586 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1587 float range = GetSpellMaxRange(srange);
1588 float minrange = GetSpellMinRange(srange);
1590 float dist = GetCombatDistance(pVictim);
1592 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1593 // continue;
1594 if( dist > range || dist < minrange )
1595 continue;
1596 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1597 continue;
1598 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1599 continue;
1600 return spellInfo;
1602 return NULL;
1605 SpellEntry const *Creature::reachWithSpellCure(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_HEAL ) )
1626 bcontinue = false;
1627 break;
1630 if(bcontinue) continue;
1632 if(spellInfo->manaCost > GetPower(POWER_MANA))
1633 continue;
1634 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1635 float range = GetSpellMaxRange(srange);
1636 float minrange = GetSpellMinRange(srange);
1638 float dist = GetCombatDistance(pVictim);
1640 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1641 // continue;
1642 if( dist > range || dist < minrange )
1643 continue;
1644 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1645 continue;
1646 if(spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
1647 continue;
1648 return spellInfo;
1650 return NULL;
1653 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1655 // gamemaster in GM mode see all, including ghosts
1656 if(pl->isGameMaster())
1657 return true;
1659 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1660 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1662 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1663 return false;
1664 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1667 // Dead player see live creatures near own corpse
1668 if(isAlive())
1670 Corpse *corpse = pl->GetCorpse();
1671 if(corpse)
1673 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1674 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1675 return true;
1679 // Dead player see Spirit Healer or Spirit Guide
1680 if(isSpiritService())
1681 return true;
1683 // and not see any other
1684 return false;
1687 void Creature::CallAssistance()
1689 if( !m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed())
1691 SetNoCallAssistance(true);
1693 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
1694 if(radius > 0)
1696 std::list<Creature*> assistList;
1699 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1700 Cell cell(p);
1701 cell.data.Part.reserved = ALL_DISTRICT;
1702 cell.SetNoCreate();
1704 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1705 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(this, assistList, u_check);
1707 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1709 CellLock<GridReadGuard> cell_lock(cell, p);
1710 cell_lock->Visit(cell_lock, grid_creature_searcher, *GetMap());
1713 if (!assistList.empty())
1715 AssistDelayEvent *e = new AssistDelayEvent(getVictim()->GetGUID(), *this);
1716 while (!assistList.empty())
1718 // Pushing guids because in delay can happen some creature gets despawned => invalid pointer
1719 e->AddAssistant((*assistList.begin())->GetGUID());
1720 assistList.pop_front();
1722 m_Events.AddEvent(e, m_Events.CalculateTime(sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
1728 bool Creature::CanAssistTo(const Unit* u, const Unit* enemy) const
1730 // we don't need help from zombies :)
1731 if( !isAlive() )
1732 return false;
1734 // skip fighting creature
1735 if( isInCombat() )
1736 return false;
1738 // only from same creature faction
1739 if(getFaction() != u->getFaction() )
1740 return false;
1742 // only free creature
1743 if( GetCharmerOrOwnerGUID() )
1744 return false;
1746 // skip non hostile to caster enemy creatures
1747 if( !IsHostileTo(enemy) )
1748 return false;
1750 return true;
1753 void Creature::SaveRespawnTime()
1755 if(isPet() || !m_DBTableGuid)
1756 return;
1758 if(m_respawnTime > time(NULL)) // dead (no corpse)
1759 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1760 else if(m_deathTimer > 0) // dead (corpse)
1761 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/IN_MILISECONDS);
1764 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1766 if(!pVictim)
1767 return true;
1769 if(!pVictim->IsInMap(this))
1770 return true;
1772 if(!pVictim->isTargetableForAttack())
1773 return true;
1775 if(!pVictim->isInAccessablePlaceFor(this))
1776 return true;
1778 if(sMapStore.LookupEntry(GetMapId())->IsDungeon())
1779 return false;
1781 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1782 float AttackDist = GetAttackDistance(pVictim);
1783 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1785 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
1786 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1789 CreatureDataAddon const* Creature::GetCreatureAddon() const
1791 if (m_DBTableGuid)
1793 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1794 return addon;
1797 // dependent from heroic mode entry
1798 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1801 //creature_addon table
1802 bool Creature::LoadCreaturesAddon(bool reload)
1804 CreatureDataAddon const *cainfo = GetCreatureAddon();
1805 if(!cainfo)
1806 return false;
1808 if (cainfo->mount != 0)
1809 Mount(cainfo->mount);
1811 if (cainfo->bytes0 != 0)
1812 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1814 if (cainfo->bytes1 != 0)
1815 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1817 if (cainfo->bytes2 != 0)
1818 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1820 if (cainfo->emote != 0)
1821 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1823 if (cainfo->move_flags != 0)
1824 SetUnitMovementFlags(cainfo->move_flags);
1826 if(cainfo->auras)
1828 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1830 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1831 if (!AdditionalSpellInfo)
1833 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1834 continue;
1837 // skip already applied aura
1838 if(HasAura(cAura->spell_id,cAura->effect_idx))
1840 if(!reload)
1841 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);
1843 continue;
1846 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1847 AddAura(AdditionalAura);
1848 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1851 return true;
1854 /// Send a message to LocalDefense channel for players opposition team in the zone
1855 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1857 uint32 enemy_team = attacker->GetTeam();
1859 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1860 data << (uint32)GetZoneId();
1861 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1864 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1866 m_CreatureSpellCooldowns[spell_id] = end_time;
1869 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1871 m_CreatureCategoryCooldowns[category] = apply_time;
1874 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1876 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1877 if(!spellInfo)
1878 return;
1880 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1881 if(cooldown)
1882 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/IN_MILISECONDS);
1884 if(spellInfo->Category)
1885 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1887 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1890 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1893 if(!spellInfo)
1894 return false;
1896 // check global cooldown if spell affected by it
1897 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1898 return true;
1900 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1901 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / IN_MILISECONDS)) > time(NULL));
1904 bool Creature::HasSpellCooldown(uint32 spell_id) const
1906 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1907 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1910 bool Creature::IsInEvadeMode() const
1912 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1915 bool Creature::HasSpell(uint32 spellID) const
1917 uint8 i;
1918 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1919 if(spellID == m_spells[i])
1920 break;
1921 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1924 time_t Creature::GetRespawnTimeEx() const
1926 time_t now = time(NULL);
1927 if(m_respawnTime > now) // dead (no corpse)
1928 return m_respawnTime;
1929 else if(m_deathTimer > 0) // dead (corpse)
1930 return now+m_respawnDelay+m_deathTimer/IN_MILISECONDS;
1931 else
1932 return now;
1935 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1937 if (m_DBTableGuid)
1939 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1941 x = data->posX;
1942 y = data->posY;
1943 z = data->posZ;
1944 if(ori)
1945 *ori = data->orientation;
1946 if(dist)
1947 *dist = data->spawndist;
1949 return;
1953 x = GetPositionX();
1954 y = GetPositionY();
1955 z = GetPositionZ();
1956 if(ori)
1957 *ori = GetOrientation();
1958 if(dist)
1959 *dist = 0;
1962 void Creature::AllLootRemovedFromCorpse()
1964 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1966 uint32 nDeathTimer;
1968 CreatureInfo const *cinfo = GetCreatureInfo();
1970 // corpse was not skinnable -> apply corpse looted timer
1971 if (!cinfo || !cinfo->SkinLootId)
1972 nDeathTimer = (uint32)((m_corpseDelay * IN_MILISECONDS) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1973 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1974 else
1975 nDeathTimer = 0;
1977 // update death timer only if looted timer is shorter
1978 if (m_deathTimer > nDeathTimer)
1979 m_deathTimer = nDeathTimer;
1983 uint32 Creature::getLevelForTarget( Unit const* target ) const
1985 if(!isWorldBoss())
1986 return Unit::getLevelForTarget(target);
1988 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1989 if(level < 1)
1990 return 1;
1991 if(level > 255)
1992 return 255;
1993 return level;
1996 std::string Creature::GetAIName() const
1998 return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
2001 std::string Creature::GetScriptName() const
2003 return objmgr.GetScriptName(GetScriptId());
2006 uint32 Creature::GetScriptId() const
2008 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
2011 VendorItemData const* Creature::GetVendorItems() const
2013 return objmgr.GetNpcVendorItemList(GetEntry());
2016 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
2018 if(!vItem->maxcount)
2019 return vItem->maxcount;
2021 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2022 for(; itr != m_vendorItemCounts.end(); ++itr)
2023 if(itr->itemId==vItem->item)
2024 break;
2026 if(itr == m_vendorItemCounts.end())
2027 return vItem->maxcount;
2029 VendorItemCount* vCount = &*itr;
2031 time_t ptime = time(NULL);
2033 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2035 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2037 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2038 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
2040 m_vendorItemCounts.erase(itr);
2041 return vItem->maxcount;
2044 vCount->count += diff * pProto->BuyCount;
2045 vCount->lastIncrementTime = ptime;
2048 return vCount->count;
2051 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
2053 if(!vItem->maxcount)
2054 return 0;
2056 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
2057 for(; itr != m_vendorItemCounts.end(); ++itr)
2058 if(itr->itemId==vItem->item)
2059 break;
2061 if(itr == m_vendorItemCounts.end())
2063 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2064 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2065 return new_count;
2068 VendorItemCount* vCount = &*itr;
2070 time_t ptime = time(NULL);
2072 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2074 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2076 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2077 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2078 vCount->count += diff * pProto->BuyCount;
2079 else
2080 vCount->count = vItem->maxcount;
2083 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2084 vCount->lastIncrementTime = ptime;
2085 return vCount->count;
2088 TrainerSpellData const* Creature::GetTrainerSpells() const
2090 return objmgr.GetNpcTrainerSpells(GetEntry());
2093 // overwrite WorldObject function for proper name localization
2094 const char* Creature::GetNameForLocaleIdx(int32 loc_idx) const
2096 if (loc_idx >= 0)
2098 CreatureLocale const *cl = objmgr.GetCreatureLocale(GetEntry());
2099 if (cl)
2101 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
2102 return cl->Name[loc_idx].c_str();
2106 return GetName();
2109 void Creature::SetActiveObjectState( bool on )
2111 if(m_isActiveObject==on)
2112 return;
2114 bool world = IsInWorld();
2116 Map* map;
2117 if(world)
2119 map = GetMap();
2120 map->Remove(this,false);
2123 m_isActiveObject = on;
2125 if(world)
2126 map->Add(this);