[6962] Update sanctuary flag.
[getmangos.git] / src / game / Player.cpp
blob43b83a1202b5b5a7dcd315c637d350025888ba88
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "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 )
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 return true;
224 std::string PlayerTaxi::SaveTaxiDestinationsToString()
226 if(m_TaxiDestinations.empty())
227 return "";
229 std::ostringstream ss;
231 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
232 ss << m_TaxiDestinations[i] << " ";
234 return ss.str();
237 uint32 PlayerTaxi::GetCurrentTaxiPath() const
239 if(m_TaxiDestinations.size() < 2)
240 return 0;
242 uint32 path;
243 uint32 cost;
245 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
247 return path;
250 //== Player ====================================================
252 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
254 UpdateMask Player::updateVisualBits;
256 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
258 m_transport = 0;
260 m_speakTime = 0;
261 m_speakCount = 0;
263 m_objectType |= TYPEMASK_PLAYER;
264 m_objectTypeId = TYPEID_PLAYER;
266 m_valuesCount = PLAYER_END;
268 m_session = session;
270 m_divider = 0;
272 m_ExtraFlags = 0;
273 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
274 SetAcceptTicket(true);
276 // players always accept
277 if(GetSession()->GetSecurity() == SEC_PLAYER)
278 SetAcceptWhispers(true);
280 m_curSelection = 0;
281 m_lootGuid = 0;
283 m_comboTarget = 0;
284 m_comboPoints = 0;
286 m_usedTalentCount = 0;
288 m_regenTimer = 0;
289 m_weaponChangeTimer = 0;
291 m_zoneUpdateId = 0;
292 m_zoneUpdateTimer = 0;
294 m_areaUpdateId = 0;
296 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
298 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
299 // this must help in case next save after mass player load after server startup
300 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
302 clearResurrectRequestData();
304 m_SpellModRemoveCount = 0;
306 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
308 m_social = NULL;
310 // group is initialized in the reference constructor
311 SetGroupInvite(NULL);
312 m_groupUpdateMask = 0;
313 m_auraUpdateMask = 0;
315 duel = NULL;
317 m_GuildIdInvited = 0;
318 m_ArenaTeamIdInvited = 0;
320 m_atLoginFlags = AT_LOGIN_NONE;
322 m_dontMove = false;
324 pTrader = 0;
325 ClearTrade();
327 m_cinematic = 0;
329 PlayerTalkClass = new PlayerMenu( GetSession() );
330 m_currentBuybackSlot = BUYBACK_SLOT_START;
332 for ( int aX = 0 ; aX < 8 ; aX++ )
333 m_Tutorials[ aX ] = 0x00;
334 m_TutorialsChanged = false;
336 m_DailyQuestChanged = false;
337 m_lastDailyQuestTime = 0;
339 m_regenTimer = 0;
340 m_weaponChangeTimer = 0;
341 m_breathTimer = 0;
342 m_isunderwater = 0;
343 m_isInWater = false;
344 m_drunkTimer = 0;
345 m_drunk = 0;
346 m_restTime = 0;
347 m_deathTimer = 0;
348 m_deathExpireTime = 0;
350 m_swingErrorMsg = 0;
352 m_DetectInvTimer = 1000;
354 m_bgBattleGroundID = 0;
355 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
357 m_bgBattleGroundQueueID[j].bgQueueType = 0;
358 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
360 m_bgTeam = 0;
362 m_logintime = time(NULL);
363 m_Last_tick = m_logintime;
364 m_WeaponProficiency = 0;
365 m_ArmorProficiency = 0;
366 m_canParry = false;
367 m_canBlock = false;
368 m_canDualWield = false;
369 m_canTitanGrip = false;
370 m_ammoDPS = 0.0f;
372 m_temporaryUnsummonedPetNumber = 0;
373 //cache for UNIT_CREATED_BY_SPELL to allow
374 //returning reagents for temporarily removed pets
375 //when dying/logging out
376 m_oldpetspell = 0;
378 ////////////////////Rest System/////////////////////
379 time_inn_enter=0;
380 inn_pos_mapid=0;
381 inn_pos_x=0;
382 inn_pos_y=0;
383 inn_pos_z=0;
384 m_rest_bonus=0;
385 rest_type=REST_TYPE_NO;
386 ////////////////////Rest System/////////////////////
388 m_mailsLoaded = false;
389 m_mailsUpdated = false;
390 unReadMails = 0;
391 m_nextMailDelivereTime = 0;
393 m_resetTalentsCost = 0;
394 m_resetTalentsTime = 0;
395 m_itemUpdateQueueBlocked = false;
397 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
398 m_forced_speed_changes[i] = 0;
400 m_stableSlots = 0;
402 /////////////////// Instance System /////////////////////
404 m_HomebindTimer = 0;
405 m_InstanceValid = true;
406 m_dungeonDifficulty = DIFFICULTY_NORMAL;
408 for (int i = 0; i < BASEMOD_END; i++)
410 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
411 m_auraBaseMod[i][PCT_MOD] = 1.0f;
414 for (int i = 0; i < MAX_COMBAT_RATING; i++)
415 m_baseRatingValue[i] = 0;
417 // Honor System
418 m_lastHonorUpdateTime = time(NULL);
420 // Player summoning
421 m_summon_expire = 0;
422 m_summon_mapid = 0;
423 m_summon_x = 0.0f;
424 m_summon_y = 0.0f;
425 m_summon_z = 0.0f;
427 //Default movement to run mode
428 m_unit_movement_flags = 0;
430 m_mover = NULL;
432 m_miniPet = 0;
433 m_bgAfkReportedTimer = 0;
434 m_contestedPvPTimer = 0;
436 m_declinedname = NULL;
437 m_runes = NULL;
440 Player::~Player ()
442 CleanupsBeforeDelete();
444 // it must be unloaded already in PlayerLogout and accessed only for loggined player
445 //m_social = NULL;
447 // Note: buy back item already deleted from DB when player was saved
448 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
450 if(m_items[i])
451 delete m_items[i];
453 CleanupChannels();
455 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
456 delete itr->second;
458 //all mailed items should be deleted, also all mail should be deallocated
459 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
460 delete *itr;
462 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
463 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
465 delete PlayerTalkClass;
467 if (m_transport)
469 m_transport->RemovePassenger(this);
472 for(size_t x = 0; x < ItemSetEff.size(); x++)
473 if(ItemSetEff[x])
474 delete ItemSetEff[x];
476 // clean up player-instance binds, may unload some instance saves
477 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
478 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
479 itr->second.save->RemovePlayer(this);
481 delete m_declinedname;
482 delete m_runes;
485 void Player::CleanupsBeforeDelete()
487 if(m_uint32Values) // only for fully created Object
489 TradeCancel(false);
490 DuelComplete(DUEL_INTERUPTED);
492 Unit::CleanupsBeforeDelete();
495 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 )
497 //FIXME: outfitId not used in player creating
499 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
501 m_name = name;
503 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
504 if(!info)
506 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
507 return false;
510 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
511 m_items[i] = NULL;
513 m_race = race;
514 m_class = class_;
516 SetMapId(info->mapId);
517 Relocate(info->positionX,info->positionY,info->positionZ);
519 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
520 if(!cEntry)
522 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
523 return false;
526 uint8 powertype = cEntry->powerType;
528 //uint32 unitfield;
530 /*switch(powertype)
532 case POWER_ENERGY:
533 case POWER_MANA:
534 unitfield = 0x00000000;
535 break;
536 case POWER_RAGE:
537 unitfield = 0x00110000;
538 break;
539 case POWER_RUNIC_POWER:
540 unitfield = 0x0000EE00; //TODO: find correct unitfield here
541 break;
542 default:
543 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
544 return false;
547 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
548 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
550 switch(gender)
552 case GENDER_FEMALE:
553 SetDisplayId(info->displayId_f );
554 SetNativeDisplayId(info->displayId_f );
555 break;
556 case GENDER_MALE:
557 SetDisplayId(info->displayId_m );
558 SetNativeDisplayId(info->displayId_m );
559 break;
560 default:
561 sLog.outError("Invalid gender %u for player",gender);
562 return false;
563 break;
566 setFactionForRace(m_race);
568 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
570 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
571 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
572 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
573 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
574 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
575 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
576 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
578 // -1 is default value
579 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
581 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
582 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
583 SetByteValue(PLAYER_BYTES_3, 0, gender);
585 SetUInt32Value( PLAYER_GUILDID, 0 );
586 SetUInt32Value( PLAYER_GUILDRANK, 0 );
587 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
589 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
590 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
591 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
592 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
593 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
594 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
595 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
597 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
599 GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i);
600 if(gs && gs->Order)
601 SetGlyphSlot(gs->Order - 1, gs->Id);
604 // set starting level
605 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
606 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
607 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
609 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
611 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
612 if(gm_level > start_level)
613 start_level = gm_level;
616 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
618 InitRunes();
620 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
621 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
622 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
624 // Played time
625 m_Last_tick = time(NULL);
626 m_Played_time[0] = 0;
627 m_Played_time[1] = 0;
629 // base stats and related field values
630 InitStatsForLevel();
631 InitTaxiNodesForLevel();
632 InitGlyphsForLevel();
633 InitTalentForLevel();
634 InitPrimaryProffesions(); // to max set before any spell added
636 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
637 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
638 SetHealth(GetMaxHealth());
639 if (getPowerType()==POWER_MANA)
641 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
642 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
645 if(getPowerType() == POWER_RUNIC_POWER)
647 SetPower(POWER_RUNE, 8);
648 SetMaxPower(POWER_RUNE, 8);
649 SetPower(POWER_RUNIC_POWER, 0);
650 SetMaxPower(POWER_RUNIC_POWER, 1000);
653 // original spells
654 learnDefaultSpells(true);
656 // original action bar
657 std::list<uint16>::const_iterator action_itr[4];
658 for(int i=0; i<4; i++)
659 action_itr[i] = info->action[i].begin();
661 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
663 uint16 taction[4];
664 for(int i=0; i<4 ;i++)
665 taction[i] = (*action_itr[i]);
667 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
669 for(int i=0; i<4 ;i++)
670 ++action_itr[i];
673 // original items
674 CharStartOutfitEntry const* oEntry = NULL;
675 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
677 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
679 if(entry->RaceClassGender == RaceClassGender)
681 oEntry = entry;
682 break;
687 if(oEntry)
689 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
691 if(oEntry->ItemId[j] <= 0)
692 continue;
694 uint32 item_id = oEntry->ItemId[j];
697 // Hack for not existed item id in dbc 3.0.3
698 if(item_id==40582)
699 continue;
701 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
702 if(!iProto)
704 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
705 continue;
708 uint32 count = iProto->Stackable; // max stack by default (mostly 1)
709 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
711 switch(iProto->Spells[0].SpellCategory)
713 case 11: // food
714 if(iProto->Stackable > 4)
715 count = 4;
716 break;
717 case 59: // drink
718 if(iProto->Stackable > 2)
719 count = 2;
720 break;
724 StoreNewItemInBestSlots(item_id, count);
728 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
729 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
731 // bags and main-hand weapon must equipped at this moment
732 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
733 // or ammo not equipped in special bag
734 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
736 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
738 uint16 eDest;
739 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
740 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
741 if( msg == EQUIP_ERR_OK )
743 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
744 EquipItem( eDest, pItem, true);
746 // move other items to more appropriate slots (ammo not equipped in special bag)
747 else
749 ItemPosCountVec sDest;
750 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
751 if( msg == EQUIP_ERR_OK )
753 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
754 pItem = StoreItem( sDest, pItem, true);
757 // if this is ammo then use it
758 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
759 if( msg == EQUIP_ERR_OK )
760 SetAmmo( pItem->GetProto()->ItemId );
764 // all item positions resolved
766 return true;
769 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
771 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
773 // attempt equip by one
774 while(titem_amount > 0)
776 uint16 eDest;
777 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
778 if( msg != EQUIP_ERR_OK )
779 break;
781 EquipNewItem( eDest, titem_id, true);
782 AutoUnequipOffhandIfNeed();
783 --titem_amount;
786 if(titem_amount == 0)
787 return true; // equipped
789 // attempt store
790 ItemPosCountVec sDest;
791 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
792 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
793 if( msg == EQUIP_ERR_OK )
795 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
796 return true; // stored
799 // item can't be added
800 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
801 return false;
804 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
806 uint32 BreathRegen = (uint32)-1;
808 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
809 data << (uint32)Type;
810 data << MaxValue;
811 data << MaxValue;
812 data << BreathRegen;
813 data << (uint8)0;
814 data << (uint32)0; // spell id
815 GetSession()->SendPacket(&data);
818 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
820 if(Type==BREATH_TIMER)
821 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
823 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
824 data << (uint32)Type;
825 data << CurrentValue;
826 data << MaxValue;
827 data << Regen;
828 data << (uint8)0;
829 data << (uint32)0; // spell id
830 GetSession()->SendPacket( &data );
833 void Player::StopMirrorTimer(MirrorTimerType Type)
835 if(Type==BREATH_TIMER)
836 m_breathTimer = 0;
838 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
839 data << (uint32)Type;
840 GetSession()->SendPacket( &data );
843 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
845 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
846 data << (uint64)guid;
847 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
848 data << (uint32)damage;
849 data << (uint32)0;
850 data << (uint32)0;
851 SendMessageToSet(&data, true);
853 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
855 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
857 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
858 DurabilityLossAll(0.10f,false);
859 // durability lost message
860 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
861 GetSession()->SendPacket(&data);
865 void Player::HandleDrowning()
867 if(!m_isunderwater)
868 return;
870 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
871 if(waterbreath || isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
873 StopMirrorTimer(BREATH_TIMER);
874 m_isunderwater = 0;
875 return;
878 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
880 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
881 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
882 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
884 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
886 //single trigger timer
887 if (!(m_isunderwater & 0x02))
889 m_isunderwater|= 0x02;
890 m_breathTimer = UnderWaterTime + 1000;
892 //single trigger "Breathbar"
893 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
895 m_isunderwater|= 0x04;
896 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
898 //continuous trigger drowning "Damage"
899 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
901 //TODO: Check this formula
902 uint64 guid = GetGUID();
903 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
905 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
906 m_breathTimer = 2000;
909 //single trigger retract bar
910 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
912 m_isunderwater = 0x08;
914 uint32 BreathRegen = 10;
915 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
916 m_isunderwater = 0x10;
918 //remove bar
919 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
921 StopMirrorTimer(BREATH_TIMER);
922 m_isunderwater = 0;
926 void Player::HandleLava()
928 if ((m_isunderwater & 0x80) && isAlive())
930 // Single trigger Set BreathTimer
931 if (!(m_isunderwater & 0x80))
933 m_isunderwater|= 0x04;
934 m_breathTimer = 1000;
937 // Reset BreathTimer and still in the lava
938 if (!m_breathTimer)
940 uint64 guid = GetGUID();
941 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
943 // if not gamemaster then deal damage
944 if ( !isGameMaster() )
945 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
947 m_breathTimer = 1000;
950 else if (m_deathState == DEAD) // Disable breath timer and reset underwater flags
952 m_breathTimer = 0;
953 m_isunderwater = 0;
957 ///The player sobers by 256 every 10 seconds
958 void Player::HandleSobering()
960 m_drunkTimer = 0;
962 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
963 SetDrunkValue(drunk);
966 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
968 if(value >= 23000)
969 return DRUNKEN_SMASHED;
970 if(value >= 12800)
971 return DRUNKEN_DRUNK;
972 if(value & 0xFFFE)
973 return DRUNKEN_TIPSY;
974 return DRUNKEN_SOBER;
977 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
979 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
981 m_drunk = newDrunkenValue;
982 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
984 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
986 // special drunk invisibility detection
987 if(newDrunkenState >= DRUNKEN_DRUNK)
988 m_detectInvisibilityMask |= (1<<6);
989 else
990 m_detectInvisibilityMask &= ~(1<<6);
992 if(newDrunkenState == oldDrunkenState)
993 return;
995 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
996 data << uint64(GetGUID());
997 data << uint32(newDrunkenState);
998 data << uint32(itemId);
1000 SendMessageToSet(&data, true);
1003 void Player::Update( uint32 p_time )
1005 if(!IsInWorld())
1006 return;
1008 // undelivered mail
1009 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1011 SendNewMail();
1012 ++unReadMails;
1014 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1015 m_nextMailDelivereTime = 0;
1018 Unit::Update( p_time );
1020 // update player only attacks
1021 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1023 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1026 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1028 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1031 time_t now = time (NULL);
1033 UpdatePvPFlag(now);
1035 UpdateContestedPvP(p_time);
1037 UpdateDuelFlag(now);
1039 CheckDuelDistance(now);
1041 UpdateAfkReport(now);
1043 CheckExploreSystem();
1045 // Update items that have just a limited lifetime
1046 if (now>m_Last_tick)
1047 UpdateItemDuration(uint32(now- m_Last_tick));
1049 if (!m_timedquests.empty())
1051 std::set<uint32>::iterator iter = m_timedquests.begin();
1052 while (iter != m_timedquests.end())
1054 QuestStatusData& q_status = mQuestStatus[*iter];
1055 if( q_status.m_timer <= p_time )
1057 uint32 quest_id = *iter;
1058 ++iter; // current iter will be removed in FailTimedQuest
1059 FailTimedQuest( quest_id );
1061 else
1063 q_status.m_timer -= p_time;
1064 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1065 ++iter;
1070 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1072 Unit *pVictim = getVictim();
1073 if( !IsNonMeleeSpellCasted(false) && pVictim)
1075 // default combat reach 10
1076 // TODO add weapon,skill check
1078 float pldistance = ATTACK_DISTANCE;
1080 if (isAttackReady(BASE_ATTACK))
1082 if(!IsWithinDistInMap(pVictim, pldistance))
1084 setAttackTimer(BASE_ATTACK,100);
1085 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1087 SendAttackSwingNotInRange();
1088 m_swingErrorMsg = 1;
1091 //120 degrees of radiant range
1092 else if( !HasInArc( 2*M_PI/3, pVictim ))
1094 setAttackTimer(BASE_ATTACK,100);
1095 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1097 SendAttackSwingBadFacingAttack();
1098 m_swingErrorMsg = 2;
1101 else
1103 m_swingErrorMsg = 0; // reset swing error state
1105 // prevent base and off attack in same time, delay attack at 0.2 sec
1106 if(haveOffhandWeapon())
1108 uint32 off_att = getAttackTimer(OFF_ATTACK);
1109 if(off_att < ATTACK_DISPLAY_DELAY)
1110 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1112 AttackerStateUpdate(pVictim, BASE_ATTACK);
1113 resetAttackTimer(BASE_ATTACK);
1117 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1119 if(!IsWithinDistInMap(pVictim, pldistance))
1121 setAttackTimer(OFF_ATTACK,100);
1123 else if( !HasInArc( 2*M_PI/3, pVictim ))
1125 setAttackTimer(OFF_ATTACK,100);
1127 else
1129 // prevent base and off attack in same time, delay attack at 0.2 sec
1130 uint32 base_att = getAttackTimer(BASE_ATTACK);
1131 if(base_att < ATTACK_DISPLAY_DELAY)
1132 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1133 // do attack
1134 AttackerStateUpdate(pVictim, OFF_ATTACK);
1135 resetAttackTimer(OFF_ATTACK);
1139 Unit *owner = pVictim->GetOwner();
1140 Unit *u = owner ? owner : pVictim;
1141 if(u->IsPvP() && (!duel || duel->opponent != u))
1143 UpdatePvP(true);
1144 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1149 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1151 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1153 int time_inn = time(NULL)-GetTimeInnEnter();
1154 if (time_inn >= 10) //freeze update
1156 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1157 //speed collect rest bonus (section/in hour)
1158 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1159 UpdateInnerTime(time(NULL));
1164 if(m_regenTimer > 0)
1166 if(p_time >= m_regenTimer)
1167 m_regenTimer = 0;
1168 else
1169 m_regenTimer -= p_time;
1172 if (m_weaponChangeTimer > 0)
1174 if(p_time >= m_weaponChangeTimer)
1175 m_weaponChangeTimer = 0;
1176 else
1177 m_weaponChangeTimer -= p_time;
1180 if (m_zoneUpdateTimer > 0)
1182 if(p_time >= m_zoneUpdateTimer)
1184 uint32 newzone = GetZoneId();
1185 if( m_zoneUpdateId != newzone )
1186 UpdateZone(newzone); // also update area
1187 else
1189 // use area updates as well
1190 // needed for free far all arenas for example
1191 uint32 newarea = GetAreaId();
1192 if( m_areaUpdateId != newarea )
1193 UpdateArea(newarea);
1195 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1198 else
1199 m_zoneUpdateTimer -= p_time;
1202 if (isAlive())
1204 RegenerateAll();
1207 if (m_deathState == JUST_DIED)
1209 KillPlayer();
1212 if(m_nextSave > 0)
1214 if(p_time >= m_nextSave)
1216 // m_nextSave reseted in SaveToDB call
1217 SaveToDB();
1218 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1220 else
1222 m_nextSave -= p_time;
1226 //Breathtimer
1227 if(m_breathTimer > 0)
1229 if(p_time >= m_breathTimer)
1230 m_breathTimer = 0;
1231 else
1232 m_breathTimer -= p_time;
1236 //Handle Water/drowning
1237 HandleDrowning();
1239 //Handle lava
1240 HandleLava();
1242 //Handle detect stealth players
1243 if (m_DetectInvTimer > 0)
1245 if (p_time >= m_DetectInvTimer)
1247 m_DetectInvTimer = 3000;
1248 HandleStealthedUnitsDetection();
1250 else
1251 m_DetectInvTimer -= p_time;
1254 // Played time
1255 if (now > m_Last_tick)
1257 uint32 elapsed = uint32(now - m_Last_tick);
1258 m_Played_time[0] += elapsed; // Total played time
1259 m_Played_time[1] += elapsed; // Level played time
1260 m_Last_tick = now;
1263 if (m_drunk)
1265 m_drunkTimer += p_time;
1267 if (m_drunkTimer > 10000)
1268 HandleSobering();
1271 // not auto-free ghost from body in instances
1272 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1274 if(p_time >= m_deathTimer)
1276 m_deathTimer = 0;
1277 BuildPlayerRepop();
1278 RepopAtGraveyard();
1280 else
1281 m_deathTimer -= p_time;
1284 UpdateEnchantTime(p_time);
1285 UpdateHomebindTime(p_time);
1287 // group update
1288 SendUpdateToOutOfRangeGroupMembers();
1290 Pet* pet = GetPet();
1291 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1293 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1294 return;
1298 void Player::setDeathState(DeathState s)
1300 uint32 ressSpellId = 0;
1302 bool cur = isAlive();
1304 if(s == JUST_DIED && cur)
1306 // drunken state is cleared on death
1307 SetDrunkValue(0);
1308 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1309 ClearComboPoints();
1311 clearResurrectRequestData();
1313 // remove form before other mods to prevent incorrect stats calculation
1314 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1316 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1317 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1319 // remove uncontrolled pets
1320 RemoveMiniPet();
1321 RemoveGuardians();
1323 // save value before aura remove in Unit::setDeathState
1324 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1326 // passive spell
1327 if(!ressSpellId)
1328 ressSpellId = GetResurrectionSpellId();
1329 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1331 Unit::setDeathState(s);
1333 // restore resurrection spell id for player after aura remove
1334 if(s == JUST_DIED && cur && ressSpellId)
1335 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1337 if(isAlive() && !cur)
1339 //clear aura case after resurrection by another way (spells will be applied before next death)
1340 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1342 // restore default warrior stance
1343 if(getClass()== CLASS_WARRIOR)
1344 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1348 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1350 Field *fields = result->Fetch();
1352 *p_data << uint64(GetGUID());
1353 *p_data << m_name;
1355 *p_data << uint8(getRace());
1356 uint8 pClass = getClass();
1357 *p_data << uint8(pClass);
1358 *p_data << uint8(getGender());
1360 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1361 *p_data << uint8(bytes);
1362 *p_data << uint8(bytes >> 8);
1363 *p_data << uint8(bytes >> 16);
1364 *p_data << uint8(bytes >> 24);
1366 bytes = GetUInt32Value(PLAYER_BYTES_2);
1367 *p_data << uint8(bytes);
1369 *p_data << uint8(getLevel()); // player level
1370 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1371 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1372 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1373 *p_data << uint32(zoneId);
1374 *p_data << uint32(GetMapId());
1376 *p_data << GetPositionX();
1377 *p_data << GetPositionY();
1378 *p_data << GetPositionZ();
1380 // guild id
1381 *p_data << (result ? fields[13].GetUInt32() : 0);
1383 uint32 char_flags = 0;
1384 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1385 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1386 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1387 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1388 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1389 char_flags |= CHARACTER_FLAG_GHOST;
1390 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1391 char_flags |= CHARACTER_FLAG_RENAME;
1392 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1393 char_flags |= CHARACTER_FLAG_DECLINED;
1395 *p_data << uint32(char_flags); // character flags
1396 // character customize (flags?)
1397 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1398 *p_data << uint8(1); // unknown
1400 // Pets info
1402 uint32 petDisplayId = 0;
1403 uint32 petLevel = 0;
1404 uint32 petFamily = 0;
1406 // show pet at selection character in character list only for non-ghost character
1407 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1409 uint32 entry = fields[10].GetUInt32();
1410 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1411 if(cInfo)
1413 petDisplayId = fields[11].GetUInt32();
1414 petLevel = fields[12].GetUInt32();
1415 petFamily = cInfo->family;
1419 *p_data << uint32(petDisplayId);
1420 *p_data << uint32(petLevel);
1421 *p_data << uint32(petFamily);
1424 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1426 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1427 uint32 item_id = GetUInt32Value(visualbase);
1428 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1429 SpellItemEnchantmentEntry const *enchant = NULL;
1431 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1433 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1434 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1435 break;
1438 if (proto != NULL)
1440 *p_data << uint32(proto->DisplayInfoID);
1441 *p_data << uint8(proto->InventoryType);
1442 *p_data << uint32(enchant ? enchant->aura_id : 0);
1444 else
1446 *p_data << uint32(0);
1447 *p_data << uint8(0);
1448 *p_data << uint32(0); // enchant?
1451 *p_data << uint32(0); // first bag display id
1452 *p_data << uint8(0); // first bag inventory type
1453 *p_data << uint32(0); // enchant?
1456 bool Player::ToggleAFK()
1458 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1460 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1462 // afk player not allowed in battleground
1463 if(state && InBattleGround())
1464 LeaveBattleground();
1466 return state;
1469 bool Player::ToggleDND()
1471 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1473 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1476 uint8 Player::chatTag() const
1478 // it's bitmask
1479 // 0x8 - ??
1480 // 0x4 - gm
1481 // 0x2 - dnd
1482 // 0x1 - afk
1483 if(isGMChat())
1484 return 4;
1485 else if(isDND())
1486 return 3;
1487 if(isAFK())
1488 return 1;
1489 else
1490 return 0;
1493 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1495 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1497 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1498 return false;
1501 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1502 Pet* pet = GetPet();
1504 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1506 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1507 // don't let gm level > 1 either
1508 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1509 return false;
1511 // client without expansion support
1512 if(GetSession()->Expansion() < mEntry->Expansion())
1514 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1516 if(GetTransport())
1517 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1519 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1521 return false; // normal client can't teleport to this map...
1523 else
1525 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1528 // if we were on a transport, leave
1529 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1531 m_transport->RemovePassenger(this);
1532 m_transport = NULL;
1533 m_movementInfo.t_x = 0.0f;
1534 m_movementInfo.t_y = 0.0f;
1535 m_movementInfo.t_z = 0.0f;
1536 m_movementInfo.t_o = 0.0f;
1537 m_movementInfo.t_time = 0;
1540 SetSemaphoreTeleport(true);
1542 // The player was ported to another map and looses the duel immediately.
1543 // We have to perform this check before the teleport, otherwise the
1544 // ObjectAccessor won't find the flag.
1545 if (duel && GetMapId()!=mapid)
1547 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1548 if (obj)
1549 DuelComplete(DUEL_FLED);
1552 // reset movement flags at teleport, because player will continue move with these flags after teleport
1553 SetUnitMovementFlags(0);
1555 if ((GetMapId() == mapid) && (!m_transport))
1557 // prepare zone change detect
1558 uint32 old_zone = GetZoneId();
1560 // near teleport
1561 if(!GetSession()->PlayerLogout())
1563 WorldPacket data;
1564 BuildTeleportAckMsg(&data, x, y, z, orientation);
1565 GetSession()->SendPacket(&data);
1566 SetPosition( x, y, z, orientation, true);
1568 else
1569 // this will be used instead of the current location in SaveToDB
1570 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1571 SetFallInformation(0, z);
1573 //BuildHeartBeatMsg(&data);
1574 //SendMessageToSet(&data, true);
1575 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1577 //same map, only remove pet if out of range
1578 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1580 if(pet->isControlled() && !pet->isTemporarySummoned() )
1581 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1582 else
1583 m_temporaryUnsummonedPetNumber = 0;
1585 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1589 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1590 CombatStop();
1592 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1594 // resummon pet
1595 if(pet && m_temporaryUnsummonedPetNumber)
1597 Pet* NewPet = new Pet;
1598 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1599 delete NewPet;
1601 m_temporaryUnsummonedPetNumber = 0;
1605 if(!GetSession()->PlayerLogout())
1607 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1608 SetSemaphoreTeleport(false);
1610 UpdateZone(GetZoneId());
1613 // new zone
1614 if(old_zone != GetZoneId())
1616 // honorless target
1617 if(pvpInfo.inHostileArea)
1618 CastSpell(this, 2479, true);
1621 else
1623 // far teleport to another map
1624 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1625 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1627 // Check enter rights before map getting to avoid creating instance copy for player
1628 // this check not dependent from map instance copy and same for all instance copies of selected map
1629 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1631 SetSemaphoreTeleport(false);
1632 return false;
1635 // If the map is not created, assume it is possible to enter it.
1636 // It will be created in the WorldPortAck.
1637 Map *map = MapManager::Instance().FindMap(mapid);
1638 if (!map || map->CanEnter(this))
1640 SetSelection(0);
1642 CombatStop();
1644 ResetContestedPvP();
1646 // remove player from battleground on far teleport (when changing maps)
1647 if(BattleGround const* bg = GetBattleGround())
1649 // Note: at battleground join battleground id set before teleport
1650 // and we already will found "current" battleground
1651 // just need check that this is targeted map or leave
1652 if(bg->GetMapId() != mapid)
1653 LeaveBattleground(false); // don't teleport to entry point
1656 // remove pet on map change
1657 if (pet)
1659 //leaving map -> delete pet right away (doing this later will cause problems)
1660 if(pet->isControlled() && !pet->isTemporarySummoned())
1661 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1662 else
1663 m_temporaryUnsummonedPetNumber = 0;
1665 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1668 // remove all dyn objects
1669 RemoveAllDynObjects();
1671 // stop spellcasting
1672 // not attempt interrupt teleportation spell at caster teleport
1673 if(!(options & TELE_TO_SPELL))
1674 if(IsNonMeleeSpellCasted(true))
1675 InterruptNonMeleeSpells(true);
1677 if(!GetSession()->PlayerLogout())
1679 // send transfer packets
1680 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1681 data << uint32(mapid);
1682 if (m_transport)
1684 data << m_transport->GetEntry() << GetMapId();
1686 GetSession()->SendPacket(&data);
1688 data.Initialize(SMSG_NEW_WORLD, (20));
1689 if (m_transport)
1691 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1693 else
1695 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1697 GetSession()->SendPacket( &data );
1698 SendSavedInstances();
1700 // remove from old map now
1701 if(oldmap) oldmap->Remove(this, false);
1704 // new final coordinates
1705 float final_x = x;
1706 float final_y = y;
1707 float final_z = z;
1708 float final_o = orientation;
1710 if(m_transport)
1712 final_x += m_movementInfo.t_x;
1713 final_y += m_movementInfo.t_y;
1714 final_z += m_movementInfo.t_z;
1715 final_o += m_movementInfo.t_o;
1718 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1719 SetFallInformation(0, final_z);
1720 // if the player is saved before worldportack (at logout for example)
1721 // this will be used instead of the current location in SaveToDB
1723 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1725 // move packet sent by client always after far teleport
1726 // SetPosition(final_x, final_y, final_z, final_o, true);
1727 SetDontMove(true);
1729 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1731 else
1732 return false;
1734 return true;
1737 void Player::AddToWorld()
1739 ///- Do not add/remove the player from the object storage
1740 ///- It will crash when updating the ObjectAccessor
1741 ///- The player should only be added when logging in
1742 Unit::AddToWorld();
1744 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1746 if(m_items[i])
1747 m_items[i]->AddToWorld();
1751 void Player::RemoveFromWorld()
1753 // cleanup
1754 if(IsInWorld())
1756 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1757 Uncharm();
1758 UnsummonAllTotems();
1759 RemoveMiniPet();
1760 RemoveGuardians();
1763 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1765 if(m_items[i])
1766 m_items[i]->RemoveFromWorld();
1769 ///- Do not add/remove the player from the object storage
1770 ///- It will crash when updating the ObjectAccessor
1771 ///- The player should only be removed when logging out
1772 Unit::RemoveFromWorld();
1775 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1777 float addRage;
1779 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1781 if(attacker)
1783 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1785 // talent who gave more rage on attack
1786 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1788 else
1790 addRage = damage/rageconversion*2.5;
1792 // Berserker Rage effect
1793 if(HasAura(18499,0))
1794 addRage *= 1.3;
1797 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1799 ModifyPower(POWER_RAGE, uint32(addRage*10));
1802 void Player::RegenerateAll()
1804 if (m_regenTimer != 0)
1805 return;
1806 uint32 regenDelay = 2000;
1808 // Not in combat or they have regeneration
1809 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1810 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1812 RegenerateHealth();
1813 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1815 Regenerate(POWER_RAGE);
1816 if(getClass() == CLASS_DEATH_KNIGHT)
1817 Regenerate(POWER_RUNIC_POWER);
1821 Regenerate( POWER_ENERGY );
1823 Regenerate( POWER_MANA );
1825 if(getClass() == CLASS_DEATH_KNIGHT)
1826 Regenerate( POWER_RUNE );
1828 m_regenTimer = regenDelay;
1831 void Player::Regenerate(Powers power)
1833 uint32 curValue = GetPower(power);
1834 uint32 maxValue = GetMaxPower(power);
1836 float addvalue = 0.0f;
1838 switch (power)
1840 case POWER_MANA:
1842 bool recentCast = IsUnderLastManaUseEffect();
1843 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1844 if (recentCast)
1846 // Mangos Updates Mana in intervals of 2s, which is correct
1847 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1849 else
1851 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1853 } break;
1854 case POWER_RAGE: // Regenerate rage
1856 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1857 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1858 } break;
1859 case POWER_ENERGY: // Regenerate energy (rogue)
1860 addvalue = 20;
1861 break;
1862 case POWER_RUNIC_POWER:
1864 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1865 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1866 } break;
1867 case POWER_RUNE:
1869 for(uint32 i = 0; i < MAX_RUNES; ++i)
1870 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1871 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1872 } break;
1873 case POWER_FOCUS:
1874 case POWER_HAPPINESS:
1875 break;
1878 // Mana regen calculated in Player::UpdateManaRegen()
1879 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1880 if(power != POWER_MANA)
1882 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1883 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1884 if ((*i)->GetModifier()->m_miscvalue == power)
1885 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1888 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1890 curValue += uint32(addvalue);
1891 if (curValue > maxValue)
1892 curValue = maxValue;
1894 else
1896 if(curValue <= uint32(addvalue))
1897 curValue = 0;
1898 else
1899 curValue -= uint32(addvalue);
1901 SetPower(power, curValue);
1904 void Player::RegenerateHealth()
1906 uint32 curValue = GetHealth();
1907 uint32 maxValue = GetMaxHealth();
1909 if (curValue >= maxValue) return;
1911 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1913 float addvalue = 0.0f;
1915 // polymorphed case
1916 if ( IsPolymorphed() )
1917 addvalue = GetMaxHealth()/3;
1918 // normal regen case (maybe partly in combat case)
1919 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1921 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1922 if (!isInCombat())
1924 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1925 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1926 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1928 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1929 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1931 if(!IsStandState())
1932 addvalue *= 1.5;
1935 // always regeneration bonus (including combat)
1936 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1938 if(addvalue < 0)
1939 addvalue = 0;
1941 ModifyHealth(int32(addvalue));
1944 bool Player::CanInteractWithNPCs(bool alive) const
1946 if(alive && !isAlive())
1947 return false;
1948 if(isInFlight())
1949 return false;
1951 return true;
1954 bool Player::IsUnderWater() const
1956 return IsInWater() &&
1957 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1960 void Player::SetInWater(bool apply)
1962 if(m_isInWater==apply)
1963 return;
1965 //define player in water by opcodes
1966 //move player's guid into HateOfflineList of those mobs
1967 //which can't swim and move guid back into ThreatList when
1968 //on surface.
1969 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1970 m_isInWater = apply;
1972 // remove auras that need water/land
1973 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1975 getHostilRefManager().updateThreatTables();
1978 void Player::SetGameMaster(bool on)
1980 if(on)
1982 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1983 setFaction(35);
1984 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1986 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1987 ResetContestedPvP();
1989 getHostilRefManager().setOnlineOfflineState(false);
1990 CombatStop();
1992 else
1994 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1995 setFactionForRace(getRace());
1996 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1998 // restore FFA PvP Server state
1999 if(sWorld.IsFFAPvPRealm())
2000 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
2002 // restore FFA PvP area state, remove not allowed for GM mounts
2003 UpdateArea(m_areaUpdateId);
2005 getHostilRefManager().setOnlineOfflineState(true);
2008 ObjectAccessor::UpdateVisibilityForPlayer(this);
2011 void Player::SetGMVisible(bool on)
2013 if(on)
2015 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2017 // Reapply stealth/invisibility if active or show if not any
2018 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2019 SetVisibility(VISIBILITY_GROUP_STEALTH);
2020 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2021 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2022 else
2023 SetVisibility(VISIBILITY_ON);
2025 else
2027 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2029 SetAcceptWhispers(false);
2030 SetGameMaster(true);
2032 SetVisibility(VISIBILITY_OFF);
2036 bool Player::IsGroupVisibleFor(Player* p) const
2038 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2040 default: return IsInSameGroupWith(p);
2041 case 1: return IsInSameRaidWith(p);
2042 case 2: return GetTeam()==p->GetTeam();
2046 bool Player::IsInSameGroupWith(Player const* p) const
2048 return p==this || GetGroup() != NULL &&
2049 GetGroup() == p->GetGroup() &&
2050 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2053 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2054 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2055 void Player::UninviteFromGroup()
2057 Group* group = GetGroupInvite();
2058 if(!group)
2059 return;
2061 group->RemoveInvite(this);
2063 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2065 if(group->IsCreated())
2067 group->Disband(true);
2068 objmgr.RemoveGroup(group);
2070 else
2071 group->RemoveAllInvites();
2073 delete group;
2077 void Player::RemoveFromGroup(Group* group, uint64 guid)
2079 if(group)
2081 if (group->RemoveMember(guid, 0) <= 1)
2083 // group->Disband(); already disbanded in RemoveMember
2084 objmgr.RemoveGroup(group);
2085 delete group;
2086 // removemember sets the player's group pointer to NULL
2091 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2093 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2094 data << uint64(victim ? victim->GetGUID() : 0); // guid
2095 data << uint32(GivenXP+RestXP); // given experience
2096 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2097 if(victim)
2099 data << uint32(GivenXP); // experience without rested bonus
2100 data << float(1); // 1 - none 0 - 100% group bonus output
2102 data << uint8(0); // new 2.4.0
2103 GetSession()->SendPacket(&data);
2106 void Player::GiveXP(uint32 xp, Unit* victim)
2108 if ( xp < 1 )
2109 return;
2111 if(!isAlive())
2112 return;
2114 uint32 level = getLevel();
2116 // XP to money conversion processed in Player::RewardQuest
2117 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2118 return;
2120 // handle SPELL_AURA_MOD_XP_PCT auras
2121 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2122 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2123 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2125 // XP resting bonus for kill
2126 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2128 SendLogXPGain(xp,victim,rested_bonus_xp);
2130 uint32 curXP = GetUInt32Value(PLAYER_XP);
2131 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2132 uint32 newXP = curXP + xp + rested_bonus_xp;
2134 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2136 newXP -= nextLvlXP;
2138 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2139 GiveLevel(level + 1);
2141 level = getLevel();
2142 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2145 SetUInt32Value(PLAYER_XP, newXP);
2148 // Update player to next level
2149 // Current player experience not update (must be update by caller)
2150 void Player::GiveLevel(uint32 level)
2152 if ( level == getLevel() )
2153 return;
2155 PlayerLevelInfo info;
2156 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2158 PlayerClassLevelInfo classInfo;
2159 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2161 // send levelup info to client
2162 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2163 data << uint32(level);
2164 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2165 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2166 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2167 data << uint32(0);
2168 data << uint32(0);
2169 data << uint32(0);
2170 data << uint32(0);
2171 data << uint32(0);
2172 data << uint32(0);
2173 // end for
2174 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2175 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2177 GetSession()->SendPacket(&data);
2179 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2181 //update level, max level of skills
2182 if(getLevel()!= level)
2183 m_Played_time[1] = 0; // Level Played Time reset
2184 SetLevel(level);
2185 UpdateSkillsForLevel ();
2187 // save base values (bonuses already included in stored stats
2188 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2189 SetCreateStat(Stats(i), info.stats[i]);
2191 SetCreateHealth(classInfo.basehealth);
2192 SetCreateMana(classInfo.basemana);
2194 InitTalentForLevel();
2195 InitTaxiNodesForLevel();
2196 InitGlyphsForLevel();
2198 UpdateAllStats();
2200 // set current level health and mana/energy to maximum after applying all mods.
2201 SetHealth(GetMaxHealth());
2202 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2203 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2204 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2205 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2206 SetPower(POWER_FOCUS, 0);
2207 SetPower(POWER_HAPPINESS, 0);
2209 // give level to summoned pet
2210 Pet* pet = GetPet();
2211 if(pet && pet->getPetType()==SUMMON_PET)
2212 pet->GivePetLevel(level);
2213 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2216 void Player::InitTalentForLevel()
2218 uint32 level = getLevel();
2219 // talents base at level diff ( talents = level - 9 but some can be used already)
2220 if(level < 10)
2222 // Remove all talent points
2223 if(m_usedTalentCount > 0) // Free any used talents
2225 resetTalents(true);
2226 SetFreeTalentPoints(0);
2229 else
2231 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2232 // if used more that have then reset
2233 if(m_usedTalentCount > talentPointsForLevel)
2235 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2236 resetTalents(true);
2237 else
2238 SetFreeTalentPoints(0);
2240 // else update amount of free points
2241 else
2242 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2246 void Player::InitStatsForLevel(bool reapplyMods)
2248 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2249 _RemoveAllStatBonuses();
2251 PlayerClassLevelInfo classInfo;
2252 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2254 PlayerLevelInfo info;
2255 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2257 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2258 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2260 UpdateSkillsForLevel ();
2262 // set default cast time multiplier
2263 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2265 // reset size before reapply auras
2266 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2268 // save base values (bonuses already included in stored stats
2269 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2270 SetCreateStat(Stats(i), info.stats[i]);
2272 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2273 SetStat(Stats(i), info.stats[i]);
2275 SetCreateHealth(classInfo.basehealth);
2277 //set create powers
2278 SetCreateMana(classInfo.basemana);
2280 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2282 InitStatBuffMods();
2284 //reset rating fields values
2285 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2286 SetUInt32Value(index, 0);
2288 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2289 for (int i = 0; i < 7; i++)
2291 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2292 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2293 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2296 //reset attack power, damage and attack speed fields
2297 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2298 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2299 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2301 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2302 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2303 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2304 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2305 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2306 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2308 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2309 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2310 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2311 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2312 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2313 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2315 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2316 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2317 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2318 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2320 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2321 for (uint8 i = 0; i < 7; ++i)
2322 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2324 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2325 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2326 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2328 // Dodge percentage
2329 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2331 // set armor (resistance 0) to original value (create_agility*2)
2332 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2333 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2334 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2335 // set other resistance to original value (0)
2336 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2338 SetResistance(SpellSchools(i), 0);
2339 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2340 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2343 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2344 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2345 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2347 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2348 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2350 // Reset no reagent cost field
2351 for(int i = 0; i < 3; i++)
2352 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2353 // Init data for form but skip reapply item mods for form
2354 InitDataForForm(reapplyMods);
2356 // save new stats
2357 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2358 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2360 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2362 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2363 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2365 // cleanup unit flags (will be re-applied if need at aura load).
2366 RemoveFlag( UNIT_FIELD_FLAGS,
2367 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2368 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2369 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2370 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2371 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2372 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2374 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2375 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2377 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2379 // restore if need some important flags
2380 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2382 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2383 _ApplyAllStatBonuses();
2385 // set current level health and mana/energy to maximum after applying all mods.
2386 SetHealth(GetMaxHealth());
2387 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2388 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2389 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2390 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2391 SetPower(POWER_FOCUS, 0);
2392 SetPower(POWER_HAPPINESS, 0);
2393 SetPower(POWER_RUNIC_POWER, 0);
2396 void Player::SendInitialSpells()
2398 uint16 spellCount = 0;
2400 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2401 data << uint8(0);
2403 size_t countPos = data.wpos();
2404 data << uint16(spellCount); // spell count placeholder
2406 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2408 if(itr->second->state == PLAYERSPELL_REMOVED)
2409 continue;
2411 if(!itr->second->active || itr->second->disabled)
2412 continue;
2414 data << uint16(itr->first);
2415 data << uint16(0); // it's not slot id
2417 spellCount +=1;
2420 data.put<uint16>(countPos,spellCount); // write real count value
2422 uint16 spellCooldowns = m_spellCooldowns.size();
2423 data << uint16(spellCooldowns);
2424 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2426 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2427 if(!sEntry)
2428 continue;
2430 data << uint16(itr->first);
2432 time_t cooldown = 0;
2433 time_t curTime = time(NULL);
2434 if(itr->second.end > curTime)
2435 cooldown = (itr->second.end-curTime)*1000;
2437 data << uint16(itr->second.itemid); // cast item id
2438 data << uint16(sEntry->Category); // spell category
2439 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2441 data << uint32(0); // cooldown
2442 data << uint32(cooldown); // category cooldown
2444 else
2446 data << uint32(cooldown); // cooldown
2447 data << uint32(0); // category cooldown
2451 GetSession()->SendPacket(&data);
2453 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2456 void Player::RemoveMail(uint32 id)
2458 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2460 if ((*itr)->messageID == id)
2462 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2463 m_mail.erase(itr);
2464 return;
2469 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2471 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2472 data << (uint32) mailId;
2473 data << (uint32) mailAction;
2474 data << (uint32) mailError;
2475 if ( mailError == MAIL_ERR_BAG_FULL )
2476 data << (uint32) equipError;
2477 else if( mailAction == MAIL_ITEM_TAKEN )
2479 data << (uint32) item_guid; // item guid low?
2480 data << (uint32) item_count; // item count?
2482 GetSession()->SendPacket(&data);
2485 void Player::SendNewMail()
2487 // deliver undelivered mail
2488 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2489 data << (uint32) 0;
2490 GetSession()->SendPacket(&data);
2493 void Player::UpdateNextMailTimeAndUnreads()
2495 // calculate next delivery time (min. from non-delivered mails
2496 // and recalculate unReadMail
2497 time_t cTime = time(NULL);
2498 m_nextMailDelivereTime = 0;
2499 unReadMails = 0;
2500 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2502 if((*itr)->deliver_time > cTime)
2504 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2505 m_nextMailDelivereTime = (*itr)->deliver_time;
2507 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2508 ++unReadMails;
2512 void Player::AddNewMailDeliverTime(time_t deliver_time)
2514 if(deliver_time <= time(NULL)) // ready now
2516 ++unReadMails;
2517 SendNewMail();
2519 else // not ready and no have ready mails
2521 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2522 m_nextMailDelivereTime = deliver_time;
2526 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2528 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2529 if (!spellInfo)
2531 // do character spell book cleanup (all characters)
2532 if(loading && !learning) // spell load case
2534 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2535 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2537 else
2538 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2540 return false;
2543 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2545 // do character spell book cleanup (all characters)
2546 if(loading && !learning) // spell load case
2548 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2549 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2551 else
2552 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2554 return false;
2557 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2559 bool disabled_case = false;
2560 bool superceded_old = false;
2562 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2563 if (itr != m_spells.end())
2565 // update active state for known spell
2566 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2568 itr->second->active = active;
2570 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2571 if(loading && !learning)
2572 itr->second->state = PLAYERSPELL_UNCHANGED;
2573 else if(itr->second->state != PLAYERSPELL_NEW)
2574 itr->second->state = PLAYERSPELL_CHANGED;
2576 if(!active)
2578 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2579 data << uint16(spell_id);
2580 GetSession()->SendPacket(&data);
2582 return active; // learn (show in spell book if active now)
2585 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2587 if(itr->second->state != PLAYERSPELL_NEW)
2588 itr->second->state = PLAYERSPELL_CHANGED;
2589 itr->second->disabled = disabled;
2591 if(disabled)
2592 return false;
2594 disabled_case = true;
2596 else switch(itr->second->state)
2598 case PLAYERSPELL_UNCHANGED: // known saved spell
2599 return false;
2600 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2602 delete itr->second;
2603 m_spells.erase(itr);
2604 state = PLAYERSPELL_CHANGED;
2605 break; // need re-add
2607 default: // known not saved yet spell (new or modified)
2609 // can be in case spell loading but learned at some previous spell loading
2610 if(loading && !learning)
2611 itr->second->state = PLAYERSPELL_UNCHANGED;
2613 return false;
2618 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2620 // talent: unlearn all other talent ranks (high and low)
2621 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2623 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2625 for(int i=0; i <5; ++i)
2627 // skip learning spell and no rank spell case
2628 uint32 rankSpellId = talentInfo->RankID[i];
2629 if(!rankSpellId || rankSpellId==spell_id)
2630 continue;
2632 // skip unknown ranks
2633 if(!HasSpell(rankSpellId))
2634 continue;
2636 removeSpell(rankSpellId);
2640 // non talent spell: learn low ranks (recursive call)
2641 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2643 if(loading) // at spells loading, no output, but allow save
2644 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2645 else // at normal learning
2646 learnSpell(prev_spell);
2649 PlayerSpell *newspell = new PlayerSpell;
2650 newspell->active = active;
2651 newspell->state = state;
2652 newspell->disabled = disabled;
2654 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2655 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2657 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2659 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2660 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2661 if(!i_spellInfo) continue;
2663 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2665 if(itr->second->active)
2667 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2669 if(!loading) // not send spell (re-/over-)learn packets at loading
2671 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2672 data << uint16(itr->first);
2673 data << uint16(spell_id);
2674 GetSession()->SendPacket( &data );
2677 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2678 itr->second->active = false;
2679 itr->second->state = PLAYERSPELL_CHANGED;
2680 superceded_old = true; // new spell replace old in action bars and spell book.
2682 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2684 if(!loading) // not send spell (re-/over-)learn packets at loading
2686 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2687 data << uint16(spell_id);
2688 data << uint16(itr->first);
2689 GetSession()->SendPacket( &data );
2692 // mark new spell as disable (not learned yet for client and will not learned)
2693 newspell->active = false;
2694 if(newspell->state != PLAYERSPELL_NEW)
2695 newspell->state = PLAYERSPELL_CHANGED;
2702 uint16 tmpslot=slot_id;
2704 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2706 uint16 maxid = 0;
2707 PlayerSpellMap::iterator itr;
2708 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2710 if(itr->second->state == PLAYERSPELL_REMOVED)
2711 continue;
2712 if (itr->second->slotId > maxid)
2713 maxid = itr->second->slotId;
2715 tmpslot = maxid + 1;
2718 newspell->slotId = tmpslot;
2719 m_spells[spell_id] = newspell;
2721 // return false if spell disabled
2722 if (newspell->disabled)
2723 return false;
2726 uint32 talentCost = GetTalentSpellCost(spell_id);
2728 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2729 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2730 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2732 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2733 CastSpell(this, spell_id, true);
2735 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2736 else if (IsPassiveSpell(spell_id))
2738 // if spell doesn't require a stance or the player is in the required stance
2739 if( ( !spellInfo->Stances &&
2740 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2741 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2742 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2743 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2744 (spell_id == 5420 && m_form == FORM_TREE) ||
2745 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2746 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2747 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2748 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2749 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2750 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2751 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2752 //Check CasterAuraStates
2753 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2754 CastSpell(this, spell_id, true);
2756 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2758 CastSpell(this, spell_id, true);
2759 return false;
2762 // update used talent points count
2763 m_usedTalentCount += talentCost;
2765 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2766 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2768 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2769 SetFreePrimaryProffesions(freeProfs-1);
2772 // add dependent skills
2773 uint16 maxskill = GetMaxSkillValueForLevel();
2775 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2777 if(spellLearnSkill)
2779 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2780 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2782 if(skill_value < spellLearnSkill->value)
2783 skill_value = spellLearnSkill->value;
2785 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2787 if(skill_max_value < new_skill_max_value)
2788 skill_max_value = new_skill_max_value;
2790 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2792 else
2794 // not ranked skills
2795 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2796 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2798 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2800 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2801 if(!pSkill)
2802 continue;
2804 if(HasSkill(pSkill->id))
2805 continue;
2807 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2808 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2809 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2811 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2813 case SKILL_RANGE_LANGUAGE:
2814 SetSkill(pSkill->id, 300, 300 );
2815 break;
2816 case SKILL_RANGE_LEVEL:
2817 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2818 break;
2819 case SKILL_RANGE_MONO:
2820 SetSkill(pSkill->id, 1, 1 );
2821 break;
2822 default:
2823 break;
2829 // learn dependent spells
2830 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2831 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2833 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2835 if(!itr->second.autoLearned)
2837 if(loading) // at spells loading, no output, but allow save
2838 addSpell(itr->second.spell,true,true,loading);
2839 else // at normal learning
2840 learnSpell(itr->second.spell);
2844 if(!loading)
2846 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2847 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2850 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2851 return active && !disabled && !superceded_old;
2854 void Player::learnSpell(uint32 spell_id)
2856 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2858 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2859 bool active = disabled ? itr->second->active : true;
2861 bool learning = addSpell(spell_id,active);
2863 // learn all disabled higher ranks (recursive)
2864 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2865 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2867 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2868 if (disabled && iter != m_spells.end() && iter->second->disabled)
2869 learnSpell(i->second);
2872 // prevent duplicated entires in spell book
2873 if(!learning)
2874 return;
2876 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2877 data << uint32(spell_id);
2878 GetSession()->SendPacket(&data);
2881 void Player::removeSpell(uint32 spell_id, bool disabled)
2883 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2884 if (itr == m_spells.end())
2885 return;
2887 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2888 return;
2890 // unlearn non talent higher ranks (recursive)
2891 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2892 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2893 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2894 removeSpell(itr2->second,disabled);
2896 // removing
2897 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2898 data << uint16(spell_id);
2899 GetSession()->SendPacket(&data);
2901 if (disabled)
2903 itr->second->disabled = disabled;
2904 if(itr->second->state != PLAYERSPELL_NEW)
2905 itr->second->state = PLAYERSPELL_CHANGED;
2907 else
2909 if(itr->second->state == PLAYERSPELL_NEW)
2911 delete itr->second;
2912 m_spells.erase(itr);
2914 else
2915 itr->second->state = PLAYERSPELL_REMOVED;
2918 RemoveAurasDueToSpell(spell_id);
2920 // remove pet auras
2921 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2922 RemovePetAura(petSpell);
2924 // free talent points
2925 uint32 talentCosts = GetTalentSpellCost(spell_id);
2926 if(talentCosts > 0)
2928 if(talentCosts < m_usedTalentCount)
2929 m_usedTalentCount -= talentCosts;
2930 else
2931 m_usedTalentCount = 0;
2934 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2935 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2937 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2938 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2939 SetFreePrimaryProffesions(freeProfs);
2942 // remove dependent skill
2943 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2944 if(spellLearnSkill)
2946 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2947 if(!prev_spell) // first rank, remove skill
2948 SetSkill(spellLearnSkill->skill,0,0);
2949 else
2951 // search prev. skill setting by spell ranks chain
2952 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2953 while(!prevSkill && prev_spell)
2955 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2956 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2959 if(!prevSkill) // not found prev skill setting, remove skill
2960 SetSkill(spellLearnSkill->skill,0,0);
2961 else // set to prev. skill setting values
2963 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2964 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2966 if(skill_value > prevSkill->value)
2967 skill_value = prevSkill->value;
2969 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2971 if(skill_max_value > new_skill_max_value)
2972 skill_max_value = new_skill_max_value;
2974 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2979 else
2981 // not ranked skills
2982 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2983 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2985 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2987 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2988 if(!pSkill)
2989 continue;
2991 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2992 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2993 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2995 // not reset skills for professions and racial abilities
2996 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2997 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2998 continue;
3000 SetSkill(pSkill->id, 0, 0 );
3005 // remove dependent spells
3006 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3007 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3009 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3010 removeSpell(itr2->second.spell, disabled);
3013 void Player::RemoveArenaSpellCooldowns()
3015 // remove cooldowns on spells that has < 15 min CD
3016 SpellCooldowns::iterator itr, next;
3017 // iterate spell cooldowns
3018 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3020 next = itr;
3021 ++next;
3022 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3023 // check if spellentry is present and if the cooldown is less than 15 mins
3024 if( entry &&
3025 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3026 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3028 // notify player
3029 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3030 data << uint32(itr->first);
3031 data << GetGUID();
3032 GetSession()->SendPacket(&data);
3033 // remove cooldown
3034 m_spellCooldowns.erase(itr);
3039 void Player::RemoveAllSpellCooldown()
3041 if(!m_spellCooldowns.empty())
3043 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3045 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3046 data << uint32(itr->first);
3047 data << uint64(GetGUID());
3048 GetSession()->SendPacket(&data);
3050 m_spellCooldowns.clear();
3054 void Player::_LoadSpellCooldowns(QueryResult *result)
3056 m_spellCooldowns.clear();
3058 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3060 if(result)
3062 time_t curTime = time(NULL);
3066 Field *fields = result->Fetch();
3068 uint32 spell_id = fields[0].GetUInt32();
3069 uint32 item_id = fields[1].GetUInt32();
3070 time_t db_time = (time_t)fields[2].GetUInt64();
3072 if(!sSpellStore.LookupEntry(spell_id))
3074 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3075 continue;
3078 // skip outdated cooldown
3079 if(db_time <= curTime)
3080 continue;
3082 AddSpellCooldown(spell_id, item_id, db_time);
3084 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3086 while( result->NextRow() );
3088 delete result;
3092 void Player::_SaveSpellCooldowns()
3094 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3096 time_t curTime = time(NULL);
3098 // remove outdated and save active
3099 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3101 if(itr->second.end <= curTime)
3102 m_spellCooldowns.erase(itr++);
3103 else
3105 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));
3106 ++itr;
3111 uint32 Player::resetTalentsCost() const
3113 // The first time reset costs 1 gold
3114 if(m_resetTalentsCost < 1*GOLD)
3115 return 1*GOLD;
3116 // then 5 gold
3117 else if(m_resetTalentsCost < 5*GOLD)
3118 return 5*GOLD;
3119 // After that it increases in increments of 5 gold
3120 else if(m_resetTalentsCost < 10*GOLD)
3121 return 10*GOLD;
3122 else
3124 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3125 if(months > 0)
3127 // This cost will be reduced by a rate of 5 gold per month
3128 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3129 // to a minimum of 10 gold.
3130 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3132 else
3134 // After that it increases in increments of 5 gold
3135 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3136 // until it hits a cap of 50 gold.
3137 if(new_cost > 50*GOLD)
3138 new_cost = 50*GOLD;
3139 return new_cost;
3144 bool Player::resetTalents(bool no_cost)
3146 // not need after this call
3147 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3149 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3150 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3153 uint32 level = getLevel();
3154 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3156 if (m_usedTalentCount == 0)
3158 SetFreeTalentPoints(talentPointsForLevel);
3159 return false;
3162 uint32 cost = 0;
3164 if(!no_cost)
3166 cost = resetTalentsCost();
3168 if (GetMoney() < cost)
3170 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3171 return false;
3175 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3177 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3179 if (!talentInfo) continue;
3181 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3183 if(!talentTabInfo)
3184 continue;
3186 // unlearn only talents for character class
3187 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3188 // to prevent unexpected lost normal learned spell skip another class talents
3189 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3190 continue;
3192 for (int j = 0; j < 5; j++)
3194 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3196 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3198 ++itr;
3199 continue;
3202 // remove learned spells (all ranks)
3203 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3205 // unlearn if first rank is talent or learned by talent
3206 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3208 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3209 itr = GetSpellMap().begin();
3210 continue;
3212 else
3213 ++itr;
3218 SetFreeTalentPoints(talentPointsForLevel);
3220 if(!no_cost)
3222 ModifyMoney(-(int32)cost);
3224 m_resetTalentsCost = cost;
3225 m_resetTalentsTime = time(NULL);
3228 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3229 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3231 return true;
3234 bool Player::_removeSpell(uint16 spell_id)
3236 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3237 if (itr != m_spells.end())
3239 delete itr->second;
3240 m_spells.erase(itr);
3241 return true;
3243 return false;
3246 Mail* Player::GetMail(uint32 id)
3248 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3250 if ((*itr)->messageID == id)
3252 return (*itr);
3255 return NULL;
3258 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3260 if(target == this)
3262 Object::_SetCreateBits(updateMask, target);
3264 else
3266 for(uint16 index = 0; index < m_valuesCount; index++)
3268 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3269 updateMask->SetBit(index);
3274 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3276 if(target == this)
3278 Object::_SetUpdateBits(updateMask, target);
3280 else
3282 Object::_SetUpdateBits(updateMask, target);
3283 *updateMask &= updateVisualBits;
3287 void Player::InitVisibleBits()
3289 updateVisualBits.SetCount(PLAYER_END);
3291 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3292 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3293 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3294 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3295 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3296 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3297 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3298 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3299 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3300 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3301 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3302 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3303 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3304 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3305 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3306 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3307 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3308 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3309 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3310 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3311 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3312 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3313 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3314 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3315 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3316 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3317 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3318 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3319 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3320 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3321 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3322 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3323 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3324 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3325 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3326 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3327 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3328 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3329 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3330 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3331 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3332 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3333 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3334 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3335 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3336 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3337 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3338 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3339 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3340 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3341 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3342 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3343 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3344 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3345 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3347 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3348 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3349 updateVisualBits.SetBit(PLAYER_FLAGS);
3350 updateVisualBits.SetBit(PLAYER_GUILDID);
3351 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3352 updateVisualBits.SetBit(PLAYER_BYTES);
3353 updateVisualBits.SetBit(PLAYER_BYTES_2);
3354 updateVisualBits.SetBit(PLAYER_BYTES_3);
3355 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3356 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3358 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3359 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3360 updateVisualBits.SetBit(i);
3362 // Players visible items are not inventory stuff
3363 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3365 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3367 // item creator
3368 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3369 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3371 // item entry
3372 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3374 // item enchantments
3375 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3376 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3378 // random properties
3379 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3380 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3381 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3384 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3387 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3389 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3391 if(m_items[i] == NULL)
3392 continue;
3394 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3397 if(target == this)
3399 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3401 if(m_items[i] == NULL)
3402 continue;
3404 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3406 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3408 if(m_items[i] == NULL)
3409 continue;
3411 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3415 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3418 void Player::DestroyForPlayer( Player *target ) const
3420 Unit::DestroyForPlayer( target );
3422 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3424 if(m_items[i] == NULL)
3425 continue;
3427 m_items[i]->DestroyForPlayer( target );
3430 if(target == this)
3432 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3434 if(m_items[i] == NULL)
3435 continue;
3437 m_items[i]->DestroyForPlayer( target );
3439 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3441 if(m_items[i] == NULL)
3442 continue;
3444 m_items[i]->DestroyForPlayer( target );
3449 bool Player::HasSpell(uint32 spell) const
3451 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3452 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3455 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3457 if (!trainer_spell)
3458 return TRAINER_SPELL_RED;
3460 if (!trainer_spell->spell)
3461 return TRAINER_SPELL_RED;
3463 // known spell
3464 if(HasSpell(trainer_spell->spell))
3465 return TRAINER_SPELL_GRAY;
3467 // check race/class requirement
3468 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3469 return TRAINER_SPELL_RED;
3471 // check level requirement
3472 if(getLevel() < trainer_spell->reqlevel)
3473 return TRAINER_SPELL_RED;
3475 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3477 // check prev.rank requirement
3478 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3479 return TRAINER_SPELL_RED;
3481 // check additional spell requirement
3482 if(spell_chain->req && !HasSpell(spell_chain->req))
3483 return TRAINER_SPELL_RED;
3486 // check skill requirement
3487 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3488 return TRAINER_SPELL_RED;
3490 // exist, already checked at loading
3491 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3493 // secondary prof. or not prof. spell
3494 uint32 skill = spell->EffectMiscValue[1];
3496 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3497 return TRAINER_SPELL_GREEN;
3499 // check primary prof. limit
3500 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3501 return TRAINER_SPELL_RED;
3503 return TRAINER_SPELL_GREEN;
3506 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3508 uint32 guid = GUID_LOPART(playerguid);
3510 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3511 // bones will be deleted by corpse/bones deleting thread shortly
3512 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3514 // remove from guild
3515 uint32 guildId = GetGuildIdFromDB(playerguid);
3516 if(guildId != 0)
3518 Guild* guild = objmgr.GetGuildById(guildId);
3519 if(guild)
3520 guild->DelMember(guid);
3523 // remove from arena teams
3524 LeaveAllArenaTeams(playerguid);
3526 // the player was uninvited already on logout so just remove from group
3527 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3528 if(resultGroup)
3530 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3531 delete resultGroup;
3532 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3533 if(group)
3535 RemoveFromGroup(group, playerguid);
3539 // remove signs from petitions (also remove petitions if owner);
3540 RemovePetitionsAndSigns(playerguid, 10);
3542 // return back all mails with COD and Item 0 1 2 3 4 5 6
3543 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);
3544 if(resultMail)
3548 Field *fields = resultMail->Fetch();
3550 uint32 mail_id = fields[0].GetUInt32();
3551 uint16 mailTemplateId= fields[1].GetUInt16();
3552 uint32 sender = fields[2].GetUInt32();
3553 std::string subject = fields[3].GetCppString();
3554 uint32 itemTextId = fields[4].GetUInt32();
3555 uint32 money = fields[5].GetUInt32();
3556 bool has_items = fields[6].GetBool();
3558 //we can return mail now
3559 //so firstly delete the old one
3560 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3562 MailItemsInfo mi;
3563 if(has_items)
3565 // data needs to be at first place for Item::LoadFromDB
3566 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);
3567 if(resultItems)
3571 Field *fields2 = resultItems->Fetch();
3573 uint32 item_guidlow = fields2[1].GetUInt32();
3574 uint32 item_template = fields2[2].GetUInt32();
3576 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3577 if(!itemProto)
3579 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3580 continue;
3583 Item *pItem = NewItemOrBag(itemProto);
3584 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3586 pItem->FSetState(ITEM_REMOVED);
3587 pItem->SaveToDB(); // it also deletes item object !
3588 continue;
3591 mi.AddItem(item_guidlow, item_template, pItem);
3593 while (resultItems->NextRow());
3595 delete resultItems;
3599 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3601 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3603 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3605 while (resultMail->NextRow());
3607 delete resultMail;
3610 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3611 // Get guids of character's pets, will deleted in transaction
3612 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3614 // NOW we can finally clear other DB data related to character
3615 CharacterDatabase.BeginTransaction();
3616 if (resultPets)
3620 Field *fields3 = resultPets->Fetch();
3621 uint32 petguidlow = fields3[0].GetUInt32();
3622 Pet::DeleteFromDB(petguidlow);
3623 } while (resultPets->NextRow());
3624 delete resultPets;
3627 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3628 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3629 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3630 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3631 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3632 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3633 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3634 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3635 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3636 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3637 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3638 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3639 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3640 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3641 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3642 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3643 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3644 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3645 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3646 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3647 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3648 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3649 CharacterDatabase.CommitTransaction();
3651 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3652 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3655 void Player::SetMovement(PlayerMovementType pType)
3657 WorldPacket data;
3658 switch(pType)
3660 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3661 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3662 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3663 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3664 default:
3665 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3666 return;
3668 data.append(GetPackGUID());
3669 data << uint32(0);
3670 GetSession()->SendPacket( &data );
3673 /* Preconditions:
3674 - a resurrectable corpse must not be loaded for the player (only bones)
3675 - the player must be in world
3677 void Player::BuildPlayerRepop()
3679 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3680 data.append(GetPackGUID());
3681 GetSession()->SendPacket(&data);
3683 if(getRace() == RACE_NIGHTELF)
3684 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)
3685 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3687 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3688 // there must be SMSG.STOP_MIRROR_TIMER
3689 // there we must send 888 opcode
3691 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3692 if(GetCorpse())
3694 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3695 assert(false);
3698 // create a corpse and place it at the player's location
3699 CreateCorpse();
3700 Corpse *corpse = GetCorpse();
3701 if(!corpse)
3703 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3704 return;
3706 GetMap()->Add(corpse);
3708 // convert player body to ghost
3709 SetHealth( 1 );
3711 SetMovement(MOVE_WATER_WALK);
3712 if(!GetSession()->isLogingOut())
3713 SetMovement(MOVE_UNROOT);
3715 // BG - remove insignia related
3716 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3718 SendCorpseReclaimDelay();
3720 // to prevent cheating
3721 corpse->ResetGhostTime();
3723 StopMirrorTimers(); //disable timers(bars)
3725 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3727 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3730 void Player::SendDelayResponse(const uint32 ml_seconds)
3732 //FIXME: is this delay time arg really need? 50msec by default in code
3733 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3734 data << (uint32)time(NULL);
3735 data << (uint32)0;
3736 GetSession()->SendPacket( &data );
3739 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3741 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3742 data << uint32(-1);
3743 data << float(0);
3744 data << float(0);
3745 data << float(0);
3746 GetSession()->SendPacket(&data);
3748 // speed change, land walk
3750 // remove death flag + set aura
3751 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3752 if(getRace() == RACE_NIGHTELF)
3753 RemoveAurasDueToSpell(20584); // speed bonuses
3754 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3756 setDeathState(ALIVE);
3758 SetMovement(MOVE_LAND_WALK);
3759 SetMovement(MOVE_UNROOT);
3761 m_deathTimer = 0;
3763 // set health/powers (0- will be set in caller)
3764 if(restore_percent>0.0f)
3766 SetHealth(uint32(GetMaxHealth()*restore_percent));
3767 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3768 SetPower(POWER_RAGE, 0);
3769 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3772 // update visibility
3773 ObjectAccessor::UpdateVisibilityForPlayer(this);
3775 // some items limited to specific map
3776 DestroyZoneLimitedItem( true, GetZoneId());
3778 if(!applySickness)
3779 return;
3781 //Characters from level 1-10 are not affected by resurrection sickness.
3782 //Characters from level 11-19 will suffer from one minute of sickness
3783 //for each level they are above 10.
3784 //Characters level 20 and up suffer from ten minutes of sickness.
3785 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3787 if(int32(getLevel()) >= startLevel)
3789 // set resurrection sickness
3790 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3792 // not full duration
3793 if(int32(getLevel()) < startLevel+9)
3795 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3797 for(int i =0; i < 3; ++i)
3799 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3801 Aur->SetAuraDuration(delta*1000);
3802 Aur->SendAuraUpdate(false);
3809 void Player::KillPlayer()
3811 SetMovement(MOVE_ROOT);
3813 StopMirrorTimers(); //disable timers(bars)
3815 setDeathState(CORPSE);
3816 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3818 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3819 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3821 // 6 minutes until repop at graveyard
3822 m_deathTimer = 6*MINUTE*1000;
3824 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3826 // don't create corpse at this moment, player might be falling
3828 // update visibility
3829 ObjectAccessor::UpdateObjectVisibility(this);
3832 void Player::CreateCorpse()
3834 // prevent existence 2 corpse for player
3835 SpawnCorpseBones();
3837 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3839 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3840 SetPvPDeath(false);
3842 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3843 GetPositionY(), GetPositionZ(), GetOrientation()))
3845 delete corpse;
3846 return;
3849 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3850 _pb = GetUInt32Value(PLAYER_BYTES);
3851 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3853 uint8 race = (uint8)(_uf);
3854 uint8 skin = (uint8)(_pb);
3855 uint8 face = (uint8)(_pb >> 8);
3856 uint8 hairstyle = (uint8)(_pb >> 16);
3857 uint8 haircolor = (uint8)(_pb >> 24);
3858 uint8 facialhair = (uint8)(_pb2);
3860 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3861 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3863 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3864 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3866 uint32 flags = CORPSE_FLAG_UNK2;
3867 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3868 flags |= CORPSE_FLAG_HIDE_HELM;
3869 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3870 flags |= CORPSE_FLAG_HIDE_CLOAK;
3871 if(InBattleGround())
3872 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3873 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3875 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3877 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3879 uint32 iDisplayID;
3880 uint16 iIventoryType;
3881 uint32 _cfi;
3882 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3884 if(m_items[i])
3886 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3887 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3889 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3890 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3894 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3895 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3896 assert(entry);
3897 if(entry->map_type != MAP_BATTLEGROUND)
3898 corpse->SaveToDB();
3900 // register for player, but not show
3901 ObjectAccessor::Instance().AddCorpse(corpse);
3904 void Player::SpawnCorpseBones()
3906 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3907 SaveToDB(); // prevent loading as ghost without corpse
3910 Corpse* Player::GetCorpse() const
3912 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3915 void Player::DurabilityLossAll(double percent, bool inventory)
3917 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3918 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3919 DurabilityLoss(pItem,percent);
3921 if(inventory)
3923 // bags not have durability
3924 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3926 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3927 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3928 DurabilityLoss(pItem,percent);
3930 // keys not have durability
3931 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3933 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3934 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3935 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3936 if(Item* pItem = GetItemByPos( i, j ))
3937 DurabilityLoss(pItem,percent);
3941 void Player::DurabilityLoss(Item* item, double percent)
3943 if(!item )
3944 return;
3946 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3948 if(!pMaxDurability)
3949 return;
3951 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3953 if(pDurabilityLoss < 1 )
3954 pDurabilityLoss = 1;
3956 DurabilityPointsLoss(item,pDurabilityLoss);
3959 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3961 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3962 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3963 DurabilityPointsLoss(pItem,points);
3965 if(inventory)
3967 // bags not have durability
3968 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3970 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3971 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3972 DurabilityPointsLoss(pItem,points);
3974 // keys not have durability
3975 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3977 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3978 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3979 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3980 if(Item* pItem = GetItemByPos( i, j ))
3981 DurabilityPointsLoss(pItem,points);
3985 void Player::DurabilityPointsLoss(Item* item, int32 points)
3987 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3988 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3989 int32 pNewDurability = pOldDurability - points;
3991 if (pNewDurability < 0)
3992 pNewDurability = 0;
3993 else if (pNewDurability > pMaxDurability)
3994 pNewDurability = pMaxDurability;
3996 if (pOldDurability != pNewDurability)
3998 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3999 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4000 _ApplyItemMods(item,item->GetSlot(), false);
4002 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4004 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4005 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4006 _ApplyItemMods(item,item->GetSlot(), true);
4008 item->SetState(ITEM_CHANGED, this);
4012 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4014 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4015 DurabilityPointsLoss(pItem,1);
4018 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4020 uint32 TotalCost = 0;
4021 // equipped, backpack, bags itself
4022 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4023 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4025 // bank, buyback and keys not repaired
4027 // items in inventory bags
4028 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4029 for(int i = 0; i < MAX_BAG_SIZE; i++)
4030 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4031 return TotalCost;
4034 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4036 Item* item = GetItemByPos(pos);
4038 uint32 TotalCost = 0;
4039 if(!item)
4040 return TotalCost;
4042 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4043 if(!maxDurability)
4044 return TotalCost;
4046 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4048 if(cost)
4050 uint32 LostDurability = maxDurability - curDurability;
4051 if(LostDurability>0)
4053 ItemPrototype const *ditemProto = item->GetProto();
4055 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4056 if(!dcost)
4058 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4059 return TotalCost;
4062 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4063 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4064 if(!dQualitymodEntry)
4066 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4067 return TotalCost;
4070 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4071 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4073 costs = uint32(costs * discountMod);
4075 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4076 costs = 1;
4078 if (guildBank)
4080 if (GetGuildId()==0)
4082 DEBUG_LOG("You are not member of a guild");
4083 return TotalCost;
4086 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4087 if (!pGuild)
4088 return TotalCost;
4090 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4092 DEBUG_LOG("You do not have rights to withdraw for repairs");
4093 return TotalCost;
4096 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4098 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4099 return TotalCost;
4102 if (pGuild->GetGuildBankMoney() < costs)
4104 DEBUG_LOG("There is not enough money in bank");
4105 return TotalCost;
4108 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4109 TotalCost = costs;
4111 else if (GetMoney() < costs)
4113 DEBUG_LOG("You do not have enough money");
4114 return TotalCost;
4116 else
4117 ModifyMoney( -int32(costs) );
4121 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4122 item->SetState(ITEM_CHANGED, this);
4124 // reapply mods for total broken and repaired item if equipped
4125 if(IsEquipmentPos(pos) && !curDurability)
4126 _ApplyItemMods(item,pos & 255, true);
4127 return TotalCost;
4130 void Player::RepopAtGraveyard()
4132 // note: this can be called also when the player is alive
4133 // for example from WorldSession::HandleMovementOpcodes
4135 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4137 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4138 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4140 ResurrectPlayer(0.5f);
4141 SpawnCorpseBones();
4144 WorldSafeLocsEntry const *ClosestGrave = NULL;
4146 // Special handle for battleground maps
4147 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4149 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4150 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4151 else
4152 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4154 // stop countdown until repop
4155 m_deathTimer = 0;
4157 // if no grave found, stay at the current location
4158 // and don't show spirit healer location
4159 if(ClosestGrave)
4161 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4162 if(isDead()) // not send if alive, because it used in TeleportTo()
4164 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4165 data << ClosestGrave->map_id;
4166 data << ClosestGrave->x;
4167 data << ClosestGrave->y;
4168 data << ClosestGrave->z;
4169 GetSession()->SendPacket(&data);
4174 void Player::JoinedChannel(Channel *c)
4176 m_channels.push_back(c);
4179 void Player::LeftChannel(Channel *c)
4181 m_channels.remove(c);
4184 void Player::CleanupChannels()
4186 while(!m_channels.empty())
4188 Channel* ch = *m_channels.begin();
4189 m_channels.erase(m_channels.begin()); // remove from player's channel list
4190 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4191 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4192 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4195 sLog.outDebug("Player: channels cleaned up!");
4198 void Player::UpdateLocalChannels(uint32 newZone )
4200 if(m_channels.empty())
4201 return;
4203 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4204 if(!current_zone)
4205 return;
4207 ChannelMgr* cMgr = channelMgr(GetTeam());
4208 if(!cMgr)
4209 return;
4211 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4213 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4215 next = i; ++next;
4217 // skip non built-in channels
4218 if(!(*i)->IsConstant())
4219 continue;
4221 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4222 if(!ch)
4223 continue;
4225 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4226 continue;
4228 // new channel
4229 char new_channel_name_buf[100];
4230 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4231 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4233 if((*i)!=new_channel)
4235 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4237 // leave old channel
4238 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4239 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4240 LeftChannel(*i); // remove from player's channel list
4241 cMgr->LeftChannel(name); // delete if empty
4244 sLog.outDebug("Player: channels cleaned up!");
4247 void Player::LeaveLFGChannel()
4249 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4251 if((*i)->IsLFG())
4253 (*i)->Leave(GetGUID());
4254 break;
4259 void Player::UpdateDefense()
4261 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4263 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4265 // update dependent from defense skill part
4266 UpdateDefenseBonusesMod();
4270 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4272 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4274 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4275 return;
4278 float val = 1.0f;
4280 switch(modType)
4282 case FLAT_MOD:
4283 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4284 break;
4285 case PCT_MOD:
4286 if(amount <= -100.0f)
4287 amount = -200.0f;
4289 val = (100.0f + amount) / 100.0f;
4290 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4291 break;
4294 if(!CanModifyStats())
4295 return;
4297 switch(modGroup)
4299 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4300 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4301 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4302 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4303 default: break;
4307 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4309 if(modGroup >= BASEMOD_END || modType > MOD_END)
4311 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4312 return 0.0f;
4315 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4316 return 0.0f;
4318 return m_auraBaseMod[modGroup][modType];
4321 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4323 if(modGroup >= BASEMOD_END)
4325 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4326 return 0.0f;
4329 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4330 return 0.0f;
4332 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4335 uint32 Player::GetShieldBlockValue() const
4337 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4339 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4341 value = (value < 0) ? 0 : value;
4343 return uint32(value);
4346 float Player::GetMeleeCritFromAgility()
4348 uint32 level = getLevel();
4349 uint32 pclass = getClass();
4351 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4353 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4354 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4355 if (critBase==NULL || critRatio==NULL)
4356 return 0.0f;
4358 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4359 return crit*100.0f;
4362 float Player::GetDodgeFromAgility()
4364 // Table for base dodge values
4365 float dodge_base[MAX_CLASSES] = {
4366 0.0075f, // Warrior
4367 0.00652f, // Paladin
4368 -0.0545f, // Hunter
4369 -0.0059f, // Rogue
4370 0.03183f, // Priest
4371 0.0114f, // DK
4372 0.0167f, // Shaman
4373 0.034575f, // Mage
4374 0.02011f, // Warlock
4375 0.0f, // ??
4376 -0.0187f // Druid
4378 // Crit/agility to dodge/agility coefficient multipliers
4379 float crit_to_dodge[MAX_CLASSES] = {
4380 1.1f, // Warrior
4381 1.0f, // Paladin
4382 1.6f, // Hunter
4383 2.0f, // Rogue
4384 1.0f, // Priest
4385 1.0f, // DK?
4386 1.0f, // Shaman
4387 1.0f, // Mage
4388 1.0f, // Warlock
4389 0.0f, // ??
4390 1.7f // Druid
4393 uint32 level = getLevel();
4394 uint32 pclass = getClass();
4396 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4398 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4399 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4400 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4401 return 0.0f;
4403 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4404 return dodge*100.0f;
4407 float Player::GetSpellCritFromIntellect()
4409 uint32 level = getLevel();
4410 uint32 pclass = getClass();
4412 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4414 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4415 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4416 if (critBase==NULL || critRatio==NULL)
4417 return 0.0f;
4419 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4420 return crit*100.0f;
4423 float Player::GetRatingCoefficient(CombatRating cr) const
4425 uint32 level = getLevel();
4427 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4429 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4430 if (Rating == NULL)
4431 return 1.0f; // By default use minimum coefficient (not must be called)
4433 return Rating->ratio;
4436 float Player::GetRatingBonusValue(CombatRating cr) const
4438 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4441 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4443 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4444 if (melee>25.0f) melee = 25.0f;
4445 return uint32 (melee * damage /100.0f);
4448 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4450 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4451 if (ranged>25.0f) ranged=25.0f;
4452 return uint32 (ranged * damage /100.0f);
4455 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4457 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4458 // In wow script resilience limited to 25%
4459 if (spell>25.0f)
4460 spell = 25.0f;
4461 return uint32 (spell * damage / 100.0f);
4464 uint32 Player::GetDotDamageReduction(uint32 damage) const
4466 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4467 // Dot resilience not limited (limit it by 100%)
4468 if (spellDot > 100.0f)
4469 spellDot = 100.0f;
4470 return uint32 (spellDot * damage / 100.0f);
4473 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4475 switch (attType)
4477 case BASE_ATTACK:
4478 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4479 case OFF_ATTACK:
4480 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4481 default:
4482 break;
4484 return 0.0f;
4487 float Player::OCTRegenHPPerSpirit()
4489 uint32 level = getLevel();
4490 uint32 pclass = getClass();
4492 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4494 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4495 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4496 if (baseRatio==NULL || moreRatio==NULL)
4497 return 0.0f;
4499 // Formula from PaperDollFrame script
4500 float spirit = GetStat(STAT_SPIRIT);
4501 float baseSpirit = spirit;
4502 if (baseSpirit>50) baseSpirit = 50;
4503 float moreSpirit = spirit - baseSpirit;
4504 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4505 return regen;
4508 float Player::OCTRegenMPPerSpirit()
4510 uint32 level = getLevel();
4511 uint32 pclass = getClass();
4513 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4515 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4516 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4517 if (moreRatio==NULL)
4518 return 0.0f;
4520 // Formula get from PaperDollFrame script
4521 float spirit = GetStat(STAT_SPIRIT);
4522 float regen = spirit * moreRatio->ratio;
4523 return regen;
4526 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4528 m_baseRatingValue[cr]+=(apply ? value : -value);
4530 int32 amount = uint32(m_baseRatingValue[cr]);
4531 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4532 // stat used stored in miscValueB for this aura
4533 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4534 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4535 if ((*i)->GetMiscValue() & (1<<cr))
4536 amount += GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f;
4537 if (amount < 0)
4538 amount = 0;
4539 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4541 float RatingCoeffecient = GetRatingCoefficient(cr);
4542 float RatingChange = 0.0f;
4544 bool affectStats = CanModifyStats();
4546 switch (cr)
4548 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4549 case CR_DEFENSE_SKILL:
4550 UpdateDefenseBonusesMod();
4551 break;
4552 case CR_DODGE:
4553 UpdateDodgePercentage();
4554 break;
4555 case CR_PARRY:
4556 UpdateParryPercentage();
4557 break;
4558 case CR_BLOCK:
4559 UpdateBlockPercentage();
4560 break;
4561 case CR_HIT_MELEE:
4562 UpdateMeleeHitChances();
4563 break;
4564 case CR_HIT_RANGED:
4565 UpdateRangedHitChances();
4566 break;
4567 case CR_HIT_SPELL:
4568 UpdateSpellHitChances();
4569 break;
4570 case CR_CRIT_MELEE:
4571 if(affectStats)
4573 UpdateCritPercentage(BASE_ATTACK);
4574 UpdateCritPercentage(OFF_ATTACK);
4576 break;
4577 case CR_CRIT_RANGED:
4578 if(affectStats)
4579 UpdateCritPercentage(RANGED_ATTACK);
4580 break;
4581 case CR_CRIT_SPELL:
4582 if(affectStats)
4583 UpdateAllSpellCritChances();
4584 break;
4585 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4586 case CR_HIT_TAKEN_RANGED:
4587 break;
4588 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4589 break;
4590 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4591 case CR_CRIT_TAKEN_RANGED:
4592 break;
4593 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4594 break;
4595 case CR_HASTE_MELEE:
4596 RatingChange = value / RatingCoeffecient;
4597 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4598 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4599 break;
4600 case CR_HASTE_RANGED:
4601 RatingChange = value / RatingCoeffecient;
4602 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4603 break;
4604 case CR_HASTE_SPELL:
4605 RatingChange = value / RatingCoeffecient;
4606 ApplyCastTimePercentMod(RatingChange,apply);
4607 break;
4608 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4609 case CR_WEAPON_SKILL_OFFHAND:
4610 case CR_WEAPON_SKILL_RANGED:
4611 break;
4612 case CR_EXPERTISE:
4613 if(affectStats)
4615 UpdateExpertise(BASE_ATTACK);
4616 UpdateExpertise(OFF_ATTACK);
4618 break;
4622 void Player::SetRegularAttackTime()
4624 for(int i = 0; i < MAX_ATTACK; ++i)
4626 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4627 if(tmpitem && !tmpitem->IsBroken())
4629 ItemPrototype const *proto = tmpitem->GetProto();
4630 if(proto->Delay)
4631 SetAttackTime(WeaponAttackType(i), proto->Delay);
4632 else
4633 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4638 //skill+step, checking for max value
4639 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4641 if(!skill_id)
4642 return false;
4644 uint16 i=0;
4645 for (; i < PLAYER_MAX_SKILLS; i++)
4646 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4647 break;
4649 if(i>=PLAYER_MAX_SKILLS)
4650 return false;
4652 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4653 uint32 value = SKILL_VALUE(data);
4654 uint32 max = SKILL_MAX(data);
4656 if ((!max) || (!value) || (value >= max))
4657 return false;
4659 if (value*512 < max*urand(0,512))
4661 uint32 new_value = value+step;
4662 if(new_value > max)
4663 new_value = max;
4665 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4666 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4667 return true;
4670 return false;
4673 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4675 if ( SkillValue >= GrayLevel )
4676 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4677 if ( SkillValue >= GreenLevel )
4678 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4679 if ( SkillValue >= YellowLevel )
4680 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4681 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4684 bool Player::UpdateCraftSkill(uint32 spellid)
4686 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4688 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4689 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4691 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4693 if(_spell_idx->second->skillId)
4695 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4697 // Alchemy Discoveries here
4698 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4699 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4701 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4702 learnSpell(discoveredSpell);
4705 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4707 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4708 _spell_idx->second->max_value,
4709 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4710 _spell_idx->second->min_value),
4711 craft_skill_gain);
4714 return false;
4717 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4719 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4721 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4723 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4724 switch (SkillId)
4726 case SKILL_HERBALISM:
4727 case SKILL_LOCKPICKING:
4728 case SKILL_JEWELCRAFTING:
4729 case SKILL_INSCRIPTION:
4730 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4731 case SKILL_SKINNING:
4732 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4733 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4734 else
4735 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4736 case SKILL_MINING:
4737 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4738 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4739 else
4740 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4742 return false;
4745 bool Player::UpdateFishingSkill()
4747 sLog.outDebug("UpdateFishingSkill");
4749 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4751 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4753 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4755 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4758 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4760 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4761 if ( !SkillId )
4762 return false;
4764 if(Chance <= 0) // speedup in 0 chance case
4766 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4767 return false;
4770 uint16 i=0;
4771 for (; i < PLAYER_MAX_SKILLS; i++)
4772 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4773 if ( i >= PLAYER_MAX_SKILLS )
4774 return false;
4776 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4777 uint16 SkillValue = SKILL_VALUE(data);
4778 uint16 MaxValue = SKILL_MAX(data);
4780 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4781 return false;
4783 int32 Roll = irand(1,1000);
4785 if ( Roll <= Chance )
4787 uint32 new_value = SkillValue+step;
4788 if(new_value > MaxValue)
4789 new_value = MaxValue;
4791 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4792 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4793 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4794 return true;
4797 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4798 return false;
4801 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4803 // no skill gain in pvp
4804 Unit *pVictim = getVictim();
4805 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4806 return;
4808 if(IsInFeralForm())
4809 return; // always maximized SKILL_FERAL_COMBAT in fact
4811 if(m_form == FORM_TREE)
4812 return; // use weapon but not skill up
4814 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4816 switch(attType)
4818 case BASE_ATTACK:
4820 Item *tmpitem = GetWeaponForAttack(attType,true);
4822 if (!tmpitem)
4823 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4824 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4825 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4826 break;
4828 case OFF_ATTACK:
4829 case RANGED_ATTACK:
4831 Item *tmpitem = GetWeaponForAttack(attType,true);
4832 if (tmpitem)
4833 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4834 break;
4837 UpdateAllCritPercentages();
4840 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4842 /* Not need, this checked on call this func from trigger system
4843 switch(outcome)
4845 case MELEE_HIT_CRIT:
4846 case MELEE_HIT_DODGE:
4847 case MELEE_HIT_PARRY:
4848 case MELEE_HIT_BLOCK:
4849 case MELEE_HIT_BLOCK_CRIT:
4850 return;
4852 default:
4853 break;
4856 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4857 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4858 uint32 moblevel = pVictim->getLevelForTarget(this);
4859 if(moblevel < greylevel)
4860 return;
4862 if (moblevel > plevel + 5)
4863 moblevel = plevel + 5;
4865 uint32 lvldif = moblevel - greylevel;
4866 if(lvldif < 3)
4867 lvldif = 3;
4869 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4870 if(skilldif <= 0)
4871 return;
4873 float chance = float(3 * lvldif * skilldif) / plevel;
4874 if(!defence)
4876 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4877 chance *= 0.1f * GetStat(STAT_INTELLECT);
4880 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4882 if(roll_chance_f(chance))
4884 if(defence)
4885 UpdateDefense();
4886 else
4887 UpdateWeaponSkill(attType);
4889 else
4890 return;
4893 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4895 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4896 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4898 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4899 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4900 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4902 if(talent) // permanent bonus stored in high part
4903 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4904 else // temporary/item bonus stored in low part
4905 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4906 return;
4910 void Player::UpdateSkillsForLevel()
4912 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4913 uint32 maxSkill = GetMaxSkillValueForLevel();
4915 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
4917 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4918 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4920 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4922 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4923 if(!pSkill)
4924 continue;
4926 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4927 continue;
4929 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4930 uint32 max = SKILL_MAX(data);
4931 uint32 val = SKILL_VALUE(data);
4933 /// update only level dependent max skill values
4934 if(max!=1)
4936 /// miximize skill always
4937 if(alwaysMaxSkill)
4938 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
4939 /// update max skill value if current max skill not maximized
4940 else if(max != maxconfskill)
4941 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
4946 void Player::UpdateSkillsToMaxSkillsForLevel()
4948 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4949 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4951 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4952 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4953 continue;
4954 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4956 uint32 max = SKILL_MAX(data);
4958 if(max > 1)
4959 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4961 if(pskill == SKILL_DEFENSE)
4962 UpdateDefenseBonusesMod();
4966 // This functions sets a skill line value (and adds if doesn't exist yet)
4967 // To "remove" a skill line, set it's values to zero
4968 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4970 if(!id)
4971 return;
4973 uint16 i=0;
4974 for (; i < PLAYER_MAX_SKILLS; i++)
4975 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4977 if(i<PLAYER_MAX_SKILLS) //has skill
4979 if(currVal)
4981 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4982 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4984 else //remove
4986 // clear skill fields
4987 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4988 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4989 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4991 // remove spells that depend on this skill when removing the skill
4992 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4994 ++next;
4995 if(itr->second->state == PLAYERSPELL_REMOVED)
4996 continue;
4998 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4999 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
5001 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
5003 if (_spell_idx->second->skillId == id)
5005 // this may remove more than one spell (dependents)
5006 removeSpell(itr->first);
5007 next = m_spells.begin();
5008 break;
5014 else if(currVal) //add
5016 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5017 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5019 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5020 if(!pSkill)
5022 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5023 return;
5025 // enable unlearn button for primary professions only
5026 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5027 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5028 else
5029 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5030 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5031 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5033 // apply skill bonuses
5034 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5036 // temporary bonuses
5037 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5038 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5039 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5040 (*i)->ApplyModifier(true);
5042 // permanent bonuses
5043 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5044 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5045 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5046 (*i)->ApplyModifier(true);
5048 // Learn all spells for skill
5049 learnSkillRewardedSpells(id);
5050 return;
5055 bool Player::HasSkill(uint32 skill) const
5057 if(!skill)return false;
5058 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5060 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5062 return true;
5065 return false;
5068 uint16 Player::GetSkillValue(uint32 skill) const
5070 if(!skill)
5071 return 0;
5073 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5075 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5077 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5079 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5080 result += SKILL_TEMP_BONUS(bonus);
5081 result += SKILL_PERM_BONUS(bonus);
5082 return result < 0 ? 0 : result;
5085 return 0;
5088 uint16 Player::GetMaxSkillValue(uint32 skill) const
5090 if(!skill)return 0;
5091 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5093 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5095 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5097 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5098 result += SKILL_TEMP_BONUS(bonus);
5099 result += SKILL_PERM_BONUS(bonus);
5100 return result < 0 ? 0 : result;
5103 return 0;
5106 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5108 if(!skill)return 0;
5109 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5111 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5113 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5116 return 0;
5119 uint16 Player::GetBaseSkillValue(uint32 skill) const
5121 if(!skill)return 0;
5122 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5124 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5126 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5127 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5128 return result < 0 ? 0 : result;
5131 return 0;
5134 uint16 Player::GetPureSkillValue(uint32 skill) const
5136 if(!skill)return 0;
5137 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5139 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5141 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5144 return 0;
5147 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5149 if(!skill)
5150 return 0;
5152 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5154 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5156 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5160 return 0;
5163 void Player::SendInitialActionButtons()
5165 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5167 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5168 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5170 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5171 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5173 data << uint16(itr->second.action);
5174 data << uint8(itr->second.misc);
5175 data << uint8(itr->second.type);
5177 else
5179 data << uint32(0);
5183 GetSession()->SendPacket( &data );
5184 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5187 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5189 if(button >= MAX_ACTION_BUTTONS)
5191 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5192 return;
5195 // check cheating with adding non-known spells to action bar
5196 if(type==ACTION_BUTTON_SPELL)
5198 if(!sSpellStore.LookupEntry(action))
5200 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5201 return;
5204 if(!HasSpell(action))
5206 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5207 return;
5211 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5213 if (buttonItr==m_actionButtons.end())
5214 { // just add new button
5215 m_actionButtons[button] = ActionButton(action,type,misc);
5217 else
5218 { // change state of current button
5219 ActionButtonUpdateState uState = buttonItr->second.uState;
5220 buttonItr->second = ActionButton(action,type,misc);
5221 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5224 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5227 void Player::removeActionButton(uint8 button)
5229 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5230 if (buttonItr==m_actionButtons.end())
5231 return;
5233 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5234 m_actionButtons.erase(buttonItr); // new and not saved
5235 else
5236 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5238 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5241 void Player::SetDontMove(bool dontMove)
5243 m_dontMove = dontMove;
5246 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5248 // prevent crash when a bad coord is sent by the client
5249 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5251 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5252 return false;
5255 Map *m = GetMap();
5257 const float old_x = GetPositionX();
5258 const float old_y = GetPositionY();
5259 const float old_z = GetPositionZ();
5260 const float old_r = GetOrientation();
5262 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5264 if (teleport || old_x != x || old_y != y || old_z != z)
5265 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5266 else
5267 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5269 // move and update visible state if need
5270 m->PlayerRelocation(this, x, y, z, orientation);
5272 // reread after Map::Relocation
5273 m = GetMap();
5274 x = GetPositionX();
5275 y = GetPositionY();
5276 z = GetPositionZ();
5278 // group update
5279 if(GetGroup() && (old_x != x || old_y != y))
5280 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5283 // code block for underwater state update
5284 UpdateUnderwaterState(m, x, y, z);
5286 CheckExploreSystem();
5288 return true;
5291 void Player::SaveRecallPosition()
5293 m_recallMap = GetMapId();
5294 m_recallX = GetPositionX();
5295 m_recallY = GetPositionY();
5296 m_recallZ = GetPositionZ();
5297 m_recallO = GetOrientation();
5300 void Player::SendMessageToSet(WorldPacket *data, bool self)
5302 GetMap()->MessageBroadcast(this, data, self);
5305 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5307 GetMap()->MessageDistBroadcast(this, data, dist, self);
5310 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5312 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5315 void Player::SendDirectMessage(WorldPacket *data)
5317 GetSession()->SendPacket(data);
5320 void Player::CheckExploreSystem()
5322 if (!isAlive())
5323 return;
5325 if (isInFlight())
5326 return;
5328 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5329 if(areaFlag==0xffff)
5330 return;
5331 int offset = areaFlag / 32;
5333 if(offset >= 128)
5335 sLog.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 64 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5336 return;
5339 uint32 val = (uint32)(1 << (areaFlag % 32));
5340 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5342 if( !(currFields & val) )
5344 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5346 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5348 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5349 if(!p)
5351 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5353 else if(p->area_level > 0)
5355 uint32 area = p->ID;
5356 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5358 SendExplorationExperience(area,0);
5360 else
5362 int32 diff = int32(getLevel()) - p->area_level;
5363 uint32 XP = 0;
5364 if (diff < -5)
5366 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5368 else if (diff > 5)
5370 int32 exploration_percent = (100-((diff-5)*5));
5371 if (exploration_percent > 100)
5372 exploration_percent = 100;
5373 else if (exploration_percent < 0)
5374 exploration_percent = 0;
5376 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5378 else
5380 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5383 GiveXP( XP, NULL );
5384 SendExplorationExperience(area,XP);
5386 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5391 uint32 Player::TeamForRace(uint8 race)
5393 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5394 if(!rEntry)
5396 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5397 return ALLIANCE;
5400 switch(rEntry->TeamID)
5402 case 7: return ALLIANCE;
5403 case 1: return HORDE;
5406 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5407 return ALLIANCE;
5410 uint32 Player::getFactionForRace(uint8 race)
5412 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5413 if(!rEntry)
5415 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5416 return 0;
5419 return rEntry->FactionID;
5422 void Player::setFactionForRace(uint8 race)
5424 m_team = TeamForRace(race);
5425 setFaction( getFactionForRace(race) );
5428 void Player::UpdateReputation() const
5430 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5432 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5434 SendFactionState(&(itr->second));
5438 void Player::SendFactionState(FactionState const* faction) const
5440 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5442 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5443 data << (float) 0; // unk 2.4.0
5444 data << (uint8) 0; // wotlk 8634
5445 data << (uint32) 1; // count
5446 // for
5447 data << (uint32) faction->ReputationListID;
5448 data << (uint32) faction->Standing;
5449 // end for
5450 GetSession()->SendPacket(&data);
5454 void Player::SendInitialReputations()
5456 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5457 data << uint32 (0x00000080);
5459 RepListID a = 0;
5461 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5463 // fill in absent fields
5464 for (; a != itr->first; a++)
5466 data << uint8 (0x00);
5467 data << uint32 (0x00000000);
5470 // fill in encountered data
5471 data << uint8 (itr->second.Flags);
5472 data << uint32 (itr->second.Standing);
5474 ++a;
5477 // fill in absent fields
5478 for (; a != 128; a++)
5480 data << uint8 (0x00);
5481 data << uint32 (0x00000000);
5484 GetSession()->SendPacket(&data);
5487 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5489 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5490 if (itr != m_factions.end())
5491 return &itr->second;
5493 return NULL;
5496 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5498 // not allow declare war to own faction
5499 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5500 return;
5502 // already set
5503 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5504 return;
5506 if( atWar )
5507 faction->Flags |= FACTION_FLAG_AT_WAR;
5508 else
5509 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5511 faction->Changed = true;
5514 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5516 // always invisible or hidden faction can't be inactive
5517 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5518 return;
5520 // already set
5521 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5522 return;
5524 if(inactive)
5525 faction->Flags |= FACTION_FLAG_INACTIVE;
5526 else
5527 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5529 faction->Changed = true;
5532 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5534 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5536 if(!factionTemplateEntry)
5537 return;
5539 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5542 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5544 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5545 if(!factionEntry)
5546 return;
5548 if(factionEntry->reputationListID < 0)
5549 return;
5551 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5552 if (itr == m_factions.end())
5553 return;
5555 SetFactionVisible(&itr->second);
5558 void Player::SetFactionVisible(FactionState* faction)
5560 // always invisible or hidden faction can't be make visible
5561 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5562 return;
5564 // already set
5565 if(faction->Flags & FACTION_FLAG_VISIBLE)
5566 return;
5568 faction->Flags |= FACTION_FLAG_VISIBLE;
5569 faction->Changed = true;
5571 if(!m_session->PlayerLoading())
5573 // make faction visible in reputation list at client
5574 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5575 data << faction->ReputationListID;
5576 GetSession()->SendPacket(&data);
5580 void Player::SetInitialFactions()
5582 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5584 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5586 if( factionEntry && (factionEntry->reputationListID >= 0))
5588 FactionState newFaction;
5589 newFaction.ID = factionEntry->ID;
5590 newFaction.ReputationListID = factionEntry->reputationListID;
5591 newFaction.Standing = 0;
5592 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5593 newFaction.Changed = true;
5595 m_factions[newFaction.ReputationListID] = newFaction;
5600 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5602 if (!factionEntry)
5603 return 0;
5605 uint32 raceMask = getRaceMask();
5606 uint32 classMask = getClassMask();
5607 for (int i=0; i < 4; i++)
5609 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5610 (factionEntry->BaseRepClassMask[i]==0 ||
5611 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5612 return factionEntry->ReputationFlags[i];
5614 return 0;
5617 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5619 if (!factionEntry)
5620 return 0;
5622 uint32 raceMask = getRaceMask();
5623 uint32 classMask = getClassMask();
5624 for (int i=0; i < 4; i++)
5626 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5627 (factionEntry->BaseRepClassMask[i]==0 ||
5628 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5629 return factionEntry->BaseRepValue[i];
5632 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5633 return 0;
5636 int32 Player::GetReputation(uint32 faction_id) const
5638 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5640 if (!factionEntry)
5642 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5643 return 0;
5646 return GetReputation(factionEntry);
5649 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5651 // Faction without recorded reputation. Just ignore.
5652 if(!factionEntry)
5653 return 0;
5655 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5656 if (itr != m_factions.end())
5657 return GetBaseReputation(factionEntry) + itr->second.Standing;
5659 return 0;
5662 ReputationRank Player::GetReputationRank(uint32 faction) const
5664 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5665 if(!factionEntry)
5666 return MIN_REPUTATION_RANK;
5668 return GetReputationRank(factionEntry);
5671 ReputationRank Player::ReputationToRank(int32 standing) const
5673 int32 Limit = Reputation_Cap + 1;
5674 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5676 Limit -= ReputationRank_Length[i];
5677 if (standing >= Limit )
5678 return ReputationRank(i);
5680 return MIN_REPUTATION_RANK;
5683 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5685 int32 Reputation = GetReputation(factionEntry);
5686 return ReputationToRank(Reputation);
5689 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5691 int32 Reputation = GetBaseReputation(factionEntry);
5692 return ReputationToRank(Reputation);
5695 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5697 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5699 if(!factionTemplateEntry)
5701 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5702 return false;
5705 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5707 // Faction without recorded reputation. Just ignore.
5708 if(!factionEntry)
5709 return false;
5711 return ModifyFactionReputation(factionEntry, DeltaReputation);
5714 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5716 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5717 if (flist)
5719 bool res = false;
5720 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5722 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5723 if(factionEntryCalc)
5724 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5726 return res;
5728 else
5729 return ModifyOneFactionReputation(factionEntry, standing);
5732 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5734 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5735 if (itr != m_factions.end())
5737 int32 BaseRep = GetBaseReputation(factionEntry);
5738 int32 new_rep = BaseRep + itr->second.Standing + standing;
5740 if (new_rep > Reputation_Cap)
5741 new_rep = Reputation_Cap;
5742 else
5743 if (new_rep < Reputation_Bottom)
5744 new_rep = Reputation_Bottom;
5746 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5747 SetFactionAtWar(&itr->second,true);
5749 itr->second.Standing = new_rep - BaseRep;
5750 itr->second.Changed = true;
5752 SetFactionVisible(&itr->second);
5754 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5756 if(uint32 questid = GetQuestSlotQuestId(i))
5758 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5759 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5761 QuestStatusData& q_status = mQuestStatus[questid];
5762 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5764 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5765 if ( CanCompleteQuest( questid ) )
5766 CompleteQuest( questid );
5768 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5770 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5771 IncompleteQuest( questid );
5776 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5777 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5778 SendFactionState(&(itr->second));
5780 return true;
5782 return false;
5785 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5787 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5789 if(!factionTemplateEntry)
5791 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5792 return false;
5795 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5797 // Faction without recorded reputation. Just ignore.
5798 if(!factionEntry)
5799 return false;
5801 return SetFactionReputation(factionEntry, standing);
5804 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5806 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5807 if (flist)
5809 bool res = false;
5810 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5812 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5813 if(factionEntryCalc)
5814 res = SetOneFactionReputation(factionEntryCalc, standing);
5816 return res;
5818 else
5819 return SetOneFactionReputation(factionEntry, standing);
5822 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5824 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5825 if (itr != m_factions.end())
5827 if (standing > Reputation_Cap)
5828 standing = Reputation_Cap;
5829 else
5830 if (standing < Reputation_Bottom)
5831 standing = Reputation_Bottom;
5833 int32 BaseRep = GetBaseReputation(factionEntry);
5834 itr->second.Standing = standing - BaseRep;
5835 itr->second.Changed = true;
5837 SetFactionVisible(&itr->second);
5839 if(ReputationToRank(standing) <= REP_HOSTILE)
5840 SetFactionAtWar(&itr->second,true);
5842 SendFactionState(&(itr->second));
5843 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5844 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5845 return true;
5847 return false;
5850 //Calculate total reputation percent player gain with quest/creature level
5851 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5853 // for grey creature kill received 20%, in other case 100.
5854 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5856 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5858 percent += rep > 0 ? repMod : -repMod;
5860 if(percent <=0)
5861 return 0;
5863 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5866 //Calculates how many reputation points player gains in victim's enemy factions
5867 void Player::RewardReputation(Unit *pVictim, float rate)
5869 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5870 return;
5872 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5874 if(!Rep)
5875 return;
5877 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5879 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5880 donerep1 = int32(donerep1*rate);
5881 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5882 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5883 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5884 ModifyFactionReputation(factionEntry1, donerep1);
5886 // Wiki: Team factions value divided by 2
5887 if(Rep->is_teamaward1)
5889 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5890 if(team1_factionEntry)
5891 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5895 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5897 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5898 donerep2 = int32(donerep2*rate);
5899 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5900 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5901 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5902 ModifyFactionReputation(factionEntry2, donerep2);
5904 // Wiki: Team factions value divided by 2
5905 if(Rep->is_teamaward2)
5907 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5908 if(team2_factionEntry)
5909 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5914 //Calculate how many reputation points player gain with the quest
5915 void Player::RewardReputation(Quest const *pQuest)
5917 // quest reputation reward/loss
5918 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5920 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5922 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5923 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5924 if(factionEntry)
5925 ModifyFactionReputation(factionEntry, rep);
5929 // TODO: implement reputation spillover
5932 void Player::UpdateArenaFields(void)
5934 /* arena calcs go here */
5937 void Player::UpdateHonorFields()
5939 /// called when rewarding honor and at each save
5940 uint64 now = time(NULL);
5941 uint64 today = uint64(time(NULL) / DAY) * DAY;
5943 if(m_lastHonorUpdateTime < today)
5945 uint64 yesterday = today - DAY;
5947 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5949 // update yesterday's contribution
5950 if(m_lastHonorUpdateTime >= yesterday )
5952 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5954 // this is the first update today, reset today's contribution
5955 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5956 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5958 else
5960 // no honor/kills yesterday or today, reset
5961 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5962 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5966 m_lastHonorUpdateTime = now;
5969 ///Calculate the amount of honor gained based on the victim
5970 ///and the size of the group for which the honor is divided
5971 ///An exact honor value can also be given (overriding the calcs)
5972 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5974 // do not reward honor in arenas, but enable onkill spellproc
5975 if(InArena())
5977 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5978 return false;
5980 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5981 return false;
5983 return true;
5986 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5987 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5988 return false;
5990 uint64 victim_guid = 0;
5991 uint32 victim_rank = 0;
5993 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5994 UpdateHonorFields();
5996 if(honor <= 0)
5998 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5999 return false;
6001 victim_guid = uVictim->GetGUID();
6003 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6005 Player *pVictim = (Player *)uVictim;
6007 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6008 return false;
6010 float f = 1; //need for total kills (?? need more info)
6011 uint32 k_grey = 0;
6012 uint32 k_level = getLevel();
6013 uint32 v_level = pVictim->getLevel();
6016 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6017 // [0] Just name
6018 // [1..14] Alliance honor titles and player name
6019 // [15..28] Horde honor titles and player name
6020 // [29..38] Other title and player name
6021 // [39+] Nothing
6022 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6023 // Get Killer titles, CharTitlesEntry::bit_index
6024 // Ranks:
6025 // title[1..14] -> rank[5..18]
6026 // title[15..28] -> rank[5..18]
6027 // title[other] -> 0
6028 if (victim_title == 0)
6029 victim_guid = 0; // Don't show HK: <rank> message, only log.
6030 else if (victim_title < 15)
6031 victim_rank = victim_title + 4;
6032 else if (victim_title < 29)
6033 victim_rank = victim_title - 14 + 4;
6034 else
6035 victim_guid = 0; // Don't show HK: <rank> message, only log.
6038 if(k_level <= 5)
6039 k_grey = 0;
6040 else if( k_level <= 39 )
6041 k_grey = k_level - 5 - k_level/10;
6042 else
6043 k_grey = k_level - 1 - k_level/5;
6045 if(v_level<=k_grey)
6046 return false;
6048 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6050 int32 v_rank =1; //need more info
6052 honor = ((f * diff_level * (190 + v_rank*10))/6);
6053 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6055 // count the number of playerkills in one day
6056 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6057 // and those in a lifetime
6058 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6060 else
6062 Creature *cVictim = (Creature *)uVictim;
6064 if (!cVictim->isRacialLeader())
6065 return false;
6067 honor = 100; // ??? need more info
6068 victim_rank = 19; // HK: Leader
6072 if (uVictim != NULL)
6074 honor *= sWorld.getRate(RATE_HONOR);
6076 if(groupsize > 1)
6077 honor /= groupsize;
6079 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6082 // honor - for show honor points in log
6083 // victim_guid - for show victim name in log
6084 // victim_rank [1..4] HK: <dishonored rank>
6085 // victim_rank [5..19] HK: <alliance\horde rank>
6086 // victim_rank [0,20+] HK: <>
6087 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6088 data << (uint32) honor;
6089 data << (uint64) victim_guid;
6090 data << (uint32) victim_rank;
6092 GetSession()->SendPacket(&data);
6094 // add honor points
6095 ModifyHonorPoints(int32(honor));
6097 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6098 return true;
6101 void Player::ModifyHonorPoints( int32 value )
6103 if(value < 0)
6105 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6106 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6107 else
6108 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6110 else
6111 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6114 void Player::ModifyArenaPoints( int32 value )
6116 if(value < 0)
6118 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6119 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6120 else
6121 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6123 else
6124 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6127 uint32 Player::GetGuildIdFromDB(uint64 guid)
6129 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6130 if(!result)
6131 return 0;
6133 uint32 id = result->Fetch()[0].GetUInt32();
6134 delete result;
6135 return id;
6138 uint32 Player::GetRankFromDB(uint64 guid)
6140 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6141 if( result )
6143 uint32 v = result->Fetch()[0].GetUInt32();
6144 delete result;
6145 return v;
6147 else
6148 return 0;
6151 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6153 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid), type);
6154 if(!result)
6155 return 0;
6157 uint32 id = (*result)[0].GetUInt32();
6158 delete result;
6159 return id;
6162 uint32 Player::GetZoneIdFromDB(uint64 guid)
6164 uint32 guidLow = GUID_LOPART(guid);
6165 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6166 if (!result)
6167 return 0;
6168 Field* fields = result->Fetch();
6169 uint32 zone = fields[0].GetUInt32();
6170 delete result;
6172 if (!zone)
6174 // stored zone is zero, use generic and slow zone detection
6175 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y FROM characters WHERE guid='%u'", guidLow);
6176 if( !result )
6177 return 0;
6178 fields = result->Fetch();
6179 uint32 map = fields[0].GetUInt32();
6180 float posx = fields[1].GetFloat();
6181 float posy = fields[2].GetFloat();
6182 delete result;
6184 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6186 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6189 return zone;
6192 void Player::UpdateArea(uint32 newArea)
6194 // FFA_PVP flags are area and not zone id dependent
6195 // so apply them accordingly
6196 m_areaUpdateId = newArea;
6198 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6200 if(area && (area->flags & AREA_FLAG_ARENA))
6202 if(!isGameMaster())
6203 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6205 else
6207 // remove ffa flag only if not ffapvp realm
6208 // removal in sanctuaries and capitals is handled in zone update
6209 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6210 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6213 UpdateAreaDependentAuras(newArea);
6216 void Player::UpdateZone(uint32 newZone)
6218 m_zoneUpdateId = newZone;
6219 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6221 // zone changed, so area changed as well, update it
6222 UpdateArea(GetAreaId());
6224 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6225 if(!zone)
6226 return;
6228 if (sWorld.getConfig(CONFIG_WEATHER))
6230 Weather *wth = sWorld.FindWeather(zone->ID);
6231 if(wth)
6233 wth->SendWeatherUpdateToPlayer(this);
6235 else
6237 if(!sWorld.AddWeather(zone->ID))
6239 // send fine weather packet to remove old zone's weather
6240 Weather::SendFineWeatherUpdateToPlayer(this);
6245 pvpInfo.inHostileArea =
6246 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6247 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6248 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6249 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6251 if(pvpInfo.inHostileArea) // in hostile area
6253 if(!IsPvP() || pvpInfo.endTimer != 0)
6254 UpdatePvP(true, true);
6256 else // in friendly area
6258 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6259 pvpInfo.endTimer = time(0); // start toggle-off
6262 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6264 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6265 if(sWorld.IsFFAPvPRealm())
6266 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6268 else
6270 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6273 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6275 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6276 SetRestType(REST_TYPE_IN_CITY);
6277 InnEnter(time(0),GetMapId(),0,0,0);
6279 if(sWorld.IsFFAPvPRealm())
6280 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6282 else // anywhere else
6284 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6286 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6288 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6290 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6291 SetRestType(REST_TYPE_NO);
6293 if(sWorld.IsFFAPvPRealm())
6294 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6297 else // not in tavern (leave city then)
6299 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6300 SetRestType(REST_TYPE_NO);
6302 // Set player to FFA PVP when not in rested environment.
6303 if(sWorld.IsFFAPvPRealm())
6304 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6309 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6310 // if player resurrected at teleport this will be applied in resurrect code
6311 if(isAlive())
6312 DestroyZoneLimitedItem( true, newZone );
6314 // recent client version not send leave/join channel packets for built-in local channels
6315 UpdateLocalChannels( newZone );
6317 // group update
6318 if(GetGroup())
6319 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6321 UpdateZoneDependentAuras(newZone);
6324 //If players are too far way of duel flag... then player loose the duel
6325 void Player::CheckDuelDistance(time_t currTime)
6327 if(!duel)
6328 return;
6330 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6331 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6332 if(!obj)
6333 return;
6335 if(duel->outOfBound == 0)
6337 if(!IsWithinDistInMap(obj, 50))
6339 duel->outOfBound = currTime;
6341 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6342 GetSession()->SendPacket(&data);
6345 else
6347 if(IsWithinDistInMap(obj, 40))
6349 duel->outOfBound = 0;
6351 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6352 GetSession()->SendPacket(&data);
6354 else if(currTime >= (duel->outOfBound+10))
6356 DuelComplete(DUEL_FLED);
6361 void Player::DuelComplete(DuelCompleteType type)
6363 // duel not requested
6364 if(!duel)
6365 return;
6367 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6368 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6369 GetSession()->SendPacket(&data);
6370 duel->opponent->GetSession()->SendPacket(&data);
6372 if(type != DUEL_INTERUPTED)
6374 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6375 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6376 data << duel->opponent->GetName();
6377 data << GetName();
6378 SendMessageToSet(&data,true);
6381 // cool-down duel spell
6382 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6384 data<<GetGUID();
6385 data<<uint8(0x0);
6387 data<<(uint32)7266;
6388 data<<uint32(0x0);
6389 GetSession()->SendPacket(&data);
6390 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6391 data<<duel->opponent->GetGUID();
6392 data<<uint8(0x0);
6393 data<<(uint32)7266;
6394 data<<uint32(0x0);
6395 duel->opponent->GetSession()->SendPacket(&data);*/
6397 //Remove Duel Flag object
6398 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6399 if(obj)
6400 duel->initiator->RemoveGameObject(obj,true);
6402 /* remove auras */
6403 std::vector<uint32> auras2remove;
6404 AuraMap const& vAuras = duel->opponent->GetAuras();
6405 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6407 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6408 auras2remove.push_back(i->second->GetId());
6411 for(size_t i=0; i<auras2remove.size(); i++)
6412 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6414 auras2remove.clear();
6415 AuraMap const& auras = GetAuras();
6416 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6418 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6419 auras2remove.push_back(i->second->GetId());
6421 for(size_t i=0; i<auras2remove.size(); i++)
6422 RemoveAurasDueToSpell(auras2remove[i]);
6424 // cleanup combo points
6425 if(GetComboTarget()==duel->opponent->GetGUID())
6426 ClearComboPoints();
6427 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6428 ClearComboPoints();
6430 if(duel->opponent->GetComboTarget()==GetGUID())
6431 duel->opponent->ClearComboPoints();
6432 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6433 duel->opponent->ClearComboPoints();
6435 //cleanups
6436 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6437 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6438 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6439 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6441 delete duel->opponent->duel;
6442 duel->opponent->duel = NULL;
6443 delete duel;
6444 duel = NULL;
6447 //---------------------------------------------------------//
6449 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6451 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6452 return;
6454 // not apply/remove mods for broken item
6455 if(item->IsBroken())
6456 return;
6458 ItemPrototype const *proto = item->GetProto();
6460 if(!proto)
6461 return;
6463 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6465 uint32 attacktype = Player::GetAttackBySlot(slot);
6466 if(attacktype < MAX_ATTACK)
6467 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6469 _ApplyItemBonuses(proto,slot,apply);
6471 if( slot==EQUIPMENT_SLOT_RANGED )
6472 _ApplyAmmoBonuses();
6474 ApplyItemEquipSpell(item,apply);
6475 ApplyEnchantment(item, apply);
6477 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6478 CorrectMetaGemEnchants(slot, apply);
6480 sLog.outDebug("_ApplyItemMods complete.");
6483 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6485 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6486 return;
6488 for (int i = 0; i < 10; i++)
6490 uint32 statType = 0;
6491 int32 val = 0;
6493 if(proto->ScalingStatDistribution)
6495 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6497 statType = ssd->StatMod[i];
6499 if(uint32 modifier = ssd->Modifier[i])
6501 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6502 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6504 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6505 val = (multiplier * modifier) / 10000;
6510 else
6512 statType = proto->ItemStat[i].ItemStatType;
6513 val = float(proto->ItemStat[i].ItemStatValue);
6516 if(val == 0)
6517 continue;
6519 switch (statType)
6521 case ITEM_MOD_MANA:
6522 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6523 break;
6524 case ITEM_MOD_HEALTH: // modify HP
6525 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6526 break;
6527 case ITEM_MOD_AGILITY: // modify agility
6528 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6529 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6530 break;
6531 case ITEM_MOD_STRENGTH: //modify strength
6532 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6533 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6534 break;
6535 case ITEM_MOD_INTELLECT: //modify intellect
6536 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6537 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6538 break;
6539 case ITEM_MOD_SPIRIT: //modify spirit
6540 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6541 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6542 break;
6543 case ITEM_MOD_STAMINA: //modify stamina
6544 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6545 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6546 break;
6547 case ITEM_MOD_DEFENSE_SKILL_RATING:
6548 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6549 break;
6550 case ITEM_MOD_DODGE_RATING:
6551 ApplyRatingMod(CR_DODGE, int32(val), apply);
6552 break;
6553 case ITEM_MOD_PARRY_RATING:
6554 ApplyRatingMod(CR_PARRY, int32(val), apply);
6555 break;
6556 case ITEM_MOD_BLOCK_RATING:
6557 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6558 break;
6559 case ITEM_MOD_HIT_MELEE_RATING:
6560 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6561 break;
6562 case ITEM_MOD_HIT_RANGED_RATING:
6563 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6564 break;
6565 case ITEM_MOD_HIT_SPELL_RATING:
6566 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6567 break;
6568 case ITEM_MOD_CRIT_MELEE_RATING:
6569 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6570 break;
6571 case ITEM_MOD_CRIT_RANGED_RATING:
6572 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6573 break;
6574 case ITEM_MOD_CRIT_SPELL_RATING:
6575 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6576 break;
6577 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6578 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6579 break;
6580 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6581 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6582 break;
6583 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6584 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6585 break;
6586 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6587 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6588 break;
6589 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6590 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6591 break;
6592 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6593 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6594 break;
6595 case ITEM_MOD_HASTE_MELEE_RATING:
6596 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6597 break;
6598 case ITEM_MOD_HASTE_RANGED_RATING:
6599 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6600 break;
6601 case ITEM_MOD_HASTE_SPELL_RATING:
6602 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6603 break;
6604 case ITEM_MOD_HIT_RATING:
6605 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6606 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6607 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6608 break;
6609 case ITEM_MOD_CRIT_RATING:
6610 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6611 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6612 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6613 break;
6614 case ITEM_MOD_HIT_TAKEN_RATING:
6615 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6616 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6617 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6618 break;
6619 case ITEM_MOD_CRIT_TAKEN_RATING:
6620 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6621 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6622 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6623 break;
6624 case ITEM_MOD_RESILIENCE_RATING:
6625 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6626 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6627 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6628 break;
6629 case ITEM_MOD_HASTE_RATING:
6630 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6631 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6632 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6633 break;
6634 case ITEM_MOD_EXPERTISE_RATING:
6635 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6636 break;
6637 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6638 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6639 break;
6643 if (proto->Armor)
6644 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6646 if (proto->Block)
6647 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6649 if (proto->HolyRes)
6650 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6652 if (proto->FireRes)
6653 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6655 if (proto->NatureRes)
6656 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6658 if (proto->FrostRes)
6659 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6661 if (proto->ShadowRes)
6662 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6664 if (proto->ArcaneRes)
6665 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6667 WeaponAttackType attType = BASE_ATTACK;
6668 float damage = 0.0f;
6670 if( slot == EQUIPMENT_SLOT_RANGED && (
6671 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6672 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6674 attType = RANGED_ATTACK;
6676 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6678 attType = OFF_ATTACK;
6681 if (proto->Damage[0].DamageMin > 0 )
6683 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6684 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6685 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6688 if (proto->Damage[0].DamageMax > 0 )
6690 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6691 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6694 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6695 return;
6697 if (proto->Delay)
6699 if(slot == EQUIPMENT_SLOT_RANGED)
6700 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6701 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6702 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6703 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6704 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6707 if(CanModifyStats() && (damage || proto->Delay))
6708 UpdateDamagePhysical(attType);
6711 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6713 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6714 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6715 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6717 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6718 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6719 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6721 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6722 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6723 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6726 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6728 // generic not weapon specific case processes in aura code
6729 if(aura->GetSpellProto()->EquippedItemClass == -1)
6730 return;
6732 BaseModGroup mod = BASEMOD_END;
6733 switch(attackType)
6735 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6736 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6737 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6738 default: return;
6741 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6743 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6747 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6749 // ignore spell mods for not wands
6750 Modifier const* modifier = aura->GetModifier();
6751 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6752 return;
6754 // generic not weapon specific case processes in aura code
6755 if(aura->GetSpellProto()->EquippedItemClass == -1)
6756 return;
6758 UnitMods unitMod = UNIT_MOD_END;
6759 switch(attackType)
6761 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6762 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6763 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6764 default: return;
6767 UnitModifierType unitModType = TOTAL_VALUE;
6768 switch(modifier->m_auraname)
6770 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6771 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6772 default: return;
6775 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6777 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6781 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6783 if(!item)
6784 return;
6786 ItemPrototype const *proto = item->GetProto();
6787 if(!proto)
6788 return;
6790 for (int i = 0; i < 5; i++)
6792 _Spell const& spellData = proto->Spells[i];
6794 // no spell
6795 if(!spellData.SpellId )
6796 continue;
6798 // wrong triggering type
6799 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6800 continue;
6802 // check if it is valid spell
6803 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6804 if(!spellproto)
6805 continue;
6807 ApplyEquipSpell(spellproto,item,apply,form_change);
6811 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6813 if(apply)
6815 // Cannot be used in this stance/form
6816 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6817 return;
6819 if(form_change) // check aura active state from other form
6821 bool found = false;
6822 for (int k=0; k < 3; ++k)
6824 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6825 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6827 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6829 found = true;
6830 break;
6833 if(found)
6834 break;
6837 if(found) // and skip re-cast already active aura at form change
6838 return;
6841 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6843 CastSpell(this,spellInfo,true,item);
6845 else
6847 if(form_change) // check aura compatibility
6849 // Cannot be used in this stance/form
6850 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6851 return; // and remove only not compatible at form change
6854 if(item)
6855 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6856 else
6857 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6861 void Player::UpdateEquipSpellsAtFormChange()
6863 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6865 if(m_items[i] && !m_items[i]->IsBroken())
6867 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6868 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6872 // item set bonuses not dependent from item broken state
6873 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6875 ItemSetEffect* eff = ItemSetEff[setindex];
6876 if(!eff)
6877 continue;
6879 for(uint32 y=0;y<8; ++y)
6881 SpellEntry const* spellInfo = eff->spells[y];
6882 if(!spellInfo)
6883 continue;
6885 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6886 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6891 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6893 if(!item || item->IsBroken())
6894 return;
6896 ItemPrototype const *proto = item->GetProto();
6897 if(!proto)
6898 return;
6900 if (!Target || Target == this )
6901 return;
6903 for (int i = 0; i < 5; i++)
6905 _Spell const& spellData = proto->Spells[i];
6907 // no spell
6908 if(!spellData.SpellId )
6909 continue;
6911 // wrong triggering type
6912 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6913 continue;
6915 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6916 if(!spellInfo)
6918 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6919 continue;
6922 // not allow proc extra attack spell at extra attack
6923 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6924 return;
6926 float chance = spellInfo->procChance;
6928 if(spellData.SpellPPMRate)
6930 uint32 WeaponSpeed = GetAttackTime(attType);
6931 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6933 else if(chance > 100.0f)
6935 chance = GetWeaponProcChance();
6938 if (roll_chance_f(chance))
6939 CastSpell(Target, spellInfo->Id, true, item);
6942 // item combat enchantments
6943 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6945 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6946 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6947 if(!pEnchant) continue;
6948 for (int s=0;s<3;s++)
6950 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6951 continue;
6953 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6954 if (!spellInfo)
6956 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6957 continue;
6960 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6961 if (roll_chance_f(chance))
6963 if(IsPositiveSpell(pEnchant->spellid[s]))
6964 CastSpell(this, pEnchant->spellid[s], true, item);
6965 else
6966 CastSpell(Target, pEnchant->spellid[s], true, item);
6972 void Player::_RemoveAllItemMods()
6974 sLog.outDebug("_RemoveAllItemMods start.");
6976 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6978 if(m_items[i])
6980 ItemPrototype const *proto = m_items[i]->GetProto();
6981 if(!proto)
6982 continue;
6984 // item set bonuses not dependent from item broken state
6985 if(proto->ItemSet)
6986 RemoveItemsSetItem(this,proto);
6988 if(m_items[i]->IsBroken())
6989 continue;
6991 ApplyItemEquipSpell(m_items[i],false);
6992 ApplyEnchantment(m_items[i], false);
6996 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6998 if(m_items[i])
7000 if(m_items[i]->IsBroken())
7001 continue;
7002 ItemPrototype const *proto = m_items[i]->GetProto();
7003 if(!proto)
7004 continue;
7006 uint32 attacktype = Player::GetAttackBySlot(i);
7007 if(attacktype < MAX_ATTACK)
7008 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7010 _ApplyItemBonuses(proto,i, false);
7012 if( i == EQUIPMENT_SLOT_RANGED )
7013 _ApplyAmmoBonuses();
7017 sLog.outDebug("_RemoveAllItemMods complete.");
7020 void Player::_ApplyAllItemMods()
7022 sLog.outDebug("_ApplyAllItemMods start.");
7024 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7026 if(m_items[i])
7028 if(m_items[i]->IsBroken())
7029 continue;
7031 ItemPrototype const *proto = m_items[i]->GetProto();
7032 if(!proto)
7033 continue;
7035 uint32 attacktype = Player::GetAttackBySlot(i);
7036 if(attacktype < MAX_ATTACK)
7037 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7039 _ApplyItemBonuses(proto,i, true);
7041 if( i == EQUIPMENT_SLOT_RANGED )
7042 _ApplyAmmoBonuses();
7046 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7048 if(m_items[i])
7050 ItemPrototype const *proto = m_items[i]->GetProto();
7051 if(!proto)
7052 continue;
7054 // item set bonuses not dependent from item broken state
7055 if(proto->ItemSet)
7056 AddItemsSetItem(this,m_items[i]);
7058 if(m_items[i]->IsBroken())
7059 continue;
7061 ApplyItemEquipSpell(m_items[i],true);
7062 ApplyEnchantment(m_items[i], true);
7066 sLog.outDebug("_ApplyAllItemMods complete.");
7069 void Player::_ApplyAmmoBonuses()
7071 // check ammo
7072 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7073 if(!ammo_id)
7074 return;
7076 float currentAmmoDPS;
7078 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7079 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7080 currentAmmoDPS = 0.0f;
7081 else
7082 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7084 if(currentAmmoDPS == GetAmmoDPS())
7085 return;
7087 m_ammoDPS = currentAmmoDPS;
7089 if(CanModifyStats())
7090 UpdateDamagePhysical(RANGED_ATTACK);
7093 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7095 if(!ammo_proto)
7096 return false;
7098 // check ranged weapon
7099 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7100 if(!weapon || weapon->IsBroken() )
7101 return false;
7103 ItemPrototype const* weapon_proto = weapon->GetProto();
7104 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7105 return false;
7107 // check ammo ws. weapon compatibility
7108 switch(weapon_proto->SubClass)
7110 case ITEM_SUBCLASS_WEAPON_BOW:
7111 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7112 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7113 return false;
7114 break;
7115 case ITEM_SUBCLASS_WEAPON_GUN:
7116 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7117 return false;
7118 break;
7119 default:
7120 return false;
7123 return true;
7126 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7127 Called by remove insignia spell effect */
7128 void Player::RemovedInsignia(Player* looterPlr)
7130 if (!GetBattleGroundId())
7131 return;
7133 // If not released spirit, do it !
7134 if(m_deathTimer > 0)
7136 m_deathTimer = 0;
7137 BuildPlayerRepop();
7138 RepopAtGraveyard();
7141 Corpse *corpse = GetCorpse();
7142 if (!corpse)
7143 return;
7145 // We have to convert player corpse to bones, not to be able to resurrect there
7146 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7147 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7148 if (!bones)
7149 return;
7151 // Now we must make bones lootable, and send player loot
7152 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7154 // We store the level of our player in the gold field
7155 // We retrieve this information at Player::SendLoot()
7156 bones->loot.gold = getLevel();
7157 bones->lootRecipient = looterPlr;
7158 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7161 /*Loot type MUST be
7162 1-corpse, go
7163 2-skinning
7164 3-Fishing
7167 void Player::SendLootRelease( uint64 guid )
7169 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7170 data << uint64(guid) << uint8(1);
7171 SendDirectMessage( &data );
7174 void Player::SendLoot(uint64 guid, LootType loot_type)
7176 Loot *loot = 0;
7177 PermissionTypes permission = ALL_PERMISSION;
7179 sLog.outDebug("Player::SendLoot");
7180 if (IS_GAMEOBJECT_GUID(guid))
7182 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7183 GameObject *go =
7184 ObjectAccessor::GetGameObject(*this, guid);
7186 // not check distance for GO in case owned GO (fishing bobber case, for example)
7187 // And permit out of range GO with no owner in case fishing hole
7188 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7190 SendLootRelease(guid);
7191 return;
7194 loot = &go->loot;
7196 if(go->getLootState() == GO_READY)
7198 uint32 lootid = go->GetLootId();
7200 if(lootid)
7202 sLog.outDebug(" if(lootid)");
7203 loot->clear();
7204 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7207 if(loot_type == LOOT_FISHING)
7208 go->getFishLoot(loot);
7210 go->SetLootState(GO_ACTIVATED);
7213 else if (IS_ITEM_GUID(guid))
7215 Item *item = GetItemByGuid( guid );
7217 if (!item)
7219 SendLootRelease(guid);
7220 return;
7223 if(loot_type == LOOT_DISENCHANTING)
7225 loot = &item->loot;
7227 if(!item->m_lootGenerated)
7229 item->m_lootGenerated = true;
7230 loot->clear();
7231 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7234 else if(loot_type == LOOT_PROSPECTING)
7236 loot = &item->loot;
7238 if(!item->m_lootGenerated)
7240 item->m_lootGenerated = true;
7241 loot->clear();
7242 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7245 else if(loot_type == LOOT_MILLING)
7247 loot = &item->loot;
7249 if(!item->m_lootGenerated)
7251 item->m_lootGenerated = true;
7252 loot->clear();
7253 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this);
7256 else
7258 loot = &item->loot;
7260 if(!item->m_lootGenerated)
7262 item->m_lootGenerated = true;
7263 loot->clear();
7264 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7266 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7270 else if (IS_CORPSE_GUID(guid)) // remove insignia
7272 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7274 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7276 SendLootRelease(guid);
7277 return;
7280 loot = &bones->loot;
7282 if (!bones->lootForBody)
7284 bones->lootForBody = true;
7285 uint32 pLevel = bones->loot.gold;
7286 bones->loot.clear();
7287 // It may need a better formula
7288 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7289 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7292 if (bones->lootRecipient != this)
7293 permission = NONE_PERMISSION;
7295 else
7297 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7299 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7300 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7302 SendLootRelease(guid);
7303 return;
7306 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7308 SendLootRelease(guid);
7309 return;
7312 loot = &creature->loot;
7314 if(loot_type == LOOT_PICKPOCKETING)
7316 if ( !creature->lootForPickPocketed )
7318 creature->lootForPickPocketed = true;
7319 loot->clear();
7321 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7322 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7324 // Generate extra money for pick pocket loot
7325 const uint32 a = urand(0, creature->getLevel()/2);
7326 const uint32 b = urand(0, getLevel()/2);
7327 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7330 else
7332 // the player whose group may loot the corpse
7333 Player *recipient = creature->GetLootRecipient();
7334 if (!recipient)
7336 creature->SetLootRecipient(this);
7337 recipient = this;
7340 if (creature->lootForPickPocketed)
7342 creature->lootForPickPocketed = false;
7343 loot->clear();
7346 if(!creature->lootForBody)
7348 creature->lootForBody = true;
7349 loot->clear();
7351 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7352 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7354 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7356 if(Group* group = recipient->GetGroup())
7358 group->UpdateLooterGuid(creature,true);
7360 switch (group->GetLootMethod())
7362 case GROUP_LOOT:
7363 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7364 group->GroupLoot(recipient->GetGUID(), loot, creature);
7365 break;
7366 case NEED_BEFORE_GREED:
7367 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7368 break;
7369 case MASTER_LOOT:
7370 group->MasterLoot(recipient->GetGUID(), loot, creature);
7371 break;
7372 default:
7373 break;
7378 // possible only if creature->lootForBody && loot->empty() at spell cast check
7379 if (loot_type == LOOT_SKINNING)
7381 loot->clear();
7382 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7384 // set group rights only for loot_type != LOOT_SKINNING
7385 else
7387 if(Group* group = GetGroup())
7389 if( group == recipient->GetGroup() )
7391 if(group->GetLootMethod() == FREE_FOR_ALL)
7392 permission = ALL_PERMISSION;
7393 else if(group->GetLooterGuid() == GetGUID())
7395 if(group->GetLootMethod() == MASTER_LOOT)
7396 permission = MASTER_PERMISSION;
7397 else
7398 permission = ALL_PERMISSION;
7400 else
7401 permission = GROUP_PERMISSION;
7403 else
7404 permission = NONE_PERMISSION;
7406 else if(recipient == this)
7407 permission = ALL_PERMISSION;
7408 else
7409 permission = NONE_PERMISSION;
7414 SetLootGUID(guid);
7416 QuestItemList *q_list = 0;
7417 if (permission != NONE_PERMISSION)
7419 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7420 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7421 if (itr == lootPlayerQuestItems.end())
7422 q_list = loot->FillQuestLoot(this);
7423 else
7424 q_list = itr->second;
7427 QuestItemList *ffa_list = 0;
7428 if (permission != NONE_PERMISSION)
7430 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7431 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7432 if (itr == lootPlayerFFAItems.end())
7433 ffa_list = loot->FillFFALoot(this);
7434 else
7435 ffa_list = itr->second;
7438 QuestItemList *conditional_list = 0;
7439 if (permission != NONE_PERMISSION)
7441 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7442 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7443 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7444 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7445 else
7446 conditional_list = itr->second;
7449 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7450 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7451 loot_type = LOOT_SKINNING;
7453 if(loot_type == LOOT_FISHINGHOLE)
7454 loot_type = LOOT_FISHING;
7456 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7458 data << uint64(guid);
7459 data << uint8(loot_type);
7460 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7462 SendDirectMessage(&data);
7464 // add 'this' player as one of the players that are looting 'loot'
7465 if (permission != NONE_PERMISSION)
7466 loot->AddLooter(GetGUID());
7468 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7469 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7472 void Player::SendNotifyLootMoneyRemoved()
7474 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7475 GetSession()->SendPacket( &data );
7478 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7480 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7481 data << uint8(lootSlot);
7482 GetSession()->SendPacket( &data );
7485 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7487 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7488 data << Field;
7489 data << Value;
7490 GetSession()->SendPacket(&data);
7493 void Player::SendInitWorldStates()
7495 // data depends on zoneid/mapid...
7496 BattleGround* bg = GetBattleGround();
7497 uint16 NumberOfFields = 0;
7498 uint32 mapid = GetMapId();
7499 uint32 zoneid = GetZoneId();
7500 uint32 areaid = GetAreaId();
7501 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7502 // may be exist better way to do this...
7503 switch(zoneid)
7505 case 0:
7506 case 1:
7507 case 4:
7508 case 8:
7509 case 10:
7510 case 11:
7511 case 12:
7512 case 36:
7513 case 38:
7514 case 40:
7515 case 41:
7516 case 51:
7517 case 267:
7518 case 1519:
7519 case 1537:
7520 case 2257:
7521 case 2918:
7522 NumberOfFields = 6;
7523 break;
7524 case 2597:
7525 NumberOfFields = 81;
7526 break;
7527 case 3277:
7528 NumberOfFields = 14;
7529 break;
7530 case 3358:
7531 case 3820:
7532 NumberOfFields = 38;
7533 break;
7534 case 3483:
7535 NumberOfFields = 22;
7536 break;
7537 case 3519:
7538 NumberOfFields = 36;
7539 break;
7540 case 3521:
7541 NumberOfFields = 35;
7542 break;
7543 case 3698:
7544 case 3702:
7545 case 3968:
7546 NumberOfFields = 9;
7547 break;
7548 case 3703:
7549 NumberOfFields = 9;
7550 break;
7551 default:
7552 NumberOfFields = 10;
7553 break;
7556 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7557 data << uint32(mapid); // mapid
7558 data << uint32(zoneid); // zone id
7559 data << uint32(areaid); // area id, new 2.1.0
7560 data << uint16(NumberOfFields); // count of uint64 blocks
7561 data << uint32(0x8d8) << uint32(0x0); // 1
7562 data << uint32(0x8d7) << uint32(0x0); // 2
7563 data << uint32(0x8d6) << uint32(0x0); // 3
7564 data << uint32(0x8d5) << uint32(0x0); // 4
7565 data << uint32(0x8d4) << uint32(0x0); // 5
7566 data << uint32(0x8d3) << uint32(0x0); // 6
7567 if(mapid == 530) // Outland
7569 data << uint32(0x9bf) << uint32(0x0); // 7
7570 data << uint32(0x9bd) << uint32(0xF); // 8
7571 data << uint32(0x9bb) << uint32(0xF); // 9
7573 switch(zoneid)
7575 case 1:
7576 case 11:
7577 case 12:
7578 case 38:
7579 case 40:
7580 case 51:
7581 case 1519:
7582 case 1537:
7583 case 2257:
7584 break;
7585 case 2597: // AV
7586 data << uint32(0x7ae) << uint32(0x1); // 7
7587 data << uint32(0x532) << uint32(0x1); // 8
7588 data << uint32(0x531) << uint32(0x0); // 9
7589 data << uint32(0x52e) << uint32(0x0); // 10
7590 data << uint32(0x571) << uint32(0x0); // 11
7591 data << uint32(0x570) << uint32(0x0); // 12
7592 data << uint32(0x567) << uint32(0x1); // 13
7593 data << uint32(0x566) << uint32(0x1); // 14
7594 data << uint32(0x550) << uint32(0x1); // 15
7595 data << uint32(0x544) << uint32(0x0); // 16
7596 data << uint32(0x536) << uint32(0x0); // 17
7597 data << uint32(0x535) << uint32(0x1); // 18
7598 data << uint32(0x518) << uint32(0x0); // 19
7599 data << uint32(0x517) << uint32(0x0); // 20
7600 data << uint32(0x574) << uint32(0x0); // 21
7601 data << uint32(0x573) << uint32(0x0); // 22
7602 data << uint32(0x572) << uint32(0x0); // 23
7603 data << uint32(0x56f) << uint32(0x0); // 24
7604 data << uint32(0x56e) << uint32(0x0); // 25
7605 data << uint32(0x56d) << uint32(0x0); // 26
7606 data << uint32(0x56c) << uint32(0x0); // 27
7607 data << uint32(0x56b) << uint32(0x0); // 28
7608 data << uint32(0x56a) << uint32(0x1); // 29
7609 data << uint32(0x569) << uint32(0x1); // 30
7610 data << uint32(0x568) << uint32(0x1); // 13
7611 data << uint32(0x565) << uint32(0x0); // 32
7612 data << uint32(0x564) << uint32(0x0); // 33
7613 data << uint32(0x563) << uint32(0x0); // 34
7614 data << uint32(0x562) << uint32(0x0); // 35
7615 data << uint32(0x561) << uint32(0x0); // 36
7616 data << uint32(0x560) << uint32(0x0); // 37
7617 data << uint32(0x55f) << uint32(0x0); // 38
7618 data << uint32(0x55e) << uint32(0x0); // 39
7619 data << uint32(0x55d) << uint32(0x0); // 40
7620 data << uint32(0x3c6) << uint32(0x4); // 41
7621 data << uint32(0x3c4) << uint32(0x6); // 42
7622 data << uint32(0x3c2) << uint32(0x4); // 43
7623 data << uint32(0x516) << uint32(0x1); // 44
7624 data << uint32(0x515) << uint32(0x0); // 45
7625 data << uint32(0x3b6) << uint32(0x6); // 46
7626 data << uint32(0x55c) << uint32(0x0); // 47
7627 data << uint32(0x55b) << uint32(0x0); // 48
7628 data << uint32(0x55a) << uint32(0x0); // 49
7629 data << uint32(0x559) << uint32(0x0); // 50
7630 data << uint32(0x558) << uint32(0x0); // 51
7631 data << uint32(0x557) << uint32(0x0); // 52
7632 data << uint32(0x556) << uint32(0x0); // 53
7633 data << uint32(0x555) << uint32(0x0); // 54
7634 data << uint32(0x554) << uint32(0x1); // 55
7635 data << uint32(0x553) << uint32(0x1); // 56
7636 data << uint32(0x552) << uint32(0x1); // 57
7637 data << uint32(0x551) << uint32(0x1); // 58
7638 data << uint32(0x54f) << uint32(0x0); // 59
7639 data << uint32(0x54e) << uint32(0x0); // 60
7640 data << uint32(0x54d) << uint32(0x1); // 61
7641 data << uint32(0x54c) << uint32(0x0); // 62
7642 data << uint32(0x54b) << uint32(0x0); // 63
7643 data << uint32(0x545) << uint32(0x0); // 64
7644 data << uint32(0x543) << uint32(0x1); // 65
7645 data << uint32(0x542) << uint32(0x0); // 66
7646 data << uint32(0x540) << uint32(0x0); // 67
7647 data << uint32(0x53f) << uint32(0x0); // 68
7648 data << uint32(0x53e) << uint32(0x0); // 69
7649 data << uint32(0x53d) << uint32(0x0); // 70
7650 data << uint32(0x53c) << uint32(0x0); // 71
7651 data << uint32(0x53b) << uint32(0x0); // 72
7652 data << uint32(0x53a) << uint32(0x1); // 73
7653 data << uint32(0x539) << uint32(0x0); // 74
7654 data << uint32(0x538) << uint32(0x0); // 75
7655 data << uint32(0x537) << uint32(0x0); // 76
7656 data << uint32(0x534) << uint32(0x0); // 77
7657 data << uint32(0x533) << uint32(0x0); // 78
7658 data << uint32(0x530) << uint32(0x0); // 79
7659 data << uint32(0x52f) << uint32(0x0); // 80
7660 data << uint32(0x52d) << uint32(0x1); // 81
7661 break;
7662 case 3277: // WS
7663 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7664 bg->FillInitialWorldStates(data);
7665 else
7667 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7668 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7669 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7670 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7671 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7672 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7673 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7674 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7676 break;
7677 case 3358: // AB
7678 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7679 bg->FillInitialWorldStates(data);
7680 else
7682 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7683 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7684 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7685 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7686 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7687 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7688 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7689 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7690 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7691 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7692 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7693 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7694 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7695 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7696 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7697 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7698 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7699 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7700 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7701 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7702 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7703 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7704 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7705 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7706 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7707 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7708 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7709 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7710 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7711 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7712 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7713 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7715 break;
7716 case 3820: // EY
7717 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7718 bg->FillInitialWorldStates(data);
7719 else
7721 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7722 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7723 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7724 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7725 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7726 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7727 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7728 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7729 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7730 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7731 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7732 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7733 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7734 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7735 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7736 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7737 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7738 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7739 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7740 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7741 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7742 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7743 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7744 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7745 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7746 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7747 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7748 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7749 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7750 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7751 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7752 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7753 // and some more ... unknown
7755 break;
7756 case 3483: // Hellfire Peninsula
7757 data << uint32(0x9ba) << uint32(0x1); // 10
7758 data << uint32(0x9b9) << uint32(0x1); // 11
7759 data << uint32(0x9b5) << uint32(0x0); // 12
7760 data << uint32(0x9b4) << uint32(0x1); // 13
7761 data << uint32(0x9b3) << uint32(0x0); // 14
7762 data << uint32(0x9b2) << uint32(0x0); // 15
7763 data << uint32(0x9b1) << uint32(0x1); // 16
7764 data << uint32(0x9b0) << uint32(0x0); // 17
7765 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7766 data << uint32(0x9ac) << uint32(0x0); // 19
7767 data << uint32(0x9a8) << uint32(0x0); // 20
7768 data << uint32(0x9a7) << uint32(0x0); // 21
7769 data << uint32(0x9a6) << uint32(0x1); // 22
7770 break;
7771 case 3519: // Terokkar Forest
7772 data << uint32(0xa41) << uint32(0x0); // 10
7773 data << uint32(0xa40) << uint32(0x14); // 11
7774 data << uint32(0xa3f) << uint32(0x0); // 12
7775 data << uint32(0xa3e) << uint32(0x0); // 13
7776 data << uint32(0xa3d) << uint32(0x5); // 14
7777 data << uint32(0xa3c) << uint32(0x0); // 15
7778 data << uint32(0xa87) << uint32(0x0); // 16
7779 data << uint32(0xa86) << uint32(0x0); // 17
7780 data << uint32(0xa85) << uint32(0x0); // 18
7781 data << uint32(0xa84) << uint32(0x0); // 19
7782 data << uint32(0xa83) << uint32(0x0); // 20
7783 data << uint32(0xa82) << uint32(0x0); // 21
7784 data << uint32(0xa81) << uint32(0x0); // 22
7785 data << uint32(0xa80) << uint32(0x0); // 23
7786 data << uint32(0xa7e) << uint32(0x0); // 24
7787 data << uint32(0xa7d) << uint32(0x0); // 25
7788 data << uint32(0xa7c) << uint32(0x0); // 26
7789 data << uint32(0xa7b) << uint32(0x0); // 27
7790 data << uint32(0xa7a) << uint32(0x0); // 28
7791 data << uint32(0xa79) << uint32(0x0); // 29
7792 data << uint32(0x9d0) << uint32(0x5); // 30
7793 data << uint32(0x9ce) << uint32(0x0); // 31
7794 data << uint32(0x9cd) << uint32(0x0); // 32
7795 data << uint32(0x9cc) << uint32(0x0); // 33
7796 data << uint32(0xa88) << uint32(0x0); // 34
7797 data << uint32(0xad0) << uint32(0x0); // 35
7798 data << uint32(0xacf) << uint32(0x1); // 36
7799 break;
7800 case 3521: // Zangarmarsh
7801 data << uint32(0x9e1) << uint32(0x0); // 10
7802 data << uint32(0x9e0) << uint32(0x0); // 11
7803 data << uint32(0x9df) << uint32(0x0); // 12
7804 data << uint32(0xa5d) << uint32(0x1); // 13
7805 data << uint32(0xa5c) << uint32(0x0); // 14
7806 data << uint32(0xa5b) << uint32(0x1); // 15
7807 data << uint32(0xa5a) << uint32(0x0); // 16
7808 data << uint32(0xa59) << uint32(0x1); // 17
7809 data << uint32(0xa58) << uint32(0x0); // 18
7810 data << uint32(0xa57) << uint32(0x0); // 19
7811 data << uint32(0xa56) << uint32(0x0); // 20
7812 data << uint32(0xa55) << uint32(0x1); // 21
7813 data << uint32(0xa54) << uint32(0x0); // 22
7814 data << uint32(0x9e7) << uint32(0x0); // 23
7815 data << uint32(0x9e6) << uint32(0x0); // 24
7816 data << uint32(0x9e5) << uint32(0x0); // 25
7817 data << uint32(0xa00) << uint32(0x0); // 26
7818 data << uint32(0x9ff) << uint32(0x1); // 27
7819 data << uint32(0x9fe) << uint32(0x0); // 28
7820 data << uint32(0x9fd) << uint32(0x0); // 29
7821 data << uint32(0x9fc) << uint32(0x1); // 30
7822 data << uint32(0x9fb) << uint32(0x0); // 31
7823 data << uint32(0xa62) << uint32(0x0); // 32
7824 data << uint32(0xa61) << uint32(0x1); // 33
7825 data << uint32(0xa60) << uint32(0x1); // 34
7826 data << uint32(0xa5f) << uint32(0x0); // 35
7827 break;
7828 case 3698: // Nagrand Arena
7829 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7830 bg->FillInitialWorldStates(data);
7831 else
7833 data << uint32(0xa0f) << uint32(0x0); // 7
7834 data << uint32(0xa10) << uint32(0x0); // 8
7835 data << uint32(0xa11) << uint32(0x0); // 9 show
7837 break;
7838 case 3702: // Blade's Edge Arena
7839 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7840 bg->FillInitialWorldStates(data);
7841 else
7843 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7844 data << uint32(0x9f1) << uint32(0x0); // 8 green
7845 data << uint32(0x9f3) << uint32(0x0); // 9 show
7847 break;
7848 case 3968: // Ruins of Lordaeron
7849 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7850 bg->FillInitialWorldStates(data);
7851 else
7853 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7854 data << uint32(0xbb9) << uint32(0x0); // 8 green
7855 data << uint32(0xbba) << uint32(0x0); // 9 show
7857 break;
7858 case 3703: // Shattrath City
7859 break;
7860 default:
7861 data << uint32(0x914) << uint32(0x0); // 7
7862 data << uint32(0x913) << uint32(0x0); // 8
7863 data << uint32(0x912) << uint32(0x0); // 9
7864 data << uint32(0x915) << uint32(0x0); // 10
7865 break;
7867 GetSession()->SendPacket(&data);
7870 uint32 Player::GetXPRestBonus(uint32 xp)
7872 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7874 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7875 rested_bonus = xp;
7877 SetRestBonus( GetRestBonus() - rested_bonus);
7879 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7880 return rested_bonus;
7883 void Player::SetBindPoint(uint64 guid)
7885 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7886 data << uint64(guid);
7887 GetSession()->SendPacket( &data );
7890 void Player::SendTalentWipeConfirm(uint64 guid)
7892 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7893 data << uint64(guid);
7894 data << uint32(resetTalentsCost());
7895 GetSession()->SendPacket( &data );
7898 void Player::SendPetSkillWipeConfirm()
7900 Pet* pet = GetPet();
7901 if(!pet)
7902 return;
7903 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7904 data << pet->GetGUID();
7905 data << uint32(pet->resetTalentsCost());
7906 GetSession()->SendPacket( &data );
7909 /*********************************************************/
7910 /*** STORAGE SYSTEM ***/
7911 /*********************************************************/
7913 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7915 assert(i < 3);
7916 if(i < 2 && item)
7918 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7919 return;
7920 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7921 if(charges == 0)
7922 return;
7923 if(charges > 1)
7924 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7925 else if(charges <= 1)
7927 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7928 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7933 void Player::SetSheath( uint32 sheathed )
7935 switch (sheathed)
7937 case SHEATH_STATE_UNARMED: // no prepared weapon
7938 SetVirtualItemSlot(0,NULL);
7939 SetVirtualItemSlot(1,NULL);
7940 SetVirtualItemSlot(2,NULL);
7941 break;
7942 case SHEATH_STATE_MELEE: // prepared melee weapon
7944 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7945 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7946 SetVirtualItemSlot(2,NULL);
7947 }; break;
7948 case SHEATH_STATE_RANGED: // prepared ranged weapon
7949 SetVirtualItemSlot(0,NULL);
7950 SetVirtualItemSlot(1,NULL);
7951 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7952 break;
7953 default:
7954 SetVirtualItemSlot(0,NULL);
7955 SetVirtualItemSlot(1,NULL);
7956 SetVirtualItemSlot(2,NULL);
7957 break;
7959 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7962 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7964 uint8 pClass = getClass();
7966 uint8 slots[4];
7967 slots[0] = NULL_SLOT;
7968 slots[1] = NULL_SLOT;
7969 slots[2] = NULL_SLOT;
7970 slots[3] = NULL_SLOT;
7971 switch( proto->InventoryType )
7973 case INVTYPE_HEAD:
7974 slots[0] = EQUIPMENT_SLOT_HEAD;
7975 break;
7976 case INVTYPE_NECK:
7977 slots[0] = EQUIPMENT_SLOT_NECK;
7978 break;
7979 case INVTYPE_SHOULDERS:
7980 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7981 break;
7982 case INVTYPE_BODY:
7983 slots[0] = EQUIPMENT_SLOT_BODY;
7984 break;
7985 case INVTYPE_CHEST:
7986 slots[0] = EQUIPMENT_SLOT_CHEST;
7987 break;
7988 case INVTYPE_ROBE:
7989 slots[0] = EQUIPMENT_SLOT_CHEST;
7990 break;
7991 case INVTYPE_WAIST:
7992 slots[0] = EQUIPMENT_SLOT_WAIST;
7993 break;
7994 case INVTYPE_LEGS:
7995 slots[0] = EQUIPMENT_SLOT_LEGS;
7996 break;
7997 case INVTYPE_FEET:
7998 slots[0] = EQUIPMENT_SLOT_FEET;
7999 break;
8000 case INVTYPE_WRISTS:
8001 slots[0] = EQUIPMENT_SLOT_WRISTS;
8002 break;
8003 case INVTYPE_HANDS:
8004 slots[0] = EQUIPMENT_SLOT_HANDS;
8005 break;
8006 case INVTYPE_FINGER:
8007 slots[0] = EQUIPMENT_SLOT_FINGER1;
8008 slots[1] = EQUIPMENT_SLOT_FINGER2;
8009 break;
8010 case INVTYPE_TRINKET:
8011 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8012 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8013 break;
8014 case INVTYPE_CLOAK:
8015 slots[0] = EQUIPMENT_SLOT_BACK;
8016 break;
8017 case INVTYPE_WEAPON:
8019 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8021 // suggest offhand slot only if know dual wielding
8022 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8023 if(CanDualWield())
8024 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8025 break;
8027 case INVTYPE_SHIELD:
8028 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8029 break;
8030 case INVTYPE_RANGED:
8031 slots[0] = EQUIPMENT_SLOT_RANGED;
8032 break;
8033 case INVTYPE_2HWEAPON:
8034 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8035 if (CanDualWield() && CanTitanGrip())
8036 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8037 break;
8038 case INVTYPE_TABARD:
8039 slots[0] = EQUIPMENT_SLOT_TABARD;
8040 break;
8041 case INVTYPE_WEAPONMAINHAND:
8042 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8043 break;
8044 case INVTYPE_WEAPONOFFHAND:
8045 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8046 break;
8047 case INVTYPE_HOLDABLE:
8048 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8049 break;
8050 case INVTYPE_THROWN:
8051 slots[0] = EQUIPMENT_SLOT_RANGED;
8052 break;
8053 case INVTYPE_RANGEDRIGHT:
8054 slots[0] = EQUIPMENT_SLOT_RANGED;
8055 break;
8056 case INVTYPE_BAG:
8057 slots[0] = INVENTORY_SLOT_BAG_1;
8058 slots[1] = INVENTORY_SLOT_BAG_2;
8059 slots[2] = INVENTORY_SLOT_BAG_3;
8060 slots[3] = INVENTORY_SLOT_BAG_4;
8061 break;
8062 case INVTYPE_RELIC:
8064 switch(proto->SubClass)
8066 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8067 if (pClass == CLASS_PALADIN)
8068 slots[0] = EQUIPMENT_SLOT_RANGED;
8069 break;
8070 case ITEM_SUBCLASS_ARMOR_IDOL:
8071 if (pClass == CLASS_DRUID)
8072 slots[0] = EQUIPMENT_SLOT_RANGED;
8073 break;
8074 case ITEM_SUBCLASS_ARMOR_TOTEM:
8075 if (pClass == CLASS_SHAMAN)
8076 slots[0] = EQUIPMENT_SLOT_RANGED;
8077 break;
8078 case ITEM_SUBCLASS_ARMOR_MISC:
8079 if (pClass == CLASS_WARLOCK)
8080 slots[0] = EQUIPMENT_SLOT_RANGED;
8081 break;
8082 case ITEM_SUBCLASS_ARMOR_SIGIL:
8083 if (pClass == CLASS_DEATH_KNIGHT)
8084 slots[0] = EQUIPMENT_SLOT_RANGED;
8085 break;
8087 break;
8089 default :
8090 return NULL_SLOT;
8093 if( slot != NULL_SLOT )
8095 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8097 for (int i = 0; i < 4; i++)
8099 if ( slots[i] == slot )
8100 return slot;
8104 else
8106 // search free slot at first
8107 for (int i = 0; i < 4; i++)
8109 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8111 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8112 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8113 return slots[i];
8117 // if not found free and can swap return first appropriate from used
8118 for (int i = 0; i < 4; i++)
8120 if ( slots[i] != NULL_SLOT && swap )
8121 return slots[i];
8125 // no free position
8126 return NULL_SLOT;
8129 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8131 Item *pItem;
8132 uint32 tempcount = 0;
8134 uint8 res = EQUIP_ERR_OK;
8136 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8138 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8139 if( pItem && pItem->GetEntry() == item )
8141 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8142 if(ires==EQUIP_ERR_OK)
8144 tempcount += pItem->GetCount();
8145 if( tempcount >= count )
8146 return EQUIP_ERR_OK;
8148 else
8149 res = ires;
8152 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8154 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8155 if( pItem && pItem->GetEntry() == item )
8157 tempcount += pItem->GetCount();
8158 if( tempcount >= count )
8159 return EQUIP_ERR_OK;
8162 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8164 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8165 if( pItem && pItem->GetEntry() == item )
8167 tempcount += pItem->GetCount();
8168 if( tempcount >= count )
8169 return EQUIP_ERR_OK;
8172 Bag *pBag;
8173 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8175 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8176 if( pBag )
8178 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8180 pItem = GetItemByPos( i, j );
8181 if( pItem && pItem->GetEntry() == item )
8183 tempcount += pItem->GetCount();
8184 if( tempcount >= count )
8185 return EQUIP_ERR_OK;
8191 // not found req. item count and have unequippable items
8192 return res;
8195 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8197 uint32 count = 0;
8198 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8200 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8201 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8202 count += pItem->GetCount();
8204 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8206 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8207 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8208 count += pItem->GetCount();
8210 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8212 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8213 if( pBag )
8214 count += pBag->GetItemCount(item,skipItem);
8217 if(skipItem && skipItem->GetProto()->GemProperties)
8219 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8221 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8222 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8223 count += pItem->GetGemCountWithID(item);
8227 if(inBankAlso)
8229 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8231 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8232 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8233 count += pItem->GetCount();
8235 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8237 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8238 if( pBag )
8239 count += pBag->GetItemCount(item,skipItem);
8242 if(skipItem && skipItem->GetProto()->GemProperties)
8244 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8246 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8247 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8248 count += pItem->GetGemCountWithID(item);
8253 return count;
8256 Item* Player::GetItemByGuid( uint64 guid ) const
8258 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8260 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8261 if( pItem && pItem->GetGUID() == guid )
8262 return pItem;
8264 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8266 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8267 if( pItem && pItem->GetGUID() == guid )
8268 return pItem;
8271 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8273 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8274 if( pBag )
8276 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8278 Item* pItem = pBag->GetItemByPos( j );
8279 if( pItem && pItem->GetGUID() == guid )
8280 return pItem;
8284 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8286 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8287 if( pBag )
8289 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8291 Item* pItem = pBag->GetItemByPos( j );
8292 if( pItem && pItem->GetGUID() == guid )
8293 return pItem;
8298 return NULL;
8301 Item* Player::GetItemByPos( uint16 pos ) const
8303 uint8 bag = pos >> 8;
8304 uint8 slot = pos & 255;
8305 return GetItemByPos( bag, slot );
8308 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8310 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8311 return m_items[slot];
8312 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8313 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8315 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8316 if ( pBag )
8317 return pBag->GetItemByPos(slot);
8319 return NULL;
8322 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8324 uint16 slot;
8325 switch (attackType)
8327 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8328 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8329 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8330 default: return NULL;
8333 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8334 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8335 return NULL;
8337 if(!useable)
8338 return item;
8340 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8341 return NULL;
8343 return item;
8346 Item* Player::GetShield(bool useable) const
8348 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8349 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8350 return NULL;
8352 if(!useable)
8353 return item;
8355 if( item->IsBroken())
8356 return NULL;
8358 return item;
8361 uint32 Player::GetAttackBySlot( uint8 slot )
8363 switch(slot)
8365 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8366 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8367 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8368 default: return MAX_ATTACK;
8372 bool Player::HasBankBagSlot( uint8 slot ) const
8374 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8375 if( slot < maxslot )
8376 return true;
8377 return false;
8380 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8382 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8383 return true;
8384 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8385 return true;
8386 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8387 return true;
8388 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8389 return true;
8390 return false;
8393 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8395 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8396 return true;
8397 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8398 return true;
8399 return false;
8402 bool Player::IsBankPos( uint8 bag, uint8 slot )
8404 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8405 return true;
8406 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8407 return true;
8408 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8409 return true;
8410 return false;
8413 bool Player::IsBagPos( uint16 pos )
8415 uint8 bag = pos >> 8;
8416 uint8 slot = pos & 255;
8417 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8418 return true;
8419 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8420 return true;
8421 return false;
8424 bool Player::IsValidPos( uint8 bag, uint8 slot )
8426 // post selected
8427 if(bag == NULL_BAG)
8428 return true;
8430 if (bag == INVENTORY_SLOT_BAG_0)
8432 // any post selected
8433 if (slot == NULL_SLOT)
8434 return true;
8436 // equipment
8437 if (slot < EQUIPMENT_SLOT_END)
8438 return true;
8440 // bag equip slots
8441 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8442 return true;
8444 // backpack slots
8445 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8446 return true;
8448 // keyring slots
8449 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8450 return true;
8452 // bank main slots
8453 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8454 return true;
8456 // bank bag slots
8457 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8458 return true;
8460 return false;
8463 // bag content slots
8464 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8466 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8467 if(!pBag)
8468 return false;
8470 // any post selected
8471 if (slot == NULL_SLOT)
8472 return true;
8474 return slot < pBag->GetBagSize();
8477 // bank bag content slots
8478 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8480 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8481 if(!pBag)
8482 return false;
8484 // any post selected
8485 if (slot == NULL_SLOT)
8486 return true;
8488 return slot < pBag->GetBagSize();
8491 // where this?
8492 return false;
8496 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8498 uint32 tempcount = 0;
8499 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8501 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8502 if( pItem && pItem->GetEntry() == item )
8504 tempcount += pItem->GetCount();
8505 if( tempcount >= count )
8506 return true;
8509 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8511 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8512 if( pItem && pItem->GetEntry() == item )
8514 tempcount += pItem->GetCount();
8515 if( tempcount >= count )
8516 return true;
8519 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8521 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8523 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8525 Item* pItem = GetItemByPos( i, j );
8526 if( pItem && pItem->GetEntry() == item )
8528 tempcount += pItem->GetCount();
8529 if( tempcount >= count )
8530 return true;
8536 if(inBankAlso)
8538 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8540 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8541 if( pItem && pItem->GetEntry() == item )
8543 tempcount += pItem->GetCount();
8544 if( tempcount >= count )
8545 return true;
8548 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8550 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8552 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8554 Item* pItem = GetItemByPos( i, j );
8555 if( pItem && pItem->GetEntry() == item )
8557 tempcount += pItem->GetCount();
8558 if( tempcount >= count )
8559 return true;
8566 return false;
8569 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8571 Item *pItem;
8572 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8574 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8575 if( pItem && pItem->GetEntry() == item )
8576 return pItem;
8579 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8580 if (pProto && pProto->GemProperties)
8582 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8584 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8585 if( pItem && pItem->GetProto()->Socket[0].Color )
8587 if (pItem->GetGemCountWithID(item) > 0 )
8588 return pItem;
8593 return NULL;
8596 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8598 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8599 if( !pProto )
8601 if(no_space_count)
8602 *no_space_count = count;
8603 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8606 // no maximum
8607 if(pProto->MaxCount == 0)
8608 return EQUIP_ERR_OK;
8610 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8612 if( curcount + count > pProto->MaxCount )
8614 if(no_space_count)
8615 *no_space_count = count +curcount - pProto->MaxCount;
8616 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8619 return EQUIP_ERR_OK;
8622 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8624 Item *pItem;
8625 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8627 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8628 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8629 return true;
8631 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8633 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8634 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8635 return true;
8637 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8639 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8641 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8643 pItem = GetItemByPos( i, j );
8644 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8645 return true;
8649 return false;
8652 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8654 Item* pItem2 = GetItemByPos( bag, slot );
8656 // ignore move item (this slot will be empty at move)
8657 if(pItem2==pSrcItem)
8658 pItem2 = NULL;
8660 uint32 need_space;
8662 // empty specific slot - check item fit to slot
8663 if( !pItem2 || swap )
8665 if( bag == INVENTORY_SLOT_BAG_0 )
8667 // keyring case
8668 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8669 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8671 // vanitypet case
8672 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS))
8673 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8675 // currencytoken case
8676 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8677 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8679 // guestbag case
8680 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS))
8681 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8683 // prevent cheating
8684 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8685 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8687 else
8689 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8690 if( !pBag )
8691 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8693 ItemPrototype const* pBagProto = pBag->GetProto();
8694 if( !pBagProto )
8695 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8697 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8698 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8701 // non empty stack with space
8702 need_space = pProto->Stackable;
8704 // non empty slot, check item type
8705 else
8707 // check item type
8708 if(pItem2->GetEntry() != pProto->ItemId)
8709 return EQUIP_ERR_ITEM_CANT_STACK;
8711 // check free space
8712 if(pItem2->GetCount() >= pProto->Stackable)
8713 return EQUIP_ERR_ITEM_CANT_STACK;
8715 need_space = pProto->Stackable - pItem2->GetCount();
8718 if(need_space > count)
8719 need_space = count;
8721 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8722 if(!newPosition.isContainedIn(dest))
8724 dest.push_back(newPosition);
8725 count -= need_space;
8727 return EQUIP_ERR_OK;
8730 uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
8732 // skip specific bag already processed in first called _CanStoreItem_InBag
8733 if(bag==skip_bag)
8734 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8736 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8737 if( !pBag )
8738 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8740 ItemPrototype const* pBagProto = pBag->GetProto();
8741 if( !pBagProto )
8742 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8744 // specialized bag mode or non-specilized
8745 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8746 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8748 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8749 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8751 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8753 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8754 if(j==skip_slot)
8755 continue;
8757 Item* pItem2 = GetItemByPos( bag, j );
8759 // ignore move item (this slot will be empty at move)
8760 if(pItem2==pSrcItem)
8761 pItem2 = NULL;
8763 // if merge skip empty, if !merge skip non-empty
8764 if((pItem2!=NULL)!=merge)
8765 continue;
8767 if( pItem2 )
8769 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8771 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8772 if(need_space > count)
8773 need_space = count;
8775 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8776 if(!newPosition.isContainedIn(dest))
8778 dest.push_back(newPosition);
8779 count -= need_space;
8781 if(count==0)
8782 return EQUIP_ERR_OK;
8786 else
8788 uint32 need_space = pProto->Stackable;
8789 if(need_space > count)
8790 need_space = count;
8792 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8793 if(!newPosition.isContainedIn(dest))
8795 dest.push_back(newPosition);
8796 count -= need_space;
8798 if(count==0)
8799 return EQUIP_ERR_OK;
8803 return EQUIP_ERR_OK;
8806 uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
8808 for(uint32 j = slot_begin; j < slot_end; j++)
8810 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8811 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8812 continue;
8814 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8816 // ignore move item (this slot will be empty at move)
8817 if(pItem2==pSrcItem)
8818 pItem2 = NULL;
8820 // if merge skip empty, if !merge skip non-empty
8821 if((pItem2!=NULL)!=merge)
8822 continue;
8824 if( pItem2 )
8826 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8828 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8829 if(need_space > count)
8830 need_space = count;
8831 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8832 if(!newPosition.isContainedIn(dest))
8834 dest.push_back(newPosition);
8835 count -= need_space;
8837 if(count==0)
8838 return EQUIP_ERR_OK;
8842 else
8844 uint32 need_space = pProto->Stackable;
8845 if(need_space > count)
8846 need_space = count;
8848 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8849 if(!newPosition.isContainedIn(dest))
8851 dest.push_back(newPosition);
8852 count -= need_space;
8854 if(count==0)
8855 return EQUIP_ERR_OK;
8859 return EQUIP_ERR_OK;
8862 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8864 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8866 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8867 if( !pProto )
8869 if(no_space_count)
8870 *no_space_count = count;
8871 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8874 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8876 if(no_space_count)
8877 *no_space_count = count;
8878 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8881 // check count of items (skip for auto move for same player from bank)
8882 uint32 no_similar_count = 0; // can't store this amount similar items
8883 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8884 if(res!=EQUIP_ERR_OK)
8886 if(count==no_similar_count)
8888 if(no_space_count)
8889 *no_space_count = no_similar_count;
8890 return res;
8892 count -= no_similar_count;
8895 // in specific slot
8896 if( bag != NULL_BAG && slot != NULL_SLOT )
8898 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8899 if(res!=EQUIP_ERR_OK)
8901 if(no_space_count)
8902 *no_space_count = count + no_similar_count;
8903 return res;
8906 if(count==0)
8908 if(no_similar_count==0)
8909 return EQUIP_ERR_OK;
8911 if(no_space_count)
8912 *no_space_count = count + no_similar_count;
8913 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8917 // not specific slot or have space for partly store only in specific slot
8919 // in specific bag
8920 if( bag != NULL_BAG )
8922 // search stack in bag for merge to
8923 if( pProto->Stackable > 1 )
8925 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8927 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8928 if(res!=EQUIP_ERR_OK)
8930 if(no_space_count)
8931 *no_space_count = count + no_similar_count;
8932 return res;
8935 if(count==0)
8937 if(no_similar_count==0)
8938 return EQUIP_ERR_OK;
8940 if(no_space_count)
8941 *no_space_count = count + no_similar_count;
8942 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8945 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8946 if(res!=EQUIP_ERR_OK)
8948 if(no_space_count)
8949 *no_space_count = count + no_similar_count;
8950 return res;
8953 if(count==0)
8955 if(no_similar_count==0)
8956 return EQUIP_ERR_OK;
8958 if(no_space_count)
8959 *no_space_count = count + no_similar_count;
8960 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8963 else // equipped bag
8965 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8966 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8967 if(res!=EQUIP_ERR_OK)
8968 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8970 if(res!=EQUIP_ERR_OK)
8972 if(no_space_count)
8973 *no_space_count = count + no_similar_count;
8974 return res;
8977 if(count==0)
8979 if(no_similar_count==0)
8980 return EQUIP_ERR_OK;
8982 if(no_space_count)
8983 *no_space_count = count + no_similar_count;
8984 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8989 // search free slot in bag for place to
8990 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8992 // search free slot - keyring case
8993 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8995 uint32 keyringSize = GetMaxKeyringSize();
8996 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8997 if(res!=EQUIP_ERR_OK)
8999 if(no_space_count)
9000 *no_space_count = count + no_similar_count;
9001 return res;
9004 if(count==0)
9006 if(no_similar_count==0)
9007 return EQUIP_ERR_OK;
9009 if(no_space_count)
9010 *no_space_count = count + no_similar_count;
9011 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9014 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9016 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9017 if(res!=EQUIP_ERR_OK)
9019 if(no_space_count)
9020 *no_space_count = count + no_similar_count;
9021 return res;
9024 if(count==0)
9026 if(no_similar_count==0)
9027 return EQUIP_ERR_OK;
9029 if(no_space_count)
9030 *no_space_count = count + no_similar_count;
9031 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9034 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9036 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9037 if(res!=EQUIP_ERR_OK)
9039 if(no_space_count)
9040 *no_space_count = count + no_similar_count;
9041 return res;
9044 if(count==0)
9046 if(no_similar_count==0)
9047 return EQUIP_ERR_OK;
9049 if(no_space_count)
9050 *no_space_count = count + no_similar_count;
9051 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9054 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9056 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9057 if(res!=EQUIP_ERR_OK)
9059 if(no_space_count)
9060 *no_space_count = count + no_similar_count;
9061 return res;
9064 if(count==0)
9066 if(no_similar_count==0)
9067 return EQUIP_ERR_OK;
9069 if(no_space_count)
9070 *no_space_count = count + no_similar_count;
9071 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9075 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9076 if(res!=EQUIP_ERR_OK)
9078 if(no_space_count)
9079 *no_space_count = count + no_similar_count;
9080 return res;
9083 if(count==0)
9085 if(no_similar_count==0)
9086 return EQUIP_ERR_OK;
9088 if(no_space_count)
9089 *no_space_count = count + no_similar_count;
9090 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9093 else // equipped bag
9095 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9096 if(res!=EQUIP_ERR_OK)
9097 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9099 if(res!=EQUIP_ERR_OK)
9101 if(no_space_count)
9102 *no_space_count = count + no_similar_count;
9103 return res;
9106 if(count==0)
9108 if(no_similar_count==0)
9109 return EQUIP_ERR_OK;
9111 if(no_space_count)
9112 *no_space_count = count + no_similar_count;
9113 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9118 // not specific bag or have space for partly store only in specific bag
9120 // search stack for merge to
9121 if( pProto->Stackable > 1 )
9123 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9124 if(res!=EQUIP_ERR_OK)
9126 if(no_space_count)
9127 *no_space_count = count + no_similar_count;
9128 return res;
9131 if(count==0)
9133 if(no_similar_count==0)
9134 return EQUIP_ERR_OK;
9136 if(no_space_count)
9137 *no_space_count = count + no_similar_count;
9138 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9141 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9142 if(res!=EQUIP_ERR_OK)
9144 if(no_space_count)
9145 *no_space_count = count + no_similar_count;
9146 return res;
9149 if(count==0)
9151 if(no_similar_count==0)
9152 return EQUIP_ERR_OK;
9154 if(no_space_count)
9155 *no_space_count = count + no_similar_count;
9156 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9159 if( pProto->BagFamily )
9161 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9163 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9164 if(res!=EQUIP_ERR_OK)
9165 continue;
9167 if(count==0)
9169 if(no_similar_count==0)
9170 return EQUIP_ERR_OK;
9172 if(no_space_count)
9173 *no_space_count = count + no_similar_count;
9174 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9179 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9181 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9182 if(res!=EQUIP_ERR_OK)
9183 continue;
9185 if(count==0)
9187 if(no_similar_count==0)
9188 return EQUIP_ERR_OK;
9190 if(no_space_count)
9191 *no_space_count = count + no_similar_count;
9192 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9197 // search free slot - special bag case
9198 if( pProto->BagFamily )
9200 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9202 uint32 keyringSize = GetMaxKeyringSize();
9203 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9204 if(res!=EQUIP_ERR_OK)
9206 if(no_space_count)
9207 *no_space_count = count + no_similar_count;
9208 return res;
9211 if(count==0)
9213 if(no_similar_count==0)
9214 return EQUIP_ERR_OK;
9216 if(no_space_count)
9217 *no_space_count = count + no_similar_count;
9218 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9221 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9223 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9224 if(res!=EQUIP_ERR_OK)
9226 if(no_space_count)
9227 *no_space_count = count + no_similar_count;
9228 return res;
9231 if(count==0)
9233 if(no_similar_count==0)
9234 return EQUIP_ERR_OK;
9236 if(no_space_count)
9237 *no_space_count = count + no_similar_count;
9238 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9241 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9243 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9244 if(res!=EQUIP_ERR_OK)
9246 if(no_space_count)
9247 *no_space_count = count + no_similar_count;
9248 return res;
9251 if(count==0)
9253 if(no_similar_count==0)
9254 return EQUIP_ERR_OK;
9256 if(no_space_count)
9257 *no_space_count = count + no_similar_count;
9258 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9261 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9263 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9264 if(res!=EQUIP_ERR_OK)
9266 if(no_space_count)
9267 *no_space_count = count + no_similar_count;
9268 return res;
9271 if(count==0)
9273 if(no_similar_count==0)
9274 return EQUIP_ERR_OK;
9276 if(no_space_count)
9277 *no_space_count = count + no_similar_count;
9278 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9282 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9284 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9285 if(res!=EQUIP_ERR_OK)
9286 continue;
9288 if(count==0)
9290 if(no_similar_count==0)
9291 return EQUIP_ERR_OK;
9293 if(no_space_count)
9294 *no_space_count = count + no_similar_count;
9295 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9300 // search free slot
9301 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9302 if(res!=EQUIP_ERR_OK)
9304 if(no_space_count)
9305 *no_space_count = count + no_similar_count;
9306 return res;
9309 if(count==0)
9311 if(no_similar_count==0)
9312 return EQUIP_ERR_OK;
9314 if(no_space_count)
9315 *no_space_count = count + no_similar_count;
9316 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9319 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9321 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9322 if(res!=EQUIP_ERR_OK)
9323 continue;
9325 if(count==0)
9327 if(no_similar_count==0)
9328 return EQUIP_ERR_OK;
9330 if(no_space_count)
9331 *no_space_count = count + no_similar_count;
9332 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9336 if(no_space_count)
9337 *no_space_count = count + no_similar_count;
9339 return EQUIP_ERR_INVENTORY_FULL;
9342 //////////////////////////////////////////////////////////////////////////
9343 uint8 Player::CanStoreItems( Item **pItems,int count) const
9345 Item *pItem2;
9347 // fill space table
9348 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9349 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9350 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9351 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9352 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9353 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9355 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9356 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9357 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9358 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9359 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9360 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9362 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9364 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9366 if (pItem2 && !pItem2->IsInTrade())
9368 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9372 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9374 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9376 if (pItem2 && !pItem2->IsInTrade())
9378 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9382 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9384 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9386 if (pItem2 && !pItem2->IsInTrade())
9388 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9392 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9394 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9396 if (pItem2 && !pItem2->IsInTrade())
9398 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9402 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9404 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9406 if (pItem2 && !pItem2->IsInTrade())
9408 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9412 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9414 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9416 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9418 pItem2 = GetItemByPos( i, j );
9419 if (pItem2 && !pItem2->IsInTrade())
9421 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9427 // check free space for all items
9428 for (int k=0;k<count;k++)
9430 Item *pItem = pItems[k];
9432 // no item
9433 if (!pItem) continue;
9435 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9436 ItemPrototype const *pProto = pItem->GetProto();
9438 // strange item
9439 if( !pProto )
9440 return EQUIP_ERR_ITEM_NOT_FOUND;
9442 // item it 'bind'
9443 if(pItem->IsBindedNotWith(GetGUID()))
9444 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9446 Bag *pBag;
9447 ItemPrototype const *pBagProto;
9449 // item is 'one item only'
9450 uint8 res = CanTakeMoreSimilarItems(pItem);
9451 if(res != EQUIP_ERR_OK)
9452 return res;
9454 // search stack for merge to
9455 if( pProto->Stackable > 1 )
9457 bool b_found = false;
9459 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9461 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9462 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9464 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9465 b_found = true;
9466 break;
9469 if (b_found) continue;
9471 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9473 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9474 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9476 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9477 b_found = true;
9478 break;
9481 if (b_found) continue;
9483 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9485 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9486 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9488 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9489 b_found = true;
9490 break;
9493 if (b_found) continue;
9495 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9497 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9498 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9500 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9501 b_found = true;
9502 break;
9505 if (b_found) continue;
9507 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9509 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9510 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9512 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9513 b_found = true;
9514 break;
9517 if (b_found) continue;
9519 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9521 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9522 if( pBag )
9524 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9526 pItem2 = GetItemByPos( t, j );
9527 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9529 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9530 b_found = true;
9531 break;
9536 if (b_found) continue;
9539 // special bag case
9540 if( pProto->BagFamily )
9542 bool b_found = false;
9543 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9545 uint32 keyringSize = GetMaxKeyringSize();
9546 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9548 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9550 inv_keys[t-KEYRING_SLOT_START] = 1;
9551 b_found = true;
9552 break;
9557 if (b_found) continue;
9559 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9561 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9563 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9565 inv_pets[t-VANITYPET_SLOT_START] = 1;
9566 b_found = true;
9567 break;
9572 if (b_found) continue;
9574 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9576 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9578 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9580 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9581 b_found = true;
9582 break;
9587 if (b_found) continue;
9589 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9591 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9593 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9595 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9596 b_found = true;
9597 break;
9602 if (b_found) continue;
9604 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9606 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9607 if( pBag )
9609 pBagProto = pBag->GetProto();
9611 // not plain container check
9612 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9613 ItemCanGoIntoBag(pProto,pBagProto) )
9615 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9617 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9619 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9620 b_found = true;
9621 break;
9627 if (b_found) continue;
9630 // search free slot
9631 bool b_found = false;
9632 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9634 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9636 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9637 b_found = true;
9638 break;
9641 if (b_found) continue;
9643 // search free slot in bags
9644 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9646 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9647 if( pBag )
9649 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9651 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9653 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9654 b_found = true;
9655 break;
9661 // no free slot found?
9662 if (!b_found)
9663 return EQUIP_ERR_INVENTORY_FULL;
9666 return EQUIP_ERR_OK;
9669 //////////////////////////////////////////////////////////////////////////
9670 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9672 dest = 0;
9673 Item *pItem = Item::CreateItem( item, 1, this );
9674 if( pItem )
9676 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9677 delete pItem;
9678 return result;
9681 return EQUIP_ERR_ITEM_NOT_FOUND;
9684 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9686 dest = 0;
9687 if( pItem )
9689 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9690 ItemPrototype const *pProto = pItem->GetProto();
9691 if( pProto )
9693 // May be here should be more stronger checks; STUNNED checked
9694 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9695 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9696 return EQUIP_ERR_YOU_ARE_STUNNED;
9698 if(pItem->IsBindedNotWith(GetGUID()))
9699 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9701 // check count of items (skip for auto move for same player from bank)
9702 uint8 res = CanTakeMoreSimilarItems(pItem);
9703 if(res != EQUIP_ERR_OK)
9704 return res;
9706 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9707 // - combat
9708 // - in-progress arenas
9709 if( !pProto->CanChangeEquipStateInCombat() )
9711 if( isInCombat() )
9712 return EQUIP_ERR_NOT_IN_COMBAT;
9714 if(BattleGround* bg = GetBattleGround())
9715 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9716 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9719 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9720 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9722 if(IsNonMeleeSpellCasted(false))
9723 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9725 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9726 if( eslot == NULL_SLOT )
9727 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9729 uint8 msg = CanUseItem( pItem , not_loading );
9730 if( msg != EQUIP_ERR_OK )
9731 return msg;
9732 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9733 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9735 // check unique-equipped on item
9736 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9738 // there is an equip limit on this item
9739 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9740 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9741 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9744 // check unique-equipped on gems
9745 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9747 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9748 if(!enchant_id)
9749 continue;
9750 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9751 if(!enchantEntry)
9752 continue;
9754 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9755 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9757 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9758 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9759 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9763 // check unique-equipped special item classes
9764 if (pProto->Class == ITEM_CLASS_QUIVER)
9766 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9768 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9770 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9772 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9773 (!swap || pBag->GetSlot() != eslot ) )
9775 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9776 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9777 else
9778 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9785 uint32 type = pProto->InventoryType;
9787 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9789 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9791 if(!CanDualWield())
9792 return EQUIP_ERR_CANT_DUAL_WIELD;
9794 else if (type == INVTYPE_2HWEAPON)
9796 if(!CanDualWield() || !CanTitanGrip())
9797 return EQUIP_ERR_CANT_DUAL_WIELD;
9800 if(IsTwoHandUsed())
9801 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9804 // equip two-hand weapon case (with possible unequip 2 items)
9805 if( type == INVTYPE_2HWEAPON )
9807 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9809 if (!CanTitanGrip())
9810 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9812 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9813 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9815 if (!CanTitanGrip())
9817 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9818 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9819 ItemPosCountVec off_dest;
9820 if( offItem && (!not_loading ||
9821 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9822 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9823 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9826 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9827 return EQUIP_ERR_OK;
9830 if( !swap )
9831 return EQUIP_ERR_ITEM_NOT_FOUND;
9832 else
9833 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9836 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9838 // Applied only to equipped items and bank bags
9839 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9840 return EQUIP_ERR_OK;
9842 Item* pItem = GetItemByPos(pos);
9844 // Applied only to existed equipped item
9845 if( !pItem )
9846 return EQUIP_ERR_OK;
9848 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9850 ItemPrototype const *pProto = pItem->GetProto();
9851 if( !pProto )
9852 return EQUIP_ERR_ITEM_NOT_FOUND;
9854 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9855 // - combat
9856 // - in-progress arenas
9857 if( !pProto->CanChangeEquipStateInCombat() )
9859 if( isInCombat() )
9860 return EQUIP_ERR_NOT_IN_COMBAT;
9862 if(BattleGround* bg = GetBattleGround())
9863 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9864 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9867 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9868 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9870 return EQUIP_ERR_OK;
9873 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9875 if( !pItem )
9876 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9878 uint32 count = pItem->GetCount();
9880 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9881 ItemPrototype const *pProto = pItem->GetProto();
9882 if( !pProto )
9883 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9885 if( pItem->IsBindedNotWith(GetGUID()) )
9886 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9888 // check count of items (skip for auto move for same player from bank)
9889 uint8 res = CanTakeMoreSimilarItems(pItem);
9890 if(res != EQUIP_ERR_OK)
9891 return res;
9893 // in specific slot
9894 if( bag != NULL_BAG && slot != NULL_SLOT )
9896 if( pProto->InventoryType == INVTYPE_BAG )
9898 Bag *pBag = (Bag*)pItem;
9899 if( pBag )
9901 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9903 if( !HasBankBagSlot( slot ) )
9904 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9905 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9906 return cantuse;
9908 else
9910 if( !pBag->IsEmpty() )
9911 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9915 else
9917 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9918 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9921 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9922 if(res!=EQUIP_ERR_OK)
9923 return res;
9925 if(count==0)
9926 return EQUIP_ERR_OK;
9929 // not specific slot or have space for partly store only in specific slot
9931 // in specific bag
9932 if( bag != NULL_BAG )
9934 if( pProto->InventoryType == INVTYPE_BAG )
9936 Bag *pBag = (Bag*)pItem;
9937 if( pBag && !pBag->IsEmpty() )
9938 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9941 // search stack in bag for merge to
9942 if( pProto->Stackable > 1 )
9944 if( bag == INVENTORY_SLOT_BAG_0 )
9946 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9947 if(res!=EQUIP_ERR_OK)
9948 return res;
9950 if(count==0)
9951 return EQUIP_ERR_OK;
9953 else
9955 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9956 if(res!=EQUIP_ERR_OK)
9957 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9959 if(res!=EQUIP_ERR_OK)
9960 return res;
9962 if(count==0)
9963 return EQUIP_ERR_OK;
9967 // search free slot in bag
9968 if( bag == INVENTORY_SLOT_BAG_0 )
9970 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9971 if(res!=EQUIP_ERR_OK)
9972 return res;
9974 if(count==0)
9975 return EQUIP_ERR_OK;
9977 else
9979 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9980 if(res!=EQUIP_ERR_OK)
9981 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9983 if(res!=EQUIP_ERR_OK)
9984 return res;
9986 if(count==0)
9987 return EQUIP_ERR_OK;
9991 // not specific bag or have space for partly store only in specific bag
9993 // search stack for merge to
9994 if( pProto->Stackable > 1 )
9996 // in slots
9997 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9998 if(res!=EQUIP_ERR_OK)
9999 return res;
10001 if(count==0)
10002 return EQUIP_ERR_OK;
10004 // in special bags
10005 if( pProto->BagFamily )
10007 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10009 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10010 if(res!=EQUIP_ERR_OK)
10011 continue;
10013 if(count==0)
10014 return EQUIP_ERR_OK;
10018 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10020 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10021 if(res!=EQUIP_ERR_OK)
10022 continue;
10024 if(count==0)
10025 return EQUIP_ERR_OK;
10029 // search free place in special bag
10030 if( pProto->BagFamily )
10032 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10034 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10035 if(res!=EQUIP_ERR_OK)
10036 continue;
10038 if(count==0)
10039 return EQUIP_ERR_OK;
10043 // search free space
10044 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10045 if(res!=EQUIP_ERR_OK)
10046 return res;
10048 if(count==0)
10049 return EQUIP_ERR_OK;
10051 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10053 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10054 if(res!=EQUIP_ERR_OK)
10055 continue;
10057 if(count==0)
10058 return EQUIP_ERR_OK;
10060 return EQUIP_ERR_BANK_FULL;
10063 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10065 if( pItem )
10067 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10068 if( !isAlive() && not_loading )
10069 return EQUIP_ERR_YOU_ARE_DEAD;
10070 //if( isStunned() )
10071 // return EQUIP_ERR_YOU_ARE_STUNNED;
10072 ItemPrototype const *pProto = pItem->GetProto();
10073 if( pProto )
10075 if( pItem->IsBindedNotWith(GetGUID()) )
10076 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10077 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10078 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10079 if( pItem->GetSkill() != 0 )
10081 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10082 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10084 if( pProto->RequiredSkill != 0 )
10086 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10087 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10088 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10089 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10091 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10092 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10093 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10094 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10095 if( getLevel() < pProto->RequiredLevel )
10096 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10097 return EQUIP_ERR_OK;
10100 return EQUIP_ERR_ITEM_NOT_FOUND;
10103 bool Player::CanUseItem( ItemPrototype const *pProto )
10105 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10107 if( pProto )
10109 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10110 return false;
10111 if( pProto->RequiredSkill != 0 )
10113 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10114 return false;
10115 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10116 return false;
10118 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10119 return false;
10120 if( getLevel() < pProto->RequiredLevel )
10121 return false;
10122 return true;
10124 return false;
10127 uint8 Player::CanUseAmmo( uint32 item ) const
10129 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10130 if( !isAlive() )
10131 return EQUIP_ERR_YOU_ARE_DEAD;
10132 //if( isStunned() )
10133 // return EQUIP_ERR_YOU_ARE_STUNNED;
10134 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10135 if( pProto )
10137 if( pProto->InventoryType!= INVTYPE_AMMO )
10138 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10139 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10140 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10141 if( pProto->RequiredSkill != 0 )
10143 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10144 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10145 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10146 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10148 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10149 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10150 /*if( GetReputation() < pProto->RequiredReputation )
10151 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10153 if( getLevel() < pProto->RequiredLevel )
10154 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10156 // Requires No Ammo
10157 if(GetDummyAura(46699))
10158 return EQUIP_ERR_BAG_FULL6;
10160 return EQUIP_ERR_OK;
10162 return EQUIP_ERR_ITEM_NOT_FOUND;
10165 void Player::SetAmmo( uint32 item )
10167 if(!item)
10168 return;
10170 // already set
10171 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10172 return;
10174 // check ammo
10175 if(item)
10177 uint8 msg = CanUseAmmo( item );
10178 if( msg != EQUIP_ERR_OK )
10180 SendEquipError( msg, NULL, NULL );
10181 return;
10185 SetUInt32Value(PLAYER_AMMO_ID, item);
10187 _ApplyAmmoBonuses();
10190 void Player::RemoveAmmo()
10192 SetUInt32Value(PLAYER_AMMO_ID, 0);
10194 m_ammoDPS = 0.0f;
10196 if(CanModifyStats())
10197 UpdateDamagePhysical(RANGED_ATTACK);
10200 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10201 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10203 uint32 count = 0;
10204 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10205 count += itr->count;
10207 Item *pItem = Item::CreateItem( item, count, this );
10208 if( pItem )
10210 ItemAddedQuestCheck( item, count );
10211 if(randomPropertyId)
10212 pItem->SetItemRandomProperties(randomPropertyId);
10213 pItem = StoreItem( dest, pItem, update );
10215 return pItem;
10218 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10220 if( !pItem )
10221 return NULL;
10223 Item* lastItem = pItem;
10225 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10227 uint16 pos = itr->pos;
10228 uint32 count = itr->count;
10230 ++itr;
10232 if(itr == dest.end())
10234 lastItem = _StoreItem(pos,pItem,count,false,update);
10235 break;
10238 lastItem = _StoreItem(pos,pItem,count,true,update);
10241 return lastItem;
10244 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10245 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10247 if( !pItem )
10248 return NULL;
10250 uint8 bag = pos >> 8;
10251 uint8 slot = pos & 255;
10253 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10255 Item *pItem2 = GetItemByPos( bag, slot );
10257 if( !pItem2 )
10259 if(clone)
10260 pItem = pItem->CloneItem(count,this);
10261 else
10262 pItem->SetCount(count);
10264 if(!pItem)
10265 return NULL;
10267 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10268 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10269 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10270 pItem->SetBinding( true );
10272 if( bag == INVENTORY_SLOT_BAG_0 )
10274 m_items[slot] = pItem;
10275 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10276 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10277 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10279 pItem->SetSlot( slot );
10280 pItem->SetContainer( NULL );
10282 if( IsInWorld() && update )
10284 pItem->AddToWorld();
10285 pItem->SendUpdateToPlayer( this );
10288 pItem->SetState(ITEM_CHANGED, this);
10290 else
10292 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10293 if( pBag )
10295 pBag->StoreItem( slot, pItem, update );
10296 if( IsInWorld() && update )
10298 pItem->AddToWorld();
10299 pItem->SendUpdateToPlayer( this );
10301 pItem->SetState(ITEM_CHANGED, this);
10302 pBag->SetState(ITEM_CHANGED, this);
10306 AddEnchantmentDurations(pItem);
10307 AddItemDurations(pItem);
10309 return pItem;
10311 else
10313 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10314 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10315 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10316 pItem2->SetBinding( true );
10318 pItem2->SetCount( pItem2->GetCount() + count );
10319 if( IsInWorld() && update )
10320 pItem2->SendUpdateToPlayer( this );
10322 if(!clone)
10324 // delete item (it not in any slot currently)
10325 if( IsInWorld() && update )
10327 pItem->RemoveFromWorld();
10328 pItem->DestroyForPlayer( this );
10331 RemoveEnchantmentDurations(pItem);
10332 RemoveItemDurations(pItem);
10334 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10335 pItem->SetState(ITEM_REMOVED, this);
10337 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10338 AddEnchantmentDurations(pItem2);
10340 pItem2->SetState(ITEM_CHANGED, this);
10342 return pItem2;
10346 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10348 Item *pItem = Item::CreateItem( item, 1, this );
10349 if( pItem )
10351 ItemAddedQuestCheck( item, 1 );
10352 Item * retItem = EquipItem( pos, pItem, update );
10354 return retItem;
10356 return NULL;
10359 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10361 if( pItem )
10363 AddEnchantmentDurations(pItem);
10364 AddItemDurations(pItem);
10366 uint8 bag = pos >> 8;
10367 uint8 slot = pos & 255;
10369 Item *pItem2 = GetItemByPos( bag, slot );
10371 if( !pItem2 )
10373 VisualizeItem( slot, pItem);
10375 if(isAlive())
10377 ItemPrototype const *pProto = pItem->GetProto();
10379 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10380 if(pProto && pProto->ItemSet)
10381 AddItemsSetItem(this,pItem);
10383 _ApplyItemMods(pItem, slot, true);
10385 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10387 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10389 if (getClass() == CLASS_ROGUE)
10390 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10392 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10394 if (!spellProto)
10395 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10396 else
10398 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10400 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10401 data << uint64(GetGUID());
10402 data << uint8(1);
10403 data << uint32(cooldownSpell);
10404 data << uint32(0);
10405 GetSession()->SendPacket(&data);
10410 if( IsInWorld() && update )
10412 pItem->AddToWorld();
10413 pItem->SendUpdateToPlayer( this );
10416 ApplyEquipCooldown(pItem);
10418 if( slot == EQUIPMENT_SLOT_MAINHAND )
10419 UpdateExpertise(BASE_ATTACK);
10420 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10421 UpdateExpertise(OFF_ATTACK);
10423 else
10425 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10426 if( IsInWorld() && update )
10427 pItem2->SendUpdateToPlayer( this );
10429 // delete item (it not in any slot currently)
10430 //pItem->DeleteFromDB();
10431 if( IsInWorld() && update )
10433 pItem->RemoveFromWorld();
10434 pItem->DestroyForPlayer( this );
10437 RemoveEnchantmentDurations(pItem);
10438 RemoveItemDurations(pItem);
10440 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10441 pItem->SetState(ITEM_REMOVED, this);
10442 pItem2->SetState(ITEM_CHANGED, this);
10444 ApplyEquipCooldown(pItem2);
10446 return pItem2;
10450 return pItem;
10453 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10455 if( pItem )
10457 AddEnchantmentDurations(pItem);
10458 AddItemDurations(pItem);
10460 uint8 slot = pos & 255;
10461 VisualizeItem( slot, pItem);
10463 if( IsInWorld() )
10465 pItem->AddToWorld();
10466 pItem->SendUpdateToPlayer( this );
10471 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10473 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10474 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10475 // entry // Size: 1
10476 // inspected enchantments // Size: 6
10477 // ? // Size: 5
10478 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10479 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10480 // // = 16
10482 if(pItem)
10484 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10486 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10487 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10489 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10490 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10492 // Use SetInt16Value to prevent set high part to FFFF for negative value
10493 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10494 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10496 else
10498 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10500 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10501 SetUInt32Value(VisibleBase + 0, 0);
10503 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10504 SetUInt32Value(VisibleBase + 1 + i, 0);
10506 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10507 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10511 void Player::VisualizeItem( uint8 slot, Item *pItem)
10513 if(!pItem)
10514 return;
10516 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10517 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10518 pItem->SetBinding( true );
10520 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10522 m_items[slot] = pItem;
10523 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10524 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10525 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10526 pItem->SetSlot( slot );
10527 pItem->SetContainer( NULL );
10529 if( slot < EQUIPMENT_SLOT_END )
10530 SetVisibleItemSlot(slot,pItem);
10532 pItem->SetState(ITEM_CHANGED, this);
10535 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10537 // note: removeitem does not actually change the item
10538 // it only takes the item out of storage temporarily
10539 // note2: if removeitem is to be used for delinking
10540 // the item must be removed from the player's updatequeue
10542 Item *pItem = GetItemByPos( bag, slot );
10543 if( pItem )
10545 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10547 RemoveEnchantmentDurations(pItem);
10548 RemoveItemDurations(pItem);
10550 if( bag == INVENTORY_SLOT_BAG_0 )
10552 if ( slot < INVENTORY_SLOT_BAG_END )
10554 ItemPrototype const *pProto = pItem->GetProto();
10555 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10557 if(pProto && pProto->ItemSet)
10558 RemoveItemsSetItem(this,pProto);
10560 _ApplyItemMods(pItem, slot, false);
10562 // remove item dependent auras and casts (only weapon and armor slots)
10563 if(slot < EQUIPMENT_SLOT_END)
10564 RemoveItemDependentAurasAndCasts(pItem);
10566 // remove held enchantments
10567 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10569 if (pItem->GetItemSuffixFactor())
10571 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10572 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10574 else
10576 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10577 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10582 m_items[slot] = NULL;
10583 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10585 if ( slot < EQUIPMENT_SLOT_END )
10586 SetVisibleItemSlot(slot,NULL);
10588 else
10590 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10591 if( pBag )
10592 pBag->RemoveItem(slot, update);
10594 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10595 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10596 pItem->SetSlot( NULL_SLOT );
10597 if( IsInWorld() && update )
10598 pItem->SendUpdateToPlayer( this );
10600 if( slot == EQUIPMENT_SLOT_MAINHAND )
10601 UpdateExpertise(BASE_ATTACK);
10602 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10603 UpdateExpertise(OFF_ATTACK);
10607 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10608 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10610 if(Item* it = GetItemByPos(bag,slot))
10612 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10613 RemoveItem( bag,slot,update);
10614 it->RemoveFromUpdateQueueOf(this);
10615 if(it->IsInWorld())
10617 it->RemoveFromWorld();
10618 it->DestroyForPlayer( this );
10623 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10624 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10626 // update quest counters
10627 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10629 // store item
10630 Item* pLastItem = StoreItem( dest, pItem, update);
10632 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10633 if(pLastItem==pItem)
10635 // update owner for last item (this can be original item with wrong owner
10636 if(pLastItem->GetOwnerGUID() != GetGUID())
10637 pLastItem->SetOwnerGUID(GetGUID());
10639 // if this original item then it need create record in inventory
10640 // in case trade we already have item in other player inventory
10641 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10645 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10647 Item *pItem = GetItemByPos( bag, slot );
10648 if( pItem )
10650 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10652 // start from destroy contained items (only equipped bag can have its)
10653 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10655 for (int i = 0; i < MAX_BAG_SIZE; i++)
10656 DestroyItem(slot,i,update);
10659 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10660 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10662 RemoveEnchantmentDurations(pItem);
10663 RemoveItemDurations(pItem);
10665 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10667 if( bag == INVENTORY_SLOT_BAG_0 )
10669 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10671 // equipment and equipped bags can have applied bonuses
10672 if ( slot < INVENTORY_SLOT_BAG_END )
10674 ItemPrototype const *pProto = pItem->GetProto();
10676 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10677 if(pProto && pProto->ItemSet)
10678 RemoveItemsSetItem(this,pProto);
10680 _ApplyItemMods(pItem, slot, false);
10683 if ( slot < EQUIPMENT_SLOT_END )
10685 // remove item dependent auras and casts (only weapon and armor slots)
10686 RemoveItemDependentAurasAndCasts(pItem);
10688 // equipment visual show
10689 SetVisibleItemSlot(slot,NULL);
10692 m_items[slot] = NULL;
10694 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10695 pBag->RemoveItem(slot, update);
10697 if( IsInWorld() && update )
10699 pItem->RemoveFromWorld();
10700 pItem->DestroyForPlayer(this);
10703 //pItem->SetOwnerGUID(0);
10704 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10705 pItem->SetSlot( NULL_SLOT );
10706 pItem->SetState(ITEM_REMOVED, this);
10710 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10712 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10713 Item *pItem;
10714 ItemPrototype const *pProto;
10715 uint32 remcount = 0;
10717 // in inventory
10718 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10720 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10721 if( pItem && pItem->GetEntry() == item )
10723 if( pItem->GetCount() + remcount <= count )
10725 // all items in inventory can unequipped
10726 remcount += pItem->GetCount();
10727 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10729 if(remcount >=count)
10730 return;
10732 else
10734 pProto = pItem->GetProto();
10735 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10736 pItem->SetCount( pItem->GetCount() - count + remcount );
10737 if( IsInWorld() & update )
10738 pItem->SendUpdateToPlayer( this );
10739 pItem->SetState(ITEM_CHANGED, this);
10740 return;
10744 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10746 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10747 if( pItem && pItem->GetEntry() == item )
10749 if( pItem->GetCount() + remcount <= count )
10751 // all keys can be unequipped
10752 remcount += pItem->GetCount();
10753 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10755 if(remcount >=count)
10756 return;
10758 else
10760 pProto = pItem->GetProto();
10761 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10762 pItem->SetCount( pItem->GetCount() - count + remcount );
10763 if( IsInWorld() & update )
10764 pItem->SendUpdateToPlayer( this );
10765 pItem->SetState(ITEM_CHANGED, this);
10766 return;
10771 // in inventory bags
10772 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10774 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10776 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10778 pItem = pBag->GetItemByPos(j);
10779 if( pItem && pItem->GetEntry() == item )
10781 // all items in bags can be unequipped
10782 if( pItem->GetCount() + remcount <= count )
10784 remcount += pItem->GetCount();
10785 DestroyItem( i, j, update );
10787 if(remcount >=count)
10788 return;
10790 else
10792 pProto = pItem->GetProto();
10793 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10794 pItem->SetCount( pItem->GetCount() - count + remcount );
10795 if( IsInWorld() && update )
10796 pItem->SendUpdateToPlayer( this );
10797 pItem->SetState(ITEM_CHANGED, this);
10798 return;
10805 // in equipment and bag list
10806 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10808 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10809 if( pItem && pItem->GetEntry() == item )
10811 if( pItem->GetCount() + remcount <= count )
10813 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10815 remcount += pItem->GetCount();
10816 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10818 if(remcount >=count)
10819 return;
10822 else
10824 pProto = pItem->GetProto();
10825 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10826 pItem->SetCount( pItem->GetCount() - count + remcount );
10827 if( IsInWorld() & update )
10828 pItem->SendUpdateToPlayer( this );
10829 pItem->SetState(ITEM_CHANGED, this);
10830 return;
10836 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10838 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10840 // in inventory
10841 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10843 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10844 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10845 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10847 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10849 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10850 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10851 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10854 // in inventory bags
10855 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10857 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10858 if( pBag )
10860 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10862 Item* pItem = pBag->GetItemByPos(j);
10863 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10864 DestroyItem( i, j, update);
10869 // in equipment and bag list
10870 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10872 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10873 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10874 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10878 void Player::DestroyConjuredItems( bool update )
10880 // used when entering arena
10881 // destroys all conjured items
10882 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10884 // in inventory
10885 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10887 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10888 if( pItem && pItem->GetProto() &&
10889 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10890 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10891 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10894 // in inventory bags
10895 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10897 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10898 if( pBag )
10900 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10902 Item* pItem = pBag->GetItemByPos(j);
10903 if( pItem && pItem->GetProto() &&
10904 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10905 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10906 DestroyItem( i, j, update);
10911 // in equipment and bag list
10912 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10914 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10915 if( pItem && pItem->GetProto() &&
10916 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10917 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10918 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10922 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10924 if(!pItem)
10925 return;
10927 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10929 if( pItem->GetCount() <= count )
10931 count-= pItem->GetCount();
10933 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10935 else
10937 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10938 pItem->SetCount( pItem->GetCount() - count );
10939 count = 0;
10940 if( IsInWorld() & update )
10941 pItem->SendUpdateToPlayer( this );
10942 pItem->SetState(ITEM_CHANGED, this);
10946 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10948 uint8 srcbag = src >> 8;
10949 uint8 srcslot = src & 255;
10951 uint8 dstbag = dst >> 8;
10952 uint8 dstslot = dst & 255;
10954 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10955 if( !pSrcItem )
10957 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10958 return;
10961 // not let split all items (can be only at cheating)
10962 if(pSrcItem->GetCount() == count)
10964 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10965 return;
10968 // not let split more existed items (can be only at cheating)
10969 if(pSrcItem->GetCount() < count)
10971 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10972 return;
10975 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10977 //best error message found for attempting to split while looting
10978 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10979 return;
10982 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10983 Item *pNewItem = pSrcItem->CloneItem( count, this );
10984 if( !pNewItem )
10986 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10987 return;
10990 if( IsInventoryPos( dst ) )
10992 // change item amount before check (for unique max count check)
10993 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10995 ItemPosCountVec dest;
10996 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10997 if( msg != EQUIP_ERR_OK )
10999 delete pNewItem;
11000 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11001 SendEquipError( msg, pSrcItem, NULL );
11002 return;
11005 if( IsInWorld() )
11006 pSrcItem->SendUpdateToPlayer( this );
11007 pSrcItem->SetState(ITEM_CHANGED, this);
11008 StoreItem( dest, pNewItem, true);
11010 else if( IsBankPos ( dst ) )
11012 // change item amount before check (for unique max count check)
11013 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11015 ItemPosCountVec dest;
11016 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11017 if( msg != EQUIP_ERR_OK )
11019 delete pNewItem;
11020 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11021 SendEquipError( msg, pSrcItem, NULL );
11022 return;
11025 if( IsInWorld() )
11026 pSrcItem->SendUpdateToPlayer( this );
11027 pSrcItem->SetState(ITEM_CHANGED, this);
11028 BankItem( dest, pNewItem, true);
11030 else if( IsEquipmentPos ( dst ) )
11032 // change item amount before check (for unique max count check), provide space for splitted items
11033 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11035 uint16 dest;
11036 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11037 if( msg != EQUIP_ERR_OK )
11039 delete pNewItem;
11040 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11041 SendEquipError( msg, pSrcItem, NULL );
11042 return;
11045 if( IsInWorld() )
11046 pSrcItem->SendUpdateToPlayer( this );
11047 pSrcItem->SetState(ITEM_CHANGED, this);
11048 EquipItem( dest, pNewItem, true);
11049 AutoUnequipOffhandIfNeed();
11053 void Player::SwapItem( uint16 src, uint16 dst )
11055 uint8 srcbag = src >> 8;
11056 uint8 srcslot = src & 255;
11058 uint8 dstbag = dst >> 8;
11059 uint8 dstslot = dst & 255;
11061 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11062 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11064 if( !pSrcItem )
11065 return;
11067 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11069 if(!isAlive() )
11071 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11072 return;
11075 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11077 //best error message found for attempting to swap while looting
11078 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11079 return;
11082 // check unequip potability for equipped items and bank bags
11083 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11085 // bags can be swapped with empty bag slots
11086 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
11087 if(msg != EQUIP_ERR_OK)
11089 SendEquipError( msg, pSrcItem, pDstItem );
11090 return;
11094 // prevent put equipped/bank bag in self
11095 if( IsBagPos ( src ) && srcslot == dstbag)
11097 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11098 return;
11101 if( !pDstItem )
11103 if( IsInventoryPos( dst ) )
11105 ItemPosCountVec dest;
11106 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11107 if( msg != EQUIP_ERR_OK )
11109 SendEquipError( msg, pSrcItem, NULL );
11110 return;
11113 RemoveItem(srcbag, srcslot, true);
11114 StoreItem( dest, pSrcItem, true);
11116 else if( IsBankPos ( dst ) )
11118 ItemPosCountVec dest;
11119 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11120 if( msg != EQUIP_ERR_OK )
11122 SendEquipError( msg, pSrcItem, NULL );
11123 return;
11126 RemoveItem(srcbag, srcslot, true);
11127 BankItem( dest, pSrcItem, true);
11129 else if( IsEquipmentPos ( dst ) )
11131 uint16 dest;
11132 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11133 if( msg != EQUIP_ERR_OK )
11135 SendEquipError( msg, pSrcItem, NULL );
11136 return;
11139 RemoveItem(srcbag, srcslot, true);
11140 EquipItem( dest, pSrcItem, true);
11141 AutoUnequipOffhandIfNeed();
11144 else // if (!pDstItem)
11146 if(pDstItem->m_lootGenerated) // prevent swap looting item
11148 //best error message found for attempting to swap while looting
11149 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11150 return;
11153 // check unequip potability for equipped items and bank bags
11154 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11156 // bags can be swapped with empty bag slots
11157 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11158 if(msg != EQUIP_ERR_OK)
11160 SendEquipError( msg, pSrcItem, pDstItem );
11161 return;
11165 // attempt merge to / fill target item
11167 uint8 msg;
11168 ItemPosCountVec sDest;
11169 uint16 eDest;
11170 if( IsInventoryPos( dst ) )
11171 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11172 else if( IsBankPos ( dst ) )
11173 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11174 else if( IsEquipmentPos ( dst ) )
11175 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11176 else
11177 return;
11179 // can be merge/fill
11180 if(msg == EQUIP_ERR_OK)
11182 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
11184 RemoveItem(srcbag, srcslot, true);
11186 if( IsInventoryPos( dst ) )
11187 StoreItem( sDest, pSrcItem, true);
11188 else if( IsBankPos ( dst ) )
11189 BankItem( sDest, pSrcItem, true);
11190 else if( IsEquipmentPos ( dst ) )
11192 EquipItem( eDest, pSrcItem, true);
11193 AutoUnequipOffhandIfNeed();
11196 else
11198 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
11199 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
11200 pSrcItem->SetState(ITEM_CHANGED, this);
11201 pDstItem->SetState(ITEM_CHANGED, this);
11202 if( IsInWorld() )
11204 pSrcItem->SendUpdateToPlayer( this );
11205 pDstItem->SendUpdateToPlayer( this );
11208 return;
11212 // impossible merge/fill, do real swap
11213 uint8 msg;
11215 // check src->dest move possibility
11216 ItemPosCountVec sDest;
11217 uint16 eDest;
11218 if( IsInventoryPos( dst ) )
11219 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11220 else if( IsBankPos( dst ) )
11221 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11222 else if( IsEquipmentPos( dst ) )
11224 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11225 if( msg == EQUIP_ERR_OK )
11226 msg = CanUnequipItem( eDest, true );
11229 if( msg != EQUIP_ERR_OK )
11231 SendEquipError( msg, pSrcItem, pDstItem );
11232 return;
11235 // check dest->src move possibility
11236 ItemPosCountVec sDest2;
11237 uint16 eDest2;
11238 if( IsInventoryPos( src ) )
11239 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11240 else if( IsBankPos( src ) )
11241 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11242 else if( IsEquipmentPos( src ) )
11244 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11245 if( msg == EQUIP_ERR_OK )
11246 msg = CanUnequipItem( eDest2, true);
11249 if( msg != EQUIP_ERR_OK )
11251 SendEquipError( msg, pDstItem, pSrcItem );
11252 return;
11255 // now do moves, remove...
11256 RemoveItem(dstbag, dstslot, false);
11257 RemoveItem(srcbag, srcslot, false);
11259 // add to dest
11260 if( IsInventoryPos( dst ) )
11261 StoreItem(sDest, pSrcItem, true);
11262 else if( IsBankPos( dst ) )
11263 BankItem(sDest, pSrcItem, true);
11264 else if( IsEquipmentPos( dst ) )
11265 EquipItem(eDest, pSrcItem, true);
11267 // add to src
11268 if( IsInventoryPos( src ) )
11269 StoreItem(sDest2, pDstItem, true);
11270 else if( IsBankPos( src ) )
11271 BankItem(sDest2, pDstItem, true);
11272 else if( IsEquipmentPos( src ) )
11273 EquipItem(eDest2, pDstItem, true);
11275 AutoUnequipOffhandIfNeed();
11279 void Player::AddItemToBuyBackSlot( Item *pItem )
11281 if( pItem )
11283 uint32 slot = m_currentBuybackSlot;
11284 // if current back slot non-empty search oldest or free
11285 if(m_items[slot])
11287 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11288 uint32 oldest_slot = BUYBACK_SLOT_START;
11290 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11292 // found empty
11293 if(!m_items[i])
11295 slot = i;
11296 break;
11299 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11301 if(oldest_time > i_time)
11303 oldest_time = i_time;
11304 oldest_slot = i;
11308 // find oldest
11309 slot = oldest_slot;
11312 RemoveItemFromBuyBackSlot( slot, true );
11313 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11315 m_items[slot] = pItem;
11316 time_t base = time(NULL);
11317 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11318 uint32 eslot = slot - BUYBACK_SLOT_START;
11320 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11321 ItemPrototype const *pProto = pItem->GetProto();
11322 if( pProto )
11323 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11324 else
11325 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11326 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11328 // move to next (for non filled list is move most optimized choice)
11329 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11330 ++m_currentBuybackSlot;
11334 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11336 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11337 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11338 return m_items[slot];
11339 return NULL;
11342 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11344 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11345 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11347 Item *pItem = m_items[slot];
11348 if( pItem )
11350 pItem->RemoveFromWorld();
11351 if(del) pItem->SetState(ITEM_REMOVED, this);
11354 m_items[slot] = NULL;
11356 uint32 eslot = slot - BUYBACK_SLOT_START;
11357 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11358 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11359 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11361 // if current backslot is filled set to now free slot
11362 if(m_items[m_currentBuybackSlot])
11363 m_currentBuybackSlot = slot;
11367 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11369 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11370 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11371 data << uint8(msg);
11373 if(msg)
11375 data << uint64(pItem ? pItem->GetGUID() : 0);
11376 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11377 data << uint8(0); // not 0 there...
11379 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11381 uint32 level = 0;
11383 if(pItem)
11384 if(ItemPrototype const* proto = pItem->GetProto())
11385 level = proto->RequiredLevel;
11387 data << uint32(level); // new 2.4.0
11390 GetSession()->SendPacket(&data);
11393 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11395 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11396 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11397 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11398 data << uint32(item);
11399 if( param > 0 )
11400 data << uint32(param);
11401 data << uint8(msg);
11402 GetSession()->SendPacket(&data);
11405 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11407 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11408 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11409 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11410 data << uint64(guid);
11411 if( param > 0 )
11412 data << uint32(param);
11413 data << uint8(msg);
11414 GetSession()->SendPacket(&data);
11417 void Player::ClearTrade()
11419 tradeGold = 0;
11420 acceptTrade = false;
11421 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11422 tradeItems[i] = NULL_SLOT;
11425 void Player::TradeCancel(bool sendback)
11427 if(pTrader)
11429 // send yellow "Trade canceled" message to both traders
11430 WorldSession* ws;
11431 ws = GetSession();
11432 if(sendback)
11433 ws->SendCancelTrade();
11434 ws = pTrader->GetSession();
11435 if(!ws->PlayerLogout())
11436 ws->SendCancelTrade();
11438 // cleanup
11439 ClearTrade();
11440 pTrader->ClearTrade();
11441 // prevent loss of reference
11442 pTrader->pTrader = NULL;
11443 pTrader = NULL;
11447 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11449 if(m_itemDuration.empty())
11450 return;
11452 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11454 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11456 Item* item = *itr;
11457 ++itr; // current element can be erased in UpdateDuration
11459 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11460 item->UpdateDuration(this,time);
11464 void Player::UpdateEnchantTime(uint32 time)
11466 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11468 assert(itr->item);
11469 next=itr;
11470 if(!itr->item->GetEnchantmentId(itr->slot))
11472 next = m_enchantDuration.erase(itr);
11474 else if(itr->leftduration <= time)
11476 ApplyEnchantment(itr->item,itr->slot,false,false);
11477 itr->item->ClearEnchantment(itr->slot);
11478 next = m_enchantDuration.erase(itr);
11480 else if(itr->leftduration > time)
11482 itr->leftduration -= time;
11483 ++next;
11488 void Player::AddEnchantmentDurations(Item *item)
11490 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11492 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11493 continue;
11495 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11496 if( duration > 0 )
11497 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11501 void Player::RemoveEnchantmentDurations(Item *item)
11503 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11505 if(itr->item == item)
11507 // save duration in item
11508 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11509 itr = m_enchantDuration.erase(itr);
11511 else
11512 ++itr;
11516 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11518 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11519 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11521 next = itr;
11522 if(itr->slot==slot)
11524 if(itr->item && itr->item->GetEnchantmentId(slot))
11526 // remove from stats
11527 ApplyEnchantment(itr->item,slot,false,false);
11528 // remove visual
11529 itr->item->ClearEnchantment(slot);
11531 // remove from update list
11532 next = m_enchantDuration.erase(itr);
11534 else
11535 ++next;
11538 // remove enchants from inventory items
11539 // NOTE: no need to remove these from stats, since these aren't equipped
11540 // in inventory
11541 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11543 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11544 if( pItem && pItem->GetEnchantmentId(slot) )
11545 pItem->ClearEnchantment(slot);
11548 // in inventory bags
11549 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11551 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11552 if( pBag )
11554 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11556 Item* pItem = pBag->GetItemByPos(j);
11557 if( pItem && pItem->GetEnchantmentId(slot) )
11558 pItem->ClearEnchantment(slot);
11564 // duration == 0 will remove item enchant
11565 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11567 if(!item)
11568 return;
11570 if(slot >= MAX_ENCHANTMENT_SLOT)
11571 return;
11573 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11575 if(itr->item == item && itr->slot == slot)
11577 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11578 m_enchantDuration.erase(itr);
11579 break;
11582 if(item && duration > 0 )
11584 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11585 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11589 void Player::ApplyEnchantment(Item *item,bool apply)
11591 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11592 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11595 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11597 if(!item)
11598 return;
11600 if(!item->IsEquipped())
11601 return;
11603 if(slot >= MAX_ENCHANTMENT_SLOT)
11604 return;
11606 uint32 enchant_id = item->GetEnchantmentId(slot);
11607 if(!enchant_id)
11608 return;
11610 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11611 if(!pEnchant)
11612 return;
11614 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11615 return;
11617 for (int s=0; s<3; s++)
11619 uint32 enchant_display_type = pEnchant->type[s];
11620 uint32 enchant_amount = pEnchant->amount[s];
11621 uint32 enchant_spell_id = pEnchant->spellid[s];
11623 switch(enchant_display_type)
11625 case ITEM_ENCHANTMENT_TYPE_NONE:
11626 break;
11627 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11628 // processed in Player::CastItemCombatSpell
11629 break;
11630 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11631 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11632 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11633 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11634 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11635 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11636 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11637 break;
11638 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11639 if(enchant_spell_id)
11641 if(apply)
11643 int32 basepoints = 0;
11644 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11645 if (item->GetItemRandomPropertyId())
11647 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11648 if (item_rand)
11650 // Search enchant_amount
11651 for (int k=0; k<3; k++)
11653 if(item_rand->enchant_id[k] == enchant_id)
11655 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11656 break;
11661 // Cast custom spell vs all equal basepoints getted from enchant_amount
11662 if (basepoints)
11663 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11664 else
11665 CastSpell(this,enchant_spell_id,true,item);
11667 else
11668 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11670 break;
11671 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11672 if (!enchant_amount)
11674 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11675 if(item_rand)
11677 for (int k=0; k<3; k++)
11679 if(item_rand->enchant_id[k] == enchant_id)
11681 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11682 break;
11688 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11689 break;
11690 case ITEM_ENCHANTMENT_TYPE_STAT:
11692 if (!enchant_amount)
11694 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11695 if(item_rand_suffix)
11697 for (int k=0; k<3; k++)
11699 if(item_rand_suffix->enchant_id[k] == enchant_id)
11701 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11702 break;
11708 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11709 switch (enchant_spell_id)
11711 case ITEM_MOD_AGILITY:
11712 sLog.outDebug("+ %u AGILITY",enchant_amount);
11713 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11714 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11715 break;
11716 case ITEM_MOD_STRENGTH:
11717 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11718 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11719 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11720 break;
11721 case ITEM_MOD_INTELLECT:
11722 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11723 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11724 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11725 break;
11726 case ITEM_MOD_SPIRIT:
11727 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11728 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11729 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11730 break;
11731 case ITEM_MOD_STAMINA:
11732 sLog.outDebug("+ %u STAMINA",enchant_amount);
11733 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11734 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11735 break;
11736 case ITEM_MOD_DEFENSE_SKILL_RATING:
11737 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11738 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11739 break;
11740 case ITEM_MOD_DODGE_RATING:
11741 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11742 sLog.outDebug("+ %u DODGE", enchant_amount);
11743 break;
11744 case ITEM_MOD_PARRY_RATING:
11745 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11746 sLog.outDebug("+ %u PARRY", enchant_amount);
11747 break;
11748 case ITEM_MOD_BLOCK_RATING:
11749 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11750 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11751 break;
11752 case ITEM_MOD_HIT_MELEE_RATING:
11753 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11754 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11755 break;
11756 case ITEM_MOD_HIT_RANGED_RATING:
11757 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11758 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11759 break;
11760 case ITEM_MOD_HIT_SPELL_RATING:
11761 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11762 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11763 break;
11764 case ITEM_MOD_CRIT_MELEE_RATING:
11765 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11766 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11767 break;
11768 case ITEM_MOD_CRIT_RANGED_RATING:
11769 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11770 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11771 break;
11772 case ITEM_MOD_CRIT_SPELL_RATING:
11773 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11774 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11775 break;
11776 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11777 // in Enchantments
11778 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11779 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11780 // break;
11781 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11782 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11783 // break;
11784 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11785 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11786 // break;
11787 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11788 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11789 // break;
11790 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11791 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11792 // break;
11793 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11794 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11795 // break;
11796 // case ITEM_MOD_HASTE_MELEE_RATING:
11797 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11798 // break;
11799 // case ITEM_MOD_HASTE_RANGED_RATING:
11800 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11801 // break;
11802 case ITEM_MOD_HASTE_SPELL_RATING:
11803 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11804 break;
11805 case ITEM_MOD_HIT_RATING:
11806 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11807 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11808 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11809 sLog.outDebug("+ %u HIT", enchant_amount);
11810 break;
11811 case ITEM_MOD_CRIT_RATING:
11812 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11813 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11814 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11815 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11816 break;
11817 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11818 // case ITEM_MOD_HIT_TAKEN_RATING:
11819 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11820 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11821 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11822 // break;
11823 // case ITEM_MOD_CRIT_TAKEN_RATING:
11824 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11825 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11826 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11827 // break;
11828 case ITEM_MOD_RESILIENCE_RATING:
11829 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11830 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11831 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11832 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11833 break;
11834 case ITEM_MOD_HASTE_RATING:
11835 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11836 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11837 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11838 sLog.outDebug("+ %u HASTE", enchant_amount);
11839 break;
11840 case ITEM_MOD_EXPERTISE_RATING:
11841 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11842 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11843 break;
11844 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11845 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11846 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11847 break;
11848 default:
11849 break;
11851 break;
11853 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11855 if(getClass() == CLASS_SHAMAN)
11857 float addValue = 0.0f;
11858 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11860 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11861 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11863 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11865 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11866 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11869 break;
11871 default:
11872 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11873 break;
11874 } /*switch(enchant_display_type)*/
11875 } /*for*/
11877 // visualize enchantment at player and equipped items
11878 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11880 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11881 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11884 if(apply_dur)
11886 if(apply)
11888 // set duration
11889 uint32 duration = item->GetEnchantmentDuration(slot);
11890 if(duration > 0)
11891 AddEnchantmentDuration(item,slot,duration);
11893 else
11895 // duration == 0 will remove EnchantDuration
11896 AddEnchantmentDuration(item,slot,0);
11901 void Player::SendEnchantmentDurations()
11903 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11905 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11909 void Player::SendItemDurations()
11911 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11913 (*itr)->SendTimeUpdate(this);
11917 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11919 if(!item) // prevent crash
11920 return;
11922 // last check 2.0.10
11923 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11924 data << GetGUID(); // player GUID
11925 data << uint32(received); // 0=looted, 1=from npc
11926 data << uint32(created); // 0=received, 1=created
11927 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11928 data << (uint8)item->GetBagSlot(); // bagslot
11929 // item slot, but when added to stack: 0xFFFFFFFF
11930 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11931 data << uint32(item->GetEntry()); // item id
11932 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11933 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11934 data << uint32(count); // count of items
11935 data << GetItemCount(item->GetEntry()); // count of items in inventory
11937 if (broadcast && GetGroup())
11938 GetGroup()->BroadcastPacket(&data);
11939 else
11940 GetSession()->SendPacket(&data);
11943 /*********************************************************/
11944 /*** QUEST SYSTEM ***/
11945 /*********************************************************/
11947 void Player::PrepareQuestMenu( uint64 guid )
11949 Object *pObject;
11950 QuestRelations* pObjectQR;
11951 QuestRelations* pObjectQIR;
11952 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11953 if( pCreature )
11955 pObject = (Object*)pCreature;
11956 pObjectQR = &objmgr.mCreatureQuestRelations;
11957 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11959 else
11961 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11962 if( pGameObject )
11964 pObject = (Object*)pGameObject;
11965 pObjectQR = &objmgr.mGOQuestRelations;
11966 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11968 else
11969 return;
11972 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11973 qm.ClearMenu();
11975 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11977 uint32 quest_id = i->second;
11978 QuestStatus status = GetQuestStatus( quest_id );
11979 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11980 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11981 else if ( status == QUEST_STATUS_INCOMPLETE )
11982 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11983 else if (status == QUEST_STATUS_AVAILABLE )
11984 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11987 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11989 uint32 quest_id = i->second;
11990 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11991 if(!pQuest) continue;
11993 QuestStatus status = GetQuestStatus( quest_id );
11995 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11996 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11997 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11998 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12002 void Player::SendPreparedQuest( uint64 guid )
12004 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12005 if( questMenu.Empty() )
12006 return;
12008 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12010 uint32 status = qmi0.m_qIcon;
12012 // single element case
12013 if ( questMenu.MenuItemCount() == 1 )
12015 // Auto open -- maybe also should verify there is no greeting
12016 uint32 quest_id = qmi0.m_qId;
12017 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12018 if ( pQuest )
12020 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12021 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12022 else if( status == DIALOG_STATUS_INCOMPLETE )
12023 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12024 // Send completable on repeatable quest if player don't have quest
12025 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12026 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12027 else
12028 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12031 // multiply entries
12032 else
12034 QEmote qe;
12035 qe._Delay = 0;
12036 qe._Emote = 0;
12037 std::string title = "";
12038 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12039 if( pCreature )
12041 uint32 textid = pCreature->GetNpcTextId();
12042 GossipText * gossiptext = objmgr.GetGossipText(textid);
12043 if( !gossiptext )
12045 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12046 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12047 title = "";
12049 else
12051 qe = gossiptext->Options[0].Emotes[0];
12053 if(!gossiptext->Options[0].Text_0.empty())
12055 title = gossiptext->Options[0].Text_0;
12057 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12058 if (loc_idx >= 0)
12060 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12061 if (nl)
12063 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12064 title = nl->Text_0[0][loc_idx];
12068 else
12070 title = gossiptext->Options[0].Text_1;
12072 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12073 if (loc_idx >= 0)
12075 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12076 if (nl)
12078 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12079 title = nl->Text_1[0][loc_idx];
12085 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12089 bool Player::IsActiveQuest( uint32 quest_id ) const
12091 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12093 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12096 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12098 Object *pObject;
12099 QuestRelations* pObjectQR;
12100 QuestRelations* pObjectQIR;
12102 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12103 if( pCreature )
12105 pObject = (Object*)pCreature;
12106 pObjectQR = &objmgr.mCreatureQuestRelations;
12107 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12109 else
12111 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12112 if( pGameObject )
12114 pObject = (Object*)pGameObject;
12115 pObjectQR = &objmgr.mGOQuestRelations;
12116 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12118 else
12119 return NULL;
12122 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12123 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12125 if (itr->second == nextQuestID)
12126 return objmgr.GetQuestTemplate(nextQuestID);
12129 return NULL;
12132 bool Player::CanSeeStartQuest( Quest const *pQuest )
12134 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12135 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12136 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12137 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12139 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12142 return false;
12145 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12147 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12148 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12149 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12150 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12151 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12152 && SatisfyQuestDay( pQuest, msg );
12155 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12157 if( !SatisfyQuestLog( msg ) )
12158 return false;
12160 uint32 srcitem = pQuest->GetSrcItemId();
12161 if( srcitem > 0 )
12163 uint32 count = pQuest->GetSrcItemCount();
12164 ItemPosCountVec dest;
12165 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12167 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12168 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12169 return true;
12170 else if( msg != EQUIP_ERR_OK )
12172 SendEquipError( msg, NULL, NULL );
12173 return false;
12176 return true;
12179 bool Player::CanCompleteQuest( uint32 quest_id )
12181 if( quest_id )
12183 QuestStatusData& q_status = mQuestStatus[quest_id];
12184 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12185 return false; // not allow re-complete quest
12187 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12189 if(!qInfo)
12190 return false;
12192 // auto complete quest
12193 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12194 return true;
12196 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12199 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12201 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12203 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12204 return false;
12208 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12210 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12212 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12213 continue;
12215 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12216 return false;
12220 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12221 return false;
12223 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12224 return false;
12226 if ( qInfo->GetRewOrReqMoney() < 0 )
12228 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12229 return false;
12232 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12233 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12234 return false;
12236 return true;
12239 return false;
12242 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12244 // Solve problem that player don't have the quest and try complete it.
12245 // if repeatable she must be able to complete event if player don't have it.
12246 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12247 if( !CanTakeQuest(pQuest, false) )
12248 return false;
12250 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12251 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12252 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12253 return false;
12255 if( !CanRewardQuest(pQuest, false) )
12256 return false;
12258 return true;
12261 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12263 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12264 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12265 return false;
12267 // daily quest can't be rewarded (25 daily quest already completed)
12268 if(!SatisfyQuestDay(pQuest,true))
12269 return false;
12271 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12272 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12273 return false;
12275 // prevent receive reward with quest items in bank
12276 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12278 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12280 if( pQuest->ReqItemCount[i]!= 0 &&
12281 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12283 if(msg)
12284 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12285 return false;
12290 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12291 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12292 return false;
12294 return true;
12297 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12299 // prevent receive reward with quest items in bank or for not completed quest
12300 if(!CanRewardQuest(pQuest,msg))
12301 return false;
12303 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12305 if( pQuest->RewChoiceItemId[reward] )
12307 ItemPosCountVec dest;
12308 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12309 if( res != EQUIP_ERR_OK )
12311 SendEquipError( res, NULL, NULL );
12312 return false;
12317 if ( pQuest->GetRewItemsCount() > 0 )
12319 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12321 if( pQuest->RewItemId[i] )
12323 ItemPosCountVec dest;
12324 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12325 if( res != EQUIP_ERR_OK )
12327 SendEquipError( res, NULL, NULL );
12328 return false;
12334 return true;
12337 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12339 uint16 log_slot = FindQuestSlot( 0 );
12340 assert(log_slot < MAX_QUEST_LOG_SIZE);
12342 uint32 quest_id = pQuest->GetQuestId();
12344 // if not exist then created with set uState==NEW and rewarded=false
12345 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12346 if (questStatusData.uState != QUEST_NEW)
12347 questStatusData.uState = QUEST_CHANGED;
12349 // check for repeatable quests status reset
12350 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12351 questStatusData.m_explored = false;
12353 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12355 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12356 questStatusData.m_itemcount[i] = 0;
12359 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12361 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12362 questStatusData.m_creatureOrGOcount[i] = 0;
12365 GiveQuestSourceItem( pQuest );
12366 AdjustQuestReqItemCount( pQuest );
12368 if( pQuest->GetRepObjectiveFaction() )
12369 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12371 uint32 qtime = 0;
12372 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12374 uint32 limittime = pQuest->GetLimitTime();
12376 // shared timed quest
12377 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12378 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12380 AddTimedQuest( quest_id );
12381 questStatusData.m_timer = limittime * 1000;
12382 qtime = static_cast<uint32>(time(NULL)) + limittime;
12384 else
12385 questStatusData.m_timer = 0;
12387 SetQuestSlot(log_slot, quest_id, qtime);
12389 //starting initial quest script
12390 if(questGiver && pQuest->GetQuestStartScript()!=0)
12391 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12393 UpdateForQuestsGO();
12396 void Player::CompleteQuest( uint32 quest_id )
12398 if( quest_id )
12400 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12402 uint16 log_slot = FindQuestSlot( quest_id );
12403 if( log_slot < MAX_QUEST_LOG_SIZE)
12404 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12406 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12408 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12409 RewardQuest(qInfo,0,this,false);
12410 else
12411 SendQuestComplete( quest_id );
12416 void Player::IncompleteQuest( uint32 quest_id )
12418 if( quest_id )
12420 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12422 uint16 log_slot = FindQuestSlot( quest_id );
12423 if( log_slot < MAX_QUEST_LOG_SIZE)
12424 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12428 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12430 uint32 quest_id = pQuest->GetQuestId();
12432 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12434 if ( pQuest->ReqItemId[i] )
12435 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12438 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12439 // SetTimedQuest( 0 );
12440 m_timedquests.erase(pQuest->GetQuestId());
12442 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12444 if( pQuest->RewChoiceItemId[reward] )
12446 ItemPosCountVec dest;
12447 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12449 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12450 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12455 if ( pQuest->GetRewItemsCount() > 0 )
12457 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12459 if( pQuest->RewItemId[i] )
12461 ItemPosCountVec dest;
12462 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12464 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12465 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12471 RewardReputation( pQuest );
12473 if( pQuest->GetRewSpellCast() > 0 )
12474 CastSpell( this, pQuest->GetRewSpellCast(), true);
12475 else if( pQuest->GetRewSpell() > 0)
12476 CastSpell( this, pQuest->GetRewSpell(), true);
12478 uint16 log_slot = FindQuestSlot( quest_id );
12479 if( log_slot < MAX_QUEST_LOG_SIZE)
12480 SetQuestSlot(log_slot,0);
12482 QuestStatusData& q_status = mQuestStatus[quest_id];
12484 // Not give XP in case already completed once repeatable quest
12485 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12487 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12488 GiveXP( XP , NULL );
12489 else
12490 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12492 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12493 ModifyMoney( pQuest->GetRewOrReqMoney() );
12495 // honor reward
12496 if(pQuest->GetRewHonorableKills())
12497 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12499 // title reward
12500 if(pQuest->GetCharTitleId())
12502 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12503 SetTitle(titleEntry);
12506 // Send reward mail
12507 if(pQuest->GetRewMailTemplateId())
12509 MailMessageType mailType;
12510 uint32 senderGuidOrEntry;
12511 switch(questGiver->GetTypeId())
12513 case TYPEID_UNIT:
12514 mailType = MAIL_CREATURE;
12515 senderGuidOrEntry = questGiver->GetEntry();
12516 break;
12517 case TYPEID_GAMEOBJECT:
12518 mailType = MAIL_GAMEOBJECT;
12519 senderGuidOrEntry = questGiver->GetEntry();
12520 break;
12521 case TYPEID_ITEM:
12522 mailType = MAIL_ITEM;
12523 senderGuidOrEntry = questGiver->GetEntry();
12524 break;
12525 case TYPEID_PLAYER:
12526 mailType = MAIL_NORMAL;
12527 senderGuidOrEntry = questGiver->GetGUIDLow();
12528 break;
12529 default:
12530 mailType = MAIL_NORMAL;
12531 senderGuidOrEntry = GetGUIDLow();
12532 break;
12535 Loot questMailLoot;
12537 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12539 // fill mail
12540 MailItemsInfo mi; // item list preparing
12542 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12544 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12546 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12548 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12549 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12554 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12556 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12558 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12560 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12561 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12566 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12569 if(pQuest->IsDaily())
12571 SetDailyQuestStatus(quest_id);
12572 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12575 if ( !pQuest->IsRepeatable() )
12576 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12577 else
12578 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12580 q_status.m_rewarded = true;
12582 if(announce)
12583 SendQuestReward( pQuest, XP, questGiver );
12585 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12586 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12587 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12590 void Player::FailQuest( uint32 quest_id )
12592 if( quest_id )
12594 IncompleteQuest( quest_id );
12596 uint16 log_slot = FindQuestSlot( quest_id );
12597 if( log_slot < MAX_QUEST_LOG_SIZE)
12599 SetQuestSlotTimer(log_slot, 1 );
12600 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12602 SendQuestFailed( quest_id );
12606 void Player::FailTimedQuest( uint32 quest_id )
12608 if( quest_id )
12610 QuestStatusData& q_status = mQuestStatus[quest_id];
12612 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12613 q_status.m_timer = 0;
12615 IncompleteQuest( quest_id );
12617 uint16 log_slot = FindQuestSlot( quest_id );
12618 if( log_slot < MAX_QUEST_LOG_SIZE)
12620 SetQuestSlotTimer(log_slot, 1 );
12621 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12623 SendQuestTimerFailed( quest_id );
12627 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12629 int32 zoneOrSort = qInfo->GetZoneOrSort();
12630 int32 skillOrClass = qInfo->GetSkillOrClass();
12632 // skip zone zoneOrSort and 0 case skillOrClass
12633 if( zoneOrSort >= 0 && skillOrClass == 0 )
12634 return true;
12636 int32 questSort = -zoneOrSort;
12637 uint8 reqSortClass = ClassByQuestSort(questSort);
12639 // check class sort cases in zoneOrSort
12640 if( reqSortClass != 0 && getClass() != reqSortClass)
12642 if( msg )
12643 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12644 return false;
12647 // check class
12648 if( skillOrClass < 0 )
12650 uint8 reqClass = -int32(skillOrClass);
12651 if(getClass() != reqClass)
12653 if( msg )
12654 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12655 return false;
12658 // check skill
12659 else if( skillOrClass > 0 )
12661 uint32 reqSkill = skillOrClass;
12662 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12664 if( msg )
12665 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12666 return false;
12670 return true;
12673 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12675 if( getLevel() < qInfo->GetMinLevel() )
12677 if( msg )
12678 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12679 return false;
12681 return true;
12684 bool Player::SatisfyQuestLog( bool msg )
12686 // exist free slot
12687 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12688 return true;
12690 if( msg )
12692 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12693 GetSession()->SendPacket( &data );
12694 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12696 return false;
12699 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12701 // No previous quest (might be first quest in a series)
12702 if( qInfo->prevQuests.empty())
12703 return true;
12705 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12707 uint32 prevId = abs(*iter);
12709 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12710 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12712 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12714 // If any of the positive previous quests completed, return true
12715 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12717 // skip one-from-all exclusive group
12718 if(qPrevInfo->GetExclusiveGroup() >= 0)
12719 return true;
12721 // each-from-all exclusive group ( < 0)
12722 // can be start if only all quests in prev quest exclusive group completed and rewarded
12723 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12724 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12726 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12728 for(; iter != end; ++iter)
12730 uint32 exclude_Id = iter->second;
12732 // skip checked quest id, only state of other quests in group is interesting
12733 if(exclude_Id == prevId)
12734 continue;
12736 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12738 // alternative quest from group also must be completed and rewarded(reported)
12739 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12741 if( msg )
12742 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12743 return false;
12746 return true;
12748 // If any of the negative previous quests active, return true
12749 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12750 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12752 // skip one-from-all exclusive group
12753 if(qPrevInfo->GetExclusiveGroup() >= 0)
12754 return true;
12756 // each-from-all exclusive group ( < 0)
12757 // can be start if only all quests in prev quest exclusive group active
12758 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12759 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12761 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12763 for(; iter != end; ++iter)
12765 uint32 exclude_Id = iter->second;
12767 // skip checked quest id, only state of other quests in group is interesting
12768 if(exclude_Id == prevId)
12769 continue;
12771 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12773 // alternative quest from group also must be active
12774 if( i_exstatus == mQuestStatus.end() ||
12775 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12776 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12778 if( msg )
12779 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12780 return false;
12783 return true;
12788 // Has only positive prev. quests in non-rewarded state
12789 // and negative prev. quests in non-active state
12790 if( msg )
12791 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12793 return false;
12796 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12798 uint32 reqraces = qInfo->GetRequiredRaces();
12799 if ( reqraces == 0 )
12800 return true;
12801 if( (reqraces & getRaceMask()) == 0 )
12803 if( msg )
12804 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12805 return false;
12807 return true;
12810 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12812 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12813 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12815 if( msg )
12816 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12817 return false;
12820 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12821 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12823 if( msg )
12824 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12825 return false;
12828 return true;
12831 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12833 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12834 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12836 if( msg )
12837 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12838 return false;
12840 return true;
12843 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12845 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12847 if( msg )
12848 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12849 return false;
12851 return true;
12854 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12856 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12857 if(qInfo->GetExclusiveGroup() <= 0)
12858 return true;
12860 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12861 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12863 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12865 for(; iter != end; ++iter)
12867 uint32 exclude_Id = iter->second;
12869 // skip checked quest id, only state of other quests in group is interesting
12870 if(exclude_Id == qInfo->GetQuestId())
12871 continue;
12873 // not allow have daily quest if daily quest from exclusive group already recently completed
12874 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12875 if( !SatisfyQuestDay(Nquest, false) )
12877 if( msg )
12878 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12879 return false;
12882 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12884 // alternative quest already started or completed
12885 if( i_exstatus != mQuestStatus.end()
12886 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12888 if( msg )
12889 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12890 return false;
12893 return true;
12896 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12898 if(!qInfo->GetNextQuestInChain())
12899 return true;
12901 // next quest in chain already started or completed
12902 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12903 if( itr != mQuestStatus.end()
12904 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12906 if( msg )
12907 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12908 return false;
12911 // check for all quests further up the chain
12912 // only necessary if there are quest chains with more than one quest that can be skipped
12913 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12914 return true;
12917 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12919 // No previous quest in chain
12920 if( qInfo->prevChainQuests.empty())
12921 return true;
12923 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12925 uint32 prevId = *iter;
12927 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12929 if( i_prevstatus != mQuestStatus.end() )
12931 // If any of the previous quests in chain active, return false
12932 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12933 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12935 if( msg )
12936 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12937 return false;
12941 // check for all quests further down the chain
12942 // only necessary if there are quest chains with more than one quest that can be skipped
12943 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12944 // return false;
12947 // No previous quest in chain active
12948 return true;
12951 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12953 if(!qInfo->IsDaily())
12954 return true;
12956 bool have_slot = false;
12957 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12959 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12960 if(qInfo->GetQuestId()==id)
12961 return false;
12963 if(!id)
12964 have_slot = true;
12967 if(!have_slot)
12969 if( msg )
12970 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12971 return false;
12974 return true;
12977 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12979 uint32 srcitem = pQuest->GetSrcItemId();
12980 if( srcitem > 0 )
12982 uint32 count = pQuest->GetSrcItemCount();
12983 if( count <= 0 )
12984 count = 1;
12986 ItemPosCountVec dest;
12987 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12988 if( msg == EQUIP_ERR_OK )
12990 Item * item = StoreNewItem(dest, srcitem, true);
12991 SendNewItem(item, count, true, false);
12992 return true;
12994 // player already have max amount required item, just report success
12995 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12996 return true;
12997 else
12998 SendEquipError( msg, NULL, NULL );
12999 return false;
13002 return true;
13005 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13007 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13008 if( qInfo )
13010 uint32 srcitem = qInfo->GetSrcItemId();
13011 if( srcitem > 0 )
13013 uint32 count = qInfo->GetSrcItemCount();
13014 if( count <= 0 )
13015 count = 1;
13017 // exist one case when destroy source quest item not possible:
13018 // non un-equippable item (equipped non-empty bag, for example)
13019 uint8 res = CanUnequipItems(srcitem,count);
13020 if(res != EQUIP_ERR_OK)
13022 if(msg)
13023 SendEquipError( res, NULL, NULL );
13024 return false;
13027 DestroyItemCount(srcitem, count, true, true);
13030 return true;
13033 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13035 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13036 if( qInfo )
13038 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13039 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13040 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13041 && !qInfo->IsRepeatable() )
13042 return itr->second.m_rewarded;
13044 return false;
13046 return false;
13049 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13051 if( quest_id )
13053 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13054 if( itr != mQuestStatus.end() )
13055 return itr->second.m_status;
13057 return QUEST_STATUS_NONE;
13060 bool Player::CanShareQuest(uint32 quest_id) const
13062 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13063 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13065 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13066 if( itr != mQuestStatus.end() )
13067 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13069 return false;
13072 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13074 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13075 if( qInfo )
13077 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13079 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13080 m_timedquests.erase(qInfo->GetQuestId());
13083 QuestStatusData& q_status = mQuestStatus[quest_id];
13085 q_status.m_status = status;
13086 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13089 UpdateForQuestsGO();
13092 // not used in MaNGOS, but used in scripting code
13093 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13095 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13096 if( !qInfo )
13097 return 0;
13099 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13100 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13101 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13103 return 0;
13106 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
13108 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13110 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
13112 uint32 reqitemcount = pQuest->ReqItemCount[i];
13113 if( reqitemcount != 0 )
13115 uint32 quest_id = pQuest->GetQuestId();
13116 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13118 QuestStatusData& q_status = mQuestStatus[quest_id];
13119 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13120 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13126 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13128 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13129 if ( GetQuestSlotQuestId(i) == quest_id )
13130 return i;
13132 return MAX_QUEST_LOG_SIZE;
13135 void Player::AreaExploredOrEventHappens( uint32 questId )
13137 if( questId )
13139 uint16 log_slot = FindQuestSlot( questId );
13140 if( log_slot < MAX_QUEST_LOG_SIZE)
13142 QuestStatusData& q_status = mQuestStatus[questId];
13144 if(!q_status.m_explored)
13146 q_status.m_explored = true;
13147 if (q_status.uState != QUEST_NEW)
13148 q_status.uState = QUEST_CHANGED;
13151 if( CanCompleteQuest( questId ) )
13152 CompleteQuest( questId );
13156 //not used in mangosd, function for external script library
13157 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13159 if( Group *pGroup = GetGroup() )
13161 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13163 Player *pGroupGuy = itr->getSource();
13165 // for any leave or dead (with not released body) group member at appropriate distance
13166 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13167 pGroupGuy->AreaExploredOrEventHappens(questId);
13170 else
13171 AreaExploredOrEventHappens(questId);
13174 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13176 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13178 uint32 questid = GetQuestSlotQuestId(i);
13179 if ( questid == 0 )
13180 continue;
13182 QuestStatusData& q_status = mQuestStatus[questid];
13184 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13185 continue;
13187 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13188 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13189 continue;
13191 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13193 uint32 reqitem = qInfo->ReqItemId[j];
13194 if ( reqitem == entry )
13196 uint32 reqitemcount = qInfo->ReqItemCount[j];
13197 uint32 curitemcount = q_status.m_itemcount[j];
13198 if ( curitemcount < reqitemcount )
13200 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13201 q_status.m_itemcount[j] += additemcount;
13202 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13204 SendQuestUpdateAddItem( qInfo, j, additemcount );
13206 if ( CanCompleteQuest( questid ) )
13207 CompleteQuest( questid );
13208 return;
13212 UpdateForQuestsGO();
13213 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13216 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13218 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13220 uint32 questid = GetQuestSlotQuestId(i);
13221 if(!questid)
13222 continue;
13223 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13224 if ( !qInfo )
13225 continue;
13226 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13227 continue;
13229 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13231 uint32 reqitem = qInfo->ReqItemId[j];
13232 if ( reqitem == entry )
13234 QuestStatusData& q_status = mQuestStatus[questid];
13236 uint32 reqitemcount = qInfo->ReqItemCount[j];
13237 uint32 curitemcount;
13238 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13239 curitemcount = q_status.m_itemcount[j];
13240 else
13241 curitemcount = GetItemCount(entry,true);
13242 if ( curitemcount < reqitemcount + count )
13244 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13245 q_status.m_itemcount[j] = curitemcount - remitemcount;
13246 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13248 IncompleteQuest( questid );
13250 return;
13254 UpdateForQuestsGO();
13257 void Player::KilledMonster( uint32 entry, uint64 guid )
13259 uint32 addkillcount = 1;
13260 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13261 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13263 uint32 questid = GetQuestSlotQuestId(i);
13264 if(!questid)
13265 continue;
13267 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13268 if( !qInfo )
13269 continue;
13270 // just if !ingroup || !noraidgroup || raidgroup
13271 QuestStatusData& q_status = mQuestStatus[questid];
13272 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13274 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13276 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13278 // skip GO activate objective or none
13279 if(qInfo->ReqCreatureOrGOId[j] <=0)
13280 continue;
13282 // skip Cast at creature objective
13283 if(qInfo->ReqSpell[j] !=0 )
13284 continue;
13286 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13288 if ( reqkill == entry )
13290 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13291 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13292 if ( curkillcount < reqkillcount )
13294 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13295 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13297 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13299 if ( CanCompleteQuest( questid ) )
13300 CompleteQuest( questid );
13302 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13303 continue;
13311 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13313 bool isCreature = IS_CREATURE_GUID(guid);
13315 uint32 addCastCount = 1;
13316 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13318 uint32 questid = GetQuestSlotQuestId(i);
13319 if(!questid)
13320 continue;
13322 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13323 if ( !qInfo )
13324 continue;
13326 QuestStatusData& q_status = mQuestStatus[questid];
13328 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13330 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13332 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13334 // skip kill creature objective (0) or wrong spell casts
13335 if(qInfo->ReqSpell[j] != spell_id )
13336 continue;
13338 uint32 reqTarget = 0;
13340 if(isCreature)
13342 // creature activate objectives
13343 if(qInfo->ReqCreatureOrGOId[j] > 0)
13344 // checked at quest_template loading
13345 reqTarget = qInfo->ReqCreatureOrGOId[j];
13347 else
13349 // GO activate objective
13350 if(qInfo->ReqCreatureOrGOId[j] < 0)
13351 // checked at quest_template loading
13352 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13355 // other not this creature/GO related objectives
13356 if( reqTarget != entry )
13357 continue;
13359 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13360 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13361 if ( curCastCount < reqCastCount )
13363 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13364 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13366 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13369 if ( CanCompleteQuest( questid ) )
13370 CompleteQuest( questid );
13372 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13373 break;
13380 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13382 uint32 addTalkCount = 1;
13383 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13385 uint32 questid = GetQuestSlotQuestId(i);
13386 if(!questid)
13387 continue;
13389 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13390 if ( !qInfo )
13391 continue;
13393 QuestStatusData& q_status = mQuestStatus[questid];
13395 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13397 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13399 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13401 // skip spell casts and Gameobject objectives
13402 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13403 continue;
13405 uint32 reqTarget = 0;
13407 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13408 // checked at quest_template loading
13409 reqTarget = qInfo->ReqCreatureOrGOId[j];
13410 else
13411 continue;
13413 if ( reqTarget == entry )
13415 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13416 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13417 if ( curTalkCount < reqTalkCount )
13419 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13420 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13422 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13424 if ( CanCompleteQuest( questid ) )
13425 CompleteQuest( questid );
13427 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13428 continue;
13436 void Player::MoneyChanged( uint32 count )
13438 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13440 uint32 questid = GetQuestSlotQuestId(i);
13441 if (!questid)
13442 continue;
13444 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13445 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13447 QuestStatusData& q_status = mQuestStatus[questid];
13449 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13451 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13453 if ( CanCompleteQuest( questid ) )
13454 CompleteQuest( questid );
13457 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13459 if(int32(count) < -qInfo->GetRewOrReqMoney())
13460 IncompleteQuest( questid );
13466 bool Player::HasQuestForItem( uint32 itemid ) const
13468 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13470 QuestStatusData const& q_status = i->second;
13472 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13474 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13475 if(!qinfo)
13476 continue;
13478 // hide quest if player is in raid-group and quest is no raid quest
13479 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13480 continue;
13482 // There should be no mixed ReqItem/ReqSource drop
13483 // This part for ReqItem drop
13484 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13486 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13487 return true;
13489 // This part - for ReqSource
13490 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13492 // examined item is a source item
13493 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13495 uint32 idx = qinfo->ReqSourceRef[j]-1;
13497 // total count of created ReqItems and SourceItems is less than ReqItemCount
13498 if(qinfo->ReqItemId[idx] != 0 &&
13499 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13500 return true;
13502 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13503 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13505 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13506 return true;
13508 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13509 else if(qinfo->ReqSpell[idx] != 0)
13511 // not casted and need more reagents/item for use.
13512 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13513 return true;
13519 return false;
13522 void Player::SendQuestComplete( uint32 quest_id )
13524 if( quest_id )
13526 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13527 data << uint32(quest_id);
13528 GetSession()->SendPacket( &data );
13529 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13533 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13535 uint32 questid = pQuest->GetQuestId();
13536 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13537 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13538 data << uint32(questid);
13540 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13542 data << uint32(XP);
13543 data << uint32(pQuest->GetRewOrReqMoney());
13545 else
13547 data << uint32(0);
13548 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13551 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13552 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13553 GetSession()->SendPacket( &data );
13555 if (pQuest->GetQuestCompleteScript() != 0)
13556 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13559 void Player::SendQuestFailed( uint32 quest_id )
13561 if( quest_id )
13563 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13564 data << quest_id;
13565 data << uint32(0); // failed reason (4 for inventory is full)
13566 GetSession()->SendPacket( &data );
13567 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13571 void Player::SendQuestTimerFailed( uint32 quest_id )
13573 if( quest_id )
13575 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13576 data << quest_id;
13577 GetSession()->SendPacket( &data );
13578 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13582 void Player::SendCanTakeQuestResponse( uint32 msg )
13584 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13585 data << uint32(msg);
13586 GetSession()->SendPacket( &data );
13587 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13590 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13592 if( pPlayer )
13594 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13595 data << uint64(pPlayer->GetGUID());
13596 data << uint8(msg); // valid values: 0-8
13597 GetSession()->SendPacket( &data );
13598 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13602 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13604 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13605 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13606 //data << pQuest->ReqItemId[item_idx];
13607 //data << count;
13608 GetSession()->SendPacket( &data );
13611 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13613 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13615 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13616 if (entry < 0)
13617 // client expected gameobject template id in form (id|0x80000000)
13618 entry = (-entry) | 0x80000000;
13620 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13621 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13622 data << uint32(pQuest->GetQuestId());
13623 data << uint32(entry);
13624 data << uint32(old_count + add_count);
13625 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13626 data << uint64(guid);
13627 GetSession()->SendPacket(&data);
13629 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13630 if( log_slot < MAX_QUEST_LOG_SIZE)
13631 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13634 /*********************************************************/
13635 /*** LOAD SYSTEM ***/
13636 /*********************************************************/
13638 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13640 bool delete_result = true;
13641 if(!result)
13643 // 0 1 2 3 4 5 6 7 8 9
13644 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13645 if(!result) return false;
13647 else delete_result = false;
13649 Field *fields = result->Fetch();
13651 if(!LoadValues( fields[1].GetString()))
13653 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13654 if(delete_result) delete result;
13655 return false;
13658 // overwrite possible wrong/corrupted guid
13659 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13661 m_name = fields[2].GetCppString();
13663 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13664 SetMapId(fields[6].GetUInt32());
13665 // the instance id is not needed at character enum
13667 m_Played_time[0] = fields[7].GetUInt32();
13668 m_Played_time[1] = fields[8].GetUInt32();
13670 m_atLoginFlags = fields[9].GetUInt32();
13672 // I don't see these used anywhere ..
13673 /*_LoadGroup();
13675 _LoadBoundInstances();*/
13677 if (delete_result) delete result;
13679 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13680 m_items[i] = NULL;
13682 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13683 m_deathState = DEAD;
13685 return true;
13688 void Player::_LoadDeclinedNames(QueryResult* result)
13690 if(!result)
13691 return;
13693 if(m_declinedname)
13694 delete m_declinedname;
13696 m_declinedname = new DeclinedName;
13697 Field *fields = result->Fetch();
13698 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13699 m_declinedname->name[i] = fields[i].GetCppString();
13701 delete result;
13704 void Player::_LoadArenaTeamInfo(QueryResult *result)
13706 // arenateamid, played_week, played_season, personal_rating
13707 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13708 if (!result)
13709 return;
13713 Field *fields = result->Fetch();
13715 uint32 arenateamid = fields[0].GetUInt32();
13716 uint32 played_week = fields[1].GetUInt32();
13717 uint32 played_season = fields[2].GetUInt32();
13718 uint32 personal_rating = fields[3].GetUInt32();
13720 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13721 if(!aTeam)
13723 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13724 continue;
13726 uint8 arenaSlot = aTeam->GetSlot();
13728 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13729 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13730 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13731 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13732 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13733 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13735 }while (result->NextRow());
13736 delete result;
13739 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13741 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13742 if(!result)
13743 return false;
13745 Field *fields = result->Fetch();
13747 x = fields[0].GetFloat();
13748 y = fields[1].GetFloat();
13749 z = fields[2].GetFloat();
13750 o = fields[3].GetFloat();
13751 mapid = fields[4].GetUInt32();
13752 in_flight = !fields[5].GetCppString().empty();
13754 delete result;
13755 return true;
13758 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13760 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13761 if( !result )
13762 return false;
13764 Field *fields = result->Fetch();
13766 data = StrSplit(fields[0].GetCppString(), " ");
13768 delete result;
13770 return true;
13773 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13775 if(index >= data.size())
13776 return 0;
13778 return (uint32)atoi(data[index].c_str());
13781 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13783 float result;
13784 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13785 memcpy(&result, &temp, sizeof(result));
13787 return result;
13790 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13792 Tokens data;
13793 if(!LoadValuesArrayFromDB(data,guid))
13794 return 0;
13796 return GetUInt32ValueFromArray(data,index);
13799 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13801 float result;
13802 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13803 memcpy(&result, &temp, sizeof(result));
13805 return result;
13808 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13810 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33
13811 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
13812 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13814 if(!result)
13816 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13817 return false;
13820 Field *fields = result->Fetch();
13822 uint32 dbAccountId = fields[1].GetUInt32();
13824 // check if the character's account in the db and the logged in account match.
13825 // player should be able to load/delete character only with correct account!
13826 if( dbAccountId != GetSession()->GetAccountId() )
13828 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13829 delete result;
13830 return false;
13833 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13835 m_name = fields[3].GetCppString();
13837 // check name limitations
13838 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13840 delete result;
13841 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13842 return false;
13845 if(!LoadValues( fields[2].GetString()))
13847 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13848 delete result;
13849 return false;
13852 // overwrite possible wrong/corrupted guid
13853 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13855 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13856 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13858 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13859 SetVisibleItemSlot(slot,NULL);
13861 if (m_items[slot])
13863 delete m_items[slot];
13864 m_items[slot] = NULL;
13868 // update money limits
13869 if(GetMoney() > MAX_MONEY_AMOUNT)
13870 SetMoney(MAX_MONEY_AMOUNT);
13872 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13873 outDebugValues();
13875 m_race = fields[4].GetUInt8();
13876 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13877 //Other way is to saves m_team into characters table.
13878 setFactionForRace(m_race);
13879 SetCharm(0);
13881 m_class = fields[5].GetUInt8();
13883 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13884 if(!info)
13886 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13887 delete result;
13888 return false;
13891 InitPrimaryProffesions(); // to max set before any spell loaded
13893 uint32 transGUID = fields[24].GetUInt32();
13894 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13895 SetFallInformation(0, fields[8].GetFloat());
13896 SetMapId(fields[9].GetUInt32());
13897 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13899 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13901 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13903 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13904 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13905 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13907 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13909 // check arena teams integrity
13910 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13912 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13913 if(!arena_team_id)
13914 continue;
13916 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13917 if(at->HaveMember(GetGUID()))
13918 continue;
13920 // arena team not exist or not member, cleanup fields
13921 for(int j =0; j < 6; ++j)
13922 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13925 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13927 if(!IsPositionValid())
13929 sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
13931 SetMapId(info->mapId);
13932 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13934 transGUID = 0;
13936 m_movementInfo.t_x = 0.0f;
13937 m_movementInfo.t_y = 0.0f;
13938 m_movementInfo.t_z = 0.0f;
13939 m_movementInfo.t_o = 0.0f;
13942 // load the player's map here if it's not already loaded
13943 Map *map = GetMap();
13944 // since the player may not be bound to the map yet, make sure subsequent
13945 // getmap calls won't create new maps
13946 SetInstanceId(map->GetInstanceId());
13948 SaveRecallPosition();
13950 if (transGUID != 0)
13952 m_movementInfo.t_x = fields[20].GetFloat();
13953 m_movementInfo.t_y = fields[21].GetFloat();
13954 m_movementInfo.t_z = fields[22].GetFloat();
13955 m_movementInfo.t_o = fields[23].GetFloat();
13957 if( !MaNGOS::IsValidMapCoord(
13958 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13959 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13960 // transport size limited
13961 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13963 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13964 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13965 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13967 SetMapId(info->mapId);
13968 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13970 m_movementInfo.t_x = 0.0f;
13971 m_movementInfo.t_y = 0.0f;
13972 m_movementInfo.t_z = 0.0f;
13973 m_movementInfo.t_o = 0.0f;
13975 transGUID = 0;
13979 if (transGUID != 0)
13981 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13983 if( (*iter)->GetGUIDLow() == transGUID)
13985 m_transport = *iter;
13986 m_transport->AddPassenger(this);
13987 SetMapId(m_transport->GetMapId());
13988 break;
13992 if(!m_transport)
13994 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13995 guid,transGUID);
13997 SetMapId(info->mapId);
13998 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14000 m_movementInfo.t_x = 0.0f;
14001 m_movementInfo.t_y = 0.0f;
14002 m_movementInfo.t_z = 0.0f;
14003 m_movementInfo.t_o = 0.0f;
14005 transGUID = 0;
14009 time_t now = time(NULL);
14010 time_t logoutTime = time_t(fields[16].GetUInt64());
14012 // since last logout (in seconds)
14013 uint64 time_diff = uint64(now - logoutTime);
14015 // set value, including drunk invisibility detection
14016 // calculate sobering. after 15 minutes logged out, the player will be sober again
14017 float soberFactor;
14018 if(time_diff > 15*MINUTE)
14019 soberFactor = 0;
14020 else
14021 soberFactor = 1-time_diff/(15.0f*MINUTE);
14022 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14023 SetDrunkValue(newDrunkenValue);
14025 m_rest_bonus = fields[15].GetFloat();
14026 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14027 float bubble0 = 0.031;
14028 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14029 float bubble1 = 0.125;
14031 if((int32)fields[16].GetUInt32() > 0)
14033 float bubble = fields[17].GetUInt32() > 0
14034 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14035 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14037 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14040 m_cinematic = fields[12].GetUInt32();
14041 m_Played_time[0]= fields[13].GetUInt32();
14042 m_Played_time[1]= fields[14].GetUInt32();
14044 m_resetTalentsCost = fields[18].GetUInt32();
14045 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14047 // reserve some flags
14048 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14050 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14051 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14053 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14055 uint32 extraflags = fields[25].GetUInt32();
14057 m_stableSlots = fields[26].GetUInt32();
14058 if(m_stableSlots > 4)
14060 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14061 m_stableSlots = 4;
14064 m_atLoginFlags = fields[27].GetUInt32();
14066 // Honor system
14067 // Update Honor kills data
14068 m_lastHonorUpdateTime = logoutTime;
14069 UpdateHonorFields();
14071 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14072 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14073 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14075 std::string taxi_nodes = fields[31].GetCppString();
14077 delete result;
14079 // clear channel spell data (if saved at channel spell casting)
14080 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14081 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14083 // clear charm/summon related fields
14084 SetCharm(NULL);
14085 SetPet(NULL);
14086 SetCharmerGUID(NULL);
14087 SetOwnerGUID(NULL);
14088 SetCreatorGUID(NULL);
14090 // reset some aura modifiers before aura apply
14091 SetFarSight(NULL);
14092 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14093 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14095 // reset skill modifiers and set correct unlearn flags
14096 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
14098 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
14100 // set correct unlearn bit
14101 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
14102 if(!id) continue;
14104 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
14105 if(!pSkill) continue;
14107 // enable unlearn button for primary professions only
14108 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
14109 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
14110 else
14111 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
14114 // make sure the unit is considered out of combat for proper loading
14115 ClearInCombat();
14117 // make sure the unit is considered not in duel for proper loading
14118 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14119 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14121 // remember loaded power/health values to restore after stats initialization and modifier applying
14122 uint32 savedHealth = GetHealth();
14123 uint32 savedPower[MAX_POWERS];
14124 for(uint32 i = 0; i < MAX_POWERS; ++i)
14125 savedPower[i] = GetPower(Powers(i));
14127 // reset stats before loading any modifiers
14128 InitStatsForLevel();
14129 InitTaxiNodesForLevel();
14130 InitGlyphsForLevel();
14131 InitRunes();
14133 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14135 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14136 //_LoadMail();
14138 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14140 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14141 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14142 m_deathState = DEAD;
14144 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14146 // after spell load
14147 InitTalentForLevel();
14148 learnSkillRewardedSpells();
14150 // after spell load, learn rewarded spell if need also
14151 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14152 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14154 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14156 // must be before inventory (some items required reputation check)
14157 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14159 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14161 // update items with duration and realtime
14162 UpdateItemDuration(time_diff, true);
14164 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14166 // unread mails and next delivery time, actual mails not loaded
14167 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14169 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14171 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14172 return false;
14174 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14175 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14176 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14178 if(!HasTitle(curTitle))
14179 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14182 // Not finish taxi flight path
14183 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
14185 // problems with taxi path loading
14186 TaxiNodesEntry const* nodeEntry = NULL;
14187 if(uint32 node_id = m_taxi.GetTaxiSource())
14188 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14190 if(!nodeEntry) // don't know taxi start node, to homebind
14192 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14193 SetMapId(m_homebindMapId);
14194 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
14195 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14197 else // have start node, to it
14199 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14200 SetMapId(nodeEntry->map_id);
14201 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14202 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14204 m_taxi.ClearTaxiDestinations();
14206 else if(uint32 node_id = m_taxi.GetTaxiSource())
14208 // save source node as recall coord to prevent recall and fall from sky
14209 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14210 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14211 m_recallMap = nodeEntry->map_id;
14212 m_recallX = nodeEntry->x;
14213 m_recallY = nodeEntry->y;
14214 m_recallZ = nodeEntry->z;
14216 // flight will started later
14219 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14221 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14222 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14223 if(!isAlive())
14224 RemoveAllAurasOnDeath();
14226 //apply all stat bonuses from items and auras
14227 SetCanModifyStats(true);
14228 UpdateAllStats();
14230 // restore remembered power/health values (but not more max values)
14231 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14232 for(uint32 i = 0; i < MAX_POWERS; ++i)
14233 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14235 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14236 outDebugValues();
14238 // GM state
14239 if(GetSession()->GetSecurity() > SEC_PLAYER)
14241 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14243 default:
14244 case 0: break; // disable
14245 case 1: SetGameMaster(true); break; // enable
14246 case 2: // save state
14247 if(extraflags & PLAYER_EXTRA_GM_ON)
14248 SetGameMaster(true);
14249 break;
14252 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14254 default:
14255 case 0: break; // disable
14256 case 1: SetAcceptTicket(true); break; // enable
14257 case 2: // save state
14258 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14259 SetAcceptTicket(true);
14260 break;
14263 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14265 default:
14266 case 0: break; // disable
14267 case 1: SetGMChat(true); break; // enable
14268 case 2: // save state
14269 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14270 SetGMChat(true);
14271 break;
14274 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14276 default:
14277 case 0: break; // disable
14278 case 1: SetAcceptWhispers(true); break; // enable
14279 case 2: // save state
14280 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14281 SetAcceptWhispers(true);
14282 break;
14286 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14288 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14289 m_achievementMgr.CheckAllAchievementCriteria();
14290 return true;
14293 bool Player::isAllowedToLoot(Creature* creature)
14295 if(Player* recipient = creature->GetLootRecipient())
14297 if (recipient == this)
14298 return true;
14299 if( Group* otherGroup = recipient->GetGroup())
14301 Group* thisGroup = GetGroup();
14302 if(!thisGroup)
14303 return false;
14304 return thisGroup == otherGroup;
14306 return false;
14308 else
14309 // prevent other players from looting if the recipient got disconnected
14310 return !creature->hasLootRecipient();
14313 void Player::_LoadActions(QueryResult *result)
14315 m_actionButtons.clear();
14317 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14319 if(result)
14323 Field *fields = result->Fetch();
14325 uint8 button = fields[0].GetUInt8();
14327 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14329 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14331 while( result->NextRow() );
14333 delete result;
14337 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14339 m_Auras.clear();
14340 for (int i = 0; i < TOTAL_AURAS; i++)
14341 m_modAuras[i].clear();
14343 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14345 if(result)
14349 Field *fields = result->Fetch();
14350 uint64 caster_guid = fields[0].GetUInt64();
14351 uint32 spellid = fields[1].GetUInt32();
14352 uint32 effindex = fields[2].GetUInt32();
14353 uint32 stackcount = fields[3].GetUInt32();
14354 int32 damage = (int32)fields[4].GetUInt32();
14355 int32 maxduration = (int32)fields[5].GetUInt32();
14356 int32 remaintime = (int32)fields[6].GetUInt32();
14357 int32 remaincharges = (int32)fields[7].GetUInt32();
14359 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14360 if(!spellproto)
14362 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14363 continue;
14366 if(effindex >= 3)
14368 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14369 continue;
14372 // negative effects should continue counting down after logout
14373 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14375 if(remaintime <= int32(timediff))
14376 continue;
14378 remaintime -= timediff;
14381 // prevent wrong values of remaincharges
14382 if(spellproto->procCharges)
14384 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14385 remaincharges = spellproto->procCharges;
14387 else
14388 remaincharges = -1;
14390 //do not load single target auras (unless they were cast by the player)
14391 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14392 continue;
14394 for(uint32 i=0; i<stackcount; i++)
14396 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14397 if(!damage)
14398 damage = aura->GetModifier()->m_amount;
14399 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14400 AddAura(aura);
14401 sLog.outString("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14404 while( result->NextRow() );
14406 delete result;
14409 if(m_class == CLASS_WARRIOR)
14410 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14413 void Player::LoadCorpse()
14415 if( isAlive() )
14417 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14419 else
14421 if(Corpse *corpse = GetCorpse())
14423 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14425 else
14427 //Prevent Dead Player login without corpse
14428 ResurrectPlayer(0.5f);
14433 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14435 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
14436 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14437 //NOTE: the "order by `bag`" is important because it makes sure
14438 //the bagMap is filled before items in the bags are loaded
14439 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14440 //expected to be equipped before offhand items (TODO: fixme)
14442 uint32 zone = GetZoneId();
14444 if (result)
14446 std::list<Item*> problematicItems;
14448 // prevent items from being added to the queue when stored
14449 m_itemUpdateQueueBlocked = true;
14452 Field *fields = result->Fetch();
14453 uint32 bag_guid = fields[1].GetUInt32();
14454 uint8 slot = fields[2].GetUInt8();
14455 uint32 item_guid = fields[3].GetUInt32();
14456 uint32 item_id = fields[4].GetUInt32();
14458 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14460 if(!proto)
14462 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14463 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14464 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14465 continue;
14468 Item *item = NewItemOrBag(proto);
14470 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14472 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14473 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14474 item->FSetState(ITEM_REMOVED);
14475 item->SaveToDB(); // it also deletes item object !
14476 continue;
14479 // not allow have in alive state item limited to another map/zone
14480 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14482 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14483 item->FSetState(ITEM_REMOVED);
14484 item->SaveToDB(); // it also deletes item object !
14485 continue;
14488 // "Conjured items disappear if you are logged out for more than 15 minutes"
14489 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14491 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14492 item->FSetState(ITEM_REMOVED);
14493 item->SaveToDB(); // it also deletes item object !
14494 continue;
14497 bool success = true;
14499 if (!bag_guid)
14501 // the item is not in a bag
14502 item->SetContainer( NULL );
14503 item->SetSlot(slot);
14505 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14507 ItemPosCountVec dest;
14508 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14509 item = StoreItem(dest, item, true);
14510 else
14511 success = false;
14513 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14515 uint16 dest;
14516 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14517 QuickEquipItem(dest, item);
14518 else
14519 success = false;
14521 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14523 ItemPosCountVec dest;
14524 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14525 item = BankItem(dest, item, true);
14526 else
14527 success = false;
14530 if(success)
14532 // store bags that may contain items in them
14533 if(item->IsBag() && IsBagPos(item->GetPos()))
14534 bagMap[item_guid] = (Bag*)item;
14537 else
14539 item->SetSlot(NULL_SLOT);
14540 // the item is in a bag, find the bag
14541 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14542 if(itr != bagMap.end())
14543 itr->second->StoreItem(slot, item, true );
14544 else
14545 success = false;
14548 // item's state may have changed after stored
14549 if (success)
14550 item->SetState(ITEM_UNCHANGED, this);
14551 else
14553 sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_guid, item_id, bag_guid, slot);
14554 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14555 problematicItems.push_back(item);
14557 } while (result->NextRow());
14559 delete result;
14560 m_itemUpdateQueueBlocked = false;
14562 // send by mail problematic items
14563 while(!problematicItems.empty())
14565 // fill mail
14566 MailItemsInfo mi; // item list preparing
14568 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14570 Item* item = problematicItems.front();
14571 problematicItems.pop_front();
14573 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14576 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14578 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14581 //if(isAlive())
14582 _ApplyAllItemMods();
14585 // load mailed item which should receive current player
14586 void Player::_LoadMailedItems(Mail *mail)
14588 // data needs to be at first place for Item::LoadFromDB
14589 QueryResult* result = CharacterDatabase.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail->messageID);
14590 if(!result)
14591 return;
14595 Field *fields = result->Fetch();
14596 uint32 item_guid_low = fields[1].GetUInt32();
14597 uint32 item_template = fields[2].GetUInt32();
14599 mail->AddItem(item_guid_low, item_template);
14601 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14603 if(!proto)
14605 sLog.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14606 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14607 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14608 continue;
14611 Item *item = NewItemOrBag(proto);
14613 if(!item->LoadFromDB(item_guid_low, 0, result))
14615 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14616 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14617 item->FSetState(ITEM_REMOVED);
14618 item->SaveToDB(); // it also deletes item object !
14619 continue;
14622 AddMItem(item);
14623 } while (result->NextRow());
14625 delete result;
14628 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14630 //set a count of unread mails
14631 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14632 if (resultUnread)
14634 Field *fieldMail = resultUnread->Fetch();
14635 unReadMails = fieldMail[0].GetUInt8();
14636 delete resultUnread;
14639 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14640 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14641 if (resultDelivery)
14643 Field *fieldMail = resultDelivery->Fetch();
14644 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14645 delete resultDelivery;
14649 void Player::_LoadMail()
14651 m_mail.clear();
14652 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14653 QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
14654 if(result)
14658 Field *fields = result->Fetch();
14659 Mail *m = new Mail;
14660 m->messageID = fields[0].GetUInt32();
14661 m->messageType = fields[1].GetUInt8();
14662 m->sender = fields[2].GetUInt32();
14663 m->receiver = fields[3].GetUInt32();
14664 m->subject = fields[4].GetCppString();
14665 m->itemTextId = fields[5].GetUInt32();
14666 bool has_items = fields[6].GetBool();
14667 m->expire_time = (time_t)fields[7].GetUInt64();
14668 m->deliver_time = (time_t)fields[8].GetUInt64();
14669 m->money = fields[9].GetUInt32();
14670 m->COD = fields[10].GetUInt32();
14671 m->checked = fields[11].GetUInt32();
14672 m->stationery = fields[12].GetUInt8();
14673 m->mailTemplateId = fields[13].GetInt16();
14675 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14677 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14678 m->mailTemplateId = 0;
14681 m->state = MAIL_STATE_UNCHANGED;
14683 if (has_items)
14684 _LoadMailedItems(m);
14686 m_mail.push_back(m);
14687 } while( result->NextRow() );
14688 delete result;
14690 m_mailsLoaded = true;
14693 void Player::LoadPet()
14695 //fixme: the pet should still be loaded if the player is not in world
14696 // just not added to the map
14697 if(IsInWorld())
14699 Pet *pet = new Pet;
14700 if(!pet->LoadPetFromDB(this,0,0,true))
14701 delete pet;
14705 void Player::_LoadQuestStatus(QueryResult *result)
14707 mQuestStatus.clear();
14709 uint32 slot = 0;
14711 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14712 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
14714 if(result)
14718 Field *fields = result->Fetch();
14720 uint32 quest_id = fields[0].GetUInt32();
14721 // used to be new, no delete?
14722 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14723 if( pQuest )
14725 // find or create
14726 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14728 uint32 qstatus = fields[1].GetUInt32();
14729 if(qstatus < MAX_QUEST_STATUS)
14730 questStatusData.m_status = QuestStatus(qstatus);
14731 else
14733 questStatusData.m_status = QUEST_STATUS_NONE;
14734 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14737 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14738 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14740 time_t quest_time = time_t(fields[4].GetUInt64());
14742 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14744 AddTimedQuest( quest_id );
14746 if (quest_time <= sWorld.GetGameTime())
14747 questStatusData.m_timer = 1;
14748 else
14749 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14751 else
14752 quest_time = 0;
14754 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14755 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14756 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14757 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14758 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14759 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14760 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14761 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14763 questStatusData.uState = QUEST_UNCHANGED;
14765 // add to quest log
14766 if( slot < MAX_QUEST_LOG_SIZE &&
14767 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14768 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14769 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14771 SetQuestSlot(slot,quest_id,quest_time);
14773 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14774 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14776 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14777 if(questStatusData.m_creatureOrGOcount[idx])
14778 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14780 ++slot;
14783 if(questStatusData.m_rewarded)
14785 // learn rewarded spell if unknown
14786 learnQuestRewardedSpells(pQuest);
14788 // set rewarded title if any
14789 if(pQuest->GetCharTitleId())
14791 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14792 SetTitle(titleEntry);
14796 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14799 while( result->NextRow() );
14801 delete result;
14804 // clear quest log tail
14805 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14806 SetQuestSlot(i,0);
14809 void Player::_LoadDailyQuestStatus(QueryResult *result)
14811 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14812 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14814 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14816 if(result)
14818 uint32 quest_daily_idx = 0;
14822 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14824 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14825 break;
14828 Field *fields = result->Fetch();
14830 uint32 quest_id = fields[0].GetUInt32();
14832 // save _any_ from daily quest times (it must be after last reset anyway)
14833 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14835 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14836 if( !pQuest )
14837 continue;
14839 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14840 ++quest_daily_idx;
14842 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14844 while( result->NextRow() );
14846 delete result;
14849 m_DailyQuestChanged = false;
14852 void Player::_LoadReputation(QueryResult *result)
14854 m_factions.clear();
14856 // Set initial reputations (so everything is nifty before DB data load)
14857 SetInitialFactions();
14859 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14861 if(result)
14865 Field *fields = result->Fetch();
14867 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14868 if( factionEntry && (factionEntry->reputationListID >= 0))
14870 FactionState* faction = &m_factions[factionEntry->reputationListID];
14872 // update standing to current
14873 faction->Standing = int32(fields[1].GetUInt32());
14875 uint32 dbFactionFlags = fields[2].GetUInt32();
14877 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14878 SetFactionVisible(faction); // have internal checks for forced invisibility
14880 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14881 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14883 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14884 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14885 else // DB not at war
14887 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14888 if( faction->Flags & FACTION_FLAG_VISIBLE )
14889 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14892 // set atWar for hostile
14893 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14894 SetFactionAtWar(faction,true);
14896 // reset changed flag if values similar to saved in DB
14897 if(faction->Flags==dbFactionFlags)
14898 faction->Changed = false;
14901 while( result->NextRow() );
14903 delete result;
14907 void Player::_LoadSpells(QueryResult *result)
14909 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14910 delete itr->second;
14911 m_spells.clear();
14913 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14915 if(result)
14919 Field *fields = result->Fetch();
14921 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14923 while( result->NextRow() );
14925 delete result;
14929 void Player::_LoadTutorials(QueryResult *result)
14931 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14933 if(result)
14937 Field *fields = result->Fetch();
14939 for (int iI=0; iI<8; iI++)
14940 m_Tutorials[iI] = fields[iI].GetUInt32();
14942 while( result->NextRow() );
14944 delete result;
14947 m_TutorialsChanged = false;
14950 void Player::_LoadGroup(QueryResult *result)
14952 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14953 if(result)
14955 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14956 delete result;
14957 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14958 if(group)
14960 uint8 subgroup = group->GetMemberGroup(GetGUID());
14961 SetGroup(group, subgroup);
14962 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14964 // the group leader may change the instance difficulty while the player is offline
14965 SetDifficulty(group->GetDifficulty());
14971 void Player::_LoadBoundInstances(QueryResult *result)
14973 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14974 m_boundInstances[i].clear();
14976 Group *group = GetGroup();
14978 //QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
14979 if(result)
14983 Field *fields = result->Fetch();
14984 bool perm = fields[1].GetBool();
14985 uint32 mapId = fields[2].GetUInt32();
14986 uint32 instanceId = fields[0].GetUInt32();
14987 uint8 difficulty = fields[3].GetUInt8();
14988 time_t resetTime = (time_t)fields[4].GetUInt64();
14989 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14990 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14991 // and in that case it is not used
14993 if(!perm && group)
14995 sLog.outError("_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d,%d,%d", GetName(), GetGUIDLow(), GUID_LOPART(group->GetLeaderGUID()), mapId, instanceId, difficulty);
14996 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14997 continue;
15000 // since non permanent binds are always solo bind, they can always be reset
15001 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15002 if(save) BindToInstance(save, perm, true);
15003 } while(result->NextRow());
15004 delete result;
15008 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15010 // some instances only have one difficulty
15011 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15012 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15014 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15015 if(itr != m_boundInstances[difficulty].end())
15016 return &itr->second;
15017 else
15018 return NULL;
15021 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15023 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15024 UnbindInstance(itr, difficulty, unload);
15027 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15029 if(itr != m_boundInstances[difficulty].end())
15031 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15032 itr->second.save->RemovePlayer(this); // save can become invalid
15033 m_boundInstances[difficulty].erase(itr++);
15037 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15039 if(save)
15041 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15042 if(bind.save)
15044 // update the save when the group kills a boss
15045 if(permanent != bind.perm || save != bind.save)
15046 if(!load) CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u' WHERE guid = '%u' AND instance = '%u'", save->GetInstanceId(), permanent, GetGUIDLow(), bind.save->GetInstanceId());
15048 else
15049 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15051 if(bind.save != save)
15053 if(bind.save) bind.save->RemovePlayer(this);
15054 save->AddPlayer(this);
15057 if(permanent) save->SetCanReset(false);
15059 bind.save = save;
15060 bind.perm = permanent;
15061 if(!load) sLog.outDebug("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty());
15062 return &bind;
15064 else
15065 return NULL;
15068 void Player::SendRaidInfo()
15070 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15072 uint32 counter = 0, i;
15073 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
15074 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15075 if(itr->second.perm) counter++;
15077 data << counter;
15078 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
15080 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15082 if(itr->second.perm)
15084 InstanceSave *save = itr->second.save;
15085 data << (save->GetMapId());
15086 data << (uint32)(save->GetResetTime() - time(NULL));
15087 data << save->GetInstanceId();
15088 data << uint32(counter);
15089 counter--;
15093 GetSession()->SendPacket(&data);
15097 - called on every successful teleportation to a map
15099 void Player::SendSavedInstances()
15101 bool hasBeenSaved = false;
15102 WorldPacket data;
15104 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15106 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15108 if(itr->second.perm) // only permanent binds are sent
15110 hasBeenSaved = true;
15111 break;
15116 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15117 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15118 data << uint32(hasBeenSaved);
15119 GetSession()->SendPacket(&data);
15121 if(!hasBeenSaved)
15122 return;
15124 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15126 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15128 if(itr->second.perm)
15130 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15131 data << uint32(itr->second.save->GetMapId());
15132 GetSession()->SendPacket(&data);
15138 /// convert the player's binds to the group
15139 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15141 bool has_binds = false;
15142 bool has_solo = false;
15144 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15145 assert(player_guid);
15147 // copy all binds to the group, when changing leader it's assumed the character
15148 // will not have any solo binds
15150 if(player)
15152 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15154 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15156 has_binds = true;
15157 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15158 // permanent binds are not removed
15159 if(!itr->second.perm)
15161 player->UnbindInstance(itr, i, true); // increments itr
15162 has_solo = true;
15164 else
15165 ++itr;
15170 // if the player's not online we don't know what binds it has
15171 if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
15172 // the following should not get executed when changing leaders
15173 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15176 bool Player::_LoadHomeBind(QueryResult *result)
15178 bool ok = false;
15179 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15180 if (result)
15182 Field *fields = result->Fetch();
15183 m_homebindMapId = fields[0].GetUInt32();
15184 m_homebindZoneId = fields[1].GetUInt16();
15185 m_homebindX = fields[2].GetFloat();
15186 m_homebindY = fields[3].GetFloat();
15187 m_homebindZ = fields[4].GetFloat();
15188 delete result;
15190 // accept saved data only for valid position (and non instanceable)
15191 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15192 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15194 ok = true;
15196 else
15197 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15200 if(!ok)
15202 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15203 if(!info) return false;
15205 m_homebindMapId = info->mapId;
15206 m_homebindZoneId = info->zoneId;
15207 m_homebindX = info->positionX;
15208 m_homebindY = info->positionY;
15209 m_homebindZ = info->positionZ;
15211 CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15214 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15215 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15217 return true;
15220 /*********************************************************/
15221 /*** SAVE SYSTEM ***/
15222 /*********************************************************/
15224 void Player::SaveToDB()
15226 // delay auto save at any saves (manual, in code, or autosave)
15227 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15229 // first save/honor gain after midnight will also update the player's honor fields
15230 UpdateHonorFields();
15232 // players aren't saved on battleground maps
15233 uint32 mapid = IsBeingTeleported() ? GetTeleportDest().mapid : GetMapId();
15234 const MapEntry * me = sMapStore.LookupEntry(mapid);
15235 if(!me || me->IsBattleGroundOrArena())
15236 return;
15238 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15239 //save, far from tavern/city
15240 //save, but in tavern/city
15241 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15242 outDebugValues();
15244 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15245 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15246 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15247 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15248 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15249 uint32 tmp_displayid = GetDisplayId();
15251 // Set player sit state to standing on save, also stealth and shifted form
15252 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15253 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15254 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15255 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15256 SetDisplayId(GetNativeDisplayId());
15258 bool inworld = IsInWorld();
15260 CharacterDatabase.BeginTransaction();
15262 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15264 std::string sql_name = m_name;
15265 CharacterDatabase.escape_string(sql_name);
15267 std::ostringstream ss;
15268 ss << "INSERT INTO characters (guid,account,name,race,class,"
15269 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15270 "taximask, online, cinematic, "
15271 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15272 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15273 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15274 << GetGUIDLow() << ", "
15275 << GetSession()->GetAccountId() << ", '"
15276 << sql_name << "', "
15277 << m_race << ", "
15278 << m_class << ", ";
15280 bool save_to_dest = false;
15281 if(IsBeingTeleported())
15283 // don't save to battlegrounds or arenas
15284 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15285 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15286 save_to_dest = true;
15289 if(!save_to_dest)
15291 ss << GetMapId() << ", "
15292 << (uint32)GetDifficulty() << ", "
15293 << finiteAlways(GetPositionX()) << ", "
15294 << finiteAlways(GetPositionY()) << ", "
15295 << finiteAlways(GetPositionZ()) << ", "
15296 << finiteAlways(GetOrientation()) << ", '";
15298 else
15300 ss << GetTeleportDest().mapid << ", "
15301 << (uint32)GetDifficulty() << ", "
15302 << finiteAlways(GetTeleportDest().x) << ", "
15303 << finiteAlways(GetTeleportDest().y) << ", "
15304 << finiteAlways(GetTeleportDest().z) << ", "
15305 << finiteAlways(GetTeleportDest().o) << ", '";
15308 uint16 i;
15309 for( i = 0; i < m_valuesCount; i++ )
15311 ss << GetUInt32Value(i) << " ";
15314 ss << "', '";
15316 for( i = 0; i < 8; i++ )
15317 ss << m_taxi.GetTaximask(i) << " ";
15319 ss << "', ";
15320 ss << (inworld ? 1 : 0);
15322 ss << ", ";
15323 ss << m_cinematic;
15325 ss << ", ";
15326 ss << m_Played_time[0];
15327 ss << ", ";
15328 ss << m_Played_time[1];
15330 ss << ", ";
15331 ss << finiteAlways(m_rest_bonus);
15332 ss << ", ";
15333 ss << (uint64)time(NULL);
15334 ss << ", ";
15335 ss << is_save_resting;
15336 ss << ", ";
15337 ss << m_resetTalentsCost;
15338 ss << ", ";
15339 ss << (uint64)m_resetTalentsTime;
15341 ss << ", ";
15342 ss << finiteAlways(m_movementInfo.t_x);
15343 ss << ", ";
15344 ss << finiteAlways(m_movementInfo.t_y);
15345 ss << ", ";
15346 ss << finiteAlways(m_movementInfo.t_z);
15347 ss << ", ";
15348 ss << finiteAlways(m_movementInfo.t_o);
15349 ss << ", ";
15350 if (m_transport)
15351 ss << m_transport->GetGUIDLow();
15352 else
15353 ss << "0";
15355 ss << ", ";
15356 ss << m_ExtraFlags;
15358 ss << ", ";
15359 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15361 ss << ", ";
15362 ss << uint32(m_atLoginFlags);
15364 ss << ", ";
15365 ss << GetZoneId();
15367 ss << ", ";
15368 ss << (uint64)m_deathExpireTime;
15370 ss << ", '";
15371 ss << m_taxi.SaveTaxiDestinationsToString();
15372 ss << "', '0' )";
15374 CharacterDatabase.Execute( ss.str().c_str() );
15376 if(m_mailsUpdated) //save mails only when needed
15377 _SaveMail();
15379 _SaveInventory();
15380 _SaveQuestStatus();
15381 _SaveDailyQuestStatus();
15382 _SaveTutorials();
15383 _SaveSpells();
15384 _SaveSpellCooldowns();
15385 _SaveActions();
15386 _SaveAuras();
15387 _SaveReputation();
15389 CharacterDatabase.CommitTransaction();
15391 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15392 SetDisplayId(tmp_displayid);
15393 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15394 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15395 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15396 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15398 // save pet (hunter pet level and experience and all type pets health/mana).
15399 if(Pet* pet = GetPet())
15400 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15401 m_achievementMgr.SaveToDB();
15404 // fast save function for item/money cheating preventing - save only inventory and money state
15405 void Player::SaveInventoryAndGoldToDB()
15407 _SaveInventory();
15408 //money is in data field
15409 SaveDataFieldToDB();
15412 void Player::_SaveActions()
15414 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15416 switch (itr->second.uState)
15418 case ACTIONBUTTON_NEW:
15419 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15420 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15421 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15422 ++itr;
15423 break;
15424 case ACTIONBUTTON_CHANGED:
15425 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15426 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15427 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15428 ++itr;
15429 break;
15430 case ACTIONBUTTON_DELETED:
15431 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15432 m_actionButtons.erase(itr++);
15433 break;
15434 default:
15435 ++itr;
15436 break;
15441 void Player::_SaveAuras()
15443 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15445 AuraMap const& auras = GetAuras();
15447 if (auras.empty())
15448 return;
15450 spellEffectPair lastEffectPair = auras.begin()->first;
15451 uint32 stackCounter = 1;
15453 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15455 if(itr == auras.end() || lastEffectPair != itr->first)
15457 AuraMap::const_iterator itr2 = itr;
15458 // save previous spellEffectPair to db
15459 itr2--;
15460 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15462 //skip all auras from spells that are passive or need a shapeshift
15463 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15465 //do not save single target auras (unless they were cast by the player)
15466 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15468 uint8 i;
15469 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15470 for (i = 0; i < 3; i++)
15471 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15472 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15473 break;
15475 if (i == 3)
15477 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15478 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15479 GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->m_procCharges));
15484 if(itr == auras.end())
15485 break;
15488 if (lastEffectPair == itr->first)
15489 stackCounter++;
15490 else
15492 lastEffectPair = itr->first;
15493 stackCounter = 1;
15498 void Player::_SaveInventory()
15500 // force items in buyback slots to new state
15501 // and remove those that aren't already
15502 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15504 Item *item = m_items[i];
15505 if (!item || item->GetState() == ITEM_NEW) continue;
15506 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15507 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15508 m_items[i]->FSetState(ITEM_NEW);
15511 // update enchantment durations
15512 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15514 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15517 // if no changes
15518 if (m_itemUpdateQueue.empty()) return;
15520 // do not save if the update queue is corrupt
15521 bool error = false;
15522 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15524 Item *item = m_itemUpdateQueue[i];
15525 if(!item || item->GetState() == ITEM_REMOVED) continue;
15526 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15528 if (test == NULL)
15530 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
15531 error = true;
15533 else if (test != item)
15535 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
15536 error = true;
15540 if (error)
15542 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15543 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15544 return;
15547 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15549 Item *item = m_itemUpdateQueue[i];
15550 if(!item) continue;
15552 Bag *container = item->GetContainer();
15553 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15555 switch(item->GetState())
15557 case ITEM_NEW:
15558 CharacterDatabase.PExecute("INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES ('%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetGUIDLow(), item->GetEntry());
15559 break;
15560 case ITEM_CHANGED:
15561 CharacterDatabase.PExecute("UPDATE character_inventory SET guid='%u', bag='%u', slot='%u', item_template='%u' WHERE item='%u'", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetEntry(), item->GetGUIDLow());
15562 break;
15563 case ITEM_REMOVED:
15564 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15565 break;
15566 case ITEM_UNCHANGED:
15567 break;
15570 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15572 m_itemUpdateQueue.clear();
15575 void Player::_SaveMail()
15577 if (!m_mailsLoaded)
15578 return;
15580 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15582 Mail *m = (*itr);
15583 if (m->state == MAIL_STATE_CHANGED)
15585 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15586 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15587 if(m->removedItems.size())
15589 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15590 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15591 m->removedItems.clear();
15593 m->state = MAIL_STATE_UNCHANGED;
15595 else if (m->state == MAIL_STATE_DELETED)
15597 if (m->HasItems())
15598 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15599 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15600 if (m->itemTextId)
15601 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15602 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15603 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15607 //deallocate deleted mails...
15608 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15610 if ((*itr)->state == MAIL_STATE_DELETED)
15612 Mail* m = *itr;
15613 m_mail.erase(itr);
15614 delete m;
15615 itr = m_mail.begin();
15617 else
15618 ++itr;
15621 m_mailsUpdated = false;
15624 void Player::_SaveQuestStatus()
15626 // we don't need transactions here.
15627 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15629 switch (i->second.uState)
15631 case QUEST_NEW :
15632 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15633 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15634 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
15635 break;
15636 case QUEST_CHANGED :
15637 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15638 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
15639 break;
15640 case QUEST_UNCHANGED:
15641 break;
15643 i->second.uState = QUEST_UNCHANGED;
15647 void Player::_SaveDailyQuestStatus()
15649 if(!m_DailyQuestChanged)
15650 return;
15652 m_DailyQuestChanged = false;
15654 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15656 // we don't need transactions here.
15657 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15658 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15659 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15660 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15661 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15664 void Player::_SaveReputation()
15666 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15668 if (itr->second.Changed)
15670 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15671 CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
15672 itr->second.Changed = false;
15677 void Player::_SaveSpells()
15679 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15681 ++next;
15682 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15683 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15684 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15685 CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,slot,active,disabled) VALUES ('%u', '%u', '%u','%u','%u')", GetGUIDLow(), itr->first, itr->second->slotId,itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0);
15687 if (itr->second->state == PLAYERSPELL_REMOVED)
15688 _removeSpell(itr->first);
15689 else
15690 itr->second->state = PLAYERSPELL_UNCHANGED;
15694 void Player::_SaveTutorials()
15696 if(!m_TutorialsChanged)
15697 return;
15699 uint32 Rows=0;
15700 // it's better than rebuilding indexes multiple times
15701 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15702 if(result)
15704 Rows = result->Fetch()[0].GetUInt32();
15705 delete result;
15708 if (Rows)
15710 CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15711 m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetSession()->GetAccountId(), realmID );
15713 else
15715 CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID, m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
15718 m_TutorialsChanged = false;
15721 void Player::outDebugValues() const
15723 if(!sLog.IsOutDebug()) // optimize disabled debug output
15724 return;
15726 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15727 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15728 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15729 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15730 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15731 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15732 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15733 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15734 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15735 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15736 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15737 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15740 /*********************************************************/
15741 /*** FLOOD FILTER SYSTEM ***/
15742 /*********************************************************/
15744 void Player::UpdateSpeakTime()
15746 // ignore chat spam protection for GMs in any mode
15747 if(GetSession()->GetSecurity() > SEC_PLAYER)
15748 return;
15750 time_t current = time (NULL);
15751 if(m_speakTime > current)
15753 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15754 if(!max_count)
15755 return;
15757 ++m_speakCount;
15758 if(m_speakCount >= max_count)
15760 // prevent overwrite mute time, if message send just before mutes set, for example.
15761 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15762 if(GetSession()->m_muteTime < new_mute)
15763 GetSession()->m_muteTime = new_mute;
15765 m_speakCount = 0;
15768 else
15769 m_speakCount = 0;
15771 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15774 bool Player::CanSpeak() const
15776 return GetSession()->m_muteTime <= time (NULL);
15779 /*********************************************************/
15780 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15781 /*********************************************************/
15783 void Player::SendAttackSwingNotInRange()
15785 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15786 GetSession()->SendPacket( &data );
15789 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15791 std::ostringstream ss;
15792 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15793 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15794 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15795 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15796 sLog.outDebug(ss.str().c_str());
15797 CharacterDatabase.Execute(ss.str().c_str());
15800 void Player::SaveDataFieldToDB()
15802 std::ostringstream ss;
15803 ss<<"UPDATE characters SET data='";
15805 for(uint16 i = 0; i < m_valuesCount; i++ )
15807 ss << GetUInt32Value(i) << " ";
15809 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15811 CharacterDatabase.Execute(ss.str().c_str());
15814 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15816 std::ostringstream ss2;
15817 ss2<<"UPDATE characters SET data='";
15818 int i=0;
15819 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15821 ss2<<tokens[i]<<" ";
15823 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15825 return CharacterDatabase.Execute(ss2.str().c_str());
15828 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15830 char buf[11];
15831 snprintf(buf,11,"%u",value);
15833 if(index >= tokens.size())
15834 return;
15836 tokens[index] = buf;
15839 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15841 Tokens tokens;
15842 if(!LoadValuesArrayFromDB(tokens,guid))
15843 return;
15845 if(index >= tokens.size())
15846 return;
15848 char buf[11];
15849 snprintf(buf,11,"%u",value);
15850 tokens[index] = buf;
15852 SaveValuesArrayInDB(tokens,guid);
15855 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15857 uint32 temp;
15858 memcpy(&temp, &value, sizeof(value));
15859 Player::SetUInt32ValueInDB(index, temp, guid);
15862 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15864 Tokens tokens;
15865 if(!LoadValuesArrayFromDB(tokens, guid))
15866 return;
15868 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15869 uint8 race = unit_bytes0 & 0xFF;
15870 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15872 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15873 if(!info)
15874 return;
15876 unit_bytes0 &= ~(0xFF << 16);
15877 unit_bytes0 |= (gender << 16);
15878 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15880 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15881 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15883 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15885 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15886 player_bytes2 &= ~0xFF;
15887 player_bytes2 |= facialHair;
15888 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15890 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15891 player_bytes3 &= ~0xFF;
15892 player_bytes3 |= gender;
15893 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15895 SaveValuesArrayInDB(tokens, guid);
15898 void Player::SendAttackSwingNotStanding()
15900 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15901 GetSession()->SendPacket( &data );
15904 void Player::SendAttackSwingDeadTarget()
15906 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15907 GetSession()->SendPacket( &data );
15910 void Player::SendAttackSwingCantAttack()
15912 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15913 GetSession()->SendPacket( &data );
15916 void Player::SendAttackSwingCancelAttack()
15918 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15919 GetSession()->SendPacket( &data );
15922 void Player::SendAttackSwingBadFacingAttack()
15924 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15925 GetSession()->SendPacket( &data );
15928 void Player::SendAutoRepeatCancel()
15930 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15931 data.append(GetPackGUID()); // may be it's target guid
15932 GetSession()->SendPacket( &data );
15935 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15937 WorldPacket data(SMSG_PLAY_SOUND, 4);
15938 data << Sound;
15939 if (OnlySelf)
15940 GetSession()->SendPacket( &data );
15941 else
15942 SendMessageToSet( &data, true );
15945 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15947 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15948 data << Area;
15949 data << Experience;
15950 GetSession()->SendPacket(&data);
15953 void Player::SendDungeonDifficulty(bool IsInGroup)
15955 uint8 val = 0x00000001;
15956 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15957 data << (uint32)GetDifficulty();
15958 data << uint32(val);
15959 data << uint32(IsInGroup);
15960 GetSession()->SendPacket(&data);
15963 void Player::SendResetFailedNotify(uint32 mapid)
15965 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15966 data << uint32(mapid);
15967 GetSession()->SendPacket(&data);
15970 /// Reset all solo instances and optionally send a message on success for each
15971 void Player::ResetInstances(uint8 method)
15973 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15975 // we assume that when the difficulty changes, all instances that can be reset will be
15976 uint8 dif = GetDifficulty();
15978 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15980 InstanceSave *p = itr->second.save;
15981 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15982 if(!entry || !p->CanReset())
15984 ++itr;
15985 continue;
15988 if(method == INSTANCE_RESET_ALL)
15990 // the "reset all instances" method can only reset normal maps
15991 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15993 ++itr;
15994 continue;
15998 // if the map is loaded, reset it
15999 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16000 if(map && map->IsDungeon())
16001 ((InstanceMap*)map)->Reset(method);
16003 // since this is a solo instance there should not be any players inside
16004 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16005 SendResetInstanceSuccess(p->GetMapId());
16007 p->DeleteFromDB();
16008 m_boundInstances[dif].erase(itr++);
16010 // the following should remove the instance save from the manager and delete it as well
16011 p->RemovePlayer(this);
16015 void Player::SendResetInstanceSuccess(uint32 MapId)
16017 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16018 data << MapId;
16019 GetSession()->SendPacket(&data);
16022 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16024 // TODO: find what other fail reasons there are besides players in the instance
16025 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16026 data << reason;
16027 data << MapId;
16028 GetSession()->SendPacket(&data);
16031 /*********************************************************/
16032 /*** Update timers ***/
16033 /*********************************************************/
16035 ///checks the 15 afk reports per 5 minutes limit
16036 void Player::UpdateAfkReport(time_t currTime)
16038 if(m_bgAfkReportedTimer <= currTime)
16040 m_bgAfkReportedCount = 0;
16041 m_bgAfkReportedTimer = currTime+5*MINUTE;
16045 void Player::UpdateContestedPvP(uint32 diff)
16047 if(!m_contestedPvPTimer||isInCombat())
16048 return;
16049 if(m_contestedPvPTimer <= diff)
16051 ResetContestedPvP();
16053 else
16054 m_contestedPvPTimer -= diff;
16057 void Player::UpdatePvPFlag(time_t currTime)
16059 if(!IsPvP())
16060 return;
16061 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16062 return;
16064 UpdatePvP(false);
16067 void Player::UpdateDuelFlag(time_t currTime)
16069 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16070 return;
16072 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16073 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16075 duel->startTimer = 0;
16076 duel->startTime = currTime;
16077 duel->opponent->duel->startTimer = 0;
16078 duel->opponent->duel->startTime = currTime;
16081 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16083 if(!pet)
16084 pet = GetPet();
16086 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16088 //returning of reagents only for players, so best done here
16089 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16090 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16092 if(spellInfo)
16094 for(uint32 i = 0; i < 7; ++i)
16096 if(spellInfo->Reagent[i] > 0)
16098 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16099 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16100 if( msg == EQUIP_ERR_OK )
16102 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16103 if(IsInWorld())
16104 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16109 m_temporaryUnsummonedPetNumber = 0;
16112 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16113 return;
16115 // only if current pet in slot
16116 switch(pet->getPetType())
16118 case MINI_PET:
16119 m_miniPet = 0;
16120 break;
16121 case GUARDIAN_PET:
16122 m_guardianPets.erase(pet->GetGUID());
16123 break;
16124 default:
16125 if(GetPetGUID() == pet->GetGUID())
16126 SetPet(NULL);
16127 break;
16130 pet->CombatStop();
16132 if(returnreagent)
16134 switch(pet->GetEntry())
16136 //warlock pets except imp are removed(?) when logging out
16137 case 1860:
16138 case 1863:
16139 case 417:
16140 case 17252:
16141 mode = PET_SAVE_NOT_IN_SLOT;
16142 break;
16146 pet->SavePetToDB(mode);
16148 pet->CleanupsBeforeDelete();
16149 pet->AddObjectToRemoveList();
16150 pet->m_removed = true;
16152 if(pet->isControlled())
16154 WorldPacket data(SMSG_PET_SPELLS, 8);
16155 data << uint64(0);
16156 data << uint32(0);
16157 GetSession()->SendPacket(&data);
16159 if(GetGroup())
16160 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16164 void Player::RemoveMiniPet()
16166 if(Pet* pet = GetMiniPet())
16168 pet->Remove(PET_SAVE_AS_DELETED);
16169 m_miniPet = 0;
16173 Pet* Player::GetMiniPet()
16175 if(!m_miniPet)
16176 return NULL;
16177 return ObjectAccessor::GetPet(m_miniPet);
16180 void Player::RemoveGuardians()
16182 while(!m_guardianPets.empty())
16184 uint64 guid = *m_guardianPets.begin();
16185 if(Pet* pet = ObjectAccessor::GetPet(guid))
16186 pet->Remove(PET_SAVE_AS_DELETED);
16188 m_guardianPets.erase(guid);
16192 bool Player::HasGuardianWithEntry(uint32 entry)
16194 // pet guid middle part is entry (and creature also)
16195 // and in guardian list must be guardians with same entry _always_
16196 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16197 if(GUID_ENPART(*itr)==entry)
16198 return true;
16200 return false;
16203 void Player::Uncharm()
16205 Unit* charm = GetCharm();
16206 if(!charm)
16207 return;
16209 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16210 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16213 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16215 *data << (uint8)msgtype;
16216 *data << (uint32)language;
16217 *data << (uint64)GetGUID();
16218 *data << (uint32)language; //language 2.1.0 ?
16219 *data << (uint64)GetGUID();
16220 *data << (uint32)(text.length()+1);
16221 *data << text;
16222 *data << (uint8)chatTag();
16225 void Player::Say(const std::string& text, const uint32 language)
16227 WorldPacket data(SMSG_MESSAGECHAT, 200);
16228 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16229 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16232 void Player::Yell(const std::string& text, const uint32 language)
16234 WorldPacket data(SMSG_MESSAGECHAT, 200);
16235 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16236 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16239 void Player::TextEmote(const std::string& text)
16241 WorldPacket data(SMSG_MESSAGECHAT, 200);
16242 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16243 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16246 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16248 if (language != LANG_ADDON) // if not addon data
16249 language = LANG_UNIVERSAL; // whispers should always be readable
16251 Player *rPlayer = objmgr.GetPlayer(receiver);
16253 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16254 if(!rPlayer->isDND() || isGameMaster())
16256 WorldPacket data(SMSG_MESSAGECHAT, 200);
16257 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16258 rPlayer->GetSession()->SendPacket(&data);
16260 data.Initialize(SMSG_MESSAGECHAT, 200);
16261 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16262 GetSession()->SendPacket(&data);
16264 else
16266 // announce to player that player he is whispering to is dnd and cannot receive his message
16267 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16270 if(!isAcceptWhispers())
16272 SetAcceptWhispers(true);
16273 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16276 // announce to player that player he is whispering to is afk
16277 if(rPlayer->isAFK())
16278 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16280 // if player whisper someone, auto turn of dnd to be able to receive an answer
16281 if(isDND() && !rPlayer->isGameMaster())
16282 ToggleDND();
16285 void Player::PetSpellInitialize()
16287 Pet* pet = GetPet();
16289 if(!pet)
16290 return;
16292 sLog.outDebug("Pet Spells Groups");
16294 CharmInfo *charmInfo = pet->GetCharmInfo();
16296 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16297 data << uint64(pet->GetGUID());
16298 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16299 data << uint32(0);
16300 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16302 // action bar loop
16303 for(uint32 i = 0; i < 10; i++)
16305 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16308 size_t spellsCountPos = data.wpos();
16310 // spells count
16311 uint8 addlist = 0;
16312 data << uint8(addlist); // placeholder
16314 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16316 // spells loop
16317 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16319 if(itr->second->state == PETSPELL_REMOVED)
16320 continue;
16322 data << uint16(itr->first);
16323 data << uint16(itr->second->active); // pet spell active state isn't boolean
16324 ++addlist;
16328 data.put<uint8>(spellsCountPos, addlist);
16330 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16331 data << uint8(cooldownsCount);
16333 time_t curTime = time(NULL);
16335 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16337 time_t cooldown = 0;
16339 if(itr->second > curTime)
16340 cooldown = (itr->second - curTime) * 1000;
16342 data << uint16(itr->first); // spellid
16343 data << uint16(0); // spell category?
16344 data << uint32(itr->second); // cooldown
16345 data << uint32(0); // category cooldown
16348 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16350 time_t cooldown = 0;
16352 if(itr->second > curTime)
16353 cooldown = (itr->second - curTime) * 1000;
16355 data << uint16(itr->first); // spellid
16356 data << uint16(0); // spell category?
16357 data << uint32(0); // cooldown
16358 data << uint32(itr->second); // category cooldown
16361 GetSession()->SendPacket(&data);
16364 void Player::PossessSpellInitialize()
16366 Unit* charm = GetCharm();
16368 if(!charm)
16369 return;
16371 CharmInfo *charmInfo = charm->GetCharmInfo();
16373 if(!charmInfo)
16375 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16376 return;
16379 uint8 addlist = 0;
16380 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16382 //16
16383 data << uint64(charm->GetGUID());
16384 data << uint32(0x00000000);
16385 data << uint32(0);
16386 data << uint8(0) << uint8(0) << uint16(0);
16388 for(uint32 i = 0; i < 10; i++) //40
16390 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16393 data << uint8(addlist); //1
16395 uint8 count = 0;
16396 data << uint8(count); // cooldowns count
16398 GetSession()->SendPacket(&data);
16401 void Player::CharmSpellInitialize()
16403 Unit* charm = GetCharm();
16405 if(!charm)
16406 return;
16408 CharmInfo *charmInfo = charm->GetCharmInfo();
16409 if(!charmInfo)
16411 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16412 return;
16415 uint8 addlist = 0;
16417 if(charm->GetTypeId() != TYPEID_PLAYER)
16419 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16421 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16423 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16425 if(charmInfo->GetCharmSpell(i)->spellId)
16426 ++addlist;
16431 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16433 data << uint64(charm->GetGUID());
16434 data << uint32(0x00000000);
16435 data << uint32(0);
16436 if(charm->GetTypeId() != TYPEID_PLAYER)
16437 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16438 else
16439 data << uint8(0) << uint8(0);
16440 data << uint16(0);
16442 for(uint32 i = 0; i < 10; i++) //40
16444 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16447 data << uint8(addlist); //1
16449 if(addlist)
16451 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16453 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16454 if(cspell->spellId)
16456 data << uint16(cspell->spellId);
16457 data << uint16(cspell->active);
16462 uint8 count = 0;
16463 data << uint8(count); // cooldowns count
16465 GetSession()->SendPacket(&data);
16468 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16470 if (!mod || !spellInfo)
16471 return false;
16473 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16475 // prevent apply to any spell except spell that trigger expire
16476 if(spell)
16478 if(mod->lastAffected != spell)
16479 return false;
16481 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16482 return false;
16485 return spellmgr.IsAffectedByMod(spellInfo, mod);
16488 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16490 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16492 for(int eff=0;eff<96;++eff)
16494 uint64 _mask = 0;
16495 uint64 _mask2= 0;
16496 if (eff<64) _mask = uint64(1) << (eff- 0);
16497 else _mask2= uint64(1) << (eff-64);
16498 if ( mod->mask & _mask || mod->mask2 & _mask2)
16500 int32 val = 0;
16501 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16503 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16504 val += (*itr)->value;
16506 val += apply ? mod->value : -(mod->value);
16507 WorldPacket data(Opcode, (1+1+4));
16508 data << uint8(eff);
16509 data << uint8(mod->op);
16510 data << int32(val);
16511 SendDirectMessage(&data);
16515 if (apply)
16516 m_spellMods[mod->op].push_back(mod);
16517 else
16519 if (mod->charges == -1)
16520 --m_SpellModRemoveCount;
16521 m_spellMods[mod->op].remove(mod);
16522 delete mod;
16526 void Player::RemoveSpellMods(Spell const* spell)
16528 if(!spell || (m_SpellModRemoveCount == 0))
16529 return;
16531 for(int i=0;i<MAX_SPELLMOD;++i)
16533 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16535 SpellModifier *mod = *itr;
16536 ++itr;
16538 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16540 RemoveAurasDueToSpell(mod->spellId);
16541 if (m_spellMods[i].empty())
16542 break;
16543 else
16544 itr = m_spellMods[i].begin();
16550 // send Proficiency
16551 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16553 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16554 data << pr1 << pr2;
16555 GetSession()->SendPacket (&data);
16558 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16560 QueryResult *result = NULL;
16561 if(type==10)
16562 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16563 else
16564 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16565 if(result)
16567 do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
16568 { // and SendPetitionQueryOpcode reads data from the DB
16569 Field *fields = result->Fetch();
16570 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16571 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16573 // send update if charter owner in game
16574 Player* owner = objmgr.GetPlayer(ownerguid);
16575 if(owner)
16576 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16578 } while ( result->NextRow() );
16580 delete result;
16582 if(type==10)
16583 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16584 else
16585 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16588 CharacterDatabase.BeginTransaction();
16589 if(type == 10)
16591 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16592 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16594 else
16596 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16597 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16599 CharacterDatabase.CommitTransaction();
16602 void Player::LeaveAllArenaTeams(uint64 guid)
16604 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", GUID_LOPART(guid));
16605 if(!result)
16606 return;
16610 Field *fields = result->Fetch();
16611 uint32 at_id = fields[0].GetUInt32();
16612 if(at_id != 0)
16614 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16615 if(at)
16616 at->DelMember(guid);
16618 } while (result->NextRow());
16620 delete result;
16623 void Player::SetRestBonus (float rest_bonus_new)
16625 // Prevent resting on max level
16626 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16627 rest_bonus_new = 0;
16629 if(rest_bonus_new < 0)
16630 rest_bonus_new = 0;
16632 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16634 if(rest_bonus_new > rest_bonus_max)
16635 m_rest_bonus = rest_bonus_max;
16636 else
16637 m_rest_bonus = rest_bonus_new;
16639 // update data for client
16640 if(m_rest_bonus>10)
16641 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16642 else if(m_rest_bonus<=1)
16643 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16645 //RestTickUpdate
16646 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16649 void Player::HandleStealthedUnitsDetection()
16651 std::list<Unit*> stealthedUnits;
16653 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16654 Cell cell(p);
16655 cell.data.Part.reserved = ALL_DISTRICT;
16656 cell.SetNoCreate();
16658 MaNGOS::AnyStealthedCheck u_check;
16659 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16661 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16662 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16664 CellLock<GridReadGuard> cell_lock(cell, p);
16665 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16666 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16668 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16670 if((*i)==this)
16672 i = stealthedUnits.erase(i);
16673 continue;
16676 if ((*i)->isVisibleForOrDetect(this,true))
16679 (*i)->SendUpdateToPlayer(this);
16680 m_clientGUIDs.insert((*i)->GetGUID());
16682 #ifdef MANGOS_DEBUG
16683 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16684 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16685 #endif
16687 // target aura duration for caster show only if target exist at caster client
16688 // send data at target visibility change (adding to client)
16689 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16690 SendAurasForTarget(*i);
16692 i = stealthedUnits.erase(i);
16693 continue;
16696 ++i;
16700 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16702 if(nodes.size() < 2)
16703 return false;
16705 // not let cheating with start flight mounted
16706 if(IsMounted())
16708 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16709 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16710 GetSession()->SendPacket(&data);
16711 return false;
16714 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16716 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16717 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16718 GetSession()->SendPacket(&data);
16719 return false;
16722 // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
16723 if(GetSession()->isLogingOut() ||
16724 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16725 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16726 IsNonMeleeSpellCasted(false) ||
16727 isInCombat())
16729 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16730 data << uint32(ERR_TAXIPLAYERBUSY);
16731 GetSession()->SendPacket(&data);
16732 return false;
16735 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16736 return false;
16738 uint32 sourcenode = nodes[0];
16740 // starting node too far away (cheat?)
16741 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16742 if( !node || node->map_id != GetMapId() ||
16743 (node->x - GetPositionX())*(node->x - GetPositionX())+
16744 (node->y - GetPositionY())*(node->y - GetPositionY())+
16745 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16746 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16748 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16749 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16750 GetSession()->SendPacket(&data);
16751 return false;
16754 // Prepare to flight start now
16756 // stop combat at start taxi flight if any
16757 CombatStop();
16759 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16760 TradeCancel(true);
16762 // clean not finished taxi path if any
16763 m_taxi.ClearTaxiDestinations();
16765 // 0 element current node
16766 m_taxi.AddTaxiDestination(sourcenode);
16768 // fill destinations path tail
16769 uint32 sourcepath = 0;
16770 uint32 totalcost = 0;
16772 uint32 prevnode = sourcenode;
16773 uint32 lastnode = 0;
16775 for(uint32 i = 1; i < nodes.size(); ++i)
16777 uint32 path, cost;
16779 lastnode = nodes[i];
16780 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16782 if(!path)
16784 m_taxi.ClearTaxiDestinations();
16785 return false;
16788 totalcost += cost;
16790 if(prevnode == sourcenode)
16791 sourcepath = path;
16793 m_taxi.AddTaxiDestination(lastnode);
16795 prevnode = lastnode;
16798 if(!mount_id) // if not provide then attempt use default.
16799 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16801 if (mount_id == 0 || sourcepath == 0)
16803 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16804 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16805 GetSession()->SendPacket(&data);
16806 m_taxi.ClearTaxiDestinations();
16807 return false;
16810 uint32 money = GetMoney();
16812 if(npc)
16814 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16817 if(money < totalcost)
16819 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16820 data << uint32(ERR_TAXINOTENOUGHMONEY);
16821 GetSession()->SendPacket(&data);
16822 m_taxi.ClearTaxiDestinations();
16823 return false;
16826 //Checks and preparations done, DO FLIGHT
16827 ModifyMoney(-(int32)totalcost);
16829 // prevent stealth flight
16830 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16832 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16833 data << uint32(ERR_TAXIOK);
16834 GetSession()->SendPacket(&data);
16836 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16838 GetSession()->SendDoFlight(mount_id, sourcepath);
16840 return true;
16843 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16845 // last check 2.0.10
16846 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16847 data << GetGUID();
16848 data << uint8(0x0); // flags (0x1, 0x2)
16849 time_t curTime = time(NULL);
16850 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16852 if (itr->second->state == PLAYERSPELL_REMOVED)
16853 continue;
16854 uint32 unSpellId = itr->first;
16855 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16856 if (!spellInfo)
16858 ASSERT(spellInfo);
16859 continue;
16862 // Not send cooldown for this spells
16863 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16864 continue;
16866 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16868 data << unSpellId;
16869 data << unTimeMs; // in m.secs
16870 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16873 GetSession()->SendPacket(&data);
16876 void Player::InitDataForForm(bool reapplyMods)
16878 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16879 if(ssEntry && ssEntry->attackSpeed)
16881 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16882 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16883 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16885 else
16886 SetRegularAttackTime();
16888 switch(m_form)
16890 case FORM_CAT:
16892 if(getPowerType()!=POWER_ENERGY)
16893 setPowerType(POWER_ENERGY);
16894 break;
16896 case FORM_BEAR:
16897 case FORM_DIREBEAR:
16899 if(getPowerType()!=POWER_RAGE)
16900 setPowerType(POWER_RAGE);
16901 break;
16903 default: // 0, for example
16905 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16906 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16907 setPowerType(Powers(cEntry->powerType));
16908 break;
16912 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16913 if (!reapplyMods)
16914 UpdateEquipSpellsAtFormChange();
16916 UpdateAttackPowerAndDamage();
16917 UpdateAttackPowerAndDamage(true);
16920 // Return true is the bought item has a max count to force refresh of window by caller
16921 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16923 // cheating attempt
16924 if(count < 1) count = 1;
16926 if(!isAlive())
16927 return false;
16929 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16930 if( !pProto )
16932 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16933 return false;
16936 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16937 if (!pCreature)
16939 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16940 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16941 return false;
16944 VendorItemData const* vItems = pCreature->GetVendorItems();
16945 if(!vItems || vItems->Empty())
16947 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16948 return false;
16951 size_t vendor_slot = vItems->FindItemSlot(item);
16952 if(vendor_slot >= vItems->GetItemCount())
16954 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16955 return false;
16958 VendorItem const* crItem = vItems->m_items[vendor_slot];
16960 // check current item amount if it limited
16961 if( crItem->maxcount != 0 )
16963 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16965 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16966 return false;
16970 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16972 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16973 return false;
16976 if(crItem->ExtendedCost)
16978 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16979 if(!iece)
16981 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16982 return false;
16985 // honor points price
16986 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16988 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16989 return false;
16992 // arena points price
16993 if(GetArenaPoints() < (iece->reqarenapoints * count))
16995 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16996 return false;
16999 // item base price
17000 for (uint8 i = 0; i < 5; ++i)
17002 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17004 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17005 return false;
17009 // check for personal arena rating requirement
17010 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17012 // probably not the proper equip err
17013 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17014 return false;
17018 uint32 price = pProto->BuyPrice * count;
17020 // reputation discount
17021 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17023 if( GetMoney() < price )
17025 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17026 return false;
17029 uint8 bag = 0; // init for case invalid bagGUID
17031 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17033 Bag *pBag;
17034 if( bagguid == GetGUID() )
17036 bag = INVENTORY_SLOT_BAG_0;
17038 else
17040 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17042 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17043 if( pBag )
17045 if( bagguid == pBag->GetGUID() )
17047 bag = i;
17048 break;
17055 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17057 ItemPosCountVec dest;
17058 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17059 if( msg != EQUIP_ERR_OK )
17061 SendEquipError( msg, NULL, NULL );
17062 return false;
17065 ModifyMoney( -(int32)price );
17066 if(crItem->ExtendedCost) // case for new honor system
17068 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17069 if(iece->reqhonorpoints)
17070 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17071 if(iece->reqarenapoints)
17072 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17073 for (uint8 i = 0; i < 5; ++i)
17075 if(iece->reqitem[i])
17076 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17080 if(Item *it = StoreNewItem( dest, item, true ))
17082 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17084 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17085 data << pCreature->GetGUID();
17086 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17087 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17088 data << (uint32)count;
17089 GetSession()->SendPacket(&data);
17091 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17094 else if( IsEquipmentPos( bag, slot ) )
17096 if(pProto->BuyCount * count != 1)
17098 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17099 return false;
17102 uint16 dest;
17103 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17104 if( msg != EQUIP_ERR_OK )
17106 SendEquipError( msg, NULL, NULL );
17107 return false;
17110 ModifyMoney( -(int32)price );
17111 if(crItem->ExtendedCost) // case for new honor system
17113 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17114 if(iece->reqhonorpoints)
17115 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17116 if(iece->reqarenapoints)
17117 ModifyArenaPoints( - int32(iece->reqarenapoints));
17118 for (uint8 i = 0; i < 5; ++i)
17120 if(iece->reqitem[i])
17121 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17125 if(Item *it = EquipNewItem( dest, item, true ))
17127 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17129 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17130 data << pCreature->GetGUID();
17131 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17132 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17133 data << (uint32)count;
17134 GetSession()->SendPacket(&data);
17136 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17138 AutoUnequipOffhandIfNeed();
17141 else
17143 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17144 return false;
17147 return crItem->maxcount!=0;
17150 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17152 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17153 // the personal rating of the arena team must match the required limit as well
17154 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17155 uint32 max_personal_rating = 0;
17156 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17158 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17160 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17161 uint32 t_rating = at->GetRating();
17162 p_rating = p_rating<t_rating? p_rating : t_rating;
17163 if(max_personal_rating < p_rating)
17164 max_personal_rating = p_rating;
17167 return max_personal_rating;
17170 void Player::UpdateHomebindTime(uint32 time)
17172 // GMs never get homebind timer online
17173 if (m_InstanceValid || isGameMaster())
17175 if(m_HomebindTimer) // instance valid, but timer not reset
17177 // hide reminder
17178 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17179 data << uint32(0);
17180 data << uint32(0);
17181 GetSession()->SendPacket(&data);
17183 // instance is valid, reset homebind timer
17184 m_HomebindTimer = 0;
17186 else if (m_HomebindTimer > 0)
17188 if (time >= m_HomebindTimer)
17190 // teleport to homebind location
17191 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17193 else
17194 m_HomebindTimer -= time;
17196 else
17198 // instance is invalid, start homebind timer
17199 m_HomebindTimer = 60000;
17200 // send message to player
17201 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17202 data << m_HomebindTimer;
17203 data << uint32(1);
17204 GetSession()->SendPacket(&data);
17205 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17209 void Player::UpdatePvP(bool state, bool ovrride)
17211 if(!state || ovrride)
17213 SetPvP(state);
17214 if(Pet* pet = GetPet())
17215 pet->SetPvP(state);
17216 if(Unit* charmed = GetCharm())
17217 charmed->SetPvP(state);
17219 pvpInfo.endTimer = 0;
17221 else
17223 if(pvpInfo.endTimer != 0)
17224 pvpInfo.endTimer = time(NULL);
17225 else
17227 SetPvP(state);
17229 if(Pet* pet = GetPet())
17230 pet->SetPvP(state);
17231 if(Unit* charmed = GetCharm())
17232 charmed->SetPvP(state);
17237 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17239 SpellCooldown sc;
17240 sc.end = end_time;
17241 sc.itemid = itemid;
17242 m_spellCooldowns[spellid] = sc;
17245 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17247 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17248 return;
17250 // Get spell cooldown
17251 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17252 // Apply spellmods
17253 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17254 if (cooldown < 0)
17255 cooldown = 0;
17256 // Add cooldown
17257 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17258 // Send activate
17259 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17260 data << spellInfo->Id;
17261 data << GetGUID();
17262 SendDirectMessage(&data);
17264 //slot to be excluded while counting
17265 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17267 if(!enchantmentcondition)
17268 return true;
17270 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17272 if(!Condition)
17273 return true;
17275 uint8 curcount[4] = {0, 0, 0, 0};
17277 //counting current equipped gem colors
17278 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17280 if(i == slot)
17281 continue;
17282 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17283 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17285 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17287 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17288 if(!enchant_id)
17289 continue;
17291 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17292 if(!enchantEntry)
17293 continue;
17295 uint32 gemid = enchantEntry->GemID;
17296 if(!gemid)
17297 continue;
17299 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17300 if(!gemProto)
17301 continue;
17303 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17304 if(!gemProperty)
17305 continue;
17307 uint8 GemColor = gemProperty->color;
17309 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17311 if(tmpcolormask & GemColor)
17312 ++curcount[b];
17318 bool activate = true;
17320 for(int i = 0; i < 5; i++)
17322 if(!Condition->Color[i])
17323 continue;
17325 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17327 // if have <CompareColor> use them as count, else use <value> from Condition
17328 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17330 switch(Condition->Comparator[i])
17332 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17333 activate &= (_cur_gem < _cmp_gem) ? true : false;
17334 break;
17335 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17336 activate &= (_cur_gem > _cmp_gem) ? true : false;
17337 break;
17338 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17339 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17340 break;
17344 sLog.outDebug("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
17346 return activate;
17349 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17351 //cycle all equipped items
17352 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17354 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17355 if(slot == exceptslot)
17356 continue;
17358 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17360 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17361 continue;
17363 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17365 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17366 if(!enchant_id)
17367 continue;
17369 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17370 if(!enchantEntry)
17371 continue;
17373 uint32 condition = enchantEntry->EnchantmentCondition;
17374 if(condition)
17376 //was enchant active with/without item?
17377 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17378 //should it now be?
17379 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17381 // ignore item gem conditions
17382 //if state changed, (dis)apply enchant
17383 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17390 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17391 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17393 //cycle all equipped items
17394 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17396 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17397 if(slot == exceptslot)
17398 continue;
17400 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17402 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17403 continue;
17405 //cycle all (gem)enchants
17406 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17408 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17409 if(!enchant_id) //if no enchant go to next enchant(slot)
17410 continue;
17412 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17413 if(!enchantEntry)
17414 continue;
17416 //only metagems to be (de)activated, so only enchants with condition
17417 uint32 condition = enchantEntry->EnchantmentCondition;
17418 if(condition)
17419 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17424 void Player::LeaveBattleground(bool teleportToEntryPoint)
17426 if(BattleGround *bg = GetBattleGround())
17428 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17430 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17432 // call after remove to be sure that player resurrected for correct cast
17433 if(need_debuf)
17434 CastSpell(this, 26013, true); // Deserter
17438 bool Player::CanJoinToBattleground() const
17440 // check Deserter debuff
17441 if(GetDummyAura(26013))
17442 return false;
17444 return true;
17447 bool Player::CanReportAfkDueToLimit()
17449 // a player can complain about 15 people per 5 minutes
17450 if(m_bgAfkReportedCount >= 15)
17451 return false;
17452 ++m_bgAfkReportedCount;
17453 return true;
17456 ///This player has been blamed to be inactive in a battleground
17457 void Player::ReportedAfkBy(Player* reporter)
17459 BattleGround *bg = GetBattleGround();
17460 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17461 return;
17463 // check if player has 'Idle' or 'Inactive' debuff
17464 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17466 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17467 // 3 players have to complain to apply debuff
17468 if(m_bgAfkReporter.size() >= 3)
17470 // cast 'Idle' spell
17471 CastSpell(this, 43680, true);
17472 m_bgAfkReporter.clear();
17477 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17479 // gamemaster in GM mode see all, including ghosts
17480 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17481 return true;
17483 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17484 if (InBattleGround())
17486 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17487 return false;
17488 return true;
17491 // Live player see live player or dead player with not realized corpse
17492 if(pl->isAlive() || pl->m_deathTimer > 0)
17494 return isAlive() || m_deathTimer > 0;
17497 // Ghost see other friendly ghosts, that's for sure
17498 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17499 return true;
17501 // Dead player see live players near own corpse
17502 if(isAlive())
17504 Corpse *corpse = pl->GetCorpse();
17505 if(corpse)
17507 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17508 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17509 return true;
17513 // and not see any other
17514 return false;
17517 bool Player::IsVisibleGloballyFor( Player* u ) const
17519 if(!u)
17520 return false;
17522 // Always can see self
17523 if (u==this)
17524 return true;
17526 // Visible units, always are visible for all players
17527 if (GetVisibility() == VISIBILITY_ON)
17528 return true;
17530 // GMs are visible for higher gms (or players are visible for gms)
17531 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17532 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17534 // non faction visibility non-breakable for non-GMs
17535 if (GetVisibility() == VISIBILITY_OFF)
17536 return false;
17538 // non-gm stealth/invisibility not hide from global player lists
17539 return true;
17542 void Player::UpdateVisibilityOf(WorldObject* target)
17544 if(HaveAtClient(target))
17546 if(!target->isVisibleForInState(this,true))
17548 target->DestroyForPlayer(this);
17549 m_clientGUIDs.erase(target->GetGUID());
17551 #ifdef MANGOS_DEBUG
17552 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17553 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17554 #endif
17557 else
17559 if(target->isVisibleForInState(this,false))
17561 target->SendUpdateToPlayer(this);
17562 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17563 m_clientGUIDs.insert(target->GetGUID());
17565 #ifdef MANGOS_DEBUG
17566 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17567 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17568 #endif
17570 // target aura duration for caster show only if target exist at caster client
17571 // send data at target visibility change (adding to client)
17572 if(target!=this && target->isType(TYPEMASK_UNIT))
17573 SendAurasForTarget((Unit*)target);
17575 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17576 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17581 template<class T>
17582 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17584 s64.insert(target->GetGUID());
17587 template<>
17588 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17590 if(!target->IsTransport())
17591 s64.insert(target->GetGUID());
17594 template<class T>
17595 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17597 if(HaveAtClient(target))
17599 if(!target->isVisibleForInState(this,true))
17601 target->BuildOutOfRangeUpdateBlock(&data);
17602 m_clientGUIDs.erase(target->GetGUID());
17604 #ifdef MANGOS_DEBUG
17605 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17606 sLog.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
17607 #endif
17610 else
17612 if(target->isVisibleForInState(this,false))
17614 visibleNow.insert(target);
17615 target->BuildUpdate(data_updates);
17616 target->BuildCreateUpdateBlockForPlayer(&data, this);
17617 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17619 #ifdef MANGOS_DEBUG
17620 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17621 sLog.outDebug("Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
17622 #endif
17627 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17628 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17629 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17630 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17631 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17633 void Player::InitPrimaryProffesions()
17635 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17638 void Player::SendComboPoints()
17640 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17641 if (combotarget)
17643 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17644 data.append(combotarget->GetPackGUID());
17645 data << uint8(m_comboPoints);
17646 GetSession()->SendPacket(&data);
17650 void Player::AddComboPoints(Unit* target, int8 count)
17652 if(!count)
17653 return;
17655 // without combo points lost (duration checked in aura)
17656 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17658 if(target->GetGUID() == m_comboTarget)
17660 m_comboPoints += count;
17662 else
17664 if(m_comboTarget)
17665 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17666 target->RemoveComboPointHolder(GetGUIDLow());
17668 m_comboTarget = target->GetGUID();
17669 m_comboPoints = count;
17671 target->AddComboPointHolder(GetGUIDLow());
17674 if (m_comboPoints > 5) m_comboPoints = 5;
17675 if (m_comboPoints < 0) m_comboPoints = 0;
17677 SendComboPoints();
17680 void Player::ClearComboPoints()
17682 if(!m_comboTarget)
17683 return;
17685 // without combopoints lost (duration checked in aura)
17686 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17688 m_comboPoints = 0;
17690 SendComboPoints();
17692 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17693 target->RemoveComboPointHolder(GetGUIDLow());
17695 m_comboTarget = 0;
17698 void Player::SetGroup(Group *group, int8 subgroup)
17700 if(group == NULL) m_group.unlink();
17701 else
17703 // never use SetGroup without a subgroup unless you specify NULL for group
17704 assert(subgroup >= 0);
17705 m_group.link(group, this);
17706 m_group.setSubGroup((uint8)subgroup);
17710 void Player::SendInitialPacketsBeforeAddToMap()
17712 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17713 data << uint32(0); // unknown, may be rest state time or experience
17714 GetSession()->SendPacket(&data);
17716 // Homebind
17717 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17718 data << m_homebindX << m_homebindY << m_homebindZ;
17719 data << (uint32) m_homebindMapId;
17720 data << (uint32) m_homebindZoneId;
17721 GetSession()->SendPacket(&data);
17723 // SMSG_SET_PROFICIENCY
17724 // SMSG_UPDATE_AURA_DURATION
17726 // tutorial stuff
17727 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17728 for (int i = 0; i < 8; ++i)
17729 data << uint32( GetTutorialInt(i) );
17730 GetSession()->SendPacket(&data);
17732 SendInitialSpells();
17734 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17735 data << uint32(0); // count, for(count) uint32;
17736 GetSession()->SendPacket(&data);
17738 SendInitialActionButtons();
17739 SendInitialReputations();
17740 m_achievementMgr.SendAllAchievementData();
17741 UpdateZone(GetZoneId());
17742 SendInitWorldStates();
17744 // SMSG_SET_AURA_SINGLE
17746 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17747 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17748 data << (float)0.01666667f; // game speed
17749 GetSession()->SendPacket( &data );
17751 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17752 data << uint32(0x00000000); // on blizz it increments periodically
17753 GetSession()->SendPacket(&data);
17755 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17756 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17757 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17759 m_mover = this;
17762 void Player::SendInitialPacketsAfterAddToMap()
17764 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17765 data << uint32(0x00000000); // on blizz it increments periodically
17766 GetSession()->SendPacket(&data);
17768 CastSpell(this, 836, true); // LOGINEFFECT
17770 // set some aura effects that send packet to player client after add player to map
17771 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17772 // same auras state lost at far teleport, send it one more time in this case also
17773 static const AuraType auratypes[] =
17775 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17776 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17777 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17779 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17781 Unit::AuraList const& auraList = GetAurasByType(*itr);
17782 if(!auraList.empty())
17783 auraList.front()->ApplyModifier(true,true);
17786 if(HasAuraType(SPELL_AURA_MOD_STUN))
17787 SetMovement(MOVE_ROOT);
17789 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17790 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17792 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17793 data.append(GetPackGUID());
17794 data << (uint32)2;
17795 SendMessageToSet(&data,true);
17798 SendAurasForTarget(this);
17799 SendEnchantmentDurations(); // must be after add to map
17800 SendItemDurations(); // must be after add to map
17803 void Player::SendUpdateToOutOfRangeGroupMembers()
17805 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17806 return;
17807 if(Group* group = GetGroup())
17808 group->UpdatePlayerOutOfRange(this);
17810 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17811 m_auraUpdateMask = 0;
17812 if(Pet *pet = GetPet())
17813 pet->ResetAuraUpdateMask();
17816 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17818 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17819 data << uint32(mapid);
17820 data << uint8(reason); // transfer abort reason
17821 switch(reason)
17823 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17824 case TRANSFER_ABORT_DIFFICULTY:
17825 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17826 data << uint8(arg);
17827 break;
17829 GetSession()->SendPacket(&data);
17832 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17834 // type of warning, based on the time remaining until reset
17835 uint32 type;
17836 if(time > 3600)
17837 type = RAID_INSTANCE_WELCOME;
17838 else if(time > 900 && time <= 3600)
17839 type = RAID_INSTANCE_WARNING_HOURS;
17840 else if(time > 300 && time <= 900)
17841 type = RAID_INSTANCE_WARNING_MIN;
17842 else
17843 type = RAID_INSTANCE_WARNING_MIN_SOON;
17844 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17845 data << uint32(type);
17846 data << uint32(mapid);
17847 data << uint32(time);
17848 GetSession()->SendPacket(&data);
17851 void Player::ApplyEquipCooldown( Item * pItem )
17853 for(int i = 0; i <5; ++i)
17855 _Spell const& spellData = pItem->GetProto()->Spells[i];
17857 // no spell
17858 if( !spellData.SpellId )
17859 continue;
17861 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17862 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17863 continue;
17865 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17867 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17868 data << pItem->GetGUID();
17869 data << uint32(spellData.SpellId);
17870 GetSession()->SendPacket(&data);
17874 void Player::resetSpells()
17876 // not need after this call
17877 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17879 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17880 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17883 // make full copy of map (spells removed and marked as deleted at another spell remove
17884 // and we can't use original map for safe iterative with visit each spell at loop end
17885 PlayerSpellMap smap = GetSpellMap();
17887 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17888 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17890 learnDefaultSpells();
17891 learnQuestRewardedSpells();
17894 void Player::learnDefaultSpells(bool loading)
17896 // learn default race/class spells
17897 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17898 std::list<CreateSpellPair>::const_iterator spell_itr;
17899 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17901 uint16 tspell = spell_itr->first;
17902 if (tspell)
17904 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17905 if(loading || !spell_itr->second) // not care about passive spells or loading case
17906 addSpell(tspell,spell_itr->second);
17907 else // but send in normal spell in game learn case
17908 learnSpell(tspell);
17913 void Player::learnQuestRewardedSpells(Quest const* quest)
17915 uint32 spell_id = quest->GetRewSpellCast();
17917 // skip quests without rewarded spell
17918 if( !spell_id )
17919 return;
17921 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17922 if(!spellInfo)
17923 return;
17925 // check learned spells state
17926 bool found = false;
17927 for(int i=0; i < 3; ++i)
17929 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17931 found = true;
17932 break;
17936 // skip quests with not teaching spell or already known spell
17937 if(!found)
17938 return;
17940 // prevent learn non first rank unknown profession and second specialization for same profession)
17941 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17942 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17944 // not have first rank learned (unlearned prof?)
17945 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17946 if( !HasSpell(first_spell) )
17947 return;
17949 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17950 if(!learnedInfo)
17951 return;
17953 // specialization
17954 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17956 // search other specialization for same prof
17957 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17959 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17960 continue;
17962 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17963 if(!itrInfo)
17964 return;
17966 // compare only specializations
17967 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17968 continue;
17970 // compare same chain spells
17971 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17972 continue;
17974 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17975 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17976 return;
17981 CastSpell( this, spell_id, true);
17984 void Player::learnQuestRewardedSpells()
17986 // learn spells received from quest completing
17987 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17989 // skip no rewarded quests
17990 if(!itr->second.m_rewarded)
17991 continue;
17993 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17994 if( !quest )
17995 continue;
17997 learnQuestRewardedSpells(quest);
18001 void Player::learnSkillRewardedSpells(uint32 skill_id )
18003 uint32 raceMask = getRaceMask();
18004 uint32 classMask = getClassMask();
18005 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18007 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18008 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18009 continue;
18010 // Check race if set
18011 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18012 continue;
18013 // Check class if set
18014 if (pAbility->classmask && !(pAbility->classmask & classMask))
18015 continue;
18017 if (sSpellStore.LookupEntry(pAbility->spellId))
18019 // Ok need learn spell
18020 learnSpell(pAbility->spellId);
18025 void Player::learnSkillRewardedSpells()
18027 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
18029 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
18030 continue;
18032 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
18034 learnSkillRewardedSpells(pskill);
18038 void Player::SendAurasForTarget(Unit *target)
18040 if(target->GetVisibleAuras()->empty()) // speedup things
18041 return;
18043 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18044 data.append(target->GetPackGUID());
18046 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18047 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18049 for(uint32 j = 0; j < 3; ++j)
18051 if(Aura *aura = target->GetAura(itr->second, j))
18053 data << uint8(aura->GetAuraSlot());
18054 data << uint32(aura->GetId());
18056 if(aura->GetId())
18058 uint8 auraFlags = aura->GetAuraFlags();
18059 // flags
18060 data << uint8(auraFlags);
18061 // level
18062 data << uint8(aura->GetAuraLevel());
18063 // charges
18064 data << uint8(aura->m_procCharges >= 0 ? aura->m_procCharges : 0 );
18066 if(!(auraFlags & AFLAG_NOT_CASTER))
18068 data << uint8(0); // packed GUID of someone (caster?)
18071 if(auraFlags & AFLAG_DURATION) // include aura duration
18073 data << uint32(aura->GetAuraMaxDuration());
18074 data << uint32(aura->GetAuraDuration());
18077 break;
18082 GetSession()->SendPacket(&data);
18085 void Player::SetDailyQuestStatus( uint32 quest_id )
18087 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18089 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18091 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18092 m_lastDailyQuestTime = time(NULL); // last daily quest time
18093 m_DailyQuestChanged = true;
18094 break;
18099 void Player::ResetDailyQuestStatus()
18101 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18102 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18104 // DB data deleted in caller
18105 m_DailyQuestChanged = false;
18106 m_lastDailyQuestTime = 0;
18109 BattleGround* Player::GetBattleGround() const
18111 if(GetBattleGroundId()==0)
18112 return NULL;
18114 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18117 bool Player::InArena() const
18119 BattleGround *bg = GetBattleGround();
18120 if(!bg || !bg->isArena())
18121 return false;
18123 return true;
18126 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
18128 // get a template bg instead of running one
18129 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18130 if(!bg)
18131 return false;
18133 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18134 return false;
18136 return true;
18139 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
18141 if(queue_id < 1)
18142 return 0;
18144 if(queue_id >=7)
18145 queue_id = 7;
18147 return 10*(queue_id+1);
18150 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
18152 if(queue_id >=7)
18153 return 255; // hardcoded max level
18155 return 10*(queue_id+2)-1;
18158 uint32 Player::GetBattleGroundQueueIdFromLevel() const
18160 uint32 level = getLevel();
18161 if(level <= 19)
18162 return 0;
18163 else if (level > 79)
18164 return 7;
18165 else
18166 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18168 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18169 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18170 assert(bg);
18171 return (getLevel() - bg->GetMinLevel()) / 10;*/
18174 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18176 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18177 if(!vendor_faction)
18178 return 1.0f;
18180 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18181 if(rank <= REP_NEUTRAL)
18182 return 1.0f;
18184 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18187 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18189 uint32 racemask = getRaceMask();
18190 uint32 classmask = getClassMask();
18192 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18193 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18195 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18197 // skip wrong race skills
18198 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18199 return false;
18201 // skip wrong class skills
18202 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18203 return false;
18205 return true;
18208 bool Player::HasQuestForGO(int32 GOId)
18210 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
18212 QuestStatusData qs=i->second;
18213 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18215 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
18216 if(!qinfo)
18217 continue;
18219 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18220 continue;
18222 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18224 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18225 continue;
18227 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18228 return true;
18232 return false;
18235 void Player::UpdateForQuestsGO()
18237 if(m_clientGUIDs.empty())
18238 return;
18240 UpdateData udata;
18241 WorldPacket packet;
18242 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18244 if(IS_GAMEOBJECT_GUID(*itr))
18246 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18247 if(obj)
18248 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18251 udata.BuildPacket(&packet);
18252 GetSession()->SendPacket(&packet);
18255 void Player::SummonIfPossible(bool agree)
18257 if(!agree)
18259 m_summon_expire = 0;
18260 return;
18263 // expire and auto declined
18264 if(m_summon_expire < time(NULL))
18265 return;
18267 // stop taxi flight at summon
18268 if(isInFlight())
18270 GetMotionMaster()->MovementExpired();
18271 m_taxi.ClearTaxiDestinations();
18274 // drop flag at summon
18275 if(BattleGround *bg = GetBattleGround())
18276 bg->EventPlayerDroppedFlag(this);
18278 m_summon_expire = 0;
18280 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18283 void Player::RemoveItemDurations( Item *item )
18285 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18287 if(*itr==item)
18289 m_itemDuration.erase(itr);
18290 break;
18295 void Player::AddItemDurations( Item *item )
18297 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18299 m_itemDuration.push_back(item);
18300 item->SendTimeUpdate(this);
18304 void Player::AutoUnequipOffhandIfNeed()
18306 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18307 if(!offItem)
18308 return;
18310 // need unequip for 2h-weapon without TitanGrip
18311 if (!IsTwoHandUsed())
18312 return;
18314 ItemPosCountVec off_dest;
18315 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18316 if( off_msg == EQUIP_ERR_OK )
18318 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18319 StoreItem( off_dest, offItem, true );
18321 else
18323 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18327 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18329 if(spellInfo->EquippedItemClass < 0)
18330 return true;
18332 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18333 // for optimize check 2 used cases only
18334 switch(spellInfo->EquippedItemClass)
18336 case ITEM_CLASS_WEAPON:
18338 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18339 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18340 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18341 return true;
18342 break;
18344 case ITEM_CLASS_ARMOR:
18346 // tabard not have dependent spells
18347 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18348 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18349 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18350 return true;
18352 // shields can be equipped to offhand slot
18353 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18354 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18355 return true;
18357 // ranged slot can have some armor subclasses
18358 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18359 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18360 return true;
18362 break;
18364 default:
18365 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18366 break;
18369 return false;
18372 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18374 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18375 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18376 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18377 return true;
18379 // Check no reagent use mask
18380 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18381 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18382 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18383 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18384 return true;
18386 return false;
18389 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18391 AuraMap& auras = GetAuras();
18392 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18394 Aura* aura = itr->second;
18396 // skip passive (passive item dependent spells work in another way) and not self applied auras
18397 SpellEntry const* spellInfo = aura->GetSpellProto();
18398 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18400 ++itr;
18401 continue;
18404 // skip if not item dependent or have alternative item
18405 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18407 ++itr;
18408 continue;
18411 // no alt item, remove aura, restart check
18412 RemoveAurasDueToSpell(aura->GetId());
18413 itr = auras.begin();
18416 // currently casted spells can be dependent from item
18417 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18419 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18420 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18421 InterruptSpell(i);
18425 uint32 Player::GetResurrectionSpellId()
18427 // search priceless resurrection possibilities
18428 uint32 prio = 0;
18429 uint32 spell_id = 0;
18430 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18431 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18433 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18434 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18436 switch((*itr)->GetId())
18438 case 20707: spell_id = 3026; break; // rank 1
18439 case 20762: spell_id = 20758; break; // rank 2
18440 case 20763: spell_id = 20759; break; // rank 3
18441 case 20764: spell_id = 20760; break; // rank 4
18442 case 20765: spell_id = 20761; break; // rank 5
18443 case 27239: spell_id = 27240; break; // rank 6
18444 default:
18445 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18446 continue;
18449 prio = 3;
18451 // Twisting Nether // prio: 2 (max)
18452 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18454 prio = 2;
18455 spell_id = 23700;
18459 // Reincarnation (passive spell) // prio: 1
18460 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18461 spell_id = 21169;
18463 return spell_id;
18466 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18468 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18470 // prepare data for near group iteration (PvP and !PvP cases)
18471 uint32 xp = 0;
18472 bool honored_kill = false;
18474 if(Group *pGroup = GetGroup())
18476 uint32 count = 0;
18477 uint32 sum_level = 0;
18478 Player* member_with_max_level = NULL;
18479 Player* not_gray_member_with_max_level = NULL;
18481 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18483 if(member_with_max_level)
18485 /// not get Xp in PvP or no not gray players in group
18486 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18488 /// skip in check PvP case (for speed, not used)
18489 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18490 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18491 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18493 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18495 Player* pGroupGuy = itr->getSource();
18496 if(!pGroupGuy)
18497 continue;
18499 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18500 continue; // member (alive or dead) or his corpse at req. distance
18502 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18503 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18504 honored_kill = true;
18506 // xp and reputation only in !PvP case
18507 if(!PvP)
18509 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18511 // if is in dungeon then all receive full reputation at kill
18512 // rewarded any alive/dead/near_corpse group member
18513 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18515 // XP updated only for alive group member
18516 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18517 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18519 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18521 pGroupGuy->GiveXP(itr_xp, pVictim);
18522 if(Pet* pet = pGroupGuy->GetPet())
18523 pet->GivePetXP(itr_xp/2);
18526 // quest objectives updated only for alive group member or dead but with not released body
18527 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18529 // normal creature (not pet/etc) can be only in !PvP case
18530 if(pVictim->GetTypeId()==TYPEID_UNIT)
18531 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18537 else // if (!pGroup)
18539 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18541 // honor can be in PvP and !PvP (racial leader) cases
18542 if(RewardHonor(pVictim,1))
18543 honored_kill = true;
18545 // xp and reputation only in !PvP case
18546 if(!PvP)
18548 RewardReputation(pVictim,1);
18549 GiveXP(xp, pVictim);
18551 if(Pet* pet = GetPet())
18552 pet->GivePetXP(xp);
18554 // normal creature (not pet/etc) can be only in !PvP case
18555 if(pVictim->GetTypeId()==TYPEID_UNIT)
18556 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18559 return xp || honored_kill;
18562 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18564 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18565 return true;
18567 if(isAlive())
18568 return false;
18570 Corpse* corpse = GetCorpse();
18571 if(!corpse)
18572 return false;
18574 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18577 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18579 Item* item = GetWeaponForAttack(attType,true);
18581 // unarmed only with base attack
18582 if(attType != BASE_ATTACK && !item)
18583 return 0;
18585 // weapon skill or (unarmed for base attack)
18586 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18587 return GetBaseSkillValue(skill);
18590 void Player::ResurectUsingRequestData()
18592 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18593 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18595 ResurrectPlayer(0.0f,false);
18597 if(GetMaxHealth() > m_resurrectHealth)
18598 SetHealth( m_resurrectHealth );
18599 else
18600 SetHealth( GetMaxHealth() );
18602 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18603 SetPower(POWER_MANA, m_resurrectMana );
18604 else
18605 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18607 SetPower(POWER_RAGE, 0 );
18609 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18611 SpawnCorpseBones();
18614 void Player::SetClientControl(Unit* target, uint8 allowMove)
18616 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18617 data.append(target->GetPackGUID());
18618 data << uint8(allowMove);
18619 GetSession()->SendPacket(&data);
18622 void Player::UpdateZoneDependentAuras( uint32 newZone )
18624 // remove new continent flight forms
18625 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), newZone);
18626 if( !isGameMaster() && v_map != 530 && v_map != 571)
18628 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18629 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18632 // Some spells applied at enter into zone (with subzones)
18633 // Human Illusion
18634 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18635 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18637 uint32 spellid = 0;
18638 // all horde races
18639 if( GetTeam() == HORDE )
18640 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18641 // and some alliance races
18642 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18643 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18645 if(spellid && !HasAura(spellid,0) )
18646 CastSpell(this,spellid,true);
18650 void Player::UpdateAreaDependentAuras( uint32 newArea )
18652 // remove auras from spells with area limitations
18653 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18655 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18656 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
18657 RemoveAura(iter);
18658 else
18659 ++iter;
18662 // unmount if enter in this subzone
18663 if( newArea == 35)
18664 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18665 // Dragonmaw Illusion
18666 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18668 if( GetDummyAura(40214) )
18670 if( !HasAura(40216,0) )
18671 CastSpell(this,40216,true);
18672 if( !HasAura(42016,0) )
18673 CastSpell(this,42016,true);
18678 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18680 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18681 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18683 return copseReclaimDelay[0];
18686 time_t now = time(NULL);
18687 // 0..2 full period
18688 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18689 return copseReclaimDelay[count];
18692 void Player::UpdateCorpseReclaimDelay()
18694 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18696 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18697 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18698 return;
18700 time_t now = time(NULL);
18701 if(now < m_deathExpireTime)
18703 // full and partly periods 1..3
18704 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18705 if(count < MAX_DEATH_COUNT)
18706 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18707 else
18708 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18710 else
18711 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18714 void Player::SendCorpseReclaimDelay(bool load)
18716 Corpse* corpse = GetCorpse();
18717 if(!corpse)
18718 return;
18720 uint32 delay;
18721 if(load)
18723 if(corpse->GetGhostTime() > m_deathExpireTime)
18724 return;
18726 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18728 uint32 count;
18729 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18730 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18732 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18733 if(count>=MAX_DEATH_COUNT)
18734 count = MAX_DEATH_COUNT-1;
18736 else
18737 count=0;
18739 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18741 time_t now = time(NULL);
18742 if(now >= expected_time)
18743 return;
18745 delay = expected_time-now;
18747 else
18748 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18750 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18751 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18752 data << uint32(delay*1000);
18753 GetSession()->SendPacket( &data );
18756 Player* Player::GetNextRandomRaidMember(float radius)
18758 Group *pGroup = GetGroup();
18759 if(!pGroup)
18760 return NULL;
18762 std::vector<Player*> nearMembers;
18763 nearMembers.reserve(pGroup->GetMembersCount());
18765 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18767 Player* Target = itr->getSource();
18769 // IsHostileTo check duel and controlled by enemy
18770 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18771 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18772 nearMembers.push_back(Target);
18775 if (nearMembers.empty())
18776 return NULL;
18778 uint32 randTarget = urand(0,nearMembers.size()-1);
18779 return nearMembers[randTarget];
18782 PartyResult Player::CanUninviteFromGroup() const
18784 const Group* grp = GetGroup();
18785 if(!grp)
18786 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18788 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18789 return PARTY_RESULT_YOU_NOT_LEADER;
18791 if(InBattleGround())
18792 return PARTY_RESULT_INVITE_RESTRICTED;
18794 return PARTY_RESULT_OK;
18797 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18799 float water_z = m->GetWaterLevel(x,y);
18800 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18801 uint8 flag1 = m->GetTerrainType(x,y);
18803 //!Underwater check, not in water if underground or above water level
18804 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18805 m_isunderwater &= 0x7A;
18806 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18807 m_isunderwater |= 0x01;
18809 //!in lava check, anywhere under lava level
18810 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18811 m_isunderwater |= 0x80;
18814 void Player::SetCanParry( bool value )
18816 if(m_canParry==value)
18817 return;
18819 m_canParry = value;
18820 UpdateParryPercentage();
18823 void Player::SetCanBlock( bool value )
18825 if(m_canBlock==value)
18826 return;
18828 m_canBlock = value;
18829 UpdateBlockPercentage();
18832 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18834 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18835 if(itr->pos == pos)
18836 return true;
18838 return false;
18841 bool Player::isAllowUseBattleGroundObject()
18843 return ( //InBattleGround() && // in battleground - not need, check in other cases
18844 !IsMounted() && // not mounted
18845 !HasStealthAura() && // not stealthed
18846 !HasInvisibilityAura() && // not invisible
18847 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18848 isAlive() // live player
18852 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18854 uint32 level = getLevel();
18856 if(level > GT_MAX_LEVEL)
18857 level = GT_MAX_LEVEL; // max level in this dbc
18859 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18860 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18861 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18863 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18864 return 0;
18866 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18868 if(!bsc) // shouldn't happen
18869 return 0xFFFFFFFF;
18871 float cost = 0;
18873 if(hairstyle != newhairstyle)
18874 cost += bsc->cost; // full price
18876 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18877 cost += bsc->cost * 0.5f; // +1/2 of price
18879 if(facialhair != newfacialhair)
18880 cost += bsc->cost * 0.75f; // +3/4 of price
18882 return uint32(cost);
18885 void Player::InitGlyphsForLevel()
18887 uint32 level = getLevel();
18888 uint32 value = 0;
18890 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18891 if(level >= 15)
18892 value |= (0x01 | 0x02);
18893 if(level >= 30)
18894 value |= 0x04;
18895 if(level >= 50)
18896 value |= 0x08;
18897 if(level >= 70)
18898 value |= 0x10;
18899 if(level >= 80)
18900 value |= 0x20;
18902 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
18905 void Player::EnterVehicle(Vehicle *vehicle)
18907 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
18908 if(!ve)
18909 return;
18911 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
18912 if(!veSeat)
18913 return;
18915 vehicle->SetCharmerGUID(GetGUID());
18916 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
18917 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
18918 vehicle->setFaction(getFaction());
18920 SetCharm(vehicle); // charm
18921 SetFarSight(vehicle->GetGUID()); // set view
18923 SetClientControl(vehicle, 1); // redirect controls to vehicle
18925 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
18926 GetSession()->SendPacket(&data);
18928 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
18929 data.append(GetPackGUID());
18930 data << uint32(0); // counter?
18931 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
18932 data << uint16(0); // special flags
18933 data << uint32(getMSTime()); // time
18934 data << vehicle->GetPositionX(); // x
18935 data << vehicle->GetPositionY(); // y
18936 data << vehicle->GetPositionZ(); // z
18937 data << vehicle->GetOrientation(); // o
18938 // transport part, TODO: load/calculate seat offsets
18939 data << uint64(vehicle->GetGUID()); // transport guid
18940 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
18941 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
18942 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
18943 data << float(0); // transport orientation
18944 data << uint32(getMSTime()); // transport time
18945 data << uint8(0); // seat
18946 // end of transport part
18947 data << uint32(0); // fall time
18948 GetSession()->SendPacket(&data);
18950 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
18951 data << uint64(vehicle->GetGUID());
18952 data << uint32(0x00000000);
18953 data << uint32(0x00000000);
18954 data << uint32(0x00000101);
18956 for(uint32 i = 0; i < 10; ++i)
18957 data << uint16(0) << uint8(0) << uint8(i+8);
18959 data << uint8(0);
18960 data << uint8(0);
18961 GetSession()->SendPacket(&data);
18964 void Player::ExitVehicle(Vehicle *vehicle)
18966 vehicle->SetCharmerGUID(0);
18967 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
18968 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
18969 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
18971 SetCharm(NULL);
18972 SetFarSight(NULL);
18974 SetClientControl(vehicle, 0);
18976 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
18977 data.append(GetPackGUID());
18978 data << uint32(0); // counter?
18979 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
18980 data << uint16(0x40); // special flags
18981 data << uint32(getMSTime()); // time
18982 data << vehicle->GetPositionX(); // x
18983 data << vehicle->GetPositionY(); // y
18984 data << vehicle->GetPositionZ(); // z
18985 data << vehicle->GetOrientation(); // o
18986 data << uint32(0); // fall time
18987 GetSession()->SendPacket(&data);
18989 data.Initialize(SMSG_PET_SPELLS, 8+4);
18990 data << uint64(0);
18991 data << uint32(0);
18992 GetSession()->SendPacket(&data);
18994 // only for flyable vehicles?
18995 CastSpell(this, 45472, true); // Parachute
18998 bool Player::HasTitle(uint32 bitIndex)
19000 if (bitIndex > 128)
19001 return false;
19003 uint32 fieldIndexOffset = bitIndex/32;
19004 uint32 flag = 1 << (bitIndex%32);
19005 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19008 void Player::SetTitle(CharTitlesEntry const* title)
19010 uint32 fieldIndexOffset = title->bit_index/32;
19011 uint32 flag = 1 << (title->bit_index%32);
19012 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19015 void Player::ConvertRune(uint8 index, uint8 newType)
19017 SetCurrentRune(index, newType);
19019 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19020 data << uint8(index);
19021 data << uint8(newType);
19022 GetSession()->SendPacket(&data);
19025 void Player::ResyncRunes(uint8 count)
19027 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19028 for(uint32 i = 0; i < count; ++i)
19030 data << uint8(GetCurrentRune(i)); // rune type
19031 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19033 GetSession()->SendPacket(&data);
19036 void Player::AddRunePower(uint8 index)
19038 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19039 data << uint32(1 << index); // mask (0x00-0x3F probably)
19040 GetSession()->SendPacket(&data);
19043 void Player::InitRunes()
19045 if(getClass() != CLASS_DEATH_KNIGHT)
19046 return;
19048 m_runes = new Runes;
19050 m_runes->runeState = 0;
19052 for(uint32 i = 0; i < MAX_RUNES; ++i)
19054 SetBaseRune(i, i / 2); // init base types
19055 SetCurrentRune(i, i / 2); // init current types
19056 SetRuneCooldown(i, 0); // reset cooldowns
19057 m_runes->SetRuneState(i);
19060 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19061 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);