Added missing talent points update at player/pet level change.
[AHbot.git] / src / game / Pet.cpp
blob3e5253bdcb9aaf5e97adb520efd996714ae8ed09
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 "Log.h"
22 #include "WorldPacket.h"
23 #include "ObjectMgr.h"
24 #include "SpellMgr.h"
25 #include "Pet.h"
26 #include "Formulas.h"
27 #include "SpellAuras.h"
28 #include "CreatureAI.h"
29 #include "Unit.h"
30 #include "Util.h"
32 char const* petTypeSuffix[MAX_PET_TYPE] =
34 "'s Minion", // SUMMON_PET
35 "'s Pet", // HUNTER_PET
36 "'s Guardian", // GUARDIAN_PET
37 "'s Companion" // MINI_PET
40 Pet::Pet(PetType type) :
41 Creature(), m_removed(false), m_petType(type), m_happinessTimer(7500), m_duration(0), m_resetTalentsCost(0),
42 m_bonusdamage(0), m_resetTalentsTime(0), m_usedTalentCount(0), m_auraUpdateMask(0), m_loading(false),
43 m_declinedname(NULL)
45 m_isPet = true;
46 m_name = "Pet";
47 m_regenTimer = 4000;
49 // pets always have a charminfo, even if they are not actually charmed
50 CharmInfo* charmInfo = InitCharmInfo(this);
52 if(type == MINI_PET) // always passive
53 charmInfo->SetReactState(REACT_PASSIVE);
54 else if(type == GUARDIAN_PET) // always aggressive
55 charmInfo->SetReactState(REACT_AGGRESSIVE);
58 Pet::~Pet()
60 if(m_uint32Values) // only for fully created Object
62 for (PetSpellMap::const_iterator i = m_spells.begin(); i != m_spells.end(); ++i)
63 delete i->second;
64 ObjectAccessor::Instance().RemoveObject(this);
67 delete m_declinedname;
70 void Pet::AddToWorld()
72 ///- Register the pet for guid lookup
73 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
74 Unit::AddToWorld();
77 void Pet::RemoveFromWorld()
79 ///- Remove the pet from the accessor
80 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
81 ///- Don't call the function for Creature, normal mobs + totems go in a different storage
82 Unit::RemoveFromWorld();
85 bool Pet::LoadPetFromDB( Player* owner, uint32 petentry, uint32 petnumber, bool current )
87 m_loading = true;
89 uint32 ownerid = owner->GetGUIDLow();
91 QueryResult *result;
93 if (petnumber)
94 // known petnumber entry 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
95 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
96 "FROM character_pet WHERE owner = '%u' AND id = '%u'",
97 ownerid, petnumber);
98 else if (current)
99 // current pet (slot 0) 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
100 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
101 "FROM character_pet WHERE owner = '%u' AND slot = '%u'",
102 ownerid, PET_SAVE_AS_CURRENT );
103 else if (petentry)
104 // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
105 // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
106 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
107 "FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '%u' OR slot > '%u') ",
108 ownerid, petentry,PET_SAVE_AS_CURRENT,PET_SAVE_LAST_STABLE_SLOT);
109 else
110 // any current or other non-stabled pet (for hunter "call pet")
111 // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
112 result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, talentpoints, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType "
113 "FROM character_pet WHERE owner = '%u' AND (slot = '%u' OR slot > '%u') ",
114 ownerid,PET_SAVE_AS_CURRENT,PET_SAVE_LAST_STABLE_SLOT);
116 if(!result)
117 return false;
119 Field *fields = result->Fetch();
121 // update for case of current pet "slot = 0"
122 petentry = fields[1].GetUInt32();
123 if (!petentry)
125 delete result;
126 return false;
129 uint32 summon_spell_id = fields[19].GetUInt32();
130 SpellEntry const* spellInfo = sSpellStore.LookupEntry(summon_spell_id);
132 bool is_temporary_summoned = spellInfo && GetSpellDuration(spellInfo) > 0;
134 // check temporary summoned pets like mage water elemental
135 if (current && is_temporary_summoned)
137 delete result;
138 return false;
141 uint32 pet_number = fields[0].GetUInt32();
143 if (current && owner->IsPetNeedBeTemporaryUnsummoned())
145 owner->SetTemporaryUnsummonedPetNumber(pet_number);
146 delete result;
147 return false;
150 Map *map = owner->GetMap();
151 uint32 guid = objmgr.GenerateLowGuid(HIGHGUID_PET);
152 if (!Create(guid, map, owner->GetPhaseMask(), petentry, pet_number))
154 delete result;
155 return false;
158 float px, py, pz;
159 owner->GetClosePoint(px, py, pz, GetObjectSize(), PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
161 Relocate(px, py, pz, owner->GetOrientation());
163 if (!IsPositionValid())
165 sLog.outError("Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
166 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
167 delete result;
168 return false;
171 setPetType(PetType(fields[20].GetUInt8()));
172 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, owner->getFaction());
173 SetUInt32Value(UNIT_CREATED_BY_SPELL, summon_spell_id);
175 CreatureInfo const *cinfo = GetCreatureInfo();
176 if (cinfo->type == CREATURE_TYPE_CRITTER)
178 AIM_Initialize();
179 map->Add((Creature*)this);
180 delete result;
181 return true;
184 if (getPetType() == HUNTER_PET || (getPetType() == SUMMON_PET && cinfo->type == CREATURE_TYPE_DEMON && owner->getClass() == CLASS_WARLOCK))
185 m_charmInfo->SetPetNumber(pet_number, true);
186 else
187 m_charmInfo->SetPetNumber(pet_number, false);
189 SetOwnerGUID(owner->GetGUID());
190 SetDisplayId(fields[3].GetUInt32());
191 SetNativeDisplayId(fields[3].GetUInt32());
192 uint32 petlevel = fields[4].GetUInt32();
193 SetUInt32Value(UNIT_NPC_FLAGS, 0);
194 SetName(fields[9].GetString());
196 switch (getPetType())
198 case SUMMON_PET:
199 petlevel=owner->getLevel();
201 SetUInt32Value(UNIT_FIELD_BYTES_0, 2048);
202 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
203 // this enables popup window (pet dismiss, cancel)
204 break;
205 case HUNTER_PET:
206 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
207 SetByteValue(UNIT_FIELD_BYTES_1, 1, fields[7].GetUInt32());
208 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE);
209 SetByteValue(UNIT_FIELD_BYTES_2, 2, fields[10].GetBool() ? UNIT_RENAME_NOT_ALLOWED : UNIT_RENAME_ALLOWED);
211 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
212 // this enables popup window (pet abandon, cancel)
213 SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
214 SetPower(POWER_HAPPINESS, fields[13].GetUInt32());
215 setPowerType(POWER_FOCUS);
216 break;
217 default:
218 sLog.outError("Pet have incorrect type (%u) for pet loading.", getPetType());
221 InitStatsForLevel(petlevel);
222 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
223 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, fields[5].GetUInt32());
224 SetCreatorGUID(owner->GetGUID());
226 m_charmInfo->SetReactState(ReactStates(fields[6].GetUInt8()));
228 uint32 savedhealth = fields[11].GetUInt32();
229 uint32 savedmana = fields[12].GetUInt32();
231 // set current pet as current
232 // 0=current
233 // 1..MAX_PET_STABLES in stable slot
234 // PET_SAVE_NOT_IN_SLOT(100) = not stable slot (summoning))
235 if (fields[8].GetUInt32() != 0)
237 CharacterDatabase.BeginTransaction();
238 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND slot = '%u' AND id <> '%u'",
239 PET_SAVE_NOT_IN_SLOT, ownerid, PET_SAVE_AS_CURRENT, m_charmInfo->GetPetNumber());
240 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND id = '%u'",
241 PET_SAVE_AS_CURRENT, ownerid, m_charmInfo->GetPetNumber());
242 CharacterDatabase.CommitTransaction();
245 if (!is_temporary_summoned)
247 // permanent controlled pets store state in DB
248 Tokens tokens = StrSplit(fields[14].GetString(), " ");
250 if (tokens.size() != 20)
252 delete result;
253 return false;
256 int index;
257 Tokens::iterator iter;
258 for(iter = tokens.begin(), index = 0; index < 10; ++iter, ++index )
260 m_charmInfo->GetActionBarEntry(index)->Type = atol((*iter).c_str());
261 ++iter;
262 m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
265 //init teach spells
266 tokens = StrSplit(fields[15].GetString(), " ");
267 for (iter = tokens.begin(), index = 0; index < 4; ++iter, ++index)
269 uint32 tmp = atol((*iter).c_str());
271 ++iter;
273 if(tmp)
274 AddTeachSpell(tmp, atol((*iter).c_str()));
275 else
276 break;
280 // since last save (in seconds)
281 uint32 timediff = (time(NULL) - fields[16].GetUInt32());
283 m_resetTalentsCost = fields[17].GetUInt32();
284 m_resetTalentsTime = fields[18].GetUInt64();
286 delete result;
288 //load spells/cooldowns/auras
289 SetCanModifyStats(true);
290 _LoadAuras(timediff);
292 //init AB
293 if (is_temporary_summoned)
295 // Temporary summoned pets always have initial spell list at load
296 InitPetCreateSpells();
298 else
300 LearnPetPassives();
301 CastPetAuras(current);
304 if (getPetType() == SUMMON_PET && !current) //all (?) summon pets come with full health when called, but not when they are current
306 SetHealth(GetMaxHealth());
307 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
309 else
311 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
312 SetPower(POWER_MANA, savedmana > GetMaxPower(POWER_MANA) ? GetMaxPower(POWER_MANA) : savedmana);
315 AIM_Initialize();
316 map->Add((Creature*)this);
318 // Spells should be loaded after pet is added to map, because in CheckCast is check on it
319 _LoadSpells();
320 _LoadSpellCooldowns();
322 owner->SetPet(this); // in DB stored only full controlled creature
323 sLog.outDebug("New Pet has guid %u", GetGUIDLow());
325 if (owner->GetTypeId() == TYPEID_PLAYER)
327 ((Player*)owner)->PetSpellInitialize();
328 if(((Player*)owner)->GetGroup())
329 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_PET);
332 if (owner->GetTypeId() == TYPEID_PLAYER && getPetType() == HUNTER_PET)
334 result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'", owner->GetGUIDLow(), GetCharmInfo()->GetPetNumber());
336 if(result)
338 if(m_declinedname)
339 delete m_declinedname;
341 m_declinedname = new DeclinedName;
342 Field *fields2 = result->Fetch();
343 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
345 m_declinedname->name[i] = fields2[i].GetCppString();
350 m_loading = false;
351 return true;
354 void Pet::SavePetToDB(PetSaveMode mode)
356 if (!GetEntry())
357 return;
359 // save only fully controlled creature
360 if (!isControlled())
361 return;
363 // not save not player pets
364 if(!IS_PLAYER_GUID(GetOwnerGUID()))
365 return;
367 Player* pOwner = (Player*)GetOwner();
368 if (!pOwner)
369 return;
371 // not save pet as current if another pet temporary unsummoned
372 if (mode == PET_SAVE_AS_CURRENT && pOwner->GetTemporaryUnsummonedPetNumber() &&
373 pOwner->GetTemporaryUnsummonedPetNumber() != m_charmInfo->GetPetNumber())
375 // pet will lost anyway at restore temporary unsummoned
376 if(getPetType()==HUNTER_PET)
377 return;
379 // for warlock case
380 mode = PET_SAVE_NOT_IN_SLOT;
383 uint32 curhealth = GetHealth();
384 uint32 curmana = GetPower(POWER_MANA);
386 // stable and not in slot saves
387 if(mode > PET_SAVE_AS_CURRENT)
389 RemoveAllAuras();
391 //only alive hunter pets get auras saved, the others don't
392 if(!(getPetType() == HUNTER_PET && isAlive()))
393 m_Auras.clear();
396 _SaveSpells();
397 _SaveSpellCooldowns();
398 _SaveAuras();
400 // current/stable/not_in_slot
401 if(mode >= PET_SAVE_AS_CURRENT)
403 uint32 owner = GUID_LOPART(GetOwnerGUID());
404 std::string name = m_name;
405 CharacterDatabase.escape_string(name);
406 CharacterDatabase.BeginTransaction();
407 // remove current data
408 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND id = '%u'", owner,m_charmInfo->GetPetNumber() );
410 // prevent duplicate using slot (except PET_SAVE_NOT_IN_SLOT)
411 if(mode <= PET_SAVE_LAST_STABLE_SLOT)
412 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND slot = '%u'",
413 PET_SAVE_NOT_IN_SLOT, owner, uint32(mode) );
415 // prevent existence another hunter pet in PET_SAVE_AS_CURRENT and PET_SAVE_NOT_IN_SLOT
416 if(getPetType()==HUNTER_PET && (mode==PET_SAVE_AS_CURRENT||mode > PET_SAVE_LAST_STABLE_SLOT))
417 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u' AND (slot = '%u' OR slot > '%u')",
418 owner,PET_SAVE_AS_CURRENT,PET_SAVE_LAST_STABLE_SLOT);
419 // save pet
420 std::ostringstream ss;
421 ss << "INSERT INTO character_pet ( id, entry, owner, modelid, level, exp, Reactstate, talentpoints, slot, name, renamed, curhealth, curmana, curhappiness, abdata, TeachSpelldata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType) "
422 << "VALUES ("
423 << m_charmInfo->GetPetNumber() << ", "
424 << GetEntry() << ", "
425 << owner << ", "
426 << GetNativeDisplayId() << ", "
427 << getLevel() << ", "
428 << GetUInt32Value(UNIT_FIELD_PETEXPERIENCE) << ", "
429 << uint32(m_charmInfo->GetReactState()) << ", "
430 << uint32(GetFreeTalentPoints()) << ", "
431 << uint32(mode) << ", '"
432 << name.c_str() << "', "
433 << uint32((GetByteValue(UNIT_FIELD_BYTES_2, 2) == UNIT_RENAME_ALLOWED)?0:1) << ", "
434 << (curhealth<1?1:curhealth) << ", "
435 << curmana << ", "
436 << GetPower(POWER_HAPPINESS) << ", '";
438 for(uint32 i = 0; i < 10; ++i)
439 ss << uint32(m_charmInfo->GetActionBarEntry(i)->Type) << " " << uint32(m_charmInfo->GetActionBarEntry(i)->SpellOrAction) << " ";
440 ss << "', '";
442 //save spells the pet can teach to it's Master
444 int i = 0;
445 for(TeachSpellMap::const_iterator itr = m_teachspells.begin(); i < 4 && itr != m_teachspells.end(); ++i, ++itr)
446 ss << itr->first << " " << itr->second << " ";
447 for(; i < 4; ++i)
448 ss << uint32(0) << " " << uint32(0) << " ";
451 ss << "', "
452 << time(NULL) << ", "
453 << uint32(m_resetTalentsCost) << ", "
454 << uint64(m_resetTalentsTime) << ", "
455 << GetUInt32Value(UNIT_CREATED_BY_SPELL) << ", "
456 << uint32(getPetType()) << ")";
458 CharacterDatabase.Execute( ss.str().c_str() );
459 CharacterDatabase.CommitTransaction();
461 // delete
462 else
464 RemoveAllAuras();
465 DeleteFromDB(m_charmInfo->GetPetNumber());
469 void Pet::DeleteFromDB(uint32 guidlow)
471 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE id = '%u'", guidlow);
472 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE id = '%u'", guidlow);
473 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", guidlow);
474 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u'", guidlow);
475 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", guidlow);
478 void Pet::setDeathState(DeathState s) // overwrite virtual Creature::setDeathState and Unit::setDeathState
480 Creature::setDeathState(s);
481 if(getDeathState()==CORPSE)
483 //remove summoned pet (no corpse)
484 if(getPetType()==SUMMON_PET)
485 Remove(PET_SAVE_NOT_IN_SLOT);
486 // other will despawn at corpse desppawning (Pet::Update code)
487 else
489 // pet corpse non lootable and non skinnable
490 SetUInt32Value( UNIT_DYNAMIC_FLAGS, 0x00 );
491 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
493 //lose happiness when died and not in BG/Arena
494 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
495 if(!mapEntry || (mapEntry->map_type != MAP_ARENA && mapEntry->map_type != MAP_BATTLEGROUND))
496 ModifyPower(POWER_HAPPINESS, -HAPPINESS_LEVEL_SIZE);
498 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
501 else if(getDeathState()==ALIVE)
503 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
504 CastPetAuras(true);
508 void Pet::Update(uint32 diff)
510 if(m_removed) // pet already removed, just wait in remove queue, no updates
511 return;
513 switch( m_deathState )
515 case CORPSE:
517 if( m_deathTimer <= diff )
519 assert(getPetType()!=SUMMON_PET && "Must be already removed.");
520 Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER!
521 return;
523 break;
525 case ALIVE:
527 // unsummon pet that lost owner
528 Unit* owner = GetOwner();
529 if(!owner || (!IsWithinDistInMap(owner, OWNER_MAX_DISTANCE) && (owner->GetCharmGUID() && (owner->GetCharmGUID() != GetGUID()))) || (isControlled() && !owner->GetPetGUID()))
531 Remove(PET_SAVE_NOT_IN_SLOT, true);
532 return;
535 if(isControlled())
537 if( owner->GetPetGUID() != GetGUID() )
539 Remove(getPetType()==HUNTER_PET?PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
540 return;
544 if(m_duration > 0)
546 if(m_duration > diff)
547 m_duration -= diff;
548 else
550 Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT);
551 return;
555 if(getPetType() != HUNTER_PET)
556 break;
558 //regenerate Focus
559 if(m_regenTimer <= diff)
561 RegenerateFocus();
562 m_regenTimer = 4000;
564 else
565 m_regenTimer -= diff;
567 if(m_happinessTimer <= diff)
569 LooseHappiness();
570 m_happinessTimer = 7500;
572 else
573 m_happinessTimer -= diff;
575 break;
577 default:
578 break;
580 Creature::Update(diff);
583 void Pet::RegenerateFocus()
585 uint32 curValue = GetPower(POWER_FOCUS);
586 uint32 maxValue = GetMaxPower(POWER_FOCUS);
588 if (curValue >= maxValue)
589 return;
591 float addvalue = 24 * sWorld.getRate(RATE_POWER_FOCUS);
593 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
594 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
595 if ((*i)->GetModifier()->m_miscvalue == POWER_FOCUS)
596 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
598 ModifyPower(POWER_FOCUS, (int32)addvalue);
601 void Pet::LooseHappiness()
603 uint32 curValue = GetPower(POWER_HAPPINESS);
604 if (curValue <= 0)
605 return;
606 int32 addvalue = 670; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
607 if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
608 addvalue = int32(addvalue * 1.5);
609 ModifyPower(POWER_HAPPINESS, -addvalue);
612 HappinessState Pet::GetHappinessState()
614 if(GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE)
615 return UNHAPPY;
616 else if(GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2)
617 return HAPPY;
618 else
619 return CONTENT;
622 bool Pet::CanTakeMoreActiveSpells(uint32 spellid)
624 uint8 activecount = 1;
625 uint32 chainstartstore[ACTIVE_SPELLS_MAX];
627 if(IsPassiveSpell(spellid))
628 return true;
630 chainstartstore[0] = spellmgr.GetFirstSpellInChain(spellid);
632 for (PetSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
634 if(IsPassiveSpell(itr->first))
635 continue;
637 uint32 chainstart = spellmgr.GetFirstSpellInChain(itr->first);
639 uint8 x;
641 for(x = 0; x < activecount; x++)
643 if(chainstart == chainstartstore[x])
644 break;
647 if(x == activecount) //spellchain not yet saved -> add active count
649 ++activecount;
650 if(activecount > ACTIVE_SPELLS_MAX)
651 return false;
652 chainstartstore[x] = chainstart;
655 return true;
658 void Pet::Remove(PetSaveMode mode, bool returnreagent)
660 Unit* owner = GetOwner();
662 if(owner)
664 if(owner->GetTypeId()==TYPEID_PLAYER)
666 ((Player*)owner)->RemovePet(this,mode,returnreagent);
667 return;
670 // only if current pet in slot
671 if(owner->GetPetGUID()==GetGUID())
672 owner->SetPet(0);
675 CleanupsBeforeDelete();
676 AddObjectToRemoveList();
677 m_removed = true;
680 void Pet::GivePetXP(uint32 xp)
682 if(getPetType() != HUNTER_PET)
683 return;
685 if ( xp < 1 )
686 return;
688 if(!isAlive())
689 return;
691 uint32 level = getLevel();
693 // XP to money conversion processed in Player::RewardQuest
694 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
695 return;
697 uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE);
698 uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
699 uint32 newXP = curXP + xp;
701 if(newXP >= nextLvlXP && level+1 > GetOwner()->getLevel())
703 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, nextLvlXP-1);
704 return;
707 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
709 newXP -= nextLvlXP;
711 SetLevel( level + 1 );
712 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(level+1)/4);
714 level = getLevel();
715 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
716 GivePetLevel(level);
719 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, newXP);
722 void Pet::GivePetLevel(uint32 level)
724 if(!level)
725 return;
727 InitStatsForLevel(level);
728 InitTalentForLevel();
731 bool Pet::CreateBaseAtCreature(Creature* creature)
733 if(!creature)
735 sLog.outError("CRITICAL: NULL pointer parsed into CreateBaseAtCreature()");
736 return false;
738 uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
740 sLog.outBasic("SetInstanceID()");
741 SetInstanceId(creature->GetInstanceId());
743 sLog.outBasic("Create pet");
744 uint32 pet_number = objmgr.GeneratePetNumber();
745 if(!Create(guid, creature->GetMap(), creature->GetPhaseMask(), creature->GetEntry(), pet_number))
746 return false;
748 Relocate(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetOrientation());
750 if(!IsPositionValid())
752 sLog.outError("Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
753 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
754 return false;
757 CreatureInfo const *cinfo = GetCreatureInfo();
758 if(!cinfo)
760 sLog.outError("CreateBaseAtCreature() failed, creatureInfo is missing!");
761 return false;
764 if(cinfo->type == CREATURE_TYPE_CRITTER)
766 setPetType(MINI_PET);
767 return true;
769 SetDisplayId(creature->GetDisplayId());
770 SetNativeDisplayId(creature->GetNativeDisplayId());
771 SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
772 SetPower(POWER_HAPPINESS, 166500);
773 setPowerType(POWER_FOCUS);
774 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, 0);
775 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
776 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(creature->getLevel())/4);
777 SetUInt32Value(UNIT_NPC_FLAGS, 0);
779 if(CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family))
780 SetName(cFamily->Name[sWorld.GetDefaultDbcLocale()]);
781 else
782 SetName(creature->GetNameForLocaleIdx(objmgr.GetDBCLocaleIndex()));
784 if(cinfo->type == CREATURE_TYPE_BEAST)
786 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
787 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
788 SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
789 SetUInt32Value(UNIT_MOD_CAST_SPEED, creature->GetUInt32Value(UNIT_MOD_CAST_SPEED));
791 return true;
794 bool Pet::InitStatsForLevel(uint32 petlevel)
796 CreatureInfo const *cinfo = GetCreatureInfo();
797 assert(cinfo);
799 Unit* owner = GetOwner();
800 if(!owner)
802 sLog.outError("attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo->Entry);
803 return false;
806 uint32 creature_ID = (getPetType() == HUNTER_PET) ? 1 : cinfo->Entry;
808 SetLevel(petlevel);
810 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
812 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50));
814 SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
815 SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
816 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
818 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0);
820 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family);
821 if(cFamily && cFamily->minScale > 0.0f && getPetType()==HUNTER_PET)
823 float scale;
824 if (getLevel() >= cFamily->maxScaleLevel)
825 scale = cFamily->maxScale;
826 else if (getLevel() <= cFamily->minScaleLevel)
827 scale = cFamily->minScale;
828 else
829 scale = cFamily->minScale + (getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale);
831 SetFloatValue(OBJECT_FIELD_SCALE_X, scale);
833 m_bonusdamage = 0;
835 int32 createResistance[MAX_SPELL_SCHOOL] = {0,0,0,0,0,0,0};
837 if(cinfo && getPetType() != HUNTER_PET)
839 createResistance[SPELL_SCHOOL_HOLY] = cinfo->resistance1;
840 createResistance[SPELL_SCHOOL_FIRE] = cinfo->resistance2;
841 createResistance[SPELL_SCHOOL_NATURE] = cinfo->resistance3;
842 createResistance[SPELL_SCHOOL_FROST] = cinfo->resistance4;
843 createResistance[SPELL_SCHOOL_SHADOW] = cinfo->resistance5;
844 createResistance[SPELL_SCHOOL_ARCANE] = cinfo->resistance6;
847 switch(getPetType())
849 case SUMMON_PET:
851 if(owner->GetTypeId() == TYPEID_PLAYER)
853 switch(owner->getClass())
855 case CLASS_WARLOCK:
858 //the damage bonus used for pets is either fire or shadow damage, whatever is higher
859 uint32 fire = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE);
860 uint32 shadow = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW);
861 uint32 val = (fire > shadow) ? fire : shadow;
863 SetBonusDamage(int32 (val * 0.15f));
864 //bonusAP += val * 0.57;
865 break;
867 case CLASS_MAGE:
869 //40% damage bonus of mage's frost damage
870 float val = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) * 0.4;
871 if(val < 0)
872 val = 0;
873 SetBonusDamage( int32(val));
874 break;
876 default:
877 break;
881 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
882 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
884 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
886 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
887 if(pInfo) // exist in DB
889 SetCreateHealth(pInfo->health);
890 SetCreateMana(pInfo->mana);
892 if(pInfo->armor > 0)
893 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
895 for(int stat = 0; stat < MAX_STATS; ++stat)
897 SetCreateStat(Stats(stat), float(pInfo->stats[stat]));
900 else // not exist in DB, use some default fake data
902 sLog.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo->Entry);
904 // remove elite bonuses included in DB values
905 SetCreateHealth(uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
906 SetCreateMana( uint32(((float(cinfo->maxmana) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
908 SetCreateStat(STAT_STRENGTH, 22);
909 SetCreateStat(STAT_AGILITY, 22);
910 SetCreateStat(STAT_STAMINA, 25);
911 SetCreateStat(STAT_INTELLECT, 28);
912 SetCreateStat(STAT_SPIRIT, 27);
914 break;
916 case HUNTER_PET:
918 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(petlevel)/4);
919 learnLevelupSpells();
920 //these formula may not be correct; however, it is designed to be close to what it should be
921 //this makes dps 0.5 of pets level
922 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
923 //damage range is then petlevel / 2
924 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
925 //damage is increased afterwards as strength and pet scaling modify attack power
927 //stored standard pet stats are entry 1 in pet_levelinfo
928 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
929 if(pInfo) // exist in DB
931 SetCreateHealth(pInfo->health);
932 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
933 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
935 for( int i = STAT_STRENGTH; i < MAX_STATS; ++i)
937 SetCreateStat(Stats(i), float(pInfo->stats[i]));
940 else // not exist in DB, use some default fake data
942 sLog.outErrorDb("Hunter pet levelstats missing in DB");
944 // remove elite bonuses included in DB values
945 SetCreateHealth( uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
947 SetCreateStat(STAT_STRENGTH, 22);
948 SetCreateStat(STAT_AGILITY, 22);
949 SetCreateStat(STAT_STAMINA, 25);
950 SetCreateStat(STAT_INTELLECT, 28);
951 SetCreateStat(STAT_SPIRIT, 27);
953 break;
955 case GUARDIAN_PET:
956 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
957 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, 1000);
959 SetCreateMana(28 + 10*petlevel);
960 SetCreateHealth(28 + 30*petlevel);
962 // FIXME: this is wrong formula, possible each guardian pet have own damage formula
963 //these formula may not be correct; however, it is designed to be close to what it should be
964 //this makes dps 0.5 of pets level
965 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)));
966 //damage range is then petlevel / 2
967 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)));
968 break;
969 default:
970 sLog.outError("Pet have incorrect type (%u) for levelup.", getPetType());
971 break;
974 for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
975 SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START + i), BASE_VALUE, float(createResistance[i]));
977 UpdateAllStats();
979 SetHealth(GetMaxHealth());
980 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
982 return true;
985 bool Pet::HaveInDiet(ItemPrototype const* item) const
987 if (!item->FoodType)
988 return false;
990 CreatureInfo const* cInfo = GetCreatureInfo();
991 if(!cInfo)
992 return false;
994 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
995 if(!cFamily)
996 return false;
998 uint32 diet = cFamily->petFoodMask;
999 uint32 FoodMask = 1 << (item->FoodType-1);
1000 return diet & FoodMask;
1003 uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel)
1005 // -5 or greater food level
1006 if(getLevel() <= itemlevel + 5) //possible to feed level 60 pet with level 55 level food for full effect
1007 return 35000;
1008 // -10..-6
1009 else if(getLevel() <= itemlevel + 10) //pure guess, but sounds good
1010 return 17000;
1011 // -14..-11
1012 else if(getLevel() <= itemlevel + 14) //level 55 food gets green on 70, makes sense to me
1013 return 8000;
1014 // -15 or less
1015 else
1016 return 0; //food too low level
1019 void Pet::_LoadSpellCooldowns()
1021 m_CreatureSpellCooldowns.clear();
1022 m_CreatureCategoryCooldowns.clear();
1024 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1026 if(result)
1028 time_t curTime = time(NULL);
1030 WorldPacket data(SMSG_SPELL_COOLDOWN, (8+1+result->GetRowCount()*8));
1031 data << GetGUID();
1032 data << uint8(0x0); // flags (0x1, 0x2)
1036 Field *fields = result->Fetch();
1038 uint32 spell_id = fields[0].GetUInt32();
1039 time_t db_time = (time_t)fields[1].GetUInt64();
1041 if(!sSpellStore.LookupEntry(spell_id))
1043 sLog.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo->GetPetNumber(),spell_id);
1044 continue;
1047 // skip outdated cooldown
1048 if(db_time <= curTime)
1049 continue;
1051 data << uint32(spell_id);
1052 data << uint32(uint32(db_time-curTime)*IN_MILISECONDS);
1054 _AddCreatureSpellCooldown(spell_id,db_time);
1056 sLog.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).", m_charmInfo->GetPetNumber(), spell_id, uint32(db_time-curTime));
1058 while( result->NextRow() );
1060 delete result;
1062 if(!m_CreatureSpellCooldowns.empty() && GetOwner())
1064 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1069 void Pet::_SaveSpellCooldowns()
1071 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1073 time_t curTime = time(NULL);
1075 // remove oudated and save active
1076 for(CreatureSpellCooldowns::iterator itr = m_CreatureSpellCooldowns.begin();itr != m_CreatureSpellCooldowns.end();)
1078 if(itr->second <= curTime)
1079 m_CreatureSpellCooldowns.erase(itr++);
1080 else
1082 CharacterDatabase.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" I64FMTD "')", m_charmInfo->GetPetNumber(), itr->first, uint64(itr->second));
1083 ++itr;
1088 void Pet::_LoadSpells()
1090 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active FROM pet_spell WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1092 if(result)
1096 Field *fields = result->Fetch();
1098 addSpell(fields[0].GetUInt32(), fields[1].GetUInt16(), PETSPELL_UNCHANGED);
1100 while( result->NextRow() );
1102 delete result;
1106 void Pet::_SaveSpells()
1108 for (PetSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
1110 ++next;
1111 if (itr->second->type == PETSPELL_FAMILY) continue; // prevent saving family passives to DB
1112 if (itr->second->state == PETSPELL_REMOVED || itr->second->state == PETSPELL_CHANGED)
1113 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
1114 if (itr->second->state == PETSPELL_NEW || itr->second->state == PETSPELL_CHANGED)
1115 CharacterDatabase.PExecute("INSERT INTO pet_spell (guid,spell,active) VALUES ('%u', '%u', '%u')", m_charmInfo->GetPetNumber(), itr->first, itr->second->active);
1117 if (itr->second->state == PETSPELL_REMOVED)
1118 _removeSpell(itr->first);
1119 else
1120 itr->second->state = PETSPELL_UNCHANGED;
1124 void Pet::_LoadAuras(uint32 timediff)
1126 m_Auras.clear();
1127 for (int i = 0; i < TOTAL_AURAS; ++i)
1128 m_modAuras[i].clear();
1130 QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1132 if(result)
1136 Field *fields = result->Fetch();
1137 uint64 caster_guid = fields[0].GetUInt64();
1138 uint32 spellid = fields[1].GetUInt32();
1139 uint32 effindex = fields[2].GetUInt32();
1140 uint32 stackcount= fields[3].GetUInt32();
1141 int32 damage = (int32)fields[4].GetUInt32();
1142 int32 maxduration = (int32)fields[5].GetUInt32();
1143 int32 remaintime = (int32)fields[6].GetUInt32();
1144 int32 remaincharges = (int32)fields[7].GetUInt32();
1146 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
1147 if(!spellproto)
1149 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
1150 continue;
1153 if(effindex >= 3)
1155 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
1156 continue;
1159 // negative effects should continue counting down after logout
1160 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
1162 if(remaintime <= int32(timediff))
1163 continue;
1165 remaintime -= timediff;
1168 // prevent wrong values of remaincharges
1169 if(spellproto->procCharges)
1171 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
1172 remaincharges = spellproto->procCharges;
1174 else
1175 remaincharges = -1;
1177 /// do not load single target auras (unless they were cast by the player)
1178 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
1179 continue;
1181 for(uint32 i=0; i<stackcount; ++i)
1183 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
1185 if(!damage)
1186 damage = aura->GetModifier()->m_amount;
1187 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
1188 AddAura(aura);
1191 while( result->NextRow() );
1193 delete result;
1197 void Pet::_SaveAuras()
1199 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1201 AuraMap const& auras = GetAuras();
1202 if (auras.empty())
1203 return;
1205 spellEffectPair lastEffectPair = auras.begin()->first;
1206 uint32 stackCounter = 1;
1208 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
1210 if(itr == auras.end() || lastEffectPair != itr->first)
1212 AuraMap::const_iterator itr2 = itr;
1213 // save previous spellEffectPair to db
1214 itr2--;
1215 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
1216 /// do not save single target auras (unless they were cast by the player)
1217 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
1219 if(!itr2->second->IsPassive())
1221 // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
1222 uint8 i;
1223 for (i = 0; i < 3; ++i)
1224 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
1225 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
1226 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
1227 break;
1229 if (i == 3)
1231 CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
1232 "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%u', '%d', '%d', '%d', '%d')",
1233 m_charmInfo->GetPetNumber(), itr2->second->GetCasterGUID(),(uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->GetAuraCharges()));
1237 if(itr == auras.end())
1238 break;
1241 if (lastEffectPair == itr->first)
1242 stackCounter++;
1243 else
1245 lastEffectPair = itr->first;
1246 stackCounter = 1;
1251 bool Pet::addSpell(uint32 spell_id, uint16 active, PetSpellState state, PetSpellType type)
1253 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1254 if (!spellInfo)
1256 // do pet spell book cleanup
1257 if(state == PETSPELL_UNCHANGED) // spell load case
1259 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id);
1260 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id);
1262 else
1263 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
1265 return false;
1268 PetSpellMap::iterator itr = m_spells.find(spell_id);
1269 if (itr != m_spells.end())
1271 if (itr->second->state == PETSPELL_REMOVED)
1273 delete itr->second;
1274 m_spells.erase(itr);
1275 state = PETSPELL_CHANGED;
1277 else if (state == PETSPELL_UNCHANGED && itr->second->state != PETSPELL_UNCHANGED)
1279 // can be in case spell loading but learned at some previous spell loading
1280 itr->second->state = PETSPELL_UNCHANGED;
1282 if(active == ACT_ENABLED)
1283 ToggleAutocast(spell_id, true);
1284 else if(active == ACT_DISABLED)
1285 ToggleAutocast(spell_id, false);
1287 return false;
1289 else
1290 return false;
1293 uint32 oldspell_id = 0;
1295 PetSpell *newspell = new PetSpell;
1296 newspell->state = state;
1297 newspell->type = type;
1299 if(active == ACT_DECIDE) //active was not used before, so we save it's autocast/passive state here
1301 if(IsPassiveSpell(spell_id))
1302 newspell->active = ACT_PASSIVE;
1303 else
1304 newspell->active = ACT_DISABLED;
1306 else
1307 newspell->active = active;
1309 // talent: unlearn all other talent ranks (high and low)
1310 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
1312 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
1314 for(int i=0; i < MAX_TALENT_RANK; ++i)
1316 // skip learning spell and no rank spell case
1317 uint32 rankSpellId = talentInfo->RankID[i];
1318 if(!rankSpellId || rankSpellId==spell_id)
1319 continue;
1321 // skip unknown ranks
1322 if(!HasSpell(rankSpellId))
1323 continue;
1324 removeSpell(rankSpellId);
1328 else if(uint32 chainstart = spellmgr.GetFirstSpellInChain(spell_id))
1330 for (PetSpellMap::const_iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2)
1332 if(itr2->second->state == PETSPELL_REMOVED) continue;
1334 if(spellmgr.GetFirstSpellInChain(itr2->first) == chainstart)
1336 newspell->active = itr2->second->active;
1338 if(newspell->active == ACT_ENABLED)
1339 ToggleAutocast(itr2->first, false);
1341 oldspell_id = itr2->first;
1342 unlearnSpell(itr2->first);
1343 break;
1348 m_spells[spell_id] = newspell;
1350 if (IsPassiveSpell(spell_id))
1351 CastSpell(this, spell_id, true);
1352 else if(state == PETSPELL_NEW)
1353 m_charmInfo->AddSpellToAB(oldspell_id, spell_id);
1355 if(newspell->active == ACT_ENABLED)
1356 ToggleAutocast(spell_id, true);
1358 uint32 talentCost = GetTalentSpellCost(spell_id);
1359 if (talentCost)
1361 int32 free_points = GetMaxTalentPointsForLevel(getLevel());
1362 m_usedTalentCount+=talentCost;
1363 // update free talent points
1364 free_points-=m_usedTalentCount;
1365 SetFreeTalentPoints(free_points > 0 ? free_points : 0);
1367 return true;
1370 bool Pet::learnSpell(uint32 spell_id)
1372 // prevent duplicated entires in spell book
1373 if (!addSpell(spell_id))
1374 return false;
1376 Unit* owner = GetOwner();
1377 if(owner && owner->GetTypeId() == TYPEID_PLAYER)
1379 if(!m_loading)
1381 WorldPacket data(SMSG_PET_LEARNED_SPELL, 2);
1382 data << uint16(spell_id);
1383 ((Player*)owner)->GetSession()->SendPacket(&data);
1385 ((Player*)owner)->PetSpellInitialize();
1387 return true;
1390 void Pet::learnLevelupSpells()
1392 PetLevelupSpellSet const *levelupSpells = spellmgr.GetPetLevelupSpellList(GetCreatureInfo()->family);
1393 if(!levelupSpells)
1394 return;
1396 uint32 level = getLevel();
1398 for(PetLevelupSpellSet::const_iterator itr = levelupSpells->begin(); itr != levelupSpells->end(); ++itr)
1400 if(itr->first <= level)
1401 learnSpell(itr->second);
1402 else
1403 unlearnSpell(itr->second);
1407 bool Pet::unlearnSpell(uint32 spell_id)
1409 if(removeSpell(spell_id))
1411 if(GetOwner()->GetTypeId() == TYPEID_PLAYER)
1413 if(!m_loading)
1415 WorldPacket data(SMSG_PET_REMOVED_SPELL, 2);
1416 data << uint16(spell_id);
1417 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1420 return true;
1422 return false;
1425 bool Pet::removeSpell(uint32 spell_id)
1427 PetSpellMap::iterator itr = m_spells.find(spell_id);
1428 if (itr == m_spells.end())
1429 return false;
1431 if(itr->second->state == PETSPELL_REMOVED)
1432 return false;
1434 if(itr->second->state == PETSPELL_NEW)
1436 delete itr->second;
1437 m_spells.erase(itr);
1439 else
1440 itr->second->state = PETSPELL_REMOVED;
1442 RemoveAurasDueToSpell(spell_id);
1444 uint32 talentCost = GetTalentSpellCost(spell_id);
1445 if (talentCost > 0)
1447 if (m_usedTalentCount > talentCost)
1448 m_usedTalentCount-=talentCost;
1449 else
1450 m_usedTalentCount = 0;
1451 // update free talent points
1452 int32 free_points = GetMaxTalentPointsForLevel(getLevel()) - m_usedTalentCount;
1453 SetFreeTalentPoints(free_points > 0 ? free_points : 0);
1456 return true;
1459 bool Pet::_removeSpell(uint32 spell_id)
1461 PetSpellMap::iterator itr = m_spells.find(spell_id);
1462 if (itr != m_spells.end())
1464 delete itr->second;
1465 m_spells.erase(itr);
1466 return true;
1468 return false;
1471 void Pet::InitPetCreateSpells()
1473 m_charmInfo->InitPetActionBar();
1475 for (PetSpellMap::const_iterator i = m_spells.begin(); i != m_spells.end(); ++i)
1476 delete i->second;
1477 m_spells.clear();
1479 uint32 petspellid;
1480 PetCreateSpellEntry const* CreateSpells = objmgr.GetPetCreateSpellEntry(GetEntry());
1481 if(CreateSpells)
1483 for(uint8 i = 0; i < 4; ++i)
1485 if(!CreateSpells->spellid[i])
1486 break;
1488 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(CreateSpells->spellid[i]);
1489 if(!learn_spellproto)
1490 continue;
1492 if(learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_SPELL || learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_PET_SPELL)
1494 petspellid = learn_spellproto->EffectTriggerSpell[0];
1495 Unit* owner = GetOwner();
1496 if(owner->GetTypeId() == TYPEID_PLAYER && !((Player*)owner)->HasSpell(learn_spellproto->Id))
1498 if(IsPassiveSpell(petspellid)) //learn passive skills when tamed, not sure if thats right
1499 ((Player*)owner)->learnSpell(learn_spellproto->Id,false);
1500 else
1501 AddTeachSpell(learn_spellproto->EffectTriggerSpell[0], learn_spellproto->Id);
1504 else
1505 petspellid = learn_spellproto->Id;
1507 addSpell(petspellid);
1511 LearnPetPassives();
1513 CastPetAuras(false);
1516 void Pet::CheckLearning(uint32 spellid)
1518 //charmed case -> prevent crash
1519 if(GetTypeId() == TYPEID_PLAYER || getPetType() != HUNTER_PET)
1520 return;
1522 Unit* owner = GetOwner();
1524 if(m_teachspells.empty() || !owner || owner->GetTypeId() != TYPEID_PLAYER)
1525 return;
1527 TeachSpellMap::iterator itr = m_teachspells.find(spellid);
1528 if(itr == m_teachspells.end())
1529 return;
1531 if(urand(0, 100) < 10)
1533 ((Player*)owner)->learnSpell(itr->second,false);
1534 m_teachspells.erase(itr);
1538 bool Pet::resetTalents(bool no_cost)
1540 Unit *owner = GetOwner();
1541 if (!owner || owner->GetTypeId()!=TYPEID_PLAYER)
1542 return false;
1544 CreatureInfo const * ci = GetCreatureInfo();
1545 if(!ci)
1546 return false;
1547 // Check pet talent type
1548 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
1549 if(!pet_family || pet_family->petTalentType < 0)
1550 return false;
1552 Player *player = (Player *)owner;
1554 uint32 level = getLevel();
1555 uint32 talentPointsForLevel = GetMaxTalentPointsForLevel(level);
1557 if (m_usedTalentCount == 0)
1559 SetFreeTalentPoints(talentPointsForLevel);
1560 return false;
1563 uint32 cost = 0;
1565 if(!no_cost)
1567 cost = resetTalentsCost();
1569 if (player->GetMoney() < cost)
1571 player->SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
1572 return false;
1576 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
1578 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
1580 if (!talentInfo) continue;
1582 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
1584 if(!talentTabInfo)
1585 continue;
1587 // unlearn only talents for pets family talent type
1588 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
1589 continue;
1591 for (int j = 0; j < MAX_TALENT_RANK; j++)
1593 for(PetSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end();)
1595 if(itr->second->state == PETSPELL_REMOVED)
1597 ++itr;
1598 continue;
1600 // remove learned spells (all ranks)
1601 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
1603 // unlearn if first rank is talent or learned by talent
1604 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
1606 removeSpell(itr->first);
1607 itr = m_spells.begin();
1608 continue;
1610 else
1611 ++itr;
1616 SetFreeTalentPoints(talentPointsForLevel);
1618 if(!no_cost)
1620 player->ModifyMoney(-(int32)cost);
1622 m_resetTalentsCost = cost;
1623 m_resetTalentsTime = time(NULL);
1625 player->PetSpellInitialize();
1626 return true;
1629 void Pet::InitTalentForLevel()
1631 uint32 level = getLevel();
1632 uint32 talentPointsForLevel = GetMaxTalentPointsForLevel(level);
1633 // Reset talents in case low level (on level down) or wrong points for level (hunter can unlearn TP increase talent)
1634 if(talentPointsForLevel == 0 || m_usedTalentCount > talentPointsForLevel)
1636 // Remove all talent points
1637 resetTalents(true);
1639 SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount);
1641 Unit *owner = GetOwner();
1642 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
1643 return;
1645 ((Player*)owner)->SendTalentsInfoData(true);
1648 uint32 Pet::resetTalentsCost() const
1650 uint32 days = (sWorld.GetGameTime() - m_resetTalentsTime)/DAY;
1652 // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
1653 if(m_resetTalentsCost < 10*SILVER || days > 0)
1654 return 10*SILVER;
1655 // then 50 silver
1656 else if(m_resetTalentsCost < 50*SILVER)
1657 return 50*SILVER;
1658 // then 1 gold
1659 else if(m_resetTalentsCost < 1*GOLD)
1660 return 1*GOLD;
1661 // then increasing at a rate of 1 gold; cap 10 gold
1662 else
1663 return (m_resetTalentsCost + 1*GOLD > 10*GOLD ? 10*GOLD : m_resetTalentsCost + 1*GOLD);
1666 uint8 Pet::GetMaxTalentPointsForLevel(uint32 level)
1668 uint8 points = (level >= 20) ? ((level - 16) / 4) : 0;
1669 // Mod points from owner SPELL_AURA_MOD_PET_TALENT_POINTS
1670 if (Unit *owner = GetOwner())
1671 points+=owner->GetTotalAuraModifier(SPELL_AURA_MOD_PET_TALENT_POINTS);
1672 return points;
1675 void Pet::ToggleAutocast(uint32 spellid, bool apply)
1677 if(IsPassiveSpell(spellid))
1678 return;
1680 PetSpellMap::const_iterator itr = m_spells.find(spellid);
1682 int i;
1684 if(apply)
1686 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; ++i)
1687 ; // just search
1689 if (i == m_autospells.size())
1691 m_autospells.push_back(spellid);
1693 if(itr->second->active != ACT_ENABLED)
1695 itr->second->active = ACT_ENABLED;
1696 if(itr->second->state != PETSPELL_NEW)
1697 itr->second->state = PETSPELL_CHANGED;
1701 else
1703 AutoSpellList::iterator itr2 = m_autospells.begin();
1704 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; ++i, itr2++)
1705 ; // just search
1707 if (i < m_autospells.size())
1709 m_autospells.erase(itr2);
1710 if(itr->second->active != ACT_DISABLED)
1712 itr->second->active = ACT_DISABLED;
1713 if(itr->second->state != PETSPELL_NEW)
1714 itr->second->state = PETSPELL_CHANGED;
1720 bool Pet::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 pet_number)
1722 SetMapId(map->GetId());
1723 SetInstanceId(map->GetInstanceId());
1724 SetPhaseMask(phaseMask,false);
1726 Object::_Create(guidlow, pet_number, HIGHGUID_PET);
1728 m_DBTableGuid = guidlow;
1729 m_originalEntry = Entry;
1731 if(!InitEntry(Entry))
1732 return false;
1734 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE);
1736 if(getPetType() == MINI_PET) // always non-attackable
1737 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
1739 return true;
1742 bool Pet::HasSpell(uint32 spell) const
1744 PetSpellMap::const_iterator itr = m_spells.find(spell);
1745 return (itr != m_spells.end() && itr->second->state != PETSPELL_REMOVED );
1748 // Get all passive spells in our skill line
1749 void Pet::LearnPetPassives()
1751 CreatureInfo const* cInfo = GetCreatureInfo();
1752 if(!cInfo)
1753 return;
1755 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
1756 if(!cFamily)
1757 return;
1759 PetFamilySpellsStore::const_iterator petStore = sPetFamilySpellsStore.find(cFamily->ID);
1760 if(petStore != sPetFamilySpellsStore.end())
1762 for(PetFamilySpellsSet::const_iterator petSet = petStore->second.begin(); petSet != petStore->second.end(); ++petSet)
1763 addSpell(*petSet, ACT_DECIDE, PETSPELL_NEW, PETSPELL_FAMILY);
1767 void Pet::CastPetAuras(bool current)
1769 Unit* owner = GetOwner();
1770 if(!owner)
1771 return;
1773 if(getPetType() != HUNTER_PET && (getPetType() != SUMMON_PET || owner->getClass() != CLASS_WARLOCK))
1774 return;
1776 for(PetAuraSet::const_iterator itr = owner->m_petAuras.begin(); itr != owner->m_petAuras.end();)
1778 PetAura const* pa = *itr;
1779 ++itr;
1781 if(!current && pa->IsRemovedOnChangePet())
1782 owner->RemovePetAura(pa);
1783 else
1784 CastPetAura(pa);
1788 void Pet::CastPetAura(PetAura const* aura)
1790 uint16 auraId = aura->GetAura(GetEntry());
1791 if(!auraId)
1792 return;
1794 if(auraId == 35696) // Demonic Knowledge
1796 int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100);
1797 CastCustomSpell(this, auraId, &basePoints, NULL, NULL, true);
1799 else
1800 CastSpell(this, auraId, true);
1803 void Pet::learnSpellHighRank(uint32 spellid)
1805 learnSpell(spellid);
1807 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
1808 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
1809 learnSpellHighRank(itr->second);