[6862] Some additional mangosd.conf options for player startup and gameplay customizing.
[getmangos.git] / src / game / Player.cpp
blobf7574b06f639b58046efc4be5cb2b1525ab83cff
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"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL 1000
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 level)
131 // capital and taxi hub masks
132 switch(race)
134 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
135 case RACE_ORC: SetTaximaskNode(23); break; // Orc
136 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
137 case RACE_NIGHTELF: SetTaximaskNode(26);
138 SetTaximaskNode(27); break; // Night Elf
139 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
140 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
141 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
142 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
143 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
144 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
146 // new continent starting masks (It will be accessible only at new map)
147 switch(Player::TeamForRace(race))
149 case ALLIANCE: SetTaximaskNode(100); break;
150 case HORDE: SetTaximaskNode(99); break;
152 // level dependent taxi hubs
153 if(level>=68)
154 SetTaximaskNode(213); //Shattered Sun Staging Area
157 void PlayerTaxi::LoadTaxiMask(const char* data)
159 Tokens tokens = StrSplit(data, " ");
161 int index;
162 Tokens::iterator iter;
163 for (iter = tokens.begin(), index = 0;
164 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
166 // load and set bits only for existed taxi nodes
167 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
171 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
173 if(all)
175 for (uint8 i=0; i<TaxiMaskSize; i++)
176 data << sTaxiNodesMask[i]; // all existed nodes
178 else
180 for (uint8 i=0; i<TaxiMaskSize; i++)
181 data << uint32(m_taximask[i]); // known nodes
185 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values )
187 ClearTaxiDestinations();
189 Tokens tokens = StrSplit(values," ");
191 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
193 uint32 node = uint32(atol(iter->c_str()));
194 AddTaxiDestination(node);
197 if(m_TaxiDestinations.empty())
198 return true;
200 // Check integrity
201 if(m_TaxiDestinations.size() < 2)
202 return false;
204 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
206 uint32 cost;
207 uint32 path;
208 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
209 if(!path)
210 return false;
213 return true;
216 std::string PlayerTaxi::SaveTaxiDestinationsToString()
218 if(m_TaxiDestinations.empty())
219 return "";
221 std::ostringstream ss;
223 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
224 ss << m_TaxiDestinations[i] << " ";
226 return ss.str();
229 uint32 PlayerTaxi::GetCurrentTaxiPath() const
231 if(m_TaxiDestinations.size() < 2)
232 return 0;
234 uint32 path;
235 uint32 cost;
237 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
239 return path;
242 //== Player ====================================================
244 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
246 UpdateMask Player::updateVisualBits;
248 Player::Player (WorldSession *session): Unit()
250 m_transport = 0;
252 m_speakTime = 0;
253 m_speakCount = 0;
255 m_objectType |= TYPEMASK_PLAYER;
256 m_objectTypeId = TYPEID_PLAYER;
258 m_valuesCount = PLAYER_END;
260 m_session = session;
262 m_divider = 0;
264 m_ExtraFlags = 0;
265 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
266 SetAcceptTicket(true);
268 // players always accept
269 if(GetSession()->GetSecurity() == SEC_PLAYER)
270 SetAcceptWhispers(true);
272 m_curSelection = 0;
273 m_lootGuid = 0;
275 m_comboTarget = 0;
276 m_comboPoints = 0;
278 m_usedTalentCount = 0;
280 m_regenTimer = 0;
281 m_weaponChangeTimer = 0;
283 m_zoneUpdateId = 0;
284 m_zoneUpdateTimer = 0;
286 m_areaUpdateId = 0;
288 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
290 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
291 // this must help in case next save after mass player load after server startup
292 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
294 clearResurrectRequestData();
296 m_SpellModRemoveCount = 0;
298 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
300 m_social = NULL;
302 // group is initialized in the reference constructor
303 SetGroupInvite(NULL);
304 m_groupUpdateMask = 0;
305 m_auraUpdateMask = 0;
307 duel = NULL;
309 m_GuildIdInvited = 0;
310 m_ArenaTeamIdInvited = 0;
312 m_atLoginFlags = AT_LOGIN_NONE;
314 m_dontMove = false;
316 pTrader = 0;
317 ClearTrade();
319 m_cinematic = 0;
321 PlayerTalkClass = new PlayerMenu( GetSession() );
322 m_currentBuybackSlot = BUYBACK_SLOT_START;
324 for ( int aX = 0 ; aX < 8 ; aX++ )
325 m_Tutorials[ aX ] = 0x00;
326 m_TutorialsChanged = false;
328 m_DailyQuestChanged = false;
329 m_lastDailyQuestTime = 0;
331 m_regenTimer = 0;
332 m_weaponChangeTimer = 0;
333 m_breathTimer = 0;
334 m_isunderwater = 0;
335 m_isInWater = false;
336 m_drunkTimer = 0;
337 m_drunk = 0;
338 m_restTime = 0;
339 m_deathTimer = 0;
340 m_deathExpireTime = 0;
342 m_swingErrorMsg = 0;
344 m_DetectInvTimer = 1000;
346 m_bgBattleGroundID = 0;
347 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
349 m_bgBattleGroundQueueID[j].bgType = 0;
350 m_bgBattleGroundQueueID[j].invited = false;
352 m_bgTeam = 0;
354 m_logintime = time(NULL);
355 m_Last_tick = m_logintime;
356 m_WeaponProficiency = 0;
357 m_ArmorProficiency = 0;
358 m_canParry = false;
359 m_canBlock = false;
360 m_canDualWield = false;
361 m_ammoDPS = 0.0f;
363 m_temporaryUnsummonedPetNumber = 0;
364 //cache for UNIT_CREATED_BY_SPELL to allow
365 //returning reagents for temporarily removed pets
366 //when dying/logging out
367 m_oldpetspell = 0;
369 ////////////////////Rest System/////////////////////
370 time_inn_enter=0;
371 inn_pos_mapid=0;
372 inn_pos_x=0;
373 inn_pos_y=0;
374 inn_pos_z=0;
375 m_rest_bonus=0;
376 rest_type=REST_TYPE_NO;
377 ////////////////////Rest System/////////////////////
379 m_mailsLoaded = false;
380 m_mailsUpdated = false;
381 unReadMails = 0;
382 m_nextMailDelivereTime = 0;
384 m_resetTalentsCost = 0;
385 m_resetTalentsTime = 0;
386 m_itemUpdateQueueBlocked = false;
388 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
389 m_forced_speed_changes[i] = 0;
391 m_stableSlots = 0;
393 /////////////////// Instance System /////////////////////
395 m_HomebindTimer = 0;
396 m_InstanceValid = true;
397 m_dungeonDifficulty = DIFFICULTY_NORMAL;
399 for (int i = 0; i < BASEMOD_END; i++)
401 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
402 m_auraBaseMod[i][PCT_MOD] = 1.0f;
405 // Honor System
406 m_lastHonorUpdateTime = time(NULL);
408 // Player summoning
409 m_summon_expire = 0;
410 m_summon_mapid = 0;
411 m_summon_x = 0.0f;
412 m_summon_y = 0.0f;
413 m_summon_z = 0.0f;
415 //Default movement to run mode
416 m_unit_movement_flags = 0;
418 m_miniPet = 0;
419 m_bgAfkReportedTimer = 0;
420 m_contestedPvPTimer = 0;
422 m_declinedname = NULL;
425 Player::~Player ()
427 CleanupsBeforeDelete();
429 // it must be unloaded already in PlayerLogout and accessed only for loggined player
430 //m_social = NULL;
432 // Note: buy back item already deleted from DB when player was saved
433 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
435 if(m_items[i])
436 delete m_items[i];
438 CleanupChannels();
440 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
441 delete itr->second;
443 //all mailed items should be deleted, also all mail should be deallocated
444 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
445 delete *itr;
447 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
448 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
450 delete PlayerTalkClass;
452 if (m_transport)
454 m_transport->RemovePassenger(this);
457 for(size_t x = 0; x < ItemSetEff.size(); x++)
458 if(ItemSetEff[x])
459 delete ItemSetEff[x];
461 // clean up player-instance binds, may unload some instance saves
462 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
463 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
464 itr->second.save->RemovePlayer(this);
466 delete m_declinedname;
469 void Player::CleanupsBeforeDelete()
471 if(m_uint32Values) // only for fully created Object
473 TradeCancel(false);
474 DuelComplete(DUEL_INTERUPTED);
476 Unit::CleanupsBeforeDelete();
479 bool Player::Create( uint32 guidlow, std::string name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
481 //FIXME: outfitId not used in player creating
483 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
485 m_name = name;
487 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
488 if(!info)
490 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
491 return false;
494 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
495 m_items[i] = NULL;
497 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
499 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
500 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
501 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
504 m_race = race;
505 m_class = class_;
507 SetMapId(info->mapId);
508 Relocate(info->positionX,info->positionY,info->positionZ);
510 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
511 if(!cEntry)
513 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
514 return false;
517 uint8 powertype = cEntry->powerType;
519 uint32 unitfield;
521 switch(powertype)
523 case POWER_ENERGY:
524 case POWER_MANA:
525 unitfield = 0x00000000;
526 break;
527 case POWER_RAGE:
528 unitfield = 0x00110000;
529 break;
530 default:
531 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
532 return false;
535 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
536 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
538 switch(gender)
540 case GENDER_FEMALE:
541 SetDisplayId(info->displayId_f );
542 SetNativeDisplayId(info->displayId_f );
543 break;
544 case GENDER_MALE:
545 SetDisplayId(info->displayId_m );
546 SetNativeDisplayId(info->displayId_m );
547 break;
548 default:
549 sLog.outError("Invalid gender %u for player",gender);
550 return false;
551 break;
554 setFactionForRace(m_race);
556 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
558 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
559 SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
560 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_UNK5 );
561 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
562 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
564 //-1 is default value
565 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
567 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
568 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
569 SetByteValue(PLAYER_BYTES_3, 0, gender);
571 SetUInt32Value( PLAYER_GUILDID, 0 );
572 SetUInt32Value( PLAYER_GUILDRANK, 0 );
573 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
575 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
576 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
577 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
578 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
579 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
580 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
582 // set starting level
583 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
584 SetUInt32Value (UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_GM_LEVEL));
585 else
586 SetUInt32Value (UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL));
588 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
589 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
590 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
592 // Played time
593 m_Last_tick = time(NULL);
594 m_Played_time[0] = 0;
595 m_Played_time[1] = 0;
597 // base stats and related field values
598 InitStatsForLevel();
599 InitTaxiNodesForLevel();
600 InitTalentForLevel();
601 InitPrimaryProffesions(); // to max set before any spell added
603 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
604 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
605 SetHealth(GetMaxHealth());
606 if (getPowerType()==POWER_MANA)
608 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
609 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
612 // original spells
613 learnDefaultSpells(true);
615 // original action bar
616 std::list<uint16>::const_iterator action_itr[4];
617 for(int i=0; i<4; i++)
618 action_itr[i] = info->action[i].begin();
620 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
622 uint16 taction[4];
623 for(int i=0; i<4 ;i++)
624 taction[i] = (*action_itr[i]);
626 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
628 for(int i=0; i<4 ;i++)
629 ++action_itr[i];
632 // original items
633 CharStartOutfitEntry const* oEntry = NULL;
634 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
636 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
638 if(entry->RaceClassGender == RaceClassGender)
640 oEntry = entry;
641 break;
646 if(oEntry)
648 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
650 if(oEntry->ItemId[j] <= 0)
651 continue;
653 uint32 item_id = oEntry->ItemId[j];
655 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
656 if(!iProto)
658 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
659 continue;
662 uint32 count = iProto->Stackable; // max stack by default (mostly 1)
663 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
665 switch(iProto->Spells[0].SpellCategory)
667 case 11: // food
668 if(iProto->Stackable > 4)
669 count = 4;
670 break;
671 case 59: // drink
672 if(iProto->Stackable > 2)
673 count = 2;
674 break;
678 StoreNewItemInBestSlot(item_id, count);
682 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
683 StoreNewItemInBestSlot(item_id_itr->item_id, item_id_itr->item_amount);
685 // bags and main-hand weapon must equipped at this moment
686 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
687 // or ammo not equipped in special bag
688 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
690 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
692 uint16 eDest;
693 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
694 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
695 if( msg == EQUIP_ERR_OK )
697 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
698 EquipItem( eDest, pItem, true);
700 // move other items to more appropriate slots (ammo not equipped in special bag)
701 else
703 ItemPosCountVec sDest;
704 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
705 if( msg == EQUIP_ERR_OK )
707 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
708 pItem = StoreItem( sDest, pItem, true);
711 // if this is ammo then use it
712 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
713 if( msg == EQUIP_ERR_OK )
714 SetAmmo( pItem->GetProto()->ItemId );
718 // all item positions resolved
720 return true;
723 bool Player::StoreNewItemInBestSlot(uint32 titem_id, uint32 titem_amount)
725 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
727 // attempt equip
728 uint16 eDest;
729 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
730 if( msg == EQUIP_ERR_OK )
732 EquipNewItem( eDest, titem_id, titem_amount, true);
733 AutoUnequipOffhandIfNeed();
734 return true; // equipped
737 // attempt store
738 ItemPosCountVec sDest;
739 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
740 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
741 if( msg == EQUIP_ERR_OK )
743 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
744 return true; // stored
747 // item can't be added
748 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
749 return false;
752 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
754 uint32 BreathRegen = (uint32)-1;
756 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
757 data << (uint32)Type;
758 data << MaxValue;
759 data << MaxValue;
760 data << BreathRegen;
761 data << (uint8)0;
762 data << (uint32)0; // spell id
763 GetSession()->SendPacket(&data);
766 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
768 if(Type==BREATH_TIMER)
769 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
771 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
772 data << (uint32)Type;
773 data << CurrentValue;
774 data << MaxValue;
775 data << Regen;
776 data << (uint8)0;
777 data << (uint32)0; // spell id
778 GetSession()->SendPacket( &data );
781 void Player::StopMirrorTimer(MirrorTimerType Type)
783 if(Type==BREATH_TIMER)
784 m_breathTimer = 0;
786 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
787 data << (uint32)Type;
788 GetSession()->SendPacket( &data );
791 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
793 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
794 data << (uint64)guid;
795 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
796 data << (uint32)damage;
797 data << (uint32)0;
798 data << (uint32)0;
799 //m_session->SendPacket(&data);
800 //Let other players see that you get damage
801 SendMessageToSet(&data, true);
802 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
804 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
806 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
807 DurabilityLossAll(0.10f,false);
808 // durability lost message
809 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
810 GetSession()->SendPacket(&data);
814 void Player::HandleDrowning()
816 if(!m_isunderwater)
817 return;
819 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
820 if(waterbreath || isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
822 StopMirrorTimer(BREATH_TIMER);
823 m_isunderwater = 0;
824 return;
827 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
829 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
830 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
831 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
833 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
835 //single trigger timer
836 if (!(m_isunderwater & 0x02))
838 m_isunderwater|= 0x02;
839 m_breathTimer = UnderWaterTime + 1000;
841 //single trigger "Breathbar"
842 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
844 m_isunderwater|= 0x04;
845 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
847 //continius trigger drowning "Damage"
848 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
850 //TODO: Check this formula
851 uint64 guid = GetGUID();
852 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
854 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
855 m_breathTimer = 2000;
858 //single trigger retract bar
859 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
861 m_isunderwater = 0x08;
863 uint32 BreathRegen = 10;
864 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
865 m_isunderwater = 0x10;
867 //remove bar
868 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
870 StopMirrorTimer(BREATH_TIMER);
871 m_isunderwater = 0;
875 void Player::HandleLava()
877 bool ValidArea = false;
879 if ((m_isunderwater & 0x80) && isAlive())
881 //Single trigger Set BreathTimer
882 if (!(m_isunderwater & 0x80))
884 m_isunderwater|= 0x04;
885 m_breathTimer = 1000;
887 //Reset BreathTimer and still in the lava
888 if (!m_breathTimer)
890 uint64 guid = GetGUID();
891 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
892 uint32 dmgZone = GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
894 // Deal lava damage only in lava zones.
895 switch(dmgZone)
897 case 0x8D:
898 ValidArea = false;
899 break;
900 case 0x94:
901 ValidArea = false;
902 break;
903 case 0x2CE:
904 ValidArea = false;
905 break;
906 case 0x2CF:
907 ValidArea = false;
908 break;
909 default:
910 if (dmgZone / 5 & 0x408)
911 ValidArea = true;
914 // if is valid area and is not gamemaster then deal damage
915 if ( ValidArea && !isGameMaster() )
916 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
918 m_breathTimer = 1000;
922 //Death timer disabled and WaterFlags reset
923 else if (m_deathState == DEAD)
925 m_breathTimer = 0;
926 m_isunderwater = 0;
930 ///The player sobers by 256 every 10 seconds
931 void Player::HandleSobering()
933 m_drunkTimer = 0;
935 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
936 SetDrunkValue(drunk);
939 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
941 if(value >= 23000)
942 return DRUNKEN_SMASHED;
943 if(value >= 12800)
944 return DRUNKEN_DRUNK;
945 if(value & 0xFFFE)
946 return DRUNKEN_TIPSY;
947 return DRUNKEN_SOBER;
950 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
952 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
954 m_drunk = newDrunkenValue;
955 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
957 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
959 // special drunk invisibility detection
960 if(newDrunkenState >= DRUNKEN_DRUNK)
961 m_detectInvisibilityMask |= (1<<6);
962 else
963 m_detectInvisibilityMask &= ~(1<<6);
965 if(newDrunkenState == oldDrunkenState)
966 return;
968 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
969 data << GetGUID();
970 data << uint32(newDrunkenState);
971 data << uint32(itemId);
973 SendMessageToSet(&data, true);
976 void Player::Update( uint32 p_time )
978 if(!IsInWorld())
979 return;
981 // undelivered mail
982 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
984 SendNewMail();
985 ++unReadMails;
987 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
988 m_nextMailDelivereTime = 0;
991 Unit::Update( p_time );
993 // update player only attacks
994 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
996 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
999 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1001 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1004 time_t now = time (NULL);
1006 UpdatePvPFlag(now);
1008 UpdateContestedPvP(p_time);
1010 UpdateDuelFlag(now);
1012 CheckDuelDistance(now);
1014 UpdateAfkReport(now);
1016 CheckExploreSystem();
1018 // Update items that have just a limited lifetime
1019 if (now>m_Last_tick)
1020 UpdateItemDuration(uint32(now- m_Last_tick));
1022 if (!m_timedquests.empty())
1024 std::set<uint32>::iterator iter = m_timedquests.begin();
1025 while (iter != m_timedquests.end())
1027 QuestStatusData& q_status = mQuestStatus[*iter];
1028 if( q_status.m_timer <= p_time )
1030 uint32 quest_id = *iter;
1031 ++iter; // current iter will be removed in FailTimedQuest
1032 FailTimedQuest( quest_id );
1034 else
1036 q_status.m_timer -= p_time;
1037 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1038 ++iter;
1043 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1045 Unit *pVictim = getVictim();
1046 if( !IsNonMeleeSpellCasted(false) && pVictim)
1048 // default combat reach 10
1049 // TODO add weapon,skill check
1051 float pldistance = ATTACK_DISTANCE;
1053 if (isAttackReady(BASE_ATTACK))
1055 if(!IsWithinDistInMap(pVictim, pldistance))
1057 setAttackTimer(BASE_ATTACK,100);
1058 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1060 SendAttackSwingNotInRange();
1061 m_swingErrorMsg = 1;
1064 //120 degrees of radiant range
1065 else if( !HasInArc( 2*M_PI/3, pVictim ))
1067 setAttackTimer(BASE_ATTACK,100);
1068 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1070 SendAttackSwingBadFacingAttack();
1071 m_swingErrorMsg = 2;
1074 else
1076 m_swingErrorMsg = 0; // reset swing error state
1078 // prevent base and off attack in same time, delay attack at 0.2 sec
1079 if(haveOffhandWeapon())
1081 uint32 off_att = getAttackTimer(OFF_ATTACK);
1082 if(off_att < ATTACK_DISPLAY_DELAY)
1083 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1085 AttackerStateUpdate(pVictim, BASE_ATTACK);
1086 resetAttackTimer(BASE_ATTACK);
1090 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1092 if(!IsWithinDistInMap(pVictim, pldistance))
1094 setAttackTimer(OFF_ATTACK,100);
1096 else if( !HasInArc( 2*M_PI/3, pVictim ))
1098 setAttackTimer(OFF_ATTACK,100);
1100 else
1102 // prevent base and off attack in same time, delay attack at 0.2 sec
1103 uint32 base_att = getAttackTimer(BASE_ATTACK);
1104 if(base_att < ATTACK_DISPLAY_DELAY)
1105 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1106 // do attack
1107 AttackerStateUpdate(pVictim, OFF_ATTACK);
1108 resetAttackTimer(OFF_ATTACK);
1112 Unit *owner = pVictim->GetOwner();
1113 Unit *u = owner ? owner : pVictim;
1114 if(u->IsPvP() && (!duel || duel->opponent != u))
1116 UpdatePvP(true);
1117 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1122 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1124 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1126 int time_inn = time(NULL)-GetTimeInnEnter();
1127 if (time_inn >= 10) //freeze update
1129 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1130 //speed collect rest bonus (section/in hour)
1131 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1132 UpdateInnerTime(time(NULL));
1137 if(m_regenTimer > 0)
1139 if(p_time >= m_regenTimer)
1140 m_regenTimer = 0;
1141 else
1142 m_regenTimer -= p_time;
1145 if (m_weaponChangeTimer > 0)
1147 if(p_time >= m_weaponChangeTimer)
1148 m_weaponChangeTimer = 0;
1149 else
1150 m_weaponChangeTimer -= p_time;
1153 if (m_zoneUpdateTimer > 0)
1155 if(p_time >= m_zoneUpdateTimer)
1157 uint32 newzone = GetZoneId();
1158 if( m_zoneUpdateId != newzone )
1159 UpdateZone(newzone); // also update area
1160 else
1162 // use area updates as well
1163 // needed for free far all arenas for example
1164 uint32 newarea = GetAreaId();
1165 if( m_areaUpdateId != newarea )
1166 UpdateArea(newarea);
1168 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1171 else
1172 m_zoneUpdateTimer -= p_time;
1175 if (isAlive())
1177 RegenerateAll();
1180 if (m_deathState == JUST_DIED)
1182 KillPlayer();
1185 if(m_nextSave > 0)
1187 if(p_time >= m_nextSave)
1189 // m_nextSave reseted in SaveToDB call
1190 SaveToDB();
1191 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1193 else
1195 m_nextSave -= p_time;
1199 //Breathtimer
1200 if(m_breathTimer > 0)
1202 if(p_time >= m_breathTimer)
1203 m_breathTimer = 0;
1204 else
1205 m_breathTimer -= p_time;
1209 //Handle Water/drowning
1210 HandleDrowning();
1212 //Handle lava
1213 HandleLava();
1215 //Handle detect stealth players
1216 if (m_DetectInvTimer > 0)
1218 if (p_time >= m_DetectInvTimer)
1220 m_DetectInvTimer = 3000;
1221 HandleStealthedUnitsDetection();
1223 else
1224 m_DetectInvTimer -= p_time;
1227 // Played time
1228 if (now > m_Last_tick)
1230 uint32 elapsed = uint32(now - m_Last_tick);
1231 m_Played_time[0] += elapsed; // Total played time
1232 m_Played_time[1] += elapsed; // Level played time
1233 m_Last_tick = now;
1236 if (m_drunk)
1238 m_drunkTimer += p_time;
1240 if (m_drunkTimer > 10000)
1241 HandleSobering();
1244 // not auto-free ghost from body in instances
1245 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1247 if(p_time >= m_deathTimer)
1249 m_deathTimer = 0;
1250 BuildPlayerRepop();
1251 RepopAtGraveyard();
1253 else
1254 m_deathTimer -= p_time;
1257 UpdateEnchantTime(p_time);
1258 UpdateHomebindTime(p_time);
1260 // group update
1261 SendUpdateToOutOfRangeGroupMembers();
1263 Pet* pet = GetPet();
1264 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1266 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1267 return;
1271 void Player::setDeathState(DeathState s)
1273 uint32 ressSpellId = 0;
1275 bool cur = isAlive();
1277 if(s == JUST_DIED && cur)
1279 // drunken state is cleared on death
1280 SetDrunkValue(0);
1281 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1282 ClearComboPoints();
1284 clearResurrectRequestData();
1286 // remove form before other mods to prevent incorrect stats calculation
1287 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1289 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1290 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1292 // remove uncontrolled pets
1293 RemoveMiniPet();
1294 RemoveGuardians();
1296 // save value before aura remove in Unit::setDeathState
1297 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1299 // passive spell
1300 if(!ressSpellId)
1301 ressSpellId = GetResurrectionSpellId();
1303 Unit::setDeathState(s);
1305 // restore resurrection spell id for player after aura remove
1306 if(s == JUST_DIED && cur && ressSpellId)
1307 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1309 if(isAlive() && !cur)
1311 //clear aura case after resurrection by another way (spells will be applied before next death)
1312 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1314 // restore default warrior stance
1315 if(getClass()== CLASS_WARRIOR)
1316 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1320 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1322 *p_data << GetGUID();
1323 *p_data << m_name;
1325 *p_data << getRace();
1326 uint8 pClass = getClass();
1327 *p_data << pClass;
1328 *p_data << getGender();
1330 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1331 *p_data << uint8(bytes);
1332 *p_data << uint8(bytes >> 8);
1333 *p_data << uint8(bytes >> 16);
1334 *p_data << uint8(bytes >> 24);
1336 bytes = GetUInt32Value(PLAYER_BYTES_2);
1337 *p_data << uint8(bytes);
1339 *p_data << uint8(getLevel()); // player level
1340 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1341 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1343 *p_data << zoneId;
1344 *p_data << GetMapId();
1346 *p_data << GetPositionX();
1347 *p_data << GetPositionY();
1348 *p_data << GetPositionZ();
1350 *p_data << GetUInt32Value(PLAYER_GUILDID); // guild id
1352 uint32 char_flags = 0;
1353 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1354 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1355 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1356 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1357 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1358 char_flags |= CHARACTER_FLAG_GHOST;
1359 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1360 char_flags |= CHARACTER_FLAG_RENAME;
1361 // always send the flag if declined names aren't used
1362 // to let the client select a default method of declining the name
1363 if(!sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) || (result && result->Fetch()[13].GetCppString() != ""))
1364 char_flags |= CHARACTER_FLAG_DECLINED;
1366 *p_data << (uint32)char_flags; // character flags
1368 *p_data << (uint8)1; // unknown
1370 // Pets info
1372 uint32 petDisplayId = 0;
1373 uint32 petLevel = 0;
1374 uint32 petFamily = 0;
1376 // show pet at selection character in character list only for non-ghost character
1377 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1379 Field* fields = result->Fetch();
1381 uint32 entry = fields[10].GetUInt32();
1382 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1383 if(cInfo)
1385 petDisplayId = fields[11].GetUInt32();
1386 petLevel = fields[12].GetUInt32();
1387 petFamily = cInfo->family;
1391 *p_data << (uint32)petDisplayId;
1392 *p_data << (uint32)petLevel;
1393 *p_data << (uint32)petFamily;
1396 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1397 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1398 items[i] = NULL;
1400 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1401 if (result)
1405 Field *fields = result->Fetch();
1406 uint8 slot = fields[0].GetUInt8() & 255;
1407 uint32 item_id = fields[1].GetUInt32();
1408 if( slot >= EQUIPMENT_SLOT_END )
1409 continue;
1411 items[slot] = objmgr.GetItemPrototype(item_id);
1412 if(!items[slot])
1414 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1415 continue;
1417 } while (result->NextRow());
1418 delete result;
1421 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1423 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1424 uint32 item_id = GetUInt32Value(visualbase);
1425 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1426 SpellItemEnchantmentEntry const *enchant = NULL;
1428 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1430 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1431 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1432 break;
1435 if (proto != NULL)
1437 *p_data << (uint32)proto->DisplayInfoID;
1438 *p_data << (uint8)proto->InventoryType;
1439 *p_data << (uint32)(enchant?enchant->aura_id:0);
1441 else
1443 *p_data << (uint32)0;
1444 *p_data << (uint8)0;
1445 *p_data << (uint32)0; // enchant?
1448 *p_data << (uint32)0; // first bag display id
1449 *p_data << (uint8)0; // first bag inventory type
1450 *p_data << (uint32)0; // enchant?
1453 bool Player::ToggleAFK()
1455 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1457 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1459 // afk player not allowed in battleground
1460 if(state && InBattleGround())
1461 LeaveBattleground();
1463 return state;
1466 bool Player::ToggleDND()
1468 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1470 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1473 uint8 Player::chatTag() const
1475 // it's bitmask
1476 // 0x8 - ??
1477 // 0x4 - gm
1478 // 0x2 - dnd
1479 // 0x1 - afk
1480 if(isGMChat())
1481 return 4;
1482 else if(isDND())
1483 return 3;
1484 if(isAFK())
1485 return 1;
1486 else
1487 return 0;
1490 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1492 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1494 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1495 return false;
1498 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1499 Pet* pet = GetPet();
1501 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1503 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1504 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1505 return false;
1507 // client without expansion support
1508 if(GetSession()->Expansion() < mEntry->Expansion())
1510 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1512 if(GetTransport())
1513 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1515 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL1);
1517 return false; // normal client can't teleport to this map...
1519 else
1521 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1524 // if we were on a transport, leave
1525 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1527 m_transport->RemovePassenger(this);
1528 m_transport = NULL;
1529 m_movementInfo.t_x = 0.0f;
1530 m_movementInfo.t_y = 0.0f;
1531 m_movementInfo.t_z = 0.0f;
1532 m_movementInfo.t_o = 0.0f;
1533 m_movementInfo.t_time = 0;
1536 SetSemaphoreTeleport(true);
1538 // The player was ported to another map and looses the duel immediately.
1539 // We have to perform this check before the teleport, otherwise the
1540 // ObjectAccessor won't find the flag.
1541 if (duel && GetMapId()!=mapid)
1543 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1544 if (obj)
1545 DuelComplete(DUEL_FLED);
1548 // reset movement flags at teleport, because player will continue move with these flags after teleport
1549 SetUnitMovementFlags(0);
1551 if ((GetMapId() == mapid) && (!m_transport))
1553 // prepare zone change detect
1554 uint32 old_zone = GetZoneId();
1556 // near teleport
1557 if(!GetSession()->PlayerLogout())
1559 WorldPacket data;
1560 BuildTeleportAckMsg(&data, x, y, z, orientation);
1561 GetSession()->SendPacket(&data);
1562 SetPosition( x, y, z, orientation, true);
1564 else
1565 // this will be used instead of the current location in SaveToDB
1566 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1568 //BuildHeartBeatMsg(&data);
1569 //SendMessageToSet(&data, true);
1570 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1572 //same map, only remove pet if out of range
1573 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1575 if(pet->isControlled() && !pet->isTemporarySummoned() )
1576 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1577 else
1578 m_temporaryUnsummonedPetNumber = 0;
1580 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1584 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1585 CombatStop();
1587 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1589 // resummon pet
1590 if(pet && m_temporaryUnsummonedPetNumber)
1592 Pet* NewPet = new Pet;
1593 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1594 delete NewPet;
1596 m_temporaryUnsummonedPetNumber = 0;
1600 if(!GetSession()->PlayerLogout())
1602 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1603 SetSemaphoreTeleport(false);
1605 UpdateZone(GetZoneId());
1608 // new zone
1609 if(old_zone != GetZoneId())
1611 // honorless target
1612 if(pvpInfo.inHostileArea)
1613 CastSpell(this, 2479, true);
1616 else
1618 // far teleport to another map
1619 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1620 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1622 // Check enter rights before map getting to avoid creating instance copy for player
1623 // this check not dependent from map instance copy and same for all instance copies of selected map
1624 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1626 SetSemaphoreTeleport(false);
1627 return false;
1630 // If the map is not created, assume it is possible to enter it.
1631 // It will be created in the WorldPortAck.
1632 Map *map = MapManager::Instance().FindMap(mapid);
1633 if (!map || map->CanEnter(this))
1635 SetSelection(0);
1637 CombatStop();
1639 ResetContestedPvP();
1641 // remove player from battleground on far teleport (when changing maps)
1642 if(BattleGround const* bg = GetBattleGround())
1644 // Note: at battleground join battleground id set before teleport
1645 // and we already will found "current" battleground
1646 // just need check that this is targeted map or leave
1647 if(bg->GetMapId() != mapid)
1648 LeaveBattleground(false); // don't teleport to entry point
1651 // remove pet on map change
1652 if (pet)
1654 //leaving map -> delete pet right away (doing this later will cause problems)
1655 if(pet->isControlled() && !pet->isTemporarySummoned())
1656 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1657 else
1658 m_temporaryUnsummonedPetNumber = 0;
1660 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1663 // remove all dyn objects
1664 RemoveAllDynObjects();
1666 // stop spellcasting
1667 // not attempt interrupt teleportation spell at caster teleport
1668 if(!(options & TELE_TO_SPELL))
1669 if(IsNonMeleeSpellCasted(true))
1670 InterruptNonMeleeSpells(true);
1672 if(!GetSession()->PlayerLogout())
1674 // send transfer packets
1675 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1676 data << uint32(mapid);
1677 if (m_transport)
1679 data << m_transport->GetEntry() << GetMapId();
1681 GetSession()->SendPacket(&data);
1683 data.Initialize(SMSG_NEW_WORLD, (20));
1684 if (m_transport)
1686 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1688 else
1690 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1692 GetSession()->SendPacket( &data );
1693 SendSavedInstances();
1695 // remove from old map now
1696 if(oldmap) oldmap->Remove(this, false);
1699 // new final coordinates
1700 float final_x = x;
1701 float final_y = y;
1702 float final_z = z;
1703 float final_o = orientation;
1705 if(m_transport)
1707 final_x += m_movementInfo.t_x;
1708 final_y += m_movementInfo.t_y;
1709 final_z += m_movementInfo.t_z;
1710 final_o += m_movementInfo.t_o;
1713 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1714 // if the player is saved before worldportack (at logout for example)
1715 // this will be used instead of the current location in SaveToDB
1717 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1719 // move packet sent by client always after far teleport
1720 // SetPosition(final_x, final_y, final_z, final_o, true);
1721 SetDontMove(true);
1723 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1725 else
1726 return false;
1728 return true;
1731 void Player::AddToWorld()
1733 ///- Do not add/remove the player from the object storage
1734 ///- It will crash when updating the ObjectAccessor
1735 ///- The player should only be added when logging in
1736 Unit::AddToWorld();
1738 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1740 if(m_items[i])
1741 m_items[i]->AddToWorld();
1745 void Player::RemoveFromWorld()
1747 // cleanup
1748 if(IsInWorld())
1750 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1751 Uncharm();
1752 UnsummonAllTotems();
1753 RemoveMiniPet();
1754 RemoveGuardians();
1757 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1759 if(m_items[i])
1760 m_items[i]->RemoveFromWorld();
1763 ///- Do not add/remove the player from the object storage
1764 ///- It will crash when updating the ObjectAccessor
1765 ///- The player should only be removed when logging out
1766 Unit::RemoveFromWorld();
1769 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1771 float addRage;
1773 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1775 if(attacker)
1777 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1779 // talent who gave more rage on attack
1780 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1782 else
1784 addRage = damage/rageconversion*2.5;
1786 // Berserker Rage effect
1787 if(HasAura(18499,0))
1788 addRage *= 1.3;
1791 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1793 ModifyPower(POWER_RAGE, uint32(addRage*10));
1796 void Player::RegenerateAll()
1798 if (m_regenTimer != 0)
1799 return;
1800 uint32 regenDelay = 2000;
1802 // Not in combat or they have regeneration
1803 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1804 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1806 RegenerateHealth();
1807 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1808 Regenerate(POWER_RAGE);
1811 Regenerate( POWER_ENERGY );
1813 Regenerate( POWER_MANA );
1815 m_regenTimer = regenDelay;
1818 void Player::Regenerate(Powers power)
1820 uint32 curValue = GetPower(power);
1821 uint32 maxValue = GetMaxPower(power);
1823 float addvalue = 0.0f;
1825 switch (power)
1827 case POWER_MANA:
1829 bool recentCast = IsUnderLastManaUseEffect();
1830 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1831 if (recentCast)
1833 // Mangos Updates Mana in intervals of 2s, which is correct
1834 addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT) * ManaIncreaseRate * 2.00f;
1836 else
1838 addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN) * ManaIncreaseRate * 2.00f;
1840 } break;
1841 case POWER_RAGE: // Regenerate rage
1843 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1844 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1845 } break;
1846 case POWER_ENERGY: // Regenerate energy (rogue)
1847 addvalue = 20;
1848 break;
1849 case POWER_FOCUS:
1850 case POWER_HAPPINESS:
1851 break;
1854 // Mana regen calculated in Player::UpdateManaRegen()
1855 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1856 if(power != POWER_MANA)
1858 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1859 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1860 if ((*i)->GetModifier()->m_miscvalue == power)
1861 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1864 if (power != POWER_RAGE)
1866 curValue += uint32(addvalue);
1867 if (curValue > maxValue)
1868 curValue = maxValue;
1870 else
1872 if(curValue <= uint32(addvalue))
1873 curValue = 0;
1874 else
1875 curValue -= uint32(addvalue);
1877 SetPower(power, curValue);
1880 void Player::RegenerateHealth()
1882 uint32 curValue = GetHealth();
1883 uint32 maxValue = GetMaxHealth();
1885 if (curValue >= maxValue) return;
1887 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1889 float addvalue = 0.0f;
1891 // polymorphed case
1892 if ( IsPolymorphed() )
1893 addvalue = GetMaxHealth()/3;
1894 // normal regen case (maybe partly in combat case)
1895 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1897 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1898 if (!isInCombat())
1900 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1901 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1902 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1904 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1905 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1907 if(!IsStandState())
1908 addvalue *= 1.5;
1911 // always regeneration bonus (including combat)
1912 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1914 if(addvalue < 0)
1915 addvalue = 0;
1917 ModifyHealth(int32(addvalue));
1920 bool Player::CanInteractWithNPCs(bool alive) const
1922 if(alive && !isAlive())
1923 return false;
1924 if(isInFlight())
1925 return false;
1927 return true;
1930 bool Player::IsUnderWater() const
1932 return IsInWater() &&
1933 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1936 void Player::SetInWater(bool apply)
1938 if(m_isInWater==apply)
1939 return;
1941 //define player in water by opcodes
1942 //move player's guid into HateOfflineList of those mobs
1943 //which can't swim and move guid back into ThreatList when
1944 //on surface.
1945 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1946 m_isInWater = apply;
1948 // remove auras that need water/land
1949 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1951 getHostilRefManager().updateThreatTables();
1954 void Player::SetGameMaster(bool on)
1956 if(on)
1958 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1959 setFaction(35);
1960 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1962 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1963 ResetContestedPvP();
1965 getHostilRefManager().setOnlineOfflineState(false);
1966 CombatStop();
1968 else
1970 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1971 setFactionForRace(getRace());
1972 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1974 // restore FFA PvP Server state
1975 if(sWorld.IsFFAPvPRealm())
1976 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1978 // restore FFA PvP area state, remove not allowed for GM mounts
1979 UpdateArea(m_areaUpdateId);
1981 getHostilRefManager().setOnlineOfflineState(true);
1984 ObjectAccessor::UpdateVisibilityForPlayer(this);
1987 void Player::SetGMVisible(bool on)
1989 if(on)
1991 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1993 // Reapply stealth/invisibility if active or show if not any
1994 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
1995 SetVisibility(VISIBILITY_GROUP_STEALTH);
1996 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
1997 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
1998 else
1999 SetVisibility(VISIBILITY_ON);
2001 else
2003 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2005 SetAcceptWhispers(false);
2006 SetGameMaster(true);
2008 SetVisibility(VISIBILITY_OFF);
2012 bool Player::IsGroupVisibleFor(Player* p) const
2014 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2016 default: return IsInSameGroupWith(p);
2017 case 1: return IsInSameRaidWith(p);
2018 case 2: return GetTeam()==p->GetTeam();
2022 bool Player::IsInSameGroupWith(Player const* p) const
2024 return p==this || GetGroup() != NULL &&
2025 GetGroup() == p->GetGroup() &&
2026 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2029 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2030 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2031 void Player::UninviteFromGroup()
2033 if(GetGroupInvite()) // uninvited invitee
2035 Group* group = GetGroupInvite();
2036 group->RemoveInvite(this);
2038 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2040 if(group->IsCreated())
2042 group->Disband(true);
2043 objmgr.RemoveGroup(group);
2045 else
2046 group->RemoveAllInvites();
2048 delete group;
2053 void Player::RemoveFromGroup(Group* group, uint64 guid)
2055 if(group)
2057 if (group->RemoveMember(guid, 0) <= 1)
2059 // group->Disband(); already disbanded in RemoveMember
2060 objmgr.RemoveGroup(group);
2061 delete group;
2062 // removemember sets the player's group pointer to NULL
2067 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2069 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2070 data << uint64(victim ? victim->GetGUID() : 0); // guid
2071 data << uint32(GivenXP+RestXP); // given experience
2072 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2073 if(victim)
2075 data << uint32(GivenXP); // experience without rested bonus
2076 data << float(1); // 1 - none 0 - 100% group bonus output
2078 data << uint8(0); // new 2.4.0
2079 GetSession()->SendPacket(&data);
2082 void Player::GiveXP(uint32 xp, Unit* victim)
2084 if ( xp < 1 )
2085 return;
2087 if(!isAlive())
2088 return;
2090 uint32 level = getLevel();
2092 // XP to money conversion processed in Player::RewardQuest
2093 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2094 return;
2096 // handle SPELL_AURA_MOD_XP_PCT auras
2097 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2098 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2099 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2101 // XP resting bonus for kill
2102 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2104 SendLogXPGain(xp,victim,rested_bonus_xp);
2106 uint32 curXP = GetUInt32Value(PLAYER_XP);
2107 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2108 uint32 newXP = curXP + xp + rested_bonus_xp;
2110 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2112 newXP -= nextLvlXP;
2114 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2115 GiveLevel(level + 1);
2117 level = getLevel();
2118 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2121 SetUInt32Value(PLAYER_XP, newXP);
2124 // Update player to next level
2125 // Current player experience not update (must be update by caller)
2126 void Player::GiveLevel(uint32 level)
2128 if ( level == getLevel() )
2129 return;
2131 PlayerLevelInfo info;
2132 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2134 PlayerClassLevelInfo classInfo;
2135 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2137 // send levelup info to client
2138 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2139 data << uint32(level);
2140 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2141 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2142 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2143 data << uint32(0);
2144 data << uint32(0);
2145 data << uint32(0);
2146 data << uint32(0);
2147 // end for
2148 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2149 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2151 GetSession()->SendPacket(&data);
2153 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2155 //update level, max level of skills
2156 if(getLevel()!= level)
2157 m_Played_time[1] = 0; // Level Played Time reset
2158 SetLevel(level);
2159 UpdateSkillsForLevel ();
2161 // save base values (bonuses already included in stored stats
2162 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2163 SetCreateStat(Stats(i), info.stats[i]);
2165 SetCreateHealth(classInfo.basehealth);
2166 SetCreateMana(classInfo.basemana);
2168 InitTalentForLevel();
2169 InitTaxiNodesForLevel();
2171 UpdateAllStats();
2173 // set current level health and mana/energy to maximum after applying all mods.
2174 SetHealth(GetMaxHealth());
2175 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2176 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2177 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2178 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2179 SetPower(POWER_FOCUS, 0);
2180 SetPower(POWER_HAPPINESS, 0);
2182 // give level to summoned pet
2183 Pet* pet = GetPet();
2184 if(pet && pet->getPetType()==SUMMON_PET)
2185 pet->GivePetLevel(level);
2188 void Player::InitTalentForLevel()
2190 uint32 level = getLevel();
2191 // talents base at level diff ( talents = level - 9 but some can be used already)
2192 if(level < 10)
2194 // Remove all talent points
2195 if(m_usedTalentCount > 0) // Free any used talents
2197 resetTalents(true);
2198 SetFreeTalentPoints(0);
2201 else
2203 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2204 // if used more that have then reset
2205 if(m_usedTalentCount > talentPointsForLevel)
2207 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2208 resetTalents(true);
2209 else
2210 SetFreeTalentPoints(0);
2212 // else update amount of free points
2213 else
2214 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2218 void Player::InitStatsForLevel(bool reapplyMods)
2220 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2221 _RemoveAllStatBonuses();
2223 PlayerClassLevelInfo classInfo;
2224 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2226 PlayerLevelInfo info;
2227 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2229 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2230 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2232 UpdateSkillsForLevel ();
2234 // set default cast time multiplier
2235 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2237 // reset size before reapply auras
2238 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2240 // save base values (bonuses already included in stored stats
2241 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2242 SetCreateStat(Stats(i), info.stats[i]);
2244 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2245 SetStat(Stats(i), info.stats[i]);
2247 SetCreateHealth(classInfo.basehealth);
2249 //set create powers
2250 SetCreateMana(classInfo.basemana);
2252 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2254 InitStatBuffMods();
2256 //reset rating fields values
2257 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2258 SetUInt32Value(index, 0);
2260 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2261 for (int i = 0; i < 7; i++)
2263 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2264 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2265 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2268 //reset attack power, damage and attack speed fields
2269 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2270 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2271 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2273 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2274 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2275 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2276 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2277 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2278 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2280 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2281 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2282 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2283 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2284 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2285 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2287 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2288 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2289 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2290 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2292 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2293 for (uint8 i = 0; i < 7; ++i)
2294 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2296 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2297 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2298 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2300 // Dodge percentage
2301 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2303 // set armor (resistance 0) to original value (create_agility*2)
2304 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2305 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2306 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2307 // set other resistance to original value (0)
2308 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2310 SetResistance(SpellSchools(i), 0);
2311 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2312 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2315 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2316 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2317 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2319 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2320 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2322 // Init data for form but skip reapply item mods for form
2323 InitDataForForm(reapplyMods);
2325 // save new stats
2326 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2327 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2329 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2331 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2332 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2334 // cleanup unit flags (will be re-applied if need at aura load).
2335 RemoveFlag( UNIT_FIELD_FLAGS,
2336 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2337 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2338 UNIT_FLAG_DISABLE_ROTATE | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2339 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2340 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2341 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2343 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2344 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2346 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2348 // restore if need some important flags
2349 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2351 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2352 _ApplyAllStatBonuses();
2354 // set current level health and mana/energy to maximum after applying all mods.
2355 SetHealth(GetMaxHealth());
2356 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2357 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2358 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2359 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2360 SetPower(POWER_FOCUS, 0);
2361 SetPower(POWER_HAPPINESS, 0);
2364 void Player::SendInitialSpells()
2366 uint16 spellCount = 0;
2368 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2369 data << uint8(0);
2371 size_t countPos = data.wpos();
2372 data << uint16(spellCount); // spell count placeholder
2374 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2376 if(itr->second->state == PLAYERSPELL_REMOVED)
2377 continue;
2379 if(!itr->second->active || itr->second->disabled)
2380 continue;
2382 data << uint16(itr->first);
2383 //data << uint16(itr->second->slotId);
2384 data << uint16(0); // it's not slot id
2386 spellCount +=1;
2389 data.put<uint16>(countPos,spellCount); // write real count value
2391 uint16 spellCooldowns = m_spellCooldowns.size();
2392 data << uint16(spellCooldowns);
2393 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
2395 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2396 if(!sEntry)
2397 continue;
2399 data << uint16(itr->first);
2401 time_t cooldown = 0;
2402 time_t curTime = time(NULL);
2403 if(itr->second.end > curTime)
2404 cooldown = (itr->second.end-curTime)*1000;
2406 data << uint16(itr->second.itemid); // cast item id
2407 data << uint16(sEntry->Category); // spell category
2408 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2410 data << uint32(0);
2411 data << uint32(cooldown);
2413 else
2415 data << uint32(cooldown);
2416 data << uint32(0);
2420 GetSession()->SendPacket(&data);
2422 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2425 void Player::RemoveMail(uint32 id)
2427 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2429 if ((*itr)->messageID == id)
2431 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2432 m_mail.erase(itr);
2433 return;
2438 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2440 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2441 data << (uint32) mailId;
2442 data << (uint32) mailAction;
2443 data << (uint32) mailError;
2444 if ( mailError == MAIL_ERR_BAG_FULL )
2445 data << (uint32) equipError;
2446 else if( mailAction == MAIL_ITEM_TAKEN )
2448 data << (uint32) item_guid; // item guid low?
2449 data << (uint32) item_count; // item count?
2451 GetSession()->SendPacket(&data);
2454 void Player::SendNewMail()
2456 // deliver undelivered mail
2457 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2458 data << (uint32) 0;
2459 GetSession()->SendPacket(&data);
2462 void Player::UpdateNextMailTimeAndUnreads()
2464 // calculate next delivery time (min. from non-delivered mails
2465 // and recalculate unReadMail
2466 time_t cTime = time(NULL);
2467 m_nextMailDelivereTime = 0;
2468 unReadMails = 0;
2469 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2471 if((*itr)->deliver_time > cTime)
2473 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2474 m_nextMailDelivereTime = (*itr)->deliver_time;
2476 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2477 ++unReadMails;
2481 void Player::AddNewMailDeliverTime(time_t deliver_time)
2483 if(deliver_time <= time(NULL)) // ready now
2485 ++unReadMails;
2486 SendNewMail();
2488 else // not ready and no have ready mails
2490 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2491 m_nextMailDelivereTime = deliver_time;
2495 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2497 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2498 if (!spellInfo)
2500 // do character spell book cleanup (all characters)
2501 if(loading && !learning) // spell load case
2503 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2504 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2506 else
2507 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2509 return false;
2512 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2514 // do character spell book cleanup (all characters)
2515 if(loading && !learning) // spell load case
2517 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2518 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2520 else
2521 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2523 return false;
2526 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2528 bool disabled_case = false;
2529 bool superceded_old = false;
2531 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2532 if (itr != m_spells.end())
2534 // update active state for known spell
2535 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2537 itr->second->active = active;
2539 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2540 if(loading && !learning)
2541 itr->second->state = PLAYERSPELL_UNCHANGED;
2542 else if(itr->second->state != PLAYERSPELL_NEW)
2543 itr->second->state = PLAYERSPELL_CHANGED;
2545 if(!active)
2547 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2548 data << uint16(spell_id);
2549 GetSession()->SendPacket(&data);
2551 return active; // learn (show in spell book if active now)
2554 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2556 if(itr->second->state != PLAYERSPELL_NEW)
2557 itr->second->state = PLAYERSPELL_CHANGED;
2558 itr->second->disabled = disabled;
2560 if(disabled)
2561 return false;
2563 disabled_case = true;
2565 else switch(itr->second->state)
2567 case PLAYERSPELL_UNCHANGED: // known saved spell
2568 return false;
2569 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2571 delete itr->second;
2572 m_spells.erase(itr);
2573 state = PLAYERSPELL_CHANGED;
2574 break; // need re-add
2576 default: // known not saved yet spell (new or modified)
2578 // can be in case spell loading but learned at some previous spell loading
2579 if(loading && !learning)
2580 itr->second->state = PLAYERSPELL_UNCHANGED;
2582 return false;
2587 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2589 // talent: unlearn all other talent ranks (high and low)
2590 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2592 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2594 for(int i=0; i <5; ++i)
2596 // skip learning spell and no rank spell case
2597 uint32 rankSpellId = talentInfo->RankID[i];
2598 if(!rankSpellId || rankSpellId==spell_id)
2599 continue;
2601 // skip unknown ranks
2602 if(!HasSpell(rankSpellId))
2603 continue;
2605 removeSpell(rankSpellId);
2609 // non talent spell: learn low ranks (recursive call)
2610 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2612 if(loading) // at spells loading, no output, but allow save
2613 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2614 else // at normal learning
2615 learnSpell(prev_spell);
2618 PlayerSpell *newspell = new PlayerSpell;
2619 newspell->active = active;
2620 newspell->state = state;
2621 newspell->disabled = disabled;
2623 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2624 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2626 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2628 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2629 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2630 if(!i_spellInfo) continue;
2632 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2634 if(itr->second->active)
2636 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2638 if(!loading) // not send spell (re-/over-)learn packets at loading
2640 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2641 data << uint16(itr->first);
2642 data << uint16(spell_id);
2643 GetSession()->SendPacket( &data );
2646 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2647 itr->second->active = false;
2648 itr->second->state = PLAYERSPELL_CHANGED;
2649 superceded_old = true; // new spell replace old in action bars and spell book.
2651 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2653 if(!loading) // not send spell (re-/over-)learn packets at loading
2655 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2656 data << uint16(spell_id);
2657 data << uint16(itr->first);
2658 GetSession()->SendPacket( &data );
2661 // mark new spell as disable (not learned yet for client and will not learned)
2662 newspell->active = false;
2663 if(newspell->state != PLAYERSPELL_NEW)
2664 newspell->state = PLAYERSPELL_CHANGED;
2671 uint16 tmpslot=slot_id;
2673 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2675 uint16 maxid = 0;
2676 PlayerSpellMap::iterator itr;
2677 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2679 if(itr->second->state == PLAYERSPELL_REMOVED)
2680 continue;
2681 if (itr->second->slotId > maxid)
2682 maxid = itr->second->slotId;
2684 tmpslot = maxid + 1;
2687 newspell->slotId = tmpslot;
2688 m_spells[spell_id] = newspell;
2690 // return false if spell disabled
2691 if (newspell->disabled)
2692 return false;
2695 uint32 talentCost = GetTalentSpellCost(spell_id);
2697 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2698 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2699 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2701 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2702 CastSpell(this, spell_id, true);
2704 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2705 else if (IsPassiveSpell(spell_id))
2707 // if spell doesn't require a stance or the player is in the required stance
2708 if( ( !spellInfo->Stances &&
2709 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2710 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2711 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2712 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2713 (spell_id == 5420 && m_form == FORM_TREE) ||
2714 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2715 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2716 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2717 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2718 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2719 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2720 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2721 //Check CasterAuraStates
2722 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2723 CastSpell(this, spell_id, true);
2725 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2727 CastSpell(this, spell_id, true);
2728 return false;
2731 // update used talent points count
2732 m_usedTalentCount += talentCost;
2734 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2735 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2737 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2738 SetFreePrimaryProffesions(freeProfs-1);
2741 // add dependent skills
2742 uint16 maxskill = GetMaxSkillValueForLevel();
2744 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2746 if(spellLearnSkill)
2748 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2749 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2751 if(skill_value < spellLearnSkill->value)
2752 skill_value = spellLearnSkill->value;
2754 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2756 if(skill_max_value < new_skill_max_value)
2757 skill_max_value = new_skill_max_value;
2759 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2761 else
2763 // not ranked skills
2764 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2765 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2767 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2769 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2770 if(!pSkill)
2771 continue;
2773 if(HasSkill(pSkill->id))
2774 continue;
2776 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2777 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2778 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2779 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2780 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2782 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2784 case SKILL_RANGE_LANGUAGE:
2785 SetSkill(pSkill->id, 300, 300 );
2786 break;
2787 case SKILL_RANGE_LEVEL:
2788 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2789 break;
2790 case SKILL_RANGE_MONO:
2791 SetSkill(pSkill->id, 1, 1 );
2792 break;
2793 default:
2794 break;
2800 // learn dependent spells
2801 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2802 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2804 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2806 if(!itr->second.autoLearned)
2808 if(loading) // at spells loading, no output, but allow save
2809 addSpell(itr->second.spell,true,true,loading);
2810 else // at normal learning
2811 learnSpell(itr->second.spell);
2815 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2816 return active && !disabled && !superceded_old;
2819 void Player::learnSpell(uint32 spell_id)
2821 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2823 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2824 bool active = disabled ? itr->second->active : true;
2826 bool learning = addSpell(spell_id,active);
2828 // learn all disabled higher ranks (recursive)
2829 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2830 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2832 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2833 if (disabled && iter != m_spells.end() && iter->second->disabled)
2834 learnSpell(i->second);
2837 // prevent duplicated entires in spell book
2838 if(!learning)
2839 return;
2841 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2842 data << uint32(spell_id);
2843 GetSession()->SendPacket(&data);
2846 void Player::removeSpell(uint32 spell_id, bool disabled)
2848 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2849 if (itr == m_spells.end())
2850 return;
2852 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2853 return;
2855 // unlearn non talent higher ranks (recursive)
2856 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2857 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2858 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2859 removeSpell(itr2->second,disabled);
2861 // removing
2862 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2863 data << uint16(spell_id);
2864 GetSession()->SendPacket(&data);
2866 if (disabled)
2868 itr->second->disabled = disabled;
2869 if(itr->second->state != PLAYERSPELL_NEW)
2870 itr->second->state = PLAYERSPELL_CHANGED;
2872 else
2874 if(itr->second->state == PLAYERSPELL_NEW)
2876 delete itr->second;
2877 m_spells.erase(itr);
2879 else
2880 itr->second->state = PLAYERSPELL_REMOVED;
2883 RemoveAurasDueToSpell(spell_id);
2885 // remove pet auras
2886 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2887 RemovePetAura(petSpell);
2889 // free talent points
2890 uint32 talentCosts = GetTalentSpellCost(spell_id);
2891 if(talentCosts > 0)
2893 if(talentCosts < m_usedTalentCount)
2894 m_usedTalentCount -= talentCosts;
2895 else
2896 m_usedTalentCount = 0;
2899 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2900 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2902 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2903 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2904 SetFreePrimaryProffesions(freeProfs);
2907 // remove dependent skill
2908 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2909 if(spellLearnSkill)
2911 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2912 if(!prev_spell) // first rank, remove skill
2913 SetSkill(spellLearnSkill->skill,0,0);
2914 else
2916 // search prev. skill setting by spell ranks chain
2917 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2918 while(!prevSkill && prev_spell)
2920 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2921 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2924 if(!prevSkill) // not found prev skill setting, remove skill
2925 SetSkill(spellLearnSkill->skill,0,0);
2926 else // set to prev. skill setting values
2928 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2929 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2931 if(skill_value > prevSkill->value)
2932 skill_value = prevSkill->value;
2934 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2936 if(skill_max_value > new_skill_max_value)
2937 skill_max_value = new_skill_max_value;
2939 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2944 else
2946 // not ranked skills
2947 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2948 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2950 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2952 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2953 if(!pSkill)
2954 continue;
2956 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2957 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2958 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2959 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2960 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2962 // not reset skills for professions and racial abilities
2963 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2964 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2965 continue;
2967 SetSkill(pSkill->id, 0, 0 );
2972 // remove dependent spells
2973 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2974 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2976 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2977 removeSpell(itr2->second.spell, disabled);
2980 void Player::RemoveArenaSpellCooldowns()
2982 // remove cooldowns on spells that has < 15 min CD
2983 SpellCooldowns::iterator itr, next;
2984 // iterate spell cooldowns
2985 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2987 next = itr;
2988 ++next;
2989 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
2990 // check if spellentry is present and if the cooldown is less than 15 mins
2991 if( entry &&
2992 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
2993 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
2995 // notify player
2996 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2997 data << uint32(itr->first);
2998 data << GetGUID();
2999 GetSession()->SendPacket(&data);
3000 // remove cooldown
3001 m_spellCooldowns.erase(itr);
3006 void Player::RemoveAllSpellCooldown()
3008 if(!m_spellCooldowns.empty())
3010 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3012 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3013 data << uint32(itr->first);
3014 data << uint64(GetGUID());
3015 GetSession()->SendPacket(&data);
3017 m_spellCooldowns.clear();
3021 void Player::_LoadSpellCooldowns(QueryResult *result)
3023 m_spellCooldowns.clear();
3025 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3027 if(result)
3029 time_t curTime = time(NULL);
3033 Field *fields = result->Fetch();
3035 uint32 spell_id = fields[0].GetUInt32();
3036 uint32 item_id = fields[1].GetUInt32();
3037 time_t db_time = (time_t)fields[2].GetUInt64();
3039 if(!sSpellStore.LookupEntry(spell_id))
3041 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3042 continue;
3045 // skip outdated cooldown
3046 if(db_time <= curTime)
3047 continue;
3049 AddSpellCooldown(spell_id, item_id, db_time);
3051 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3053 while( result->NextRow() );
3055 delete result;
3059 void Player::_SaveSpellCooldowns()
3061 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3063 time_t curTime = time(NULL);
3065 // remove outdated and save active
3066 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3068 if(itr->second.end <= curTime)
3069 m_spellCooldowns.erase(itr++);
3070 else
3072 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));
3073 ++itr;
3078 uint32 Player::resetTalentsCost() const
3080 // The first time reset costs 1 gold
3081 if(m_resetTalentsCost < 1*GOLD)
3082 return 1*GOLD;
3083 // then 5 gold
3084 else if(m_resetTalentsCost < 5*GOLD)
3085 return 5*GOLD;
3086 // After that it increases in increments of 5 gold
3087 else if(m_resetTalentsCost < 10*GOLD)
3088 return 10*GOLD;
3089 else
3091 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3092 if(months > 0)
3094 // This cost will be reduced by a rate of 5 gold per month
3095 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3096 // to a minimum of 10 gold.
3097 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3099 else
3101 // After that it increases in increments of 5 gold
3102 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3103 // until it hits a cap of 50 gold.
3104 if(new_cost > 50*GOLD)
3105 new_cost = 50*GOLD;
3106 return new_cost;
3111 bool Player::resetTalents(bool no_cost)
3113 // not need after this call
3114 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3116 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3117 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3120 uint32 level = getLevel();
3121 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3123 if (m_usedTalentCount == 0)
3125 SetFreeTalentPoints(talentPointsForLevel);
3126 return false;
3129 uint32 cost = 0;
3131 if(!no_cost)
3133 cost = resetTalentsCost();
3135 if (GetMoney() < cost)
3137 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3138 return false;
3142 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3144 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3146 if (!talentInfo) continue;
3148 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3150 if(!talentTabInfo)
3151 continue;
3153 // unlearn only talents for character class
3154 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3155 // to prevent unexpected lost normal learned spell skip another class talents
3156 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3157 continue;
3159 for (int j = 0; j < 5; j++)
3161 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3163 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3165 ++itr;
3166 continue;
3169 // remove learned spells (all ranks)
3170 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3172 // unlearn if first rank is talent or learned by talent
3173 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3175 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3176 itr = GetSpellMap().begin();
3177 continue;
3179 else
3180 ++itr;
3185 SetFreeTalentPoints(talentPointsForLevel);
3187 if(!no_cost)
3189 ModifyMoney(-(int32)cost);
3191 m_resetTalentsCost = cost;
3192 m_resetTalentsTime = time(NULL);
3195 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3196 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3198 return true;
3201 bool Player::_removeSpell(uint16 spell_id)
3203 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3204 if (itr != m_spells.end())
3206 delete itr->second;
3207 m_spells.erase(itr);
3208 return true;
3210 return false;
3213 Mail* Player::GetMail(uint32 id)
3215 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
3217 if ((*itr)->messageID == id)
3219 return (*itr);
3222 return NULL;
3225 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3227 if(target == this)
3229 Object::_SetCreateBits(updateMask, target);
3231 else
3233 for(uint16 index = 0; index < m_valuesCount; index++)
3235 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3236 updateMask->SetBit(index);
3241 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3243 if(target == this)
3245 Object::_SetUpdateBits(updateMask, target);
3247 else
3249 Object::_SetUpdateBits(updateMask, target);
3250 *updateMask &= updateVisualBits;
3254 void Player::InitVisibleBits()
3256 updateVisualBits.SetCount(PLAYER_END);
3258 // TODO: really implement OWNER_ONLY and GROUP_ONLY. Flags can be found in UpdateFields.h
3260 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3261 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3262 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3264 updateVisualBits.SetBit(UNIT_FIELD_CHARM);
3265 updateVisualBits.SetBit(UNIT_FIELD_CHARM+1);
3267 updateVisualBits.SetBit(UNIT_FIELD_SUMMON);
3268 updateVisualBits.SetBit(UNIT_FIELD_SUMMON+1);
3270 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY);
3271 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY+1);
3273 updateVisualBits.SetBit(UNIT_FIELD_TARGET);
3274 updateVisualBits.SetBit(UNIT_FIELD_TARGET+1);
3276 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT);
3277 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT+1);
3279 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3280 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3281 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3282 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3283 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3284 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3286 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3287 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3288 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3289 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3290 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3291 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3293 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3294 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3295 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3296 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3297 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3298 for(uint16 i = UNIT_FIELD_AURA; i < UNIT_FIELD_AURASTATE; ++i)
3299 updateVisualBits.SetBit(i);
3300 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3301 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME);
3302 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3303 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3304 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3305 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3306 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3307 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3308 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3309 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3310 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3311 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3312 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3313 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3314 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3316 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER);
3317 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER+1);
3318 updateVisualBits.SetBit(PLAYER_FLAGS);
3319 updateVisualBits.SetBit(PLAYER_GUILDID);
3320 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3321 updateVisualBits.SetBit(PLAYER_BYTES);
3322 updateVisualBits.SetBit(PLAYER_BYTES_2);
3323 updateVisualBits.SetBit(PLAYER_BYTES_3);
3324 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3325 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3327 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3328 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i+=4)
3329 updateVisualBits.SetBit(i);
3331 //Players visible items are not inventory stuff
3332 //431) = 884 (0x374) = main weapon
3333 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; i++)
3335 // item creator
3336 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + (i*MAX_VISIBLE_ITEM_OFFSET) + 0);
3337 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + (i*MAX_VISIBLE_ITEM_OFFSET) + 1);
3339 uint16 visual_base = PLAYER_VISIBLE_ITEM_1_0 + (i*MAX_VISIBLE_ITEM_OFFSET);
3341 // item entry
3342 updateVisualBits.SetBit(visual_base + 0);
3344 // item enchantment IDs
3345 for(uint8 j = 0; j < MAX_INSPECTED_ENCHANTMENT_SLOT; ++j)
3346 updateVisualBits.SetBit(visual_base + 1 + j);
3348 // random properties
3349 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (i*MAX_VISIBLE_ITEM_OFFSET));
3350 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (i*MAX_VISIBLE_ITEM_OFFSET));
3353 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3356 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3358 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3360 if(m_items[i] == NULL)
3361 continue;
3363 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3366 if(target == this)
3369 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3371 if(m_items[i] == NULL)
3372 continue;
3374 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3376 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3378 if(m_items[i] == NULL)
3379 continue;
3381 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3385 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3388 void Player::DestroyForPlayer( Player *target ) const
3390 Unit::DestroyForPlayer( target );
3392 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3394 if(m_items[i] == NULL)
3395 continue;
3397 m_items[i]->DestroyForPlayer( target );
3400 if(target == this)
3403 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3405 if(m_items[i] == NULL)
3406 continue;
3408 m_items[i]->DestroyForPlayer( target );
3410 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3412 if(m_items[i] == NULL)
3413 continue;
3415 m_items[i]->DestroyForPlayer( target );
3420 bool Player::HasSpell(uint32 spell) const
3422 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3423 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3426 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3428 if (!trainer_spell)
3429 return TRAINER_SPELL_RED;
3431 if (!trainer_spell->spell)
3432 return TRAINER_SPELL_RED;
3434 // known spell
3435 if(HasSpell(trainer_spell->spell))
3436 return TRAINER_SPELL_GRAY;
3438 // check race/class requirement
3439 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3440 return TRAINER_SPELL_RED;
3442 // check level requirement
3443 if(getLevel() < trainer_spell->reqlevel)
3444 return TRAINER_SPELL_RED;
3446 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3448 // check prev.rank requirement
3449 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3450 return TRAINER_SPELL_RED;
3452 // check additional spell requirement
3453 if(spell_chain->req && !HasSpell(spell_chain->req))
3454 return TRAINER_SPELL_RED;
3457 // check skill requirement
3458 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3459 return TRAINER_SPELL_RED;
3461 // exist, already checked at loading
3462 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3464 // secondary prof. or not prof. spell
3465 uint32 skill = spell->EffectMiscValue[1];
3467 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3468 return TRAINER_SPELL_GREEN;
3470 // check primary prof. limit
3471 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3472 return TRAINER_SPELL_RED;
3474 return TRAINER_SPELL_GREEN;
3477 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3479 uint32 guid = GUID_LOPART(playerguid);
3481 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3482 // bones will be deleted by corpse/bones deleting thread shortly
3483 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3485 // remove from guild
3486 uint32 guildId = GetGuildIdFromDB(playerguid);
3487 if(guildId != 0)
3489 Guild* guild = objmgr.GetGuildById(guildId);
3490 if(guild)
3491 guild->DelMember(guid);
3494 // the player was uninvited already on logout so just remove from group
3495 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3496 if(resultGroup)
3498 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3499 delete resultGroup;
3500 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3501 if(group)
3503 RemoveFromGroup(group, playerguid);
3507 // remove signs from petitions (also remove petitions if owner);
3508 RemovePetitionsAndSigns(playerguid, 10);
3510 // return back all mails with COD and Item 0 1 2 3 4 5 6
3511 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);
3512 if(resultMail)
3516 Field *fields = resultMail->Fetch();
3518 uint32 mail_id = fields[0].GetUInt32();
3519 uint16 mailTemplateId= fields[1].GetUInt16();
3520 uint32 sender = fields[2].GetUInt32();
3521 std::string subject = fields[3].GetCppString();
3522 uint32 itemTextId = fields[4].GetUInt32();
3523 uint32 money = fields[5].GetUInt32();
3524 bool has_items = fields[6].GetBool();
3526 //we can return mail now
3527 //so firstly delete the old one
3528 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3530 MailItemsInfo mi;
3531 if(has_items)
3533 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3534 if(resultItems)
3538 Field *fields2 = resultItems->Fetch();
3540 uint32 item_guidlow = fields2[0].GetUInt32();
3541 uint32 item_template = fields2[1].GetUInt32();
3543 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3544 if(!itemProto)
3546 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3547 continue;
3550 Item *pItem = NewItemOrBag(itemProto);
3551 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3553 pItem->FSetState(ITEM_REMOVED);
3554 pItem->SaveToDB(); // it also deletes item object !
3555 continue;
3558 mi.AddItem(item_guidlow, item_template, pItem);
3560 while (resultItems->NextRow());
3562 delete resultItems;
3566 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3568 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3570 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3572 while (resultMail->NextRow());
3574 delete resultMail;
3577 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3578 // Get guids of character's pets, will deleted in transaction
3579 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3581 // NOW we can finally clear other DB data related to character
3582 CharacterDatabase.BeginTransaction();
3583 if (resultPets)
3587 Field *fields3 = resultPets->Fetch();
3588 uint32 petguidlow = fields3[0].GetUInt32();
3589 Pet::DeleteFromDB(petguidlow);
3590 } while (resultPets->NextRow());
3591 delete resultPets;
3594 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3595 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3596 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3597 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3598 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3599 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3600 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3601 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3602 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3603 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3604 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3605 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3606 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3607 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3608 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3609 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3610 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3611 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3612 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3613 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3614 CharacterDatabase.CommitTransaction();
3616 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3617 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3620 void Player::SetMovement(PlayerMovementType pType)
3622 WorldPacket data;
3623 switch(pType)
3625 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3626 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3627 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3628 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3629 default:
3630 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3631 return;
3633 data.append(GetPackGUID());
3634 data << uint32(0);
3635 GetSession()->SendPacket( &data );
3638 /* Preconditions:
3639 - a resurrectable corpse must not be loaded for the player (only bones)
3640 - the player must be in world
3642 void Player::BuildPlayerRepop()
3644 if(getRace() == RACE_NIGHTELF)
3645 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)
3646 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3648 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3649 // there must be SMSG.STOP_MIRROR_TIMER
3650 // there we must send 888 opcode
3652 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3653 if(GetCorpse())
3655 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3656 assert(false);
3659 // create a corpse and place it at the player's location
3660 CreateCorpse();
3661 Corpse *corpse = GetCorpse();
3662 if(!corpse)
3664 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3665 return;
3667 GetMap()->Add(corpse);
3669 // convert player body to ghost
3670 SetHealth( 1 );
3672 SetMovement(MOVE_WATER_WALK);
3673 if(!GetSession()->isLogingOut())
3674 SetMovement(MOVE_UNROOT);
3676 // BG - remove insignia related
3677 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3679 SendCorpseReclaimDelay();
3681 // to prevent cheating
3682 corpse->ResetGhostTime();
3684 StopMirrorTimers(); //disable timers(bars)
3686 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3688 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3691 void Player::SendDelayResponse(const uint32 ml_seconds)
3693 //FIXME: is this delay time arg really need? 50msec by default in code
3694 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3695 data << (uint32)time(NULL);
3696 data << (uint32)0;
3697 GetSession()->SendPacket( &data );
3700 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3702 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3703 data << uint32(-1);
3704 data << float(0);
3705 data << float(0);
3706 data << float(0);
3707 GetSession()->SendPacket(&data);
3709 // speed change, land walk
3711 // remove death flag + set aura
3712 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3713 if(getRace() == RACE_NIGHTELF)
3714 RemoveAurasDueToSpell(20584); // speed bonuses
3715 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3717 setDeathState(ALIVE);
3719 SetMovement(MOVE_LAND_WALK);
3720 SetMovement(MOVE_UNROOT);
3722 m_deathTimer = 0;
3724 // set health/powers (0- will be set in caller)
3725 if(restore_percent>0.0f)
3727 SetHealth(uint32(GetMaxHealth()*restore_percent));
3728 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3729 SetPower(POWER_RAGE, 0);
3730 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3733 // update visibility
3734 ObjectAccessor::UpdateVisibilityForPlayer(this);
3736 // some items limited to specific map
3737 DestroyZoneLimitedItem( true, GetZoneId());
3739 if(!applySickness)
3740 return;
3742 //Characters from level 1-10 are not affected by resurrection sickness.
3743 //Characters from level 11-19 will suffer from one minute of sickness
3744 //for each level they are above 10.
3745 //Characters level 20 and up suffer from ten minutes of sickness.
3746 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3748 if(int32(getLevel()) >= startLevel)
3750 // set resurrection sickness
3751 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3753 // not full duration
3754 if(int32(getLevel()) < startLevel+9)
3756 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3758 for(int i =0; i < 3; ++i)
3760 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3762 Aur->SetAuraDuration(delta*1000);
3763 Aur->UpdateAuraDuration();
3770 void Player::KillPlayer()
3772 SetMovement(MOVE_ROOT);
3774 StopMirrorTimers(); //disable timers(bars)
3776 setDeathState(CORPSE);
3777 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3779 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3780 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3782 // 6 minutes until repop at graveyard
3783 m_deathTimer = 6*MINUTE*1000;
3785 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3787 // don't create corpse at this moment, player might be falling
3789 // update visibility
3790 ObjectAccessor::UpdateObjectVisibility(this);
3793 void Player::CreateCorpse()
3795 // prevent existence 2 corpse for player
3796 SpawnCorpseBones();
3798 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3800 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3801 SetPvPDeath(false);
3803 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3804 GetPositionY(), GetPositionZ(), GetOrientation()))
3806 delete corpse;
3807 return;
3810 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3811 _pb = GetUInt32Value(PLAYER_BYTES);
3812 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3814 uint8 race = (uint8)(_uf);
3815 uint8 skin = (uint8)(_pb);
3816 uint8 face = (uint8)(_pb >> 8);
3817 uint8 hairstyle = (uint8)(_pb >> 16);
3818 uint8 haircolor = (uint8)(_pb >> 24);
3819 uint8 facialhair = (uint8)(_pb2);
3821 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3822 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3824 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3825 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3827 uint32 flags = CORPSE_FLAG_UNK2;
3828 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3829 flags |= CORPSE_FLAG_HIDE_HELM;
3830 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3831 flags |= CORPSE_FLAG_HIDE_CLOAK;
3832 if(InBattleGround())
3833 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3834 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3836 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3838 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3840 uint32 iDisplayID;
3841 uint16 iIventoryType;
3842 uint32 _cfi;
3843 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3845 if(m_items[i])
3847 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3848 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3850 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3851 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3855 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3856 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3857 assert(entry);
3858 if(entry->map_type != MAP_BATTLEGROUND)
3859 corpse->SaveToDB();
3861 // register for player, but not show
3862 ObjectAccessor::Instance().AddCorpse(corpse);
3865 void Player::SpawnCorpseBones()
3867 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3868 SaveToDB(); // prevent loading as ghost without corpse
3871 Corpse* Player::GetCorpse() const
3873 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3876 void Player::DurabilityLossAll(double percent, bool inventory)
3878 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3879 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3880 DurabilityLoss(pItem,percent);
3882 if(inventory)
3884 // bags not have durability
3885 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3887 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3888 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3889 DurabilityLoss(pItem,percent);
3891 // keys not have durability
3892 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3894 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3895 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3896 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3897 if(Item* pItem = GetItemByPos( i, j ))
3898 DurabilityLoss(pItem,percent);
3902 void Player::DurabilityLoss(Item* item, double percent)
3904 if(!item )
3905 return;
3907 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3909 if(!pMaxDurability)
3910 return;
3912 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3914 if(pDurabilityLoss < 1 )
3915 pDurabilityLoss = 1;
3917 DurabilityPointsLoss(item,pDurabilityLoss);
3920 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3922 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3923 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3924 DurabilityPointsLoss(pItem,points);
3926 if(inventory)
3928 // bags not have durability
3929 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3931 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3932 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3933 DurabilityPointsLoss(pItem,points);
3935 // keys not have durability
3936 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3938 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3939 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3940 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3941 if(Item* pItem = GetItemByPos( i, j ))
3942 DurabilityPointsLoss(pItem,points);
3946 void Player::DurabilityPointsLoss(Item* item, int32 points)
3948 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3949 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3950 int32 pNewDurability = pOldDurability - points;
3952 if (pNewDurability < 0)
3953 pNewDurability = 0;
3954 else if (pNewDurability > pMaxDurability)
3955 pNewDurability = pMaxDurability;
3957 if (pOldDurability != pNewDurability)
3959 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3960 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3961 _ApplyItemMods(item,item->GetSlot(), false);
3963 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3965 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3966 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3967 _ApplyItemMods(item,item->GetSlot(), true);
3969 item->SetState(ITEM_CHANGED, this);
3973 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3975 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3976 DurabilityPointsLoss(pItem,1);
3979 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3981 uint32 TotalCost = 0;
3982 // equipped, backpack, bags itself
3983 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3984 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3986 // bank, buyback and keys not repaired
3988 // items in inventory bags
3989 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3990 for(int i = 0; i < MAX_BAG_SIZE; i++)
3991 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3992 return TotalCost;
3995 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3997 Item* item = GetItemByPos(pos);
3999 uint32 TotalCost = 0;
4000 if(!item)
4001 return TotalCost;
4003 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4004 if(!maxDurability)
4005 return TotalCost;
4007 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4009 if(cost)
4011 uint32 LostDurability = maxDurability - curDurability;
4012 if(LostDurability>0)
4014 ItemPrototype const *ditemProto = item->GetProto();
4016 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4017 if(!dcost)
4019 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4020 return TotalCost;
4023 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4024 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4025 if(!dQualitymodEntry)
4027 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4028 return TotalCost;
4031 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4032 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4034 costs = uint32(costs * discountMod);
4036 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4037 costs = 1;
4039 if (guildBank)
4041 if (GetGuildId()==0)
4043 DEBUG_LOG("You are not member of a guild");
4044 return TotalCost;
4047 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4048 if (!pGuild)
4049 return TotalCost;
4051 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4053 DEBUG_LOG("You do not have rights to withdraw for repairs");
4054 return TotalCost;
4057 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4059 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4060 return TotalCost;
4063 if (pGuild->GetGuildBankMoney() < costs)
4065 DEBUG_LOG("There is not enough money in bank");
4066 return TotalCost;
4069 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4070 TotalCost = costs;
4072 else if (GetMoney() < costs)
4074 DEBUG_LOG("You do not have enough money");
4075 return TotalCost;
4077 else
4078 ModifyMoney( -int32(costs) );
4082 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4083 item->SetState(ITEM_CHANGED, this);
4085 // reapply mods for total broken and repaired item if equipped
4086 if(IsEquipmentPos(pos) && !curDurability)
4087 _ApplyItemMods(item,pos & 255, true);
4088 return TotalCost;
4091 void Player::RepopAtGraveyard()
4093 // note: this can be called also when the player is alive
4094 // for example from WorldSession::HandleMovementOpcodes
4096 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4098 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4099 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4101 ResurrectPlayer(0.5f);
4102 SpawnCorpseBones();
4105 WorldSafeLocsEntry const *ClosestGrave = NULL;
4107 // Special handle for battleground maps
4108 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4110 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4111 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4112 else
4113 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4115 // stop countdown until repop
4116 m_deathTimer = 0;
4118 // if no grave found, stay at the current location
4119 // and don't show spirit healer location
4120 if(ClosestGrave)
4122 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4123 if(isDead()) // not send if alive, because it used in TeleportTo()
4125 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4126 data << ClosestGrave->map_id;
4127 data << ClosestGrave->x;
4128 data << ClosestGrave->y;
4129 data << ClosestGrave->z;
4130 GetSession()->SendPacket(&data);
4135 void Player::JoinedChannel(Channel *c)
4137 m_channels.push_back(c);
4140 void Player::LeftChannel(Channel *c)
4142 m_channels.remove(c);
4145 void Player::CleanupChannels()
4147 while(!m_channels.empty())
4149 Channel* ch = *m_channels.begin();
4150 m_channels.erase(m_channels.begin()); // remove from player's channel list
4151 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4152 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4153 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4156 sLog.outDebug("Player: channels cleaned up!");
4159 void Player::UpdateLocalChannels(uint32 newZone )
4161 if(m_channels.empty())
4162 return;
4164 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4165 if(!current_zone)
4166 return;
4168 ChannelMgr* cMgr = channelMgr(GetTeam());
4169 if(!cMgr)
4170 return;
4172 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4174 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4176 next = i; ++next;
4178 // skip non built-in channels
4179 if(!(*i)->IsConstant())
4180 continue;
4182 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4183 if(!ch)
4184 continue;
4186 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4187 continue;
4189 // new channel
4190 char new_channel_name_buf[100];
4191 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4192 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4194 if((*i)!=new_channel)
4196 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4198 // leave old channel
4199 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4200 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4201 LeftChannel(*i); // remove from player's channel list
4202 cMgr->LeftChannel(name); // delete if empty
4205 sLog.outDebug("Player: channels cleaned up!");
4208 void Player::LeaveLFGChannel()
4210 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4212 if((*i)->IsLFG())
4214 (*i)->Leave(GetGUID());
4215 break;
4220 void Player::UpdateDefense()
4222 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4224 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4226 // update dependent from defense skill part
4227 UpdateDefenseBonusesMod();
4231 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4233 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4235 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4236 return;
4239 float val = 1.0f;
4241 switch(modType)
4243 case FLAT_MOD:
4244 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4245 break;
4246 case PCT_MOD:
4247 if(amount <= -100.0f)
4248 amount = -200.0f;
4250 val = (100.0f + amount) / 100.0f;
4251 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4252 break;
4255 if(!CanModifyStats())
4256 return;
4258 switch(modGroup)
4260 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4261 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4262 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4263 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4264 default: break;
4268 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4270 if(modGroup >= BASEMOD_END || modType > MOD_END)
4272 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4273 return 0.0f;
4276 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4277 return 0.0f;
4279 return m_auraBaseMod[modGroup][modType];
4282 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4284 if(modGroup >= BASEMOD_END)
4286 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4287 return 0.0f;
4290 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4291 return 0.0f;
4293 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4296 uint32 Player::GetShieldBlockValue() const
4298 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4300 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4302 value = (value < 0) ? 0 : value;
4304 return uint32(value);
4307 float Player::GetMeleeCritFromAgility()
4309 uint32 level = getLevel();
4310 uint32 pclass = getClass();
4312 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4314 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4315 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4316 if (critBase==NULL || critRatio==NULL)
4317 return 0.0f;
4319 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4320 return crit*100.0f;
4323 float Player::GetDodgeFromAgility()
4325 // Table for base dodge values
4326 float dodge_base[MAX_CLASSES] = {
4327 0.0075f, // Warrior
4328 0.00652f, // Paladin
4329 -0.0545f, // Hunter
4330 -0.0059f, // Rogue
4331 0.03183f, // Priest
4332 0.0114f, // DK
4333 0.0167f, // Shaman
4334 0.034575f, // Mage
4335 0.02011f, // Warlock
4336 0.0f, // ??
4337 -0.0187f // Druid
4339 // Crit/agility to dodge/agility coefficient multipliers
4340 float crit_to_dodge[MAX_CLASSES] = {
4341 1.1f, // Warrior
4342 1.0f, // Paladin
4343 1.6f, // Hunter
4344 2.0f, // Rogue
4345 1.0f, // Priest
4346 1.0f, // DK?
4347 1.0f, // Shaman
4348 1.0f, // Mage
4349 1.0f, // Warlock
4350 0.0f, // ??
4351 1.7f // Druid
4354 uint32 level = getLevel();
4355 uint32 pclass = getClass();
4357 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4359 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4360 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4361 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4362 return 0.0f;
4364 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4365 return dodge*100.0f;
4368 float Player::GetSpellCritFromIntellect()
4370 uint32 level = getLevel();
4371 uint32 pclass = getClass();
4373 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4375 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4376 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4377 if (critBase==NULL || critRatio==NULL)
4378 return 0.0f;
4380 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4381 return crit*100.0f;
4384 float Player::GetRatingCoefficient(CombatRating cr) const
4386 uint32 level = getLevel();
4388 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4390 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4391 if (Rating == NULL)
4392 return 1.0f; // By default use minimum coefficient (not must be called)
4394 return Rating->ratio;
4397 float Player::GetRatingBonusValue(CombatRating cr) const
4399 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4402 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4404 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4405 if (melee>25.0f) melee = 25.0f;
4406 return uint32 (melee * damage /100.0f);
4409 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4411 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4412 if (ranged>25.0f) ranged=25.0f;
4413 return uint32 (ranged * damage /100.0f);
4416 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4418 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4419 // In wow script resilience limited to 25%
4420 if (spell>25.0f)
4421 spell = 25.0f;
4422 return uint32 (spell * damage / 100.0f);
4425 uint32 Player::GetDotDamageReduction(uint32 damage) const
4427 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4428 // Dot resilience not limited (limit it by 100%)
4429 if (spellDot > 100.0f)
4430 spellDot = 100.0f;
4431 return uint32 (spellDot * damage / 100.0f);
4434 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4436 switch (attType)
4438 case BASE_ATTACK:
4439 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4440 case OFF_ATTACK:
4441 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4442 default:
4443 break;
4445 return 0.0f;
4448 float Player::OCTRegenHPPerSpirit()
4450 uint32 level = getLevel();
4451 uint32 pclass = getClass();
4453 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4455 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4456 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4457 if (baseRatio==NULL || moreRatio==NULL)
4458 return 0.0f;
4460 // Formula from PaperDollFrame script
4461 float spirit = GetStat(STAT_SPIRIT);
4462 float baseSpirit = spirit;
4463 if (baseSpirit>50) baseSpirit = 50;
4464 float moreSpirit = spirit - baseSpirit;
4465 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4466 return regen;
4469 float Player::OCTRegenMPPerSpirit()
4471 uint32 level = getLevel();
4472 uint32 pclass = getClass();
4474 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4476 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4477 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4478 if (moreRatio==NULL)
4479 return 0.0f;
4481 // Formula get from PaperDollFrame script
4482 float spirit = GetStat(STAT_SPIRIT);
4483 float regen = spirit * moreRatio->ratio;
4484 return regen;
4487 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4489 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4491 float RatingCoeffecient = GetRatingCoefficient(cr);
4492 float RatingChange = 0.0f;
4494 bool affectStats = CanModifyStats();
4496 switch (cr)
4498 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4499 case CR_DEFENSE_SKILL:
4500 UpdateDefenseBonusesMod();
4501 break;
4502 case CR_DODGE:
4503 UpdateDodgePercentage();
4504 break;
4505 case CR_PARRY:
4506 UpdateParryPercentage();
4507 break;
4508 case CR_BLOCK:
4509 UpdateBlockPercentage();
4510 break;
4511 case CR_HIT_MELEE:
4512 RatingChange = value / RatingCoeffecient;
4513 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4514 break;
4515 case CR_HIT_RANGED:
4516 RatingChange = value / RatingCoeffecient;
4517 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4518 break;
4519 case CR_HIT_SPELL:
4520 RatingChange = value / RatingCoeffecient;
4521 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4522 break;
4523 case CR_CRIT_MELEE:
4524 if(affectStats)
4526 UpdateCritPercentage(BASE_ATTACK);
4527 UpdateCritPercentage(OFF_ATTACK);
4529 break;
4530 case CR_CRIT_RANGED:
4531 if(affectStats)
4532 UpdateCritPercentage(RANGED_ATTACK);
4533 break;
4534 case CR_CRIT_SPELL:
4535 if(affectStats)
4536 UpdateAllSpellCritChances();
4537 break;
4538 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4539 case CR_HIT_TAKEN_RANGED:
4540 break;
4541 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4542 break;
4543 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4544 case CR_CRIT_TAKEN_RANGED:
4545 break;
4546 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4547 break;
4548 case CR_HASTE_MELEE:
4549 RatingChange = value / RatingCoeffecient;
4550 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4551 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4552 break;
4553 case CR_HASTE_RANGED:
4554 RatingChange = value / RatingCoeffecient;
4555 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4556 break;
4557 case CR_HASTE_SPELL:
4558 RatingChange = value / RatingCoeffecient;
4559 ApplyCastTimePercentMod(RatingChange,apply);
4560 break;
4561 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4562 case CR_WEAPON_SKILL_OFFHAND:
4563 case CR_WEAPON_SKILL_RANGED:
4564 break;
4565 case CR_EXPERTISE:
4566 if(affectStats)
4568 UpdateExpertise(BASE_ATTACK);
4569 UpdateExpertise(OFF_ATTACK);
4571 break;
4575 void Player::SetRegularAttackTime()
4577 for(int i = 0; i < MAX_ATTACK; ++i)
4579 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4580 if(tmpitem && !tmpitem->IsBroken())
4582 ItemPrototype const *proto = tmpitem->GetProto();
4583 if(proto->Delay)
4584 SetAttackTime(WeaponAttackType(i), proto->Delay);
4585 else
4586 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4591 //skill+step, checking for max value
4592 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4594 if(!skill_id)
4595 return false;
4597 uint16 i=0;
4598 for (; i < PLAYER_MAX_SKILLS; i++)
4599 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4600 break;
4602 if(i>=PLAYER_MAX_SKILLS)
4603 return false;
4605 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4606 uint32 value = SKILL_VALUE(data);
4607 uint32 max = SKILL_MAX(data);
4609 if ((!max) || (!value) || (value >= max))
4610 return false;
4612 if (value*512 < max*urand(0,512))
4614 uint32 new_value = value+step;
4615 if(new_value > max)
4616 new_value = max;
4618 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4619 return true;
4622 return false;
4625 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4627 if ( SkillValue >= GrayLevel )
4628 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4629 if ( SkillValue >= GreenLevel )
4630 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4631 if ( SkillValue >= YellowLevel )
4632 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4633 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4636 bool Player::UpdateCraftSkill(uint32 spellid)
4638 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4640 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4641 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4643 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4645 if(_spell_idx->second->skillId)
4647 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4649 // Alchemy Discoveries here
4650 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4651 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4653 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4654 learnSpell(discoveredSpell);
4657 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4659 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4660 _spell_idx->second->max_value,
4661 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4662 _spell_idx->second->min_value),
4663 craft_skill_gain);
4666 return false;
4669 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4671 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4673 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4675 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4676 switch (SkillId)
4678 case SKILL_HERBALISM:
4679 case SKILL_LOCKPICKING:
4680 case SKILL_JEWELCRAFTING:
4681 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4682 case SKILL_SKINNING:
4683 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4684 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4685 else
4686 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4687 case SKILL_MINING:
4688 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4689 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4690 else
4691 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4693 return false;
4696 bool Player::UpdateFishingSkill()
4698 sLog.outDebug("UpdateFishingSkill");
4700 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4702 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4704 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4706 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4709 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4711 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4712 if ( !SkillId )
4713 return false;
4715 if(Chance <= 0) // speedup in 0 chance case
4717 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4718 return false;
4721 uint16 i=0;
4722 for (; i < PLAYER_MAX_SKILLS; i++)
4723 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4724 if ( i >= PLAYER_MAX_SKILLS )
4725 return false;
4727 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4728 uint16 SkillValue = SKILL_VALUE(data);
4729 uint16 MaxValue = SKILL_MAX(data);
4731 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4732 return false;
4734 int32 Roll = irand(1,1000);
4736 if ( Roll <= Chance )
4738 uint32 new_value = SkillValue+step;
4739 if(new_value > MaxValue)
4740 new_value = MaxValue;
4742 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4743 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4744 return true;
4747 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4748 return false;
4751 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4753 // no skill gain in pvp
4754 Unit *pVictim = getVictim();
4755 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4756 return;
4758 if(IsInFeralForm())
4759 return; // always maximized SKILL_FERAL_COMBAT in fact
4761 if(m_form == FORM_TREE)
4762 return; // use weapon but not skill up
4764 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4766 switch(attType)
4768 case BASE_ATTACK:
4770 Item *tmpitem = GetWeaponForAttack(attType,true);
4772 if (!tmpitem)
4773 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4774 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4775 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4776 break;
4778 case OFF_ATTACK:
4779 case RANGED_ATTACK:
4781 Item *tmpitem = GetWeaponForAttack(attType,true);
4782 if (tmpitem)
4783 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4784 break;
4787 UpdateAllCritPercentages();
4790 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4792 switch(outcome)
4794 case MELEE_HIT_CRIT:
4795 case MELEE_HIT_DODGE:
4796 case MELEE_HIT_PARRY:
4797 case MELEE_HIT_BLOCK:
4798 case MELEE_HIT_BLOCK_CRIT:
4799 return;
4801 default:
4802 break;
4805 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4806 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4807 uint32 moblevel = pVictim->getLevelForTarget(this);
4808 if(moblevel < greylevel)
4809 return;
4811 if (moblevel > plevel + 5)
4812 moblevel = plevel + 5;
4814 uint32 lvldif = moblevel - greylevel;
4815 if(lvldif < 3)
4816 lvldif = 3;
4818 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4819 if(skilldif <= 0)
4820 return;
4822 float chance = float(3 * lvldif * skilldif) / plevel;
4823 if(!defence)
4825 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4826 chance *= 0.1f * GetStat(STAT_INTELLECT);
4829 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4831 if(roll_chance_f(chance))
4833 if(defence)
4834 UpdateDefense();
4835 else
4836 UpdateWeaponSkill(attType);
4838 else
4839 return;
4842 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4844 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4845 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4847 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4848 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4849 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4851 if(talent) // permanent bonus stored in high part
4852 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4853 else // temporary/item bonus stored in low part
4854 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4855 return;
4859 void Player::UpdateSkillsForLevel()
4861 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4862 uint32 maxSkill = GetMaxSkillValueForLevel();
4864 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
4866 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4867 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4869 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4871 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4872 if(!pSkill)
4873 continue;
4875 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4876 continue;
4878 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4879 uint32 max = SKILL_MAX(data);
4880 uint32 val = SKILL_VALUE(data);
4882 /// update only level dependent max skill values
4883 if(max!=1)
4885 /// miximize skill always
4886 if(alwaysMaxSkill)
4887 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
4888 /// update max skill value if current max skill not maximized
4889 else if(max != maxconfskill)
4890 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
4895 void Player::UpdateSkillsToMaxSkillsForLevel()
4897 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4898 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4900 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4901 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4902 continue;
4903 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4905 uint32 max = SKILL_MAX(data);
4907 if(max > 1)
4908 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4910 if(pskill == SKILL_DEFENSE)
4911 UpdateDefenseBonusesMod();
4915 // This functions sets a skill line value (and adds if doesn't exist yet)
4916 // To "remove" a skill line, set it's values to zero
4917 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4919 if(!id)
4920 return;
4922 uint16 i=0;
4923 for (; i < PLAYER_MAX_SKILLS; i++)
4924 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4926 if(i<PLAYER_MAX_SKILLS) //has skill
4928 if(currVal)
4929 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4930 else //remove
4932 // clear skill fields
4933 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4934 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4935 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4937 // remove spells that depend on this skill when removing the skill
4938 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4940 ++next;
4941 if(itr->second->state == PLAYERSPELL_REMOVED)
4942 continue;
4944 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4945 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4947 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4949 if (_spell_idx->second->skillId == id)
4951 // this may remove more than one spell (dependents)
4952 removeSpell(itr->first);
4953 next = m_spells.begin();
4954 break;
4960 else if(currVal) //add
4962 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4963 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4965 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4966 if(!pSkill)
4968 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4969 return;
4971 // enable unlearn button for primary professions only
4972 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4973 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4974 else
4975 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4976 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4978 // apply skill bonuses
4979 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4981 // temporary bonuses
4982 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4983 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4984 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4985 (*i)->ApplyModifier(true);
4987 // permanent bonuses
4988 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4989 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4990 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4991 (*i)->ApplyModifier(true);
4993 // Learn all spells for skill
4994 learnSkillRewardedSpells(id);
4995 return;
5000 bool Player::HasSkill(uint32 skill) const
5002 if(!skill)return false;
5003 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5005 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5007 return true;
5010 return false;
5013 uint16 Player::GetSkillValue(uint32 skill) const
5015 if(!skill)
5016 return 0;
5018 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5020 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5022 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5024 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5025 result += SKILL_TEMP_BONUS(bonus);
5026 result += SKILL_PERM_BONUS(bonus);
5027 return result < 0 ? 0 : result;
5030 return 0;
5033 uint16 Player::GetMaxSkillValue(uint32 skill) const
5035 if(!skill)return 0;
5036 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5038 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5040 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5042 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5043 result += SKILL_TEMP_BONUS(bonus);
5044 result += SKILL_PERM_BONUS(bonus);
5045 return result < 0 ? 0 : result;
5048 return 0;
5051 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5053 if(!skill)return 0;
5054 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5056 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5058 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5061 return 0;
5064 uint16 Player::GetBaseSkillValue(uint32 skill) const
5066 if(!skill)return 0;
5067 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5069 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5071 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5072 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5073 return result < 0 ? 0 : result;
5076 return 0;
5079 uint16 Player::GetPureSkillValue(uint32 skill) const
5081 if(!skill)return 0;
5082 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5084 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5086 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5089 return 0;
5092 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5094 if(!skill)
5095 return 0;
5097 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5099 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5101 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5105 return 0;
5108 void Player::SendInitialActionButtons()
5110 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5112 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5113 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5115 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5116 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5118 data << uint16(itr->second.action);
5119 data << uint8(itr->second.misc);
5120 data << uint8(itr->second.type);
5122 else
5124 data << uint32(0);
5128 GetSession()->SendPacket( &data );
5129 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5132 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5134 if(button >= MAX_ACTION_BUTTONS)
5136 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5137 return;
5140 // check cheating with adding non-known spells to action bar
5141 if(type==ACTION_BUTTON_SPELL)
5143 if(!sSpellStore.LookupEntry(action))
5145 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5146 return;
5149 if(!HasSpell(action))
5151 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5152 return;
5156 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5158 if (buttonItr==m_actionButtons.end())
5159 { // just add new button
5160 m_actionButtons[button] = ActionButton(action,type,misc);
5162 else
5163 { // change state of current button
5164 ActionButtonUpdateState uState = buttonItr->second.uState;
5165 buttonItr->second = ActionButton(action,type,misc);
5166 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5169 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5172 void Player::removeActionButton(uint8 button)
5174 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5175 if (buttonItr==m_actionButtons.end())
5176 return;
5178 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5179 m_actionButtons.erase(buttonItr); // new and not saved
5180 else
5181 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5183 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5186 void Player::SetDontMove(bool dontMove)
5188 m_dontMove = dontMove;
5191 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5193 // prevent crash when a bad coord is sent by the client
5194 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5196 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5197 return false;
5200 Map *m = GetMap();
5202 const float old_x = GetPositionX();
5203 const float old_y = GetPositionY();
5204 const float old_z = GetPositionZ();
5205 const float old_r = GetOrientation();
5207 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5209 if (teleport || old_x != x || old_y != y || old_z != z)
5210 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5211 else
5212 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5214 // move and update visible state if need
5215 m->PlayerRelocation(this, x, y, z, orientation);
5217 // reread after Map::Relocation
5218 m = GetMap();
5219 x = GetPositionX();
5220 y = GetPositionY();
5221 z = GetPositionZ();
5223 // group update
5224 if(GetGroup() && (old_x != x || old_y != y))
5225 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5228 // code block for underwater state update
5229 UpdateUnderwaterState(m, x, y, z);
5231 CheckExploreSystem();
5233 return true;
5236 void Player::SaveRecallPosition()
5238 m_recallMap = GetMapId();
5239 m_recallX = GetPositionX();
5240 m_recallY = GetPositionY();
5241 m_recallZ = GetPositionZ();
5242 m_recallO = GetOrientation();
5245 void Player::SendMessageToSet(WorldPacket *data, bool self)
5247 GetMap()->MessageBroadcast(this, data, self);
5250 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5252 GetMap()->MessageDistBroadcast(this, data, dist, self);
5255 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5257 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5260 void Player::SendDirectMessage(WorldPacket *data)
5262 GetSession()->SendPacket(data);
5265 void Player::CheckExploreSystem()
5267 if (!isAlive())
5268 return;
5270 if (isInFlight())
5271 return;
5273 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5274 if(areaFlag==0xffff)
5275 return;
5276 int offset = areaFlag / 32;
5278 if(offset >= 128)
5280 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);
5281 return;
5284 uint32 val = (uint32)(1 << (areaFlag % 32));
5285 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5287 if( !(currFields & val) )
5289 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5291 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5292 if(!p)
5294 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5296 else if(p->area_level > 0)
5298 uint32 area = p->ID;
5299 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5301 SendExplorationExperience(area,0);
5303 else
5305 int32 diff = int32(getLevel()) - p->area_level;
5306 uint32 XP = 0;
5307 if (diff < -5)
5309 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5311 else if (diff > 5)
5313 int32 exploration_percent = (100-((diff-5)*5));
5314 if (exploration_percent > 100)
5315 exploration_percent = 100;
5316 else if (exploration_percent < 0)
5317 exploration_percent = 0;
5319 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5321 else
5323 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5326 GiveXP( XP, NULL );
5327 SendExplorationExperience(area,XP);
5329 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5334 uint32 Player::TeamForRace(uint8 race)
5336 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5337 if(!rEntry)
5339 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5340 return ALLIANCE;
5343 switch(rEntry->TeamID)
5345 case 7: return ALLIANCE;
5346 case 1: return HORDE;
5349 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5350 return ALLIANCE;
5353 uint32 Player::getFactionForRace(uint8 race)
5355 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5356 if(!rEntry)
5358 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5359 return 0;
5362 return rEntry->FactionID;
5365 void Player::setFactionForRace(uint8 race)
5367 m_team = TeamForRace(race);
5368 setFaction( getFactionForRace(race) );
5371 void Player::UpdateReputation() const
5373 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5375 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5377 SendFactionState(&(itr->second));
5381 void Player::SendFactionState(FactionState const* faction) const
5383 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5385 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5386 data << (float) 0; // unk 2.4.0
5387 data << (uint32) 1; // count
5388 // for
5389 data << (uint32) faction->ReputationListID;
5390 data << (uint32) faction->Standing;
5391 // end for
5392 GetSession()->SendPacket(&data);
5396 void Player::SendInitialReputations()
5398 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5399 data << uint32 (0x00000080);
5401 RepListID a = 0;
5403 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5405 // fill in absent fields
5406 for (; a != itr->first; a++)
5408 data << uint8 (0x00);
5409 data << uint32 (0x00000000);
5412 // fill in encountered data
5413 data << uint8 (itr->second.Flags);
5414 data << uint32 (itr->second.Standing);
5416 ++a;
5419 // fill in absent fields
5420 for (; a != 128; a++)
5422 data << uint8 (0x00);
5423 data << uint32 (0x00000000);
5426 GetSession()->SendPacket(&data);
5429 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5431 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5432 if (itr != m_factions.end())
5433 return &itr->second;
5435 return NULL;
5438 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5440 // not allow declare war to own faction
5441 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5442 return;
5444 // already set
5445 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5446 return;
5448 if( atWar )
5449 faction->Flags |= FACTION_FLAG_AT_WAR;
5450 else
5451 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5453 faction->Changed = true;
5456 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5458 // always invisible or hidden faction can't be inactive
5459 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5460 return;
5462 // already set
5463 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5464 return;
5466 if(inactive)
5467 faction->Flags |= FACTION_FLAG_INACTIVE;
5468 else
5469 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5471 faction->Changed = true;
5474 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5476 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5478 if(!factionTemplateEntry)
5479 return;
5481 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5484 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5486 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5487 if(!factionEntry)
5488 return;
5490 if(factionEntry->reputationListID < 0)
5491 return;
5493 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5494 if (itr == m_factions.end())
5495 return;
5497 SetFactionVisible(&itr->second);
5500 void Player::SetFactionVisible(FactionState* faction)
5502 // always invisible or hidden faction can't be make visible
5503 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5504 return;
5506 // already set
5507 if(faction->Flags & FACTION_FLAG_VISIBLE)
5508 return;
5510 faction->Flags |= FACTION_FLAG_VISIBLE;
5511 faction->Changed = true;
5513 if(!m_session->PlayerLoading())
5515 // make faction visible in reputation list at client
5516 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5517 data << faction->ReputationListID;
5518 GetSession()->SendPacket(&data);
5522 void Player::SetInitialFactions()
5524 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5526 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5528 if( factionEntry && (factionEntry->reputationListID >= 0))
5530 FactionState newFaction;
5531 newFaction.ID = factionEntry->ID;
5532 newFaction.ReputationListID = factionEntry->reputationListID;
5533 newFaction.Standing = 0;
5534 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5535 newFaction.Changed = true;
5537 m_factions[newFaction.ReputationListID] = newFaction;
5542 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5544 if (!factionEntry)
5545 return 0;
5547 uint32 raceMask = getRaceMask();
5548 uint32 classMask = getClassMask();
5549 for (int i=0; i < 4; i++)
5551 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5552 (factionEntry->BaseRepClassMask[i]==0 ||
5553 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5554 return factionEntry->ReputationFlags[i];
5556 return 0;
5559 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5561 if (!factionEntry)
5562 return 0;
5564 uint32 raceMask = getRaceMask();
5565 uint32 classMask = getClassMask();
5566 for (int i=0; i < 4; i++)
5568 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5569 (factionEntry->BaseRepClassMask[i]==0 ||
5570 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5571 return factionEntry->BaseRepValue[i];
5574 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5575 return 0;
5578 int32 Player::GetReputation(uint32 faction_id) const
5580 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5582 if (!factionEntry)
5584 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5585 return 0;
5588 return GetReputation(factionEntry);
5591 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5593 // Faction without recorded reputation. Just ignore.
5594 if(!factionEntry)
5595 return 0;
5597 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5598 if (itr != m_factions.end())
5599 return GetBaseReputation(factionEntry) + itr->second.Standing;
5601 return 0;
5604 ReputationRank Player::GetReputationRank(uint32 faction) const
5606 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5607 if(!factionEntry)
5608 return MIN_REPUTATION_RANK;
5610 return GetReputationRank(factionEntry);
5613 ReputationRank Player::ReputationToRank(int32 standing) const
5615 int32 Limit = Reputation_Cap + 1;
5616 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5618 Limit -= ReputationRank_Length[i];
5619 if (standing >= Limit )
5620 return ReputationRank(i);
5622 return MIN_REPUTATION_RANK;
5625 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5627 int32 Reputation = GetReputation(factionEntry);
5628 return ReputationToRank(Reputation);
5631 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5633 int32 Reputation = GetBaseReputation(factionEntry);
5634 return ReputationToRank(Reputation);
5637 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5639 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5641 if(!factionTemplateEntry)
5643 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5644 return false;
5647 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5649 // Faction without recorded reputation. Just ignore.
5650 if(!factionEntry)
5651 return false;
5653 return ModifyFactionReputation(factionEntry, DeltaReputation);
5656 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5658 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5659 if (flist)
5661 bool res = false;
5662 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5664 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5665 if(factionEntryCalc)
5666 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5668 return res;
5670 else
5671 return ModifyOneFactionReputation(factionEntry, standing);
5674 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5676 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5677 if (itr != m_factions.end())
5679 int32 BaseRep = GetBaseReputation(factionEntry);
5680 int32 new_rep = BaseRep + itr->second.Standing + standing;
5682 if (new_rep > Reputation_Cap)
5683 new_rep = Reputation_Cap;
5684 else
5685 if (new_rep < Reputation_Bottom)
5686 new_rep = Reputation_Bottom;
5688 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5689 SetFactionAtWar(&itr->second,true);
5691 itr->second.Standing = new_rep - BaseRep;
5692 itr->second.Changed = true;
5694 SetFactionVisible(&itr->second);
5696 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5698 if(uint32 questid = GetQuestSlotQuestId(i))
5700 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5701 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5703 QuestStatusData& q_status = mQuestStatus[questid];
5704 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5706 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5707 if ( CanCompleteQuest( questid ) )
5708 CompleteQuest( questid );
5710 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5712 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5713 IncompleteQuest( questid );
5719 SendFactionState(&(itr->second));
5721 return true;
5723 return false;
5726 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5728 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5730 if(!factionTemplateEntry)
5732 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5733 return false;
5736 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5738 // Faction without recorded reputation. Just ignore.
5739 if(!factionEntry)
5740 return false;
5742 return SetFactionReputation(factionEntry, standing);
5745 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5747 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5748 if (flist)
5750 bool res = false;
5751 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5753 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5754 if(factionEntryCalc)
5755 res = SetOneFactionReputation(factionEntryCalc, standing);
5757 return res;
5759 else
5760 return SetOneFactionReputation(factionEntry, standing);
5763 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5765 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5766 if (itr != m_factions.end())
5768 if (standing > Reputation_Cap)
5769 standing = Reputation_Cap;
5770 else
5771 if (standing < Reputation_Bottom)
5772 standing = Reputation_Bottom;
5774 int32 BaseRep = GetBaseReputation(factionEntry);
5775 itr->second.Standing = standing - BaseRep;
5776 itr->second.Changed = true;
5778 SetFactionVisible(&itr->second);
5780 if(ReputationToRank(standing) <= REP_HOSTILE)
5781 SetFactionAtWar(&itr->second,true);
5783 SendFactionState(&(itr->second));
5784 return true;
5786 return false;
5789 //Calculate total reputation percent player gain with quest/creature level
5790 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5792 // for grey creature kill received 20%, in other case 100.
5793 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5795 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5797 percent += rep > 0 ? repMod : -repMod;
5799 if(percent <=0)
5800 return 0;
5802 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5805 //Calculates how many reputation points player gains in victim's enemy factions
5806 void Player::RewardReputation(Unit *pVictim, float rate)
5808 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5809 return;
5811 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5813 if(!Rep)
5814 return;
5816 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5818 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5819 donerep1 = int32(donerep1*rate);
5820 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5821 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5822 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5823 ModifyFactionReputation(factionEntry1, donerep1);
5825 // Wiki: Team factions value divided by 2
5826 if(Rep->is_teamaward1)
5828 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5829 if(team1_factionEntry)
5830 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5834 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5836 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5837 donerep2 = int32(donerep2*rate);
5838 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5839 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5840 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5841 ModifyFactionReputation(factionEntry2, donerep2);
5843 // Wiki: Team factions value divided by 2
5844 if(Rep->is_teamaward2)
5846 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5847 if(team2_factionEntry)
5848 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5853 //Calculate how many reputation points player gain with the quest
5854 void Player::RewardReputation(Quest const *pQuest)
5856 // quest reputation reward/loss
5857 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5859 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5861 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5862 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5863 if(factionEntry)
5864 ModifyFactionReputation(factionEntry, rep);
5868 // TODO: implement reputation spillover
5871 void Player::UpdateArenaFields(void)
5873 /* arena calcs go here */
5876 void Player::UpdateHonorFields()
5878 /// called when rewarding honor and at each save
5879 uint64 now = time(NULL);
5880 uint64 today = uint64(time(NULL) / DAY) * DAY;
5882 if(m_lastHonorUpdateTime < today)
5884 uint64 yesterday = today - DAY;
5886 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5888 // update yesterday's contribution
5889 if(m_lastHonorUpdateTime >= yesterday )
5891 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5893 // this is the first update today, reset today's contribution
5894 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5895 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5897 else
5899 // no honor/kills yesterday or today, reset
5900 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5901 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5905 m_lastHonorUpdateTime = now;
5908 ///Calculate the amount of honor gained based on the victim
5909 ///and the size of the group for which the honor is divided
5910 ///An exact honor value can also be given (overriding the calcs)
5911 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5913 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5914 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5915 return false;
5917 uint64 victim_guid = 0;
5918 uint32 victim_rank = 0;
5920 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5921 UpdateHonorFields();
5923 if(honor <= 0)
5925 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5926 return false;
5928 victim_guid = uVictim->GetGUID();
5930 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5932 Player *pVictim = (Player *)uVictim;
5934 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5935 return false;
5937 float f = 1; //need for total kills (?? need more info)
5938 uint32 k_grey = 0;
5939 uint32 k_level = getLevel();
5940 uint32 v_level = pVictim->getLevel();
5943 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5944 // [0] Just name
5945 // [1..14] Alliance honor titles and player name
5946 // [15..28] Horde honor titles and player name
5947 // [29..38] Other title and player name
5948 // [39+] Nothing
5949 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5950 // Get Killer titles, CharTitlesEntry::bit_index
5951 // Ranks:
5952 // title[1..14] -> rank[5..18]
5953 // title[15..28] -> rank[5..18]
5954 // title[other] -> 0
5955 if (victim_title == 0)
5956 victim_guid = 0; // Don't show HK: <rank> message, only log.
5957 else if (victim_title < 15)
5958 victim_rank = victim_title + 4;
5959 else if (victim_title < 29)
5960 victim_rank = victim_title - 14 + 4;
5961 else
5962 victim_guid = 0; // Don't show HK: <rank> message, only log.
5965 if(k_level <= 5)
5966 k_grey = 0;
5967 else if( k_level <= 39 )
5968 k_grey = k_level - 5 - k_level/10;
5969 else
5970 k_grey = k_level - 1 - k_level/5;
5972 if(v_level<=k_grey)
5973 return false;
5975 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5977 int32 v_rank =1; //need more info
5979 honor = ((f * diff_level * (190 + v_rank*10))/6);
5980 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5982 // count the number of playerkills in one day
5983 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5984 // and those in a lifetime
5985 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5987 else
5989 Creature *cVictim = (Creature *)uVictim;
5991 if (!cVictim->isRacialLeader())
5992 return false;
5994 honor = 100; // ??? need more info
5995 victim_rank = 19; // HK: Leader
5999 if (uVictim != NULL)
6001 honor *= sWorld.getRate(RATE_HONOR);
6003 if(groupsize > 1)
6004 honor /= groupsize;
6006 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6009 // honor - for show honor points in log
6010 // victim_guid - for show victim name in log
6011 // victim_rank [1..4] HK: <dishonored rank>
6012 // victim_rank [5..19] HK: <alliance\horde rank>
6013 // victim_rank [0,20+] HK: <>
6014 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6015 data << (uint32) honor;
6016 data << (uint64) victim_guid;
6017 data << (uint32) victim_rank;
6019 GetSession()->SendPacket(&data);
6021 // add honor points
6022 ModifyHonorPoints(int32(honor));
6024 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6025 return true;
6028 void Player::ModifyHonorPoints( int32 value )
6030 if(value < 0)
6032 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6033 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6034 else
6035 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6037 else
6038 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6041 void Player::ModifyArenaPoints( int32 value )
6043 if(value < 0)
6045 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6046 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6047 else
6048 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6050 else
6051 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6054 uint32 Player::GetGuildIdFromDB(uint64 guid)
6056 std::ostringstream ss;
6057 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
6058 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6059 if( result )
6061 uint32 v = result->Fetch()[0].GetUInt32();
6062 delete result;
6063 return v;
6065 else
6066 return 0;
6069 uint32 Player::GetRankFromDB(uint64 guid)
6071 std::ostringstream ss;
6072 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6073 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6074 if( result )
6076 uint32 v = result->Fetch()[0].GetUInt32();
6077 delete result;
6078 return v;
6080 else
6081 return 0;
6084 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6086 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);
6087 if(!result)
6088 return 0;
6090 uint32 id = (*result)[0].GetUInt32();
6091 delete result;
6092 return id;
6095 uint32 Player::GetZoneIdFromDB(uint64 guid)
6097 std::ostringstream ss;
6099 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6100 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6101 if (!result)
6102 return 0;
6103 Field* fields = result->Fetch();
6104 uint32 zone = fields[0].GetUInt32();
6105 delete result;
6107 if (!zone)
6109 // stored zone is zero, use generic and slow zone detection
6110 ss.str("");
6111 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6112 result = CharacterDatabase.Query(ss.str().c_str());
6113 if( !result )
6114 return 0;
6115 fields = result->Fetch();
6116 uint32 map = fields[0].GetUInt32();
6117 float posx = fields[1].GetFloat();
6118 float posy = fields[2].GetFloat();
6119 delete result;
6121 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6123 ss.str("");
6124 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6125 CharacterDatabase.Execute(ss.str().c_str());
6128 return zone;
6131 void Player::UpdateArea(uint32 newArea)
6133 // FFA_PVP flags are area and not zone id dependent
6134 // so apply them accordingly
6135 m_areaUpdateId = newArea;
6137 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6139 if(area && (area->flags & AREA_FLAG_ARENA))
6141 if(!isGameMaster())
6142 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6144 else
6146 // remove ffa flag only if not ffapvp realm
6147 // removal in sanctuaries and capitals is handled in zone update
6148 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6149 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6152 UpdateAreaDependentAuras(newArea);
6155 void Player::UpdateZone(uint32 newZone)
6157 m_zoneUpdateId = newZone;
6158 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6160 // zone changed, so area changed as well, update it
6161 UpdateArea(GetAreaId());
6163 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6164 if(!zone)
6165 return;
6167 if (sWorld.getConfig(CONFIG_WEATHER))
6169 Weather *wth = sWorld.FindWeather(zone->ID);
6170 if(wth)
6172 wth->SendWeatherUpdateToPlayer(this);
6174 else
6176 if(!sWorld.AddWeather(zone->ID))
6178 // send fine weather packet to remove old zone's weather
6179 Weather::SendFineWeatherUpdateToPlayer(this);
6184 pvpInfo.inHostileArea =
6185 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6186 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6187 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6188 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6190 if(pvpInfo.inHostileArea) // in hostile area
6192 if(!IsPvP() || pvpInfo.endTimer != 0)
6193 UpdatePvP(true, true);
6195 else // in friendly area
6197 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6198 pvpInfo.endTimer = time(0); // start toggle-off
6201 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6203 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6204 if(sWorld.IsFFAPvPRealm())
6205 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6207 else
6209 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6212 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6214 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6215 SetRestType(REST_TYPE_IN_CITY);
6216 InnEnter(time(0),GetMapId(),0,0,0);
6218 if(sWorld.IsFFAPvPRealm())
6219 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6221 else // anywhere else
6223 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6225 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6227 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6229 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6230 SetRestType(REST_TYPE_NO);
6232 if(sWorld.IsFFAPvPRealm())
6233 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6236 else // not in tavern (leave city then)
6238 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6239 SetRestType(REST_TYPE_NO);
6241 // Set player to FFA PVP when not in rested environment.
6242 if(sWorld.IsFFAPvPRealm())
6243 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6248 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6249 // if player resurrected at teleport this will be applied in resurrect code
6250 if(isAlive())
6251 DestroyZoneLimitedItem( true, newZone );
6253 // recent client version not send leave/join channel packets for built-in local channels
6254 UpdateLocalChannels( newZone );
6256 // group update
6257 if(GetGroup())
6258 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6260 UpdateZoneDependentAuras(newZone);
6263 //If players are too far way of duel flag... then player loose the duel
6264 void Player::CheckDuelDistance(time_t currTime)
6266 if(!duel)
6267 return;
6269 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6270 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6271 if(!obj)
6272 return;
6274 if(duel->outOfBound == 0)
6276 if(!IsWithinDistInMap(obj, 50))
6278 duel->outOfBound = currTime;
6280 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6281 GetSession()->SendPacket(&data);
6284 else
6286 if(IsWithinDistInMap(obj, 40))
6288 duel->outOfBound = 0;
6290 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6291 GetSession()->SendPacket(&data);
6293 else if(currTime >= (duel->outOfBound+10))
6295 DuelComplete(DUEL_FLED);
6300 void Player::DuelComplete(DuelCompleteType type)
6302 // duel not requested
6303 if(!duel)
6304 return;
6306 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6307 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6308 GetSession()->SendPacket(&data);
6309 duel->opponent->GetSession()->SendPacket(&data);
6311 if(type != DUEL_INTERUPTED)
6313 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6314 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6315 data << duel->opponent->GetName();
6316 data << GetName();
6317 SendMessageToSet(&data,true);
6320 // cool-down duel spell
6321 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6323 data<<GetGUID();
6324 data<<uint8(0x0);
6326 data<<(uint32)7266;
6327 data<<uint32(0x0);
6328 GetSession()->SendPacket(&data);
6329 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6330 data<<duel->opponent->GetGUID();
6331 data<<uint8(0x0);
6332 data<<(uint32)7266;
6333 data<<uint32(0x0);
6334 duel->opponent->GetSession()->SendPacket(&data);*/
6336 //Remove Duel Flag object
6337 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6338 if(obj)
6339 duel->initiator->RemoveGameObject(obj,true);
6341 /* remove auras */
6342 std::vector<uint32> auras2remove;
6343 AuraMap const& vAuras = duel->opponent->GetAuras();
6344 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6346 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6347 auras2remove.push_back(i->second->GetId());
6350 for(size_t i=0; i<auras2remove.size(); i++)
6351 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6353 auras2remove.clear();
6354 AuraMap const& auras = GetAuras();
6355 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6357 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6358 auras2remove.push_back(i->second->GetId());
6360 for(size_t i=0; i<auras2remove.size(); i++)
6361 RemoveAurasDueToSpell(auras2remove[i]);
6363 // cleanup combo points
6364 if(GetComboTarget()==duel->opponent->GetGUID())
6365 ClearComboPoints();
6366 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6367 ClearComboPoints();
6369 if(duel->opponent->GetComboTarget()==GetGUID())
6370 duel->opponent->ClearComboPoints();
6371 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6372 duel->opponent->ClearComboPoints();
6374 //cleanups
6375 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6376 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6377 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6378 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6380 delete duel->opponent->duel;
6381 duel->opponent->duel = NULL;
6382 delete duel;
6383 duel = NULL;
6386 //---------------------------------------------------------//
6388 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6390 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6391 return;
6393 // not apply/remove mods for broken item
6394 if(item->IsBroken())
6395 return;
6397 ItemPrototype const *proto = item->GetProto();
6399 if(!proto)
6400 return;
6402 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6404 uint32 attacktype = Player::GetAttackBySlot(slot);
6405 if(attacktype < MAX_ATTACK)
6406 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6408 _ApplyItemBonuses(proto,slot,apply);
6410 if( slot==EQUIPMENT_SLOT_RANGED )
6411 _ApplyAmmoBonuses();
6413 ApplyItemEquipSpell(item,apply);
6414 ApplyEnchantment(item, apply);
6416 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6417 CorrectMetaGemEnchants(slot, apply);
6419 sLog.outDebug("_ApplyItemMods complete.");
6422 void Player::_ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply)
6424 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6425 return;
6427 for (int i = 0; i < 10; i++)
6429 float val = float (proto->ItemStat[i].ItemStatValue);
6431 if(val==0)
6432 continue;
6434 switch (proto->ItemStat[i].ItemStatType)
6436 case ITEM_MOD_MANA:
6437 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6438 break;
6439 case ITEM_MOD_HEALTH: // modify HP
6440 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6441 break;
6442 case ITEM_MOD_AGILITY: // modify agility
6443 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6444 ApplyStatBuffMod(STAT_AGILITY, val, apply);
6445 break;
6446 case ITEM_MOD_STRENGTH: //modify strength
6447 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6448 ApplyStatBuffMod(STAT_STRENGTH, val, apply);
6449 break;
6450 case ITEM_MOD_INTELLECT: //modify intellect
6451 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6452 ApplyStatBuffMod(STAT_INTELLECT, val, apply);
6453 break;
6454 case ITEM_MOD_SPIRIT: //modify spirit
6455 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6456 ApplyStatBuffMod(STAT_SPIRIT, val, apply);
6457 break;
6458 case ITEM_MOD_STAMINA: //modify stamina
6459 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6460 ApplyStatBuffMod(STAT_STAMINA, val, apply);
6461 break;
6462 case ITEM_MOD_DEFENSE_SKILL_RATING:
6463 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6464 break;
6465 case ITEM_MOD_DODGE_RATING:
6466 ApplyRatingMod(CR_DODGE, int32(val), apply);
6467 break;
6468 case ITEM_MOD_PARRY_RATING:
6469 ApplyRatingMod(CR_PARRY, int32(val), apply);
6470 break;
6471 case ITEM_MOD_BLOCK_RATING:
6472 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6473 break;
6474 case ITEM_MOD_HIT_MELEE_RATING:
6475 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6476 break;
6477 case ITEM_MOD_HIT_RANGED_RATING:
6478 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6479 break;
6480 case ITEM_MOD_HIT_SPELL_RATING:
6481 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6482 break;
6483 case ITEM_MOD_CRIT_MELEE_RATING:
6484 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6485 break;
6486 case ITEM_MOD_CRIT_RANGED_RATING:
6487 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6488 break;
6489 case ITEM_MOD_CRIT_SPELL_RATING:
6490 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6491 break;
6492 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6493 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6494 break;
6495 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6496 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6497 break;
6498 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6499 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6500 break;
6501 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6502 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6503 break;
6504 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6505 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6506 break;
6507 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6508 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6509 break;
6510 case ITEM_MOD_HASTE_MELEE_RATING:
6511 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6512 break;
6513 case ITEM_MOD_HASTE_RANGED_RATING:
6514 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6515 break;
6516 case ITEM_MOD_HASTE_SPELL_RATING:
6517 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6518 break;
6519 case ITEM_MOD_HIT_RATING:
6520 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6521 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6522 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6523 break;
6524 case ITEM_MOD_CRIT_RATING:
6525 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6526 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6527 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6528 break;
6529 case ITEM_MOD_HIT_TAKEN_RATING:
6530 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6531 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6532 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6533 break;
6534 case ITEM_MOD_CRIT_TAKEN_RATING:
6535 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6536 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6537 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6538 break;
6539 case ITEM_MOD_RESILIENCE_RATING:
6540 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6541 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6542 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6543 break;
6544 case ITEM_MOD_HASTE_RATING:
6545 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6546 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6547 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6548 break;
6549 case ITEM_MOD_EXPERTISE_RATING:
6550 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6551 break;
6555 if (proto->Armor)
6556 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6558 if (proto->Block)
6559 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6561 if (proto->HolyRes)
6562 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6564 if (proto->FireRes)
6565 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6567 if (proto->NatureRes)
6568 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6570 if (proto->FrostRes)
6571 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6573 if (proto->ShadowRes)
6574 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6576 if (proto->ArcaneRes)
6577 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6579 WeaponAttackType attType = BASE_ATTACK;
6580 float damage = 0.0f;
6582 if( slot == EQUIPMENT_SLOT_RANGED && (
6583 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6584 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6586 attType = RANGED_ATTACK;
6588 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6590 attType = OFF_ATTACK;
6593 if (proto->Damage[0].DamageMin > 0 )
6595 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6596 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6597 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6600 if (proto->Damage[0].DamageMax > 0 )
6602 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6603 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6606 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6607 return;
6609 if (proto->Delay)
6611 if(slot == EQUIPMENT_SLOT_RANGED)
6612 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6613 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6614 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6615 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6616 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6619 if(CanModifyStats() && (damage || proto->Delay))
6620 UpdateDamagePhysical(attType);
6623 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6625 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6626 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6627 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6629 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6630 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6631 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6633 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6634 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6635 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6638 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6640 // generic not weapon specific case processes in aura code
6641 if(aura->GetSpellProto()->EquippedItemClass == -1)
6642 return;
6644 BaseModGroup mod = BASEMOD_END;
6645 switch(attackType)
6647 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6648 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6649 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6650 default: return;
6653 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6655 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6659 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6661 // ignore spell mods for not wands
6662 Modifier const* modifier = aura->GetModifier();
6663 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6664 return;
6666 // generic not weapon specific case processes in aura code
6667 if(aura->GetSpellProto()->EquippedItemClass == -1)
6668 return;
6670 UnitMods unitMod = UNIT_MOD_END;
6671 switch(attackType)
6673 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6674 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6675 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6676 default: return;
6679 UnitModifierType unitModType = TOTAL_VALUE;
6680 switch(modifier->m_auraname)
6682 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6683 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6684 default: return;
6687 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6689 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6693 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6695 if(!item)
6696 return;
6698 ItemPrototype const *proto = item->GetProto();
6699 if(!proto)
6700 return;
6702 for (int i = 0; i < 5; i++)
6704 _Spell const& spellData = proto->Spells[i];
6706 // no spell
6707 if(!spellData.SpellId )
6708 continue;
6710 // wrong triggering type
6711 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6712 continue;
6714 // check if it is valid spell
6715 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6716 if(!spellproto)
6717 continue;
6719 ApplyEquipSpell(spellproto,item,apply,form_change);
6723 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6725 if(apply)
6727 // Cannot be used in this stance/form
6728 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6729 return;
6731 if(form_change) // check aura active state from other form
6733 bool found = false;
6734 for (int k=0; k < 3; ++k)
6736 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6737 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6739 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6741 found = true;
6742 break;
6745 if(found)
6746 break;
6749 if(found) // and skip re-cast already active aura at form change
6750 return;
6753 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6755 CastSpell(this,spellInfo,true,item);
6757 else
6759 if(form_change) // check aura compatibility
6761 // Cannot be used in this stance/form
6762 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6763 return; // and remove only not compatible at form change
6766 if(item)
6767 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6768 else
6769 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6773 void Player::UpdateEquipSpellsAtFormChange()
6775 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6777 if(m_items[i] && !m_items[i]->IsBroken())
6779 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6780 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6784 // item set bonuses not dependent from item broken state
6785 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6787 ItemSetEffect* eff = ItemSetEff[setindex];
6788 if(!eff)
6789 continue;
6791 for(uint32 y=0;y<8; ++y)
6793 SpellEntry const* spellInfo = eff->spells[y];
6794 if(!spellInfo)
6795 continue;
6797 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6798 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6803 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6805 if(!item || item->IsBroken())
6806 return;
6808 ItemPrototype const *proto = item->GetProto();
6809 if(!proto)
6810 return;
6812 if (!Target || Target == this )
6813 return;
6815 for (int i = 0; i < 5; i++)
6817 _Spell const& spellData = proto->Spells[i];
6819 // no spell
6820 if(!spellData.SpellId )
6821 continue;
6823 // wrong triggering type
6824 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6825 continue;
6827 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6828 if(!spellInfo)
6830 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6831 continue;
6834 // not allow proc extra attack spell at extra attack
6835 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6836 return;
6838 float chance = spellInfo->procChance;
6840 if(spellData.SpellPPMRate)
6842 uint32 WeaponSpeed = GetAttackTime(attType);
6843 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6845 else if(chance > 100.0f)
6847 chance = GetWeaponProcChance();
6850 if (roll_chance_f(chance))
6851 CastSpell(Target, spellInfo->Id, true, item);
6854 // item combat enchantments
6855 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6857 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6858 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6859 if(!pEnchant) continue;
6860 for (int s=0;s<3;s++)
6862 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6863 continue;
6865 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6866 if (!spellInfo)
6868 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6869 continue;
6872 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6873 if (roll_chance_f(chance))
6875 if(IsPositiveSpell(pEnchant->spellid[s]))
6876 CastSpell(this, pEnchant->spellid[s], true, item);
6877 else
6878 CastSpell(Target, pEnchant->spellid[s], true, item);
6884 void Player::_RemoveAllItemMods()
6886 sLog.outDebug("_RemoveAllItemMods start.");
6888 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6890 if(m_items[i])
6892 ItemPrototype const *proto = m_items[i]->GetProto();
6893 if(!proto)
6894 continue;
6896 // item set bonuses not dependent from item broken state
6897 if(proto->ItemSet)
6898 RemoveItemsSetItem(this,proto);
6900 if(m_items[i]->IsBroken())
6901 continue;
6903 ApplyItemEquipSpell(m_items[i],false);
6904 ApplyEnchantment(m_items[i], false);
6908 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6910 if(m_items[i])
6912 if(m_items[i]->IsBroken())
6913 continue;
6914 ItemPrototype const *proto = m_items[i]->GetProto();
6915 if(!proto)
6916 continue;
6918 uint32 attacktype = Player::GetAttackBySlot(i);
6919 if(attacktype < MAX_ATTACK)
6920 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6922 _ApplyItemBonuses(proto,i, false);
6924 if( i == EQUIPMENT_SLOT_RANGED )
6925 _ApplyAmmoBonuses();
6929 sLog.outDebug("_RemoveAllItemMods complete.");
6932 void Player::_ApplyAllItemMods()
6934 sLog.outDebug("_ApplyAllItemMods start.");
6936 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6938 if(m_items[i])
6940 if(m_items[i]->IsBroken())
6941 continue;
6943 ItemPrototype const *proto = m_items[i]->GetProto();
6944 if(!proto)
6945 continue;
6947 uint32 attacktype = Player::GetAttackBySlot(i);
6948 if(attacktype < MAX_ATTACK)
6949 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6951 _ApplyItemBonuses(proto,i, true);
6953 if( i == EQUIPMENT_SLOT_RANGED )
6954 _ApplyAmmoBonuses();
6958 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6960 if(m_items[i])
6962 ItemPrototype const *proto = m_items[i]->GetProto();
6963 if(!proto)
6964 continue;
6966 // item set bonuses not dependent from item broken state
6967 if(proto->ItemSet)
6968 AddItemsSetItem(this,m_items[i]);
6970 if(m_items[i]->IsBroken())
6971 continue;
6973 ApplyItemEquipSpell(m_items[i],true);
6974 ApplyEnchantment(m_items[i], true);
6978 sLog.outDebug("_ApplyAllItemMods complete.");
6981 void Player::_ApplyAmmoBonuses()
6983 // check ammo
6984 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6985 if(!ammo_id)
6986 return;
6988 float currentAmmoDPS;
6990 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6991 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6992 currentAmmoDPS = 0.0f;
6993 else
6994 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6996 if(currentAmmoDPS == GetAmmoDPS())
6997 return;
6999 m_ammoDPS = currentAmmoDPS;
7001 if(CanModifyStats())
7002 UpdateDamagePhysical(RANGED_ATTACK);
7005 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7007 if(!ammo_proto)
7008 return false;
7010 // check ranged weapon
7011 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7012 if(!weapon || weapon->IsBroken() )
7013 return false;
7015 ItemPrototype const* weapon_proto = weapon->GetProto();
7016 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7017 return false;
7019 // check ammo ws. weapon compatibility
7020 switch(weapon_proto->SubClass)
7022 case ITEM_SUBCLASS_WEAPON_BOW:
7023 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7024 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7025 return false;
7026 break;
7027 case ITEM_SUBCLASS_WEAPON_GUN:
7028 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7029 return false;
7030 break;
7031 default:
7032 return false;
7035 return true;
7038 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7039 Called by remove insignia spell effect */
7040 void Player::RemovedInsignia(Player* looterPlr)
7042 if (!GetBattleGroundId())
7043 return;
7045 // If not released spirit, do it !
7046 if(m_deathTimer > 0)
7048 m_deathTimer = 0;
7049 BuildPlayerRepop();
7050 RepopAtGraveyard();
7053 Corpse *corpse = GetCorpse();
7054 if (!corpse)
7055 return;
7057 // We have to convert player corpse to bones, not to be able to resurrect there
7058 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7059 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7060 if (!bones)
7061 return;
7063 // Now we must make bones lootable, and send player loot
7064 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7066 // We store the level of our player in the gold field
7067 // We retrieve this information at Player::SendLoot()
7068 bones->loot.gold = getLevel();
7069 bones->lootRecipient = looterPlr;
7070 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7073 /*Loot type MUST be
7074 1-corpse, go
7075 2-skinning
7076 3-Fishing
7079 void Player::SendLootRelease( uint64 guid )
7081 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7082 data << uint64(guid) << uint8(1);
7083 SendDirectMessage( &data );
7086 void Player::SendLoot(uint64 guid, LootType loot_type)
7088 Loot *loot = 0;
7089 PermissionTypes permission = ALL_PERMISSION;
7091 sLog.outDebug("Player::SendLoot");
7092 if (IS_GAMEOBJECT_GUID(guid))
7094 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7095 GameObject *go =
7096 ObjectAccessor::GetGameObject(*this, guid);
7098 // not check distance for GO in case owned GO (fishing bobber case, for example)
7099 // And permit out of range GO with no owner in case fishing hole
7100 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7102 SendLootRelease(guid);
7103 return;
7106 loot = &go->loot;
7108 if(go->getLootState() == GO_READY)
7110 uint32 lootid = go->GetLootId();
7112 if(lootid)
7114 sLog.outDebug(" if(lootid)");
7115 loot->clear();
7116 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7119 if(loot_type == LOOT_FISHING)
7120 go->getFishLoot(loot);
7122 go->SetLootState(GO_ACTIVATED);
7125 else if (IS_ITEM_GUID(guid))
7127 Item *item = GetItemByGuid( guid );
7129 if (!item)
7131 SendLootRelease(guid);
7132 return;
7135 if(loot_type == LOOT_DISENCHANTING)
7137 loot = &item->loot;
7139 if(!item->m_lootGenerated)
7141 item->m_lootGenerated = true;
7142 loot->clear();
7143 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7146 else if(loot_type == LOOT_PROSPECTING)
7148 loot = &item->loot;
7150 if(!item->m_lootGenerated)
7152 item->m_lootGenerated = true;
7153 loot->clear();
7154 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7157 else
7159 loot = &item->loot;
7161 if(!item->m_lootGenerated)
7163 item->m_lootGenerated = true;
7164 loot->clear();
7165 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7167 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7171 else if (IS_CORPSE_GUID(guid)) // remove insignia
7173 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7175 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7177 SendLootRelease(guid);
7178 return;
7181 loot = &bones->loot;
7183 if (!bones->lootForBody)
7185 bones->lootForBody = true;
7186 uint32 pLevel = bones->loot.gold;
7187 bones->loot.clear();
7188 // It may need a better formula
7189 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7190 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7193 if (bones->lootRecipient != this)
7194 permission = NONE_PERMISSION;
7196 else
7198 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7200 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7201 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7203 SendLootRelease(guid);
7204 return;
7207 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7209 SendLootRelease(guid);
7210 return;
7213 loot = &creature->loot;
7215 if(loot_type == LOOT_PICKPOCKETING)
7217 if ( !creature->lootForPickPocketed )
7219 creature->lootForPickPocketed = true;
7220 loot->clear();
7222 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7223 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7225 // Generate extra money for pick pocket loot
7226 const uint32 a = urand(0, creature->getLevel()/2);
7227 const uint32 b = urand(0, getLevel()/2);
7228 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7231 else
7233 // the player whose group may loot the corpse
7234 Player *recipient = creature->GetLootRecipient();
7235 if (!recipient)
7237 creature->SetLootRecipient(this);
7238 recipient = this;
7241 if (creature->lootForPickPocketed)
7243 creature->lootForPickPocketed = false;
7244 loot->clear();
7247 if(!creature->lootForBody)
7249 creature->lootForBody = true;
7250 loot->clear();
7252 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7253 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7255 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7257 if(Group* group = recipient->GetGroup())
7259 group->UpdateLooterGuid(creature,true);
7261 switch (group->GetLootMethod())
7263 case GROUP_LOOT:
7264 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7265 group->GroupLoot(recipient->GetGUID(), loot, creature);
7266 break;
7267 case NEED_BEFORE_GREED:
7268 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7269 break;
7270 case MASTER_LOOT:
7271 group->MasterLoot(recipient->GetGUID(), loot, creature);
7272 break;
7273 default:
7274 break;
7279 // possible only if creature->lootForBody && loot->empty() at spell cast check
7280 if (loot_type == LOOT_SKINNING)
7282 loot->clear();
7283 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7285 // set group rights only for loot_type != LOOT_SKINNING
7286 else
7288 if(Group* group = GetGroup())
7290 if( group == recipient->GetGroup() )
7292 if(group->GetLootMethod() == FREE_FOR_ALL)
7293 permission = ALL_PERMISSION;
7294 else if(group->GetLooterGuid() == GetGUID())
7296 if(group->GetLootMethod() == MASTER_LOOT)
7297 permission = MASTER_PERMISSION;
7298 else
7299 permission = ALL_PERMISSION;
7301 else
7302 permission = GROUP_PERMISSION;
7304 else
7305 permission = NONE_PERMISSION;
7307 else if(recipient == this)
7308 permission = ALL_PERMISSION;
7309 else
7310 permission = NONE_PERMISSION;
7315 SetLootGUID(guid);
7317 QuestItemList *q_list = 0;
7318 if (permission != NONE_PERMISSION)
7320 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7321 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7322 if (itr == lootPlayerQuestItems.end())
7323 q_list = loot->FillQuestLoot(this);
7324 else
7325 q_list = itr->second;
7328 QuestItemList *ffa_list = 0;
7329 if (permission != NONE_PERMISSION)
7331 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7332 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7333 if (itr == lootPlayerFFAItems.end())
7334 ffa_list = loot->FillFFALoot(this);
7335 else
7336 ffa_list = itr->second;
7339 QuestItemList *conditional_list = 0;
7340 if (permission != NONE_PERMISSION)
7342 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7343 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7344 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7345 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7346 else
7347 conditional_list = itr->second;
7350 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7351 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7352 loot_type = LOOT_SKINNING;
7354 if(loot_type == LOOT_FISHINGHOLE)
7355 loot_type = LOOT_FISHING;
7357 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7359 data << uint64(guid);
7360 data << uint8(loot_type);
7361 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7363 SendDirectMessage(&data);
7365 // add 'this' player as one of the players that are looting 'loot'
7366 if (permission != NONE_PERMISSION)
7367 loot->AddLooter(GetGUID());
7369 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7370 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7373 void Player::SendNotifyLootMoneyRemoved()
7375 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7376 GetSession()->SendPacket( &data );
7379 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7381 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7382 data << uint8(lootSlot);
7383 GetSession()->SendPacket( &data );
7386 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7388 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7389 data << Field;
7390 data << Value;
7391 GetSession()->SendPacket(&data);
7394 void Player::SendInitWorldStates()
7396 // data depends on zoneid/mapid...
7397 BattleGround* bg = GetBattleGround();
7398 uint16 NumberOfFields = 0;
7399 uint32 mapid = GetMapId();
7400 uint32 zoneid = GetZoneId();
7401 uint32 areaid = GetAreaId();
7402 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7403 // may be exist better way to do this...
7404 switch(zoneid)
7406 case 0:
7407 case 1:
7408 case 4:
7409 case 8:
7410 case 10:
7411 case 11:
7412 case 12:
7413 case 36:
7414 case 38:
7415 case 40:
7416 case 41:
7417 case 51:
7418 case 267:
7419 case 1519:
7420 case 1537:
7421 case 2257:
7422 case 2918:
7423 NumberOfFields = 6;
7424 break;
7425 case 2597:
7426 NumberOfFields = 81;
7427 break;
7428 case 3277:
7429 NumberOfFields = 14;
7430 break;
7431 case 3358:
7432 case 3820:
7433 NumberOfFields = 38;
7434 break;
7435 case 3483:
7436 NumberOfFields = 22;
7437 break;
7438 case 3519:
7439 NumberOfFields = 36;
7440 break;
7441 case 3521:
7442 NumberOfFields = 35;
7443 break;
7444 case 3698:
7445 case 3702:
7446 case 3968:
7447 NumberOfFields = 9;
7448 break;
7449 case 3703:
7450 NumberOfFields = 9;
7451 break;
7452 default:
7453 NumberOfFields = 10;
7454 break;
7457 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7458 data << uint32(mapid); // mapid
7459 data << uint32(zoneid); // zone id
7460 data << uint32(areaid); // area id, new 2.1.0
7461 data << uint16(NumberOfFields); // count of uint64 blocks
7462 data << uint32(0x8d8) << uint32(0x0); // 1
7463 data << uint32(0x8d7) << uint32(0x0); // 2
7464 data << uint32(0x8d6) << uint32(0x0); // 3
7465 data << uint32(0x8d5) << uint32(0x0); // 4
7466 data << uint32(0x8d4) << uint32(0x0); // 5
7467 data << uint32(0x8d3) << uint32(0x0); // 6
7468 if(mapid == 530) // Outland
7470 data << uint32(0x9bf) << uint32(0x0); // 7
7471 data << uint32(0x9bd) << uint32(0xF); // 8
7472 data << uint32(0x9bb) << uint32(0xF); // 9
7474 switch(zoneid)
7476 case 1:
7477 case 11:
7478 case 12:
7479 case 38:
7480 case 40:
7481 case 51:
7482 case 1519:
7483 case 1537:
7484 case 2257:
7485 break;
7486 case 2597: // AV
7487 data << uint32(0x7ae) << uint32(0x1); // 7
7488 data << uint32(0x532) << uint32(0x1); // 8
7489 data << uint32(0x531) << uint32(0x0); // 9
7490 data << uint32(0x52e) << uint32(0x0); // 10
7491 data << uint32(0x571) << uint32(0x0); // 11
7492 data << uint32(0x570) << uint32(0x0); // 12
7493 data << uint32(0x567) << uint32(0x1); // 13
7494 data << uint32(0x566) << uint32(0x1); // 14
7495 data << uint32(0x550) << uint32(0x1); // 15
7496 data << uint32(0x544) << uint32(0x0); // 16
7497 data << uint32(0x536) << uint32(0x0); // 17
7498 data << uint32(0x535) << uint32(0x1); // 18
7499 data << uint32(0x518) << uint32(0x0); // 19
7500 data << uint32(0x517) << uint32(0x0); // 20
7501 data << uint32(0x574) << uint32(0x0); // 21
7502 data << uint32(0x573) << uint32(0x0); // 22
7503 data << uint32(0x572) << uint32(0x0); // 23
7504 data << uint32(0x56f) << uint32(0x0); // 24
7505 data << uint32(0x56e) << uint32(0x0); // 25
7506 data << uint32(0x56d) << uint32(0x0); // 26
7507 data << uint32(0x56c) << uint32(0x0); // 27
7508 data << uint32(0x56b) << uint32(0x0); // 28
7509 data << uint32(0x56a) << uint32(0x1); // 29
7510 data << uint32(0x569) << uint32(0x1); // 30
7511 data << uint32(0x568) << uint32(0x1); // 13
7512 data << uint32(0x565) << uint32(0x0); // 32
7513 data << uint32(0x564) << uint32(0x0); // 33
7514 data << uint32(0x563) << uint32(0x0); // 34
7515 data << uint32(0x562) << uint32(0x0); // 35
7516 data << uint32(0x561) << uint32(0x0); // 36
7517 data << uint32(0x560) << uint32(0x0); // 37
7518 data << uint32(0x55f) << uint32(0x0); // 38
7519 data << uint32(0x55e) << uint32(0x0); // 39
7520 data << uint32(0x55d) << uint32(0x0); // 40
7521 data << uint32(0x3c6) << uint32(0x4); // 41
7522 data << uint32(0x3c4) << uint32(0x6); // 42
7523 data << uint32(0x3c2) << uint32(0x4); // 43
7524 data << uint32(0x516) << uint32(0x1); // 44
7525 data << uint32(0x515) << uint32(0x0); // 45
7526 data << uint32(0x3b6) << uint32(0x6); // 46
7527 data << uint32(0x55c) << uint32(0x0); // 47
7528 data << uint32(0x55b) << uint32(0x0); // 48
7529 data << uint32(0x55a) << uint32(0x0); // 49
7530 data << uint32(0x559) << uint32(0x0); // 50
7531 data << uint32(0x558) << uint32(0x0); // 51
7532 data << uint32(0x557) << uint32(0x0); // 52
7533 data << uint32(0x556) << uint32(0x0); // 53
7534 data << uint32(0x555) << uint32(0x0); // 54
7535 data << uint32(0x554) << uint32(0x1); // 55
7536 data << uint32(0x553) << uint32(0x1); // 56
7537 data << uint32(0x552) << uint32(0x1); // 57
7538 data << uint32(0x551) << uint32(0x1); // 58
7539 data << uint32(0x54f) << uint32(0x0); // 59
7540 data << uint32(0x54e) << uint32(0x0); // 60
7541 data << uint32(0x54d) << uint32(0x1); // 61
7542 data << uint32(0x54c) << uint32(0x0); // 62
7543 data << uint32(0x54b) << uint32(0x0); // 63
7544 data << uint32(0x545) << uint32(0x0); // 64
7545 data << uint32(0x543) << uint32(0x1); // 65
7546 data << uint32(0x542) << uint32(0x0); // 66
7547 data << uint32(0x540) << uint32(0x0); // 67
7548 data << uint32(0x53f) << uint32(0x0); // 68
7549 data << uint32(0x53e) << uint32(0x0); // 69
7550 data << uint32(0x53d) << uint32(0x0); // 70
7551 data << uint32(0x53c) << uint32(0x0); // 71
7552 data << uint32(0x53b) << uint32(0x0); // 72
7553 data << uint32(0x53a) << uint32(0x1); // 73
7554 data << uint32(0x539) << uint32(0x0); // 74
7555 data << uint32(0x538) << uint32(0x0); // 75
7556 data << uint32(0x537) << uint32(0x0); // 76
7557 data << uint32(0x534) << uint32(0x0); // 77
7558 data << uint32(0x533) << uint32(0x0); // 78
7559 data << uint32(0x530) << uint32(0x0); // 79
7560 data << uint32(0x52f) << uint32(0x0); // 80
7561 data << uint32(0x52d) << uint32(0x1); // 81
7562 break;
7563 case 3277: // WS
7564 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7565 bg->FillInitialWorldStates(data);
7566 else
7568 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7569 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7570 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7571 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7572 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7573 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7574 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7575 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7577 break;
7578 case 3358: // AB
7579 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7580 bg->FillInitialWorldStates(data);
7581 else
7583 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7584 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7585 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7586 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7587 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7588 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7589 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7590 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7591 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7592 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7593 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7594 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7595 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7596 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7597 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7598 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7599 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7600 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7601 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7602 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7603 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7604 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7605 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7606 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7607 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7608 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7609 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7610 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7611 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7612 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7613 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7614 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7616 break;
7617 case 3820: // EY
7618 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7619 bg->FillInitialWorldStates(data);
7620 else
7622 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7623 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7624 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7625 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7626 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7627 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7628 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7629 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7630 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7631 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7632 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7633 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7634 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7635 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7636 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7637 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7638 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7639 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7640 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7641 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7642 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7643 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7644 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7645 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7646 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7647 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7648 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7649 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7650 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7651 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7652 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7653 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7654 // and some more ... unknown
7656 break;
7657 case 3483: // Hellfire Peninsula
7658 data << uint32(0x9ba) << uint32(0x1); // 10
7659 data << uint32(0x9b9) << uint32(0x1); // 11
7660 data << uint32(0x9b5) << uint32(0x0); // 12
7661 data << uint32(0x9b4) << uint32(0x1); // 13
7662 data << uint32(0x9b3) << uint32(0x0); // 14
7663 data << uint32(0x9b2) << uint32(0x0); // 15
7664 data << uint32(0x9b1) << uint32(0x1); // 16
7665 data << uint32(0x9b0) << uint32(0x0); // 17
7666 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7667 data << uint32(0x9ac) << uint32(0x0); // 19
7668 data << uint32(0x9a8) << uint32(0x0); // 20
7669 data << uint32(0x9a7) << uint32(0x0); // 21
7670 data << uint32(0x9a6) << uint32(0x1); // 22
7671 break;
7672 case 3519: // Terokkar Forest
7673 data << uint32(0xa41) << uint32(0x0); // 10
7674 data << uint32(0xa40) << uint32(0x14); // 11
7675 data << uint32(0xa3f) << uint32(0x0); // 12
7676 data << uint32(0xa3e) << uint32(0x0); // 13
7677 data << uint32(0xa3d) << uint32(0x5); // 14
7678 data << uint32(0xa3c) << uint32(0x0); // 15
7679 data << uint32(0xa87) << uint32(0x0); // 16
7680 data << uint32(0xa86) << uint32(0x0); // 17
7681 data << uint32(0xa85) << uint32(0x0); // 18
7682 data << uint32(0xa84) << uint32(0x0); // 19
7683 data << uint32(0xa83) << uint32(0x0); // 20
7684 data << uint32(0xa82) << uint32(0x0); // 21
7685 data << uint32(0xa81) << uint32(0x0); // 22
7686 data << uint32(0xa80) << uint32(0x0); // 23
7687 data << uint32(0xa7e) << uint32(0x0); // 24
7688 data << uint32(0xa7d) << uint32(0x0); // 25
7689 data << uint32(0xa7c) << uint32(0x0); // 26
7690 data << uint32(0xa7b) << uint32(0x0); // 27
7691 data << uint32(0xa7a) << uint32(0x0); // 28
7692 data << uint32(0xa79) << uint32(0x0); // 29
7693 data << uint32(0x9d0) << uint32(0x5); // 30
7694 data << uint32(0x9ce) << uint32(0x0); // 31
7695 data << uint32(0x9cd) << uint32(0x0); // 32
7696 data << uint32(0x9cc) << uint32(0x0); // 33
7697 data << uint32(0xa88) << uint32(0x0); // 34
7698 data << uint32(0xad0) << uint32(0x0); // 35
7699 data << uint32(0xacf) << uint32(0x1); // 36
7700 break;
7701 case 3521: // Zangarmarsh
7702 data << uint32(0x9e1) << uint32(0x0); // 10
7703 data << uint32(0x9e0) << uint32(0x0); // 11
7704 data << uint32(0x9df) << uint32(0x0); // 12
7705 data << uint32(0xa5d) << uint32(0x1); // 13
7706 data << uint32(0xa5c) << uint32(0x0); // 14
7707 data << uint32(0xa5b) << uint32(0x1); // 15
7708 data << uint32(0xa5a) << uint32(0x0); // 16
7709 data << uint32(0xa59) << uint32(0x1); // 17
7710 data << uint32(0xa58) << uint32(0x0); // 18
7711 data << uint32(0xa57) << uint32(0x0); // 19
7712 data << uint32(0xa56) << uint32(0x0); // 20
7713 data << uint32(0xa55) << uint32(0x1); // 21
7714 data << uint32(0xa54) << uint32(0x0); // 22
7715 data << uint32(0x9e7) << uint32(0x0); // 23
7716 data << uint32(0x9e6) << uint32(0x0); // 24
7717 data << uint32(0x9e5) << uint32(0x0); // 25
7718 data << uint32(0xa00) << uint32(0x0); // 26
7719 data << uint32(0x9ff) << uint32(0x1); // 27
7720 data << uint32(0x9fe) << uint32(0x0); // 28
7721 data << uint32(0x9fd) << uint32(0x0); // 29
7722 data << uint32(0x9fc) << uint32(0x1); // 30
7723 data << uint32(0x9fb) << uint32(0x0); // 31
7724 data << uint32(0xa62) << uint32(0x0); // 32
7725 data << uint32(0xa61) << uint32(0x1); // 33
7726 data << uint32(0xa60) << uint32(0x1); // 34
7727 data << uint32(0xa5f) << uint32(0x0); // 35
7728 break;
7729 case 3698: // Nagrand Arena
7730 data << uint32(0xa0f) << uint32(0x0); // 7
7731 data << uint32(0xa10) << uint32(0x0); // 8
7732 data << uint32(0xa11) << uint32(0x0); // 9
7733 break;
7734 case 3702: // Blade's Edge Arena
7735 data << uint32(0x9f0) << uint32(0x0); // 7
7736 data << uint32(0x9f1) << uint32(0x0); // 8
7737 data << uint32(0x9f3) << uint32(0x0); // 9
7738 break;
7739 case 3968: // Ruins of Lordaeron
7740 data << uint32(0xbb8) << uint32(0x0); // 7
7741 data << uint32(0xbb9) << uint32(0x0); // 8
7742 data << uint32(0xbba) << uint32(0x0); // 9
7743 break;
7744 case 3703: // Shattrath City
7745 break;
7746 default:
7747 data << uint32(0x914) << uint32(0x0); // 7
7748 data << uint32(0x913) << uint32(0x0); // 8
7749 data << uint32(0x912) << uint32(0x0); // 9
7750 data << uint32(0x915) << uint32(0x0); // 10
7751 break;
7753 GetSession()->SendPacket(&data);
7756 uint32 Player::GetXPRestBonus(uint32 xp)
7758 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7760 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7761 rested_bonus = xp;
7763 SetRestBonus( GetRestBonus() - rested_bonus);
7765 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7766 return rested_bonus;
7769 void Player::SetBindPoint(uint64 guid)
7771 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7772 data << uint64(guid);
7773 GetSession()->SendPacket( &data );
7776 void Player::SendTalentWipeConfirm(uint64 guid)
7778 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7779 data << uint64(guid);
7780 data << uint32(resetTalentsCost());
7781 GetSession()->SendPacket( &data );
7784 void Player::SendPetSkillWipeConfirm()
7786 Pet* pet = GetPet();
7787 if(!pet)
7788 return;
7789 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7790 data << pet->GetGUID();
7791 data << uint32(pet->resetTalentsCost());
7792 GetSession()->SendPacket( &data );
7795 /*********************************************************/
7796 /*** STORAGE SYSTEM ***/
7797 /*********************************************************/
7799 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7801 assert(i < 3);
7802 if(i < 2 && item)
7804 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7805 return;
7806 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7807 if(charges == 0)
7808 return;
7809 if(charges > 1)
7810 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7811 else if(charges <= 1)
7813 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7814 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7819 void Player::SetSheath( uint32 sheathed )
7821 switch (sheathed)
7823 case SHEATH_STATE_UNARMED: // no prepared weapon
7824 SetVirtualItemSlot(0,NULL);
7825 SetVirtualItemSlot(1,NULL);
7826 SetVirtualItemSlot(2,NULL);
7827 break;
7828 case SHEATH_STATE_MELEE: // prepared melee weapon
7830 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7831 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7832 SetVirtualItemSlot(2,NULL);
7833 }; break;
7834 case SHEATH_STATE_RANGED: // prepared ranged weapon
7835 SetVirtualItemSlot(0,NULL);
7836 SetVirtualItemSlot(1,NULL);
7837 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7838 break;
7839 default:
7840 SetVirtualItemSlot(0,NULL);
7841 SetVirtualItemSlot(1,NULL);
7842 SetVirtualItemSlot(2,NULL);
7843 break;
7845 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7848 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7850 uint8 pClass = getClass();
7852 uint8 slots[4];
7853 slots[0] = NULL_SLOT;
7854 slots[1] = NULL_SLOT;
7855 slots[2] = NULL_SLOT;
7856 slots[3] = NULL_SLOT;
7857 switch( proto->InventoryType )
7859 case INVTYPE_HEAD:
7860 slots[0] = EQUIPMENT_SLOT_HEAD;
7861 break;
7862 case INVTYPE_NECK:
7863 slots[0] = EQUIPMENT_SLOT_NECK;
7864 break;
7865 case INVTYPE_SHOULDERS:
7866 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7867 break;
7868 case INVTYPE_BODY:
7869 slots[0] = EQUIPMENT_SLOT_BODY;
7870 break;
7871 case INVTYPE_CHEST:
7872 slots[0] = EQUIPMENT_SLOT_CHEST;
7873 break;
7874 case INVTYPE_ROBE:
7875 slots[0] = EQUIPMENT_SLOT_CHEST;
7876 break;
7877 case INVTYPE_WAIST:
7878 slots[0] = EQUIPMENT_SLOT_WAIST;
7879 break;
7880 case INVTYPE_LEGS:
7881 slots[0] = EQUIPMENT_SLOT_LEGS;
7882 break;
7883 case INVTYPE_FEET:
7884 slots[0] = EQUIPMENT_SLOT_FEET;
7885 break;
7886 case INVTYPE_WRISTS:
7887 slots[0] = EQUIPMENT_SLOT_WRISTS;
7888 break;
7889 case INVTYPE_HANDS:
7890 slots[0] = EQUIPMENT_SLOT_HANDS;
7891 break;
7892 case INVTYPE_FINGER:
7893 slots[0] = EQUIPMENT_SLOT_FINGER1;
7894 slots[1] = EQUIPMENT_SLOT_FINGER2;
7895 break;
7896 case INVTYPE_TRINKET:
7897 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7898 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7899 break;
7900 case INVTYPE_CLOAK:
7901 slots[0] = EQUIPMENT_SLOT_BACK;
7902 break;
7903 case INVTYPE_WEAPON:
7905 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7907 // suggest offhand slot only if know dual wielding
7908 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7909 if(CanDualWield())
7910 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7911 };break;
7912 case INVTYPE_SHIELD:
7913 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7914 break;
7915 case INVTYPE_RANGED:
7916 slots[0] = EQUIPMENT_SLOT_RANGED;
7917 break;
7918 case INVTYPE_2HWEAPON:
7919 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7920 break;
7921 case INVTYPE_TABARD:
7922 slots[0] = EQUIPMENT_SLOT_TABARD;
7923 break;
7924 case INVTYPE_WEAPONMAINHAND:
7925 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7926 break;
7927 case INVTYPE_WEAPONOFFHAND:
7928 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7929 break;
7930 case INVTYPE_HOLDABLE:
7931 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7932 break;
7933 case INVTYPE_THROWN:
7934 slots[0] = EQUIPMENT_SLOT_RANGED;
7935 break;
7936 case INVTYPE_RANGEDRIGHT:
7937 slots[0] = EQUIPMENT_SLOT_RANGED;
7938 break;
7939 case INVTYPE_BAG:
7940 slots[0] = INVENTORY_SLOT_BAG_1;
7941 slots[1] = INVENTORY_SLOT_BAG_2;
7942 slots[2] = INVENTORY_SLOT_BAG_3;
7943 slots[3] = INVENTORY_SLOT_BAG_4;
7944 break;
7945 case INVTYPE_RELIC:
7947 switch(proto->SubClass)
7949 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7950 if (pClass == CLASS_PALADIN)
7951 slots[0] = EQUIPMENT_SLOT_RANGED;
7952 break;
7953 case ITEM_SUBCLASS_ARMOR_IDOL:
7954 if (pClass == CLASS_DRUID)
7955 slots[0] = EQUIPMENT_SLOT_RANGED;
7956 break;
7957 case ITEM_SUBCLASS_ARMOR_TOTEM:
7958 if (pClass == CLASS_SHAMAN)
7959 slots[0] = EQUIPMENT_SLOT_RANGED;
7960 break;
7961 case ITEM_SUBCLASS_ARMOR_MISC:
7962 if (pClass == CLASS_WARLOCK)
7963 slots[0] = EQUIPMENT_SLOT_RANGED;
7964 break;
7966 break;
7968 default :
7969 return NULL_SLOT;
7972 if( slot != NULL_SLOT )
7974 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7976 for (int i = 0; i < 4; i++)
7978 if ( slots[i] == slot )
7979 return slot;
7983 else
7985 // search free slot at first
7986 for (int i = 0; i < 4; i++)
7988 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7990 // in case 2hand equipped weapon offhand slot empty but not free
7991 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7993 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7994 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7995 return slots[i];
7997 else
7998 return slots[i];
8002 // if not found free and can swap return first appropriate from used
8003 for (int i = 0; i < 4; i++)
8005 if ( slots[i] != NULL_SLOT && swap )
8006 return slots[i];
8010 // no free position
8011 return NULL_SLOT;
8014 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8016 Item *pItem;
8017 uint32 tempcount = 0;
8019 uint8 res = EQUIP_ERR_OK;
8021 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8023 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8024 if( pItem && pItem->GetEntry() == item )
8026 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8027 if(ires==EQUIP_ERR_OK)
8029 tempcount += pItem->GetCount();
8030 if( tempcount >= count )
8031 return EQUIP_ERR_OK;
8033 else
8034 res = ires;
8037 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8039 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8040 if( pItem && pItem->GetEntry() == item )
8042 tempcount += pItem->GetCount();
8043 if( tempcount >= count )
8044 return EQUIP_ERR_OK;
8047 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8049 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8050 if( pItem && pItem->GetEntry() == item )
8052 tempcount += pItem->GetCount();
8053 if( tempcount >= count )
8054 return EQUIP_ERR_OK;
8057 Bag *pBag;
8058 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8060 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8061 if( pBag )
8063 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8065 pItem = GetItemByPos( i, j );
8066 if( pItem && pItem->GetEntry() == item )
8068 tempcount += pItem->GetCount();
8069 if( tempcount >= count )
8070 return EQUIP_ERR_OK;
8076 // not found req. item count and have unequippable items
8077 return res;
8080 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8082 uint32 count = 0;
8083 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8085 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8086 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8087 count += pItem->GetCount();
8089 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8091 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8092 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8093 count += pItem->GetCount();
8095 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8097 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8098 if( pBag )
8099 count += pBag->GetItemCount(item,skipItem);
8102 if(skipItem && skipItem->GetProto()->GemProperties)
8104 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8106 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8107 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8108 count += pItem->GetGemCountWithID(item);
8112 if(inBankAlso)
8114 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8116 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8117 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8118 count += pItem->GetCount();
8120 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8122 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8123 if( pBag )
8124 count += pBag->GetItemCount(item,skipItem);
8127 if(skipItem && skipItem->GetProto()->GemProperties)
8129 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8131 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8132 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8133 count += pItem->GetGemCountWithID(item);
8138 return count;
8141 Item* Player::GetItemByGuid( uint64 guid ) const
8143 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8145 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8146 if( pItem && pItem->GetGUID() == guid )
8147 return pItem;
8149 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8151 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8152 if( pItem && pItem->GetGUID() == guid )
8153 return pItem;
8156 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8158 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8159 if( pBag )
8161 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8163 Item* pItem = pBag->GetItemByPos( j );
8164 if( pItem && pItem->GetGUID() == guid )
8165 return pItem;
8169 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8171 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8172 if( pBag )
8174 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8176 Item* pItem = pBag->GetItemByPos( j );
8177 if( pItem && pItem->GetGUID() == guid )
8178 return pItem;
8183 return NULL;
8186 Item* Player::GetItemByPos( uint16 pos ) const
8188 uint8 bag = pos >> 8;
8189 uint8 slot = pos & 255;
8190 return GetItemByPos( bag, slot );
8193 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8195 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8196 return m_items[slot];
8197 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8198 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8200 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8201 if ( pBag )
8202 return pBag->GetItemByPos(slot);
8204 return NULL;
8207 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8209 uint16 slot;
8210 switch (attackType)
8212 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8213 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8214 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8215 default: return NULL;
8218 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8219 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8220 return NULL;
8222 if(!useable)
8223 return item;
8225 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8226 return NULL;
8228 return item;
8231 Item* Player::GetShield(bool useable) const
8233 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8234 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8235 return NULL;
8237 if(!useable)
8238 return item;
8240 if( item->IsBroken())
8241 return NULL;
8243 return item;
8246 uint32 Player::GetAttackBySlot( uint8 slot )
8248 switch(slot)
8250 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8251 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8252 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8253 default: return MAX_ATTACK;
8257 bool Player::HasBankBagSlot( uint8 slot ) const
8259 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8260 if( slot < maxslot )
8261 return true;
8262 return false;
8265 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8267 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8268 return true;
8269 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8270 return true;
8271 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8272 return true;
8273 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8274 return true;
8275 return false;
8278 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8280 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8281 return true;
8282 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8283 return true;
8284 return false;
8287 bool Player::IsBankPos( uint8 bag, uint8 slot )
8289 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8290 return true;
8291 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8292 return true;
8293 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8294 return true;
8295 return false;
8298 bool Player::IsBagPos( uint16 pos )
8300 uint8 bag = pos >> 8;
8301 uint8 slot = pos & 255;
8302 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8303 return true;
8304 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8305 return true;
8306 return false;
8309 bool Player::IsValidPos( uint8 bag, uint8 slot )
8311 // post selected
8312 if(bag == NULL_BAG)
8313 return true;
8315 if (bag == INVENTORY_SLOT_BAG_0)
8317 // any post selected
8318 if (slot == NULL_SLOT)
8319 return true;
8321 // equipment
8322 if (slot < EQUIPMENT_SLOT_END)
8323 return true;
8325 // bag equip slots
8326 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8327 return true;
8329 // backpack slots
8330 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8331 return true;
8333 // keyring slots
8334 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8335 return true;
8337 // bank main slots
8338 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8339 return true;
8341 // bank bag slots
8342 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8343 return true;
8345 return false;
8348 // bag content slots
8349 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8351 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8352 if(!pBag)
8353 return false;
8355 // any post selected
8356 if (slot == NULL_SLOT)
8357 return true;
8359 return slot < pBag->GetBagSize();
8362 // bank bag content slots
8363 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8365 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8366 if(!pBag)
8367 return false;
8369 // any post selected
8370 if (slot == NULL_SLOT)
8371 return true;
8373 return slot < pBag->GetBagSize();
8376 // where this?
8377 return false;
8381 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8383 uint32 tempcount = 0;
8384 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8386 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8387 if( pItem && pItem->GetEntry() == item )
8389 tempcount += pItem->GetCount();
8390 if( tempcount >= count )
8391 return true;
8394 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8396 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8397 if( pItem && pItem->GetEntry() == item )
8399 tempcount += pItem->GetCount();
8400 if( tempcount >= count )
8401 return true;
8404 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8406 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8408 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8410 Item* pItem = GetItemByPos( i, j );
8411 if( pItem && pItem->GetEntry() == item )
8413 tempcount += pItem->GetCount();
8414 if( tempcount >= count )
8415 return true;
8421 if(inBankAlso)
8423 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8425 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8426 if( pItem && pItem->GetEntry() == item )
8428 tempcount += pItem->GetCount();
8429 if( tempcount >= count )
8430 return true;
8433 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8435 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8437 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8439 Item* pItem = GetItemByPos( i, j );
8440 if( pItem && pItem->GetEntry() == item )
8442 tempcount += pItem->GetCount();
8443 if( tempcount >= count )
8444 return true;
8451 return false;
8454 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8456 Item *pItem;
8457 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8459 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8460 if( pItem && pItem->GetEntry() == item )
8461 return pItem;
8464 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8465 if (pProto && pProto->GemProperties)
8467 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8469 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8470 if( pItem && pItem->GetProto()->Socket[0].Color )
8472 if (pItem->GetGemCountWithID(item) > 0 )
8473 return pItem;
8478 return NULL;
8481 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8483 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8484 if( !pProto )
8486 if(no_space_count)
8487 *no_space_count = count;
8488 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8491 // no maximum
8492 if(pProto->MaxCount == 0)
8493 return EQUIP_ERR_OK;
8495 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8497 if( curcount + count > pProto->MaxCount )
8499 if(no_space_count)
8500 *no_space_count = count +curcount - pProto->MaxCount;
8501 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8504 return EQUIP_ERR_OK;
8507 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8509 Item *pItem;
8510 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8512 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8513 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8514 return true;
8516 for(uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
8518 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8519 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8520 return true;
8522 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8524 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8526 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8528 pItem = GetItemByPos( i, j );
8529 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8530 return true;
8534 return false;
8537 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8539 Item* pItem2 = GetItemByPos( bag, slot );
8541 // ignore move item (this slot will be empty at move)
8542 if(pItem2==pSrcItem)
8543 pItem2 = NULL;
8545 uint32 need_space;
8547 // empty specific slot - check item fit to slot
8548 if( !pItem2 || swap )
8550 if( bag == INVENTORY_SLOT_BAG_0 )
8552 // keyring case
8553 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8554 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8556 // prevent cheating
8557 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8558 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8560 else
8562 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8563 if( !pBag )
8564 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8566 ItemPrototype const* pBagProto = pBag->GetProto();
8567 if( !pBagProto )
8568 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8570 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8571 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8574 // non empty stack with space
8575 need_space = pProto->Stackable;
8577 // non empty slot, check item type
8578 else
8580 // check item type
8581 if(pItem2->GetEntry() != pProto->ItemId)
8582 return EQUIP_ERR_ITEM_CANT_STACK;
8584 // check free space
8585 if(pItem2->GetCount() >= pProto->Stackable)
8586 return EQUIP_ERR_ITEM_CANT_STACK;
8588 need_space = pProto->Stackable - pItem2->GetCount();
8591 if(need_space > count)
8592 need_space = count;
8594 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8595 if(!newPosition.isContainedIn(dest))
8597 dest.push_back(newPosition);
8598 count -= need_space;
8600 return EQUIP_ERR_OK;
8603 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
8605 // skip specific bag already processed in first called _CanStoreItem_InBag
8606 if(bag==skip_bag)
8607 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8609 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8610 if( !pBag )
8611 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8613 ItemPrototype const* pBagProto = pBag->GetProto();
8614 if( !pBagProto )
8615 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8617 // specialized bag mode or non-specilized
8618 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8619 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8621 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8622 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8624 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8626 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8627 if(j==skip_slot)
8628 continue;
8630 Item* pItem2 = GetItemByPos( bag, j );
8632 // ignore move item (this slot will be empty at move)
8633 if(pItem2==pSrcItem)
8634 pItem2 = NULL;
8636 // if merge skip empty, if !merge skip non-empty
8637 if((pItem2!=NULL)!=merge)
8638 continue;
8640 if( pItem2 )
8642 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8644 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8645 if(need_space > count)
8646 need_space = count;
8648 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8649 if(!newPosition.isContainedIn(dest))
8651 dest.push_back(newPosition);
8652 count -= need_space;
8654 if(count==0)
8655 return EQUIP_ERR_OK;
8659 else
8661 uint32 need_space = pProto->Stackable;
8662 if(need_space > count)
8663 need_space = count;
8665 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8666 if(!newPosition.isContainedIn(dest))
8668 dest.push_back(newPosition);
8669 count -= need_space;
8671 if(count==0)
8672 return EQUIP_ERR_OK;
8676 return EQUIP_ERR_OK;
8679 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
8681 for(uint32 j = slot_begin; j < slot_end; j++)
8683 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8684 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8685 continue;
8687 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8689 // ignore move item (this slot will be empty at move)
8690 if(pItem2==pSrcItem)
8691 pItem2 = NULL;
8693 // if merge skip empty, if !merge skip non-empty
8694 if((pItem2!=NULL)!=merge)
8695 continue;
8697 if( pItem2 )
8699 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8701 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8702 if(need_space > count)
8703 need_space = count;
8704 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8705 if(!newPosition.isContainedIn(dest))
8707 dest.push_back(newPosition);
8708 count -= need_space;
8710 if(count==0)
8711 return EQUIP_ERR_OK;
8715 else
8717 uint32 need_space = pProto->Stackable;
8718 if(need_space > count)
8719 need_space = count;
8721 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8722 if(!newPosition.isContainedIn(dest))
8724 dest.push_back(newPosition);
8725 count -= need_space;
8727 if(count==0)
8728 return EQUIP_ERR_OK;
8732 return EQUIP_ERR_OK;
8735 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8737 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8739 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8740 if( !pProto )
8742 if(no_space_count)
8743 *no_space_count = count;
8744 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8747 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8749 if(no_space_count)
8750 *no_space_count = count;
8751 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8754 // check count of items (skip for auto move for same player from bank)
8755 uint32 no_similar_count = 0; // can't store this amount similar items
8756 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8757 if(res!=EQUIP_ERR_OK)
8759 if(count==no_similar_count)
8761 if(no_space_count)
8762 *no_space_count = no_similar_count;
8763 return res;
8765 count -= no_similar_count;
8768 // in specific slot
8769 if( bag != NULL_BAG && slot != NULL_SLOT )
8771 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8772 if(res!=EQUIP_ERR_OK)
8774 if(no_space_count)
8775 *no_space_count = count + no_similar_count;
8776 return res;
8779 if(count==0)
8781 if(no_similar_count==0)
8782 return EQUIP_ERR_OK;
8784 if(no_space_count)
8785 *no_space_count = count + no_similar_count;
8786 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8790 // not specific slot or have space for partly store only in specific slot
8792 // in specific bag
8793 if( bag != NULL_BAG )
8795 // search stack in bag for merge to
8796 if( pProto->Stackable > 1 )
8798 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8800 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8801 if(res!=EQUIP_ERR_OK)
8803 if(no_space_count)
8804 *no_space_count = count + no_similar_count;
8805 return res;
8808 if(count==0)
8810 if(no_similar_count==0)
8811 return EQUIP_ERR_OK;
8813 if(no_space_count)
8814 *no_space_count = count + no_similar_count;
8815 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8818 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8819 if(res!=EQUIP_ERR_OK)
8821 if(no_space_count)
8822 *no_space_count = count + no_similar_count;
8823 return res;
8826 if(count==0)
8828 if(no_similar_count==0)
8829 return EQUIP_ERR_OK;
8831 if(no_space_count)
8832 *no_space_count = count + no_similar_count;
8833 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8836 else // equipped bag
8838 // we need check 2 time (specilized/non_specialized), use NULL_BAG to prevent skipping bag
8839 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8840 if(res!=EQUIP_ERR_OK)
8841 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8843 if(res!=EQUIP_ERR_OK)
8845 if(no_space_count)
8846 *no_space_count = count + no_similar_count;
8847 return res;
8850 if(count==0)
8852 if(no_similar_count==0)
8853 return EQUIP_ERR_OK;
8855 if(no_space_count)
8856 *no_space_count = count + no_similar_count;
8857 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8862 // search free slot in bag for place to
8863 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8865 // search free slot - keyring case
8866 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8868 uint32 keyringSize = GetMaxKeyringSize();
8869 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8870 if(res!=EQUIP_ERR_OK)
8872 if(no_space_count)
8873 *no_space_count = count + no_similar_count;
8874 return res;
8877 if(count==0)
8879 if(no_similar_count==0)
8880 return EQUIP_ERR_OK;
8882 if(no_space_count)
8883 *no_space_count = count + no_similar_count;
8884 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8888 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8889 if(res!=EQUIP_ERR_OK)
8891 if(no_space_count)
8892 *no_space_count = count + no_similar_count;
8893 return res;
8896 if(count==0)
8898 if(no_similar_count==0)
8899 return EQUIP_ERR_OK;
8901 if(no_space_count)
8902 *no_space_count = count + no_similar_count;
8903 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8906 else // equipped bag
8908 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8909 if(res!=EQUIP_ERR_OK)
8910 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8912 if(res!=EQUIP_ERR_OK)
8914 if(no_space_count)
8915 *no_space_count = count + no_similar_count;
8916 return res;
8919 if(count==0)
8921 if(no_similar_count==0)
8922 return EQUIP_ERR_OK;
8924 if(no_space_count)
8925 *no_space_count = count + no_similar_count;
8926 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8931 // not specific bag or have space for partly store only in specific bag
8933 // search stack for merge to
8934 if( pProto->Stackable > 1 )
8936 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8937 if(res!=EQUIP_ERR_OK)
8939 if(no_space_count)
8940 *no_space_count = count + no_similar_count;
8941 return res;
8944 if(count==0)
8946 if(no_similar_count==0)
8947 return EQUIP_ERR_OK;
8949 if(no_space_count)
8950 *no_space_count = count + no_similar_count;
8951 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8954 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8955 if(res!=EQUIP_ERR_OK)
8957 if(no_space_count)
8958 *no_space_count = count + no_similar_count;
8959 return res;
8962 if(count==0)
8964 if(no_similar_count==0)
8965 return EQUIP_ERR_OK;
8967 if(no_space_count)
8968 *no_space_count = count + no_similar_count;
8969 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8972 if( pProto->BagFamily )
8974 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8976 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
8977 if(res!=EQUIP_ERR_OK)
8978 continue;
8980 if(count==0)
8982 if(no_similar_count==0)
8983 return EQUIP_ERR_OK;
8985 if(no_space_count)
8986 *no_space_count = count + no_similar_count;
8987 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8992 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8994 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
8995 if(res!=EQUIP_ERR_OK)
8996 continue;
8998 if(count==0)
9000 if(no_similar_count==0)
9001 return EQUIP_ERR_OK;
9003 if(no_space_count)
9004 *no_space_count = count + no_similar_count;
9005 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9010 // search free slot - special bag case
9011 if( pProto->BagFamily )
9013 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9015 uint32 keyringSize = GetMaxKeyringSize();
9016 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,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;
9035 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9037 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9038 if(res!=EQUIP_ERR_OK)
9039 continue;
9041 if(count==0)
9043 if(no_similar_count==0)
9044 return EQUIP_ERR_OK;
9046 if(no_space_count)
9047 *no_space_count = count + no_similar_count;
9048 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9053 // search free slot
9054 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9055 if(res!=EQUIP_ERR_OK)
9057 if(no_space_count)
9058 *no_space_count = count + no_similar_count;
9059 return res;
9062 if(count==0)
9064 if(no_similar_count==0)
9065 return EQUIP_ERR_OK;
9067 if(no_space_count)
9068 *no_space_count = count + no_similar_count;
9069 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9072 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9074 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9075 if(res!=EQUIP_ERR_OK)
9076 continue;
9078 if(count==0)
9080 if(no_similar_count==0)
9081 return EQUIP_ERR_OK;
9083 if(no_space_count)
9084 *no_space_count = count + no_similar_count;
9085 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9089 if(no_space_count)
9090 *no_space_count = count + no_similar_count;
9092 return EQUIP_ERR_INVENTORY_FULL;
9095 //////////////////////////////////////////////////////////////////////////
9096 uint8 Player::CanStoreItems( Item **pItems,int count) const
9098 Item *pItem2;
9100 // fill space table
9101 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9102 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9103 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9105 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9106 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9107 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9109 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9111 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9113 if (pItem2 && !pItem2->IsInTrade())
9115 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9119 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9121 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9123 if (pItem2 && !pItem2->IsInTrade())
9125 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9129 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9131 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9133 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9135 pItem2 = GetItemByPos( i, j );
9136 if (pItem2 && !pItem2->IsInTrade())
9138 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9144 // check free space for all items
9145 for (int k=0;k<count;k++)
9147 Item *pItem = pItems[k];
9149 // no item
9150 if (!pItem) continue;
9152 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9153 ItemPrototype const *pProto = pItem->GetProto();
9155 // strange item
9156 if( !pProto )
9157 return EQUIP_ERR_ITEM_NOT_FOUND;
9159 // item it 'bind'
9160 if(pItem->IsBindedNotWith(GetGUID()))
9161 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9163 Bag *pBag;
9164 ItemPrototype const *pBagProto;
9166 // item is 'one item only'
9167 uint8 res = CanTakeMoreSimilarItems(pItem);
9168 if(res != EQUIP_ERR_OK)
9169 return res;
9171 // search stack for merge to
9172 if( pProto->Stackable > 1 )
9174 bool b_found = false;
9176 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9178 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9179 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9181 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9182 b_found = true;
9183 break;
9186 if (b_found) continue;
9188 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9190 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9191 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9193 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9194 b_found = true;
9195 break;
9198 if (b_found) continue;
9200 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9202 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9203 if( pBag )
9205 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9207 pItem2 = GetItemByPos( t, j );
9208 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9210 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9211 b_found = true;
9212 break;
9217 if (b_found) continue;
9220 // special bag case
9221 if( pProto->BagFamily )
9223 bool b_found = false;
9224 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9226 uint32 keyringSize = GetMaxKeyringSize();
9227 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9229 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9231 inv_keys[t-KEYRING_SLOT_START] = 1;
9232 b_found = true;
9233 break;
9238 if (b_found) continue;
9240 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9242 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9243 if( pBag )
9245 pBagProto = pBag->GetProto();
9247 // not plain container check
9248 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9249 ItemCanGoIntoBag(pProto,pBagProto) )
9251 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9253 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9255 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9256 b_found = true;
9257 break;
9263 if (b_found) continue;
9266 // search free slot
9267 bool b_found = false;
9268 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9270 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9272 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9273 b_found = true;
9274 break;
9277 if (b_found) continue;
9279 // search free slot in bags
9280 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9282 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9283 if( pBag )
9285 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9287 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9289 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9290 b_found = true;
9291 break;
9297 // no free slot found?
9298 if (!b_found)
9299 return EQUIP_ERR_INVENTORY_FULL;
9302 return EQUIP_ERR_OK;
9305 //////////////////////////////////////////////////////////////////////////
9306 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9308 dest = 0;
9309 Item *pItem = Item::CreateItem( item, count, this );
9310 if( pItem )
9312 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9313 delete pItem;
9314 return result;
9317 return EQUIP_ERR_ITEM_NOT_FOUND;
9320 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9322 dest = 0;
9323 if( pItem )
9325 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9326 ItemPrototype const *pProto = pItem->GetProto();
9327 if( pProto )
9329 // May be here should be more stronger checks; STUNNED checked
9330 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9331 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9332 return EQUIP_ERR_YOU_ARE_STUNNED;
9334 if(pItem->IsBindedNotWith(GetGUID()))
9335 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9337 // check count of items (skip for auto move for same player from bank)
9338 uint8 res = CanTakeMoreSimilarItems(pItem);
9339 if(res != EQUIP_ERR_OK)
9340 return res;
9342 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9343 // - combat
9344 // - in-progress arenas
9345 if( !pProto->CanChangeEquipStateInCombat() )
9347 if( isInCombat() )
9348 return EQUIP_ERR_NOT_IN_COMBAT;
9350 if(BattleGround* bg = GetBattleGround())
9351 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9352 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9355 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9356 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9358 if(IsNonMeleeSpellCasted(false))
9359 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9361 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9362 if( eslot == NULL_SLOT )
9363 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9365 uint8 msg = CanUseItem( pItem , not_loading );
9366 if( msg != EQUIP_ERR_OK )
9367 return msg;
9368 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9369 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9371 // check unique-equipped on item
9372 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9374 // there is an equip limit on this item
9375 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9376 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9377 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9380 // check unique-equipped on gems
9381 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9383 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9384 if(!enchant_id)
9385 continue;
9386 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9387 if(!enchantEntry)
9388 continue;
9390 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9391 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9393 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9394 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9395 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9399 // check unique-equipped special item classes
9400 if (pProto->Class == ITEM_CLASS_QUIVER)
9402 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9404 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9406 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9408 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9409 (!swap || pBag->GetSlot() != eslot ) )
9411 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9412 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9413 else
9414 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9421 uint32 type = pProto->InventoryType;
9423 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9425 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9427 if(!CanDualWield())
9428 return EQUIP_ERR_CANT_DUAL_WIELD;
9431 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9432 if(mainItem)
9434 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9435 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9439 // equip two-hand weapon case (with possible unequip 2 items)
9440 if( type == INVTYPE_2HWEAPON )
9442 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9443 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9445 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9446 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9447 ItemPosCountVec off_dest;
9448 if( offItem && (!not_loading ||
9449 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9450 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9451 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9453 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9454 return EQUIP_ERR_OK;
9457 if( !swap )
9458 return EQUIP_ERR_ITEM_NOT_FOUND;
9459 else
9460 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9463 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9465 // Applied only to equipped items and bank bags
9466 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9467 return EQUIP_ERR_OK;
9469 Item* pItem = GetItemByPos(pos);
9471 // Applied only to existed equipped item
9472 if( !pItem )
9473 return EQUIP_ERR_OK;
9475 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9477 ItemPrototype const *pProto = pItem->GetProto();
9478 if( !pProto )
9479 return EQUIP_ERR_ITEM_NOT_FOUND;
9481 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9482 // - combat
9483 // - in-progress arenas
9484 if( !pProto->CanChangeEquipStateInCombat() )
9486 if( isInCombat() )
9487 return EQUIP_ERR_NOT_IN_COMBAT;
9489 if(BattleGround* bg = GetBattleGround())
9490 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9491 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9494 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9495 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9497 return EQUIP_ERR_OK;
9500 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9502 if( !pItem )
9503 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9505 uint32 count = pItem->GetCount();
9507 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9508 ItemPrototype const *pProto = pItem->GetProto();
9509 if( !pProto )
9510 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9512 if( pItem->IsBindedNotWith(GetGUID()) )
9513 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9515 // check count of items (skip for auto move for same player from bank)
9516 uint8 res = CanTakeMoreSimilarItems(pItem);
9517 if(res != EQUIP_ERR_OK)
9518 return res;
9520 // in specific slot
9521 if( bag != NULL_BAG && slot != NULL_SLOT )
9523 if( pProto->InventoryType == INVTYPE_BAG )
9525 Bag *pBag = (Bag*)pItem;
9526 if( pBag )
9528 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9530 if( !HasBankBagSlot( slot ) )
9531 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9532 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9533 return cantuse;
9535 else
9537 if( !pBag->IsEmpty() )
9538 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9542 else
9544 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9545 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9548 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9549 if(res!=EQUIP_ERR_OK)
9550 return res;
9552 if(count==0)
9553 return EQUIP_ERR_OK;
9556 // not specific slot or have space for partly store only in specific slot
9558 // in specific bag
9559 if( bag != NULL_BAG )
9561 if( pProto->InventoryType == INVTYPE_BAG )
9563 Bag *pBag = (Bag*)pItem;
9564 if( pBag && !pBag->IsEmpty() )
9565 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9568 // search stack in bag for merge to
9569 if( pProto->Stackable > 1 )
9571 if( bag == INVENTORY_SLOT_BAG_0 )
9573 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9574 if(res!=EQUIP_ERR_OK)
9575 return res;
9577 if(count==0)
9578 return EQUIP_ERR_OK;
9580 else
9582 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9583 if(res!=EQUIP_ERR_OK)
9584 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9586 if(res!=EQUIP_ERR_OK)
9587 return res;
9589 if(count==0)
9590 return EQUIP_ERR_OK;
9594 // search free slot in bag
9595 if( bag == INVENTORY_SLOT_BAG_0 )
9597 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9598 if(res!=EQUIP_ERR_OK)
9599 return res;
9601 if(count==0)
9602 return EQUIP_ERR_OK;
9604 else
9606 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9607 if(res!=EQUIP_ERR_OK)
9608 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9610 if(res!=EQUIP_ERR_OK)
9611 return res;
9613 if(count==0)
9614 return EQUIP_ERR_OK;
9618 // not specific bag or have space for partly store only in specific bag
9620 // search stack for merge to
9621 if( pProto->Stackable > 1 )
9623 // in slots
9624 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9625 if(res!=EQUIP_ERR_OK)
9626 return res;
9628 if(count==0)
9629 return EQUIP_ERR_OK;
9631 // in special bags
9632 if( pProto->BagFamily )
9634 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9636 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9637 if(res!=EQUIP_ERR_OK)
9638 continue;
9640 if(count==0)
9641 return EQUIP_ERR_OK;
9645 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9647 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9648 if(res!=EQUIP_ERR_OK)
9649 continue;
9651 if(count==0)
9652 return EQUIP_ERR_OK;
9656 // search free place in special bag
9657 if( pProto->BagFamily )
9659 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9661 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9662 if(res!=EQUIP_ERR_OK)
9663 continue;
9665 if(count==0)
9666 return EQUIP_ERR_OK;
9670 // search free space
9671 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9672 if(res!=EQUIP_ERR_OK)
9673 return res;
9675 if(count==0)
9676 return EQUIP_ERR_OK;
9678 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9680 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9681 if(res!=EQUIP_ERR_OK)
9682 continue;
9684 if(count==0)
9685 return EQUIP_ERR_OK;
9687 return EQUIP_ERR_BANK_FULL;
9690 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9692 if( pItem )
9694 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9695 if( !isAlive() && not_loading )
9696 return EQUIP_ERR_YOU_ARE_DEAD;
9697 //if( isStunned() )
9698 // return EQUIP_ERR_YOU_ARE_STUNNED;
9699 ItemPrototype const *pProto = pItem->GetProto();
9700 if( pProto )
9702 if( pItem->IsBindedNotWith(GetGUID()) )
9703 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9704 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9705 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9706 if( pItem->GetSkill() != 0 )
9708 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9709 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9711 if( pProto->RequiredSkill != 0 )
9713 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9714 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9715 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9716 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9718 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9719 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9720 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9721 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9722 if( getLevel() < pProto->RequiredLevel )
9723 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9724 return EQUIP_ERR_OK;
9727 return EQUIP_ERR_ITEM_NOT_FOUND;
9730 bool Player::CanUseItem( ItemPrototype const *pProto )
9732 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9734 if( pProto )
9736 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9737 return false;
9738 if( pProto->RequiredSkill != 0 )
9740 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9741 return false;
9742 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9743 return false;
9745 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9746 return false;
9747 if( getLevel() < pProto->RequiredLevel )
9748 return false;
9749 return true;
9751 return false;
9754 uint8 Player::CanUseAmmo( uint32 item ) const
9756 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9757 if( !isAlive() )
9758 return EQUIP_ERR_YOU_ARE_DEAD;
9759 //if( isStunned() )
9760 // return EQUIP_ERR_YOU_ARE_STUNNED;
9761 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9762 if( pProto )
9764 if( pProto->InventoryType!= INVTYPE_AMMO )
9765 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9766 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9767 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9768 if( pProto->RequiredSkill != 0 )
9770 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9771 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9772 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9773 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9775 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9776 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9777 /*if( GetReputation() < pProto->RequiredReputation )
9778 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9780 if( getLevel() < pProto->RequiredLevel )
9781 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9783 // Requires No Ammo
9784 if(GetDummyAura(46699))
9785 return EQUIP_ERR_BAG_FULL6;
9787 return EQUIP_ERR_OK;
9789 return EQUIP_ERR_ITEM_NOT_FOUND;
9792 void Player::SetAmmo( uint32 item )
9794 if(!item)
9795 return;
9797 // already set
9798 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9799 return;
9801 // check ammo
9802 if(item)
9804 uint8 msg = CanUseAmmo( item );
9805 if( msg != EQUIP_ERR_OK )
9807 SendEquipError( msg, NULL, NULL );
9808 return;
9812 SetUInt32Value(PLAYER_AMMO_ID, item);
9814 _ApplyAmmoBonuses();
9817 void Player::RemoveAmmo()
9819 SetUInt32Value(PLAYER_AMMO_ID, 0);
9821 m_ammoDPS = 0.0f;
9823 if(CanModifyStats())
9824 UpdateDamagePhysical(RANGED_ATTACK);
9827 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9828 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9830 uint32 count = 0;
9831 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9832 count += itr->count;
9834 Item *pItem = Item::CreateItem( item, count, this );
9835 if( pItem )
9837 ItemAddedQuestCheck( item, count );
9838 if(randomPropertyId)
9839 pItem->SetItemRandomProperties(randomPropertyId);
9840 pItem = StoreItem( dest, pItem, update );
9842 return pItem;
9845 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9847 if( !pItem )
9848 return NULL;
9850 Item* lastItem = pItem;
9852 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9854 uint16 pos = itr->pos;
9855 uint32 count = itr->count;
9857 ++itr;
9859 if(itr == dest.end())
9861 lastItem = _StoreItem(pos,pItem,count,false,update);
9862 break;
9865 lastItem = _StoreItem(pos,pItem,count,true,update);
9868 return lastItem;
9871 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9872 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
9874 if( !pItem )
9875 return NULL;
9877 uint8 bag = pos >> 8;
9878 uint8 slot = pos & 255;
9880 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
9882 Item *pItem2 = GetItemByPos( bag, slot );
9884 if( !pItem2 )
9886 if(clone)
9887 pItem = pItem->CloneItem(count,this);
9888 else
9889 pItem->SetCount(count);
9891 if(!pItem)
9892 return NULL;
9894 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9895 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
9896 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9897 pItem->SetBinding( true );
9899 if( bag == INVENTORY_SLOT_BAG_0 )
9901 m_items[slot] = pItem;
9902 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
9903 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
9904 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
9906 pItem->SetSlot( slot );
9907 pItem->SetContainer( NULL );
9909 if( IsInWorld() && update )
9911 pItem->AddToWorld();
9912 pItem->SendUpdateToPlayer( this );
9915 pItem->SetState(ITEM_CHANGED, this);
9917 else
9919 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9920 if( pBag )
9922 pBag->StoreItem( slot, pItem, update );
9923 if( IsInWorld() && update )
9925 pItem->AddToWorld();
9926 pItem->SendUpdateToPlayer( this );
9928 pItem->SetState(ITEM_CHANGED, this);
9929 pBag->SetState(ITEM_CHANGED, this);
9933 AddEnchantmentDurations(pItem);
9934 AddItemDurations(pItem);
9936 return pItem;
9938 else
9940 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9941 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
9942 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9943 pItem2->SetBinding( true );
9945 pItem2->SetCount( pItem2->GetCount() + count );
9946 if( IsInWorld() && update )
9947 pItem2->SendUpdateToPlayer( this );
9949 if(!clone)
9951 // delete item (it not in any slot currently)
9952 if( IsInWorld() && update )
9954 pItem->RemoveFromWorld();
9955 pItem->DestroyForPlayer( this );
9958 RemoveEnchantmentDurations(pItem);
9959 RemoveItemDurations(pItem);
9961 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9962 pItem->SetState(ITEM_REMOVED, this);
9964 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
9965 AddEnchantmentDurations(pItem2);
9967 pItem2->SetState(ITEM_CHANGED, this);
9969 return pItem2;
9973 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
9975 Item *pItem = Item::CreateItem( item, count, this );
9976 if( pItem )
9978 ItemAddedQuestCheck( item, count );
9979 Item * retItem = EquipItem( pos, pItem, update );
9981 return retItem;
9983 return NULL;
9986 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
9988 if( pItem )
9990 AddEnchantmentDurations(pItem);
9991 AddItemDurations(pItem);
9993 uint8 bag = pos >> 8;
9994 uint8 slot = pos & 255;
9996 Item *pItem2 = GetItemByPos( bag, slot );
9998 if( !pItem2 )
10000 VisualizeItem( slot, pItem);
10002 if(isAlive())
10004 ItemPrototype const *pProto = pItem->GetProto();
10006 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10007 if(pProto && pProto->ItemSet)
10008 AddItemsSetItem(this,pItem);
10010 _ApplyItemMods(pItem, slot, true);
10012 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10014 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10016 if (getClass() == CLASS_ROGUE)
10017 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10019 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10021 if (!spellProto)
10022 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10023 else
10025 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10027 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10028 data << uint64(GetGUID());
10029 data << uint8(1);
10030 data << uint32(cooldownSpell);
10031 data << uint32(0);
10032 GetSession()->SendPacket(&data);
10037 if( IsInWorld() && update )
10039 pItem->AddToWorld();
10040 pItem->SendUpdateToPlayer( this );
10043 ApplyEquipCooldown(pItem);
10045 if( slot == EQUIPMENT_SLOT_MAINHAND )
10046 UpdateExpertise(BASE_ATTACK);
10047 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10048 UpdateExpertise(OFF_ATTACK);
10050 else
10052 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10053 if( IsInWorld() && update )
10054 pItem2->SendUpdateToPlayer( this );
10056 // delete item (it not in any slot currently)
10057 //pItem->DeleteFromDB();
10058 if( IsInWorld() && update )
10060 pItem->RemoveFromWorld();
10061 pItem->DestroyForPlayer( this );
10064 RemoveEnchantmentDurations(pItem);
10065 RemoveItemDurations(pItem);
10067 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10068 pItem->SetState(ITEM_REMOVED, this);
10069 pItem2->SetState(ITEM_CHANGED, this);
10071 ApplyEquipCooldown(pItem2);
10073 return pItem2;
10077 return pItem;
10080 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10082 if( pItem )
10084 AddEnchantmentDurations(pItem);
10085 AddItemDurations(pItem);
10087 uint8 slot = pos & 255;
10088 VisualizeItem( slot, pItem);
10090 if( IsInWorld() )
10092 pItem->AddToWorld();
10093 pItem->SendUpdateToPlayer( this );
10098 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10100 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10101 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10102 // entry // Size: 1
10103 // inspected enchantments // Size: 6
10104 // ? // Size: 5
10105 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10106 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10107 // // = 16
10109 if(pItem)
10111 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10113 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10114 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10116 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10117 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10119 // Use SetInt16Value to prevent set high part to FFFF for negative value
10120 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10121 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10123 else
10125 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10127 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10128 SetUInt32Value(VisibleBase + 0, 0);
10130 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10131 SetUInt32Value(VisibleBase + 1 + i, 0);
10133 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10134 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10138 void Player::VisualizeItem( uint8 slot, Item *pItem)
10140 if(!pItem)
10141 return;
10143 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10144 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10145 pItem->SetBinding( true );
10147 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10149 m_items[slot] = pItem;
10150 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10151 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10152 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10153 pItem->SetSlot( slot );
10154 pItem->SetContainer( NULL );
10156 if( slot < EQUIPMENT_SLOT_END )
10157 SetVisibleItemSlot(slot,pItem);
10159 pItem->SetState(ITEM_CHANGED, this);
10162 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10164 // note: removeitem does not actually change the item
10165 // it only takes the item out of storage temporarily
10166 // note2: if removeitem is to be used for delinking
10167 // the item must be removed from the player's updatequeue
10169 Item *pItem = GetItemByPos( bag, slot );
10170 if( pItem )
10172 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10174 RemoveEnchantmentDurations(pItem);
10175 RemoveItemDurations(pItem);
10177 if( bag == INVENTORY_SLOT_BAG_0 )
10179 if ( slot < INVENTORY_SLOT_BAG_END )
10181 ItemPrototype const *pProto = pItem->GetProto();
10182 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10184 if(pProto && pProto->ItemSet)
10185 RemoveItemsSetItem(this,pProto);
10187 _ApplyItemMods(pItem, slot, false);
10189 // remove item dependent auras and casts (only weapon and armor slots)
10190 if(slot < EQUIPMENT_SLOT_END)
10191 RemoveItemDependentAurasAndCasts(pItem);
10193 // remove held enchantments
10194 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10196 if (pItem->GetItemSuffixFactor())
10198 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10199 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10201 else
10203 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10204 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10209 m_items[slot] = NULL;
10210 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10212 if ( slot < EQUIPMENT_SLOT_END )
10213 SetVisibleItemSlot(slot,NULL);
10215 else
10217 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10218 if( pBag )
10219 pBag->RemoveItem(slot, update);
10221 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10222 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10223 pItem->SetSlot( NULL_SLOT );
10224 if( IsInWorld() && update )
10225 pItem->SendUpdateToPlayer( this );
10227 if( slot == EQUIPMENT_SLOT_MAINHAND )
10228 UpdateExpertise(BASE_ATTACK);
10229 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10230 UpdateExpertise(OFF_ATTACK);
10234 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10235 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10237 if(Item* it = GetItemByPos(bag,slot))
10239 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10240 RemoveItem( bag,slot,update);
10241 it->RemoveFromUpdateQueueOf(this);
10242 if(it->IsInWorld())
10244 it->RemoveFromWorld();
10245 it->DestroyForPlayer( this );
10250 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10251 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10253 // update quest counters
10254 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10256 // store item
10257 Item* pLastItem = StoreItem( dest, pItem, update);
10259 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10260 if(pLastItem==pItem)
10262 // update owner for last item (this can be original item with wrong owner
10263 if(pLastItem->GetOwnerGUID() != GetGUID())
10264 pLastItem->SetOwnerGUID(GetGUID());
10266 // if this original item then it need create record in inventory
10267 // in case trade we already have item in other player inventory
10268 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10272 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10274 Item *pItem = GetItemByPos( bag, slot );
10275 if( pItem )
10277 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10279 // start from destroy contained items (only equipped bag can have its)
10280 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10282 for (int i = 0; i < MAX_BAG_SIZE; i++)
10283 DestroyItem(slot,i,update);
10286 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10287 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10289 RemoveEnchantmentDurations(pItem);
10290 RemoveItemDurations(pItem);
10292 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10294 if( bag == INVENTORY_SLOT_BAG_0 )
10297 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10299 // equipment and equipped bags can have applied bonuses
10300 if ( slot < INVENTORY_SLOT_BAG_END )
10302 ItemPrototype const *pProto = pItem->GetProto();
10304 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10305 if(pProto && pProto->ItemSet)
10306 RemoveItemsSetItem(this,pProto);
10308 _ApplyItemMods(pItem, slot, false);
10311 if ( slot < EQUIPMENT_SLOT_END )
10313 // remove item dependent auras and casts (only weapon and armor slots)
10314 RemoveItemDependentAurasAndCasts(pItem);
10316 // equipment visual show
10317 SetVisibleItemSlot(slot,NULL);
10320 m_items[slot] = NULL;
10322 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10323 pBag->RemoveItem(slot, update);
10325 if( IsInWorld() && update )
10327 pItem->RemoveFromWorld();
10328 pItem->DestroyForPlayer(this);
10331 //pItem->SetOwnerGUID(0);
10332 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10333 pItem->SetSlot( NULL_SLOT );
10334 pItem->SetState(ITEM_REMOVED, this);
10338 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10340 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10341 Item *pItem;
10342 ItemPrototype const *pProto;
10343 uint32 remcount = 0;
10345 // in inventory
10346 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10348 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10349 if( pItem && pItem->GetEntry() == item )
10351 if( pItem->GetCount() + remcount <= count )
10353 // all items in inventory can unequipped
10354 remcount += pItem->GetCount();
10355 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10357 if(remcount >=count)
10358 return;
10360 else
10362 pProto = pItem->GetProto();
10363 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10364 pItem->SetCount( pItem->GetCount() - count + remcount );
10365 if( IsInWorld() & update )
10366 pItem->SendUpdateToPlayer( this );
10367 pItem->SetState(ITEM_CHANGED, this);
10368 return;
10372 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10374 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10375 if( pItem && pItem->GetEntry() == item )
10377 if( pItem->GetCount() + remcount <= count )
10379 // all keys can be unequipped
10380 remcount += pItem->GetCount();
10381 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10383 if(remcount >=count)
10384 return;
10386 else
10388 pProto = pItem->GetProto();
10389 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10390 pItem->SetCount( pItem->GetCount() - count + remcount );
10391 if( IsInWorld() & update )
10392 pItem->SendUpdateToPlayer( this );
10393 pItem->SetState(ITEM_CHANGED, this);
10394 return;
10399 // in inventory bags
10400 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10402 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10404 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10406 pItem = pBag->GetItemByPos(j);
10407 if( pItem && pItem->GetEntry() == item )
10409 // all items in bags can be unequipped
10410 if( pItem->GetCount() + remcount <= count )
10412 remcount += pItem->GetCount();
10413 DestroyItem( i, j, update );
10415 if(remcount >=count)
10416 return;
10418 else
10420 pProto = pItem->GetProto();
10421 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10422 pItem->SetCount( pItem->GetCount() - count + remcount );
10423 if( IsInWorld() && update )
10424 pItem->SendUpdateToPlayer( this );
10425 pItem->SetState(ITEM_CHANGED, this);
10426 return;
10433 // in equipment and bag list
10434 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10436 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10437 if( pItem && pItem->GetEntry() == item )
10439 if( pItem->GetCount() + remcount <= count )
10441 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10443 remcount += pItem->GetCount();
10444 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10446 if(remcount >=count)
10447 return;
10450 else
10452 pProto = pItem->GetProto();
10453 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10454 pItem->SetCount( pItem->GetCount() - count + remcount );
10455 if( IsInWorld() & update )
10456 pItem->SendUpdateToPlayer( this );
10457 pItem->SetState(ITEM_CHANGED, this);
10458 return;
10464 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10466 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10468 // in inventory
10469 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10471 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10472 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10473 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10475 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10477 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10478 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10479 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10482 // in inventory bags
10483 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10485 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10486 if( pBag )
10488 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10490 Item* pItem = pBag->GetItemByPos(j);
10491 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10492 DestroyItem( i, j, update);
10497 // in equipment and bag list
10498 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10500 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10501 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10502 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10506 void Player::DestroyConjuredItems( bool update )
10508 // used when entering arena
10509 // destroys all conjured items
10510 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10512 // in inventory
10513 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10515 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10516 if( pItem && pItem->GetProto() &&
10517 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10518 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10519 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10522 // in inventory bags
10523 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10525 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10526 if( pBag )
10528 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10530 Item* pItem = pBag->GetItemByPos(j);
10531 if( pItem && pItem->GetProto() &&
10532 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10533 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10534 DestroyItem( i, j, update);
10539 // in equipment and bag list
10540 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10542 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10543 if( pItem && pItem->GetProto() &&
10544 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10545 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10546 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10550 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10552 if(!pItem)
10553 return;
10555 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10557 if( pItem->GetCount() <= count )
10559 count-= pItem->GetCount();
10561 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10563 else
10565 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10566 pItem->SetCount( pItem->GetCount() - count );
10567 count = 0;
10568 if( IsInWorld() & update )
10569 pItem->SendUpdateToPlayer( this );
10570 pItem->SetState(ITEM_CHANGED, this);
10574 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10576 uint8 srcbag = src >> 8;
10577 uint8 srcslot = src & 255;
10579 uint8 dstbag = dst >> 8;
10580 uint8 dstslot = dst & 255;
10582 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10583 if( !pSrcItem )
10585 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10586 return;
10589 // not let split all items (can be only at cheating)
10590 if(pSrcItem->GetCount() == count)
10592 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10593 return;
10596 // not let split more existed items (can be only at cheating)
10597 if(pSrcItem->GetCount() < count)
10599 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10600 return;
10603 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10605 //best error message found for attempting to split while looting
10606 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10607 return;
10610 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10611 Item *pNewItem = pSrcItem->CloneItem( count, this );
10612 if( !pNewItem )
10614 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10615 return;
10618 if( IsInventoryPos( dst ) )
10620 // change item amount before check (for unique max count check)
10621 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10623 ItemPosCountVec dest;
10624 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10625 if( msg != EQUIP_ERR_OK )
10627 delete pNewItem;
10628 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10629 SendEquipError( msg, pSrcItem, NULL );
10630 return;
10633 if( IsInWorld() )
10634 pSrcItem->SendUpdateToPlayer( this );
10635 pSrcItem->SetState(ITEM_CHANGED, this);
10636 StoreItem( dest, pNewItem, true);
10638 else if( IsBankPos ( dst ) )
10640 // change item amount before check (for unique max count check)
10641 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10643 ItemPosCountVec dest;
10644 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10645 if( msg != EQUIP_ERR_OK )
10647 delete pNewItem;
10648 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10649 SendEquipError( msg, pSrcItem, NULL );
10650 return;
10653 if( IsInWorld() )
10654 pSrcItem->SendUpdateToPlayer( this );
10655 pSrcItem->SetState(ITEM_CHANGED, this);
10656 BankItem( dest, pNewItem, true);
10658 else if( IsEquipmentPos ( dst ) )
10660 // change item amount before check (for unique max count check), provide space for splitted items
10661 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10663 uint16 dest;
10664 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10665 if( msg != EQUIP_ERR_OK )
10667 delete pNewItem;
10668 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10669 SendEquipError( msg, pSrcItem, NULL );
10670 return;
10673 if( IsInWorld() )
10674 pSrcItem->SendUpdateToPlayer( this );
10675 pSrcItem->SetState(ITEM_CHANGED, this);
10676 EquipItem( dest, pNewItem, true);
10677 AutoUnequipOffhandIfNeed();
10681 void Player::SwapItem( uint16 src, uint16 dst )
10683 uint8 srcbag = src >> 8;
10684 uint8 srcslot = src & 255;
10686 uint8 dstbag = dst >> 8;
10687 uint8 dstslot = dst & 255;
10689 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10690 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10692 if( !pSrcItem )
10693 return;
10695 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10697 if(!isAlive() )
10699 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10700 return;
10703 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10705 //best error message found for attempting to swap while looting
10706 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10707 return;
10710 // check unequip potability for equipped items and bank bags
10711 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10713 // bags can be swapped with empty bag slots
10714 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10715 if(msg != EQUIP_ERR_OK)
10717 SendEquipError( msg, pSrcItem, pDstItem );
10718 return;
10722 // prevent put equipped/bank bag in self
10723 if( IsBagPos ( src ) && srcslot == dstbag)
10725 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10726 return;
10729 if( !pDstItem )
10731 if( IsInventoryPos( dst ) )
10733 ItemPosCountVec dest;
10734 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10735 if( msg != EQUIP_ERR_OK )
10737 SendEquipError( msg, pSrcItem, NULL );
10738 return;
10741 RemoveItem(srcbag, srcslot, true);
10742 StoreItem( dest, pSrcItem, true);
10744 else if( IsBankPos ( dst ) )
10746 ItemPosCountVec dest;
10747 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10748 if( msg != EQUIP_ERR_OK )
10750 SendEquipError( msg, pSrcItem, NULL );
10751 return;
10754 RemoveItem(srcbag, srcslot, true);
10755 BankItem( dest, pSrcItem, true);
10757 else if( IsEquipmentPos ( dst ) )
10759 uint16 dest;
10760 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10761 if( msg != EQUIP_ERR_OK )
10763 SendEquipError( msg, pSrcItem, NULL );
10764 return;
10767 RemoveItem(srcbag, srcslot, true);
10768 EquipItem( dest, pSrcItem, true);
10769 AutoUnequipOffhandIfNeed();
10772 else // if (!pDstItem)
10774 if(pDstItem->m_lootGenerated) // prevent swap looting item
10776 //best error message found for attempting to swap while looting
10777 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10778 return;
10781 // check unequip potability for equipped items and bank bags
10782 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10784 // bags can be swapped with empty bag slots
10785 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
10786 if(msg != EQUIP_ERR_OK)
10788 SendEquipError( msg, pSrcItem, pDstItem );
10789 return;
10793 // attempt merge to / fill target item
10795 uint8 msg;
10796 ItemPosCountVec sDest;
10797 uint16 eDest;
10798 if( IsInventoryPos( dst ) )
10799 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10800 else if( IsBankPos ( dst ) )
10801 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10802 else if( IsEquipmentPos ( dst ) )
10803 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10804 else
10805 return;
10807 // can be merge/fill
10808 if(msg == EQUIP_ERR_OK)
10810 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
10812 RemoveItem(srcbag, srcslot, true);
10814 if( IsInventoryPos( dst ) )
10815 StoreItem( sDest, pSrcItem, true);
10816 else if( IsBankPos ( dst ) )
10817 BankItem( sDest, pSrcItem, true);
10818 else if( IsEquipmentPos ( dst ) )
10820 EquipItem( eDest, pSrcItem, true);
10821 AutoUnequipOffhandIfNeed();
10824 else
10826 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
10827 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
10828 pSrcItem->SetState(ITEM_CHANGED, this);
10829 pDstItem->SetState(ITEM_CHANGED, this);
10830 if( IsInWorld() )
10832 pSrcItem->SendUpdateToPlayer( this );
10833 pDstItem->SendUpdateToPlayer( this );
10836 return;
10840 // impossible merge/fill, do real swap
10841 uint8 msg;
10843 // check src->dest move possibility
10844 ItemPosCountVec sDest;
10845 uint16 eDest;
10846 if( IsInventoryPos( dst ) )
10847 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10848 else if( IsBankPos( dst ) )
10849 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10850 else if( IsEquipmentPos( dst ) )
10852 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10853 if( msg == EQUIP_ERR_OK )
10854 msg = CanUnequipItem( eDest, true );
10857 if( msg != EQUIP_ERR_OK )
10859 SendEquipError( msg, pSrcItem, pDstItem );
10860 return;
10863 // check dest->src move possibility
10864 ItemPosCountVec sDest2;
10865 uint16 eDest2;
10866 if( IsInventoryPos( src ) )
10867 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10868 else if( IsBankPos( src ) )
10869 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10870 else if( IsEquipmentPos( src ) )
10872 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10873 if( msg == EQUIP_ERR_OK )
10874 msg = CanUnequipItem( eDest2, true);
10877 if( msg != EQUIP_ERR_OK )
10879 SendEquipError( msg, pDstItem, pSrcItem );
10880 return;
10883 // now do moves, remove...
10884 RemoveItem(dstbag, dstslot, false);
10885 RemoveItem(srcbag, srcslot, false);
10887 // add to dest
10888 if( IsInventoryPos( dst ) )
10889 StoreItem(sDest, pSrcItem, true);
10890 else if( IsBankPos( dst ) )
10891 BankItem(sDest, pSrcItem, true);
10892 else if( IsEquipmentPos( dst ) )
10893 EquipItem(eDest, pSrcItem, true);
10895 // add to src
10896 if( IsInventoryPos( src ) )
10897 StoreItem(sDest2, pDstItem, true);
10898 else if( IsBankPos( src ) )
10899 BankItem(sDest2, pDstItem, true);
10900 else if( IsEquipmentPos( src ) )
10901 EquipItem(eDest2, pDstItem, true);
10903 AutoUnequipOffhandIfNeed();
10907 void Player::AddItemToBuyBackSlot( Item *pItem )
10909 if( pItem )
10911 uint32 slot = m_currentBuybackSlot;
10912 // if current back slot non-empty search oldest or free
10913 if(m_items[slot])
10915 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
10916 uint32 oldest_slot = BUYBACK_SLOT_START;
10918 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
10920 // found empty
10921 if(!m_items[i])
10923 slot = i;
10924 break;
10927 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
10929 if(oldest_time > i_time)
10931 oldest_time = i_time;
10932 oldest_slot = i;
10936 // find oldest
10937 slot = oldest_slot;
10940 RemoveItemFromBuyBackSlot( slot, true );
10941 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
10943 m_items[slot] = pItem;
10944 time_t base = time(NULL);
10945 uint32 etime = uint32(base - m_logintime + (30 * 3600));
10946 uint32 eslot = slot - BUYBACK_SLOT_START;
10948 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
10949 ItemPrototype const *pProto = pItem->GetProto();
10950 if( pProto )
10951 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
10952 else
10953 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10954 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
10956 // move to next (for non filled list is move most optimized choice)
10957 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
10958 ++m_currentBuybackSlot;
10962 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
10964 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
10965 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10966 return m_items[slot];
10967 return NULL;
10970 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
10972 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
10973 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10975 Item *pItem = m_items[slot];
10976 if( pItem )
10978 pItem->RemoveFromWorld();
10979 if(del) pItem->SetState(ITEM_REMOVED, this);
10982 m_items[slot] = NULL;
10984 uint32 eslot = slot - BUYBACK_SLOT_START;
10985 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
10986 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10987 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
10989 // if current backslot is filled set to now free slot
10990 if(m_items[m_currentBuybackSlot])
10991 m_currentBuybackSlot = slot;
10995 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
10997 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
10998 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
10999 data << uint8(msg);
11001 if(msg)
11003 data << uint64(pItem ? pItem->GetGUID() : 0);
11004 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11005 data << uint8(0); // not 0 there...
11007 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11009 uint32 level = 0;
11011 if(pItem)
11012 if(ItemPrototype const* proto = pItem->GetProto())
11013 level = proto->RequiredLevel;
11015 data << uint32(level); // new 2.4.0
11018 GetSession()->SendPacket(&data);
11021 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11023 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11024 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11025 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11026 data << uint32(item);
11027 if( param > 0 )
11028 data << uint32(param);
11029 data << uint8(msg);
11030 GetSession()->SendPacket(&data);
11033 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11035 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11036 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11037 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11038 data << uint64(guid);
11039 if( param > 0 )
11040 data << uint32(param);
11041 data << uint8(msg);
11042 GetSession()->SendPacket(&data);
11045 void Player::ClearTrade()
11047 tradeGold = 0;
11048 acceptTrade = false;
11049 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11050 tradeItems[i] = NULL_SLOT;
11053 void Player::TradeCancel(bool sendback)
11055 if(pTrader)
11057 // send yellow "Trade canceled" message to both traders
11058 WorldSession* ws;
11059 ws = GetSession();
11060 if(sendback)
11061 ws->SendCancelTrade();
11062 ws = pTrader->GetSession();
11063 if(!ws->PlayerLogout())
11064 ws->SendCancelTrade();
11066 // cleanup
11067 ClearTrade();
11068 pTrader->ClearTrade();
11069 // prevent loss of reference
11070 pTrader->pTrader = NULL;
11071 pTrader = NULL;
11075 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11077 if(m_itemDuration.empty())
11078 return;
11080 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11082 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11084 Item* item = *itr;
11085 ++itr; // current element can be erased in UpdateDuration
11087 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11088 item->UpdateDuration(this,time);
11092 void Player::UpdateEnchantTime(uint32 time)
11094 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11096 assert(itr->item);
11097 next=itr;
11098 if(!itr->item->GetEnchantmentId(itr->slot))
11100 next = m_enchantDuration.erase(itr);
11102 else if(itr->leftduration <= time)
11104 ApplyEnchantment(itr->item,itr->slot,false,false);
11105 itr->item->ClearEnchantment(itr->slot);
11106 next = m_enchantDuration.erase(itr);
11108 else if(itr->leftduration > time)
11110 itr->leftduration -= time;
11111 ++next;
11116 void Player::AddEnchantmentDurations(Item *item)
11118 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11120 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11121 continue;
11123 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11124 if( duration > 0 )
11125 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11129 void Player::RemoveEnchantmentDurations(Item *item)
11131 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11133 if(itr->item == item)
11135 // save duration in item
11136 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11137 itr = m_enchantDuration.erase(itr);
11139 else
11140 ++itr;
11144 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11146 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11147 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11149 next = itr;
11150 if(itr->slot==slot)
11152 if(itr->item && itr->item->GetEnchantmentId(slot))
11154 // remove from stats
11155 ApplyEnchantment(itr->item,slot,false,false);
11156 // remove visual
11157 itr->item->ClearEnchantment(slot);
11159 // remove from update list
11160 next = m_enchantDuration.erase(itr);
11162 else
11163 ++next;
11166 // remove enchants from inventory items
11167 // NOTE: no need to remove these from stats, since these aren't equipped
11168 // in inventory
11169 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11171 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11172 if( pItem && pItem->GetEnchantmentId(slot) )
11173 pItem->ClearEnchantment(slot);
11176 // in inventory bags
11177 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11179 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11180 if( pBag )
11182 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11184 Item* pItem = pBag->GetItemByPos(j);
11185 if( pItem && pItem->GetEnchantmentId(slot) )
11186 pItem->ClearEnchantment(slot);
11192 // duration == 0 will remove item enchant
11193 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11195 if(!item)
11196 return;
11198 if(slot >= MAX_ENCHANTMENT_SLOT)
11199 return;
11201 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11203 if(itr->item == item && itr->slot == slot)
11205 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11206 m_enchantDuration.erase(itr);
11207 break;
11210 if(item && duration > 0 )
11212 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11213 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11217 void Player::ApplyEnchantment(Item *item,bool apply)
11219 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11220 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11223 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11225 if(!item)
11226 return;
11228 if(!item->IsEquipped())
11229 return;
11231 if(slot >= MAX_ENCHANTMENT_SLOT)
11232 return;
11234 uint32 enchant_id = item->GetEnchantmentId(slot);
11235 if(!enchant_id)
11236 return;
11238 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11239 if(!pEnchant)
11240 return;
11242 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11243 return;
11245 for (int s=0; s<3; s++)
11247 uint32 enchant_display_type = pEnchant->type[s];
11248 uint32 enchant_amount = pEnchant->amount[s];
11249 uint32 enchant_spell_id = pEnchant->spellid[s];
11251 switch(enchant_display_type)
11253 case ITEM_ENCHANTMENT_TYPE_NONE:
11254 break;
11255 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11256 // processed in Player::CastItemCombatSpell
11257 break;
11258 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11259 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11260 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11261 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11262 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11263 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11264 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11265 break;
11266 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11267 if(enchant_spell_id)
11269 if(apply)
11271 int32 basepoints = int32(enchant_amount);
11272 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11273 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11275 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11276 if (item_rand)
11278 // Search enchant_amount
11279 for (int k=0; k<3; k++)
11281 if(item_rand->enchant_id[k] == enchant_id)
11283 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11284 break;
11289 // Cast custom spell vs all equal basepoints getted from enchant_amount
11290 if (basepoints)
11291 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11292 else
11293 CastSpell(this,enchant_spell_id,true,item);
11295 else
11296 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11298 break;
11299 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11300 if (!enchant_amount)
11302 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11303 if(item_rand)
11305 for (int k=0; k<3; k++)
11307 if(item_rand->enchant_id[k] == enchant_id)
11309 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11310 break;
11316 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11317 break;
11318 case ITEM_ENCHANTMENT_TYPE_STAT:
11320 if (!enchant_amount)
11322 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11323 if(item_rand_suffix)
11325 for (int k=0; k<3; k++)
11327 if(item_rand_suffix->enchant_id[k] == enchant_id)
11329 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11330 break;
11336 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11337 switch (enchant_spell_id)
11339 case ITEM_MOD_AGILITY:
11340 sLog.outDebug("+ %u AGILITY",enchant_amount);
11341 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11342 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11343 break;
11344 case ITEM_MOD_STRENGTH:
11345 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11346 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11347 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11348 break;
11349 case ITEM_MOD_INTELLECT:
11350 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11351 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11352 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11353 break;
11354 case ITEM_MOD_SPIRIT:
11355 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11356 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11357 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11358 break;
11359 case ITEM_MOD_STAMINA:
11360 sLog.outDebug("+ %u STAMINA",enchant_amount);
11361 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11362 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11363 break;
11364 case ITEM_MOD_DEFENSE_SKILL_RATING:
11365 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11366 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11367 break;
11368 case ITEM_MOD_DODGE_RATING:
11369 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11370 sLog.outDebug("+ %u DODGE", enchant_amount);
11371 break;
11372 case ITEM_MOD_PARRY_RATING:
11373 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11374 sLog.outDebug("+ %u PARRY", enchant_amount);
11375 break;
11376 case ITEM_MOD_BLOCK_RATING:
11377 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11378 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11379 break;
11380 case ITEM_MOD_HIT_MELEE_RATING:
11381 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11382 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11383 break;
11384 case ITEM_MOD_HIT_RANGED_RATING:
11385 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11386 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11387 break;
11388 case ITEM_MOD_HIT_SPELL_RATING:
11389 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11390 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11391 break;
11392 case ITEM_MOD_CRIT_MELEE_RATING:
11393 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11394 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11395 break;
11396 case ITEM_MOD_CRIT_RANGED_RATING:
11397 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11398 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11399 break;
11400 case ITEM_MOD_CRIT_SPELL_RATING:
11401 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11402 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11403 break;
11404 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11405 // in Enchantments
11406 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11407 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11408 // break;
11409 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11410 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11411 // break;
11412 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11413 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11414 // break;
11415 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11416 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11417 // break;
11418 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11419 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11420 // break;
11421 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11422 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11423 // break;
11424 // case ITEM_MOD_HASTE_MELEE_RATING:
11425 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11426 // break;
11427 // case ITEM_MOD_HASTE_RANGED_RATING:
11428 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11429 // break;
11430 case ITEM_MOD_HASTE_SPELL_RATING:
11431 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11432 break;
11433 case ITEM_MOD_HIT_RATING:
11434 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11435 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11436 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11437 sLog.outDebug("+ %u HIT", enchant_amount);
11438 break;
11439 case ITEM_MOD_CRIT_RATING:
11440 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11441 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11442 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11443 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11444 break;
11445 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11446 // case ITEM_MOD_HIT_TAKEN_RATING:
11447 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11448 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11449 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11450 // break;
11451 // case ITEM_MOD_CRIT_TAKEN_RATING:
11452 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11453 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11454 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11455 // break;
11456 case ITEM_MOD_RESILIENCE_RATING:
11457 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11458 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11459 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11460 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11461 break;
11462 case ITEM_MOD_HASTE_RATING:
11463 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11464 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11465 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11466 sLog.outDebug("+ %u HASTE", enchant_amount);
11467 break;
11468 case ITEM_MOD_EXPERTISE_RATING:
11469 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11470 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11471 break;
11472 default:
11473 break;
11475 break;
11477 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11479 if(getClass() == CLASS_SHAMAN)
11481 float addValue = 0.0f;
11482 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11484 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11485 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11487 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11489 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11490 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11493 break;
11495 default:
11496 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11497 break;
11498 } /*switch(enchant_display_type)*/
11499 } /*for*/
11501 // visualize enchantment at player and equipped items
11502 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11504 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11505 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11508 if(apply_dur)
11510 if(apply)
11512 // set duration
11513 uint32 duration = item->GetEnchantmentDuration(slot);
11514 if(duration > 0)
11515 AddEnchantmentDuration(item,slot,duration);
11517 else
11519 // duration == 0 will remove EnchantDuration
11520 AddEnchantmentDuration(item,slot,0);
11525 void Player::SendEnchantmentDurations()
11527 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11529 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11533 void Player::SendItemDurations()
11535 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11537 (*itr)->SendTimeUpdate(this);
11541 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11543 if(!item) // prevent crash
11544 return;
11546 // last check 2.0.10
11547 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11548 data << GetGUID(); // player GUID
11549 data << uint32(received); // 0=looted, 1=from npc
11550 data << uint32(created); // 0=received, 1=created
11551 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11552 data << (uint8)item->GetBagSlot(); // bagslot
11553 // item slot, but when added to stack: 0xFFFFFFFF
11554 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11555 data << uint32(item->GetEntry()); // item id
11556 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11557 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11558 data << uint32(count); // count of items
11559 data << GetItemCount(item->GetEntry()); // count of items in inventory
11561 if (broadcast && GetGroup())
11562 GetGroup()->BroadcastPacket(&data);
11563 else
11564 GetSession()->SendPacket(&data);
11567 /*********************************************************/
11568 /*** QUEST SYSTEM ***/
11569 /*********************************************************/
11571 void Player::PrepareQuestMenu( uint64 guid )
11573 Object *pObject;
11574 QuestRelations* pObjectQR;
11575 QuestRelations* pObjectQIR;
11576 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11577 if( pCreature )
11579 pObject = (Object*)pCreature;
11580 pObjectQR = &objmgr.mCreatureQuestRelations;
11581 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11583 else
11585 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11586 if( pGameObject )
11588 pObject = (Object*)pGameObject;
11589 pObjectQR = &objmgr.mGOQuestRelations;
11590 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11592 else
11593 return;
11596 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11597 qm.ClearMenu();
11599 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11601 uint32 quest_id = i->second;
11602 QuestStatus status = GetQuestStatus( quest_id );
11603 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11604 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11605 else if ( status == QUEST_STATUS_INCOMPLETE )
11606 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11607 else if (status == QUEST_STATUS_AVAILABLE )
11608 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11611 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11613 uint32 quest_id = i->second;
11614 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11615 if(!pQuest) continue;
11617 QuestStatus status = GetQuestStatus( quest_id );
11619 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11620 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11621 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11622 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11626 void Player::SendPreparedQuest( uint64 guid )
11628 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11629 if( questMenu.Empty() )
11630 return;
11632 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11634 uint32 status = qmi0.m_qIcon;
11636 // single element case
11637 if ( questMenu.MenuItemCount() == 1 )
11639 // Auto open -- maybe also should verify there is no greeting
11640 uint32 quest_id = qmi0.m_qId;
11641 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11642 if ( pQuest )
11644 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11645 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11646 else if( status == DIALOG_STATUS_INCOMPLETE )
11647 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11648 // Send completable on repeatable quest if player don't have quest
11649 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11650 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11651 else
11652 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11655 // multiply entries
11656 else
11658 QEmote qe;
11659 qe._Delay = 0;
11660 qe._Emote = 0;
11661 std::string title = "";
11662 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11663 if( pCreature )
11665 uint32 textid = pCreature->GetNpcTextId();
11666 GossipText * gossiptext = objmgr.GetGossipText(textid);
11667 if( !gossiptext )
11669 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11670 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11671 title = "";
11673 else
11675 qe = gossiptext->Options[0].Emotes[0];
11677 if(!gossiptext->Options[0].Text_0.empty())
11679 title = gossiptext->Options[0].Text_0;
11681 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11682 if (loc_idx >= 0)
11684 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11685 if (nl)
11687 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11688 title = nl->Text_0[0][loc_idx];
11692 else
11694 title = gossiptext->Options[0].Text_1;
11696 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11697 if (loc_idx >= 0)
11699 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11700 if (nl)
11702 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11703 title = nl->Text_1[0][loc_idx];
11709 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11713 bool Player::IsActiveQuest( uint32 quest_id ) const
11715 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11717 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11720 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11722 Object *pObject;
11723 QuestRelations* pObjectQR;
11724 QuestRelations* pObjectQIR;
11726 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11727 if( pCreature )
11729 pObject = (Object*)pCreature;
11730 pObjectQR = &objmgr.mCreatureQuestRelations;
11731 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11733 else
11735 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11736 if( pGameObject )
11738 pObject = (Object*)pGameObject;
11739 pObjectQR = &objmgr.mGOQuestRelations;
11740 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11742 else
11743 return NULL;
11746 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11747 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11749 if (itr->second == nextQuestID)
11750 return objmgr.GetQuestTemplate(nextQuestID);
11753 return NULL;
11756 bool Player::CanSeeStartQuest( Quest const *pQuest )
11758 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11759 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11760 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11761 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11763 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11766 return false;
11769 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11771 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
11772 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
11773 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
11774 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
11775 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
11776 && SatisfyQuestDay( pQuest, msg );
11779 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
11781 if( !SatisfyQuestLog( msg ) )
11782 return false;
11784 uint32 srcitem = pQuest->GetSrcItemId();
11785 if( srcitem > 0 )
11787 uint32 count = pQuest->GetSrcItemCount();
11788 ItemPosCountVec dest;
11789 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
11791 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11792 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
11793 return true;
11794 else if( msg != EQUIP_ERR_OK )
11796 SendEquipError( msg, NULL, NULL );
11797 return false;
11800 return true;
11803 bool Player::CanCompleteQuest( uint32 quest_id )
11805 if( quest_id )
11807 QuestStatusData& q_status = mQuestStatus[quest_id];
11808 if( q_status.m_status == QUEST_STATUS_COMPLETE )
11809 return false; // not allow re-complete quest
11811 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
11813 if(!qInfo)
11814 return false;
11816 // auto complete quest
11817 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
11818 return true;
11820 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
11823 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11825 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11827 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
11828 return false;
11832 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11834 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11836 if( qInfo->ReqCreatureOrGOId[i] == 0 )
11837 continue;
11839 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
11840 return false;
11844 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
11845 return false;
11847 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
11848 return false;
11850 if ( qInfo->GetRewOrReqMoney() < 0 )
11852 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
11853 return false;
11856 uint32 repFacId = qInfo->GetRepObjectiveFaction();
11857 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
11858 return false;
11860 return true;
11863 return false;
11866 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
11868 // Solve problem that player don't have the quest and try complete it.
11869 // if repeatable she must be able to complete event if player don't have it.
11870 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
11871 if( !CanTakeQuest(pQuest, false) )
11872 return false;
11874 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
11875 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11876 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
11877 return false;
11879 if( !CanRewardQuest(pQuest, false) )
11880 return false;
11882 return true;
11885 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
11887 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
11888 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
11889 return false;
11891 // daily quest can't be rewarded (25 daily quest already completed)
11892 if(!SatisfyQuestDay(pQuest,true))
11893 return false;
11895 // rewarded and not repeatable quest (only cheating case, then ignore without message)
11896 if(GetQuestRewardStatus(pQuest->GetQuestId()))
11897 return false;
11899 // prevent receive reward with quest items in bank
11900 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11902 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11904 if( pQuest->ReqItemCount[i]!= 0 &&
11905 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
11907 if(msg)
11908 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
11909 return false;
11914 // prevent receive reward with low money and GetRewOrReqMoney() < 0
11915 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
11916 return false;
11918 return true;
11921 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
11923 // prevent receive reward with quest items in bank or for not completed quest
11924 if(!CanRewardQuest(pQuest,msg))
11925 return false;
11927 if ( pQuest->GetRewChoiceItemsCount() > 0 )
11929 if( pQuest->RewChoiceItemId[reward] )
11931 ItemPosCountVec dest;
11932 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
11933 if( res != EQUIP_ERR_OK )
11935 SendEquipError( res, NULL, NULL );
11936 return false;
11941 if ( pQuest->GetRewItemsCount() > 0 )
11943 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
11945 if( pQuest->RewItemId[i] )
11947 ItemPosCountVec dest;
11948 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
11949 if( res != EQUIP_ERR_OK )
11951 SendEquipError( res, NULL, NULL );
11952 return false;
11958 return true;
11961 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
11963 uint16 log_slot = FindQuestSlot( 0 );
11964 assert(log_slot < MAX_QUEST_LOG_SIZE);
11966 uint32 quest_id = pQuest->GetQuestId();
11968 // if not exist then created with set uState==NEW and rewarded=false
11969 QuestStatusData& questStatusData = mQuestStatus[quest_id];
11970 if (questStatusData.uState != QUEST_NEW)
11971 questStatusData.uState = QUEST_CHANGED;
11973 // check for repeatable quests status reset
11974 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
11975 questStatusData.m_explored = false;
11977 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11979 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11980 questStatusData.m_itemcount[i] = 0;
11983 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11985 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11986 questStatusData.m_creatureOrGOcount[i] = 0;
11989 GiveQuestSourceItem( pQuest );
11990 AdjustQuestReqItemCount( pQuest );
11992 if( pQuest->GetRepObjectiveFaction() )
11993 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
11995 uint32 qtime = 0;
11996 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
11998 uint32 limittime = pQuest->GetLimitTime();
12000 // shared timed quest
12001 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12002 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12004 AddTimedQuest( quest_id );
12005 questStatusData.m_timer = limittime * 1000;
12006 qtime = static_cast<uint32>(time(NULL)) + limittime;
12008 else
12009 questStatusData.m_timer = 0;
12011 SetQuestSlot(log_slot, quest_id, qtime);
12013 //starting initial quest script
12014 if(questGiver && pQuest->GetQuestStartScript()!=0)
12015 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12017 UpdateForQuestsGO();
12020 void Player::CompleteQuest( uint32 quest_id )
12022 if( quest_id )
12024 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12026 uint16 log_slot = FindQuestSlot( quest_id );
12027 if( log_slot < MAX_QUEST_LOG_SIZE)
12028 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12030 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12032 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12033 RewardQuest(qInfo,0,this,false);
12034 else
12035 SendQuestComplete( quest_id );
12040 void Player::IncompleteQuest( uint32 quest_id )
12042 if( quest_id )
12044 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12046 uint16 log_slot = FindQuestSlot( quest_id );
12047 if( log_slot < MAX_QUEST_LOG_SIZE)
12048 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12052 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12054 uint32 quest_id = pQuest->GetQuestId();
12056 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12058 if ( pQuest->ReqItemId[i] )
12059 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12062 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12063 // SetTimedQuest( 0 );
12064 m_timedquests.erase(pQuest->GetQuestId());
12066 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12068 if( pQuest->RewChoiceItemId[reward] )
12070 ItemPosCountVec dest;
12071 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12073 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12074 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12079 if ( pQuest->GetRewItemsCount() > 0 )
12081 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12083 if( pQuest->RewItemId[i] )
12085 ItemPosCountVec dest;
12086 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12088 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12089 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12095 RewardReputation( pQuest );
12097 if( pQuest->GetRewSpellCast() > 0 )
12098 CastSpell( this, pQuest->GetRewSpellCast(), true);
12099 else if( pQuest->GetRewSpell() > 0)
12100 CastSpell( this, pQuest->GetRewSpell(), true);
12102 uint16 log_slot = FindQuestSlot( quest_id );
12103 if( log_slot < MAX_QUEST_LOG_SIZE)
12104 SetQuestSlot(log_slot,0);
12106 QuestStatusData& q_status = mQuestStatus[quest_id];
12108 // Not give XP in case already completed once repeatable quest
12109 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12111 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12112 GiveXP( XP , NULL );
12113 else
12114 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12116 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12117 ModifyMoney( pQuest->GetRewOrReqMoney() );
12119 // honor reward
12120 if(pQuest->GetRewHonorableKills())
12121 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12123 // title reward
12124 if(pQuest->GetCharTitleId())
12126 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12127 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12130 // Send reward mail
12131 if(pQuest->GetRewMailTemplateId())
12133 MailMessageType mailType;
12134 uint32 senderGuidOrEntry;
12135 switch(questGiver->GetTypeId())
12137 case TYPEID_UNIT:
12138 mailType = MAIL_CREATURE;
12139 senderGuidOrEntry = questGiver->GetEntry();
12140 break;
12141 case TYPEID_GAMEOBJECT:
12142 mailType = MAIL_GAMEOBJECT;
12143 senderGuidOrEntry = questGiver->GetEntry();
12144 break;
12145 case TYPEID_ITEM:
12146 mailType = MAIL_ITEM;
12147 senderGuidOrEntry = questGiver->GetEntry();
12148 break;
12149 case TYPEID_PLAYER:
12150 mailType = MAIL_NORMAL;
12151 senderGuidOrEntry = questGiver->GetGUIDLow();
12152 break;
12153 default:
12154 mailType = MAIL_NORMAL;
12155 senderGuidOrEntry = GetGUIDLow();
12156 break;
12159 Loot questMailLoot;
12161 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12163 // fill mail
12164 MailItemsInfo mi; // item list preparing
12166 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12168 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12170 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12172 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12173 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12178 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12180 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12182 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12184 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12185 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12190 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12193 if(pQuest->IsDaily())
12194 SetDailyQuestStatus(quest_id);
12196 if ( !pQuest->IsRepeatable() )
12197 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12198 else
12199 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12201 q_status.m_rewarded = true;
12203 if(announce)
12204 SendQuestReward( pQuest, XP, questGiver );
12206 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12209 void Player::FailQuest( uint32 quest_id )
12211 if( quest_id )
12213 IncompleteQuest( quest_id );
12215 uint16 log_slot = FindQuestSlot( quest_id );
12216 if( log_slot < MAX_QUEST_LOG_SIZE)
12218 SetQuestSlotTimer(log_slot, 1 );
12219 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12221 SendQuestFailed( quest_id );
12225 void Player::FailTimedQuest( uint32 quest_id )
12227 if( quest_id )
12229 QuestStatusData& q_status = mQuestStatus[quest_id];
12231 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12232 q_status.m_timer = 0;
12234 IncompleteQuest( quest_id );
12236 uint16 log_slot = FindQuestSlot( quest_id );
12237 if( log_slot < MAX_QUEST_LOG_SIZE)
12239 SetQuestSlotTimer(log_slot, 1 );
12240 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12242 SendQuestTimerFailed( quest_id );
12246 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12248 int32 zoneOrSort = qInfo->GetZoneOrSort();
12249 int32 skillOrClass = qInfo->GetSkillOrClass();
12251 // skip zone zoneOrSort and 0 case skillOrClass
12252 if( zoneOrSort >= 0 && skillOrClass == 0 )
12253 return true;
12255 int32 questSort = -zoneOrSort;
12256 uint8 reqSortClass = ClassByQuestSort(questSort);
12258 // check class sort cases in zoneOrSort
12259 if( reqSortClass != 0 && getClass() != reqSortClass)
12261 if( msg )
12262 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12263 return false;
12266 // check class
12267 if( skillOrClass < 0 )
12269 uint8 reqClass = -int32(skillOrClass);
12270 if(getClass() != reqClass)
12272 if( msg )
12273 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12274 return false;
12277 // check skill
12278 else if( skillOrClass > 0 )
12280 uint32 reqSkill = skillOrClass;
12281 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12283 if( msg )
12284 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12285 return false;
12289 return true;
12292 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12294 if( getLevel() < qInfo->GetMinLevel() )
12296 if( msg )
12297 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12298 return false;
12300 return true;
12303 bool Player::SatisfyQuestLog( bool msg )
12305 // exist free slot
12306 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12307 return true;
12309 if( msg )
12311 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12312 GetSession()->SendPacket( &data );
12313 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12315 return false;
12318 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12320 // No previous quest (might be first quest in a series)
12321 if( qInfo->prevQuests.empty())
12322 return true;
12324 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12326 uint32 prevId = abs(*iter);
12328 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12329 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12331 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12333 // If any of the positive previous quests completed, return true
12334 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12336 // skip one-from-all exclusive group
12337 if(qPrevInfo->GetExclusiveGroup() >= 0)
12338 return true;
12340 // each-from-all exclusive group ( < 0)
12341 // can be start if only all quests in prev quest exclusive group completed and rewarded
12342 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12343 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12345 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12347 for(; iter != end; ++iter)
12349 uint32 exclude_Id = iter->second;
12351 // skip checked quest id, only state of other quests in group is interesting
12352 if(exclude_Id == prevId)
12353 continue;
12355 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12357 // alternative quest from group also must be completed and rewarded(reported)
12358 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12360 if( msg )
12361 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12362 return false;
12365 return true;
12367 // If any of the negative previous quests active, return true
12368 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12369 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12371 // skip one-from-all exclusive group
12372 if(qPrevInfo->GetExclusiveGroup() >= 0)
12373 return true;
12375 // each-from-all exclusive group ( < 0)
12376 // can be start if only all quests in prev quest exclusive group active
12377 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12378 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12380 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12382 for(; iter != end; ++iter)
12384 uint32 exclude_Id = iter->second;
12386 // skip checked quest id, only state of other quests in group is interesting
12387 if(exclude_Id == prevId)
12388 continue;
12390 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12392 // alternative quest from group also must be active
12393 if( i_exstatus == mQuestStatus.end() ||
12394 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12395 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12397 if( msg )
12398 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12399 return false;
12402 return true;
12407 // Has only positive prev. quests in non-rewarded state
12408 // and negative prev. quests in non-active state
12409 if( msg )
12410 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12412 return false;
12415 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12417 uint32 reqraces = qInfo->GetRequiredRaces();
12418 if ( reqraces == 0 )
12419 return true;
12420 if( (reqraces & getRaceMask()) == 0 )
12422 if( msg )
12423 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12424 return false;
12426 return true;
12429 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12431 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12432 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12434 if( msg )
12435 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12436 return false;
12439 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12440 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12442 if( msg )
12443 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12444 return false;
12447 return true;
12450 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12452 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12453 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12455 if( msg )
12456 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12457 return false;
12459 return true;
12462 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12464 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12466 if( msg )
12467 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12468 return false;
12470 return true;
12473 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12475 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12476 if(qInfo->GetExclusiveGroup() <= 0)
12477 return true;
12479 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12480 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12482 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12484 for(; iter != end; ++iter)
12486 uint32 exclude_Id = iter->second;
12488 // skip checked quest id, only state of other quests in group is interesting
12489 if(exclude_Id == qInfo->GetQuestId())
12490 continue;
12492 // not allow have daily quest if daily quest from exclusive group already recently completed
12493 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12494 if( !SatisfyQuestDay(Nquest, false) )
12496 if( msg )
12497 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12498 return false;
12501 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12503 // alternative quest already started or completed
12504 if( i_exstatus != mQuestStatus.end()
12505 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12507 if( msg )
12508 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12509 return false;
12512 return true;
12515 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12517 if(!qInfo->GetNextQuestInChain())
12518 return true;
12520 // next quest in chain already started or completed
12521 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12522 if( itr != mQuestStatus.end()
12523 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12525 if( msg )
12526 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12527 return false;
12530 // check for all quests further up the chain
12531 // only necessary if there are quest chains with more than one quest that can be skipped
12532 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12533 return true;
12536 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12538 // No previous quest in chain
12539 if( qInfo->prevChainQuests.empty())
12540 return true;
12542 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12544 uint32 prevId = *iter;
12546 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12548 if( i_prevstatus != mQuestStatus.end() )
12550 // If any of the previous quests in chain active, return false
12551 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12552 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12554 if( msg )
12555 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12556 return false;
12560 // check for all quests further down the chain
12561 // only necessary if there are quest chains with more than one quest that can be skipped
12562 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12563 // return false;
12566 // No previous quest in chain active
12567 return true;
12570 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12572 if(!qInfo->IsDaily())
12573 return true;
12575 bool have_slot = false;
12576 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12578 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12579 if(qInfo->GetQuestId()==id)
12580 return false;
12582 if(!id)
12583 have_slot = true;
12586 if(!have_slot)
12588 if( msg )
12589 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12590 return false;
12593 return true;
12596 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12598 uint32 srcitem = pQuest->GetSrcItemId();
12599 if( srcitem > 0 )
12601 uint32 count = pQuest->GetSrcItemCount();
12602 if( count <= 0 )
12603 count = 1;
12605 ItemPosCountVec dest;
12606 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12607 if( msg == EQUIP_ERR_OK )
12609 Item * item = StoreNewItem(dest, srcitem, true);
12610 SendNewItem(item, count, true, false);
12611 return true;
12613 // player already have max amount required item, just report success
12614 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12615 return true;
12616 else
12617 SendEquipError( msg, NULL, NULL );
12618 return false;
12621 return true;
12624 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12626 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12627 if( qInfo )
12629 uint32 srcitem = qInfo->GetSrcItemId();
12630 if( srcitem > 0 )
12632 uint32 count = qInfo->GetSrcItemCount();
12633 if( count <= 0 )
12634 count = 1;
12636 // exist one case when destroy source quest item not possible:
12637 // non un-equippable item (equipped non-empty bag, for example)
12638 uint8 res = CanUnequipItems(srcitem,count);
12639 if(res != EQUIP_ERR_OK)
12641 if(msg)
12642 SendEquipError( res, NULL, NULL );
12643 return false;
12646 DestroyItemCount(srcitem, count, true, true);
12649 return true;
12652 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12654 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12655 if( qInfo )
12657 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12658 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12659 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12660 && !qInfo->IsRepeatable() )
12661 return itr->second.m_rewarded;
12663 return false;
12665 return false;
12668 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12670 if( quest_id )
12672 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12673 if( itr != mQuestStatus.end() )
12674 return itr->second.m_status;
12676 return QUEST_STATUS_NONE;
12679 bool Player::CanShareQuest(uint32 quest_id) const
12681 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12682 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12684 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12685 if( itr != mQuestStatus.end() )
12686 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12688 return false;
12691 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12693 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12694 if( qInfo )
12696 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12698 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12699 m_timedquests.erase(qInfo->GetQuestId());
12702 QuestStatusData& q_status = mQuestStatus[quest_id];
12704 q_status.m_status = status;
12705 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12708 UpdateForQuestsGO();
12711 // not used in MaNGOS, but used in scripting code
12712 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12714 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12715 if( !qInfo )
12716 return 0;
12718 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12719 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12720 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12722 return 0;
12725 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12727 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12729 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12731 uint32 reqitemcount = pQuest->ReqItemCount[i];
12732 if( reqitemcount != 0 )
12734 uint32 quest_id = pQuest->GetQuestId();
12735 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12737 QuestStatusData& q_status = mQuestStatus[quest_id];
12738 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12739 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12745 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12747 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12748 if ( GetQuestSlotQuestId(i) == quest_id )
12749 return i;
12751 return MAX_QUEST_LOG_SIZE;
12754 void Player::AreaExploredOrEventHappens( uint32 questId )
12756 if( questId )
12758 uint16 log_slot = FindQuestSlot( questId );
12759 if( log_slot < MAX_QUEST_LOG_SIZE)
12761 QuestStatusData& q_status = mQuestStatus[questId];
12763 if(!q_status.m_explored)
12765 q_status.m_explored = true;
12766 if (q_status.uState != QUEST_NEW)
12767 q_status.uState = QUEST_CHANGED;
12770 if( CanCompleteQuest( questId ) )
12771 CompleteQuest( questId );
12775 //not used in mangosd, function for external script library
12776 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
12778 if( Group *pGroup = GetGroup() )
12780 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
12782 Player *pGroupGuy = itr->getSource();
12784 // for any leave or dead (with not released body) group member at appropriate distance
12785 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
12786 pGroupGuy->AreaExploredOrEventHappens(questId);
12789 else
12790 AreaExploredOrEventHappens(questId);
12793 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
12795 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12797 uint32 questid = GetQuestSlotQuestId(i);
12798 if ( questid == 0 )
12799 continue;
12801 QuestStatusData& q_status = mQuestStatus[questid];
12803 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
12804 continue;
12806 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12807 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12808 continue;
12810 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12812 uint32 reqitem = qInfo->ReqItemId[j];
12813 if ( reqitem == entry )
12815 uint32 reqitemcount = qInfo->ReqItemCount[j];
12816 uint32 curitemcount = q_status.m_itemcount[j];
12817 if ( curitemcount < reqitemcount )
12819 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
12820 q_status.m_itemcount[j] += additemcount;
12821 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12823 SendQuestUpdateAddItem( qInfo, j, additemcount );
12825 if ( CanCompleteQuest( questid ) )
12826 CompleteQuest( questid );
12827 return;
12831 UpdateForQuestsGO();
12834 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
12836 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12838 uint32 questid = GetQuestSlotQuestId(i);
12839 if(!questid)
12840 continue;
12841 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12842 if ( !qInfo )
12843 continue;
12844 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12845 continue;
12847 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12849 uint32 reqitem = qInfo->ReqItemId[j];
12850 if ( reqitem == entry )
12852 QuestStatusData& q_status = mQuestStatus[questid];
12854 uint32 reqitemcount = qInfo->ReqItemCount[j];
12855 uint32 curitemcount;
12856 if( q_status.m_status != QUEST_STATUS_COMPLETE )
12857 curitemcount = q_status.m_itemcount[j];
12858 else
12859 curitemcount = GetItemCount(entry,true);
12860 if ( curitemcount < reqitemcount + count )
12862 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
12863 q_status.m_itemcount[j] = curitemcount - remitemcount;
12864 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12866 IncompleteQuest( questid );
12868 return;
12872 UpdateForQuestsGO();
12875 void Player::KilledMonster( uint32 entry, uint64 guid )
12877 uint32 addkillcount = 1;
12878 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12880 uint32 questid = GetQuestSlotQuestId(i);
12881 if(!questid)
12882 continue;
12884 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12885 if( !qInfo )
12886 continue;
12887 // just if !ingroup || !noraidgroup || raidgroup
12888 QuestStatusData& q_status = mQuestStatus[questid];
12889 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
12891 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
12893 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12895 // skip GO activate objective or none
12896 if(qInfo->ReqCreatureOrGOId[j] <=0)
12897 continue;
12899 // skip Cast at creature objective
12900 if(qInfo->ReqSpell[j] !=0 )
12901 continue;
12903 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
12905 if ( reqkill == entry )
12907 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
12908 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
12909 if ( curkillcount < reqkillcount )
12911 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
12912 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12914 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
12916 if ( CanCompleteQuest( questid ) )
12917 CompleteQuest( questid );
12919 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12920 continue;
12928 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
12930 bool isCreature = IS_CREATURE_GUID(guid);
12932 uint32 addCastCount = 1;
12933 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12935 uint32 questid = GetQuestSlotQuestId(i);
12936 if(!questid)
12937 continue;
12939 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12940 if ( !qInfo )
12941 continue;
12943 QuestStatusData& q_status = mQuestStatus[questid];
12945 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12947 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
12949 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12951 // skip kill creature objective (0) or wrong spell casts
12952 if(qInfo->ReqSpell[j] != spell_id )
12953 continue;
12955 uint32 reqTarget = 0;
12957 if(isCreature)
12959 // creature activate objectives
12960 if(qInfo->ReqCreatureOrGOId[j] > 0)
12961 // checked at quest_template loading
12962 reqTarget = qInfo->ReqCreatureOrGOId[j];
12964 else
12966 // GO activate objective
12967 if(qInfo->ReqCreatureOrGOId[j] < 0)
12968 // checked at quest_template loading
12969 reqTarget = - qInfo->ReqCreatureOrGOId[j];
12972 // other not this creature/GO related objectives
12973 if( reqTarget != entry )
12974 continue;
12976 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
12977 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
12978 if ( curCastCount < reqCastCount )
12980 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
12981 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12983 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
12986 if ( CanCompleteQuest( questid ) )
12987 CompleteQuest( questid );
12989 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12990 break;
12997 void Player::TalkedToCreature( uint32 entry, uint64 guid )
12999 uint32 addTalkCount = 1;
13000 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13002 uint32 questid = GetQuestSlotQuestId(i);
13003 if(!questid)
13004 continue;
13006 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13007 if ( !qInfo )
13008 continue;
13010 QuestStatusData& q_status = mQuestStatus[questid];
13012 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13014 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13016 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13018 // skip spell casts and Gameobject objectives
13019 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13020 continue;
13022 uint32 reqTarget = 0;
13024 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13025 // checked at quest_template loading
13026 reqTarget = qInfo->ReqCreatureOrGOId[j];
13027 else
13028 continue;
13030 if ( reqTarget == entry )
13032 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13033 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13034 if ( curTalkCount < reqTalkCount )
13036 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13037 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13039 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13041 if ( CanCompleteQuest( questid ) )
13042 CompleteQuest( questid );
13044 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13045 continue;
13053 void Player::MoneyChanged( uint32 count )
13055 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13057 uint32 questid = GetQuestSlotQuestId(i);
13058 if (!questid)
13059 continue;
13061 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13062 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13064 QuestStatusData& q_status = mQuestStatus[questid];
13066 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13068 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13070 if ( CanCompleteQuest( questid ) )
13071 CompleteQuest( questid );
13074 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13076 if(int32(count) < -qInfo->GetRewOrReqMoney())
13077 IncompleteQuest( questid );
13083 bool Player::HasQuestForItem( uint32 itemid ) const
13085 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13087 QuestStatusData const& q_status = i->second;
13089 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13091 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13092 if(!qinfo)
13093 continue;
13095 // hide quest if player is in raid-group and quest is no raid quest
13096 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13097 continue;
13099 // There should be no mixed ReqItem/ReqSource drop
13100 // This part for ReqItem drop
13101 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13103 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13104 return true;
13106 // This part - for ReqSource
13107 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13109 // examined item is a source item
13110 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13112 uint32 idx = qinfo->ReqSourceRef[j]-1;
13114 // total count of created ReqItems and SourceItems is less than ReqItemCount
13115 if(qinfo->ReqItemId[idx] != 0 &&
13116 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13117 return true;
13119 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13120 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13122 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13123 return true;
13125 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13126 else if(qinfo->ReqSpell[idx] != 0)
13128 // not casted and need more reagents/item for use.
13129 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13130 return true;
13136 return false;
13139 void Player::SendQuestComplete( uint32 quest_id )
13141 if( quest_id )
13143 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13144 data << quest_id;
13145 GetSession()->SendPacket( &data );
13146 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13150 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13152 uint32 questid = pQuest->GetQuestId();
13153 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13154 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4+4+pQuest->GetRewItemsCount()*8) );
13155 data << questid;
13156 data << uint32(0x03);
13158 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13160 data << XP;
13161 data << uint32(pQuest->GetRewOrReqMoney());
13163 else
13165 data << uint32(0);
13166 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13168 data << uint32(0); // new 2.3.0, HonorPoints?
13169 data << uint32( pQuest->GetRewItemsCount() ); // max is 5
13171 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13173 if ( pQuest->RewItemId[i] > 0 )
13174 data << pQuest->RewItemId[i] << pQuest->RewItemCount[i];
13175 else
13176 data << uint32(0) << uint32(0);
13178 GetSession()->SendPacket( &data );
13180 if (pQuest->GetQuestCompleteScript() != 0)
13181 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13184 void Player::SendQuestFailed( uint32 quest_id )
13186 if( quest_id )
13188 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4 );
13189 data << quest_id;
13190 GetSession()->SendPacket( &data );
13191 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13195 void Player::SendQuestTimerFailed( uint32 quest_id )
13197 if( quest_id )
13199 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13200 data << quest_id;
13201 GetSession()->SendPacket( &data );
13202 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13206 void Player::SendCanTakeQuestResponse( uint32 msg )
13208 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13209 data << uint32(msg);
13210 GetSession()->SendPacket( &data );
13211 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13214 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13216 if( pPlayer )
13218 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13219 data << uint64(pPlayer->GetGUID());
13220 data << uint8(msg); // valid values: 0-8
13221 GetSession()->SendPacket( &data );
13222 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13226 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13228 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, (4+4) );
13229 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13230 data << pQuest->ReqItemId[item_idx];
13231 data << count;
13232 GetSession()->SendPacket( &data );
13235 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13237 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13239 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13240 if (entry < 0)
13241 // client expected gameobject template id in form (id|0x80000000)
13242 entry = (-entry) | 0x80000000;
13244 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13245 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13246 data << uint32(pQuest->GetQuestId());
13247 data << uint32(entry);
13248 data << uint32(old_count + add_count);
13249 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13250 data << uint64(guid);
13251 GetSession()->SendPacket(&data);
13253 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13254 if( log_slot < MAX_QUEST_LOG_SIZE)
13255 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13258 /*********************************************************/
13259 /*** LOAD SYSTEM ***/
13260 /*********************************************************/
13262 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13264 bool delete_result = true;
13265 if(!result)
13267 // 0 1 2 3 4 5 6 7 8 9
13268 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13269 if(!result) return false;
13271 else delete_result = false;
13273 Field *fields = result->Fetch();
13275 if(!LoadValues( fields[1].GetString()))
13277 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13278 if(delete_result) delete result;
13279 return false;
13282 // overwrite possible wrong/corrupted guid
13283 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13285 m_name = fields[2].GetCppString();
13287 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13288 SetMapId(fields[6].GetUInt32());
13289 // the instance id is not needed at character enum
13291 m_Played_time[0] = fields[7].GetUInt32();
13292 m_Played_time[1] = fields[8].GetUInt32();
13294 m_atLoginFlags = fields[9].GetUInt32();
13296 // I don't see these used anywhere ..
13297 /*_LoadGroup();
13299 _LoadBoundInstances();*/
13301 if (delete_result) delete result;
13303 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13304 m_items[i] = NULL;
13306 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13307 m_deathState = DEAD;
13309 return true;
13312 void Player::_LoadDeclinedNames(QueryResult* result)
13314 if(!result)
13315 return;
13317 if(m_declinedname)
13318 delete m_declinedname;
13320 m_declinedname = new DeclinedName;
13321 Field *fields = result->Fetch();
13322 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13323 m_declinedname->name[i] = fields[i].GetCppString();
13325 delete result;
13328 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13330 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13331 if(!result)
13332 return false;
13334 Field *fields = result->Fetch();
13336 x = fields[0].GetFloat();
13337 y = fields[1].GetFloat();
13338 z = fields[2].GetFloat();
13339 o = fields[3].GetFloat();
13340 mapid = fields[4].GetUInt32();
13341 in_flight = !fields[5].GetCppString().empty();
13343 delete result;
13344 return true;
13347 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13349 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13350 if( !result )
13351 return false;
13353 Field *fields = result->Fetch();
13355 data = StrSplit(fields[0].GetCppString(), " ");
13357 delete result;
13359 return true;
13362 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13364 if(index >= data.size())
13365 return 0;
13367 return (uint32)atoi(data[index].c_str());
13370 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13372 float result;
13373 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13374 memcpy(&result, &temp, sizeof(result));
13376 return result;
13379 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13381 Tokens data;
13382 if(!LoadValuesArrayFromDB(data,guid))
13383 return 0;
13385 return GetUInt32ValueFromArray(data,index);
13388 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13390 float result;
13391 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13392 memcpy(&result, &temp, sizeof(result));
13394 return result;
13397 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13399 //// 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
13400 //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 FROM characters WHERE guid = '%u'", guid);
13401 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13403 if(!result)
13405 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13406 return false;
13409 Field *fields = result->Fetch();
13411 uint32 dbAccountId = fields[1].GetUInt32();
13413 // check if the character's account in the db and the logged in account match.
13414 // player should be able to load/delete character only with correct account!
13415 if( dbAccountId != GetSession()->GetAccountId() )
13417 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13418 delete result;
13419 return false;
13422 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13424 m_name = fields[3].GetCppString();
13426 // check name limitations
13427 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13429 delete result;
13430 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13431 return false;
13434 if(!LoadValues( fields[2].GetString()))
13436 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13437 delete result;
13438 return false;
13441 // overwrite possible wrong/corrupted guid
13442 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13444 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13445 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13447 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13448 SetVisibleItemSlot(slot,NULL);
13450 if (m_items[slot])
13452 delete m_items[slot];
13453 m_items[slot] = NULL;
13457 // update money limits
13458 if(GetMoney() > MAX_MONEY_AMOUNT)
13459 SetMoney(MAX_MONEY_AMOUNT);
13461 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13462 outDebugValues();
13464 m_race = fields[4].GetUInt8();
13465 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13466 //Other way is to saves m_team into characters table.
13467 setFactionForRace(m_race);
13468 SetCharm(0);
13470 m_class = fields[5].GetUInt8();
13472 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13473 if(!info)
13475 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13476 delete result;
13477 return false;
13480 InitPrimaryProffesions(); // to max set before any spell loaded
13482 uint32 transGUID = fields[24].GetUInt32();
13483 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13484 SetMapId(fields[9].GetUInt32());
13485 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13487 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13489 // check arena teams integrity
13490 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13492 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13493 if(!arena_team_id)
13494 continue;
13496 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13497 if(at->HaveMember(GetGUID()))
13498 continue;
13500 // arena team not exist or not member, cleanup fields
13501 for(int j =0; j < 6; ++j)
13502 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13505 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13507 if(!IsPositionValid())
13509 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());
13511 SetMapId(info->mapId);
13512 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13514 transGUID = 0;
13516 m_movementInfo.t_x = 0.0f;
13517 m_movementInfo.t_y = 0.0f;
13518 m_movementInfo.t_z = 0.0f;
13519 m_movementInfo.t_o = 0.0f;
13522 // load the player's map here if it's not already loaded
13523 Map *map = GetMap();
13524 // since the player may not be bound to the map yet, make sure subsequent
13525 // getmap calls won't create new maps
13526 SetInstanceId(map->GetInstanceId());
13528 SaveRecallPosition();
13530 if (transGUID != 0)
13532 m_movementInfo.t_x = fields[20].GetFloat();
13533 m_movementInfo.t_y = fields[21].GetFloat();
13534 m_movementInfo.t_z = fields[22].GetFloat();
13535 m_movementInfo.t_o = fields[23].GetFloat();
13537 if( !MaNGOS::IsValidMapCoord(
13538 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13539 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13540 // transport size limited
13541 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13543 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13544 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13545 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13547 SetMapId(info->mapId);
13548 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13550 m_movementInfo.t_x = 0.0f;
13551 m_movementInfo.t_y = 0.0f;
13552 m_movementInfo.t_z = 0.0f;
13553 m_movementInfo.t_o = 0.0f;
13555 transGUID = 0;
13559 if (transGUID != 0)
13561 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13563 if( (*iter)->GetGUIDLow() == transGUID)
13565 m_transport = *iter;
13566 m_transport->AddPassenger(this);
13567 SetMapId(m_transport->GetMapId());
13568 break;
13572 if(!m_transport)
13574 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13575 guid,transGUID);
13577 SetMapId(info->mapId);
13578 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13580 m_movementInfo.t_x = 0.0f;
13581 m_movementInfo.t_y = 0.0f;
13582 m_movementInfo.t_z = 0.0f;
13583 m_movementInfo.t_o = 0.0f;
13585 transGUID = 0;
13589 time_t now = time(NULL);
13590 time_t logoutTime = time_t(fields[16].GetUInt64());
13592 // since last logout (in seconds)
13593 uint64 time_diff = uint64(now - logoutTime);
13595 // set value, including drunk invisibility detection
13596 // calculate sobering. after 15 minutes logged out, the player will be sober again
13597 float soberFactor;
13598 if(time_diff > 15*MINUTE)
13599 soberFactor = 0;
13600 else
13601 soberFactor = 1-time_diff/(15.0f*MINUTE);
13602 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13603 SetDrunkValue(newDrunkenValue);
13605 m_rest_bonus = fields[15].GetFloat();
13606 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13607 float bubble0 = 0.031;
13608 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13609 float bubble1 = 0.125;
13611 if((int32)fields[16].GetUInt32() > 0)
13613 float bubble = fields[17].GetUInt32() > 0
13614 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13615 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13617 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13620 m_cinematic = fields[12].GetUInt32();
13621 m_Played_time[0]= fields[13].GetUInt32();
13622 m_Played_time[1]= fields[14].GetUInt32();
13624 m_resetTalentsCost = fields[18].GetUInt32();
13625 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13627 // reserve some flags
13628 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13630 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13631 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13633 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13635 uint32 extraflags = fields[25].GetUInt32();
13637 m_stableSlots = fields[26].GetUInt32();
13638 if(m_stableSlots > 2)
13640 sLog.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots));
13641 m_stableSlots = 2;
13644 m_atLoginFlags = fields[27].GetUInt32();
13646 // Honor system
13647 // Update Honor kills data
13648 m_lastHonorUpdateTime = logoutTime;
13649 UpdateHonorFields();
13651 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13652 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13653 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13655 std::string taxi_nodes = fields[31].GetCppString();
13657 delete result;
13659 // clear channel spell data (if saved at channel spell casting)
13660 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13661 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13663 // clear charm/summon related fields
13664 SetUInt64Value(UNIT_FIELD_CHARM,0);
13665 SetUInt64Value(UNIT_FIELD_SUMMON,0);
13666 SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
13667 SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
13668 SetUInt64Value(UNIT_FIELD_CREATEDBY,0);
13670 // reset some aura modifiers before aura apply
13671 SetUInt64Value(PLAYER_FARSIGHT, 0);
13672 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
13673 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
13675 // reset skill modifiers and set correct unlearn flags
13676 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
13678 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
13680 // set correct unlearn bit
13681 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
13682 if(!id) continue;
13684 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
13685 if(!pSkill) continue;
13687 // enable unlearn button for primary professions only
13688 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
13689 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
13690 else
13691 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
13694 // make sure the unit is considered out of combat for proper loading
13695 ClearInCombat();
13697 // make sure the unit is considered not in duel for proper loading
13698 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
13699 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
13701 // remember loaded power/health values to restore after stats initialization and modifier applying
13702 uint32 savedHealth = GetHealth();
13703 uint32 savedPower[MAX_POWERS];
13704 for(uint32 i = 0; i < MAX_POWERS; ++i)
13705 savedPower[i] = GetPower(Powers(i));
13707 // reset stats before loading any modifiers
13708 InitStatsForLevel();
13709 InitTaxiNodesForLevel();
13711 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13713 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13714 //_LoadMail();
13716 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
13718 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13719 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13720 m_deathState = DEAD;
13722 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
13724 // after spell load
13725 InitTalentForLevel();
13726 learnSkillRewardedSpells();
13728 // after spell load, learn rewarded spell if need also
13729 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
13730 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
13732 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
13734 // must be before inventory (some items required reputation check)
13735 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
13737 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
13739 // update items with duration and realtime
13740 UpdateItemDuration(time_diff, true);
13742 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
13744 // unread mails and next delivery time, actual mails not loaded
13745 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
13747 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
13749 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13750 return false;
13752 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13753 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13754 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
13756 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << curTitle))
13757 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
13760 // Not finish taxi flight path
13761 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
13763 // problems with taxi path loading
13764 TaxiNodesEntry const* nodeEntry = NULL;
13765 if(uint32 node_id = m_taxi.GetTaxiSource())
13766 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13768 if(!nodeEntry) // don't know taxi start node, to homebind
13770 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13771 SetMapId(m_homebindMapId);
13772 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
13773 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13775 else // have start node, to it
13777 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13778 SetMapId(nodeEntry->map_id);
13779 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
13780 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13782 m_taxi.ClearTaxiDestinations();
13784 else if(uint32 node_id = m_taxi.GetTaxiSource())
13786 // save source node as recall coord to prevent recall and fall from sky
13787 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13788 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
13789 m_recallMap = nodeEntry->map_id;
13790 m_recallX = nodeEntry->x;
13791 m_recallY = nodeEntry->y;
13792 m_recallZ = nodeEntry->z;
13794 // flight will started later
13797 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
13799 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
13800 // Do now before stats re-calculation cleanup for ghost state unexpected auras
13801 if(!isAlive())
13802 RemoveAllAurasOnDeath();
13804 //apply all stat bonuses from items and auras
13805 SetCanModifyStats(true);
13806 UpdateAllStats();
13808 // restore remembered power/health values (but not more max values)
13809 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
13810 for(uint32 i = 0; i < MAX_POWERS; ++i)
13811 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
13813 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
13814 outDebugValues();
13816 // GM state
13817 if(GetSession()->GetSecurity() > SEC_PLAYER)
13819 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
13821 default:
13822 case 0: break; // disable
13823 case 1: SetGameMaster(true); break; // enable
13824 case 2: // save state
13825 if(extraflags & PLAYER_EXTRA_GM_ON)
13826 SetGameMaster(true);
13827 break;
13830 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
13832 default:
13833 case 0: break; // disable
13834 case 1: SetAcceptTicket(true); break; // enable
13835 case 2: // save state
13836 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
13837 SetAcceptTicket(true);
13838 break;
13841 switch(sWorld.getConfig(CONFIG_GM_CHAT))
13843 default:
13844 case 0: break; // disable
13845 case 1: SetGMChat(true); break; // enable
13846 case 2: // save state
13847 if(extraflags & PLAYER_EXTRA_GM_CHAT)
13848 SetGMChat(true);
13849 break;
13852 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
13854 default:
13855 case 0: break; // disable
13856 case 1: SetAcceptWhispers(true); break; // enable
13857 case 2: // save state
13858 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
13859 SetAcceptWhispers(true);
13860 break;
13864 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
13866 return true;
13869 bool Player::isAllowedToLoot(Creature* creature)
13871 if(Player* recipient = creature->GetLootRecipient())
13873 if (recipient == this)
13874 return true;
13875 if( Group* otherGroup = recipient->GetGroup())
13877 Group* thisGroup = GetGroup();
13878 if(!thisGroup)
13879 return false;
13880 return thisGroup == otherGroup;
13882 return false;
13884 else
13885 // prevent other players from looting if the recipient got disconnected
13886 return !creature->hasLootRecipient();
13889 void Player::_LoadActions(QueryResult *result)
13891 m_actionButtons.clear();
13893 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
13895 if(result)
13899 Field *fields = result->Fetch();
13901 uint8 button = fields[0].GetUInt8();
13903 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
13905 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
13907 while( result->NextRow() );
13909 delete result;
13913 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
13915 m_Auras.clear();
13916 for (int i = 0; i < TOTAL_AURAS; i++)
13917 m_modAuras[i].clear();
13919 // all aura related fields
13920 for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
13921 SetUInt32Value(i, 0);
13923 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
13925 if(result)
13929 Field *fields = result->Fetch();
13930 uint64 caster_guid = fields[0].GetUInt64();
13931 uint32 spellid = fields[1].GetUInt32();
13932 uint32 effindex = fields[2].GetUInt32();
13933 uint32 stackcount = fields[3].GetUInt32();
13934 int32 damage = (int32)fields[4].GetUInt32();
13935 int32 maxduration = (int32)fields[5].GetUInt32();
13936 int32 remaintime = (int32)fields[6].GetUInt32();
13937 int32 remaincharges = (int32)fields[7].GetUInt32();
13939 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
13940 if(!spellproto)
13942 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
13943 continue;
13946 if(effindex >= 3)
13948 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
13949 continue;
13952 // negative effects should continue counting down after logout
13953 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
13955 if(remaintime <= int32(timediff))
13956 continue;
13958 remaintime -= timediff;
13961 // prevent wrong values of remaincharges
13962 if(spellproto->procCharges)
13964 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
13965 remaincharges = spellproto->procCharges;
13967 else
13968 remaincharges = -1;
13970 //do not load single target auras (unless they were cast by the player)
13971 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
13972 continue;
13974 for(uint32 i=0; i<stackcount; i++)
13976 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
13977 if(!damage)
13978 damage = aura->GetModifier()->m_amount;
13979 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
13980 AddAura(aura);
13981 sLog.outString("Added aura spellid %u, effect %u", spellproto->Id, effindex);
13984 while( result->NextRow() );
13986 delete result;
13989 if(m_class == CLASS_WARRIOR)
13990 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
13993 void Player::LoadCorpse()
13995 if( isAlive() )
13997 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
13999 else
14001 if(Corpse *corpse = GetCorpse())
14003 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14005 else
14007 //Prevent Dead Player login without corpse
14008 ResurrectPlayer(0.5f);
14013 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14015 //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());
14016 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14017 //NOTE: the "order by `bag`" is important because it makes sure
14018 //the bagMap is filled before items in the bags are loaded
14019 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14020 //expected to be equipped before offhand items (TODO: fixme)
14022 uint32 zone = GetZoneId();
14024 if (result)
14026 std::list<Item*> problematicItems;
14028 // prevent items from being added to the queue when stored
14029 m_itemUpdateQueueBlocked = true;
14032 Field *fields = result->Fetch();
14033 uint32 bag_guid = fields[1].GetUInt32();
14034 uint8 slot = fields[2].GetUInt8();
14035 uint32 item_guid = fields[3].GetUInt32();
14036 uint32 item_id = fields[4].GetUInt32();
14038 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14040 if(!proto)
14042 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14043 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14044 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14045 continue;
14048 Item *item = NewItemOrBag(proto);
14050 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14052 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14053 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14054 item->FSetState(ITEM_REMOVED);
14055 item->SaveToDB(); // it also deletes item object !
14056 continue;
14059 // not allow have in alive state item limited to another map/zone
14060 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14062 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14063 item->FSetState(ITEM_REMOVED);
14064 item->SaveToDB(); // it also deletes item object !
14065 continue;
14068 // "Conjured items disappear if you are logged out for more than 15 minutes"
14069 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14071 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14072 item->FSetState(ITEM_REMOVED);
14073 item->SaveToDB(); // it also deletes item object !
14074 continue;
14077 bool success = true;
14079 if (!bag_guid)
14081 // the item is not in a bag
14082 item->SetContainer( NULL );
14083 item->SetSlot(slot);
14085 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14087 ItemPosCountVec dest;
14088 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14089 item = StoreItem(dest, item, true);
14090 else
14091 success = false;
14093 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14095 uint16 dest;
14096 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14097 QuickEquipItem(dest, item);
14098 else
14099 success = false;
14101 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14103 ItemPosCountVec dest;
14104 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14105 item = BankItem(dest, item, true);
14106 else
14107 success = false;
14110 if(success)
14112 // store bags that may contain items in them
14113 if(item->IsBag() && IsBagPos(item->GetPos()))
14114 bagMap[item_guid] = (Bag*)item;
14117 else
14119 item->SetSlot(NULL_SLOT);
14120 // the item is in a bag, find the bag
14121 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14122 if(itr != bagMap.end())
14123 itr->second->StoreItem(slot, item, true );
14124 else
14125 success = false;
14128 // item's state may have changed after stored
14129 if (success)
14130 item->SetState(ITEM_UNCHANGED, this);
14131 else
14133 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);
14134 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14135 problematicItems.push_back(item);
14137 } while (result->NextRow());
14139 delete result;
14140 m_itemUpdateQueueBlocked = false;
14142 // send by mail problematic items
14143 while(!problematicItems.empty())
14145 // fill mail
14146 MailItemsInfo mi; // item list preparing
14148 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14150 Item* item = problematicItems.front();
14151 problematicItems.pop_front();
14153 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14156 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14158 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14161 //if(isAlive())
14162 _ApplyAllItemMods();
14165 // load mailed item which should receive current player
14166 void Player::_LoadMailedItems(Mail *mail)
14168 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14169 if(!result)
14170 return;
14174 Field *fields = result->Fetch();
14175 uint32 item_guid_low = fields[0].GetUInt32();
14176 uint32 item_template = fields[1].GetUInt32();
14178 mail->AddItem(item_guid_low, item_template);
14180 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14182 if(!proto)
14184 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);
14185 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14186 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14187 continue;
14190 Item *item = NewItemOrBag(proto);
14192 if(!item->LoadFromDB(item_guid_low, 0))
14194 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14195 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14196 item->FSetState(ITEM_REMOVED);
14197 item->SaveToDB(); // it also deletes item object !
14198 continue;
14201 AddMItem(item);
14202 } while (result->NextRow());
14204 delete result;
14207 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14209 //set a count of unread mails
14210 //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);
14211 if (resultUnread)
14213 Field *fieldMail = resultUnread->Fetch();
14214 unReadMails = fieldMail[0].GetUInt8();
14215 delete resultUnread;
14218 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14219 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14220 if (resultDelivery)
14222 Field *fieldMail = resultDelivery->Fetch();
14223 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14224 delete resultDelivery;
14228 void Player::_LoadMail()
14230 m_mail.clear();
14231 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14232 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());
14233 if(result)
14237 Field *fields = result->Fetch();
14238 Mail *m = new Mail;
14239 m->messageID = fields[0].GetUInt32();
14240 m->messageType = fields[1].GetUInt8();
14241 m->sender = fields[2].GetUInt32();
14242 m->receiver = fields[3].GetUInt32();
14243 m->subject = fields[4].GetCppString();
14244 m->itemTextId = fields[5].GetUInt32();
14245 bool has_items = fields[6].GetBool();
14246 m->expire_time = (time_t)fields[7].GetUInt64();
14247 m->deliver_time = (time_t)fields[8].GetUInt64();
14248 m->money = fields[9].GetUInt32();
14249 m->COD = fields[10].GetUInt32();
14250 m->checked = fields[11].GetUInt32();
14251 m->stationery = fields[12].GetUInt8();
14252 m->mailTemplateId = fields[13].GetInt16();
14254 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14256 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14257 m->mailTemplateId = 0;
14260 m->state = MAIL_STATE_UNCHANGED;
14262 if (has_items)
14263 _LoadMailedItems(m);
14265 m_mail.push_back(m);
14266 } while( result->NextRow() );
14267 delete result;
14269 m_mailsLoaded = true;
14272 void Player::LoadPet()
14274 //fixme: the pet should still be loaded if the player is not in world
14275 // just not added to the map
14276 if(IsInWorld())
14278 Pet *pet = new Pet;
14279 if(!pet->LoadPetFromDB(this,0,0,true))
14280 delete pet;
14284 void Player::_LoadQuestStatus(QueryResult *result)
14286 mQuestStatus.clear();
14288 uint32 slot = 0;
14290 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14291 //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());
14293 if(result)
14297 Field *fields = result->Fetch();
14299 uint32 quest_id = fields[0].GetUInt32();
14300 // used to be new, no delete?
14301 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14302 if( pQuest )
14304 // find or create
14305 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14307 uint32 qstatus = fields[1].GetUInt32();
14308 if(qstatus < MAX_QUEST_STATUS)
14309 questStatusData.m_status = QuestStatus(qstatus);
14310 else
14312 questStatusData.m_status = QUEST_STATUS_NONE;
14313 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14316 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14317 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14319 time_t quest_time = time_t(fields[4].GetUInt64());
14321 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14323 AddTimedQuest( quest_id );
14325 if (quest_time <= sWorld.GetGameTime())
14326 questStatusData.m_timer = 1;
14327 else
14328 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14330 else
14331 quest_time = 0;
14333 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14334 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14335 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14336 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14337 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14338 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14339 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14340 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14342 questStatusData.uState = QUEST_UNCHANGED;
14344 // add to quest log
14345 if( slot < MAX_QUEST_LOG_SIZE &&
14346 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14347 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14348 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14350 SetQuestSlot(slot,quest_id,quest_time);
14352 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14353 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14355 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14356 if(questStatusData.m_creatureOrGOcount[idx])
14357 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14359 ++slot;
14362 if(questStatusData.m_rewarded)
14364 // learn rewarded spell if unknown
14365 learnQuestRewardedSpells(pQuest);
14367 // set rewarded title if any
14368 if(pQuest->GetCharTitleId())
14370 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14371 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
14375 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14378 while( result->NextRow() );
14380 delete result;
14383 // clear quest log tail
14384 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14385 SetQuestSlot(i,0);
14388 void Player::_LoadDailyQuestStatus(QueryResult *result)
14390 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14391 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14393 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14395 if(result)
14397 uint32 quest_daily_idx = 0;
14401 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14403 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14404 break;
14407 Field *fields = result->Fetch();
14409 uint32 quest_id = fields[0].GetUInt32();
14411 // save _any_ from daily quest times (it must be after last reset anyway)
14412 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14414 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14415 if( !pQuest )
14416 continue;
14418 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14419 ++quest_daily_idx;
14421 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14423 while( result->NextRow() );
14425 delete result;
14428 m_DailyQuestChanged = false;
14431 void Player::_LoadReputation(QueryResult *result)
14433 m_factions.clear();
14435 // Set initial reputations (so everything is nifty before DB data load)
14436 SetInitialFactions();
14438 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14440 if(result)
14444 Field *fields = result->Fetch();
14446 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14447 if( factionEntry && (factionEntry->reputationListID >= 0))
14449 FactionState* faction = &m_factions[factionEntry->reputationListID];
14451 // update standing to current
14452 faction->Standing = int32(fields[1].GetUInt32());
14454 uint32 dbFactionFlags = fields[2].GetUInt32();
14456 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14457 SetFactionVisible(faction); // have internal checks for forced invisibility
14459 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14460 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14462 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14463 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14464 else // DB not at war
14466 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14467 if( faction->Flags & FACTION_FLAG_VISIBLE )
14468 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14471 // set atWar for hostile
14472 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14473 SetFactionAtWar(faction,true);
14475 // reset changed flag if values similar to saved in DB
14476 if(faction->Flags==dbFactionFlags)
14477 faction->Changed = false;
14480 while( result->NextRow() );
14482 delete result;
14486 void Player::_LoadSpells(QueryResult *result)
14488 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14489 delete itr->second;
14490 m_spells.clear();
14492 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14494 if(result)
14498 Field *fields = result->Fetch();
14500 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14502 while( result->NextRow() );
14504 delete result;
14508 void Player::_LoadTutorials(QueryResult *result)
14510 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14512 if(result)
14516 Field *fields = result->Fetch();
14518 for (int iI=0; iI<8; iI++)
14519 m_Tutorials[iI] = fields[iI].GetUInt32();
14521 while( result->NextRow() );
14523 delete result;
14526 m_TutorialsChanged = false;
14529 void Player::_LoadGroup(QueryResult *result)
14531 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14532 if(result)
14534 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14535 delete result;
14536 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14537 if(group)
14539 uint8 subgroup = group->GetMemberGroup(GetGUID());
14540 SetGroup(group, subgroup);
14541 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14543 // the group leader may change the instance difficulty while the player is offline
14544 SetDifficulty(group->GetDifficulty());
14550 void Player::_LoadBoundInstances(QueryResult *result)
14552 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14553 m_boundInstances[i].clear();
14555 Group *group = GetGroup();
14557 //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));
14558 if(result)
14562 Field *fields = result->Fetch();
14563 bool perm = fields[1].GetBool();
14564 uint32 mapId = fields[2].GetUInt32();
14565 uint32 instanceId = fields[0].GetUInt32();
14566 uint8 difficulty = fields[3].GetUInt8();
14567 time_t resetTime = (time_t)fields[4].GetUInt64();
14568 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14569 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14570 // and in that case it is not used
14572 if(!perm && group)
14574 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);
14575 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14576 continue;
14579 // since non permanent binds are always solo bind, they can always be reset
14580 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14581 if(save) BindToInstance(save, perm, true);
14582 } while(result->NextRow());
14583 delete result;
14587 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14589 // some instances only have one difficulty
14590 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14591 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14593 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14594 if(itr != m_boundInstances[difficulty].end())
14595 return &itr->second;
14596 else
14597 return NULL;
14600 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14602 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14603 UnbindInstance(itr, difficulty, unload);
14606 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14608 if(itr != m_boundInstances[difficulty].end())
14610 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14611 itr->second.save->RemovePlayer(this); // save can become invalid
14612 m_boundInstances[difficulty].erase(itr++);
14616 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14618 if(save)
14620 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14621 if(bind.save)
14623 // update the save when the group kills a boss
14624 if(permanent != bind.perm || save != bind.save)
14625 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());
14627 else
14628 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14630 if(bind.save != save)
14632 if(bind.save) bind.save->RemovePlayer(this);
14633 save->AddPlayer(this);
14636 if(permanent) save->SetCanReset(false);
14638 bind.save = save;
14639 bind.perm = permanent;
14640 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());
14641 return &bind;
14643 else
14644 return NULL;
14647 void Player::SendRaidInfo()
14649 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14651 uint32 counter = 0, i;
14652 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14653 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14654 if(itr->second.perm) counter++;
14656 data << counter;
14657 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14659 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14661 if(itr->second.perm)
14663 InstanceSave *save = itr->second.save;
14664 data << (save->GetMapId());
14665 data << (uint32)(save->GetResetTime() - time(NULL));
14666 data << save->GetInstanceId();
14667 data << uint32(counter);
14668 counter--;
14672 GetSession()->SendPacket(&data);
14676 - called on every successful teleportation to a map
14678 void Player::SendSavedInstances()
14680 bool hasBeenSaved = false;
14681 WorldPacket data;
14683 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14685 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14687 if(itr->second.perm) // only permanent binds are sent
14689 hasBeenSaved = true;
14690 break;
14695 //Send opcode 811. true or false means, whether you have current raid/heroic instances
14696 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
14697 data << uint32(hasBeenSaved);
14698 GetSession()->SendPacket(&data);
14700 if(!hasBeenSaved)
14701 return;
14703 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14705 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14707 if(itr->second.perm)
14709 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
14710 data << uint32(itr->second.save->GetMapId());
14711 GetSession()->SendPacket(&data);
14717 /// convert the player's binds to the group
14718 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
14720 bool has_binds = false;
14721 bool has_solo = false;
14723 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
14724 assert(player_guid);
14726 // copy all binds to the group, when changing leader it's assumed the character
14727 // will not have any solo binds
14729 if(player)
14731 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14733 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
14735 has_binds = true;
14736 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
14737 // permanent binds are not removed
14738 if(!itr->second.perm)
14740 player->UnbindInstance(itr, i, true); // increments itr
14741 has_solo = true;
14743 else
14744 ++itr;
14749 // if the player's not online we don't know what binds it has
14750 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));
14751 // the following should not get executed when changing leaders
14752 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
14755 bool Player::_LoadHomeBind(QueryResult *result)
14757 bool ok = false;
14758 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14759 if (result)
14761 Field *fields = result->Fetch();
14762 m_homebindMapId = fields[0].GetUInt32();
14763 m_homebindZoneId = fields[1].GetUInt16();
14764 m_homebindX = fields[2].GetFloat();
14765 m_homebindY = fields[3].GetFloat();
14766 m_homebindZ = fields[4].GetFloat();
14767 delete result;
14769 // accept saved data only for valid position (and non instanceable)
14770 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
14771 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
14773 ok = true;
14775 else
14776 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14779 if(!ok)
14781 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
14782 if(!info) return false;
14784 m_homebindMapId = info->mapId;
14785 m_homebindZoneId = info->zoneId;
14786 m_homebindX = info->positionX;
14787 m_homebindY = info->positionY;
14788 m_homebindZ = info->positionZ;
14790 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);
14793 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
14794 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
14796 return true;
14799 /*********************************************************/
14800 /*** SAVE SYSTEM ***/
14801 /*********************************************************/
14803 void Player::SaveToDB()
14805 // delay auto save at any saves (manual, in code, or autosave)
14806 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
14808 // first save/honor gain after midnight will also update the player's honor fields
14809 UpdateHonorFields();
14811 // Must saved before enter into BattleGround
14812 if(InBattleGround())
14813 return;
14815 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
14816 //save, far from tavern/city
14817 //save, but in tavern/city
14818 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
14819 outDebugValues();
14821 // save state (after auras removing), if aura remove some flags then it must set it back by self)
14822 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
14823 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
14824 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
14825 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
14826 uint32 tmp_displayid = GetDisplayId();
14828 // Set player sit state to standing on save, also stealth and shifted form
14829 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
14830 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
14831 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
14832 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
14833 SetDisplayId(GetNativeDisplayId());
14835 bool inworld = IsInWorld();
14837 CharacterDatabase.BeginTransaction();
14839 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
14841 std::string sql_name = m_name;
14842 CharacterDatabase.escape_string(sql_name);
14844 std::ostringstream ss;
14845 ss << "INSERT INTO characters (guid,account,name,race,class,"
14846 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
14847 "taximask, online, cinematic, "
14848 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
14849 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
14850 "death_expire_time, taxi_path) VALUES ("
14851 << GetGUIDLow() << ", "
14852 << GetSession()->GetAccountId() << ", '"
14853 << sql_name << "', "
14854 << m_race << ", "
14855 << m_class << ", ";
14857 bool save_to_dest = false;
14858 if(IsBeingTeleported())
14860 // don't save to battlegrounds or arenas
14861 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
14862 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
14863 save_to_dest = true;
14866 if(!save_to_dest)
14868 ss << GetMapId() << ", "
14869 << (uint32)GetDifficulty() << ", "
14870 << finiteAlways(GetPositionX()) << ", "
14871 << finiteAlways(GetPositionY()) << ", "
14872 << finiteAlways(GetPositionZ()) << ", "
14873 << finiteAlways(GetOrientation()) << ", '";
14875 else
14877 ss << GetTeleportDest().mapid << ", "
14878 << (uint32)GetDifficulty() << ", "
14879 << finiteAlways(GetTeleportDest().x) << ", "
14880 << finiteAlways(GetTeleportDest().y) << ", "
14881 << finiteAlways(GetTeleportDest().z) << ", "
14882 << finiteAlways(GetTeleportDest().o) << ", '";
14885 uint16 i;
14886 for( i = 0; i < m_valuesCount; i++ )
14888 ss << GetUInt32Value(i) << " ";
14891 ss << "', '";
14893 for( i = 0; i < 8; i++ )
14894 ss << m_taxi.GetTaximask(i) << " ";
14896 ss << "', ";
14897 ss << (inworld ? 1 : 0);
14899 ss << ", ";
14900 ss << m_cinematic;
14902 ss << ", ";
14903 ss << m_Played_time[0];
14904 ss << ", ";
14905 ss << m_Played_time[1];
14907 ss << ", ";
14908 ss << finiteAlways(m_rest_bonus);
14909 ss << ", ";
14910 ss << (uint64)time(NULL);
14911 ss << ", ";
14912 ss << is_save_resting;
14913 ss << ", ";
14914 ss << m_resetTalentsCost;
14915 ss << ", ";
14916 ss << (uint64)m_resetTalentsTime;
14918 ss << ", ";
14919 ss << finiteAlways(m_movementInfo.t_x);
14920 ss << ", ";
14921 ss << finiteAlways(m_movementInfo.t_y);
14922 ss << ", ";
14923 ss << finiteAlways(m_movementInfo.t_z);
14924 ss << ", ";
14925 ss << finiteAlways(m_movementInfo.t_o);
14926 ss << ", ";
14927 if (m_transport)
14928 ss << m_transport->GetGUIDLow();
14929 else
14930 ss << "0";
14932 ss << ", ";
14933 ss << m_ExtraFlags;
14935 ss << ", ";
14936 ss << uint32(m_stableSlots); // to prevent save uint8 as char
14938 ss << ", ";
14939 ss << uint32(m_atLoginFlags);
14941 ss << ", ";
14942 ss << GetZoneId();
14944 ss << ", ";
14945 ss << (uint64)m_deathExpireTime;
14947 ss << ", '";
14948 ss << m_taxi.SaveTaxiDestinationsToString();
14949 ss << "' )";
14951 CharacterDatabase.Execute( ss.str().c_str() );
14953 if(m_mailsUpdated) //save mails only when needed
14954 _SaveMail();
14956 _SaveInventory();
14957 _SaveQuestStatus();
14958 _SaveDailyQuestStatus();
14959 _SaveTutorials();
14960 _SaveSpells();
14961 _SaveSpellCooldowns();
14962 _SaveActions();
14963 _SaveAuras();
14964 _SaveReputation();
14966 CharacterDatabase.CommitTransaction();
14968 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
14969 SetDisplayId(tmp_displayid);
14970 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
14971 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
14972 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
14973 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
14975 // save pet (hunter pet level and experience and all type pets health/mana).
14976 if(Pet* pet = GetPet())
14977 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
14980 // fast save function for item/money cheating preventing - save only inventory and money state
14981 void Player::SaveInventoryAndGoldToDB()
14983 _SaveInventory();
14984 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
14987 void Player::_SaveActions()
14989 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
14991 switch (itr->second.uState)
14993 case ACTIONBUTTON_NEW:
14994 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
14995 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
14996 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14997 ++itr;
14998 break;
14999 case ACTIONBUTTON_CHANGED:
15000 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15001 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15002 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15003 ++itr;
15004 break;
15005 case ACTIONBUTTON_DELETED:
15006 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15007 m_actionButtons.erase(itr++);
15008 break;
15009 default:
15010 ++itr;
15011 break;
15016 void Player::_SaveAuras()
15018 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15020 AuraMap const& auras = GetAuras();
15022 if (auras.empty())
15023 return;
15025 spellEffectPair lastEffectPair = auras.begin()->first;
15026 uint32 stackCounter = 1;
15028 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15030 if(itr == auras.end() || lastEffectPair != itr->first)
15032 AuraMap::const_iterator itr2 = itr;
15033 // save previous spellEffectPair to db
15034 itr2--;
15035 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15037 //skip all auras from spells that are passive or need a shapeshift
15038 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15040 //do not save single target auras (unless they were cast by the player)
15041 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15043 uint8 i;
15044 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15045 for (i = 0; i < 3; i++)
15046 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15047 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15048 break;
15050 if (i == 3)
15052 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15053 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15054 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));
15059 if(itr == auras.end())
15060 break;
15063 if (lastEffectPair == itr->first)
15064 stackCounter++;
15065 else
15067 lastEffectPair = itr->first;
15068 stackCounter = 1;
15073 void Player::_SaveInventory()
15075 // force items in buyback slots to new state
15076 // and remove those that aren't already
15077 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15079 Item *item = m_items[i];
15080 if (!item || item->GetState() == ITEM_NEW) continue;
15081 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15082 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15083 m_items[i]->FSetState(ITEM_NEW);
15086 // update enchantment durations
15087 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15089 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15092 // if no changes
15093 if (m_itemUpdateQueue.empty()) return;
15095 // do not save if the update queue is corrupt
15096 bool error = false;
15097 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15099 Item *item = m_itemUpdateQueue[i];
15100 if(!item || item->GetState() == ITEM_REMOVED) continue;
15101 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15103 if (test == NULL)
15105 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());
15106 error = true;
15108 else if (test != item)
15110 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());
15111 error = true;
15115 if (error)
15117 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15118 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15119 return;
15122 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15124 Item *item = m_itemUpdateQueue[i];
15125 if(!item) continue;
15127 Bag *container = item->GetContainer();
15128 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15130 switch(item->GetState())
15132 case ITEM_NEW:
15133 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());
15134 break;
15135 case ITEM_CHANGED:
15136 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());
15137 break;
15138 case ITEM_REMOVED:
15139 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15140 break;
15141 case ITEM_UNCHANGED:
15142 break;
15145 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15147 m_itemUpdateQueue.clear();
15150 void Player::_SaveMail()
15152 if (!m_mailsLoaded)
15153 return;
15155 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
15157 Mail *m = (*itr);
15158 if (m->state == MAIL_STATE_CHANGED)
15160 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'",
15161 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15162 if(m->removedItems.size())
15164 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15165 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15166 m->removedItems.clear();
15168 m->state = MAIL_STATE_UNCHANGED;
15170 else if (m->state == MAIL_STATE_DELETED)
15172 if (m->HasItems())
15173 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15174 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15175 if (m->itemTextId)
15176 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15177 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15178 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15182 //deallocate deleted mails...
15183 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15185 if ((*itr)->state == MAIL_STATE_DELETED)
15187 Mail* m = *itr;
15188 m_mail.erase(itr);
15189 delete m;
15190 itr = m_mail.begin();
15192 else
15193 ++itr;
15196 m_mailsUpdated = false;
15199 void Player::_SaveQuestStatus()
15201 // we don't need transactions here.
15202 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15204 switch (i->second.uState)
15206 case QUEST_NEW :
15207 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15208 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15209 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]);
15210 break;
15211 case QUEST_CHANGED :
15212 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' ",
15213 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 );
15214 break;
15215 case QUEST_UNCHANGED:
15216 break;
15218 i->second.uState = QUEST_UNCHANGED;
15222 void Player::_SaveDailyQuestStatus()
15224 if(!m_DailyQuestChanged)
15225 return;
15227 m_DailyQuestChanged = false;
15229 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15231 // we don't need transactions here.
15232 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15233 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15234 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15235 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15236 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15239 void Player::_SaveReputation()
15241 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15243 if (itr->second.Changed)
15245 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15246 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);
15247 itr->second.Changed = false;
15252 void Player::_SaveSpells()
15254 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15256 ++next;
15257 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15258 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15259 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15260 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);
15262 if (itr->second->state == PLAYERSPELL_REMOVED)
15263 _removeSpell(itr->first);
15264 else
15265 itr->second->state = PLAYERSPELL_UNCHANGED;
15269 void Player::_SaveTutorials()
15271 if(!m_TutorialsChanged)
15272 return;
15274 uint32 Rows=0;
15275 // it's better than rebuilding indexes multiple times
15276 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15277 if(result)
15279 Rows = result->Fetch()[0].GetUInt32();
15280 delete result;
15283 if (Rows)
15285 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'",
15286 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 );
15288 else
15290 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]);
15293 m_TutorialsChanged = false;
15296 void Player::outDebugValues() const
15298 if(!sLog.IsOutDebug()) // optimize disabled debug output
15299 return;
15301 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15302 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15303 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15304 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15305 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15306 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15307 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15308 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15309 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15310 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15311 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15312 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15315 /*********************************************************/
15316 /*** FLOOD FILTER SYSTEM ***/
15317 /*********************************************************/
15319 void Player::UpdateSpeakTime()
15321 // ignore chat spam protection for GMs in any mode
15322 if(GetSession()->GetSecurity() > SEC_PLAYER)
15323 return;
15325 time_t current = time (NULL);
15326 if(m_speakTime > current)
15328 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15329 if(!max_count)
15330 return;
15332 ++m_speakCount;
15333 if(m_speakCount >= max_count)
15335 // prevent overwrite mute time, if message send just before mutes set, for example.
15336 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15337 if(GetSession()->m_muteTime < new_mute)
15338 GetSession()->m_muteTime = new_mute;
15340 m_speakCount = 0;
15343 else
15344 m_speakCount = 0;
15346 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15349 bool Player::CanSpeak() const
15351 return GetSession()->m_muteTime <= time (NULL);
15354 /*********************************************************/
15355 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15356 /*********************************************************/
15358 void Player::SendAttackSwingNotInRange()
15360 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15361 GetSession()->SendPacket( &data );
15364 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15366 std::ostringstream ss;
15367 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15368 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15369 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15370 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15371 sLog.outDebug(ss.str().c_str());
15372 CharacterDatabase.Execute(ss.str().c_str());
15375 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15377 std::ostringstream ss2;
15378 ss2<<"UPDATE characters SET data='";
15379 int i=0;
15380 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15382 ss2<<tokens[i]<<" ";
15384 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15386 return CharacterDatabase.Execute(ss2.str().c_str());
15389 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15391 char buf[11];
15392 snprintf(buf,11,"%u",value);
15394 if(index >= tokens.size())
15395 return;
15397 tokens[index] = buf;
15400 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15402 Tokens tokens;
15403 if(!LoadValuesArrayFromDB(tokens,guid))
15404 return;
15406 if(index >= tokens.size())
15407 return;
15409 char buf[11];
15410 snprintf(buf,11,"%u",value);
15411 tokens[index] = buf;
15413 SaveValuesArrayInDB(tokens,guid);
15416 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15418 uint32 temp;
15419 memcpy(&temp, &value, sizeof(value));
15420 Player::SetUInt32ValueInDB(index, temp, guid);
15423 void Player::SendAttackSwingNotStanding()
15425 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15426 GetSession()->SendPacket( &data );
15429 void Player::SendAttackSwingDeadTarget()
15431 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15432 GetSession()->SendPacket( &data );
15435 void Player::SendAttackSwingCantAttack()
15437 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15438 GetSession()->SendPacket( &data );
15441 void Player::SendAttackSwingCancelAttack()
15443 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15444 GetSession()->SendPacket( &data );
15447 void Player::SendAttackSwingBadFacingAttack()
15449 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15450 GetSession()->SendPacket( &data );
15453 void Player::SendAutoRepeatCancel()
15455 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, 0);
15456 GetSession()->SendPacket( &data );
15459 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15461 WorldPacket data(SMSG_PLAY_SOUND, 4);
15462 data << Sound;
15463 if (OnlySelf)
15464 GetSession()->SendPacket( &data );
15465 else
15466 SendMessageToSet( &data, true );
15469 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15471 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15472 data << Area;
15473 data << Experience;
15474 GetSession()->SendPacket(&data);
15477 void Player::SendDungeonDifficulty(bool IsInGroup)
15479 uint8 val = 0x00000001;
15480 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15481 data << (uint32)GetDifficulty();
15482 data << uint32(val);
15483 data << uint32(IsInGroup);
15484 GetSession()->SendPacket(&data);
15487 void Player::SendResetFailedNotify(uint32 mapid)
15489 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15490 data << uint32(mapid);
15491 GetSession()->SendPacket(&data);
15494 /// Reset all solo instances and optionally send a message on success for each
15495 void Player::ResetInstances(uint8 method)
15497 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15499 // we assume that when the difficulty changes, all instances that can be reset will be
15500 uint8 dif = GetDifficulty();
15502 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15504 InstanceSave *p = itr->second.save;
15505 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15506 if(!entry || !p->CanReset())
15508 ++itr;
15509 continue;
15512 if(method == INSTANCE_RESET_ALL)
15514 // the "reset all instances" method can only reset normal maps
15515 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15517 ++itr;
15518 continue;
15522 // if the map is loaded, reset it
15523 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15524 if(map && map->IsDungeon())
15525 ((InstanceMap*)map)->Reset(method);
15527 // since this is a solo instance there should not be any players inside
15528 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15529 SendResetInstanceSuccess(p->GetMapId());
15531 p->DeleteFromDB();
15532 m_boundInstances[dif].erase(itr++);
15534 // the following should remove the instance save from the manager and delete it as well
15535 p->RemovePlayer(this);
15539 void Player::SendResetInstanceSuccess(uint32 MapId)
15541 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15542 data << MapId;
15543 GetSession()->SendPacket(&data);
15546 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15548 // TODO: find what other fail reasons there are besides players in the instance
15549 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15550 data << reason;
15551 data << MapId;
15552 GetSession()->SendPacket(&data);
15555 /*********************************************************/
15556 /*** Update timers ***/
15557 /*********************************************************/
15559 ///checks the 15 afk reports per 5 minutes limit
15560 void Player::UpdateAfkReport(time_t currTime)
15562 if(m_bgAfkReportedTimer <= currTime)
15564 m_bgAfkReportedCount = 0;
15565 m_bgAfkReportedTimer = currTime+5*MINUTE;
15569 void Player::UpdateContestedPvP(uint32 diff)
15571 if(!m_contestedPvPTimer||isInCombat())
15572 return;
15573 if(m_contestedPvPTimer <= diff)
15575 ResetContestedPvP();
15577 else
15578 m_contestedPvPTimer -= diff;
15581 void Player::UpdatePvPFlag(time_t currTime)
15583 if(!IsPvP())
15584 return;
15585 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15586 return;
15588 UpdatePvP(false);
15591 void Player::UpdateDuelFlag(time_t currTime)
15593 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15594 return;
15596 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15597 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15599 duel->startTimer = 0;
15600 duel->startTime = currTime;
15601 duel->opponent->duel->startTimer = 0;
15602 duel->opponent->duel->startTime = currTime;
15605 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15607 if(!pet)
15608 pet = GetPet();
15610 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15612 //returning of reagents only for players, so best done here
15613 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
15614 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15616 if(spellInfo)
15618 for(uint32 i = 0; i < 7; ++i)
15620 if(spellInfo->Reagent[i] > 0)
15622 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15623 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
15624 if( msg == EQUIP_ERR_OK )
15626 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
15627 if(IsInWorld())
15628 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
15633 m_temporaryUnsummonedPetNumber = 0;
15636 if(!pet || pet->GetOwnerGUID()!=GetGUID())
15637 return;
15639 // only if current pet in slot
15640 switch(pet->getPetType())
15642 case MINI_PET:
15643 m_miniPet = 0;
15644 break;
15645 case GUARDIAN_PET:
15646 m_guardianPets.erase(pet->GetGUID());
15647 break;
15648 default:
15649 if(GetPetGUID()==pet->GetGUID())
15650 SetPet(0);
15651 break;
15654 pet->CombatStop();
15656 if(returnreagent)
15658 switch(pet->GetEntry())
15660 //warlock pets except imp are removed(?) when logging out
15661 case 1860:
15662 case 1863:
15663 case 417:
15664 case 17252:
15665 mode = PET_SAVE_NOT_IN_SLOT;
15666 break;
15670 pet->SavePetToDB(mode);
15672 pet->CleanupsBeforeDelete();
15673 pet->AddObjectToRemoveList();
15674 pet->m_removed = true;
15676 if(pet->isControlled())
15678 WorldPacket data(SMSG_PET_SPELLS, 8);
15679 data << uint64(0);
15680 GetSession()->SendPacket(&data);
15682 if(GetGroup())
15683 SetGroupUpdateFlag(GROUP_UPDATE_PET);
15687 void Player::RemoveMiniPet()
15689 if(Pet* pet = GetMiniPet())
15691 pet->Remove(PET_SAVE_AS_DELETED);
15692 m_miniPet = 0;
15696 Pet* Player::GetMiniPet()
15698 if(!m_miniPet)
15699 return NULL;
15700 return ObjectAccessor::GetPet(m_miniPet);
15703 void Player::RemoveGuardians()
15705 while(!m_guardianPets.empty())
15707 uint64 guid = *m_guardianPets.begin();
15708 if(Pet* pet = ObjectAccessor::GetPet(guid))
15709 pet->Remove(PET_SAVE_AS_DELETED);
15711 m_guardianPets.erase(guid);
15715 bool Player::HasGuardianWithEntry(uint32 entry)
15717 // pet guid middle part is entry (and creature also)
15718 // and in guardian list must be guardians with same entry _always_
15719 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
15720 if(GUID_ENPART(*itr)==entry)
15721 return true;
15723 return false;
15726 void Player::Uncharm()
15728 Unit* charm = GetCharm();
15729 if(!charm)
15730 return;
15732 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
15733 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
15736 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, std::string text, uint32 language) const
15738 *data << (uint8)msgtype;
15739 *data << (uint32)language;
15740 *data << (uint64)GetGUID();
15741 *data << (uint32)language; //language 2.1.0 ?
15742 *data << (uint64)GetGUID();
15743 *data << (uint32)(text.length()+1);
15744 *data << text;
15745 *data << (uint8)chatTag();
15748 void Player::Say(const std::string text, const uint32 language)
15750 WorldPacket data(SMSG_MESSAGECHAT, 200);
15751 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
15752 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
15755 void Player::Yell(const std::string text, const uint32 language)
15757 WorldPacket data(SMSG_MESSAGECHAT, 200);
15758 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
15759 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
15762 void Player::TextEmote(const std::string text)
15764 WorldPacket data(SMSG_MESSAGECHAT, 200);
15765 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
15766 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
15769 void Player::Whisper(std::string text, uint32 language,uint64 receiver)
15771 if (language != LANG_ADDON) // if not addon data
15772 language = LANG_UNIVERSAL; // whispers should always be readable
15774 Player *rPlayer = objmgr.GetPlayer(receiver);
15776 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15777 if(!rPlayer->isDND() || isGameMaster())
15779 WorldPacket data(SMSG_MESSAGECHAT, 200);
15780 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
15781 rPlayer->GetSession()->SendPacket(&data);
15783 data.Initialize(SMSG_MESSAGECHAT, 200);
15784 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
15785 GetSession()->SendPacket(&data);
15787 else
15789 // announce to player that player he is whispering to is dnd and cannot receive his message
15790 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
15793 if(!isAcceptWhispers())
15795 SetAcceptWhispers(true);
15796 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
15799 // announce to player that player he is whispering to is afk
15800 if(rPlayer->isAFK())
15801 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
15803 // if player whisper someone, auto turn of dnd to be able to receive an answer
15804 if(isDND() && !rPlayer->isGameMaster())
15805 ToggleDND();
15808 void Player::PetSpellInitialize()
15810 Pet* pet = GetPet();
15812 if(pet)
15814 uint8 addlist = 0;
15816 sLog.outDebug("Pet Spells Groups");
15818 CreatureInfo const *cinfo = pet->GetCreatureInfo();
15820 if(pet->isControlled() && (pet->getPetType() == HUNTER_PET || cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK))
15822 for(PetSpellMap::iterator itr = pet->m_spells.begin();itr != pet->m_spells.end();itr++)
15824 if(itr->second->state == PETSPELL_REMOVED)
15825 continue;
15826 ++addlist;
15830 // first line + actionbar + spellcount + spells + last adds
15831 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);
15833 CharmInfo *charmInfo = pet->GetCharmInfo();
15835 //16
15836 data << (uint64)pet->GetGUID() << uint32(0x00000000) << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
15838 for(uint32 i = 0; i < 10; i++) //40
15840 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15843 data << uint8(addlist); //1
15845 if(addlist && pet->isControlled())
15847 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
15849 if(itr->second->state == PETSPELL_REMOVED)
15850 continue;
15852 data << uint16(itr->first);
15853 data << uint16(itr->second->active); // pet spell active state isn't boolean
15857 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
15858 uint8 count = 3; //1+8+8+8=25
15860 // if count = 0, then end of packet...
15861 data << count;
15862 // uint32 value is spell id...
15863 // uint64 value is constant 0, unknown...
15864 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15865 //data << uint32(0x5fd1) << uint64(0); // if count = 2
15866 data << uint32(0x8e8c) << uint64(0); // if count = 3
15867 data << uint32(0x8e8b) << uint64(0); // if count = 3
15869 GetSession()->SendPacket(&data);
15873 void Player::PossessSpellInitialize()
15875 Unit* charm = GetCharm();
15877 if(!charm)
15878 return;
15880 CharmInfo *charmInfo = charm->GetCharmInfo();
15882 if(!charmInfo)
15884 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15885 return;
15888 uint8 addlist = 0;
15889 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15891 //16
15892 data << (uint64)charm->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);
15894 for(uint32 i = 0; i < 10; i++) //40
15896 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15899 data << uint8(addlist); //1
15901 uint8 count = 3;
15902 data << count;
15903 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15904 data << uint32(0x8e8c) << uint64(0); // if count = 3
15905 data << uint32(0x8e8b) << uint64(0); // if count = 3
15907 GetSession()->SendPacket(&data);
15910 void Player::CharmSpellInitialize()
15912 Unit* charm = GetCharm();
15914 if(!charm)
15915 return;
15917 CharmInfo *charmInfo = charm->GetCharmInfo();
15918 if(!charmInfo)
15920 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15921 return;
15924 uint8 addlist = 0;
15926 if(charm->GetTypeId() != TYPEID_PLAYER)
15928 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
15930 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
15932 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15934 if(charmInfo->GetCharmSpell(i)->spellId)
15935 ++addlist;
15940 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15942 data << (uint64)charm->GetGUID() << uint32(0x00000000);
15944 if(charm->GetTypeId() != TYPEID_PLAYER)
15945 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
15946 else
15947 data << uint8(0) << uint8(0);
15949 data << uint16(0);
15951 for(uint32 i = 0; i < 10; i++) //40
15953 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15956 data << uint8(addlist); //1
15958 if(addlist)
15960 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15962 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
15963 if(cspell->spellId)
15965 data << uint16(cspell->spellId);
15966 data << uint16(cspell->active);
15971 uint8 count = 3;
15972 data << count;
15973 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15974 data << uint32(0x8e8c) << uint64(0); // if count = 3
15975 data << uint32(0x8e8b) << uint64(0); // if count = 3
15977 GetSession()->SendPacket(&data);
15980 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
15982 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15983 if (!spellInfo) return 0;
15984 int32 total = 0;
15985 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15987 SpellModifier *mod = *itr;
15989 if(!IsAffectedBySpellmod(spellInfo,mod))
15990 continue;
15992 if (mod->type == SPELLMOD_FLAT)
15993 total += mod->value;
15995 return total;
15998 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
16000 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16001 if (!spellInfo) return 0;
16002 int32 total = 0;
16003 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16005 SpellModifier *mod = *itr;
16007 if(!IsAffectedBySpellmod(spellInfo,mod))
16008 continue;
16010 if (mod->type == SPELLMOD_PCT)
16011 total += mod->value;
16013 return total;
16016 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16018 if (!mod || !spellInfo)
16019 return false;
16021 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16023 // prevent apply to any spell except spell that trigger expire
16024 if(spell)
16026 if(mod->lastAffected != spell)
16027 return false;
16029 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16030 return false;
16033 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
16036 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16038 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16040 for(int eff=0;eff<64;++eff)
16042 uint64 _mask = uint64(1) << eff;
16043 if ( mod->mask & _mask)
16045 int32 val = 0;
16046 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16048 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
16049 val += (*itr)->value;
16051 val += apply ? mod->value : -(mod->value);
16052 WorldPacket data(Opcode, (1+1+4));
16053 data << uint8(eff);
16054 data << uint8(mod->op);
16055 data << int32(val);
16056 SendDirectMessage(&data);
16060 if (apply)
16061 m_spellMods[mod->op].push_back(mod);
16062 else
16064 if (mod->charges == -1)
16065 --m_SpellModRemoveCount;
16066 m_spellMods[mod->op].remove(mod);
16067 delete mod;
16071 void Player::RemoveSpellMods(Spell const* spell)
16073 if(!spell || (m_SpellModRemoveCount == 0))
16074 return;
16076 for(int i=0;i<MAX_SPELLMOD;++i)
16078 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16080 SpellModifier *mod = *itr;
16081 ++itr;
16083 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16085 RemoveAurasDueToSpell(mod->spellId);
16086 if (m_spellMods[i].empty())
16087 break;
16088 else
16089 itr = m_spellMods[i].begin();
16095 // send Proficiency
16096 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16098 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16099 data << pr1 << pr2;
16100 GetSession()->SendPacket (&data);
16103 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16105 QueryResult *result = NULL;
16106 if(type==10)
16107 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16108 else
16109 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16110 if(result)
16112 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.
16113 { // and SendPetitionQueryOpcode reads data from the DB
16114 Field *fields = result->Fetch();
16115 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16116 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16118 // send update if charter owner in game
16119 Player* owner = objmgr.GetPlayer(ownerguid);
16120 if(owner)
16121 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16123 } while ( result->NextRow() );
16125 delete result;
16127 if(type==10)
16128 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16129 else
16130 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16133 CharacterDatabase.BeginTransaction();
16134 if(type == 10)
16136 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16137 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16139 else
16141 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16142 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16144 CharacterDatabase.CommitTransaction();
16147 void Player::SetRestBonus (float rest_bonus_new)
16149 // Prevent resting on max level
16150 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16151 rest_bonus_new = 0;
16153 if(rest_bonus_new < 0)
16154 rest_bonus_new = 0;
16156 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16158 if(rest_bonus_new > rest_bonus_max)
16159 m_rest_bonus = rest_bonus_max;
16160 else
16161 m_rest_bonus = rest_bonus_new;
16163 // update data for client
16164 if(m_rest_bonus>10)
16165 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16166 else if(m_rest_bonus<=1)
16167 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16169 //RestTickUpdate
16170 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16173 void Player::HandleStealthedUnitsDetection()
16175 std::list<Unit*> stealthedUnits;
16177 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16178 Cell cell(p);
16179 cell.data.Part.reserved = ALL_DISTRICT;
16180 cell.SetNoCreate();
16182 MaNGOS::AnyStealthedCheck u_check;
16183 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16185 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16186 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16188 CellLock<GridReadGuard> cell_lock(cell, p);
16189 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16190 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16192 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16194 if((*i)==this)
16196 i = stealthedUnits.erase(i);
16197 continue;
16200 if ((*i)->isVisibleForOrDetect(this,true))
16203 (*i)->SendUpdateToPlayer(this);
16204 m_clientGUIDs.insert((*i)->GetGUID());
16206 #ifdef MANGOS_DEBUG
16207 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16208 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16209 #endif
16211 // target aura duration for caster show only if target exist at caster client
16212 // send data at target visibility change (adding to client)
16213 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16214 SendAuraDurationsForTarget(*i);
16216 i = stealthedUnits.erase(i);
16217 continue;
16220 ++i;
16224 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16226 if(nodes.size() < 2)
16227 return false;
16229 // not let cheating with start flight mounted
16230 if(IsMounted())
16232 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16233 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16234 GetSession()->SendPacket(&data);
16235 return false;
16238 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16240 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16241 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16242 GetSession()->SendPacket(&data);
16243 return false;
16246 // 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
16247 if(GetSession()->isLogingOut() ||
16248 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16249 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16250 IsNonMeleeSpellCasted(false) ||
16251 isInCombat())
16253 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16254 data << uint32(ERR_TAXIPLAYERBUSY);
16255 GetSession()->SendPacket(&data);
16256 return false;
16259 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16260 return false;
16262 uint32 sourcenode = nodes[0];
16264 // starting node too far away (cheat?)
16265 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16266 if( !node || node->map_id != GetMapId() ||
16267 (node->x - GetPositionX())*(node->x - GetPositionX())+
16268 (node->y - GetPositionY())*(node->y - GetPositionY())+
16269 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16270 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16272 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16273 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16274 GetSession()->SendPacket(&data);
16275 return false;
16278 // Prepare to flight start now
16280 // stop combat at start taxi flight if any
16281 CombatStop();
16283 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16284 TradeCancel(true);
16286 // clean not finished taxi path if any
16287 m_taxi.ClearTaxiDestinations();
16289 // 0 element current node
16290 m_taxi.AddTaxiDestination(sourcenode);
16292 // fill destinations path tail
16293 uint32 sourcepath = 0;
16294 uint32 totalcost = 0;
16296 uint32 prevnode = sourcenode;
16297 uint32 lastnode = 0;
16299 for(uint32 i = 1; i < nodes.size(); ++i)
16301 uint32 path, cost;
16303 lastnode = nodes[i];
16304 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16306 if(!path)
16308 m_taxi.ClearTaxiDestinations();
16309 return false;
16312 totalcost += cost;
16314 if(prevnode == sourcenode)
16315 sourcepath = path;
16317 m_taxi.AddTaxiDestination(lastnode);
16319 prevnode = lastnode;
16322 if(!mount_id) // if not provide then attempt use default.
16323 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16325 if (mount_id == 0 || sourcepath == 0)
16327 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16328 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16329 GetSession()->SendPacket(&data);
16330 m_taxi.ClearTaxiDestinations();
16331 return false;
16334 uint32 money = GetMoney();
16336 if(npc)
16338 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16341 if(money < totalcost)
16343 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16344 data << uint32(ERR_TAXINOTENOUGHMONEY);
16345 GetSession()->SendPacket(&data);
16346 m_taxi.ClearTaxiDestinations();
16347 return false;
16350 //Checks and preparations done, DO FLIGHT
16351 ModifyMoney(-(int32)totalcost);
16353 // prevent stealth flight
16354 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16356 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16357 data << uint32(ERR_TAXIOK);
16358 GetSession()->SendPacket(&data);
16360 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16362 GetSession()->SendDoFlight(mount_id, sourcepath);
16364 return true;
16367 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16369 // last check 2.0.10
16370 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16371 data << GetGUID();
16372 data << uint8(0x0); // flags (0x1, 0x2)
16373 time_t curTime = time(NULL);
16374 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16376 if (itr->second->state == PLAYERSPELL_REMOVED)
16377 continue;
16378 uint32 unSpellId = itr->first;
16379 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16380 if (!spellInfo)
16382 ASSERT(spellInfo);
16383 continue;
16386 // Not send cooldown for this spells
16387 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16388 continue;
16390 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16392 data << unSpellId;
16393 data << unTimeMs; // in m.secs
16394 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16397 GetSession()->SendPacket(&data);
16400 void Player::InitDataForForm(bool reapplyMods)
16402 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16403 if(ssEntry && ssEntry->attackSpeed)
16405 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16406 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16407 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16409 else
16410 SetRegularAttackTime();
16412 switch(m_form)
16414 case FORM_CAT:
16416 if(getPowerType()!=POWER_ENERGY)
16417 setPowerType(POWER_ENERGY);
16418 break;
16420 case FORM_BEAR:
16421 case FORM_DIREBEAR:
16423 if(getPowerType()!=POWER_RAGE)
16424 setPowerType(POWER_RAGE);
16425 break;
16427 default: // 0, for example
16429 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16430 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16431 setPowerType(Powers(cEntry->powerType));
16432 break;
16436 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16437 if (!reapplyMods)
16438 UpdateEquipSpellsAtFormChange();
16440 UpdateAttackPowerAndDamage();
16441 UpdateAttackPowerAndDamage(true);
16444 // Return true is the bought item has a max count to force refresh of window by caller
16445 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16447 // cheating attempt
16448 if(count < 1) count = 1;
16450 if(!isAlive())
16451 return false;
16453 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16454 if( !pProto )
16456 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16457 return false;
16460 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16461 if (!pCreature)
16463 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16464 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16465 return false;
16468 VendorItemData const* vItems = pCreature->GetVendorItems();
16469 if(!vItems || vItems->Empty())
16471 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16472 return false;
16475 size_t vendor_slot = vItems->FindItemSlot(item);
16476 if(vendor_slot >= vItems->GetItemCount())
16478 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16479 return false;
16482 VendorItem const* crItem = vItems->m_items[vendor_slot];
16484 // check current item amount if it limited
16485 if( crItem->maxcount != 0 )
16487 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16489 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16490 return false;
16494 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16496 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16497 return false;
16500 if(crItem->ExtendedCost)
16502 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16503 if(!iece)
16505 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16506 return false;
16509 // honor points price
16510 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16512 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16513 return false;
16516 // arena points price
16517 if(GetArenaPoints() < (iece->reqarenapoints * count))
16519 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16520 return false;
16523 // item base price
16524 for (uint8 i = 0; i < 5; ++i)
16526 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16528 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16529 return false;
16533 // check for personal arena rating requirement
16534 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16536 // probably not the proper equip err
16537 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16538 return false;
16542 uint32 price = pProto->BuyPrice * count;
16544 // reputation discount
16545 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16547 if( GetMoney() < price )
16549 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16550 return false;
16553 uint8 bag = 0; // init for case invalid bagGUID
16555 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16557 Bag *pBag;
16558 if( bagguid == GetGUID() )
16560 bag = INVENTORY_SLOT_BAG_0;
16562 else
16564 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16566 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16567 if( pBag )
16569 if( bagguid == pBag->GetGUID() )
16571 bag = i;
16572 break;
16579 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16581 ItemPosCountVec dest;
16582 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16583 if( msg != EQUIP_ERR_OK )
16585 SendEquipError( msg, NULL, NULL );
16586 return false;
16589 ModifyMoney( -(int32)price );
16590 if(crItem->ExtendedCost) // case for new honor system
16592 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16593 if(iece->reqhonorpoints)
16594 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16595 if(iece->reqarenapoints)
16596 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16597 for (uint8 i = 0; i < 5; ++i)
16599 if(iece->reqitem[i])
16600 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16604 if(Item *it = StoreNewItem( dest, item, true ))
16606 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16608 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16609 data << pCreature->GetGUID();
16610 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16611 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16612 data << (uint32)count;
16613 GetSession()->SendPacket(&data);
16615 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16618 else if( IsEquipmentPos( bag, slot ) )
16620 uint16 dest;
16621 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16622 if( msg != EQUIP_ERR_OK )
16624 SendEquipError( msg, NULL, NULL );
16625 return false;
16628 ModifyMoney( -(int32)price );
16629 if(crItem->ExtendedCost) // case for new honor system
16631 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16632 if(iece->reqhonorpoints)
16633 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16634 if(iece->reqarenapoints)
16635 ModifyArenaPoints( - int32(iece->reqarenapoints));
16636 for (uint8 i = 0; i < 5; ++i)
16638 if(iece->reqitem[i])
16639 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16643 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16645 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16647 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16648 data << pCreature->GetGUID();
16649 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16650 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16651 data << (uint32)count;
16652 GetSession()->SendPacket(&data);
16654 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16656 AutoUnequipOffhandIfNeed();
16659 else
16661 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16662 return false;
16665 return crItem->maxcount!=0;
16668 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16670 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16671 // the personal rating of the arena team must match the required limit as well
16672 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16673 uint32 max_personal_rating = 0;
16674 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16676 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16678 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16679 uint32 t_rating = at->GetRating();
16680 p_rating = p_rating<t_rating? p_rating : t_rating;
16681 if(max_personal_rating < p_rating)
16682 max_personal_rating = p_rating;
16685 return max_personal_rating;
16688 void Player::UpdateHomebindTime(uint32 time)
16690 // GMs never get homebind timer online
16691 if (m_InstanceValid || isGameMaster())
16693 if(m_HomebindTimer) // instance valid, but timer not reset
16695 // hide reminder
16696 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16697 data << uint32(0);
16698 data << uint32(0);
16699 GetSession()->SendPacket(&data);
16701 // instance is valid, reset homebind timer
16702 m_HomebindTimer = 0;
16704 else if (m_HomebindTimer > 0)
16706 if (time >= m_HomebindTimer)
16708 // teleport to homebind location
16709 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16711 else
16712 m_HomebindTimer -= time;
16714 else
16716 // instance is invalid, start homebind timer
16717 m_HomebindTimer = 60000;
16718 // send message to player
16719 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16720 data << m_HomebindTimer;
16721 data << uint32(1);
16722 GetSession()->SendPacket(&data);
16723 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16727 void Player::UpdatePvP(bool state, bool ovrride)
16729 if(!state || ovrride)
16731 SetPvP(state);
16732 if(Pet* pet = GetPet())
16733 pet->SetPvP(state);
16734 if(Unit* charmed = GetCharm())
16735 charmed->SetPvP(state);
16737 pvpInfo.endTimer = 0;
16739 else
16741 if(pvpInfo.endTimer != 0)
16742 pvpInfo.endTimer = time(NULL);
16743 else
16745 SetPvP(state);
16747 if(Pet* pet = GetPet())
16748 pet->SetPvP(state);
16749 if(Unit* charmed = GetCharm())
16750 charmed->SetPvP(state);
16755 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16757 SpellCooldown sc;
16758 sc.end = end_time;
16759 sc.itemid = itemid;
16760 m_spellCooldowns[spellid] = sc;
16763 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16765 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16766 return;
16768 // Get spell cooldown
16769 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16770 // Apply spellmods
16771 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16772 if (cooldown < 0)
16773 cooldown = 0;
16774 // Add cooldown
16775 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16776 // Send activate
16777 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16778 data << spellInfo->Id;
16779 data << GetGUID();
16780 SendDirectMessage(&data);
16782 //slot to be excluded while counting
16783 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16785 if(!enchantmentcondition)
16786 return true;
16788 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16790 if(!Condition)
16791 return true;
16793 uint8 curcount[4] = {0, 0, 0, 0};
16795 //counting current equipped gem colors
16796 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
16798 if(i == slot)
16799 continue;
16800 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
16801 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
16803 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16805 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16806 if(!enchant_id)
16807 continue;
16809 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16810 if(!enchantEntry)
16811 continue;
16813 uint32 gemid = enchantEntry->GemID;
16814 if(!gemid)
16815 continue;
16817 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
16818 if(!gemProto)
16819 continue;
16821 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
16822 if(!gemProperty)
16823 continue;
16825 uint8 GemColor = gemProperty->color;
16827 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
16829 if(tmpcolormask & GemColor)
16830 ++curcount[b];
16836 bool activate = true;
16838 for(int i = 0; i < 5; i++)
16840 if(!Condition->Color[i])
16841 continue;
16843 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
16845 // if have <CompareColor> use them as count, else use <value> from Condition
16846 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
16848 switch(Condition->Comparator[i])
16850 case 2: // requires less <color> than (<value> || <comparecolor>) gems
16851 activate &= (_cur_gem < _cmp_gem) ? true : false;
16852 break;
16853 case 3: // requires more <color> than (<value> || <comparecolor>) gems
16854 activate &= (_cur_gem > _cmp_gem) ? true : false;
16855 break;
16856 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
16857 activate &= (_cur_gem >= _cmp_gem) ? true : false;
16858 break;
16862 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");
16864 return activate;
16867 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
16869 //cycle all equipped items
16870 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16872 //enchants for the slot being socketed are handled by Player::ApplyItemMods
16873 if(slot == exceptslot)
16874 continue;
16876 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16878 if(!pItem || !pItem->GetProto()->Socket[0].Color)
16879 continue;
16881 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16883 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16884 if(!enchant_id)
16885 continue;
16887 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16888 if(!enchantEntry)
16889 continue;
16891 uint32 condition = enchantEntry->EnchantmentCondition;
16892 if(condition)
16894 //was enchant active with/without item?
16895 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
16896 //should it now be?
16897 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
16899 // ignore item gem conditions
16900 //if state changed, (dis)apply enchant
16901 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
16908 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
16909 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
16911 //cycle all equipped items
16912 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16914 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
16915 if(slot == exceptslot)
16916 continue;
16918 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16920 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
16921 continue;
16923 //cycle all (gem)enchants
16924 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16926 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16927 if(!enchant_id) //if no enchant go to next enchant(slot)
16928 continue;
16930 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16931 if(!enchantEntry)
16932 continue;
16934 //only metagems to be (de)activated, so only enchants with condition
16935 uint32 condition = enchantEntry->EnchantmentCondition;
16936 if(condition)
16937 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
16942 void Player::LeaveBattleground(bool teleportToEntryPoint)
16944 if(BattleGround *bg = GetBattleGround())
16946 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
16948 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
16950 // call after remove to be sure that player resurrected for correct cast
16951 if(need_debuf)
16952 CastSpell(this, 26013, true); // Deserter
16956 bool Player::CanJoinToBattleground() const
16958 // check Deserter debuff
16959 if(GetDummyAura(26013))
16960 return false;
16962 return true;
16965 bool Player::CanReportAfkDueToLimit()
16967 // a player can complain about 15 people per 5 minutes
16968 if(m_bgAfkReportedCount >= 15)
16969 return false;
16970 ++m_bgAfkReportedCount;
16971 return true;
16974 ///This player has been blamed to be inactive in a battleground
16975 void Player::ReportedAfkBy(Player* reporter)
16977 BattleGround *bg = GetBattleGround();
16978 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
16979 return;
16981 // check if player has 'Idle' or 'Inactive' debuff
16982 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
16984 m_bgAfkReporter.insert(reporter->GetGUIDLow());
16985 // 3 players have to complain to apply debuff
16986 if(m_bgAfkReporter.size() >= 3)
16988 // cast 'Idle' spell
16989 CastSpell(this, 43680, true);
16990 m_bgAfkReporter.clear();
16995 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
16997 // gamemaster in GM mode see all, including ghosts
16998 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
16999 return true;
17001 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17002 if (InBattleGround())
17004 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17005 return false;
17006 return true;
17009 // Live player see live player or dead player with not realized corpse
17010 if(pl->isAlive() || pl->m_deathTimer > 0)
17012 return isAlive() || m_deathTimer > 0;
17015 // Ghost see other friendly ghosts, that's for sure
17016 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17017 return true;
17019 // Dead player see live players near own corpse
17020 if(isAlive())
17022 Corpse *corpse = pl->GetCorpse();
17023 if(corpse)
17025 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17026 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17027 return true;
17031 // and not see any other
17032 return false;
17035 bool Player::IsVisibleGloballyFor( Player* u ) const
17037 if(!u)
17038 return false;
17040 // Always can see self
17041 if (u==this)
17042 return true;
17044 // Visible units, always are visible for all players
17045 if (GetVisibility() == VISIBILITY_ON)
17046 return true;
17048 // GMs are visible for higher gms (or players are visible for gms)
17049 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17050 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17052 // non faction visibility non-breakable for non-GMs
17053 if (GetVisibility() == VISIBILITY_OFF)
17054 return false;
17056 // non-gm stealth/invisibility not hide from global player lists
17057 return true;
17060 void Player::UpdateVisibilityOf(WorldObject* target)
17062 if(HaveAtClient(target))
17064 if(!target->isVisibleForInState(this,true))
17066 target->DestroyForPlayer(this);
17067 m_clientGUIDs.erase(target->GetGUID());
17069 #ifdef MANGOS_DEBUG
17070 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17071 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17072 #endif
17075 else
17077 if(target->isVisibleForInState(this,false))
17079 target->SendUpdateToPlayer(this);
17080 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17081 m_clientGUIDs.insert(target->GetGUID());
17083 #ifdef MANGOS_DEBUG
17084 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17085 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17086 #endif
17088 // target aura duration for caster show only if target exist at caster client
17089 // send data at target visibility change (adding to client)
17090 if(target!=this && target->isType(TYPEMASK_UNIT))
17091 SendAuraDurationsForTarget((Unit*)target);
17093 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17094 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17099 template<class T>
17100 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17102 s64.insert(target->GetGUID());
17105 template<>
17106 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17108 if(!target->IsTransport())
17109 s64.insert(target->GetGUID());
17112 template<class T>
17113 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17115 if(HaveAtClient(target))
17117 if(!target->isVisibleForInState(this,true))
17119 target->BuildOutOfRangeUpdateBlock(&data);
17120 m_clientGUIDs.erase(target->GetGUID());
17122 #ifdef MANGOS_DEBUG
17123 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17124 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));
17125 #endif
17128 else
17130 if(target->isVisibleForInState(this,false))
17132 visibleNow.insert(target);
17133 target->BuildUpdate(data_updates);
17134 target->BuildCreateUpdateBlockForPlayer(&data, this);
17135 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17137 #ifdef MANGOS_DEBUG
17138 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17139 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));
17140 #endif
17145 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17146 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17147 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17148 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17149 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17151 void Player::InitPrimaryProffesions()
17153 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17156 void Player::SendComboPoints()
17158 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17159 if (combotarget)
17161 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17162 data.append(combotarget->GetPackGUID());
17163 data << uint8(m_comboPoints);
17164 GetSession()->SendPacket(&data);
17168 void Player::AddComboPoints(Unit* target, int8 count)
17170 if(!count)
17171 return;
17173 // without combo points lost (duration checked in aura)
17174 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17176 if(target->GetGUID() == m_comboTarget)
17178 m_comboPoints += count;
17180 else
17182 if(m_comboTarget)
17183 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17184 target->RemoveComboPointHolder(GetGUIDLow());
17186 m_comboTarget = target->GetGUID();
17187 m_comboPoints = count;
17189 target->AddComboPointHolder(GetGUIDLow());
17192 if (m_comboPoints > 5) m_comboPoints = 5;
17193 if (m_comboPoints < 0) m_comboPoints = 0;
17195 SendComboPoints();
17198 void Player::ClearComboPoints()
17200 if(!m_comboTarget)
17201 return;
17203 // without combopoints lost (duration checked in aura)
17204 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17206 m_comboPoints = 0;
17208 SendComboPoints();
17210 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17211 target->RemoveComboPointHolder(GetGUIDLow());
17213 m_comboTarget = 0;
17216 void Player::SetGroup(Group *group, int8 subgroup)
17218 if(group == NULL) m_group.unlink();
17219 else
17221 // never use SetGroup without a subgroup unless you specify NULL for group
17222 assert(subgroup >= 0);
17223 m_group.link(group, this);
17224 m_group.setSubGroup((uint8)subgroup);
17228 void Player::SendInitialPacketsBeforeAddToMap()
17230 WorldPacket data(SMSG_SET_REST_START, 4);
17231 data << uint32(0); // unknown, may be rest state time or experience
17232 GetSession()->SendPacket(&data);
17234 // Homebind
17235 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17236 data << m_homebindX << m_homebindY << m_homebindZ;
17237 data << (uint32) m_homebindMapId;
17238 data << (uint32) m_homebindZoneId;
17239 GetSession()->SendPacket(&data);
17241 // SMSG_SET_PROFICIENCY
17242 // SMSG_UPDATE_AURA_DURATION
17244 // tutorial stuff
17245 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17246 for (int i = 0; i < 8; ++i)
17247 data << uint32( GetTutorialInt(i) );
17248 GetSession()->SendPacket(&data);
17250 SendInitialSpells();
17252 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17253 data << uint32(0); // count, for(count) uint32;
17254 GetSession()->SendPacket(&data);
17256 SendInitialActionButtons();
17257 SendInitialReputations();
17258 UpdateZone(GetZoneId());
17259 SendInitWorldStates();
17261 // SMSG_SET_AURA_SINGLE
17263 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17264 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17265 data << (float)0.01666667f; // game speed
17266 GetSession()->SendPacket( &data );
17268 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17269 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17270 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17273 void Player::SendInitialPacketsAfterAddToMap()
17275 CastSpell(this, 836, true); // LOGINEFFECT
17277 // set some aura effects that send packet to player client after add player to map
17278 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17279 // same auras state lost at far teleport, send it one more time in this case also
17280 static const AuraType auratypes[] =
17282 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17283 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17284 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17286 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17288 Unit::AuraList const& auraList = GetAurasByType(*itr);
17289 if(!auraList.empty())
17290 auraList.front()->ApplyModifier(true,true);
17293 if(HasAuraType(SPELL_AURA_MOD_STUN))
17294 SetMovement(MOVE_ROOT);
17296 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17297 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17299 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17300 data.append(GetPackGUID());
17301 data << (uint32)2;
17302 SendMessageToSet(&data,true);
17305 SendEnchantmentDurations(); // must be after add to map
17306 SendItemDurations(); // must be after add to map
17309 void Player::SendUpdateToOutOfRangeGroupMembers()
17311 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17312 return;
17313 if(Group* group = GetGroup())
17314 group->UpdatePlayerOutOfRange(this);
17316 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17317 m_auraUpdateMask = 0;
17318 if(Pet *pet = GetPet())
17319 pet->ResetAuraUpdateMask();
17322 void Player::SendTransferAborted(uint32 mapid, uint16 reason)
17324 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17325 data << uint32(mapid);
17326 data << uint16(reason); // transfer abort reason
17327 GetSession()->SendPacket(&data);
17330 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17332 // type of warning, based on the time remaining until reset
17333 uint32 type;
17334 if(time > 3600)
17335 type = RAID_INSTANCE_WELCOME;
17336 else if(time > 900 && time <= 3600)
17337 type = RAID_INSTANCE_WARNING_HOURS;
17338 else if(time > 300 && time <= 900)
17339 type = RAID_INSTANCE_WARNING_MIN;
17340 else
17341 type = RAID_INSTANCE_WARNING_MIN_SOON;
17342 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17343 data << uint32(type);
17344 data << uint32(mapid);
17345 data << uint32(time);
17346 GetSession()->SendPacket(&data);
17349 void Player::ApplyEquipCooldown( Item * pItem )
17351 for(int i = 0; i <5; ++i)
17353 _Spell const& spellData = pItem->GetProto()->Spells[i];
17355 // no spell
17356 if( !spellData.SpellId )
17357 continue;
17359 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17360 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17361 continue;
17363 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17365 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17366 data << pItem->GetGUID();
17367 data << uint32(spellData.SpellId);
17368 GetSession()->SendPacket(&data);
17372 void Player::resetSpells()
17374 // not need after this call
17375 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17377 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17378 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17381 // make full copy of map (spells removed and marked as deleted at another spell remove
17382 // and we can't use original map for safe iterative with visit each spell at loop end
17383 PlayerSpellMap smap = GetSpellMap();
17385 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17386 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17388 learnDefaultSpells();
17389 learnQuestRewardedSpells();
17392 void Player::learnDefaultSpells(bool loading)
17394 // learn default race/class spells
17395 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17396 std::list<CreateSpellPair>::const_iterator spell_itr;
17397 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17399 uint16 tspell = spell_itr->first;
17400 if (tspell)
17402 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17403 if(loading || !spell_itr->second) // not care about passive spells or loading case
17404 addSpell(tspell,spell_itr->second);
17405 else // but send in normal spell in game learn case
17406 learnSpell(tspell);
17411 void Player::learnQuestRewardedSpells(Quest const* quest)
17413 uint32 spell_id = quest->GetRewSpellCast();
17415 // skip quests without rewarded spell
17416 if( !spell_id )
17417 return;
17419 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17420 if(!spellInfo)
17421 return;
17423 // check learned spells state
17424 bool found = false;
17425 for(int i=0; i < 3; ++i)
17427 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17429 found = true;
17430 break;
17434 // skip quests with not teaching spell or already known spell
17435 if(!found)
17436 return;
17438 // prevent learn non first rank unknown profession and second specialization for same profession)
17439 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17440 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17442 // not have first rank learned (unlearned prof?)
17443 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17444 if( !HasSpell(first_spell) )
17445 return;
17447 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17448 if(!learnedInfo)
17449 return;
17451 // specialization
17452 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17454 // search other specialization for same prof
17455 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17457 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17458 continue;
17460 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17461 if(!itrInfo)
17462 return;
17464 // compare only specializations
17465 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17466 continue;
17468 // compare same chain spells
17469 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17470 continue;
17472 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17473 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17474 return;
17479 CastSpell( this, spell_id, true);
17482 void Player::learnQuestRewardedSpells()
17484 // learn spells received from quest completing
17485 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17487 // skip no rewarded quests
17488 if(!itr->second.m_rewarded)
17489 continue;
17491 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17492 if( !quest )
17493 continue;
17495 learnQuestRewardedSpells(quest);
17499 void Player::learnSkillRewardedSpells(uint32 skill_id )
17501 uint32 raceMask = getRaceMask();
17502 uint32 classMask = getClassMask();
17503 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17505 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17506 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17507 continue;
17508 // Check race if set
17509 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17510 continue;
17511 // Check class if set
17512 if (pAbility->classmask && !(pAbility->classmask & classMask))
17513 continue;
17515 if (sSpellStore.LookupEntry(pAbility->spellId))
17517 // Ok need learn spell
17518 learnSpell(pAbility->spellId);
17523 void Player::learnSkillRewardedSpells()
17525 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17527 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17528 continue;
17530 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17532 learnSkillRewardedSpells(pskill);
17536 void Player::SendAuraDurationsForTarget(Unit* target)
17538 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17540 Aura* aura = itr->second;
17541 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17542 continue;
17544 aura->SendAuraDurationForCaster(this);
17548 void Player::SetDailyQuestStatus( uint32 quest_id )
17550 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17552 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17554 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17555 m_lastDailyQuestTime = time(NULL); // last daily quest time
17556 m_DailyQuestChanged = true;
17557 break;
17562 void Player::ResetDailyQuestStatus()
17564 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17565 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17567 // DB data deleted in caller
17568 m_DailyQuestChanged = false;
17569 m_lastDailyQuestTime = 0;
17572 BattleGround* Player::GetBattleGround() const
17574 if(GetBattleGroundId()==0)
17575 return NULL;
17577 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17580 bool Player::InArena() const
17582 BattleGround *bg = GetBattleGround();
17583 if(!bg || !bg->isArena())
17584 return false;
17586 return true;
17589 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17591 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17592 if(!bg)
17593 return false;
17595 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17596 return false;
17598 return true;
17601 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17603 if(queue_id < 1)
17604 return 0;
17606 if(queue_id >=6)
17607 queue_id = 6;
17609 return 10*(queue_id+1);
17612 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17614 if(queue_id >=6)
17615 return 255; // hardcoded max level
17617 return 10*(queue_id+2)-1;
17620 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17622 uint32 level = getLevel();
17623 if(level <= 19)
17624 return 0;
17625 else if (level > 69)
17626 return 6;
17627 else
17628 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17631 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17633 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17634 if(!vendor_faction)
17635 return 1.0f;
17637 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17638 if(rank <= REP_NEUTRAL)
17639 return 1.0f;
17641 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17644 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17646 uint32 racemask = getRaceMask();
17647 uint32 classmask = getClassMask();
17649 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17650 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17652 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17654 // skip wrong race skills
17655 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17656 return false;
17658 // skip wrong class skills
17659 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17660 return false;
17662 return true;
17665 bool Player::HasQuestForGO(int32 GOId)
17667 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17669 QuestStatusData qs=i->second;
17670 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17672 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17673 if(!qinfo)
17674 continue;
17676 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17677 continue;
17679 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17681 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17682 continue;
17684 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17685 return true;
17689 return false;
17692 void Player::UpdateForQuestsGO()
17694 if(m_clientGUIDs.empty())
17695 return;
17697 UpdateData udata;
17698 WorldPacket packet;
17699 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17701 if(IS_GAMEOBJECT_GUID(*itr))
17703 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17704 if(obj)
17705 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17708 udata.BuildPacket(&packet);
17709 GetSession()->SendPacket(&packet);
17712 void Player::SummonIfPossible(bool agree)
17714 if(!agree)
17716 m_summon_expire = 0;
17717 return;
17720 // expire and auto declined
17721 if(m_summon_expire < time(NULL))
17722 return;
17724 // stop taxi flight at summon
17725 if(isInFlight())
17727 GetMotionMaster()->MovementExpired();
17728 m_taxi.ClearTaxiDestinations();
17731 // drop flag at summon
17732 if(BattleGround *bg = GetBattleGround())
17733 bg->EventPlayerDroppedFlag(this);
17735 m_summon_expire = 0;
17737 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17740 void Player::RemoveItemDurations( Item *item )
17742 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17744 if(*itr==item)
17746 m_itemDuration.erase(itr);
17747 break;
17752 void Player::AddItemDurations( Item *item )
17754 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17756 m_itemDuration.push_back(item);
17757 item->SendTimeUpdate(this);
17761 void Player::AutoUnequipOffhandIfNeed()
17763 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
17764 if(!offItem)
17765 return;
17767 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
17769 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
17770 return;
17772 ItemPosCountVec off_dest;
17773 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
17774 if( off_msg == EQUIP_ERR_OK )
17776 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
17777 StoreItem( off_dest, offItem, true );
17779 else
17781 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
17785 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
17787 if(spellInfo->EquippedItemClass < 0)
17788 return true;
17790 // scan other equipped items for same requirements (mostly 2 daggers/etc)
17791 // for optimize check 2 used cases only
17792 switch(spellInfo->EquippedItemClass)
17794 case ITEM_CLASS_WEAPON:
17796 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
17797 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17798 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17799 return true;
17800 break;
17802 case ITEM_CLASS_ARMOR:
17804 // tabard not have dependent spells
17805 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
17806 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17807 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17808 return true;
17810 // shields can be equipped to offhand slot
17811 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
17812 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17813 return true;
17815 // ranged slot can have some armor subclasses
17816 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
17817 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17818 return true;
17820 break;
17822 default:
17823 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
17824 break;
17827 return false;
17830 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
17832 AuraMap& auras = GetAuras();
17833 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
17835 Aura* aura = itr->second;
17837 // skip passive (passive item dependent spells work in another way) and not self applied auras
17838 SpellEntry const* spellInfo = aura->GetSpellProto();
17839 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17841 ++itr;
17842 continue;
17845 // skip if not item dependent or have alternative item
17846 if(HasItemFitToSpellReqirements(spellInfo,pItem))
17848 ++itr;
17849 continue;
17852 // no alt item, remove aura, restart check
17853 RemoveAurasDueToSpell(aura->GetId());
17854 itr = auras.begin();
17857 // currently casted spells can be dependent from item
17858 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
17860 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
17861 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
17862 InterruptSpell(i);
17866 uint32 Player::GetResurrectionSpellId()
17868 // search priceless resurrection possibilities
17869 uint32 prio = 0;
17870 uint32 spell_id = 0;
17871 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
17872 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
17874 // Soulstone Resurrection // prio: 3 (max, non death persistent)
17875 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
17877 switch((*itr)->GetId())
17879 case 20707: spell_id = 3026; break; // rank 1
17880 case 20762: spell_id = 20758; break; // rank 2
17881 case 20763: spell_id = 20759; break; // rank 3
17882 case 20764: spell_id = 20760; break; // rank 4
17883 case 20765: spell_id = 20761; break; // rank 5
17884 case 27239: spell_id = 27240; break; // rank 6
17885 default:
17886 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
17887 continue;
17890 prio = 3;
17892 // Twisting Nether // prio: 2 (max)
17893 else if((*itr)->GetId()==23701 && roll_chance_i(10))
17895 prio = 2;
17896 spell_id = 23700;
17900 // Reincarnation (passive spell) // prio: 1
17901 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
17902 spell_id = 21169;
17904 return spell_id;
17907 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
17909 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
17911 // prepare data for near group iteration (PvP and !PvP cases)
17912 uint32 xp = 0;
17913 bool honored_kill = false;
17915 if(Group *pGroup = GetGroup())
17917 uint32 count = 0;
17918 uint32 sum_level = 0;
17919 Player* member_with_max_level = NULL;
17920 Player* not_gray_member_with_max_level = NULL;
17922 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
17924 if(member_with_max_level)
17926 /// not get Xp in PvP or no not gray players in group
17927 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
17929 /// skip in check PvP case (for speed, not used)
17930 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
17931 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
17932 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
17934 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
17936 Player* pGroupGuy = itr->getSource();
17937 if(!pGroupGuy)
17938 continue;
17940 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
17941 continue; // member (alive or dead) or his corpse at req. distance
17943 // honor can be in PvP and !PvP (racial leader) cases (for alive)
17944 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
17945 honored_kill = true;
17947 // xp and reputation only in !PvP case
17948 if(!PvP)
17950 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
17952 // if is in dungeon then all receive full reputation at kill
17953 // rewarded any alive/dead/near_corpse group member
17954 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
17956 // XP updated only for alive group member
17957 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
17958 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
17960 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
17962 pGroupGuy->GiveXP(itr_xp, pVictim);
17963 if(Pet* pet = pGroupGuy->GetPet())
17964 pet->GivePetXP(itr_xp/2);
17967 // quest objectives updated only for alive group member or dead but with not released body
17968 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
17970 // normal creature (not pet/etc) can be only in !PvP case
17971 if(pVictim->GetTypeId()==TYPEID_UNIT)
17972 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
17978 else // if (!pGroup)
17980 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
17982 // honor can be in PvP and !PvP (racial leader) cases
17983 if(RewardHonor(pVictim,1))
17984 honored_kill = true;
17986 // xp and reputation only in !PvP case
17987 if(!PvP)
17989 RewardReputation(pVictim,1);
17990 GiveXP(xp, pVictim);
17992 if(Pet* pet = GetPet())
17993 pet->GivePetXP(xp);
17995 // normal creature (not pet/etc) can be only in !PvP case
17996 if(pVictim->GetTypeId()==TYPEID_UNIT)
17997 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18000 return xp || honored_kill;
18003 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18005 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18006 return true;
18008 if(isAlive())
18009 return false;
18011 Corpse* corpse = GetCorpse();
18012 if(!corpse)
18013 return false;
18015 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18018 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18020 Item* item = GetWeaponForAttack(attType,true);
18022 // unarmed only with base attack
18023 if(attType != BASE_ATTACK && !item)
18024 return 0;
18026 // weapon skill or (unarmed for base attack)
18027 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18028 return GetBaseSkillValue(skill);
18031 void Player::ResurectUsingRequestData()
18033 ResurrectPlayer(0.0f,false);
18035 if(GetMaxHealth() > m_resurrectHealth)
18036 SetHealth( m_resurrectHealth );
18037 else
18038 SetHealth( GetMaxHealth() );
18040 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18041 SetPower(POWER_MANA, m_resurrectMana );
18042 else
18043 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18045 SetPower(POWER_RAGE, 0 );
18047 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18049 SpawnCorpseBones();
18051 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18054 void Player::SetClientControl(Unit* target, uint8 allowMove)
18056 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18057 data.append(target->GetPackGUID());
18058 data << uint8(allowMove);
18059 GetSession()->SendPacket(&data);
18062 void Player::UpdateZoneDependentAuras( uint32 newZone )
18064 // remove new continent flight forms
18065 if( !isGameMaster() &&
18066 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
18068 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18069 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18072 // Some spells applied at enter into zone (with subzones)
18073 // Human Illusion
18074 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18075 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18077 uint32 spellid = 0;
18078 // all horde races
18079 if( GetTeam() == HORDE )
18080 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18081 // and some alliance races
18082 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18083 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18085 if(spellid && !HasAura(spellid,0) )
18086 CastSpell(this,spellid,true);
18090 void Player::UpdateAreaDependentAuras( uint32 newArea )
18092 // remove auras from spells with area limitations
18093 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18095 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18096 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
18097 RemoveAura(iter);
18098 else
18099 ++iter;
18102 // unmount if enter in this subzone
18103 if( newArea == 35)
18104 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18105 // Dragonmaw Illusion
18106 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18108 if( GetDummyAura(40214) )
18110 if( !HasAura(40216,0) )
18111 CastSpell(this,40216,true);
18112 if( !HasAura(42016,0) )
18113 CastSpell(this,42016,true);
18118 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18120 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18121 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18123 return copseReclaimDelay[0];
18126 time_t now = time(NULL);
18127 // 0..2 full period
18128 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18129 return copseReclaimDelay[count];
18132 void Player::UpdateCorpseReclaimDelay()
18134 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18136 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18137 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18138 return;
18140 time_t now = time(NULL);
18141 if(now < m_deathExpireTime)
18143 // full and partly periods 1..3
18144 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18145 if(count < MAX_DEATH_COUNT)
18146 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18147 else
18148 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18150 else
18151 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18154 void Player::SendCorpseReclaimDelay(bool load)
18156 Corpse* corpse = GetCorpse();
18157 if(!corpse)
18158 return;
18160 uint32 delay;
18161 if(load)
18163 if(corpse->GetGhostTime() > m_deathExpireTime)
18164 return;
18166 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18168 uint32 count;
18169 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18170 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18172 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18173 if(count>=MAX_DEATH_COUNT)
18174 count = MAX_DEATH_COUNT-1;
18176 else
18177 count=0;
18179 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18181 time_t now = time(NULL);
18182 if(now >= expected_time)
18183 return;
18185 delay = expected_time-now;
18187 else
18188 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18190 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18191 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18192 data << uint32(delay*1000);
18193 GetSession()->SendPacket( &data );
18196 Player* Player::GetNextRandomRaidMember(float radius)
18198 Group *pGroup = GetGroup();
18199 if(!pGroup)
18200 return NULL;
18202 std::vector<Player*> nearMembers;
18203 nearMembers.reserve(pGroup->GetMembersCount());
18205 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18207 Player* Target = itr->getSource();
18209 // IsHostileTo check duel and controlled by enemy
18210 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18211 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18212 nearMembers.push_back(Target);
18215 if (nearMembers.empty())
18216 return NULL;
18218 uint32 randTarget = urand(0,nearMembers.size()-1);
18219 return nearMembers[randTarget];
18222 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18224 float water_z = m->GetWaterLevel(x,y);
18225 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18226 uint8 flag1 = m->GetTerrainType(x,y);
18228 //!Underwater check, not in water if underground or above water level
18229 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18230 m_isunderwater &= 0x7A;
18231 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18232 m_isunderwater |= 0x01;
18234 //!in lava check, anywhere under lava level
18235 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18236 m_isunderwater |= 0x80;
18239 void Player::SetCanParry( bool value )
18241 if(m_canParry==value)
18242 return;
18244 m_canParry = value;
18245 UpdateParryPercentage();
18248 void Player::SetCanBlock( bool value )
18250 if(m_canBlock==value)
18251 return;
18253 m_canBlock = value;
18254 UpdateBlockPercentage();
18257 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18259 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18260 if(itr->pos == pos)
18261 return true;
18263 return false;
18266 bool Player::isAllowUseBattleGroundObject()
18268 return ( //InBattleGround() && // in battleground - not need, check in other cases
18269 !IsMounted() && // not mounted
18270 !HasStealthAura() && // not stealthed
18271 !HasInvisibilityAura() && // not invisible
18272 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18273 isAlive() // live player