[7886] Drop use table `petcreateinfo_spell`
[getmangos.git] / src / game / Pet.cpp
blob8025d3a8536c1c74b8f3da11172581dac1b8fa89
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
61 ObjectAccessor::Instance().RemoveObject(this);
63 delete m_declinedname;
66 void Pet::AddToWorld()
68 ///- Register the pet for guid lookup
69 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
70 Unit::AddToWorld();
73 void Pet::RemoveFromWorld()
75 ///- Remove the pet from the accessor
76 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
77 ///- Don't call the function for Creature, normal mobs + totems go in a different storage
78 Unit::RemoveFromWorld();
81 bool Pet::LoadPetFromDB( Player* owner, uint32 petentry, uint32 petnumber, bool current )
83 m_loading = true;
85 uint32 ownerid = owner->GetGUIDLow();
87 QueryResult *result;
89 if (petnumber)
90 // known petnumber entry 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
91 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 "
92 "FROM character_pet WHERE owner = '%u' AND id = '%u'",
93 ownerid, petnumber);
94 else if (current)
95 // 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
96 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 "
97 "FROM character_pet WHERE owner = '%u' AND slot = '%u'",
98 ownerid, PET_SAVE_AS_CURRENT );
99 else if (petentry)
100 // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
101 // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
102 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 "
103 "FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '%u' OR slot > '%u') ",
104 ownerid, petentry,PET_SAVE_AS_CURRENT,PET_SAVE_LAST_STABLE_SLOT);
105 else
106 // any current or other non-stabled pet (for hunter "call pet")
107 // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
108 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 "
109 "FROM character_pet WHERE owner = '%u' AND (slot = '%u' OR slot > '%u') ",
110 ownerid,PET_SAVE_AS_CURRENT,PET_SAVE_LAST_STABLE_SLOT);
112 if(!result)
113 return false;
115 Field *fields = result->Fetch();
117 // update for case of current pet "slot = 0"
118 petentry = fields[1].GetUInt32();
119 if (!petentry)
121 delete result;
122 return false;
125 uint32 summon_spell_id = fields[19].GetUInt32();
126 SpellEntry const* spellInfo = sSpellStore.LookupEntry(summon_spell_id);
128 bool is_temporary_summoned = spellInfo && GetSpellDuration(spellInfo) > 0;
130 // check temporary summoned pets like mage water elemental
131 if (current && is_temporary_summoned)
133 delete result;
134 return false;
137 uint32 pet_number = fields[0].GetUInt32();
139 if (current && owner->IsPetNeedBeTemporaryUnsummoned())
141 owner->SetTemporaryUnsummonedPetNumber(pet_number);
142 delete result;
143 return false;
146 Map *map = owner->GetMap();
147 uint32 guid = objmgr.GenerateLowGuid(HIGHGUID_PET);
148 if (!Create(guid, map, owner->GetPhaseMask(), petentry, pet_number))
150 delete result;
151 return false;
154 float px, py, pz;
155 owner->GetClosePoint(px, py, pz, GetObjectSize(), PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
157 Relocate(px, py, pz, owner->GetOrientation());
159 if (!IsPositionValid())
161 sLog.outError("Pet (guidlow %d, entry %d) not loaded. Suggested coordinates isn't valid (X: %f Y: %f)",
162 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
163 delete result;
164 return false;
167 setPetType(PetType(fields[20].GetUInt8()));
168 SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, owner->getFaction());
169 SetUInt32Value(UNIT_CREATED_BY_SPELL, summon_spell_id);
171 CreatureInfo const *cinfo = GetCreatureInfo();
172 if (cinfo->type == CREATURE_TYPE_CRITTER)
174 AIM_Initialize();
175 map->Add((Creature*)this);
176 delete result;
177 return true;
180 m_charmInfo->SetPetNumber(pet_number, IsPermanentPetFor(owner));
182 SetOwnerGUID(owner->GetGUID());
183 SetDisplayId(fields[3].GetUInt32());
184 SetNativeDisplayId(fields[3].GetUInt32());
185 uint32 petlevel = fields[4].GetUInt32();
186 SetUInt32Value(UNIT_NPC_FLAGS, 0);
187 SetName(fields[9].GetString());
189 switch (getPetType())
191 case SUMMON_PET:
192 petlevel=owner->getLevel();
194 SetUInt32Value(UNIT_FIELD_BYTES_0, 2048);
195 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
196 // this enables popup window (pet dismiss, cancel)
197 break;
198 case HUNTER_PET:
199 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
200 SetByteValue(UNIT_FIELD_BYTES_1, 1, fields[7].GetUInt32());
201 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE);
202 SetByteValue(UNIT_FIELD_BYTES_2, 2, fields[10].GetBool() ? UNIT_RENAME_NOT_ALLOWED : UNIT_RENAME_ALLOWED);
204 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
205 // this enables popup window (pet abandon, cancel)
206 SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
207 SetPower(POWER_HAPPINESS, fields[13].GetUInt32());
208 setPowerType(POWER_FOCUS);
209 break;
210 default:
211 sLog.outError("Pet have incorrect type (%u) for pet loading.", getPetType());
214 if(owner->IsPvP())
215 SetPvP(true);
217 InitStatsForLevel(petlevel);
218 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
219 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, fields[5].GetUInt32());
220 SetCreatorGUID(owner->GetGUID());
222 m_charmInfo->SetReactState(ReactStates(fields[6].GetUInt8()));
224 uint32 savedhealth = fields[11].GetUInt32();
225 uint32 savedmana = fields[12].GetUInt32();
227 // set current pet as current
228 // 0=current
229 // 1..MAX_PET_STABLES in stable slot
230 // PET_SAVE_NOT_IN_SLOT(100) = not stable slot (summoning))
231 if (fields[8].GetUInt32() != 0)
233 CharacterDatabase.BeginTransaction();
234 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND slot = '%u' AND id <> '%u'",
235 PET_SAVE_NOT_IN_SLOT, ownerid, PET_SAVE_AS_CURRENT, m_charmInfo->GetPetNumber());
236 CharacterDatabase.PExecute("UPDATE character_pet SET slot = '%u' WHERE owner = '%u' AND id = '%u'",
237 PET_SAVE_AS_CURRENT, ownerid, m_charmInfo->GetPetNumber());
238 CharacterDatabase.CommitTransaction();
241 if (!is_temporary_summoned)
243 // permanent controlled pets store state in DB
244 Tokens tokens = StrSplit(fields[14].GetString(), " ");
246 if (tokens.size() != 20)
248 delete result;
249 return false;
252 int index;
253 Tokens::iterator iter;
254 for(iter = tokens.begin(), index = 0; index < 10; ++iter, ++index )
256 m_charmInfo->GetActionBarEntry(index)->Type = atol((*iter).c_str());
257 ++iter;
258 m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
261 //init teach spells
262 tokens = StrSplit(fields[15].GetString(), " ");
263 for (iter = tokens.begin(), index = 0; index < 4; ++iter, ++index)
265 uint32 tmp = atol((*iter).c_str());
267 ++iter;
269 if(tmp)
270 AddTeachSpell(tmp, atol((*iter).c_str()));
271 else
272 break;
276 // since last save (in seconds)
277 uint32 timediff = (time(NULL) - fields[16].GetUInt32());
279 m_resetTalentsCost = fields[17].GetUInt32();
280 m_resetTalentsTime = fields[18].GetUInt64();
282 delete result;
284 //load spells/cooldowns/auras
285 SetCanModifyStats(true);
286 _LoadAuras(timediff);
288 //init AB
289 if (is_temporary_summoned)
291 // Temporary summoned pets always have initial spell list at load
292 InitPetCreateSpells();
294 else
296 LearnPetPassives();
297 CastPetAuras(current);
300 if (getPetType() == SUMMON_PET && !current) //all (?) summon pets come with full health when called, but not when they are current
302 SetHealth(GetMaxHealth());
303 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
305 else
307 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
308 SetPower(POWER_MANA, savedmana > GetMaxPower(POWER_MANA) ? GetMaxPower(POWER_MANA) : savedmana);
311 AIM_Initialize();
312 map->Add((Creature*)this);
314 // Spells should be loaded after pet is added to map, because in CheckCast is check on it
315 _LoadSpells();
316 _LoadSpellCooldowns();
318 owner->SetPet(this); // in DB stored only full controlled creature
319 sLog.outDebug("New Pet has guid %u", GetGUIDLow());
321 if (owner->GetTypeId() == TYPEID_PLAYER)
323 ((Player*)owner)->PetSpellInitialize();
324 if(((Player*)owner)->GetGroup())
325 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_PET);
328 if (owner->GetTypeId() == TYPEID_PLAYER && getPetType() == HUNTER_PET)
330 result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'", owner->GetGUIDLow(), GetCharmInfo()->GetPetNumber());
332 if(result)
334 if(m_declinedname)
335 delete m_declinedname;
337 m_declinedname = new DeclinedName;
338 Field *fields2 = result->Fetch();
339 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
341 m_declinedname->name[i] = fields2[i].GetCppString();
346 InitLevelupSpellsForLevel();
348 m_loading = false;
350 SynchronizeLevelWithOwner();
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 //regenerate focus for hunter pets or energy for deathknight's ghoul
556 if(m_regenTimer <= diff)
558 switch (getPowerType())
560 case POWER_FOCUS:
561 case POWER_ENERGY:
562 Regenerate(getPowerType());
563 break;
564 default:
565 break;
567 m_regenTimer = 4000;
569 else
570 m_regenTimer -= diff;
572 if(getPetType() != HUNTER_PET)
573 break;
575 if(m_happinessTimer <= diff)
577 LooseHappiness();
578 m_happinessTimer = 7500;
580 else
581 m_happinessTimer -= diff;
583 break;
585 default:
586 break;
588 Creature::Update(diff);
591 void Pet::Regenerate(Powers power)
593 uint32 curValue = GetPower(power);
594 uint32 maxValue = GetMaxPower(power);
596 if (curValue >= maxValue)
597 return;
599 float addvalue = 0.0f;
601 switch (power)
603 case POWER_FOCUS:
605 // For hunter pets.
606 addvalue = 24 * sWorld.getRate(RATE_POWER_FOCUS);
607 break;
609 case POWER_ENERGY:
611 // For deathknight's ghoul.
612 addvalue = 20;
613 break;
615 default:
616 return;
619 // Apply modifiers (if any).
620 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
621 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
622 if ((*i)->GetModifier()->m_miscvalue == power)
623 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
625 ModifyPower(power, (int32)addvalue);
628 void Pet::LooseHappiness()
630 uint32 curValue = GetPower(POWER_HAPPINESS);
631 if (curValue <= 0)
632 return;
633 int32 addvalue = 670; //value is 70/35/17/8/4 (per min) * 1000 / 8 (timer 7.5 secs)
634 if(isInCombat()) //we know in combat happiness fades faster, multiplier guess
635 addvalue = int32(addvalue * 1.5);
636 ModifyPower(POWER_HAPPINESS, -addvalue);
639 HappinessState Pet::GetHappinessState()
641 if(GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE)
642 return UNHAPPY;
643 else if(GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2)
644 return HAPPY;
645 else
646 return CONTENT;
649 bool Pet::CanTakeMoreActiveSpells(uint32 spellid)
651 uint8 activecount = 1;
652 uint32 chainstartstore[ACTIVE_SPELLS_MAX];
654 if(IsPassiveSpell(spellid))
655 return true;
657 chainstartstore[0] = spellmgr.GetFirstSpellInChain(spellid);
659 for (PetSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
661 if(itr->second.state == PETSPELL_REMOVED)
662 continue;
664 if(IsPassiveSpell(itr->first))
665 continue;
667 uint32 chainstart = spellmgr.GetFirstSpellInChain(itr->first);
669 uint8 x;
671 for(x = 0; x < activecount; x++)
673 if(chainstart == chainstartstore[x])
674 break;
677 if(x == activecount) //spellchain not yet saved -> add active count
679 ++activecount;
680 if(activecount > ACTIVE_SPELLS_MAX)
681 return false;
682 chainstartstore[x] = chainstart;
685 return true;
688 void Pet::Remove(PetSaveMode mode, bool returnreagent)
690 Unit* owner = GetOwner();
692 if(owner)
694 if(owner->GetTypeId()==TYPEID_PLAYER)
696 ((Player*)owner)->RemovePet(this,mode,returnreagent);
697 return;
700 // only if current pet in slot
701 if(owner->GetPetGUID()==GetGUID())
702 owner->SetPet(0);
705 CleanupsBeforeDelete();
706 AddObjectToRemoveList();
707 m_removed = true;
710 void Pet::GivePetXP(uint32 xp)
712 if(getPetType() != HUNTER_PET)
713 return;
715 if ( xp < 1 )
716 return;
718 if(!isAlive())
719 return;
721 uint32 level = getLevel();
723 // XP to money conversion processed in Player::RewardQuest
724 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
725 return;
727 uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE);
728 uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
729 uint32 newXP = curXP + xp;
731 if(newXP >= nextLvlXP && level+1 > GetOwner()->getLevel())
733 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, nextLvlXP-1);
734 return;
737 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
739 newXP -= nextLvlXP;
741 GivePetLevel(level+1);
742 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(level+1)/4);
744 level = getLevel();
745 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP);
748 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, newXP);
751 void Pet::GivePetLevel(uint32 level)
753 if(!level)
754 return;
756 InitStatsForLevel(level);
757 InitLevelupSpellsForLevel();
758 InitTalentForLevel();
761 bool Pet::CreateBaseAtCreature(Creature* creature)
763 if(!creature)
765 sLog.outError("CRITICAL: NULL pointer parsed into CreateBaseAtCreature()");
766 return false;
768 uint32 guid=objmgr.GenerateLowGuid(HIGHGUID_PET);
770 sLog.outBasic("SetInstanceID()");
771 SetInstanceId(creature->GetInstanceId());
773 sLog.outBasic("Create pet");
774 uint32 pet_number = objmgr.GeneratePetNumber();
775 if(!Create(guid, creature->GetMap(), creature->GetPhaseMask(), creature->GetEntry(), pet_number))
776 return false;
778 Relocate(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetOrientation());
780 if(!IsPositionValid())
782 sLog.outError("Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)",
783 GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY());
784 return false;
787 CreatureInfo const *cinfo = GetCreatureInfo();
788 if(!cinfo)
790 sLog.outError("CreateBaseAtCreature() failed, creatureInfo is missing!");
791 return false;
794 if(cinfo->type == CREATURE_TYPE_CRITTER)
796 setPetType(MINI_PET);
797 return true;
799 SetDisplayId(creature->GetDisplayId());
800 SetNativeDisplayId(creature->GetNativeDisplayId());
801 SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
802 SetPower(POWER_HAPPINESS, 166500);
803 setPowerType(POWER_FOCUS);
804 SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, 0);
805 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
806 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(creature->getLevel())/4);
807 SetUInt32Value(UNIT_NPC_FLAGS, 0);
809 if(CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family))
810 SetName(cFamily->Name[sWorld.GetDefaultDbcLocale()]);
811 else
812 SetName(creature->GetNameForLocaleIdx(objmgr.GetDBCLocaleIndex()));
814 if(cinfo->type == CREATURE_TYPE_BEAST)
816 SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100);
817 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE );
818 SetByteValue(UNIT_FIELD_BYTES_2, 2, UNIT_RENAME_ALLOWED);
819 SetUInt32Value(UNIT_MOD_CAST_SPEED, creature->GetUInt32Value(UNIT_MOD_CAST_SPEED));
821 return true;
824 bool Pet::InitStatsForLevel(uint32 petlevel)
826 CreatureInfo const *cinfo = GetCreatureInfo();
827 assert(cinfo);
829 Unit* owner = GetOwner();
830 if(!owner)
832 sLog.outError("attempt to summon pet (Entry %u) without owner! Attempt terminated.", cinfo->Entry);
833 return false;
836 uint32 creature_ID = (getPetType() == HUNTER_PET) ? 1 : cinfo->Entry;
838 SetLevel(petlevel);
840 SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
842 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50));
844 SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
845 SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
846 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
848 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0);
850 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cinfo->family);
851 if(cFamily && cFamily->minScale > 0.0f && getPetType()==HUNTER_PET)
853 float scale;
854 if (getLevel() >= cFamily->maxScaleLevel)
855 scale = cFamily->maxScale;
856 else if (getLevel() <= cFamily->minScaleLevel)
857 scale = cFamily->minScale;
858 else
859 scale = cFamily->minScale + float(getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale);
861 SetFloatValue(OBJECT_FIELD_SCALE_X, scale);
863 m_bonusdamage = 0;
865 int32 createResistance[MAX_SPELL_SCHOOL] = {0,0,0,0,0,0,0};
867 if(cinfo && getPetType() != HUNTER_PET)
869 createResistance[SPELL_SCHOOL_HOLY] = cinfo->resistance1;
870 createResistance[SPELL_SCHOOL_FIRE] = cinfo->resistance2;
871 createResistance[SPELL_SCHOOL_NATURE] = cinfo->resistance3;
872 createResistance[SPELL_SCHOOL_FROST] = cinfo->resistance4;
873 createResistance[SPELL_SCHOOL_SHADOW] = cinfo->resistance5;
874 createResistance[SPELL_SCHOOL_ARCANE] = cinfo->resistance6;
877 switch(getPetType())
879 case SUMMON_PET:
881 if(owner->GetTypeId() == TYPEID_PLAYER)
883 switch(owner->getClass())
885 case CLASS_WARLOCK:
888 //the damage bonus used for pets is either fire or shadow damage, whatever is higher
889 uint32 fire = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE);
890 uint32 shadow = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW);
891 uint32 val = (fire > shadow) ? fire : shadow;
893 SetBonusDamage(int32 (val * 0.15f));
894 //bonusAP += val * 0.57;
895 break;
897 case CLASS_MAGE:
899 //40% damage bonus of mage's frost damage
900 float val = owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) * 0.4;
901 if(val < 0)
902 val = 0;
903 SetBonusDamage( int32(val));
904 break;
906 default:
907 break;
911 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
912 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
914 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
916 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
917 if(pInfo) // exist in DB
919 SetCreateHealth(pInfo->health);
920 SetCreateMana(pInfo->mana);
922 if(pInfo->armor > 0)
923 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
925 for(int stat = 0; stat < MAX_STATS; ++stat)
927 SetCreateStat(Stats(stat), float(pInfo->stats[stat]));
930 else // not exist in DB, use some default fake data
932 sLog.outErrorDb("Summoned pet (Entry: %u) not have pet stats data in DB",cinfo->Entry);
934 // remove elite bonuses included in DB values
935 SetCreateHealth(uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
936 SetCreateMana( uint32(((float(cinfo->maxmana) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
938 SetCreateStat(STAT_STRENGTH, 22);
939 SetCreateStat(STAT_AGILITY, 22);
940 SetCreateStat(STAT_STAMINA, 25);
941 SetCreateStat(STAT_INTELLECT, 28);
942 SetCreateStat(STAT_SPIRIT, 27);
944 break;
946 case HUNTER_PET:
948 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(petlevel)/4);
949 //these formula may not be correct; however, it is designed to be close to what it should be
950 //this makes dps 0.5 of pets level
951 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)) );
952 //damage range is then petlevel / 2
953 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)) );
954 //damage is increased afterwards as strength and pet scaling modify attack power
956 //stored standard pet stats are entry 1 in pet_levelinfo
957 PetLevelInfo const* pInfo = objmgr.GetPetLevelInfo(creature_ID, petlevel);
958 if(pInfo) // exist in DB
960 SetCreateHealth(pInfo->health);
961 SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(pInfo->armor));
962 //SetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE, float(cinfo->attackpower));
964 for( int i = STAT_STRENGTH; i < MAX_STATS; ++i)
966 SetCreateStat(Stats(i), float(pInfo->stats[i]));
969 else // not exist in DB, use some default fake data
971 sLog.outErrorDb("Hunter pet levelstats missing in DB");
973 // remove elite bonuses included in DB values
974 SetCreateHealth( uint32(((float(cinfo->maxhealth) / cinfo->maxlevel) / (1 + 2 * cinfo->rank)) * petlevel) );
976 SetCreateStat(STAT_STRENGTH, 22);
977 SetCreateStat(STAT_AGILITY, 22);
978 SetCreateStat(STAT_STAMINA, 25);
979 SetCreateStat(STAT_INTELLECT, 28);
980 SetCreateStat(STAT_SPIRIT, 27);
982 break;
984 case GUARDIAN_PET:
985 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
986 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, 1000);
988 SetCreateMana(28 + 10*petlevel);
989 SetCreateHealth(28 + 30*petlevel);
991 // FIXME: this is wrong formula, possible each guardian pet have own damage formula
992 //these formula may not be correct; however, it is designed to be close to what it should be
993 //this makes dps 0.5 of pets level
994 SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4)));
995 //damage range is then petlevel / 2
996 SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4)));
997 break;
998 default:
999 sLog.outError("Pet have incorrect type (%u) for levelup.", getPetType());
1000 break;
1003 for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
1004 SetModifierValue(UnitMods(UNIT_MOD_RESISTANCE_START + i), BASE_VALUE, float(createResistance[i]));
1006 UpdateAllStats();
1008 SetHealth(GetMaxHealth());
1009 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
1011 return true;
1014 bool Pet::HaveInDiet(ItemPrototype const* item) const
1016 if (!item->FoodType)
1017 return false;
1019 CreatureInfo const* cInfo = GetCreatureInfo();
1020 if(!cInfo)
1021 return false;
1023 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
1024 if(!cFamily)
1025 return false;
1027 uint32 diet = cFamily->petFoodMask;
1028 uint32 FoodMask = 1 << (item->FoodType-1);
1029 return diet & FoodMask;
1032 uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel)
1034 // -5 or greater food level
1035 if(getLevel() <= itemlevel + 5) //possible to feed level 60 pet with level 55 level food for full effect
1036 return 35000;
1037 // -10..-6
1038 else if(getLevel() <= itemlevel + 10) //pure guess, but sounds good
1039 return 17000;
1040 // -14..-11
1041 else if(getLevel() <= itemlevel + 14) //level 55 food gets green on 70, makes sense to me
1042 return 8000;
1043 // -15 or less
1044 else
1045 return 0; //food too low level
1048 void Pet::_LoadSpellCooldowns()
1050 m_CreatureSpellCooldowns.clear();
1051 m_CreatureCategoryCooldowns.clear();
1053 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1055 if(result)
1057 time_t curTime = time(NULL);
1059 WorldPacket data(SMSG_SPELL_COOLDOWN, (8+1+result->GetRowCount()*8));
1060 data << GetGUID();
1061 data << uint8(0x0); // flags (0x1, 0x2)
1065 Field *fields = result->Fetch();
1067 uint32 spell_id = fields[0].GetUInt32();
1068 time_t db_time = (time_t)fields[1].GetUInt64();
1070 if(!sSpellStore.LookupEntry(spell_id))
1072 sLog.outError("Pet %u have unknown spell %u in `pet_spell_cooldown`, skipping.",m_charmInfo->GetPetNumber(),spell_id);
1073 continue;
1076 // skip outdated cooldown
1077 if(db_time <= curTime)
1078 continue;
1080 data << uint32(spell_id);
1081 data << uint32(uint32(db_time-curTime)*IN_MILISECONDS);
1083 _AddCreatureSpellCooldown(spell_id,db_time);
1085 sLog.outDebug("Pet (Number: %u) spell %u cooldown loaded (%u secs).", m_charmInfo->GetPetNumber(), spell_id, uint32(db_time-curTime));
1087 while( result->NextRow() );
1089 delete result;
1091 if(!m_CreatureSpellCooldowns.empty() && GetOwner())
1093 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1098 void Pet::_SaveSpellCooldowns()
1100 CharacterDatabase.PExecute("DELETE FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1102 time_t curTime = time(NULL);
1104 // remove oudated and save active
1105 for(CreatureSpellCooldowns::iterator itr = m_CreatureSpellCooldowns.begin();itr != m_CreatureSpellCooldowns.end();)
1107 if(itr->second <= curTime)
1108 m_CreatureSpellCooldowns.erase(itr++);
1109 else
1111 CharacterDatabase.PExecute("INSERT INTO pet_spell_cooldown (guid,spell,time) VALUES ('%u', '%u', '" I64FMTD "')", m_charmInfo->GetPetNumber(), itr->first, uint64(itr->second));
1112 ++itr;
1117 void Pet::_LoadSpells()
1119 QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active FROM pet_spell WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1121 if(result)
1125 Field *fields = result->Fetch();
1127 addSpell(fields[0].GetUInt32(), ActiveStates(fields[1].GetUInt16()), PETSPELL_UNCHANGED);
1129 while( result->NextRow() );
1131 delete result;
1135 void Pet::_SaveSpells()
1137 for (PetSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
1139 ++next;
1141 // prevent saving family passives to DB
1142 if (itr->second.type == PETSPELL_FAMILY)
1143 continue;
1145 switch(itr->second.state)
1147 case PETSPELL_REMOVED:
1148 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
1149 m_spells.erase(itr);
1150 continue;
1151 case PETSPELL_CHANGED:
1152 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE guid = '%u' and spell = '%u'", m_charmInfo->GetPetNumber(), itr->first);
1153 CharacterDatabase.PExecute("INSERT INTO pet_spell (guid,spell,active) VALUES ('%u', '%u', '%u')", m_charmInfo->GetPetNumber(), itr->first, itr->second.active);
1154 break;
1155 case PETSPELL_NEW:
1156 CharacterDatabase.PExecute("INSERT INTO pet_spell (guid,spell,active) VALUES ('%u', '%u', '%u')", m_charmInfo->GetPetNumber(), itr->first, itr->second.active);
1157 break;
1158 case PETSPELL_UNCHANGED:
1159 continue;
1162 itr->second.state = PETSPELL_UNCHANGED;
1166 void Pet::_LoadAuras(uint32 timediff)
1168 m_Auras.clear();
1169 for (int i = 0; i < TOTAL_AURAS; ++i)
1170 m_modAuras[i].clear();
1172 QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
1174 if(result)
1178 Field *fields = result->Fetch();
1179 uint64 caster_guid = fields[0].GetUInt64();
1180 uint32 spellid = fields[1].GetUInt32();
1181 uint32 effindex = fields[2].GetUInt32();
1182 uint32 stackcount= fields[3].GetUInt32();
1183 int32 damage = (int32)fields[4].GetUInt32();
1184 int32 maxduration = (int32)fields[5].GetUInt32();
1185 int32 remaintime = (int32)fields[6].GetUInt32();
1186 int32 remaincharges = (int32)fields[7].GetUInt32();
1188 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
1189 if(!spellproto)
1191 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
1192 continue;
1195 if(effindex >= 3)
1197 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
1198 continue;
1201 // negative effects should continue counting down after logout
1202 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
1204 if(remaintime <= int32(timediff))
1205 continue;
1207 remaintime -= timediff;
1210 // prevent wrong values of remaincharges
1211 if(spellproto->procCharges)
1213 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
1214 remaincharges = spellproto->procCharges;
1216 else
1217 remaincharges = -1;
1219 /// do not load single target auras (unless they were cast by the player)
1220 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
1221 continue;
1223 for(uint32 i=0; i<stackcount; ++i)
1225 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
1227 if(!damage)
1228 damage = aura->GetModifier()->m_amount;
1229 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
1230 AddAura(aura);
1233 while( result->NextRow() );
1235 delete result;
1239 void Pet::_SaveAuras()
1241 CharacterDatabase.PExecute("DELETE FROM pet_aura WHERE guid = '%u'", m_charmInfo->GetPetNumber());
1243 AuraMap const& auras = GetAuras();
1244 if (auras.empty())
1245 return;
1247 spellEffectPair lastEffectPair = auras.begin()->first;
1248 uint32 stackCounter = 1;
1250 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
1252 if(itr == auras.end() || lastEffectPair != itr->first)
1254 AuraMap::const_iterator itr2 = itr;
1255 // save previous spellEffectPair to db
1256 itr2--;
1257 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
1258 /// do not save single target auras (unless they were cast by the player)
1259 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
1261 if(!itr2->second->IsPassive())
1263 // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
1264 uint8 i;
1265 for (i = 0; i < 3; ++i)
1266 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
1267 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
1268 spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
1269 break;
1271 if (i == 3)
1273 CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
1274 "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%u', '%d', '%d', '%d', '%d')",
1275 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()));
1279 if(itr == auras.end())
1280 break;
1283 if (lastEffectPair == itr->first)
1284 stackCounter++;
1285 else
1287 lastEffectPair = itr->first;
1288 stackCounter = 1;
1293 bool Pet::addSpell(uint32 spell_id,ActiveStates active /*= ACT_DECIDE*/, PetSpellState state /*= PETSPELL_NEW*/, PetSpellType type /*= PETSPELL_NORMAL*/)
1295 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
1296 if (!spellInfo)
1298 // do pet spell book cleanup
1299 if(state == PETSPELL_UNCHANGED) // spell load case
1301 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request, deleting for all pets in `pet_spell`.",spell_id);
1302 CharacterDatabase.PExecute("DELETE FROM pet_spell WHERE spell = '%u'",spell_id);
1304 else
1305 sLog.outError("Pet::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
1307 return false;
1310 PetSpellMap::iterator itr = m_spells.find(spell_id);
1311 if (itr != m_spells.end())
1313 if (itr->second.state == PETSPELL_REMOVED)
1315 m_spells.erase(itr);
1316 state = PETSPELL_CHANGED;
1318 else if (state == PETSPELL_UNCHANGED && itr->second.state != PETSPELL_UNCHANGED)
1320 // can be in case spell loading but learned at some previous spell loading
1321 itr->second.state = PETSPELL_UNCHANGED;
1323 if(active == ACT_ENABLED)
1324 ToggleAutocast(spell_id, true);
1325 else if(active == ACT_DISABLED)
1326 ToggleAutocast(spell_id, false);
1328 return false;
1330 else
1331 return false;
1334 uint32 oldspell_id = 0;
1336 PetSpell newspell;
1337 newspell.state = state;
1338 newspell.type = type;
1340 if(active == ACT_DECIDE) //active was not used before, so we save it's autocast/passive state here
1342 if(IsPassiveSpell(spell_id))
1343 newspell.active = ACT_PASSIVE;
1344 else
1345 newspell.active = ACT_DISABLED;
1347 else
1348 newspell.active = active;
1350 // talent: unlearn all other talent ranks (high and low)
1351 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
1353 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
1355 for(int i=0; i < MAX_TALENT_RANK; ++i)
1357 // skip learning spell and no rank spell case
1358 uint32 rankSpellId = talentInfo->RankID[i];
1359 if(!rankSpellId || rankSpellId==spell_id)
1360 continue;
1362 // skip unknown ranks
1363 if(!HasSpell(rankSpellId))
1364 continue;
1365 removeSpell(rankSpellId,false);
1369 else if(spellmgr.GetSpellRank(spell_id)!=0)
1371 for (PetSpellMap::const_iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2)
1373 if(itr2->second.state == PETSPELL_REMOVED) continue;
1375 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
1377 // replace by new high rank
1378 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
1380 newspell.active = itr2->second.active;
1382 if(newspell.active == ACT_ENABLED)
1383 ToggleAutocast(itr2->first, false);
1385 oldspell_id = itr2->first;
1386 unlearnSpell(itr2->first,false);
1387 break;
1389 // ignore new lesser rank
1390 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
1391 return false;
1396 m_spells[spell_id] = newspell;
1398 if (IsPassiveSpell(spell_id))
1399 CastSpell(this, spell_id, true);
1400 else
1401 m_charmInfo->AddSpellToAB(oldspell_id, spell_id);
1403 if(newspell.active == ACT_ENABLED)
1404 ToggleAutocast(spell_id, true);
1406 uint32 talentCost = GetTalentSpellCost(spell_id);
1407 if (talentCost)
1409 int32 free_points = GetMaxTalentPointsForLevel(getLevel());
1410 m_usedTalentCount+=talentCost;
1411 // update free talent points
1412 free_points-=m_usedTalentCount;
1413 SetFreeTalentPoints(free_points > 0 ? free_points : 0);
1415 return true;
1418 bool Pet::learnSpell(uint32 spell_id)
1420 // prevent duplicated entires in spell book
1421 if (!addSpell(spell_id))
1422 return false;
1424 Unit* owner = GetOwner();
1425 if(owner && owner->GetTypeId() == TYPEID_PLAYER)
1427 if(!m_loading)
1429 WorldPacket data(SMSG_PET_LEARNED_SPELL, 2);
1430 data << uint16(spell_id);
1431 ((Player*)owner)->GetSession()->SendPacket(&data);
1433 ((Player*)owner)->PetSpellInitialize();
1435 return true;
1438 void Pet::InitLevelupSpellsForLevel()
1440 uint32 level = getLevel();
1442 if(PetLevelupSpellSet const *levelupSpells = GetCreatureInfo()->family ? spellmgr.GetPetLevelupSpellList(GetCreatureInfo()->family) : NULL)
1444 // PetLevelupSpellSet ordered by levels, process in reversed order
1445 for(PetLevelupSpellSet::const_reverse_iterator itr = levelupSpells->rbegin(); itr != levelupSpells->rend(); ++itr)
1447 // will called first if level down
1448 if(itr->first > level)
1449 unlearnSpell(itr->second,true); // will learn prev rank if any
1450 // will called if level up
1451 else
1452 learnSpell(itr->second); // will unlearn prev rank if any
1456 int32 petSpellsId = GetCreatureInfo()->PetSpellDataId ? -(int32)GetCreatureInfo()->PetSpellDataId : GetEntry();
1458 // default spells (can be not learned if pet level (as owner level decrease result for example) less first possible in normal game)
1459 if(PetDefaultSpellsEntry const *defSpells = spellmgr.GetPetDefaultSpellsEntry(petSpellsId))
1461 for(int i = 0; i < MAX_CREATURE_SPELL_DATA_SLOT; ++i)
1463 SpellEntry const* spellEntry = sSpellStore.LookupEntry(defSpells->spellid[i]);
1464 if(!spellEntry)
1465 continue;
1467 // will called first if level down
1468 if(spellEntry->spellLevel > level)
1469 unlearnSpell(spellEntry->Id,false);
1470 // will called if level up
1471 else
1472 learnSpell(spellEntry->Id);
1477 bool Pet::unlearnSpell(uint32 spell_id, bool learn_prev)
1479 if(removeSpell(spell_id,learn_prev))
1481 if(GetOwner()->GetTypeId() == TYPEID_PLAYER)
1483 if(!m_loading)
1485 WorldPacket data(SMSG_PET_REMOVED_SPELL, 2);
1486 data << uint16(spell_id);
1487 ((Player*)GetOwner())->GetSession()->SendPacket(&data);
1490 return true;
1492 return false;
1495 bool Pet::removeSpell(uint32 spell_id, bool learn_prev)
1497 PetSpellMap::iterator itr = m_spells.find(spell_id);
1498 if (itr == m_spells.end())
1499 return false;
1501 if(itr->second.state == PETSPELL_REMOVED)
1502 return false;
1504 if(itr->second.state == PETSPELL_NEW)
1505 m_spells.erase(itr);
1506 else
1507 itr->second.state = PETSPELL_REMOVED;
1509 RemoveAurasDueToSpell(spell_id);
1511 uint32 talentCost = GetTalentSpellCost(spell_id);
1512 if (talentCost > 0)
1514 if (m_usedTalentCount > talentCost)
1515 m_usedTalentCount-=talentCost;
1516 else
1517 m_usedTalentCount = 0;
1518 // update free talent points
1519 int32 free_points = GetMaxTalentPointsForLevel(getLevel()) - m_usedTalentCount;
1520 SetFreeTalentPoints(free_points > 0 ? free_points : 0);
1523 if (learn_prev)
1525 if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
1527 // replace to next spell
1528 if(!talentCost && !IsPassiveSpell(prev_id))
1529 m_charmInfo->AddSpellToAB(spell_id, prev_id);
1531 learnSpell(prev_id);
1533 else
1534 learn_prev = false;
1537 // if remove last rank or non-ranked then update action bar at server and client if need
1538 if(!learn_prev && m_charmInfo->AddSpellToAB(spell_id, 0))
1540 // need update action bar for last removed rank
1541 if (Unit* owner = GetOwner())
1542 if (owner->GetTypeId() == TYPEID_PLAYER)
1543 ((Player*)owner)->PetSpellInitialize();
1546 return true;
1549 void Pet::InitPetCreateSpells()
1551 m_charmInfo->InitPetActionBar();
1552 m_spells.clear();
1554 uint32 petspellid;
1555 PetCreateSpellEntry const* CreateSpells = objmgr.GetPetCreateSpellEntry(GetEntry());
1556 if(CreateSpells)
1558 for(uint8 i = 0; i < 4; ++i)
1560 if(!CreateSpells->spellid[i])
1561 break;
1563 SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(CreateSpells->spellid[i]);
1564 if(!learn_spellproto)
1565 continue;
1567 if(learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_SPELL || learn_spellproto->Effect[0] == SPELL_EFFECT_LEARN_PET_SPELL)
1569 petspellid = learn_spellproto->EffectTriggerSpell[0];
1570 Unit* owner = GetOwner();
1571 if(owner->GetTypeId() == TYPEID_PLAYER && !((Player*)owner)->HasSpell(learn_spellproto->Id))
1573 if(IsPassiveSpell(petspellid)) //learn passive skills when tamed, not sure if thats right
1574 ((Player*)owner)->learnSpell(learn_spellproto->Id,false);
1575 else
1576 AddTeachSpell(learn_spellproto->EffectTriggerSpell[0], learn_spellproto->Id);
1579 else
1580 petspellid = learn_spellproto->Id;
1582 addSpell(petspellid);
1586 LearnPetPassives();
1588 CastPetAuras(false);
1591 void Pet::CheckLearning(uint32 spellid)
1593 //charmed case -> prevent crash
1594 if(GetTypeId() == TYPEID_PLAYER || getPetType() != HUNTER_PET)
1595 return;
1597 Unit* owner = GetOwner();
1599 if(m_teachspells.empty() || !owner || owner->GetTypeId() != TYPEID_PLAYER)
1600 return;
1602 TeachSpellMap::iterator itr = m_teachspells.find(spellid);
1603 if(itr == m_teachspells.end())
1604 return;
1606 if(urand(0, 100) < 10)
1608 ((Player*)owner)->learnSpell(itr->second,false);
1609 m_teachspells.erase(itr);
1613 bool Pet::resetTalents(bool no_cost)
1615 Unit *owner = GetOwner();
1616 if (!owner || owner->GetTypeId()!=TYPEID_PLAYER)
1617 return false;
1619 CreatureInfo const * ci = GetCreatureInfo();
1620 if(!ci)
1621 return false;
1622 // Check pet talent type
1623 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
1624 if(!pet_family || pet_family->petTalentType < 0)
1625 return false;
1627 Player *player = (Player *)owner;
1629 uint32 level = getLevel();
1630 uint32 talentPointsForLevel = GetMaxTalentPointsForLevel(level);
1632 if (m_usedTalentCount == 0)
1634 SetFreeTalentPoints(talentPointsForLevel);
1635 return false;
1638 uint32 cost = 0;
1640 if(!no_cost)
1642 cost = resetTalentsCost();
1644 if (player->GetMoney() < cost)
1646 player->SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
1647 return false;
1651 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
1653 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
1655 if (!talentInfo) continue;
1657 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
1659 if(!talentTabInfo)
1660 continue;
1662 // unlearn only talents for pets family talent type
1663 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
1664 continue;
1666 for (int j = 0; j < MAX_TALENT_RANK; j++)
1668 for(PetSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end();)
1670 if(itr->second.state == PETSPELL_REMOVED)
1672 ++itr;
1673 continue;
1675 // remove learned spells (all ranks)
1676 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
1678 // unlearn if first rank is talent or learned by talent
1679 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
1681 removeSpell(itr->first,false);
1682 itr = m_spells.begin();
1683 continue;
1685 else
1686 ++itr;
1691 SetFreeTalentPoints(talentPointsForLevel);
1693 if(!no_cost)
1695 player->ModifyMoney(-(int32)cost);
1697 m_resetTalentsCost = cost;
1698 m_resetTalentsTime = time(NULL);
1700 player->PetSpellInitialize();
1701 return true;
1704 void Pet::InitTalentForLevel()
1706 uint32 level = getLevel();
1707 uint32 talentPointsForLevel = GetMaxTalentPointsForLevel(level);
1708 // Reset talents in case low level (on level down) or wrong points for level (hunter can unlearn TP increase talent)
1709 if(talentPointsForLevel == 0 || m_usedTalentCount > talentPointsForLevel)
1711 // Remove all talent points
1712 resetTalents(true);
1714 SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount);
1717 uint32 Pet::resetTalentsCost() const
1719 uint32 days = (sWorld.GetGameTime() - m_resetTalentsTime)/DAY;
1721 // The first time reset costs 10 silver; after 1 day cost is reset to 10 silver
1722 if(m_resetTalentsCost < 10*SILVER || days > 0)
1723 return 10*SILVER;
1724 // then 50 silver
1725 else if(m_resetTalentsCost < 50*SILVER)
1726 return 50*SILVER;
1727 // then 1 gold
1728 else if(m_resetTalentsCost < 1*GOLD)
1729 return 1*GOLD;
1730 // then increasing at a rate of 1 gold; cap 10 gold
1731 else
1732 return (m_resetTalentsCost + 1*GOLD > 10*GOLD ? 10*GOLD : m_resetTalentsCost + 1*GOLD);
1735 uint8 Pet::GetMaxTalentPointsForLevel(uint32 level)
1737 uint8 points = (level >= 20) ? ((level - 16) / 4) : 0;
1738 // Mod points from owner SPELL_AURA_MOD_PET_TALENT_POINTS
1739 if (Unit *owner = GetOwner())
1740 points+=owner->GetTotalAuraModifier(SPELL_AURA_MOD_PET_TALENT_POINTS);
1741 return points;
1744 void Pet::ToggleAutocast(uint32 spellid, bool apply)
1746 if(IsPassiveSpell(spellid))
1747 return;
1749 PetSpellMap::iterator itr = m_spells.find(spellid);
1751 int i;
1753 if(apply)
1755 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; ++i)
1756 ; // just search
1758 if (i == m_autospells.size())
1760 m_autospells.push_back(spellid);
1762 if(itr->second.active != ACT_ENABLED)
1764 itr->second.active = ACT_ENABLED;
1765 if(itr->second.state != PETSPELL_NEW)
1766 itr->second.state = PETSPELL_CHANGED;
1770 else
1772 AutoSpellList::iterator itr2 = m_autospells.begin();
1773 for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; ++i, itr2++)
1774 ; // just search
1776 if (i < m_autospells.size())
1778 m_autospells.erase(itr2);
1779 if(itr->second.active != ACT_DISABLED)
1781 itr->second.active = ACT_DISABLED;
1782 if(itr->second.state != PETSPELL_NEW)
1783 itr->second.state = PETSPELL_CHANGED;
1789 bool Pet::IsPermanentPetFor(Player* owner)
1791 switch(getPetType())
1793 case SUMMON_PET:
1794 switch(owner->getClass())
1796 case CLASS_WARLOCK:
1797 return GetCreatureInfo()->type == CREATURE_TYPE_DEMON;
1798 case CLASS_DEATH_KNIGHT:
1799 return GetCreatureInfo()->type == CREATURE_TYPE_UNDEAD;
1800 default:
1801 return false;
1803 case HUNTER_PET:
1804 return true;
1805 default:
1806 return false;
1810 bool Pet::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 pet_number)
1812 SetMapId(map->GetId());
1813 SetInstanceId(map->GetInstanceId());
1814 SetPhaseMask(phaseMask,false);
1816 Object::_Create(guidlow, pet_number, HIGHGUID_PET);
1818 m_DBTableGuid = guidlow;
1819 m_originalEntry = Entry;
1821 if(!InitEntry(Entry))
1822 return false;
1824 SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE);
1826 if(getPetType() == MINI_PET) // always non-attackable
1827 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
1829 return true;
1832 bool Pet::HasSpell(uint32 spell) const
1834 PetSpellMap::const_iterator itr = m_spells.find(spell);
1835 return (itr != m_spells.end() && itr->second.state != PETSPELL_REMOVED );
1838 // Get all passive spells in our skill line
1839 void Pet::LearnPetPassives()
1841 CreatureInfo const* cInfo = GetCreatureInfo();
1842 if(!cInfo)
1843 return;
1845 CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(cInfo->family);
1846 if(!cFamily)
1847 return;
1849 PetFamilySpellsStore::const_iterator petStore = sPetFamilySpellsStore.find(cFamily->ID);
1850 if(petStore != sPetFamilySpellsStore.end())
1852 for(PetFamilySpellsSet::const_iterator petSet = petStore->second.begin(); petSet != petStore->second.end(); ++petSet)
1853 addSpell(*petSet, ACT_DECIDE, PETSPELL_NEW, PETSPELL_FAMILY);
1857 void Pet::CastPetAuras(bool current)
1859 Unit* owner = GetOwner();
1860 if(!owner || owner->GetTypeId()!=TYPEID_PLAYER)
1861 return;
1863 if(!IsPermanentPetFor((Player*)owner))
1864 return;
1866 for(PetAuraSet::const_iterator itr = owner->m_petAuras.begin(); itr != owner->m_petAuras.end();)
1868 PetAura const* pa = *itr;
1869 ++itr;
1871 if(!current && pa->IsRemovedOnChangePet())
1872 owner->RemovePetAura(pa);
1873 else
1874 CastPetAura(pa);
1878 void Pet::CastPetAura(PetAura const* aura)
1880 uint16 auraId = aura->GetAura(GetEntry());
1881 if(!auraId)
1882 return;
1884 if(auraId == 35696) // Demonic Knowledge
1886 int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100);
1887 CastCustomSpell(this, auraId, &basePoints, NULL, NULL, true);
1889 else
1890 CastSpell(this, auraId, true);
1893 void Pet::learnSpellHighRank(uint32 spellid)
1895 learnSpell(spellid);
1897 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
1898 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
1899 learnSpellHighRank(itr->second);
1902 void Pet::SynchronizeLevelWithOwner()
1904 Unit* owner = GetOwner();
1905 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
1906 return;
1908 switch(getPetType())
1910 // always same level
1911 case SUMMON_PET:
1912 GivePetLevel(owner->getLevel());
1913 break;
1914 // can't be greater owner level
1915 case HUNTER_PET:
1916 if(getLevel() > owner->getLevel())
1918 GivePetLevel(owner->getLevel());
1919 SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, objmgr.GetXPForLevel(owner->getLevel())/4);
1920 SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP)-1);
1922 break;
1923 default:
1924 break;