[2008_10_31_01_mangos_creature_template.sql] Creature related code and DB cleanups.
[getmangos.git] / src / game / Creature.cpp
blobce5d9f797a676941973401f3faa2d03293f245d7
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "World.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "Creature.h"
27 #include "QuestDef.h"
28 #include "GossipDef.h"
29 #include "Player.h"
30 #include "Opcodes.h"
31 #include "Log.h"
32 #include "LootMgr.h"
33 #include "MapManager.h"
34 #include "CreatureAI.h"
35 #include "CreatureAISelector.h"
36 #include "Formulas.h"
37 #include "SpellAuras.h"
38 #include "WaypointMovementGenerator.h"
39 #include "InstanceData.h"
40 #include "BattleGround.h"
41 #include "Util.h"
42 #include "GridNotifiers.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
46 // apply implementation of the singletons
47 #include "Policies/SingletonImp.h"
49 void TrainerSpellData::Clear()
51 for (TrainerSpellList::iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
52 delete (*itr);
53 spellList.empty();
56 TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
58 for(TrainerSpellList::const_iterator itr = spellList.begin(); itr != spellList.end(); ++itr)
59 if((*itr)->spell == spell_id)
60 return *itr;
62 return NULL;
65 bool VendorItemData::RemoveItem( uint32 item_id )
67 for(VendorItemList::iterator i = m_items.begin(); i != m_items.end(); ++i )
69 if((*i)->item==item_id)
71 m_items.erase(i);
72 return true;
75 return false;
78 size_t VendorItemData::FindItemSlot(uint32 item_id) const
80 for(size_t i = 0; i < m_items.size(); ++i )
81 if(m_items[i]->item==item_id)
82 return i;
83 return m_items.size();
86 VendorItem const* VendorItemData::FindItem(uint32 item_id) const
88 for(VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i )
89 if((*i)->item==item_id)
90 return *i;
91 return NULL;
94 Creature::Creature() :
95 Unit(), i_AI(NULL),
96 lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(0), lootingGroupLeaderGUID(0),
97 m_lootMoney(0), m_lootRecipient(0),
98 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
99 m_gossipOptionLoaded(false), m_emoteState(0), m_isPet(false), m_isTotem(false),
100 m_regenTimer(2000), m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
101 m_AlreadyCallAssistence(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
102 m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL),m_creatureInfo(NULL), m_DBTableGuid(0)
104 m_valuesCount = UNIT_END;
106 for(int i =0; i<4; ++i)
107 m_spells[i] = 0;
109 m_CreatureSpellCooldowns.clear();
110 m_CreatureCategoryCooldowns.clear();
111 m_GlobalCooldown = 0;
112 m_unit_movement_flags = MOVEMENTFLAG_WALK_MODE;
115 Creature::~Creature()
117 CleanupsBeforeDelete();
119 m_vendorItemCounts.clear();
121 delete i_AI;
122 i_AI = NULL;
125 void Creature::AddToWorld()
127 ///- Register the creature for guid lookup
128 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
129 Unit::AddToWorld();
132 void Creature::RemoveFromWorld()
134 ///- Remove the creature from the accessor
135 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
136 Unit::RemoveFromWorld();
139 void Creature::RemoveCorpse()
141 if( getDeathState()!=CORPSE && !m_isDeadByDefault || getDeathState()!=ALIVE && m_isDeadByDefault )
142 return;
144 m_deathTimer = 0;
145 setDeathState(DEAD);
146 ObjectAccessor::UpdateObjectVisibility(this);
147 loot.clear();
148 m_respawnTime = time(NULL) + m_respawnDelay;
150 float x,y,z,o;
151 GetRespawnCoord(x, y, z, &o);
152 MapManager::Instance().GetMap(GetMapId(), this)->CreatureRelocation(this,x,y,z,o);
156 * change the entry of creature until respawn
158 bool Creature::InitEntry(uint32 Entry, uint32 team, const CreatureData *data )
160 CreatureInfo const *normalInfo = objmgr.GetCreatureTemplate(Entry);
161 if(!normalInfo)
163 sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
164 return false;
167 // get heroic mode entry
168 uint32 actualEntry = Entry;
169 CreatureInfo const *cinfo = normalInfo;
170 if(normalInfo->HeroicEntry)
172 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
173 if(map && map->IsHeroic())
175 cinfo = objmgr.GetCreatureTemplate(normalInfo->HeroicEntry);
176 if(!cinfo)
178 sLog.outErrorDb("Creature::UpdateEntry creature heroic entry %u does not exist.", actualEntry);
179 return false;
184 SetEntry(Entry); // normal entry always
185 m_creatureInfo = cinfo; // map mode related always
187 if (cinfo->DisplayID_A == 0 || cinfo->DisplayID_H == 0) // Cancel load if no model defined
189 sLog.outErrorDb("Creature (Entry: %u) has no model defined for Horde or Alliance in table `creature_template`, can't load. ",Entry);
190 return false;
193 uint32 display_id = objmgr.ChooseDisplayId(team, GetCreatureInfo(), data);
194 CreatureModelInfo const *minfo = objmgr.GetCreatureModelRandomGender(display_id);
195 if (!minfo)
197 sLog.outErrorDb("Creature (Entry: %u) has model %u not found in table `creature_model_info`, can't load. ", Entry, display_id);
198 return false;
200 else
201 display_id = minfo->modelid; // it can be different (for another gender)
203 SetDisplayId(display_id);
204 SetNativeDisplayId(display_id);
205 SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
207 // Load creature equipment
208 if(!data || data->equipmentId == 0)
209 { // use default from the template
210 LoadEquipment(cinfo->equipmentId);
212 else if(data && data->equipmentId != -1)
213 { // override, -1 means no equipment
214 LoadEquipment(data->equipmentId);
217 SetName(normalInfo->Name); // at normal entry always
219 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,minfo->bounding_radius);
220 SetFloatValue(UNIT_FIELD_COMBATREACH,minfo->combat_reach );
222 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
224 SetSpeed(MOVE_WALK, cinfo->speed );
225 SetSpeed(MOVE_RUN, cinfo->speed );
226 SetSpeed(MOVE_SWIM, cinfo->speed );
228 SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
230 // checked at loading
231 m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
232 if(!m_respawnradius && m_defaultMovementType==RANDOM_MOTION_TYPE)
233 m_defaultMovementType = IDLE_MOTION_TYPE;
235 return true;
238 bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData *data )
240 if(!InitEntry(Entry,team,data))
241 return false;
243 m_regenHealth = GetCreatureInfo()->RegenHealth;
245 // creatures always have melee weapon ready if any
246 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
247 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_AURAS );
249 SelectLevel(GetCreatureInfo());
250 if (team == HORDE)
251 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_H);
252 else
253 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetCreatureInfo()->faction_A);
255 SetUInt32Value(UNIT_NPC_FLAGS,GetCreatureInfo()->npcflag);
257 SetAttackTime(BASE_ATTACK, GetCreatureInfo()->baseattacktime);
258 SetAttackTime(OFF_ATTACK, GetCreatureInfo()->baseattacktime);
259 SetAttackTime(RANGED_ATTACK,GetCreatureInfo()->rangeattacktime);
261 SetUInt32Value(UNIT_FIELD_FLAGS,GetCreatureInfo()->unit_flags);
262 SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
264 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->armor));
265 SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->resistance1));
266 SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->resistance2));
267 SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->resistance3));
268 SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->resistance4));
269 SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->resistance5));
270 SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->resistance6));
272 SetCanModifyStats(true);
273 UpdateAllStats();
275 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->faction_A);
276 if (factionTemplate) // check and error show at loading templates
278 FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction);
279 if (factionEntry)
280 if( !(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) &&
281 (factionEntry->team == ALLIANCE || factionEntry->team == HORDE) )
282 SetPvP(true);
285 m_spells[0] = GetCreatureInfo()->spell1;
286 m_spells[1] = GetCreatureInfo()->spell2;
287 m_spells[2] = GetCreatureInfo()->spell3;
288 m_spells[3] = GetCreatureInfo()->spell4;
290 return true;
293 void Creature::Update(uint32 diff)
295 if(m_GlobalCooldown <= diff)
296 m_GlobalCooldown = 0;
297 else
298 m_GlobalCooldown -= diff;
300 switch( m_deathState )
302 case JUST_ALIVED:
303 // Dont must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
304 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)",GetGUIDLow(),GetEntry());
305 break;
306 case JUST_DIED:
307 // Dont must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
308 sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)",GetGUIDLow(),GetEntry());
309 break;
310 case DEAD:
312 if( m_respawnTime <= time(NULL) )
314 DEBUG_LOG("Respawning...");
315 m_respawnTime = 0;
316 lootForPickPocketed = false;
317 lootForBody = false;
319 if(m_originalEntry != GetEntry())
320 UpdateEntry(m_originalEntry);
322 CreatureInfo const *cinfo = GetCreatureInfo();
324 SelectLevel(cinfo);
325 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
326 if (m_isDeadByDefault)
328 setDeathState(JUST_DIED);
329 SetHealth(0);
330 i_motionMaster.Clear();
331 clearUnitState(UNIT_STAT_ALL_STATE);
332 LoadCreaturesAddon(true);
334 else
335 setDeathState( JUST_ALIVED );
337 //Call AI respawn virtual function
338 i_AI->JustRespawned();
340 MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
342 break;
344 case CORPSE:
346 if (m_isDeadByDefault)
347 break;
349 if( m_deathTimer <= diff )
351 RemoveCorpse();
352 DEBUG_LOG("Removing corpse... %u ", GetEntry());
354 else
356 m_deathTimer -= diff;
357 if (m_groupLootTimer && lootingGroupLeaderGUID)
359 if(diff <= m_groupLootTimer)
361 m_groupLootTimer -= diff;
363 else
365 Group* group = objmgr.GetGroupByLeader(lootingGroupLeaderGUID);
366 if (group)
367 group->EndRoll();
368 m_groupLootTimer = 0;
369 lootingGroupLeaderGUID = 0;
374 break;
376 case ALIVE:
378 if (m_isDeadByDefault)
380 if( m_deathTimer <= diff )
382 RemoveCorpse();
383 DEBUG_LOG("Removing alive corpse... %u ", GetEntry());
385 else
387 m_deathTimer -= diff;
391 Unit::Update( diff );
393 // creature can be dead after Unit::Update call
394 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
395 if(!isAlive())
396 break;
398 if(!IsInEvadeMode())
400 // do not allow the AI to be changed during update
401 m_AI_locked = true;
402 i_AI->UpdateAI(diff);
403 m_AI_locked = false;
406 // creature can be dead after UpdateAI call
407 // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
408 if(!isAlive())
409 break;
410 if(m_regenTimer > 0)
412 if(diff >= m_regenTimer)
413 m_regenTimer = 0;
414 else
415 m_regenTimer -= diff;
417 if (m_regenTimer != 0)
418 break;
420 if (!isInCombat() || IsPolymorphed())
421 RegenerateHealth();
423 RegenerateMana();
425 m_regenTimer = 2000;
426 break;
428 default:
429 break;
433 void Creature::RegenerateMana()
435 uint32 curValue = GetPower(POWER_MANA);
436 uint32 maxValue = GetMaxPower(POWER_MANA);
438 if (curValue >= maxValue)
439 return;
441 uint32 addvalue = 0;
443 // Combat and any controlled creature
444 if (isInCombat() || GetCharmerOrOwnerGUID())
446 if(!IsUnderLastManaUseEffect())
448 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
449 float Spirit = GetStat(STAT_SPIRIT);
451 addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate);
454 else
455 addvalue = maxValue/3;
457 ModifyPower(POWER_MANA, addvalue);
460 void Creature::RegenerateHealth()
462 if (!isRegeneratingHealth())
463 return;
465 uint32 curValue = GetHealth();
466 uint32 maxValue = GetMaxHealth();
468 if (curValue >= maxValue)
469 return;
471 uint32 addvalue = 0;
473 // Not only pet, but any controelled creature
474 if(GetCharmerOrOwnerGUID())
476 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
477 float Spirit = GetStat(STAT_SPIRIT);
479 if( GetPower(POWER_MANA) > 0 )
480 addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
481 else
482 addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
484 else
485 addvalue = maxValue/3;
487 ModifyHealth(addvalue);
490 bool Creature::AIM_Initialize()
492 // make sure nothing can change the AI during AI update
493 if(m_AI_locked)
495 sLog.outDebug("AIM_Initialize: failed to init, locked.");
496 return false;
499 CreatureAI * oldAI = i_AI;
500 i_motionMaster.Initialize();
501 i_AI = FactorySelector::selectAI(this);
502 if (oldAI)
503 delete oldAI;
504 return true;
507 bool Creature::Create (uint32 guidlow, Map *map, uint32 Entry, uint32 team, const CreatureData *data)
509 SetMapId(map->GetId());
510 SetInstanceId(map->GetInstanceId());
512 //oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
513 const bool bResult = CreateFromProto(guidlow, Entry, team, data);
515 if (bResult)
517 switch (GetCreatureInfo()->rank)
519 case CREATURE_ELITE_RARE:
520 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RARE);
521 break;
522 case CREATURE_ELITE_ELITE:
523 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_ELITE);
524 break;
525 case CREATURE_ELITE_RAREELITE:
526 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_RAREELITE);
527 break;
528 case CREATURE_ELITE_WORLDBOSS:
529 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
530 break;
531 default:
532 m_corpseDelay = sWorld.getConfig(CONFIG_CORPSE_DECAY_NORMAL);
533 break;
535 LoadCreaturesAddon();
538 return bResult;
541 bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const
543 if(!isTrainer())
544 return false;
546 TrainerSpellData const* trainer_spells = GetTrainerSpells();
548 if(!trainer_spells || trainer_spells->spellList.empty())
550 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
551 GetGUIDLow(),GetEntry());
552 return false;
555 switch(GetCreatureInfo()->trainer_type)
557 case TRAINER_TYPE_CLASS:
558 if(pPlayer->getClass()!=GetCreatureInfo()->classNum)
560 if(msg)
562 pPlayer->PlayerTalkClass->ClearMenus();
563 switch(GetCreatureInfo()->classNum)
565 case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu( 4913,GetGUID()); break;
566 case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090,GetGUID()); break;
567 case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu( 328,GetGUID()); break;
568 case CLASS_PALADIN:pPlayer->PlayerTalkClass->SendGossipMenu( 1635,GetGUID()); break;
569 case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu( 4436,GetGUID()); break;
570 case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu( 4797,GetGUID()); break;
571 case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu( 5003,GetGUID()); break;
572 case CLASS_WARLOCK:pPlayer->PlayerTalkClass->SendGossipMenu( 5836,GetGUID()); break;
573 case CLASS_WARRIOR:pPlayer->PlayerTalkClass->SendGossipMenu( 4985,GetGUID()); break;
576 return false;
578 break;
579 case TRAINER_TYPE_PETS:
580 if(pPlayer->getClass()!=CLASS_HUNTER)
582 pPlayer->PlayerTalkClass->ClearMenus();
583 pPlayer->PlayerTalkClass->SendGossipMenu(3620,GetGUID());
584 return false;
586 break;
587 case TRAINER_TYPE_MOUNTS:
588 if(GetCreatureInfo()->race && pPlayer->getRace() != GetCreatureInfo()->race)
590 if(msg)
592 pPlayer->PlayerTalkClass->ClearMenus();
593 switch(GetCreatureInfo()->classNum)
595 case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865,GetGUID()); break;
596 case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881,GetGUID()); break;
597 case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861,GetGUID()); break;
598 case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
599 case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863,GetGUID()); break;
600 case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
601 case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816,GetGUID()); break;
602 case RACE_UNDEAD_PLAYER:pPlayer->PlayerTalkClass->SendGossipMenu( 624,GetGUID()); break;
603 case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862,GetGUID()); break;
604 case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864,GetGUID()); break;
607 return false;
609 break;
610 case TRAINER_TYPE_TRADESKILLS:
611 if(GetCreatureInfo()->trainer_spell && !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell))
613 if(msg)
615 pPlayer->PlayerTalkClass->ClearMenus();
616 pPlayer->PlayerTalkClass->SendGossipMenu(11031,GetGUID());
618 return false;
620 break;
621 default:
622 return false; // checked and error output at creature_template loading
624 return true;
627 bool Creature::isCanIneractWithBattleMaster(Player* pPlayer, bool msg) const
629 if(!isBattleMaster())
630 return false;
632 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
633 if(!msg)
634 return pPlayer->GetBGAccessByLevel(bgTypeId);
636 if(!pPlayer->GetBGAccessByLevel(bgTypeId))
638 pPlayer->PlayerTalkClass->ClearMenus();
639 switch(bgTypeId)
641 case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616,GetGUID()); break;
642 case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599,GetGUID()); break;
643 case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642,GetGUID()); break;
644 case BATTLEGROUND_EY:
645 case BATTLEGROUND_NA:
646 case BATTLEGROUND_BE:
647 case BATTLEGROUND_AA:
648 case BATTLEGROUND_RL: pPlayer->PlayerTalkClass->SendGossipMenu(10024,GetGUID()); break;
649 break;
651 return false;
653 return true;
656 bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const
658 return pPlayer->getLevel() >= 10
659 && GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
660 && pPlayer->getClass() == GetCreatureInfo()->classNum;
663 void Creature::prepareGossipMenu( Player *pPlayer,uint32 gossipid )
665 PlayerMenu* pm=pPlayer->PlayerTalkClass;
666 pm->ClearMenus();
668 // lazy loading single time at use
669 LoadGossipOptions();
671 for( GossipOptionList::iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
673 GossipOption* gso=&*i;
674 if(gso->GossipId == gossipid)
676 bool cantalking=true;
677 if(gso->Id==1)
679 uint32 textid=GetNpcTextId();
680 GossipText * gossiptext=objmgr.GetGossipText(textid);
681 if(!gossiptext)
682 cantalking=false;
684 else
686 switch (gso->Action)
688 case GOSSIP_OPTION_QUESTGIVER:
689 pPlayer->PrepareQuestMenu(GetGUID());
690 //if (pm->GetQuestMenu()->MenuItemCount() == 0)
691 cantalking=false;
692 //pm->GetQuestMenu()->ClearMenu();
693 break;
694 case GOSSIP_OPTION_ARMORER:
695 cantalking=false; // added in special mode
696 break;
697 case GOSSIP_OPTION_SPIRITHEALER:
698 if( !pPlayer->isDead() )
699 cantalking=false;
700 break;
701 case GOSSIP_OPTION_VENDOR:
703 VendorItemData const* vItems = GetVendorItems();
704 if(!vItems || vItems->Empty())
706 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.",
707 GetGUIDLow(),GetEntry());
708 cantalking=false;
710 break;
712 case GOSSIP_OPTION_TRAINER:
713 if(!isCanTrainingOf(pPlayer,false))
714 cantalking=false;
715 break;
716 case GOSSIP_OPTION_UNLEARNTALENTS:
717 if(!isCanTrainingAndResetTalentsOf(pPlayer))
718 cantalking=false;
719 break;
720 case GOSSIP_OPTION_UNLEARNPETSKILLS:
721 if(!pPlayer->GetPet() || pPlayer->GetPet()->getPetType() != HUNTER_PET || pPlayer->GetPet()->m_spells.size() <= 1 || GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || GetCreatureInfo()->classNum != CLASS_HUNTER)
722 cantalking=false;
723 break;
724 case GOSSIP_OPTION_TAXIVENDOR:
725 if ( pPlayer->GetSession()->SendLearnNewTaxiNode(this) )
726 return;
727 break;
728 case GOSSIP_OPTION_BATTLEFIELD:
729 if(!isCanIneractWithBattleMaster(pPlayer,false))
730 cantalking=false;
731 break;
732 case GOSSIP_OPTION_SPIRITGUIDE:
733 case GOSSIP_OPTION_INNKEEPER:
734 case GOSSIP_OPTION_BANKER:
735 case GOSSIP_OPTION_PETITIONER:
736 case GOSSIP_OPTION_STABLEPET:
737 case GOSSIP_OPTION_TABARDDESIGNER:
738 case GOSSIP_OPTION_AUCTIONEER:
739 break; // no checks
740 default:
741 sLog.outErrorDb("Creature %u (entry: %u) have unknown gossip option %u",GetDBTableGUIDLow(),GetEntry(),gso->Action);
742 break;
746 //note for future dev: should have database fields for BoxMessage & BoxMoney
747 if(!gso->OptionText.empty() && cantalking)
749 std::string OptionText = gso->OptionText;
750 std::string BoxText = gso->BoxText;
751 int loc_idx = pPlayer->GetSession()->GetSessionDbLocaleIndex();
752 if (loc_idx >= 0)
754 NpcOptionLocale const *no = objmgr.GetNpcOptionLocale(gso->Id);
755 if (no)
757 if (no->OptionText.size() > loc_idx && !no->OptionText[loc_idx].empty())
758 OptionText=no->OptionText[loc_idx];
759 if (no->BoxText.size() > loc_idx && !no->BoxText[loc_idx].empty())
760 BoxText=no->BoxText[loc_idx];
763 pm->GetGossipMenu().AddMenuItem((uint8)gso->Icon,OptionText, gossipid,gso->Action,BoxText,gso->BoxMoney,gso->Coded);
768 ///some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
769 if(pm->Empty())
771 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
773 isCanTrainingOf(pPlayer,true); // output error message if need
775 if(HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
777 isCanIneractWithBattleMaster(pPlayer,true); // output error message if need
782 void Creature::sendPreparedGossip(Player* player)
784 if(!player)
785 return;
787 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
789 // in case empty gossip menu open quest menu if any
790 if (gossipmenu.Empty() && GetNpcTextId() == 0)
792 player->SendPreparedQuest(GetGUID());
793 return;
796 // in case non empty gossip menu (that not included quests list size) show it
797 // (quest entries from quest menu wiill be included in list)
798 player->PlayerTalkClass->SendGossipMenu(GetNpcTextId(), GetGUID());
801 void Creature::OnGossipSelect(Player* player, uint32 option)
803 GossipMenu& gossipmenu = player->PlayerTalkClass->GetGossipMenu();
805 if(option >= gossipmenu.MenuItemCount())
806 return;
808 uint32 action=gossipmenu.GetItem(option).m_gAction;
809 uint32 zoneid=GetZoneId();
810 uint64 guid=GetGUID();
812 GossipOption const *gossip=GetGossipOption( action );
813 if(!gossip)
815 zoneid=0;
816 gossip=GetGossipOption( action );
817 if(!gossip)
818 return;
821 uint32 textid=GetGossipTextId( action, zoneid);
822 if(textid==0)
823 textid=GetNpcTextId();
825 switch (gossip->Action)
827 case GOSSIP_OPTION_GOSSIP:
828 player->PlayerTalkClass->CloseGossip();
829 player->PlayerTalkClass->SendTalking( textid );
830 break;
831 case GOSSIP_OPTION_SPIRITHEALER:
832 if( player->isDead() )
833 CastSpell(this,17251,true,NULL,NULL,player->GetGUID());
834 break;
835 case GOSSIP_OPTION_QUESTGIVER:
836 player->PrepareQuestMenu( guid );
837 player->SendPreparedQuest( guid );
838 break;
839 case GOSSIP_OPTION_VENDOR:
840 case GOSSIP_OPTION_ARMORER:
841 player->GetSession()->SendListInventory(guid);
842 break;
843 case GOSSIP_OPTION_STABLEPET:
844 player->GetSession()->SendStablePet(guid);
845 break;
846 case GOSSIP_OPTION_TRAINER:
847 player->GetSession()->SendTrainerList(guid);
848 break;
849 case GOSSIP_OPTION_UNLEARNTALENTS:
850 player->PlayerTalkClass->CloseGossip();
851 player->SendTalentWipeConfirm(guid);
852 break;
853 case GOSSIP_OPTION_UNLEARNPETSKILLS:
854 player->PlayerTalkClass->CloseGossip();
855 player->SendPetSkillWipeConfirm();
856 break;
857 case GOSSIP_OPTION_TAXIVENDOR:
858 player->GetSession()->SendTaxiMenu(this);
859 break;
860 case GOSSIP_OPTION_INNKEEPER:
861 player->PlayerTalkClass->CloseGossip();
862 player->SetBindPoint( guid );
863 break;
864 case GOSSIP_OPTION_BANKER:
865 player->GetSession()->SendShowBank( guid );
866 break;
867 case GOSSIP_OPTION_PETITIONER:
868 player->PlayerTalkClass->CloseGossip();
869 player->GetSession()->SendPetitionShowList( guid );
870 break;
871 case GOSSIP_OPTION_TABARDDESIGNER:
872 player->PlayerTalkClass->CloseGossip();
873 player->GetSession()->SendTabardVendorActivate( guid );
874 break;
875 case GOSSIP_OPTION_AUCTIONEER:
876 player->GetSession()->SendAuctionHello( guid, this );
877 break;
878 case GOSSIP_OPTION_SPIRITGUIDE:
879 case GOSSIP_GUARD_SPELLTRAINER:
880 case GOSSIP_GUARD_SKILLTRAINER:
881 prepareGossipMenu( player,gossip->Id );
882 sendPreparedGossip( player );
883 break;
884 case GOSSIP_OPTION_BATTLEFIELD:
886 uint32 bgTypeId = objmgr.GetBattleMasterBG(GetEntry());
887 player->GetSession()->SendBattlegGroundList( GetGUID(), bgTypeId );
888 break;
890 default:
891 OnPoiSelect( player, gossip );
892 break;
897 void Creature::OnPoiSelect(Player* player, GossipOption const *gossip)
899 if(gossip->GossipId==GOSSIP_GUARD_SPELLTRAINER || gossip->GossipId==GOSSIP_GUARD_SKILLTRAINER)
901 //float x,y;
902 //bool findnpc=false;
903 Poi_Icon icon = ICON_POI_0;
904 //QueryResult *result;
905 //Field *fields;
906 uint32 mapid=GetMapId();
907 Map const* map=MapManager::Instance().GetBaseMap( mapid );
908 uint16 areaflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
909 uint32 zoneid=Map::GetZoneId(areaflag,mapid);
910 std::string areaname= gossip->OptionText;
912 uint16 pflag;
914 // use the action relate to creaturetemplate.trainer_type ?
915 result= WorldDatabase.PQuery("SELECT creature.position_x,creature.position_y FROM creature,creature_template WHERE creature.map = '%u' AND creature.id = creature_template.entry AND creature_template.trainer_type = '%u'", mapid, gossip->Action );
916 if(!result)
917 return;
920 fields = result->Fetch();
921 x=fields[0].GetFloat();
922 y=fields[1].GetFloat();
923 pflag=map->GetAreaFlag(GetPositionX(),GetPositionY());
924 if(pflag==areaflag)
926 findnpc=true;
927 break;
929 }while(result->NextRow());
931 delete result;
933 if(!findnpc)
935 player->PlayerTalkClass->SendTalking( "$NSorry", "Here no this person.");
936 return;
939 //need add more case.
940 switch(gossip->Action)
942 case GOSSIP_GUARD_BANK:
943 icon=ICON_POI_HOUSE;
944 break;
945 case GOSSIP_GUARD_RIDE:
946 icon=ICON_POI_RWHORSE;
947 break;
948 case GOSSIP_GUARD_GUILD:
949 icon=ICON_POI_BLUETOWER;
950 break;
951 default:
952 icon=ICON_POI_TOWER;
953 break;
955 uint32 textid=GetGossipTextId( gossip->Action, zoneid );
956 player->PlayerTalkClass->SendTalking( textid );
957 // how this could worked player->PlayerTalkClass->SendPointOfInterest( x, y, icon, 2, 15, areaname.c_str() );
961 uint32 Creature::GetGossipTextId(uint32 action, uint32 zoneid)
963 QueryResult *result= WorldDatabase.PQuery("SELECT textid FROM npc_gossip_textid WHERE action = '%u' AND zoneid ='%u'", action, zoneid );
965 if(!result)
966 return 0;
968 Field *fields = result->Fetch();
969 uint32 id = fields[0].GetUInt32();
971 delete result;
973 return id;
976 uint32 Creature::GetNpcTextId()
978 if (!m_DBTableGuid)
979 return DEFAULT_GOSSIP_MESSAGE;
981 if(uint32 pos = objmgr.GetNpcGossip(m_DBTableGuid))
982 return pos;
984 return DEFAULT_GOSSIP_MESSAGE;
987 GossipOption const* Creature::GetGossipOption( uint32 id ) const
989 for( GossipOptionList::const_iterator i = m_goptions.begin( ); i != m_goptions.end( ); i++ )
991 if(i->Action==id )
992 return &*i;
994 return NULL;
997 void Creature::LoadGossipOptions()
999 if(m_gossipOptionLoaded)
1000 return;
1002 uint32 npcflags=GetUInt32Value(UNIT_NPC_FLAGS);
1004 CacheNpcOptionList const& noList = objmgr.GetNpcOptions ();
1005 for (CacheNpcOptionList::const_iterator i = noList.begin (); i != noList.end (); ++i)
1006 if(i->NpcFlag & npcflags)
1007 addGossipOption(*i);
1009 m_gossipOptionLoaded = true;
1012 void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type)
1014 /* uint32 timeElap = getMSTime();
1015 if ((timeElap - m_startMove) < m_moveTime)
1017 oX = (dX - oX) * ( (timeElap - m_startMove) / m_moveTime );
1018 oY = (dY - oY) * ( (timeElap - m_startMove) / m_moveTime );
1020 else
1022 oX = dX;
1023 oY = dY;
1026 dX = x;
1027 dY = y;
1028 m_orientation = atan2((oY - dY), (oX - dX));
1030 m_startMove = getMSTime();
1031 m_moveTime = time;*/
1032 SendMonsterMove(x, y, z, type, MovementFlags, time);
1035 Player *Creature::GetLootRecipient() const
1037 if (!m_lootRecipient) return NULL;
1038 else return ObjectAccessor::FindPlayer(m_lootRecipient);
1041 void Creature::SetLootRecipient(Unit *unit)
1043 // set the player whose group should receive the right
1044 // to loot the creature after it dies
1045 // should be set to NULL after the loot disappears
1047 if (!unit)
1049 m_lootRecipient = 0;
1050 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1051 return;
1054 Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
1055 if(!player) // normal creature, no player involved
1056 return;
1058 m_lootRecipient = player->GetGUID();
1059 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER);
1062 void Creature::SaveToDB()
1064 // this should only be used when the creature has already been loaded
1065 // perferably after adding to map, because mapid may not be valid otherwise
1066 CreatureData const *data = objmgr.GetCreatureData(m_DBTableGuid);
1067 if(!data)
1069 sLog.outError("Creature::SaveToDB failed, cannot get creature data!");
1070 return;
1073 SaveToDB(GetMapId(), data->spawnMask);
1076 void Creature::SaveToDB(uint32 mapid, uint8 spawnMask)
1078 // update in loaded data
1079 if (!m_DBTableGuid)
1080 m_DBTableGuid = GetGUIDLow();
1081 CreatureData& data = objmgr.NewOrExistCreatureData(m_DBTableGuid);
1083 uint32 displayId = GetNativeDisplayId();
1085 // check if it's a custom model and if not, use 0 for displayId
1086 CreatureInfo const *cinfo = GetCreatureInfo();
1087 if(cinfo)
1089 if(displayId != cinfo->DisplayID_A && displayId != cinfo->DisplayID_H)
1091 CreatureModelInfo const *minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_A);
1092 if(!minfo || displayId != minfo->modelid_other_gender)
1094 minfo = objmgr.GetCreatureModelInfo(cinfo->DisplayID_H);
1095 if(minfo && displayId == minfo->modelid_other_gender)
1096 displayId = 0;
1098 else
1099 displayId = 0;
1101 else
1102 displayId = 0;
1105 // data->guid = guid don't must be update at save
1106 data.id = GetEntry();
1107 data.mapid = mapid;
1108 data.displayid = displayId;
1109 data.equipmentId = GetEquipmentId();
1110 data.posX = GetPositionX();
1111 data.posY = GetPositionY();
1112 data.posZ = GetPositionZ();
1113 data.orientation = GetOrientation();
1114 data.spawntimesecs = m_respawnDelay;
1115 // prevent add data integrity problems
1116 data.spawndist = GetDefaultMovementType()==IDLE_MOTION_TYPE ? 0 : m_respawnradius;
1117 data.currentwaypoint = 0;
1118 data.curhealth = GetHealth();
1119 data.curmana = GetPower(POWER_MANA);
1120 data.is_dead = m_isDeadByDefault;
1121 // prevent add data integrity problems
1122 data.movementType = !m_respawnradius && GetDefaultMovementType()==RANDOM_MOTION_TYPE
1123 ? IDLE_MOTION_TYPE : GetDefaultMovementType();
1124 data.spawnMask = spawnMask;
1126 // updated in DB
1127 WorldDatabase.BeginTransaction();
1129 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1131 std::ostringstream ss;
1132 ss << "INSERT INTO creature VALUES ("
1133 << m_DBTableGuid << ","
1134 << GetEntry() << ","
1135 << mapid <<","
1136 << (uint32)spawnMask << ","
1137 << displayId <<","
1138 << GetEquipmentId() <<","
1139 << GetPositionX() << ","
1140 << GetPositionY() << ","
1141 << GetPositionZ() << ","
1142 << GetOrientation() << ","
1143 << m_respawnDelay << "," //respawn time
1144 << (float) m_respawnradius << "," //spawn distance (float)
1145 << (uint32) (0) << "," //currentwaypoint
1146 << GetHealth() << "," //curhealth
1147 << GetPower(POWER_MANA) << "," //curmana
1148 << (m_isDeadByDefault ? 1 : 0) << "," //is_dead
1149 << GetDefaultMovementType() << ")"; //default movement generator type
1151 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
1153 WorldDatabase.CommitTransaction();
1156 void Creature::SelectLevel(const CreatureInfo *cinfo)
1158 uint32 rank = isPet()? 0 : cinfo->rank;
1160 // level
1161 uint32 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
1162 uint32 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
1163 uint32 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
1164 SetLevel(level);
1166 float rellevel = maxlevel == minlevel ? 0 : (float(level - minlevel))/(maxlevel - minlevel);
1168 // health
1169 float healthmod = _GetHealthMod(rank);
1171 uint32 minhealth = std::min(cinfo->maxhealth, cinfo->minhealth);
1172 uint32 maxhealth = std::max(cinfo->maxhealth, cinfo->minhealth);
1173 uint32 health = uint32(healthmod * (minhealth + uint32(rellevel*(maxhealth - minhealth))));
1175 SetCreateHealth(health);
1176 SetMaxHealth(health);
1177 SetHealth(health);
1179 // mana
1180 uint32 minmana = std::min(cinfo->maxmana, cinfo->minmana);
1181 uint32 maxmana = std::max(cinfo->maxmana, cinfo->minmana);
1182 uint32 mana = minmana + uint32(rellevel*(maxmana - minmana));
1184 SetCreateMana(mana);
1185 SetMaxPower(POWER_MANA, mana); //MAX Mana
1186 SetPower(POWER_MANA, mana);
1188 SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, health);
1189 SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, mana);
1191 // damage
1192 float damagemod = _GetDamageMod(rank);
1194 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
1195 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
1197 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,cinfo->minrangedmg * damagemod);
1198 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,cinfo->maxrangedmg * damagemod);
1200 SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, cinfo->attackpower * damagemod);
1203 float Creature::_GetHealthMod(int32 Rank)
1205 switch (Rank) // define rates for each elite rank
1207 case CREATURE_ELITE_NORMAL:
1208 return sWorld.getRate(RATE_CREATURE_NORMAL_HP);
1209 case CREATURE_ELITE_ELITE:
1210 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1211 case CREATURE_ELITE_RAREELITE:
1212 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
1213 case CREATURE_ELITE_WORLDBOSS:
1214 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
1215 case CREATURE_ELITE_RARE:
1216 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_HP);
1217 default:
1218 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_HP);
1222 float Creature::_GetDamageMod(int32 Rank)
1224 switch (Rank) // define rates for each elite rank
1226 case CREATURE_ELITE_NORMAL:
1227 return sWorld.getRate(RATE_CREATURE_NORMAL_DAMAGE);
1228 case CREATURE_ELITE_ELITE:
1229 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1230 case CREATURE_ELITE_RAREELITE:
1231 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
1232 case CREATURE_ELITE_WORLDBOSS:
1233 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
1234 case CREATURE_ELITE_RARE:
1235 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
1236 default:
1237 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
1241 float Creature::GetSpellDamageMod(int32 Rank)
1243 switch (Rank) // define rates for each elite rank
1245 case CREATURE_ELITE_NORMAL:
1246 return sWorld.getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
1247 case CREATURE_ELITE_ELITE:
1248 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1249 case CREATURE_ELITE_RAREELITE:
1250 return sWorld.getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
1251 case CREATURE_ELITE_WORLDBOSS:
1252 return sWorld.getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
1253 case CREATURE_ELITE_RARE:
1254 return sWorld.getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
1255 default:
1256 return sWorld.getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
1260 bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 team, const CreatureData *data)
1262 CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(Entry);
1263 if(!cinfo)
1265 sLog.outErrorDb("Error: creature entry %u does not exist.", Entry);
1266 return false;
1268 m_originalEntry = Entry;
1270 Object::_Create(guidlow, Entry, HIGHGUID_UNIT);
1272 if(!UpdateEntry(Entry, team, data))
1273 return false;
1275 //Notify the map's instance data.
1276 //Only works if you create the object in it, not if it is moves to that map.
1277 //Normally non-players do not teleport to other maps.
1278 Map *map = MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
1279 if(map && map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
1281 ((InstanceMap*)map)->GetInstanceData()->OnCreatureCreate(this, Entry);
1284 return true;
1287 bool Creature::LoadFromDB(uint32 guid, Map *map)
1289 CreatureData const* data = objmgr.GetCreatureData(guid);
1291 if(!data)
1293 sLog.outErrorDb("Creature (GUID: %u) not found in table `creature`, can't load. ",guid);
1294 return false;
1297 m_DBTableGuid = guid;
1298 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_UNIT);
1300 uint16 team = 0;
1301 if(!Create(guid,map,data->id,team,data))
1302 return false;
1304 Relocate(data->posX,data->posY,data->posZ,data->orientation);
1306 if(!IsPositionValid())
1308 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",GetGUIDLow(),GetEntry(),GetPositionX(),GetPositionY());
1309 return false;
1312 m_respawnradius = data->spawndist;
1314 m_respawnDelay = data->spawntimesecs;
1315 m_isDeadByDefault = data->is_dead;
1316 m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
1318 m_respawnTime = objmgr.GetCreatureRespawnTime(m_DBTableGuid,GetInstanceId());
1319 if(m_respawnTime > time(NULL)) // not ready to respawn
1320 m_deathState = DEAD;
1321 else if(m_respawnTime) // respawn time set but expired
1323 m_respawnTime = 0;
1324 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1327 uint32 curhealth = data->curhealth;
1328 if(curhealth)
1330 curhealth = uint32(curhealth*_GetHealthMod(GetCreatureInfo()->rank));
1331 if(curhealth < 1)
1332 curhealth = 1;
1335 SetHealth(m_deathState == ALIVE ? curhealth : 0);
1336 SetPower(POWER_MANA,data->curmana);
1338 SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
1340 // checked at creature_template loading
1341 m_defaultMovementType = MovementGeneratorType(data->movementType);
1343 AIM_Initialize();
1344 return true;
1347 void Creature::LoadEquipment(uint32 equip_entry, bool force)
1349 if(equip_entry == 0)
1351 if (force)
1353 for (uint8 i = 0; i < 3; i++)
1355 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, 0);
1356 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), 0);
1357 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, 0);
1359 m_equipmentId = 0;
1361 return;
1364 EquipmentInfo const *einfo = objmgr.GetEquipmentInfo(equip_entry);
1365 if (!einfo)
1366 return;
1368 m_equipmentId = equip_entry;
1369 for (uint8 i = 0; i < 3; i++)
1371 SetUInt32Value( UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + i, einfo->equipmodel[i]);
1372 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2), einfo->equipinfo[i]);
1373 SetUInt32Value( UNIT_VIRTUAL_ITEM_INFO + (i * 2) + 1, einfo->equipslot[i]);
1377 bool Creature::hasQuest(uint32 quest_id) const
1379 QuestRelations const& qr = objmgr.mCreatureQuestRelations;
1380 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1382 if(itr->second==quest_id)
1383 return true;
1385 return false;
1388 bool Creature::hasInvolvedQuest(uint32 quest_id) const
1390 QuestRelations const& qr = objmgr.mCreatureQuestInvolvedRelations;
1391 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
1393 if(itr->second==quest_id)
1394 return true;
1396 return false;
1399 void Creature::DeleteFromDB()
1401 if (!m_DBTableGuid)
1403 sLog.outDebug("Trying to delete not saved creature!");
1404 return;
1407 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1408 objmgr.DeleteCreatureData(m_DBTableGuid);
1410 WorldDatabase.BeginTransaction();
1411 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
1412 WorldDatabase.PExecuteLog("DELETE FROM creature_addon WHERE guid = '%u'", m_DBTableGuid);
1413 WorldDatabase.PExecuteLog("DELETE FROM creature_movement WHERE id = '%u'", m_DBTableGuid);
1414 WorldDatabase.PExecuteLog("DELETE FROM game_event_creature WHERE guid = '%u'", m_DBTableGuid);
1415 WorldDatabase.PExecuteLog("DELETE FROM game_event_model_equip WHERE guid = '%u'", m_DBTableGuid);
1416 WorldDatabase.CommitTransaction();
1419 float Creature::GetAttackDistance(Unit const* pl) const
1421 float aggroRate = sWorld.getRate(RATE_CREATURE_AGGRO);
1422 if(aggroRate==0)
1423 return 0.0f;
1425 int32 playerlevel = pl->getLevelForTarget(this);
1426 int32 creaturelevel = getLevelForTarget(pl);
1428 int32 leveldif = playerlevel - creaturelevel;
1430 // "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."
1431 if ( leveldif < - 25)
1432 leveldif = -25;
1434 // "The aggro radius of a mob having the same level as the player is roughly 20 yards"
1435 float RetDistance = 20;
1437 // "Aggro Radius varries with level difference at a rate of roughly 1 yard/level"
1438 // radius grow if playlevel < creaturelevel
1439 RetDistance -= (float)leveldif;
1441 if(creaturelevel+5 <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1443 // detect range auras
1444 RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
1446 // detected range auras
1447 RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
1450 // "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
1451 if(RetDistance < 5)
1452 RetDistance = 5;
1454 return (RetDistance*aggroRate);
1457 void Creature::setDeathState(DeathState s)
1459 if((s == JUST_DIED && !m_isDeadByDefault)||(s == JUST_ALIVED && m_isDeadByDefault))
1461 m_deathTimer = m_corpseDelay*1000;
1463 // always save boss respawn time at death to prevent crash cheating
1464 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY) || isWorldBoss())
1465 SaveRespawnTime();
1467 if(!IsStopped())
1468 StopMoving();
1470 Unit::setDeathState(s);
1472 if(s == JUST_DIED)
1474 SetUInt64Value (UNIT_FIELD_TARGET,0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
1475 SetUInt32Value(UNIT_NPC_FLAGS, 0);
1477 if(!isPet() && GetCreatureInfo()->SkinLootId)
1478 if ( LootTemplates_Skinning.HaveLootFor(GetCreatureInfo()->SkinLootId) )
1479 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1481 Unit::setDeathState(CORPSE);
1483 if(s == JUST_ALIVED)
1485 SetHealth(GetMaxHealth());
1486 SetLootRecipient(NULL);
1487 Unit::setDeathState(ALIVE);
1488 CreatureInfo const *cinfo = GetCreatureInfo();
1489 SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0);
1490 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
1491 AddUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
1492 SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
1493 clearUnitState(UNIT_STAT_ALL_STATE);
1494 i_motionMaster.Clear();
1495 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
1496 LoadCreaturesAddon(true);
1500 void Creature::Respawn()
1502 RemoveCorpse();
1504 // forced recreate creature object at clients
1505 UnitVisibility currentVis = GetVisibility();
1506 SetVisibility(VISIBILITY_RESPAWN);
1507 ObjectAccessor::UpdateObjectVisibility(this);
1508 SetVisibility(currentVis); // restore visibility state
1509 ObjectAccessor::UpdateObjectVisibility(this);
1511 if(getDeathState()==DEAD)
1513 if (m_DBTableGuid)
1514 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),0);
1515 m_respawnTime = time(NULL); // respawn at next tick
1519 bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
1521 if (!spellInfo)
1522 return false;
1524 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->Mechanic - 1)))
1525 return true;
1527 return Unit::IsImmunedToSpell(spellInfo, useCharges);
1530 bool Creature::IsImmunedToSpellEffect(uint32 effect, uint32 mechanic) const
1532 if (GetCreatureInfo()->MechanicImmuneMask & (1 << (mechanic-1)))
1533 return true;
1535 return Unit::IsImmunedToSpellEffect(effect, mechanic);
1538 SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim)
1540 if(!pVictim)
1541 return NULL;
1543 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1545 if(!m_spells[i])
1546 continue;
1547 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1548 if(!spellInfo)
1550 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1551 continue;
1554 bool bcontinue = true;
1555 for(uint32 j=0;j<3;j++)
1557 if( (spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE ) ||
1558 (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL) ||
1559 (spellInfo->Effect[j] == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) ||
1560 (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH )
1563 bcontinue = false;
1564 break;
1567 if(bcontinue) continue;
1569 if(spellInfo->manaCost > GetPower(POWER_MANA))
1570 continue;
1571 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1572 float range = GetSpellMaxRange(srange);
1573 float minrange = GetSpellMinRange(srange);
1574 float dist = GetDistance(pVictim);
1575 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1576 // continue;
1577 if( dist > range || dist < minrange )
1578 continue;
1579 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1580 continue;
1581 return spellInfo;
1583 return NULL;
1586 SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim)
1588 if(!pVictim)
1589 return NULL;
1591 for(uint32 i=0; i < CREATURE_MAX_SPELLS; i++)
1593 if(!m_spells[i])
1594 continue;
1595 SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i] );
1596 if(!spellInfo)
1598 sLog.outError("WORLD: unknown spell id %i\n", m_spells[i]);
1599 continue;
1602 bool bcontinue = true;
1603 for(uint32 j=0;j<3;j++)
1605 if( (spellInfo->Effect[j] == SPELL_EFFECT_HEAL ) )
1607 bcontinue = false;
1608 break;
1611 if(bcontinue) continue;
1613 if(spellInfo->manaCost > GetPower(POWER_MANA))
1614 continue;
1615 SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
1616 float range = GetSpellMaxRange(srange);
1617 float minrange = GetSpellMinRange(srange);
1618 float dist = GetDistance(pVictim);
1619 //if(!isInFront( pVictim, range ) && spellInfo->AttributesEx )
1620 // continue;
1621 if( dist > range || dist < minrange )
1622 continue;
1623 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1624 continue;
1625 return spellInfo;
1627 return NULL;
1630 bool Creature::IsVisibleInGridForPlayer(Player* pl) const
1632 // gamemaster in GM mode see all, including ghosts
1633 if(pl->isGameMaster())
1634 return true;
1636 // Live player (or with not release body see live creatures or death creatures with corpse disappearing time > 0
1637 if(pl->isAlive() || pl->GetDeathTimer() > 0)
1639 if(GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INVISIBLE)
1640 return false;
1641 return isAlive() || m_deathTimer > 0 || m_isDeadByDefault && m_deathState==CORPSE;
1644 // Dead player see live creatures near own corpse
1645 if(isAlive())
1647 Corpse *corpse = pl->GetCorpse();
1648 if(corpse)
1650 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
1651 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
1652 return true;
1656 // Dead player see Spirit Healer or Spirit Guide
1657 if(isSpiritService())
1658 return true;
1660 // and not see any other
1661 return false;
1664 void Creature::CallAssistence()
1666 if( !m_AlreadyCallAssistence && getVictim() && !isPet() && !isCharmed())
1668 SetNoCallAssistence(true);
1670 float radius = sWorld.getConfig(CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS);
1671 if(radius > 0)
1673 std::list<Creature*> assistList;
1676 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1677 Cell cell(p);
1678 cell.data.Part.reserved = ALL_DISTRICT;
1679 cell.SetNoCreate();
1681 MaNGOS::AnyAssistCreatureInRangeCheck u_check(this, getVictim(), radius);
1682 MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck> searcher(assistList, u_check);
1684 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::AnyAssistCreatureInRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
1686 CellLock<GridReadGuard> cell_lock(cell, p);
1687 cell_lock->Visit(cell_lock, grid_creature_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
1690 for(std::list<Creature*>::iterator iter = assistList.begin(); iter != assistList.end(); ++iter)
1692 (*iter)->SetNoCallAssistence(true);
1693 if((*iter)->AI())
1694 (*iter)->AI()->AttackStart(getVictim());
1700 void Creature::SaveRespawnTime()
1702 if(isPet() || !m_DBTableGuid)
1703 return;
1705 if(m_respawnTime > time(NULL)) // dead (no corpse)
1706 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
1707 else if(m_deathTimer > 0) // dead (corpse)
1708 objmgr.SaveCreatureRespawnTime(m_DBTableGuid,GetInstanceId(),time(NULL)+m_respawnDelay+m_deathTimer/1000);
1711 bool Creature::IsOutOfThreatArea(Unit* pVictim) const
1713 if(!pVictim)
1714 return true;
1716 if(!pVictim->IsInMap(this))
1717 return true;
1719 if(!pVictim->isTargetableForAttack())
1720 return true;
1722 if(!pVictim->isInAccessablePlaceFor(this))
1723 return true;
1725 if(sMapStore.LookupEntry(GetMapId())->Instanceable())
1726 return false;
1728 float length = pVictim->GetDistance(CombatStartX,CombatStartY,CombatStartZ);
1729 float AttackDist = GetAttackDistance(pVictim);
1730 uint32 ThreatRadius = sWorld.getConfig(CONFIG_THREAT_RADIUS);
1732 //Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and ouf of combat every update tick.
1733 return ( length > (ThreatRadius > AttackDist ? ThreatRadius : AttackDist));
1736 CreatureDataAddon const* Creature::GetCreatureAddon() const
1738 if (m_DBTableGuid)
1740 if(CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
1741 return addon;
1744 // dependent from heroic mode entry
1745 return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
1748 //creature_addon table
1749 bool Creature::LoadCreaturesAddon(bool reload)
1751 CreatureDataAddon const *cainfo = GetCreatureAddon();
1752 if(!cainfo)
1753 return false;
1755 if (cainfo->mount != 0)
1756 Mount(cainfo->mount);
1758 if (cainfo->bytes0 != 0)
1759 SetUInt32Value(UNIT_FIELD_BYTES_0, cainfo->bytes0);
1761 if (cainfo->bytes1 != 0)
1762 SetUInt32Value(UNIT_FIELD_BYTES_1, cainfo->bytes1);
1764 if (cainfo->bytes2 != 0)
1765 SetUInt32Value(UNIT_FIELD_BYTES_2, cainfo->bytes2);
1767 if (cainfo->emote != 0)
1768 SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
1770 if (cainfo->move_flags != 0)
1771 SetUnitMovementFlags(cainfo->move_flags);
1773 if(cainfo->auras)
1775 for (CreatureDataAddonAura const* cAura = cainfo->auras; cAura->spell_id; ++cAura)
1777 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura->spell_id);
1778 if (!AdditionalSpellInfo)
1780 sLog.outErrorDb("Creature (GUIDLow: %u Entry: %u ) has wrong spell %u defined in `auras` field.",GetGUIDLow(),GetEntry(),cAura->spell_id);
1781 continue;
1784 // skip already applied aura
1785 if(HasAura(cAura->spell_id,cAura->effect_idx))
1787 if(!reload)
1788 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);
1790 continue;
1793 Aura* AdditionalAura = CreateAura(AdditionalSpellInfo, cAura->effect_idx, NULL, this, this, 0);
1794 AddAura(AdditionalAura);
1795 sLog.outDebug("Spell: %u with Aura %u added to creature (GUIDLow: %u Entry: %u )", cAura->spell_id, AdditionalSpellInfo->EffectApplyAuraName[0],GetGUIDLow(),GetEntry());
1798 return true;
1801 /// Send a message to LocalDefense channel for players oposition team in the zone
1802 void Creature::SendZoneUnderAttackMessage(Player* attacker)
1804 uint32 enemy_team = attacker->GetTeam();
1806 WorldPacket data(SMSG_ZONE_UNDER_ATTACK,4);
1807 data << (uint32)GetZoneId();
1808 sWorld.SendGlobalMessage(&data,NULL,(enemy_team==ALLIANCE ? HORDE : ALLIANCE));
1811 void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time)
1813 m_CreatureSpellCooldowns[spell_id] = end_time;
1816 void Creature::_AddCreatureCategoryCooldown(uint32 category, time_t apply_time)
1818 m_CreatureCategoryCooldowns[category] = apply_time;
1821 void Creature::AddCreatureSpellCooldown(uint32 spellid)
1823 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
1824 if(!spellInfo)
1825 return;
1827 uint32 cooldown = GetSpellRecoveryTime(spellInfo);
1828 if(cooldown)
1829 _AddCreatureSpellCooldown(spellid, time(NULL) + cooldown/1000);
1831 if(spellInfo->Category)
1832 _AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
1834 m_GlobalCooldown = spellInfo->StartRecoveryTime;
1837 bool Creature::HasCategoryCooldown(uint32 spell_id) const
1839 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1840 if(!spellInfo)
1841 return false;
1843 // check global cooldown if spell affected by it
1844 if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
1845 return true;
1847 CreatureSpellCooldowns::const_iterator itr = m_CreatureCategoryCooldowns.find(spellInfo->Category);
1848 return(itr != m_CreatureCategoryCooldowns.end() && time_t(itr->second + (spellInfo->CategoryRecoveryTime / 1000)) > time(NULL));
1851 bool Creature::HasSpellCooldown(uint32 spell_id) const
1853 CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id);
1854 return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL)) || HasCategoryCooldown(spell_id);
1857 bool Creature::IsInEvadeMode() const
1859 return !i_motionMaster.empty() && i_motionMaster.GetCurrentMovementGeneratorType() == HOME_MOTION_TYPE;
1862 bool Creature::HasSpell(uint32 spellID) const
1864 uint8 i;
1865 for(i = 0; i < CREATURE_MAX_SPELLS; ++i)
1866 if(spellID == m_spells[i])
1867 break;
1868 return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
1871 time_t Creature::GetRespawnTimeEx() const
1873 time_t now = time(NULL);
1874 if(m_respawnTime > now) // dead (no corpse)
1875 return m_respawnTime;
1876 else if(m_deathTimer > 0) // dead (corpse)
1877 return now+m_respawnDelay+m_deathTimer/1000;
1878 else
1879 return now;
1882 void Creature::GetRespawnCoord( float &x, float &y, float &z, float* ori, float* dist ) const
1884 if (m_DBTableGuid)
1886 if (CreatureData const* data = objmgr.GetCreatureData(GetDBTableGUIDLow()))
1888 x = data->posX;
1889 y = data->posY;
1890 z = data->posZ;
1891 if(ori)
1892 *ori = data->orientation;
1893 if(dist)
1894 *dist = data->spawndist;
1896 return;
1900 x = GetPositionX();
1901 y = GetPositionY();
1902 z = GetPositionZ();
1903 if(ori)
1904 *ori = GetOrientation();
1905 if(dist)
1906 *dist = 0;
1909 void Creature::AllLootRemovedFromCorpse()
1911 if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE))
1913 uint32 nDeathTimer;
1915 CreatureInfo const *cinfo = GetCreatureInfo();
1917 // corpse was not skinnable -> apply corpse looted timer
1918 if (!cinfo || !cinfo->SkinLootId)
1919 nDeathTimer = (uint32)((m_corpseDelay * 1000) * sWorld.getRate(RATE_CORPSE_DECAY_LOOTED));
1920 // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
1921 else
1922 nDeathTimer = 0;
1924 // update death timer only if looted timer is shorter
1925 if (m_deathTimer > nDeathTimer)
1926 m_deathTimer = nDeathTimer;
1930 uint32 Creature::getLevelForTarget( Unit const* target ) const
1932 if(!isWorldBoss())
1933 return Unit::getLevelForTarget(target);
1935 uint32 level = target->getLevel()+sWorld.getConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
1936 if(level < 1)
1937 return 1;
1938 if(level > 255)
1939 return 255;
1940 return level;
1943 char const* Creature::GetScriptName() const
1945 return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptName;
1948 VendorItemData const* Creature::GetVendorItems() const
1950 return objmgr.GetNpcVendorItemList(GetEntry());
1953 uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem)
1955 if(!vItem->maxcount)
1956 return vItem->maxcount;
1958 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1959 for(; itr != m_vendorItemCounts.end(); ++itr)
1960 if(itr->itemId==vItem->item)
1961 break;
1963 if(itr == m_vendorItemCounts.end())
1964 return vItem->maxcount;
1966 VendorItemCount* vCount = &*itr;
1968 time_t ptime = time(NULL);
1970 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
1972 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
1974 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
1975 if((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount )
1977 m_vendorItemCounts.erase(itr);
1978 return vItem->maxcount;
1981 vCount->count += diff * pProto->BuyCount;
1982 vCount->lastIncrementTime = ptime;
1985 return vCount->count;
1988 uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count)
1990 if(!vItem->maxcount)
1991 return 0;
1993 VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
1994 for(; itr != m_vendorItemCounts.end(); ++itr)
1995 if(itr->itemId==vItem->item)
1996 break;
1998 if(itr == m_vendorItemCounts.end())
2000 uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0;
2001 m_vendorItemCounts.push_back(VendorItemCount(vItem->item,new_count));
2002 return new_count;
2005 VendorItemCount* vCount = &*itr;
2007 time_t ptime = time(NULL);
2009 if( vCount->lastIncrementTime + vItem->incrtime <= ptime )
2011 ItemPrototype const* pProto = objmgr.GetItemPrototype(vItem->item);
2013 uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime);
2014 if((vCount->count + diff * pProto->BuyCount) < vItem->maxcount )
2015 vCount->count += diff * pProto->BuyCount;
2016 else
2017 vCount->count = vItem->maxcount;
2020 vCount->count = vCount->count > used_count ? vCount->count-used_count : 0;
2021 vCount->lastIncrementTime = ptime;
2022 return vCount->count;
2025 TrainerSpellData const* Creature::GetTrainerSpells() const
2027 return objmgr.GetNpcTrainerSpells(GetEntry());