[7146] Trailing whitespace code cleanup
[getmangos.git] / src / game / Player.cpp
blob5bf05d8a8baba0bc600ff10b9aac7b094527afa9
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 "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
148 switch(chrClass)
150 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
151 break;
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race))
157 case ALLIANCE: SetTaximaskNode(100); break;
158 case HORDE: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
161 if(level>=68)
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data)
167 Tokens tokens = StrSplit(data, " ");
169 int index;
170 Tokens::iterator iter;
171 for (iter = tokens.begin(), index = 0;
172 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
174 // load and set bits only for existed taxi nodes
175 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
181 if(all)
183 for (uint8 i=0; i<TaxiMaskSize; i++)
184 data << uint32(sTaxiNodesMask[i]); // all existed nodes
186 else
188 for (uint8 i=0; i<TaxiMaskSize; i++)
189 data << uint32(m_taximask[i]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
195 ClearTaxiDestinations();
197 Tokens tokens = StrSplit(values," ");
199 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
201 uint32 node = uint32(atol(iter->c_str()));
202 AddTaxiDestination(node);
205 if(m_TaxiDestinations.empty())
206 return true;
208 // Check integrity
209 if(m_TaxiDestinations.size() < 2)
210 return false;
212 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
214 uint32 cost;
215 uint32 path;
216 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
217 if(!path)
218 return false;
221 // can't load taxi path without mount set (quest taxi path?)
222 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
223 return false;
225 return true;
228 std::string PlayerTaxi::SaveTaxiDestinationsToString()
230 if(m_TaxiDestinations.empty())
231 return "";
233 std::ostringstream ss;
235 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
236 ss << m_TaxiDestinations[i] << " ";
238 return ss.str();
241 uint32 PlayerTaxi::GetCurrentTaxiPath() const
243 if(m_TaxiDestinations.size() < 2)
244 return 0;
246 uint32 path;
247 uint32 cost;
249 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
251 return path;
254 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
256 ss << "'";
257 for(int i = 0; i < TaxiMaskSize; ++i)
258 ss << taxi.m_taximask[i] << " ";
259 ss << "'";
260 return ss;
263 //== Player ====================================================
265 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
267 UpdateMask Player::updateVisualBits;
269 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
271 m_transport = 0;
273 m_speakTime = 0;
274 m_speakCount = 0;
276 m_objectType |= TYPEMASK_PLAYER;
277 m_objectTypeId = TYPEID_PLAYER;
279 m_valuesCount = PLAYER_END;
281 m_session = session;
283 m_divider = 0;
285 m_ExtraFlags = 0;
286 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
287 SetAcceptTicket(true);
289 // players always accept
290 if(GetSession()->GetSecurity() == SEC_PLAYER)
291 SetAcceptWhispers(true);
293 m_curSelection = 0;
294 m_lootGuid = 0;
296 m_comboTarget = 0;
297 m_comboPoints = 0;
299 m_usedTalentCount = 0;
300 m_questRewardTalentCount = 0;
302 m_regenTimer = 0;
303 m_weaponChangeTimer = 0;
305 m_zoneUpdateId = 0;
306 m_zoneUpdateTimer = 0;
308 m_areaUpdateId = 0;
310 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
312 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
313 // this must help in case next save after mass player load after server startup
314 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
316 clearResurrectRequestData();
318 m_SpellModRemoveCount = 0;
320 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
322 m_social = NULL;
324 // group is initialized in the reference constructor
325 SetGroupInvite(NULL);
326 m_groupUpdateMask = 0;
327 m_auraUpdateMask = 0;
329 duel = NULL;
331 m_GuildIdInvited = 0;
332 m_ArenaTeamIdInvited = 0;
334 m_atLoginFlags = AT_LOGIN_NONE;
336 m_dontMove = false;
338 pTrader = 0;
339 ClearTrade();
341 m_cinematic = 0;
343 PlayerTalkClass = new PlayerMenu( GetSession() );
344 m_currentBuybackSlot = BUYBACK_SLOT_START;
346 for ( int aX = 0 ; aX < 8 ; aX++ )
347 m_Tutorials[ aX ] = 0x00;
348 m_TutorialsChanged = false;
350 m_DailyQuestChanged = false;
351 m_lastDailyQuestTime = 0;
353 m_regenTimer = 0;
354 m_weaponChangeTimer = 0;
355 m_breathTimer = 0;
356 m_isunderwater = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1000;
368 m_bgBattleGroundID = 0;
369 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
371 m_bgBattleGroundQueueID[j].bgQueueType = 0;
372 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
374 m_bgTeam = 0;
376 m_logintime = time(NULL);
377 m_Last_tick = m_logintime;
378 m_WeaponProficiency = 0;
379 m_ArmorProficiency = 0;
380 m_canParry = false;
381 m_canBlock = false;
382 m_canDualWield = false;
383 m_canTitanGrip = false;
384 m_ammoDPS = 0.0f;
386 m_temporaryUnsummonedPetNumber = 0;
387 //cache for UNIT_CREATED_BY_SPELL to allow
388 //returning reagents for temporarily removed pets
389 //when dying/logging out
390 m_oldpetspell = 0;
392 ////////////////////Rest System/////////////////////
393 time_inn_enter=0;
394 inn_pos_mapid=0;
395 inn_pos_x=0;
396 inn_pos_y=0;
397 inn_pos_z=0;
398 m_rest_bonus=0;
399 rest_type=REST_TYPE_NO;
400 ////////////////////Rest System/////////////////////
402 m_mailsLoaded = false;
403 m_mailsUpdated = false;
404 unReadMails = 0;
405 m_nextMailDelivereTime = 0;
407 m_resetTalentsCost = 0;
408 m_resetTalentsTime = 0;
409 m_itemUpdateQueueBlocked = false;
411 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
412 m_forced_speed_changes[i] = 0;
414 m_stableSlots = 0;
416 /////////////////// Instance System /////////////////////
418 m_HomebindTimer = 0;
419 m_InstanceValid = true;
420 m_dungeonDifficulty = DIFFICULTY_NORMAL;
422 for (int i = 0; i < BASEMOD_END; i++)
424 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
425 m_auraBaseMod[i][PCT_MOD] = 1.0f;
428 for (int i = 0; i < MAX_COMBAT_RATING; i++)
429 m_baseRatingValue[i] = 0;
431 m_baseSpellDamage = 0;
432 m_baseSpellHealing = 0;
433 m_baseFeralAP = 0;
434 m_baseManaRegen = 0;
436 // Honor System
437 m_lastHonorUpdateTime = time(NULL);
439 // Player summoning
440 m_summon_expire = 0;
441 m_summon_mapid = 0;
442 m_summon_x = 0.0f;
443 m_summon_y = 0.0f;
444 m_summon_z = 0.0f;
446 //Default movement to run mode
447 m_unit_movement_flags = 0;
449 m_mover = NULL;
451 m_miniPet = 0;
452 m_bgAfkReportedTimer = 0;
453 m_contestedPvPTimer = 0;
455 m_declinedname = NULL;
456 m_runes = NULL;
459 Player::~Player ()
461 CleanupsBeforeDelete();
463 // it must be unloaded already in PlayerLogout and accessed only for loggined player
464 //m_social = NULL;
466 // Note: buy back item already deleted from DB when player was saved
467 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
469 if(m_items[i])
470 delete m_items[i];
472 CleanupChannels();
474 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
475 delete itr->second;
477 //all mailed items should be deleted, also all mail should be deallocated
478 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
479 delete *itr;
481 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
482 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
484 delete PlayerTalkClass;
486 if (m_transport)
488 m_transport->RemovePassenger(this);
491 for(size_t x = 0; x < ItemSetEff.size(); x++)
492 if(ItemSetEff[x])
493 delete ItemSetEff[x];
495 // clean up player-instance binds, may unload some instance saves
496 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
497 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
498 itr->second.save->RemovePlayer(this);
500 delete m_declinedname;
501 delete m_runes;
504 void Player::CleanupsBeforeDelete()
506 if(m_uint32Values) // only for fully created Object
508 TradeCancel(false);
509 DuelComplete(DUEL_INTERUPTED);
511 Unit::CleanupsBeforeDelete();
514 bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
516 //FIXME: outfitId not used in player creating
518 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
520 m_name = name;
522 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
523 if(!info)
525 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
526 return false;
529 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
530 m_items[i] = NULL;
532 m_race = race;
533 m_class = class_;
535 SetMapId(info->mapId);
536 Relocate(info->positionX,info->positionY,info->positionZ);
538 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
539 if(!cEntry)
541 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
542 return false;
545 uint8 powertype = cEntry->powerType;
547 //uint32 unitfield;
549 /*switch(powertype)
551 case POWER_ENERGY:
552 case POWER_MANA:
553 unitfield = 0x00000000;
554 break;
555 case POWER_RAGE:
556 unitfield = 0x00110000;
557 break;
558 case POWER_RUNIC_POWER:
559 unitfield = 0x0000EE00; //TODO: find correct unitfield here
560 break;
561 default:
562 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
563 return false;
566 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
567 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
569 switch(gender)
571 case GENDER_FEMALE:
572 SetDisplayId(info->displayId_f );
573 SetNativeDisplayId(info->displayId_f );
574 break;
575 case GENDER_MALE:
576 SetDisplayId(info->displayId_m );
577 SetNativeDisplayId(info->displayId_m );
578 break;
579 default:
580 sLog.outError("Invalid gender %u for player",gender);
581 return false;
582 break;
585 setFactionForRace(m_race);
587 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
589 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
590 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
591 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
592 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
593 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
594 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
595 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
597 // -1 is default value
598 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
600 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
601 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
602 SetByteValue(PLAYER_BYTES_3, 0, gender);
604 SetUInt32Value( PLAYER_GUILDID, 0 );
605 SetUInt32Value( PLAYER_GUILDRANK, 0 );
606 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
608 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
609 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
610 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
611 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
612 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
613 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
614 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
616 // set starting level
617 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
618 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
619 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
621 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
623 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
624 if(gm_level > start_level)
625 start_level = gm_level;
628 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
630 InitRunes();
632 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
633 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
634 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
636 // Played time
637 m_Last_tick = time(NULL);
638 m_Played_time[0] = 0;
639 m_Played_time[1] = 0;
641 // base stats and related field values
642 InitStatsForLevel();
643 InitTaxiNodesForLevel();
644 InitGlyphsForLevel();
645 InitTalentForLevel();
646 InitPrimaryProffesions(); // to max set before any spell added
648 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
649 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
650 SetHealth(GetMaxHealth());
651 if (getPowerType()==POWER_MANA)
653 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
654 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
657 if(getPowerType() == POWER_RUNIC_POWER)
659 SetPower(POWER_RUNE, 8);
660 SetMaxPower(POWER_RUNE, 8);
661 SetPower(POWER_RUNIC_POWER, 0);
662 SetMaxPower(POWER_RUNIC_POWER, 1000);
665 // original spells
666 learnDefaultSpells();
668 // original action bar
669 std::list<uint16>::const_iterator action_itr[4];
670 for(int i=0; i<4; i++)
671 action_itr[i] = info->action[i].begin();
673 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
675 uint16 taction[4];
676 for(int i=0; i<4 ;i++)
677 taction[i] = (*action_itr[i]);
679 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
681 for(int i=0; i<4 ;i++)
682 ++action_itr[i];
685 // original items
686 CharStartOutfitEntry const* oEntry = NULL;
687 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
689 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
691 if(entry->RaceClassGender == RaceClassGender)
693 oEntry = entry;
694 break;
699 if(oEntry)
701 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
703 if(oEntry->ItemId[j] <= 0)
704 continue;
706 uint32 item_id = oEntry->ItemId[j];
709 // Hack for not existed item id in dbc 3.0.3
710 if(item_id==40582)
711 continue;
713 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
714 if(!iProto)
716 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
717 continue;
720 // max stack by default (mostly 1), 1 for infinity stackable
721 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
723 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
725 switch(iProto->Spells[0].SpellCategory)
727 case 11: // food
728 if(iProto->Stackable > 4)
729 count = 4;
730 break;
731 case 59: // drink
732 if(iProto->Stackable > 2)
733 count = 2;
734 break;
738 StoreNewItemInBestSlots(item_id, count);
742 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
743 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
745 // bags and main-hand weapon must equipped at this moment
746 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
747 // or ammo not equipped in special bag
748 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
750 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
752 uint16 eDest;
753 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
754 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 EquipItem( eDest, pItem, true);
760 // move other items to more appropriate slots (ammo not equipped in special bag)
761 else
763 ItemPosCountVec sDest;
764 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
765 if( msg == EQUIP_ERR_OK )
767 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
768 pItem = StoreItem( sDest, pItem, true);
771 // if this is ammo then use it
772 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
773 if( msg == EQUIP_ERR_OK )
774 SetAmmo( pItem->GetProto()->ItemId );
778 // all item positions resolved
780 return true;
783 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
785 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
787 // attempt equip by one
788 while(titem_amount > 0)
790 uint16 eDest;
791 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
792 if( msg != EQUIP_ERR_OK )
793 break;
795 EquipNewItem( eDest, titem_id, true);
796 AutoUnequipOffhandIfNeed();
797 --titem_amount;
800 if(titem_amount == 0)
801 return true; // equipped
803 // attempt store
804 ItemPosCountVec sDest;
805 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
806 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
807 if( msg == EQUIP_ERR_OK )
809 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
810 return true; // stored
813 // item can't be added
814 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
815 return false;
818 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
820 uint32 BreathRegen = (uint32)-1;
822 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
823 data << (uint32)Type;
824 data << MaxValue;
825 data << MaxValue;
826 data << BreathRegen;
827 data << (uint8)0;
828 data << (uint32)0; // spell id
829 GetSession()->SendPacket(&data);
832 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
834 if(Type==BREATH_TIMER)
835 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
837 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
838 data << (uint32)Type;
839 data << CurrentValue;
840 data << MaxValue;
841 data << Regen;
842 data << (uint8)0;
843 data << (uint32)0; // spell id
844 GetSession()->SendPacket( &data );
847 void Player::StopMirrorTimer(MirrorTimerType Type)
849 if(Type==BREATH_TIMER)
850 m_breathTimer = 0;
852 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
853 data << (uint32)Type;
854 GetSession()->SendPacket( &data );
857 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
859 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
860 data << (uint64)guid;
861 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
862 data << (uint32)damage;
863 data << (uint32)0;
864 data << (uint32)0;
865 SendMessageToSet(&data, true);
867 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
869 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
871 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
872 DurabilityLossAll(0.10f,false);
873 // durability lost message
874 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
875 GetSession()->SendPacket(&data);
879 void Player::HandleDrowning()
881 if(!(m_isunderwater&~UNDERWATER_INLAVA))
882 return;
884 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
885 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
887 StopMirrorTimer(BREATH_TIMER);
888 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
889 m_isunderwater &= UNDERWATER_INLAVA;
890 return;
893 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
895 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
896 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
897 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
899 if ((m_isunderwater & UNDERWATER_INWATER) && !(m_isunderwater & UNDERWATER_INLAVA) && isAlive())
901 //single trigger timer
902 if (!(m_isunderwater & UNDERWATER_WATER_TRIGGER))
904 m_isunderwater|= UNDERWATER_WATER_TRIGGER;
905 m_breathTimer = UnderWaterTime + 1000;
907 //single trigger "show Breathbar"
908 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & UNDERWATER_WATER_BREATHB))
910 m_isunderwater|= UNDERWATER_WATER_BREATHB;
911 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
913 //continuous trigger drowning "Damage"
914 if ((m_breathTimer == 0) && (m_isunderwater & UNDERWATER_INWATER))
916 //TODO: Check this formula
917 uint64 guid = GetGUID();
918 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
920 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
921 m_breathTimer = 2000;
924 //single trigger retract bar
925 else if (!(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater & UNDERWATER_WATER_TRIGGER) && (m_breathTimer > 0) && isAlive())
927 uint32 BreathRegen = 10;
928 // m_breathTimer will be reduced in ModifyMirrorTimer
929 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
930 m_isunderwater = UNDERWATER_WATER_BREATHB_RETRACTING;
932 //remove bar
933 else if ((m_breathTimer < 50) && !(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater == UNDERWATER_WATER_BREATHB_RETRACTING))
935 StopMirrorTimer(BREATH_TIMER);
936 m_isunderwater = UNDERWATER_NONE;
940 void Player::HandleLava()
942 if ((m_isunderwater & UNDERWATER_INLAVA) && isAlive())
945 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
946 // Single trigger Set BreathTimer
947 if (!(m_isunderwater & UNDERWATER_INLAVA))
949 m_isunderwater|= UNDERWATER_WATER_BREATHB;
950 m_breathTimer = 1000;
953 // Reset BreathTimer and still in the lava
954 if (!m_breathTimer)
956 uint64 guid = GetGUID();
957 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
959 // if not gamemaster then deal damage
960 if ( !isGameMaster() )
961 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
963 m_breathTimer = 1000;
966 else if (!isAlive()) // Disable breath timer and reset underwater flags
968 m_breathTimer = 0;
969 m_isunderwater = UNDERWATER_NONE;
973 ///The player sobers by 256 every 10 seconds
974 void Player::HandleSobering()
976 m_drunkTimer = 0;
978 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
979 SetDrunkValue(drunk);
982 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
984 if(value >= 23000)
985 return DRUNKEN_SMASHED;
986 if(value >= 12800)
987 return DRUNKEN_DRUNK;
988 if(value & 0xFFFE)
989 return DRUNKEN_TIPSY;
990 return DRUNKEN_SOBER;
993 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
995 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
997 m_drunk = newDrunkenValue;
998 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1000 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1002 // special drunk invisibility detection
1003 if(newDrunkenState >= DRUNKEN_DRUNK)
1004 m_detectInvisibilityMask |= (1<<6);
1005 else
1006 m_detectInvisibilityMask &= ~(1<<6);
1008 if(newDrunkenState == oldDrunkenState)
1009 return;
1011 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1012 data << uint64(GetGUID());
1013 data << uint32(newDrunkenState);
1014 data << uint32(itemId);
1016 SendMessageToSet(&data, true);
1019 void Player::Update( uint32 p_time )
1021 if(!IsInWorld())
1022 return;
1024 // undelivered mail
1025 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1027 SendNewMail();
1028 ++unReadMails;
1030 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1031 m_nextMailDelivereTime = 0;
1034 Unit::Update( p_time );
1036 // update player only attacks
1037 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1039 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1042 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1044 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1047 time_t now = time (NULL);
1049 UpdatePvPFlag(now);
1051 UpdateContestedPvP(p_time);
1053 UpdateDuelFlag(now);
1055 CheckDuelDistance(now);
1057 UpdateAfkReport(now);
1059 CheckExploreSystem();
1061 // Update items that have just a limited lifetime
1062 if (now>m_Last_tick)
1063 UpdateItemDuration(uint32(now- m_Last_tick));
1065 if (!m_timedquests.empty())
1067 std::set<uint32>::iterator iter = m_timedquests.begin();
1068 while (iter != m_timedquests.end())
1070 QuestStatusData& q_status = mQuestStatus[*iter];
1071 if( q_status.m_timer <= p_time )
1073 uint32 quest_id = *iter;
1074 ++iter; // current iter will be removed in FailTimedQuest
1075 FailTimedQuest( quest_id );
1077 else
1079 q_status.m_timer -= p_time;
1080 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1081 ++iter;
1086 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1088 Unit *pVictim = getVictim();
1089 if( !IsNonMeleeSpellCasted(false) && pVictim)
1091 // default combat reach 10
1092 // TODO add weapon,skill check
1094 float pldistance = ATTACK_DISTANCE;
1096 if (isAttackReady(BASE_ATTACK))
1098 if(!IsWithinDistInMap(pVictim, pldistance))
1100 setAttackTimer(BASE_ATTACK,100);
1101 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1103 SendAttackSwingNotInRange();
1104 m_swingErrorMsg = 1;
1107 //120 degrees of radiant range
1108 else if( !HasInArc( 2*M_PI/3, pVictim ))
1110 setAttackTimer(BASE_ATTACK,100);
1111 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1113 SendAttackSwingBadFacingAttack();
1114 m_swingErrorMsg = 2;
1117 else
1119 m_swingErrorMsg = 0; // reset swing error state
1121 // prevent base and off attack in same time, delay attack at 0.2 sec
1122 if(haveOffhandWeapon())
1124 uint32 off_att = getAttackTimer(OFF_ATTACK);
1125 if(off_att < ATTACK_DISPLAY_DELAY)
1126 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1128 AttackerStateUpdate(pVictim, BASE_ATTACK);
1129 resetAttackTimer(BASE_ATTACK);
1133 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1135 if(!IsWithinDistInMap(pVictim, pldistance))
1137 setAttackTimer(OFF_ATTACK,100);
1139 else if( !HasInArc( 2*M_PI/3, pVictim ))
1141 setAttackTimer(OFF_ATTACK,100);
1143 else
1145 // prevent base and off attack in same time, delay attack at 0.2 sec
1146 uint32 base_att = getAttackTimer(BASE_ATTACK);
1147 if(base_att < ATTACK_DISPLAY_DELAY)
1148 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1149 // do attack
1150 AttackerStateUpdate(pVictim, OFF_ATTACK);
1151 resetAttackTimer(OFF_ATTACK);
1155 Unit *owner = pVictim->GetOwner();
1156 Unit *u = owner ? owner : pVictim;
1157 if(u->IsPvP() && (!duel || duel->opponent != u))
1159 UpdatePvP(true);
1160 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1165 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1167 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1169 int time_inn = time(NULL)-GetTimeInnEnter();
1170 if (time_inn >= 10) //freeze update
1172 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1173 //speed collect rest bonus (section/in hour)
1174 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1175 UpdateInnerTime(time(NULL));
1180 if(m_regenTimer > 0)
1182 if(p_time >= m_regenTimer)
1183 m_regenTimer = 0;
1184 else
1185 m_regenTimer -= p_time;
1188 if (m_weaponChangeTimer > 0)
1190 if(p_time >= m_weaponChangeTimer)
1191 m_weaponChangeTimer = 0;
1192 else
1193 m_weaponChangeTimer -= p_time;
1196 if (m_zoneUpdateTimer > 0)
1198 if(p_time >= m_zoneUpdateTimer)
1200 uint32 newzone = GetZoneId();
1201 if( m_zoneUpdateId != newzone )
1202 UpdateZone(newzone); // also update area
1203 else
1205 // use area updates as well
1206 // needed for free far all arenas for example
1207 uint32 newarea = GetAreaId();
1208 if( m_areaUpdateId != newarea )
1209 UpdateArea(newarea);
1211 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1214 else
1215 m_zoneUpdateTimer -= p_time;
1218 if (isAlive())
1220 RegenerateAll();
1223 if (m_deathState == JUST_DIED)
1225 KillPlayer();
1228 if(m_nextSave > 0)
1230 if(p_time >= m_nextSave)
1232 // m_nextSave reseted in SaveToDB call
1233 SaveToDB();
1234 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1236 else
1238 m_nextSave -= p_time;
1242 //Breathtimer
1243 if(m_breathTimer > 0)
1245 if(p_time >= m_breathTimer)
1246 m_breathTimer = 0;
1247 else
1248 m_breathTimer -= p_time;
1252 //Handle Water/drowning
1253 HandleDrowning();
1255 //Handle lava
1256 HandleLava();
1258 //Handle detect stealth players
1259 if (m_DetectInvTimer > 0)
1261 if (p_time >= m_DetectInvTimer)
1263 m_DetectInvTimer = 3000;
1264 HandleStealthedUnitsDetection();
1266 else
1267 m_DetectInvTimer -= p_time;
1270 // Played time
1271 if (now > m_Last_tick)
1273 uint32 elapsed = uint32(now - m_Last_tick);
1274 m_Played_time[0] += elapsed; // Total played time
1275 m_Played_time[1] += elapsed; // Level played time
1276 m_Last_tick = now;
1279 if (m_drunk)
1281 m_drunkTimer += p_time;
1283 if (m_drunkTimer > 10000)
1284 HandleSobering();
1287 // not auto-free ghost from body in instances
1288 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1290 if(p_time >= m_deathTimer)
1292 m_deathTimer = 0;
1293 BuildPlayerRepop();
1294 RepopAtGraveyard();
1296 else
1297 m_deathTimer -= p_time;
1300 UpdateEnchantTime(p_time);
1301 UpdateHomebindTime(p_time);
1303 // group update
1304 SendUpdateToOutOfRangeGroupMembers();
1306 Pet* pet = GetPet();
1307 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1309 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1310 return;
1314 void Player::setDeathState(DeathState s)
1316 uint32 ressSpellId = 0;
1318 bool cur = isAlive();
1320 if(s == JUST_DIED && cur)
1322 // drunken state is cleared on death
1323 SetDrunkValue(0);
1324 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1325 ClearComboPoints();
1327 clearResurrectRequestData();
1329 // remove form before other mods to prevent incorrect stats calculation
1330 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1332 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1333 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1335 // remove uncontrolled pets
1336 RemoveMiniPet();
1337 RemoveGuardians();
1339 // save value before aura remove in Unit::setDeathState
1340 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1342 // passive spell
1343 if(!ressSpellId)
1344 ressSpellId = GetResurrectionSpellId();
1345 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1347 Unit::setDeathState(s);
1349 // restore resurrection spell id for player after aura remove
1350 if(s == JUST_DIED && cur && ressSpellId)
1351 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1353 if(isAlive() && !cur)
1355 //clear aura case after resurrection by another way (spells will be applied before next death)
1356 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1358 // restore default warrior stance
1359 if(getClass()== CLASS_WARRIOR)
1360 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1364 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1366 Field *fields = result->Fetch();
1368 *p_data << uint64(GetGUID());
1369 *p_data << m_name;
1371 *p_data << uint8(getRace());
1372 uint8 pClass = getClass();
1373 *p_data << uint8(pClass);
1374 *p_data << uint8(getGender());
1376 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1377 *p_data << uint8(bytes);
1378 *p_data << uint8(bytes >> 8);
1379 *p_data << uint8(bytes >> 16);
1380 *p_data << uint8(bytes >> 24);
1382 bytes = GetUInt32Value(PLAYER_BYTES_2);
1383 *p_data << uint8(bytes);
1385 *p_data << uint8(getLevel()); // player level
1386 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1387 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1388 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1389 *p_data << uint32(zoneId);
1390 *p_data << uint32(GetMapId());
1392 *p_data << GetPositionX();
1393 *p_data << GetPositionY();
1394 *p_data << GetPositionZ();
1396 // guild id
1397 *p_data << (result ? fields[13].GetUInt32() : 0);
1399 uint32 char_flags = 0;
1400 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1401 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1402 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1403 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1404 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1405 char_flags |= CHARACTER_FLAG_GHOST;
1406 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1407 char_flags |= CHARACTER_FLAG_RENAME;
1408 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1409 char_flags |= CHARACTER_FLAG_DECLINED;
1411 *p_data << uint32(char_flags); // character flags
1412 // character customize (flags?)
1413 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1414 *p_data << uint8(1); // unknown
1416 // Pets info
1418 uint32 petDisplayId = 0;
1419 uint32 petLevel = 0;
1420 uint32 petFamily = 0;
1422 // show pet at selection character in character list only for non-ghost character
1423 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1425 uint32 entry = fields[10].GetUInt32();
1426 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1427 if(cInfo)
1429 petDisplayId = fields[11].GetUInt32();
1430 petLevel = fields[12].GetUInt32();
1431 petFamily = cInfo->family;
1435 *p_data << uint32(petDisplayId);
1436 *p_data << uint32(petLevel);
1437 *p_data << uint32(petFamily);
1440 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1442 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1443 uint32 item_id = GetUInt32Value(visualbase);
1444 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1445 SpellItemEnchantmentEntry const *enchant = NULL;
1447 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1449 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1450 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1451 break;
1454 if (proto != NULL)
1456 *p_data << uint32(proto->DisplayInfoID);
1457 *p_data << uint8(proto->InventoryType);
1458 *p_data << uint32(enchant ? enchant->aura_id : 0);
1460 else
1462 *p_data << uint32(0);
1463 *p_data << uint8(0);
1464 *p_data << uint32(0); // enchant?
1467 *p_data << uint32(0); // first bag display id
1468 *p_data << uint8(0); // first bag inventory type
1469 *p_data << uint32(0); // enchant?
1472 bool Player::ToggleAFK()
1474 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1476 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1478 // afk player not allowed in battleground
1479 if(state && InBattleGround())
1480 LeaveBattleground();
1482 return state;
1485 bool Player::ToggleDND()
1487 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1489 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1492 uint8 Player::chatTag() const
1494 // it's bitmask
1495 // 0x8 - ??
1496 // 0x4 - gm
1497 // 0x2 - dnd
1498 // 0x1 - afk
1499 if(isGMChat())
1500 return 4;
1501 else if(isDND())
1502 return 3;
1503 if(isAFK())
1504 return 1;
1505 else
1506 return 0;
1509 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1511 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1513 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1514 return false;
1517 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1518 Pet* pet = GetPet();
1520 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1522 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1523 // don't let gm level > 1 either
1524 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1525 return false;
1527 // client without expansion support
1528 if(GetSession()->Expansion() < mEntry->Expansion())
1530 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1532 if(GetTransport())
1533 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1535 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1537 return false; // normal client can't teleport to this map...
1539 else
1541 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1544 // if we were on a transport, leave
1545 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1547 m_transport->RemovePassenger(this);
1548 m_transport = NULL;
1549 m_movementInfo.t_x = 0.0f;
1550 m_movementInfo.t_y = 0.0f;
1551 m_movementInfo.t_z = 0.0f;
1552 m_movementInfo.t_o = 0.0f;
1553 m_movementInfo.t_time = 0;
1556 SetSemaphoreTeleport(true);
1558 // The player was ported to another map and looses the duel immediately.
1559 // We have to perform this check before the teleport, otherwise the
1560 // ObjectAccessor won't find the flag.
1561 if (duel && GetMapId()!=mapid)
1563 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1564 if (obj)
1565 DuelComplete(DUEL_FLED);
1568 // reset movement flags at teleport, because player will continue move with these flags after teleport
1569 SetUnitMovementFlags(0);
1571 if ((GetMapId() == mapid) && (!m_transport))
1573 // prepare zone change detect
1574 uint32 old_zone = GetZoneId();
1576 // near teleport
1577 if(!GetSession()->PlayerLogout())
1579 WorldPacket data;
1580 BuildTeleportAckMsg(&data, x, y, z, orientation);
1581 GetSession()->SendPacket(&data);
1582 SetPosition( x, y, z, orientation, true);
1584 else
1585 // this will be used instead of the current location in SaveToDB
1586 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1587 SetFallInformation(0, z);
1589 //BuildHeartBeatMsg(&data);
1590 //SendMessageToSet(&data, true);
1591 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1593 //same map, only remove pet if out of range
1594 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1596 if(pet->isControlled() && !pet->isTemporarySummoned() )
1597 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1598 else
1599 m_temporaryUnsummonedPetNumber = 0;
1601 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1605 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1606 CombatStop();
1608 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1610 // resummon pet
1611 if(pet && m_temporaryUnsummonedPetNumber)
1613 Pet* NewPet = new Pet;
1614 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1615 delete NewPet;
1617 m_temporaryUnsummonedPetNumber = 0;
1621 if(!GetSession()->PlayerLogout())
1623 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1624 SetSemaphoreTeleport(false);
1626 UpdateZone(GetZoneId());
1629 // new zone
1630 if(old_zone != GetZoneId())
1632 // honorless target
1633 if(pvpInfo.inHostileArea)
1634 CastSpell(this, 2479, true);
1637 else
1639 // far teleport to another map
1640 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1641 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1643 // Check enter rights before map getting to avoid creating instance copy for player
1644 // this check not dependent from map instance copy and same for all instance copies of selected map
1645 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1647 SetSemaphoreTeleport(false);
1648 return false;
1651 // If the map is not created, assume it is possible to enter it.
1652 // It will be created in the WorldPortAck.
1653 Map *map = MapManager::Instance().FindMap(mapid);
1654 if (!map || map->CanEnter(this))
1656 SetSelection(0);
1658 CombatStop();
1660 ResetContestedPvP();
1662 // remove player from battleground on far teleport (when changing maps)
1663 if(BattleGround const* bg = GetBattleGround())
1665 // Note: at battleground join battleground id set before teleport
1666 // and we already will found "current" battleground
1667 // just need check that this is targeted map or leave
1668 if(bg->GetMapId() != mapid)
1669 LeaveBattleground(false); // don't teleport to entry point
1672 // remove pet on map change
1673 if (pet)
1675 //leaving map -> delete pet right away (doing this later will cause problems)
1676 if(pet->isControlled() && !pet->isTemporarySummoned())
1677 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1678 else
1679 m_temporaryUnsummonedPetNumber = 0;
1681 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1684 // remove all dyn objects
1685 RemoveAllDynObjects();
1687 // stop spellcasting
1688 // not attempt interrupt teleportation spell at caster teleport
1689 if(!(options & TELE_TO_SPELL))
1690 if(IsNonMeleeSpellCasted(true))
1691 InterruptNonMeleeSpells(true);
1693 if(!GetSession()->PlayerLogout())
1695 // send transfer packets
1696 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1697 data << uint32(mapid);
1698 if (m_transport)
1700 data << m_transport->GetEntry() << GetMapId();
1702 GetSession()->SendPacket(&data);
1704 data.Initialize(SMSG_NEW_WORLD, (20));
1705 if (m_transport)
1707 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1709 else
1711 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1713 GetSession()->SendPacket( &data );
1714 SendSavedInstances();
1716 // remove from old map now
1717 if(oldmap) oldmap->Remove(this, false);
1720 // new final coordinates
1721 float final_x = x;
1722 float final_y = y;
1723 float final_z = z;
1724 float final_o = orientation;
1726 if(m_transport)
1728 final_x += m_movementInfo.t_x;
1729 final_y += m_movementInfo.t_y;
1730 final_z += m_movementInfo.t_z;
1731 final_o += m_movementInfo.t_o;
1734 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1735 SetFallInformation(0, final_z);
1736 // if the player is saved before worldportack (at logout for example)
1737 // this will be used instead of the current location in SaveToDB
1739 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1741 // move packet sent by client always after far teleport
1742 // SetPosition(final_x, final_y, final_z, final_o, true);
1743 SetDontMove(true);
1745 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1747 else
1748 return false;
1750 return true;
1753 void Player::AddToWorld()
1755 ///- Do not add/remove the player from the object storage
1756 ///- It will crash when updating the ObjectAccessor
1757 ///- The player should only be added when logging in
1758 Unit::AddToWorld();
1760 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1762 if(m_items[i])
1763 m_items[i]->AddToWorld();
1767 void Player::RemoveFromWorld()
1769 // cleanup
1770 if(IsInWorld())
1772 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1773 Uncharm();
1774 UnsummonAllTotems();
1775 RemoveMiniPet();
1776 RemoveGuardians();
1779 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1781 if(m_items[i])
1782 m_items[i]->RemoveFromWorld();
1785 ///- Do not add/remove the player from the object storage
1786 ///- It will crash when updating the ObjectAccessor
1787 ///- The player should only be removed when logging out
1788 Unit::RemoveFromWorld();
1791 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1793 float addRage;
1795 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1797 if(attacker)
1799 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1801 // talent who gave more rage on attack
1802 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1804 else
1806 addRage = damage/rageconversion*2.5;
1808 // Berserker Rage effect
1809 if(HasAura(18499,0))
1810 addRage *= 1.3;
1813 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1815 ModifyPower(POWER_RAGE, uint32(addRage*10));
1818 void Player::RegenerateAll()
1820 if (m_regenTimer != 0)
1821 return;
1822 uint32 regenDelay = 2000;
1824 // Not in combat or they have regeneration
1825 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1826 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1828 RegenerateHealth();
1829 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1831 Regenerate(POWER_RAGE);
1832 if(getClass() == CLASS_DEATH_KNIGHT)
1833 Regenerate(POWER_RUNIC_POWER);
1837 Regenerate( POWER_ENERGY );
1839 Regenerate( POWER_MANA );
1841 if(getClass() == CLASS_DEATH_KNIGHT)
1842 Regenerate( POWER_RUNE );
1844 m_regenTimer = regenDelay;
1847 void Player::Regenerate(Powers power)
1849 uint32 curValue = GetPower(power);
1850 uint32 maxValue = GetMaxPower(power);
1852 float addvalue = 0.0f;
1854 switch (power)
1856 case POWER_MANA:
1858 bool recentCast = IsUnderLastManaUseEffect();
1859 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1860 if (recentCast)
1862 // Mangos Updates Mana in intervals of 2s, which is correct
1863 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1865 else
1867 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1869 } break;
1870 case POWER_RAGE: // Regenerate rage
1872 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1873 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1874 } break;
1875 case POWER_ENERGY: // Regenerate energy (rogue)
1876 addvalue = 20;
1877 break;
1878 case POWER_RUNIC_POWER:
1880 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1881 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1882 } break;
1883 case POWER_RUNE:
1885 for(uint32 i = 0; i < MAX_RUNES; ++i)
1886 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1887 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1888 } break;
1889 case POWER_FOCUS:
1890 case POWER_HAPPINESS:
1891 break;
1894 // Mana regen calculated in Player::UpdateManaRegen()
1895 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1896 if(power != POWER_MANA)
1898 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1899 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1900 if ((*i)->GetModifier()->m_miscvalue == power)
1901 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1904 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1906 curValue += uint32(addvalue);
1907 if (curValue > maxValue)
1908 curValue = maxValue;
1910 else
1912 if(curValue <= uint32(addvalue))
1913 curValue = 0;
1914 else
1915 curValue -= uint32(addvalue);
1917 SetPower(power, curValue);
1920 void Player::RegenerateHealth()
1922 uint32 curValue = GetHealth();
1923 uint32 maxValue = GetMaxHealth();
1925 if (curValue >= maxValue) return;
1927 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1929 float addvalue = 0.0f;
1931 // polymorphed case
1932 if ( IsPolymorphed() )
1933 addvalue = GetMaxHealth()/3;
1934 // normal regen case (maybe partly in combat case)
1935 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1937 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1938 if (!isInCombat())
1940 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1941 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1942 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1944 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1945 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1947 if(!IsStandState())
1948 addvalue *= 1.5;
1951 // always regeneration bonus (including combat)
1952 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1954 if(addvalue < 0)
1955 addvalue = 0;
1957 ModifyHealth(int32(addvalue));
1960 bool Player::CanInteractWithNPCs(bool alive) const
1962 if(alive && !isAlive())
1963 return false;
1964 if(isInFlight())
1965 return false;
1967 return true;
1970 bool Player::IsUnderWater() const
1972 return IsInWater() &&
1973 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1976 void Player::SetInWater(bool apply)
1978 if(m_isInWater==apply)
1979 return;
1981 //define player in water by opcodes
1982 //move player's guid into HateOfflineList of those mobs
1983 //which can't swim and move guid back into ThreatList when
1984 //on surface.
1985 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1986 m_isInWater = apply;
1988 // remove auras that need water/land
1989 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1991 getHostilRefManager().updateThreatTables();
1994 void Player::SetGameMaster(bool on)
1996 if(on)
1998 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1999 setFaction(35);
2000 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2002 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2003 ResetContestedPvP();
2005 getHostilRefManager().setOnlineOfflineState(false);
2006 CombatStop();
2008 else
2010 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2011 setFactionForRace(getRace());
2012 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2014 // restore FFA PvP Server state
2015 if(sWorld.IsFFAPvPRealm())
2016 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2018 // restore FFA PvP area state, remove not allowed for GM mounts
2019 UpdateArea(m_areaUpdateId);
2021 getHostilRefManager().setOnlineOfflineState(true);
2024 ObjectAccessor::UpdateVisibilityForPlayer(this);
2027 void Player::SetGMVisible(bool on)
2029 if(on)
2031 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2033 // Reapply stealth/invisibility if active or show if not any
2034 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2035 SetVisibility(VISIBILITY_GROUP_STEALTH);
2036 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2037 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2038 else
2039 SetVisibility(VISIBILITY_ON);
2041 else
2043 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2045 SetAcceptWhispers(false);
2046 SetGameMaster(true);
2048 SetVisibility(VISIBILITY_OFF);
2052 bool Player::IsGroupVisibleFor(Player* p) const
2054 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2056 default: return IsInSameGroupWith(p);
2057 case 1: return IsInSameRaidWith(p);
2058 case 2: return GetTeam()==p->GetTeam();
2062 bool Player::IsInSameGroupWith(Player const* p) const
2064 return p==this || GetGroup() != NULL &&
2065 GetGroup() == p->GetGroup() &&
2066 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2069 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2070 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2071 void Player::UninviteFromGroup()
2073 Group* group = GetGroupInvite();
2074 if(!group)
2075 return;
2077 group->RemoveInvite(this);
2079 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2081 if(group->IsCreated())
2083 group->Disband(true);
2084 objmgr.RemoveGroup(group);
2086 else
2087 group->RemoveAllInvites();
2089 delete group;
2093 void Player::RemoveFromGroup(Group* group, uint64 guid)
2095 if(group)
2097 if (group->RemoveMember(guid, 0) <= 1)
2099 // group->Disband(); already disbanded in RemoveMember
2100 objmgr.RemoveGroup(group);
2101 delete group;
2102 // removemember sets the player's group pointer to NULL
2107 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2109 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2110 data << uint64(victim ? victim->GetGUID() : 0); // guid
2111 data << uint32(GivenXP+RestXP); // given experience
2112 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2113 if(victim)
2115 data << uint32(GivenXP); // experience without rested bonus
2116 data << float(1); // 1 - none 0 - 100% group bonus output
2118 data << uint8(0); // new 2.4.0
2119 GetSession()->SendPacket(&data);
2122 void Player::GiveXP(uint32 xp, Unit* victim)
2124 if ( xp < 1 )
2125 return;
2127 if(!isAlive())
2128 return;
2130 uint32 level = getLevel();
2132 // XP to money conversion processed in Player::RewardQuest
2133 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2134 return;
2136 // handle SPELL_AURA_MOD_XP_PCT auras
2137 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2138 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2139 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2141 // XP resting bonus for kill
2142 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2144 SendLogXPGain(xp,victim,rested_bonus_xp);
2146 uint32 curXP = GetUInt32Value(PLAYER_XP);
2147 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2148 uint32 newXP = curXP + xp + rested_bonus_xp;
2150 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2152 newXP -= nextLvlXP;
2154 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2155 GiveLevel(level + 1);
2157 level = getLevel();
2158 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2161 SetUInt32Value(PLAYER_XP, newXP);
2164 // Update player to next level
2165 // Current player experience not update (must be update by caller)
2166 void Player::GiveLevel(uint32 level)
2168 if ( level == getLevel() )
2169 return;
2171 PlayerLevelInfo info;
2172 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2174 PlayerClassLevelInfo classInfo;
2175 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2177 // send levelup info to client
2178 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2179 data << uint32(level);
2180 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2181 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2182 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2183 data << uint32(0);
2184 data << uint32(0);
2185 data << uint32(0);
2186 data << uint32(0);
2187 data << uint32(0);
2188 data << uint32(0);
2189 // end for
2190 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2191 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2193 GetSession()->SendPacket(&data);
2195 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2197 //update level, max level of skills
2198 if(getLevel()!= level)
2199 m_Played_time[1] = 0; // Level Played Time reset
2200 SetLevel(level);
2201 UpdateSkillsForLevel ();
2203 // save base values (bonuses already included in stored stats
2204 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2205 SetCreateStat(Stats(i), info.stats[i]);
2207 SetCreateHealth(classInfo.basehealth);
2208 SetCreateMana(classInfo.basemana);
2210 InitTalentForLevel();
2211 InitTaxiNodesForLevel();
2212 InitGlyphsForLevel();
2214 UpdateAllStats();
2216 // set current level health and mana/energy to maximum after applying all mods.
2217 SetHealth(GetMaxHealth());
2218 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2219 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2220 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2221 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2222 SetPower(POWER_FOCUS, 0);
2223 SetPower(POWER_HAPPINESS, 0);
2225 // give level to summoned pet
2226 Pet* pet = GetPet();
2227 if(pet && pet->getPetType()==SUMMON_PET)
2228 pet->GivePetLevel(level);
2229 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2232 void Player::InitTalentForLevel()
2234 uint32 level = getLevel();
2235 // talents base at level diff ( talents = level - 9 but some can be used already)
2236 if(level < 10)
2238 // Remove all talent points
2239 if(m_usedTalentCount > 0) // Free any used talents
2241 resetTalents(true);
2242 SetFreeTalentPoints(0);
2245 else
2247 uint32 talentPointsForLevel = CalculateTalentsPoints();
2249 // if used more that have then reset
2250 if(m_usedTalentCount > talentPointsForLevel)
2252 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2253 resetTalents(true);
2254 else
2255 SetFreeTalentPoints(0);
2257 // else update amount of free points
2258 else
2259 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2263 void Player::InitStatsForLevel(bool reapplyMods)
2265 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2266 _RemoveAllStatBonuses();
2268 PlayerClassLevelInfo classInfo;
2269 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2271 PlayerLevelInfo info;
2272 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2274 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2275 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2277 UpdateSkillsForLevel ();
2279 // set default cast time multiplier
2280 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2282 // reset size before reapply auras
2283 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2285 // save base values (bonuses already included in stored stats
2286 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2287 SetCreateStat(Stats(i), info.stats[i]);
2289 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2290 SetStat(Stats(i), info.stats[i]);
2292 SetCreateHealth(classInfo.basehealth);
2294 //set create powers
2295 SetCreateMana(classInfo.basemana);
2297 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2299 InitStatBuffMods();
2301 //reset rating fields values
2302 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2303 SetUInt32Value(index, 0);
2305 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2306 for (int i = 0; i < 7; i++)
2308 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2309 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2310 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2313 //reset attack power, damage and attack speed fields
2314 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2315 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2316 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2318 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2319 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2320 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2321 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2322 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2323 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2325 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2326 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2327 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2328 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2329 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2330 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2332 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2333 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2334 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2335 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2337 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2338 for (uint8 i = 0; i < 7; ++i)
2339 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2341 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2342 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2343 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2345 // Dodge percentage
2346 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2348 // set armor (resistance 0) to original value (create_agility*2)
2349 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2350 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2351 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2352 // set other resistance to original value (0)
2353 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2355 SetResistance(SpellSchools(i), 0);
2356 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2357 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2360 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2361 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2362 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2364 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2365 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2367 // Reset no reagent cost field
2368 for(int i = 0; i < 3; i++)
2369 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2370 // Init data for form but skip reapply item mods for form
2371 InitDataForForm(reapplyMods);
2373 // save new stats
2374 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2375 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2377 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2379 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2380 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2382 // cleanup unit flags (will be re-applied if need at aura load).
2383 RemoveFlag( UNIT_FIELD_FLAGS,
2384 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2385 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2386 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2387 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2388 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2389 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2391 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2392 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2394 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2395 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2397 // restore if need some important flags
2398 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2400 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2401 _ApplyAllStatBonuses();
2403 // set current level health and mana/energy to maximum after applying all mods.
2404 SetHealth(GetMaxHealth());
2405 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2406 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2407 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2408 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2409 SetPower(POWER_FOCUS, 0);
2410 SetPower(POWER_HAPPINESS, 0);
2411 SetPower(POWER_RUNIC_POWER, 0);
2414 void Player::SendInitialSpells()
2416 uint16 spellCount = 0;
2418 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2419 data << uint8(0);
2421 size_t countPos = data.wpos();
2422 data << uint16(spellCount); // spell count placeholder
2424 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2426 if(itr->second->state == PLAYERSPELL_REMOVED)
2427 continue;
2429 if(!itr->second->active || itr->second->disabled)
2430 continue;
2432 data << uint16(itr->first);
2433 data << uint16(0); // it's not slot id
2435 spellCount +=1;
2438 data.put<uint16>(countPos,spellCount); // write real count value
2440 uint16 spellCooldowns = m_spellCooldowns.size();
2441 data << uint16(spellCooldowns);
2442 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2444 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2445 if(!sEntry)
2446 continue;
2448 data << uint16(itr->first);
2450 time_t cooldown = 0;
2451 time_t curTime = time(NULL);
2452 if(itr->second.end > curTime)
2453 cooldown = (itr->second.end-curTime)*1000;
2455 data << uint16(itr->second.itemid); // cast item id
2456 data << uint16(sEntry->Category); // spell category
2457 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2459 data << uint32(0); // cooldown
2460 data << uint32(cooldown); // category cooldown
2462 else
2464 data << uint32(cooldown); // cooldown
2465 data << uint32(0); // category cooldown
2469 GetSession()->SendPacket(&data);
2471 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2474 void Player::RemoveMail(uint32 id)
2476 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2478 if ((*itr)->messageID == id)
2480 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2481 m_mail.erase(itr);
2482 return;
2487 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2489 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2490 data << (uint32) mailId;
2491 data << (uint32) mailAction;
2492 data << (uint32) mailError;
2493 if ( mailError == MAIL_ERR_BAG_FULL )
2494 data << (uint32) equipError;
2495 else if( mailAction == MAIL_ITEM_TAKEN )
2497 data << (uint32) item_guid; // item guid low?
2498 data << (uint32) item_count; // item count?
2500 GetSession()->SendPacket(&data);
2503 void Player::SendNewMail()
2505 // deliver undelivered mail
2506 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2507 data << (uint32) 0;
2508 GetSession()->SendPacket(&data);
2511 void Player::UpdateNextMailTimeAndUnreads()
2513 // calculate next delivery time (min. from non-delivered mails
2514 // and recalculate unReadMail
2515 time_t cTime = time(NULL);
2516 m_nextMailDelivereTime = 0;
2517 unReadMails = 0;
2518 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2520 if((*itr)->deliver_time > cTime)
2522 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2523 m_nextMailDelivereTime = (*itr)->deliver_time;
2525 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2526 ++unReadMails;
2530 void Player::AddNewMailDeliverTime(time_t deliver_time)
2532 if(deliver_time <= time(NULL)) // ready now
2534 ++unReadMails;
2535 SendNewMail();
2537 else // not ready and no have ready mails
2539 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2540 m_nextMailDelivereTime = deliver_time;
2544 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool disabled)
2546 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2547 if (!spellInfo)
2549 // do character spell book cleanup (all characters)
2550 if(!IsInWorld() && !learning) // spell load case
2552 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2553 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2555 else
2556 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2558 return false;
2561 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2563 // do character spell book cleanup (all characters)
2564 if(!IsInWorld() && !learning) // spell load case
2566 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2567 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2569 else
2570 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2572 return false;
2575 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2577 bool disabled_case = false;
2578 bool superceded_old = false;
2580 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2581 if (itr != m_spells.end())
2583 // update active state for known spell
2584 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2586 itr->second->active = active;
2588 // !IsInWorld() && !learning == explicitly load from DB and then exist in it already and set correctly
2589 if(!IsInWorld() && !learning)
2590 itr->second->state = PLAYERSPELL_UNCHANGED;
2591 else if(itr->second->state != PLAYERSPELL_NEW)
2592 itr->second->state = PLAYERSPELL_CHANGED;
2594 if(!active)
2596 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2597 data << uint16(spell_id);
2598 GetSession()->SendPacket(&data);
2600 return active; // learn (show in spell book if active now)
2603 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2605 if(itr->second->state != PLAYERSPELL_NEW)
2606 itr->second->state = PLAYERSPELL_CHANGED;
2607 itr->second->disabled = disabled;
2609 if(disabled)
2610 return false;
2612 disabled_case = true;
2614 else switch(itr->second->state)
2616 case PLAYERSPELL_UNCHANGED: // known saved spell
2617 return false;
2618 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2620 delete itr->second;
2621 m_spells.erase(itr);
2622 state = PLAYERSPELL_CHANGED;
2623 break; // need re-add
2625 default: // known not saved yet spell (new or modified)
2627 // can be in case spell loading but learned at some previous spell loading
2628 if(!IsInWorld() && !learning)
2629 itr->second->state = PLAYERSPELL_UNCHANGED;
2631 return false;
2636 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2638 // talent: unlearn all other talent ranks (high and low)
2639 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2641 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2643 for(int i=0; i <5; ++i)
2645 // skip learning spell and no rank spell case
2646 uint32 rankSpellId = talentInfo->RankID[i];
2647 if(!rankSpellId || rankSpellId==spell_id)
2648 continue;
2650 // skip unknown ranks
2651 if(!HasSpell(rankSpellId))
2652 continue;
2654 removeSpell(rankSpellId);
2658 // non talent spell: learn low ranks (recursive call)
2659 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2661 if(!IsInWorld()) // at spells loading, no output, but allow save
2662 addSpell(prev_spell,active,true,disabled);
2663 else // at normal learning
2664 learnSpell(prev_spell);
2667 PlayerSpell *newspell = new PlayerSpell;
2668 newspell->active = active;
2669 newspell->state = state;
2670 newspell->disabled = disabled;
2672 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2673 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2675 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2677 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2678 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2679 if(!i_spellInfo) continue;
2681 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2683 if(itr->second->active)
2685 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2687 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2689 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2690 data << uint16(itr->first);
2691 data << uint16(spell_id);
2692 GetSession()->SendPacket( &data );
2695 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2696 itr->second->active = false;
2697 itr->second->state = PLAYERSPELL_CHANGED;
2698 superceded_old = true; // new spell replace old in action bars and spell book.
2700 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2702 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2704 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2705 data << uint16(spell_id);
2706 data << uint16(itr->first);
2707 GetSession()->SendPacket( &data );
2710 // mark new spell as disable (not learned yet for client and will not learned)
2711 newspell->active = false;
2712 if(newspell->state != PLAYERSPELL_NEW)
2713 newspell->state = PLAYERSPELL_CHANGED;
2720 m_spells[spell_id] = newspell;
2722 // return false if spell disabled
2723 if (newspell->disabled)
2724 return false;
2727 uint32 talentCost = GetTalentSpellCost(spell_id);
2729 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2730 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2731 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2733 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2734 CastSpell(this, spell_id, true);
2736 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2737 else if (IsPassiveSpell(spell_id))
2739 bool need_cast = false;
2741 switch(spell_id)
2743 // some spells not have stance data expacted cast at form change or present
2744 case 5420: need_cast = (m_form == FORM_TREE); break;
2745 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2746 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2747 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2748 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2749 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2750 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2751 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2752 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2753 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2754 // another spells have proper stance data
2755 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2757 //Check CasterAuraStates
2758 if (need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState))))
2759 CastSpell(this, spell_id, true);
2761 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2763 CastSpell(this, spell_id, true);
2764 return false;
2767 // update used talent points count
2768 m_usedTalentCount += talentCost;
2770 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2771 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2773 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2774 SetFreePrimaryProffesions(freeProfs-1);
2777 // add dependent skills
2778 uint16 maxskill = GetMaxSkillValueForLevel();
2780 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2782 if(spellLearnSkill)
2784 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2785 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2787 if(skill_value < spellLearnSkill->value)
2788 skill_value = spellLearnSkill->value;
2790 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2792 if(skill_max_value < new_skill_max_value)
2793 skill_max_value = new_skill_max_value;
2795 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2797 else
2799 // not ranked skills
2800 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2801 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2803 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2805 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2806 if(!pSkill)
2807 continue;
2809 if(HasSkill(pSkill->id))
2810 continue;
2812 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2813 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2814 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2816 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2818 case SKILL_RANGE_LANGUAGE:
2819 SetSkill(pSkill->id, 300, 300 );
2820 break;
2821 case SKILL_RANGE_LEVEL:
2822 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2823 break;
2824 case SKILL_RANGE_MONO:
2825 SetSkill(pSkill->id, 1, 1 );
2826 break;
2827 default:
2828 break;
2834 // learn dependent spells
2835 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2836 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2838 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2840 if(!itr->second.autoLearned)
2842 if(!IsInWorld() || !itr->second.active) // at spells loading, no output, but allow save
2843 addSpell(itr->second.spell,itr->second.active,true,false);
2844 else // at normal learning
2845 learnSpell(itr->second.spell);
2849 if(IsInWorld())
2851 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2852 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2855 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2856 return active && !disabled && !superceded_old;
2859 void Player::learnSpell(uint32 spell_id)
2861 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2863 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2864 bool active = disabled ? itr->second->active : true;
2866 bool learning = addSpell(spell_id,active,true,false);
2868 // learn all disabled higher ranks (recursive)
2869 if(disabled)
2871 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2872 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2874 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2875 if (iter != m_spells.end() && iter->second->disabled)
2876 learnSpell(i->second);
2880 // prevent duplicated entires in spell book, also not send if not in world (loading)
2881 if(!learning || !IsInWorld ())
2882 return;
2884 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2885 data << uint32(spell_id);
2886 GetSession()->SendPacket(&data);
2889 void Player::removeSpell(uint32 spell_id, bool disabled)
2891 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2892 if (itr == m_spells.end())
2893 return;
2895 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2896 return;
2898 // unlearn non talent higher ranks (recursive)
2899 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2900 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2901 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2902 removeSpell(itr2->second,disabled);
2904 // removing
2905 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2906 data << uint16(spell_id);
2907 GetSession()->SendPacket(&data);
2909 if (disabled)
2911 itr->second->disabled = disabled;
2912 if(itr->second->state != PLAYERSPELL_NEW)
2913 itr->second->state = PLAYERSPELL_CHANGED;
2915 else
2917 if(itr->second->state == PLAYERSPELL_NEW)
2919 delete itr->second;
2920 m_spells.erase(itr);
2922 else
2923 itr->second->state = PLAYERSPELL_REMOVED;
2926 RemoveAurasDueToSpell(spell_id);
2928 // remove pet auras
2929 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2930 RemovePetAura(petSpell);
2932 // free talent points
2933 uint32 talentCosts = GetTalentSpellCost(spell_id);
2934 if(talentCosts > 0)
2936 if(talentCosts < m_usedTalentCount)
2937 m_usedTalentCount -= talentCosts;
2938 else
2939 m_usedTalentCount = 0;
2942 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2943 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2945 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2946 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2947 SetFreePrimaryProffesions(freeProfs);
2950 // remove dependent skill
2951 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2952 if(spellLearnSkill)
2954 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2955 if(!prev_spell) // first rank, remove skill
2956 SetSkill(spellLearnSkill->skill,0,0);
2957 else
2959 // search prev. skill setting by spell ranks chain
2960 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2961 while(!prevSkill && prev_spell)
2963 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2964 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2967 if(!prevSkill) // not found prev skill setting, remove skill
2968 SetSkill(spellLearnSkill->skill,0,0);
2969 else // set to prev. skill setting values
2971 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2972 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2974 if(skill_value > prevSkill->value)
2975 skill_value = prevSkill->value;
2977 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2979 if(skill_max_value > new_skill_max_value)
2980 skill_max_value = new_skill_max_value;
2982 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2987 else
2989 // not ranked skills
2990 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2991 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2993 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2995 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2996 if(!pSkill)
2997 continue;
2999 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3000 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3001 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
3003 // not reset skills for professions and racial abilities
3004 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3005 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3006 continue;
3008 SetSkill(pSkill->id, 0, 0 );
3013 // remove dependent spells
3014 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3015 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3017 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3018 removeSpell(itr2->second.spell, disabled);
3020 // TODO: recast if need lesser ranks spell for passive with IsPassiveSpellStackableWithRanks
3023 void Player::RemoveArenaSpellCooldowns()
3025 // remove cooldowns on spells that has < 15 min CD
3026 SpellCooldowns::iterator itr, next;
3027 // iterate spell cooldowns
3028 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3030 next = itr;
3031 ++next;
3032 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3033 // check if spellentry is present and if the cooldown is less than 15 mins
3034 if( entry &&
3035 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3036 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3038 // notify player
3039 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3040 data << uint32(itr->first);
3041 data << GetGUID();
3042 GetSession()->SendPacket(&data);
3043 // remove cooldown
3044 m_spellCooldowns.erase(itr);
3049 void Player::RemoveAllSpellCooldown()
3051 if(!m_spellCooldowns.empty())
3053 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3055 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3056 data << uint32(itr->first);
3057 data << uint64(GetGUID());
3058 GetSession()->SendPacket(&data);
3060 m_spellCooldowns.clear();
3064 void Player::_LoadSpellCooldowns(QueryResult *result)
3066 m_spellCooldowns.clear();
3068 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3070 if(result)
3072 time_t curTime = time(NULL);
3076 Field *fields = result->Fetch();
3078 uint32 spell_id = fields[0].GetUInt32();
3079 uint32 item_id = fields[1].GetUInt32();
3080 time_t db_time = (time_t)fields[2].GetUInt64();
3082 if(!sSpellStore.LookupEntry(spell_id))
3084 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3085 continue;
3088 // skip outdated cooldown
3089 if(db_time <= curTime)
3090 continue;
3092 AddSpellCooldown(spell_id, item_id, db_time);
3094 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3096 while( result->NextRow() );
3098 delete result;
3102 void Player::_SaveSpellCooldowns()
3104 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3106 time_t curTime = time(NULL);
3108 // remove outdated and save active
3109 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3111 if(itr->second.end <= curTime)
3112 m_spellCooldowns.erase(itr++);
3113 else
3115 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3116 ++itr;
3121 uint32 Player::resetTalentsCost() const
3123 // The first time reset costs 1 gold
3124 if(m_resetTalentsCost < 1*GOLD)
3125 return 1*GOLD;
3126 // then 5 gold
3127 else if(m_resetTalentsCost < 5*GOLD)
3128 return 5*GOLD;
3129 // After that it increases in increments of 5 gold
3130 else if(m_resetTalentsCost < 10*GOLD)
3131 return 10*GOLD;
3132 else
3134 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3135 if(months > 0)
3137 // This cost will be reduced by a rate of 5 gold per month
3138 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3139 // to a minimum of 10 gold.
3140 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3142 else
3144 // After that it increases in increments of 5 gold
3145 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3146 // until it hits a cap of 50 gold.
3147 if(new_cost > 50*GOLD)
3148 new_cost = 50*GOLD;
3149 return new_cost;
3154 bool Player::resetTalents(bool no_cost)
3156 // not need after this call
3157 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3159 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3160 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3163 uint32 talentPointsForLevel = CalculateTalentsPoints();
3165 if (m_usedTalentCount == 0)
3167 SetFreeTalentPoints(talentPointsForLevel);
3168 return false;
3171 uint32 cost = 0;
3173 if(!no_cost)
3175 cost = resetTalentsCost();
3177 if (GetMoney() < cost)
3179 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3180 return false;
3184 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3186 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3188 if (!talentInfo) continue;
3190 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3192 if(!talentTabInfo)
3193 continue;
3195 // unlearn only talents for character class
3196 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3197 // to prevent unexpected lost normal learned spell skip another class talents
3198 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3199 continue;
3201 for (int j = 0; j < 5; j++)
3203 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3205 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3207 ++itr;
3208 continue;
3211 // remove learned spells (all ranks)
3212 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3214 // unlearn if first rank is talent or learned by talent
3215 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3217 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3218 itr = GetSpellMap().begin();
3219 continue;
3221 else
3222 ++itr;
3227 SetFreeTalentPoints(talentPointsForLevel);
3229 if(!no_cost)
3231 ModifyMoney(-(int32)cost);
3233 m_resetTalentsCost = cost;
3234 m_resetTalentsTime = time(NULL);
3237 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3238 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3240 return true;
3243 bool Player::_removeSpell(uint16 spell_id)
3245 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3246 if (itr != m_spells.end())
3248 delete itr->second;
3249 m_spells.erase(itr);
3250 return true;
3252 return false;
3255 Mail* Player::GetMail(uint32 id)
3257 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3259 if ((*itr)->messageID == id)
3261 return (*itr);
3264 return NULL;
3267 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3269 if(target == this)
3271 Object::_SetCreateBits(updateMask, target);
3273 else
3275 for(uint16 index = 0; index < m_valuesCount; index++)
3277 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3278 updateMask->SetBit(index);
3283 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3285 if(target == this)
3287 Object::_SetUpdateBits(updateMask, target);
3289 else
3291 Object::_SetUpdateBits(updateMask, target);
3292 *updateMask &= updateVisualBits;
3296 void Player::InitVisibleBits()
3298 updateVisualBits.SetCount(PLAYER_END);
3300 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3301 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3302 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3303 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3304 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3305 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3306 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3307 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3308 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3309 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3310 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3311 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3312 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3313 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3314 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3315 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3316 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3317 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3318 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3319 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3320 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3321 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3322 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3323 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3324 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3325 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3326 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3327 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3328 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3329 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3330 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3331 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3332 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3333 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3334 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3335 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3336 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3337 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3338 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3339 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3340 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3341 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3342 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3343 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3344 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3345 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3346 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3347 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3348 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3349 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3350 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3351 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3352 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3353 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3354 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3356 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3357 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3358 updateVisualBits.SetBit(PLAYER_FLAGS);
3359 updateVisualBits.SetBit(PLAYER_GUILDID);
3360 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3361 updateVisualBits.SetBit(PLAYER_BYTES);
3362 updateVisualBits.SetBit(PLAYER_BYTES_2);
3363 updateVisualBits.SetBit(PLAYER_BYTES_3);
3364 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3365 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3367 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3368 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3369 updateVisualBits.SetBit(i);
3371 // Players visible items are not inventory stuff
3372 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3374 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3376 // item creator
3377 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3378 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3380 // item entry
3381 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3383 // item enchantments
3384 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3385 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3387 // random properties
3388 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3389 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3390 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3393 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3396 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3398 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3400 if(m_items[i] == NULL)
3401 continue;
3403 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3406 if(target == this)
3408 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3410 if(m_items[i] == NULL)
3411 continue;
3413 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3415 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3417 if(m_items[i] == NULL)
3418 continue;
3420 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3424 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3427 void Player::DestroyForPlayer( Player *target ) const
3429 Unit::DestroyForPlayer( target );
3431 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3433 if(m_items[i] == NULL)
3434 continue;
3436 m_items[i]->DestroyForPlayer( target );
3439 if(target == this)
3441 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3443 if(m_items[i] == NULL)
3444 continue;
3446 m_items[i]->DestroyForPlayer( target );
3448 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3450 if(m_items[i] == NULL)
3451 continue;
3453 m_items[i]->DestroyForPlayer( target );
3458 bool Player::HasSpell(uint32 spell) const
3460 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3461 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3464 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3466 if (!trainer_spell)
3467 return TRAINER_SPELL_RED;
3469 if (!trainer_spell->learned_spell)
3470 return TRAINER_SPELL_RED;
3472 // known spell
3473 if(HasSpell(trainer_spell->learned_spell))
3474 return TRAINER_SPELL_GRAY;
3476 // check race/class requirement
3477 if(!IsSpellFitByClassAndRace(trainer_spell->learned_spell))
3478 return TRAINER_SPELL_RED;
3480 // check level requirement
3481 if(getLevel() < trainer_spell->reqlevel)
3482 return TRAINER_SPELL_RED;
3484 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learned_spell))
3486 // check prev.rank requirement
3487 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3488 return TRAINER_SPELL_RED;
3490 // check additional spell requirement
3491 if(spell_chain->req && !HasSpell(spell_chain->req))
3492 return TRAINER_SPELL_RED;
3495 // check skill requirement
3496 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3497 return TRAINER_SPELL_RED;
3499 // exist, already checked at loading
3500 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learned_spell);
3502 // secondary prof. or not prof. spell
3503 uint32 skill = spell->EffectMiscValue[1];
3505 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3506 return TRAINER_SPELL_GREEN;
3508 // check primary prof. limit
3509 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3510 return TRAINER_SPELL_RED;
3512 return TRAINER_SPELL_GREEN;
3515 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3517 uint32 guid = GUID_LOPART(playerguid);
3519 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3520 // bones will be deleted by corpse/bones deleting thread shortly
3521 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3523 // remove from guild
3524 uint32 guildId = GetGuildIdFromDB(playerguid);
3525 if(guildId != 0)
3527 Guild* guild = objmgr.GetGuildById(guildId);
3528 if(guild)
3529 guild->DelMember(guid);
3532 // remove from arena teams
3533 LeaveAllArenaTeams(playerguid);
3535 // the player was uninvited already on logout so just remove from group
3536 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3537 if(resultGroup)
3539 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3540 delete resultGroup;
3541 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3542 if(group)
3544 RemoveFromGroup(group, playerguid);
3548 // remove signs from petitions (also remove petitions if owner);
3549 RemovePetitionsAndSigns(playerguid, 10);
3551 // return back all mails with COD and Item 0 1 2 3 4 5 6
3552 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3553 if(resultMail)
3557 Field *fields = resultMail->Fetch();
3559 uint32 mail_id = fields[0].GetUInt32();
3560 uint16 mailTemplateId= fields[1].GetUInt16();
3561 uint32 sender = fields[2].GetUInt32();
3562 std::string subject = fields[3].GetCppString();
3563 uint32 itemTextId = fields[4].GetUInt32();
3564 uint32 money = fields[5].GetUInt32();
3565 bool has_items = fields[6].GetBool();
3567 //we can return mail now
3568 //so firstly delete the old one
3569 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3571 MailItemsInfo mi;
3572 if(has_items)
3574 // data needs to be at first place for Item::LoadFromDB
3575 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
3576 if(resultItems)
3580 Field *fields2 = resultItems->Fetch();
3582 uint32 item_guidlow = fields2[1].GetUInt32();
3583 uint32 item_template = fields2[2].GetUInt32();
3585 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3586 if(!itemProto)
3588 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3589 continue;
3592 Item *pItem = NewItemOrBag(itemProto);
3593 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3595 pItem->FSetState(ITEM_REMOVED);
3596 pItem->SaveToDB(); // it also deletes item object !
3597 continue;
3600 mi.AddItem(item_guidlow, item_template, pItem);
3602 while (resultItems->NextRow());
3604 delete resultItems;
3608 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3610 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3612 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3614 while (resultMail->NextRow());
3616 delete resultMail;
3619 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3620 // Get guids of character's pets, will deleted in transaction
3621 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3623 // NOW we can finally clear other DB data related to character
3624 CharacterDatabase.BeginTransaction();
3625 if (resultPets)
3629 Field *fields3 = resultPets->Fetch();
3630 uint32 petguidlow = fields3[0].GetUInt32();
3631 Pet::DeleteFromDB(petguidlow);
3632 } while (resultPets->NextRow());
3633 delete resultPets;
3636 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3637 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3638 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3639 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3640 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3641 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3642 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3643 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3644 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3645 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3646 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3647 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3648 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3649 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3650 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3651 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3652 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3653 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3654 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3655 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3656 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3657 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3658 CharacterDatabase.CommitTransaction();
3660 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3661 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3664 void Player::SetMovement(PlayerMovementType pType)
3666 WorldPacket data;
3667 switch(pType)
3669 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3670 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3671 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3672 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3673 default:
3674 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3675 return;
3677 data.append(GetPackGUID());
3678 data << uint32(0);
3679 GetSession()->SendPacket( &data );
3682 /* Preconditions:
3683 - a resurrectable corpse must not be loaded for the player (only bones)
3684 - the player must be in world
3686 void Player::BuildPlayerRepop()
3688 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3689 data.append(GetPackGUID());
3690 GetSession()->SendPacket(&data);
3692 if(getRace() == RACE_NIGHTELF)
3693 CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
3694 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3696 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3697 // there must be SMSG.STOP_MIRROR_TIMER
3698 // there we must send 888 opcode
3700 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3701 if(GetCorpse())
3703 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3704 assert(false);
3707 // create a corpse and place it at the player's location
3708 CreateCorpse();
3709 Corpse *corpse = GetCorpse();
3710 if(!corpse)
3712 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3713 return;
3715 GetMap()->Add(corpse);
3717 // convert player body to ghost
3718 SetHealth( 1 );
3720 SetMovement(MOVE_WATER_WALK);
3721 if(!GetSession()->isLogingOut())
3722 SetMovement(MOVE_UNROOT);
3724 // BG - remove insignia related
3725 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3727 SendCorpseReclaimDelay();
3729 // to prevent cheating
3730 corpse->ResetGhostTime();
3732 StopMirrorTimers(); //disable timers(bars)
3734 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3736 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3739 void Player::SendDelayResponse(const uint32 ml_seconds)
3741 //FIXME: is this delay time arg really need? 50msec by default in code
3742 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3743 data << (uint32)time(NULL);
3744 data << (uint32)0;
3745 GetSession()->SendPacket( &data );
3748 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3750 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3751 data << uint32(-1);
3752 data << float(0);
3753 data << float(0);
3754 data << float(0);
3755 GetSession()->SendPacket(&data);
3757 // speed change, land walk
3759 // remove death flag + set aura
3760 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3761 if(getRace() == RACE_NIGHTELF)
3762 RemoveAurasDueToSpell(20584); // speed bonuses
3763 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3765 setDeathState(ALIVE);
3767 SetMovement(MOVE_LAND_WALK);
3768 SetMovement(MOVE_UNROOT);
3770 m_deathTimer = 0;
3772 // set health/powers (0- will be set in caller)
3773 if(restore_percent>0.0f)
3775 SetHealth(uint32(GetMaxHealth()*restore_percent));
3776 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3777 SetPower(POWER_RAGE, 0);
3778 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3781 // update visibility
3782 ObjectAccessor::UpdateVisibilityForPlayer(this);
3784 // some items limited to specific map
3785 DestroyZoneLimitedItem( true, GetZoneId());
3787 if(!applySickness)
3788 return;
3790 //Characters from level 1-10 are not affected by resurrection sickness.
3791 //Characters from level 11-19 will suffer from one minute of sickness
3792 //for each level they are above 10.
3793 //Characters level 20 and up suffer from ten minutes of sickness.
3794 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3796 if(int32(getLevel()) >= startLevel)
3798 // set resurrection sickness
3799 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3801 // not full duration
3802 if(int32(getLevel()) < startLevel+9)
3804 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3806 for(int i =0; i < 3; ++i)