* [sql/updates/2008_10_22_01_mangos_quest_template.sql] Implemented honor rewards...
[auctionmangos.git] / src / game / Player.cpp
blob9b2fc9d09c9f8ee5b338b23b2a269db195b561ef
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 reagests 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 if(m_uint32Values) // only for fully created Object
431 sSocialMgr.RemovePlayerSocial(GetGUIDLow());
434 // Note: buy back item already deleted from DB when player was saved
435 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
437 if(m_items[i])
438 delete m_items[i];
440 CleanupChannels();
442 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
443 delete itr->second;
445 //all mailed items should be deleted, also all mail should be deallocated
446 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
447 delete *itr;
449 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
450 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
452 delete PlayerTalkClass;
454 if (m_transport)
456 m_transport->RemovePassenger(this);
459 for(size_t x = 0; x < ItemSetEff.size(); x++)
460 if(ItemSetEff[x])
461 delete ItemSetEff[x];
463 // clean up player-instance binds, may unload some instance saves
464 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
465 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
466 itr->second.save->RemovePlayer(this);
468 delete m_declinedname;
471 void Player::CleanupsBeforeDelete()
473 if(m_uint32Values) // only for fully created Object
475 TradeCancel(false);
476 DuelComplete(DUEL_INTERUPTED);
478 Unit::CleanupsBeforeDelete();
481 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 )
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 SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
557 SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
558 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_UNK5 );
559 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
560 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
562 //-1 is default value
563 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
565 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
566 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
567 SetByteValue(PLAYER_BYTES_3, 0, gender);
569 SetUInt32Value( PLAYER_GUILDID, 0 );
570 SetUInt32Value( PLAYER_GUILDRANK, 0 );
571 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
573 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
574 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
575 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
576 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
577 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
578 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
580 // set starting level
581 SetUInt32Value( UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) );
583 // Played time
584 m_Last_tick = time(NULL);
585 m_Played_time[0] = 0;
586 m_Played_time[1] = 0;
588 // base stats and related field values
589 InitStatsForLevel();
590 InitTaxiNodesForLevel();
591 InitTalentForLevel();
592 InitPrimaryProffesions(); // to max set before any spell added
594 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
595 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
596 SetHealth(GetMaxHealth());
597 if (getPowerType()==POWER_MANA)
599 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intelect)
600 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
603 learnDefaultSpells(true);
605 std::list<uint16>::const_iterator action_itr[4];
606 for(int i=0; i<4; i++)
607 action_itr[i] = info->action[i].begin();
609 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
611 uint16 taction[4];
612 for(int i=0; i<4 ;i++)
613 taction[i] = (*action_itr[i]);
615 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
617 for(int i=0; i<4 ;i++)
618 ++action_itr[i];
621 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
623 uint32 titem_id = item_id_itr->item_id;
624 uint32 titem_amount = item_id_itr->item_amount;
626 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
628 // attempt equip
629 uint16 eDest;
630 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
631 if( msg == EQUIP_ERR_OK )
633 EquipNewItem( eDest, titem_id, titem_amount, true);
634 AutoUnequipOffhandIfNeed();
635 continue; // equipped, to next
638 // attempt store
639 ItemPosCountVec sDest;
640 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
641 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
642 if( msg == EQUIP_ERR_OK )
644 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
645 continue; // stored, to next
648 // item can't be added
649 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,race,class_,msg);
652 // bags and main-hand weapon must equipped at this moment
653 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
654 // or ammo not equipped in special bag
655 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
657 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
659 uint16 eDest;
660 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
661 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
662 if( msg == EQUIP_ERR_OK )
664 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
665 EquipItem( eDest, pItem, true);
667 // move other items to more appropriate slots (ammo not equipped in special bag)
668 else
670 ItemPosCountVec sDest;
671 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
672 if( msg == EQUIP_ERR_OK )
674 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
675 pItem = StoreItem( sDest, pItem, true);
678 // if this is ammo then use it
679 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
680 if( msg == EQUIP_ERR_OK )
681 SetAmmo( pItem->GetProto()->ItemId );
685 // all item positions resolved
687 return true;
690 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
692 uint32 BreathRegen = (uint32)-1;
694 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
695 data << (uint32)Type;
696 data << MaxValue;
697 data << MaxValue;
698 data << BreathRegen;
699 data << (uint8)0;
700 data << (uint32)0; // spell id
701 GetSession()->SendPacket(&data);
704 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
706 if(Type==BREATH_TIMER)
707 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
709 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
710 data << (uint32)Type;
711 data << CurrentValue;
712 data << MaxValue;
713 data << Regen;
714 data << (uint8)0;
715 data << (uint32)0; // spell id
716 GetSession()->SendPacket( &data );
719 void Player::StopMirrorTimer(MirrorTimerType Type)
721 if(Type==BREATH_TIMER)
722 m_breathTimer = 0;
724 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
725 data << (uint32)Type;
726 GetSession()->SendPacket( &data );
729 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
731 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
732 data << (uint64)guid;
733 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
734 data << (uint32)damage;
735 data << (uint32)0;
736 data << (uint32)0;
737 //m_session->SendPacket(&data);
738 //Let other players see that you get damage
739 SendMessageToSet(&data, true);
740 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
742 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
744 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
745 DurabilityLossAll(0.10f,false);
746 // durability lost message
747 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
748 GetSession()->SendPacket(&data);
752 void Player::HandleDrowning()
754 if(!m_isunderwater)
755 return;
757 //if have water breath , then remove bar
758 if(waterbreath || isGameMaster() || !isAlive())
760 StopMirrorTimer(BREATH_TIMER);
761 m_isunderwater = 0;
762 return;
765 uint32 UnderWaterTime = 1*MINUTE*1000; // default leangthL 1 min
767 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
768 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
769 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
771 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
773 //single trigger timer
774 if (!(m_isunderwater & 0x02))
776 m_isunderwater|= 0x02;
777 m_breathTimer = UnderWaterTime + 1000;
779 //single trigger "Breathbar"
780 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
782 m_isunderwater|= 0x04;
783 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
785 //continius trigger drowning "Damage"
786 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
788 //TODO: Check this formula
789 uint64 guid = GetGUID();
790 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
792 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
793 m_breathTimer = 2000;
796 //single trigger retract bar
797 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
799 m_isunderwater = 0x08;
801 uint32 BreathRegen = 10;
802 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
803 m_isunderwater = 0x10;
805 //remove bar
806 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
808 StopMirrorTimer(BREATH_TIMER);
809 m_isunderwater = 0;
813 void Player::HandleLava()
815 bool ValidArea = false;
817 if ((m_isunderwater & 0x80) && isAlive())
819 //Single trigger Set BreathTimer
820 if (!(m_isunderwater & 0x80))
822 m_isunderwater|= 0x04;
823 m_breathTimer = 1000;
825 //Reset BreathTimer and still in the lava
826 if (!m_breathTimer)
828 uint64 guid = GetGUID();
829 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
830 uint32 dmgZone = GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
832 // Deal lava damage only in lava zones.
833 switch(dmgZone)
835 case 0x8D:
836 ValidArea = false;
837 break;
838 case 0x94:
839 ValidArea = false;
840 break;
841 case 0x2CE:
842 ValidArea = false;
843 break;
844 case 0x2CF:
845 ValidArea = false;
846 break;
847 default:
848 if (dmgZone / 5 & 0x408)
849 ValidArea = true;
852 // if is valid area and is not gamemaster then deal damage
853 if ( ValidArea && !isGameMaster() )
854 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
856 m_breathTimer = 1000;
860 //Death timer disabled and WaterFlags reset
861 else if (m_deathState == DEAD)
863 m_breathTimer = 0;
864 m_isunderwater = 0;
868 ///The player sobers by 256 every 10 seconds
869 void Player::HandleSobering()
871 m_drunkTimer = 0;
873 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
874 SetDrunkValue(drunk);
877 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
879 if(value >= 23000)
880 return DRUNKEN_SMASHED;
881 if(value >= 12800)
882 return DRUNKEN_DRUNK;
883 if(value & 0xFFFE)
884 return DRUNKEN_TIPSY;
885 return DRUNKEN_SOBER;
888 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
890 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
892 m_drunk = newDrunkenValue;
893 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
895 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
897 // special drunk invisibility detection
898 if(newDrunkenState >= DRUNKEN_DRUNK)
899 m_detectInvisibilityMask |= (1<<6);
900 else
901 m_detectInvisibilityMask &= ~(1<<6);
903 if(newDrunkenState == oldDrunkenState)
904 return;
906 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
907 data << GetGUID();
908 data << uint32(newDrunkenState);
909 data << uint32(itemId);
911 SendMessageToSet(&data, true);
914 void Player::Update( uint32 p_time )
916 if(!IsInWorld())
917 return;
919 // undelivered mail
920 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
922 SendNewMail();
923 ++unReadMails;
925 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
926 m_nextMailDelivereTime = 0;
929 Unit::Update( p_time );
931 // update player only attacks
932 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
934 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
937 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
939 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
942 time_t now = time (NULL);
944 UpdatePvPFlag(now);
946 UpdateContestedPvP(p_time);
948 UpdateDuelFlag(now);
950 CheckDuelDistance(now);
952 UpdateAfkReport(now);
954 CheckExploreSystem();
956 // Update items that have just a limited lifetime
957 if (now>m_Last_tick)
958 UpdateItemDuration(uint32(now- m_Last_tick));
960 if (!m_timedquests.empty())
962 std::set<uint32>::iterator iter = m_timedquests.begin();
963 while (iter != m_timedquests.end())
965 QuestStatusData& q_status = mQuestStatus[*iter];
966 if( q_status.m_timer <= p_time )
968 uint32 quest_id = *iter;
969 ++iter; // current iter will be removed in FailTimedQuest
970 FailTimedQuest( quest_id );
972 else
974 q_status.m_timer -= p_time;
975 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
976 ++iter;
981 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
983 Unit *pVictim = getVictim();
984 if( !IsNonMeleeSpellCasted(false) && pVictim)
986 // default combat reach 10
987 // TODO add weapon,skill check
989 float pldistance = ATTACK_DISTANCE;
991 if (isAttackReady(BASE_ATTACK))
993 if(!IsWithinDistInMap(pVictim, pldistance))
995 setAttackTimer(BASE_ATTACK,100);
996 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
998 SendAttackSwingNotInRange();
999 m_swingErrorMsg = 1;
1002 //120 degrees of radiant range
1003 else if( !HasInArc( 2*M_PI/3, pVictim ))
1005 setAttackTimer(BASE_ATTACK,100);
1006 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1008 SendAttackSwingBadFacingAttack();
1009 m_swingErrorMsg = 2;
1012 else
1014 m_swingErrorMsg = 0; // reset swing error state
1016 // prevent base and off attack in same time, delay attack at 0.2 sec
1017 if(haveOffhandWeapon())
1019 uint32 off_att = getAttackTimer(OFF_ATTACK);
1020 if(off_att < ATTACK_DISPLAY_DELAY)
1021 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1023 AttackerStateUpdate(pVictim, BASE_ATTACK);
1024 resetAttackTimer(BASE_ATTACK);
1028 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1030 if(!IsWithinDistInMap(pVictim, pldistance))
1032 setAttackTimer(OFF_ATTACK,100);
1034 else if( !HasInArc( 2*M_PI/3, pVictim ))
1036 setAttackTimer(OFF_ATTACK,100);
1038 else
1040 // prevent base and off attack in same time, delay attack at 0.2 sec
1041 uint32 base_att = getAttackTimer(BASE_ATTACK);
1042 if(base_att < ATTACK_DISPLAY_DELAY)
1043 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1044 // do attack
1045 AttackerStateUpdate(pVictim, OFF_ATTACK);
1046 resetAttackTimer(OFF_ATTACK);
1050 Unit *owner = pVictim->GetOwner();
1051 Unit *u = owner ? owner : pVictim;
1052 if(u->IsPvP() && (!duel || duel->opponent != u))
1054 UpdatePvP(true);
1055 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1060 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1062 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1064 int time_inn = time(NULL)-GetTimeInnEnter();
1065 if (time_inn >= 10) //freeze update
1067 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1068 //speed collect rest bonus (section/in hour)
1069 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1070 UpdateInnerTime(time(NULL));
1075 if(m_regenTimer > 0)
1077 if(p_time >= m_regenTimer)
1078 m_regenTimer = 0;
1079 else
1080 m_regenTimer -= p_time;
1083 if (m_weaponChangeTimer > 0)
1085 if(p_time >= m_weaponChangeTimer)
1086 m_weaponChangeTimer = 0;
1087 else
1088 m_weaponChangeTimer -= p_time;
1091 if (m_zoneUpdateTimer > 0)
1093 if(p_time >= m_zoneUpdateTimer)
1095 uint32 newzone = GetZoneId();
1096 if( m_zoneUpdateId != newzone )
1097 UpdateZone(newzone); // also update area
1098 else
1100 // use area updates as well
1101 // needed for free far all arenas for example
1102 uint32 newarea = GetAreaId();
1103 if( m_areaUpdateId != newarea )
1104 UpdateArea(newarea);
1106 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1109 else
1110 m_zoneUpdateTimer -= p_time;
1113 if (isAlive())
1115 RegenerateAll();
1118 if (m_deathState == JUST_DIED)
1120 KillPlayer();
1123 if(m_nextSave > 0)
1125 if(p_time >= m_nextSave)
1127 // m_nextSave reseted in SaveToDB call
1128 SaveToDB();
1129 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1131 else
1133 m_nextSave -= p_time;
1137 //Breathtimer
1138 if(m_breathTimer > 0)
1140 if(p_time >= m_breathTimer)
1141 m_breathTimer = 0;
1142 else
1143 m_breathTimer -= p_time;
1147 //Handle Water/drowning
1148 HandleDrowning();
1150 //Handle lava
1151 HandleLava();
1153 //Handle detect stealth players
1154 if (m_DetectInvTimer > 0)
1156 if (p_time >= m_DetectInvTimer)
1158 m_DetectInvTimer = 3000;
1159 HandleStealthedUnitsDetection();
1161 else
1162 m_DetectInvTimer -= p_time;
1165 // Played time
1166 if (now > m_Last_tick)
1168 uint32 elapsed = uint32(now - m_Last_tick);
1169 m_Played_time[0] += elapsed; // Total played time
1170 m_Played_time[1] += elapsed; // Level played time
1171 m_Last_tick = now;
1174 if (m_drunk)
1176 m_drunkTimer += p_time;
1178 if (m_drunkTimer > 10000)
1179 HandleSobering();
1182 // not auto-free ghost from body in instances
1183 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1185 if(p_time >= m_deathTimer)
1187 m_deathTimer = 0;
1188 BuildPlayerRepop();
1189 RepopAtGraveyard();
1191 else
1192 m_deathTimer -= p_time;
1195 UpdateEnchantTime(p_time);
1196 UpdateHomebindTime(p_time);
1198 // group update
1199 SendUpdateToOutOfRangeGroupMembers();
1201 Pet* pet = GetPet();
1202 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1204 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1205 return;
1209 void Player::setDeathState(DeathState s)
1211 uint32 ressSpellId = 0;
1213 bool cur = isAlive();
1215 if(s == JUST_DIED && cur)
1217 // drunken state is cleared on death
1218 SetDrunkValue(0);
1219 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1220 ClearComboPoints();
1222 clearResurrectRequestData();
1224 // remove form before other mods to prevent incorrect stats calculation
1225 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1227 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1228 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1230 // remove uncontrolled pets
1231 RemoveMiniPet();
1232 RemoveGuardians();
1234 // save value before aura remove in Unit::setDeathState
1235 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1237 // passive spell
1238 if(!ressSpellId)
1239 ressSpellId = GetResurrectionSpellId();
1241 Unit::setDeathState(s);
1243 // restore resurrection spell id for player after aura remove
1244 if(s == JUST_DIED && cur && ressSpellId)
1245 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1247 if(isAlive() && !cur)
1249 //clear aura case after resurrection by another way (spells will be applied before next death)
1250 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1252 // restore default warrior stance
1253 if(getClass()== CLASS_WARRIOR)
1254 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1258 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1260 *p_data << GetGUID();
1261 *p_data << m_name;
1263 *p_data << getRace();
1264 uint8 pClass = getClass();
1265 *p_data << pClass;
1266 *p_data << getGender();
1268 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1269 *p_data << uint8(bytes);
1270 *p_data << uint8(bytes >> 8);
1271 *p_data << uint8(bytes >> 16);
1272 *p_data << uint8(bytes >> 24);
1274 bytes = GetUInt32Value(PLAYER_BYTES_2);
1275 *p_data << uint8(bytes);
1277 *p_data << uint8(getLevel()); // player level
1278 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1279 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1281 *p_data << zoneId;
1282 *p_data << GetMapId();
1284 *p_data << GetPositionX();
1285 *p_data << GetPositionY();
1286 *p_data << GetPositionZ();
1288 *p_data << GetUInt32Value(PLAYER_GUILDID); // guild id
1290 uint32 char_flags = 0;
1291 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1292 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1293 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1294 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1295 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1296 char_flags |= CHARACTER_FLAG_GHOST;
1297 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1298 char_flags |= CHARACTER_FLAG_RENAME;
1299 // always send the flag if declined names aren't used
1300 // to let the client select a default method of declining the name
1301 if(!sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) || (result && result->Fetch()[12].GetCppString() != ""))
1302 char_flags |= CHARACTER_FLAG_DECLINED;
1304 *p_data << (uint32)char_flags; // character flags
1306 *p_data << (uint8)1; // unknown
1308 // Pets info
1310 uint32 petDisplayId = 0;
1311 uint32 petLevel = 0;
1312 uint32 petFamily = 0;
1314 // show pet at selection character in character list only for non-ghost character
1315 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1317 Field* fields = result->Fetch();
1319 uint32 entry = fields[9].GetUInt32();
1320 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1321 if(cInfo)
1323 petDisplayId = fields[10].GetUInt32();
1324 petLevel = fields[11].GetUInt32();
1325 petFamily = cInfo->family;
1329 *p_data << (uint32)petDisplayId;
1330 *p_data << (uint32)petLevel;
1331 *p_data << (uint32)petFamily;
1334 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1335 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1336 items[i] = NULL;
1338 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1339 if (result)
1343 Field *fields = result->Fetch();
1344 uint8 slot = fields[0].GetUInt8() & 255;
1345 uint32 item_id = fields[1].GetUInt32();
1346 if( slot >= EQUIPMENT_SLOT_END )
1347 continue;
1349 items[slot] = objmgr.GetItemPrototype(item_id);
1350 if(!items[slot])
1352 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1353 continue;
1355 } while (result->NextRow());
1356 delete result;
1359 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1361 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1362 uint32 item_id = GetUInt32Value(visualbase);
1363 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1364 SpellItemEnchantmentEntry const *enchant = NULL;
1366 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1368 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1369 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1370 break;
1373 if (proto != NULL)
1375 *p_data << (uint32)proto->DisplayInfoID;
1376 *p_data << (uint8)proto->InventoryType;
1377 *p_data << (uint32)(enchant?enchant->aura_id:0);
1379 else
1381 *p_data << (uint32)0;
1382 *p_data << (uint8)0;
1383 *p_data << (uint32)0; // enchant?
1386 *p_data << (uint32)0; // first bag display id
1387 *p_data << (uint8)0; // first bag inventory type
1388 *p_data << (uint32)0; // enchant?
1391 bool Player::ToggleAFK()
1393 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1395 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1397 // afk player not allowed in battleground
1398 if(state && InBattleGround())
1399 LeaveBattleground();
1401 return state;
1404 bool Player::ToggleDND()
1406 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1408 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1411 uint8 Player::chatTag() const
1413 // it's bitmask
1414 // 0x8 - ??
1415 // 0x4 - gm
1416 // 0x2 - dnd
1417 // 0x1 - afk
1418 if(isGMChat())
1419 return 4;
1420 else if(isDND())
1421 return 3;
1422 if(isAFK())
1423 return 1;
1424 else
1425 return 0;
1428 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1430 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1432 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1433 return false;
1436 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1437 Pet* pet = GetPet();
1439 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1441 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1442 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1443 return false;
1445 // client without expansion support
1446 if(GetSession()->Expansion() < mEntry->Expansion())
1448 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessable map %u", GetName(), mapid);
1450 if(GetTransport())
1451 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1453 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL1);
1455 return false; // normal client can't teleport to this map...
1457 else
1459 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1462 // if we were on a transport, leave
1463 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1465 m_transport->RemovePassenger(this);
1466 m_transport = NULL;
1467 m_movementInfo.t_x = 0.0f;
1468 m_movementInfo.t_y = 0.0f;
1469 m_movementInfo.t_z = 0.0f;
1470 m_movementInfo.t_o = 0.0f;
1471 m_movementInfo.t_time = 0;
1474 SetSemaphoreTeleport(true);
1476 // The player was ported to another map and looses the duel immediatly.
1477 // We have to perform this check before the teleport, otherwise the
1478 // ObjectAccessor won't find the flag.
1479 if (duel && this->GetMapId()!=mapid)
1481 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1482 if (obj)
1483 DuelComplete(DUEL_FLED);
1486 // reset movement flags at teleport, because player will continue move with these flags after teleport
1487 SetUnitMovementFlags(0);
1489 if ((this->GetMapId() == mapid) && (!m_transport))
1491 // prepare zone change detect
1492 uint32 old_zone = GetZoneId();
1494 // near teleport
1495 if(!GetSession()->PlayerLogout())
1497 WorldPacket data;
1498 BuildTeleportAckMsg(&data, x, y, z, orientation);
1499 GetSession()->SendPacket(&data);
1500 SetPosition( x, y, z, orientation, true);
1502 else
1503 // this will be used instead of the current location in SaveToDB
1504 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1506 //BuildHeartBeatMsg(&data);
1507 //SendMessageToSet(&data, true);
1508 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1510 //same map, only remove pet if out of range
1511 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1513 if(pet->isControlled() && !pet->isTemporarySummoned() )
1514 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1515 else
1516 m_temporaryUnsummonedPetNumber = 0;
1518 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1522 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1523 CombatStop();
1525 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1527 // resummon pet
1528 if(pet && m_temporaryUnsummonedPetNumber)
1530 Pet* NewPet = new Pet;
1531 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1532 delete NewPet;
1534 m_temporaryUnsummonedPetNumber = 0;
1538 if(!GetSession()->PlayerLogout())
1540 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1541 SetSemaphoreTeleport(false);
1543 UpdateZone(GetZoneId());
1546 // new zone
1547 if(old_zone != GetZoneId())
1549 // honorless target
1550 if(pvpInfo.inHostileArea)
1551 CastSpell(this, 2479, true);
1554 else
1556 // far teleport to another map
1557 Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
1558 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1560 // Check enter rights before map getting to avoid creating instance copy for player
1561 // this check not dependent from map instance copy and same for all instance copies of selected map
1562 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1564 SetSemaphoreTeleport(false);
1565 return false;
1568 // If the map is not created, assume it is possible to enter it.
1569 // It will be created in the WorldPortAck.
1570 Map *map = MapManager::Instance().FindMap(mapid);
1571 if (!map || map->CanEnter(this))
1573 SetSelection(0);
1575 CombatStop();
1577 ResetContestedPvP();
1579 // remove player from battleground on far teleport (when changing maps)
1580 if(BattleGround const* bg = GetBattleGround())
1582 // Note: at battleground join battleground id set before teleport
1583 // and we already will found "current" battleground
1584 // just need check that this is targeted map or leave
1585 if(bg->GetMapId() != mapid)
1586 LeaveBattleground(false); // don't teleport to entry point
1589 // remove pet on map change
1590 if (pet)
1592 //leaving map -> delete pet right away (doing this later will cause problems)
1593 if(pet->isControlled() && !pet->isTemporarySummoned())
1594 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1595 else
1596 m_temporaryUnsummonedPetNumber = 0;
1598 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1601 // remove all dyn objects
1602 RemoveAllDynObjects();
1604 // stop spellcasting
1605 // not attempt interrupt teleportation spell at caster teleport
1606 if(!(options & TELE_TO_SPELL))
1607 if(IsNonMeleeSpellCasted(true))
1608 InterruptNonMeleeSpells(true);
1610 if(!GetSession()->PlayerLogout())
1612 // send transfer packets
1613 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1614 data << uint32(mapid);
1615 if (m_transport)
1617 data << m_transport->GetEntry() << GetMapId();
1619 GetSession()->SendPacket(&data);
1621 data.Initialize(SMSG_NEW_WORLD, (20));
1622 if (m_transport)
1624 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1626 else
1628 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1630 GetSession()->SendPacket( &data );
1631 SendSavedInstances();
1633 // remove from old map now
1634 if(oldmap) oldmap->Remove(this, false);
1637 // new final coordinates
1638 float final_x = x;
1639 float final_y = y;
1640 float final_z = z;
1641 float final_o = orientation;
1643 if(m_transport)
1645 final_x += m_movementInfo.t_x;
1646 final_y += m_movementInfo.t_y;
1647 final_z += m_movementInfo.t_z;
1648 final_o += m_movementInfo.t_o;
1651 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1652 // if the player is saved before worldportack (at logout for example)
1653 // this will be used instead of the current location in SaveToDB
1655 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1657 // move packet sent by client always after far teleport
1658 // SetPosition(final_x, final_y, final_z, final_o, true);
1659 SetDontMove(true);
1661 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1663 else
1664 return false;
1666 return true;
1669 void Player::AddToWorld()
1671 ///- Do not add/remove the player from the object storage
1672 ///- It will crash when updating the ObjectAccessor
1673 ///- The player should only be added when logging in
1674 Unit::AddToWorld();
1676 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1678 if(m_items[i])
1679 m_items[i]->AddToWorld();
1683 void Player::RemoveFromWorld()
1685 // cleanup
1686 if(IsInWorld())
1688 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1689 Uncharm();
1690 UnsummonAllTotems();
1691 RemoveMiniPet();
1692 RemoveGuardians();
1695 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1697 if(m_items[i])
1698 m_items[i]->RemoveFromWorld();
1701 ///- Do not add/remove the player from the object storage
1702 ///- It will crash when updating the ObjectAccessor
1703 ///- The player should only be removed when logging out
1704 Unit::RemoveFromWorld();
1707 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1709 float addRage;
1711 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1713 if(attacker)
1715 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1717 // talent who gave more rage on attack
1718 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1720 else
1722 addRage = damage/rageconversion*2.5;
1724 // Berserker Rage effect
1725 if(HasAura(18499,0))
1726 addRage *= 1.3;
1729 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1731 ModifyPower(POWER_RAGE, uint32(addRage*10));
1734 void Player::RegenerateAll()
1736 if (m_regenTimer != 0)
1737 return;
1738 uint32 regenDelay = 2000;
1740 // Not in combat or they have regeneration
1741 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1742 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1744 RegenerateHealth();
1745 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1746 Regenerate(POWER_RAGE);
1749 Regenerate( POWER_ENERGY );
1751 Regenerate( POWER_MANA );
1753 m_regenTimer = regenDelay;
1756 void Player::Regenerate(Powers power)
1758 uint32 curValue = GetPower(power);
1759 uint32 maxValue = GetMaxPower(power);
1761 float addvalue = 0.0f;
1763 switch (power)
1765 case POWER_MANA:
1767 bool recentCast = IsUnderLastManaUseEffect();
1768 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1769 if (recentCast)
1771 // Mangos Updates Mana in intervals of 2s, which is correct
1772 addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT) * ManaIncreaseRate * 2.00f;
1774 else
1776 addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN) * ManaIncreaseRate * 2.00f;
1778 } break;
1779 case POWER_RAGE: // Regenerate rage
1781 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1782 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1783 } break;
1784 case POWER_ENERGY: // Regenerate energy (rogue)
1785 addvalue = 20;
1786 break;
1787 case POWER_FOCUS:
1788 case POWER_HAPPINESS:
1789 break;
1792 // Mana regen calculated in Player::UpdateManaRegen()
1793 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1794 if(power != POWER_MANA)
1796 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1797 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1798 if ((*i)->GetModifier()->m_miscvalue == power)
1799 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1802 if (power != POWER_RAGE)
1804 curValue += uint32(addvalue);
1805 if (curValue > maxValue)
1806 curValue = maxValue;
1808 else
1810 if(curValue <= uint32(addvalue))
1811 curValue = 0;
1812 else
1813 curValue -= uint32(addvalue);
1815 SetPower(power, curValue);
1818 void Player::RegenerateHealth()
1820 uint32 curValue = GetHealth();
1821 uint32 maxValue = GetMaxHealth();
1823 if (curValue >= maxValue) return;
1825 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1827 float addvalue = 0.0f;
1829 // polymorphed case
1830 if ( IsPolymorphed() )
1831 addvalue = GetMaxHealth()/3;
1832 // normal regen case (maybe partly in combat case)
1833 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1835 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1836 if (!isInCombat())
1838 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1839 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1840 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1842 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1843 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1845 if(!IsStandState())
1846 addvalue *= 1.5;
1849 // always regeneration bonus (including combat)
1850 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1852 if(addvalue < 0)
1853 addvalue = 0;
1855 ModifyHealth(int32(addvalue));
1858 bool Player::CanInteractWithNPCs(bool alive) const
1860 if(alive && !isAlive())
1861 return false;
1862 if(isInFlight())
1863 return false;
1865 return true;
1868 bool Player::IsUnderWater() const
1870 return IsInWater() &&
1871 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1874 void Player::SetInWater(bool apply)
1876 if(m_isInWater==apply)
1877 return;
1879 //define player in water by opcodes
1880 //move player's guid into HateOfflineList of those mobs
1881 //which can't swim and move guid back into ThreatList when
1882 //on surface.
1883 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1884 m_isInWater = apply;
1886 // remove auras that need water/land
1887 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1889 getHostilRefManager().updateThreatTables();
1892 void Player::SetGameMaster(bool on)
1894 if(on)
1896 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1897 setFaction(35);
1898 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1900 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1901 ResetContestedPvP();
1903 getHostilRefManager().setOnlineOfflineState(false);
1904 CombatStop();
1906 else
1908 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1909 setFactionForRace(getRace());
1910 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1912 // restore FFA PvP Server state
1913 if(sWorld.IsFFAPvPRealm())
1914 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1916 // restore FFA PvP area state, remove not allowed for GM mounts
1917 UpdateArea(m_areaUpdateId);
1919 getHostilRefManager().setOnlineOfflineState(true);
1922 ObjectAccessor::UpdateVisibilityForPlayer(this);
1925 void Player::SetGMVisible(bool on)
1927 if(on)
1929 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1931 // Reapply stealth/invisibility if active or show if not any
1932 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
1933 SetVisibility(VISIBILITY_GROUP_STEALTH);
1934 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
1935 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
1936 else
1937 SetVisibility(VISIBILITY_ON);
1939 else
1941 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
1943 SetAcceptWhispers(false);
1944 SetGameMaster(true);
1946 SetVisibility(VISIBILITY_OFF);
1950 bool Player::IsGroupVisibleFor(Player* p) const
1952 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
1954 default: return IsInSameGroupWith(p);
1955 case 1: return IsInSameRaidWith(p);
1956 case 2: return GetTeam()==p->GetTeam();
1960 bool Player::IsInSameGroupWith(Player const* p) const
1962 return p==this || GetGroup() != NULL &&
1963 GetGroup() == p->GetGroup() &&
1964 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
1967 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1968 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1969 void Player::UninviteFromGroup()
1971 if(GetGroupInvite()) // uninvited invitee
1973 Group* group = GetGroupInvite();
1974 group->RemoveInvite(this);
1976 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
1978 if(group->IsCreated())
1980 group->Disband(true);
1981 objmgr.RemoveGroup(group);
1983 else
1984 group->RemoveAllInvites();
1986 delete group;
1991 void Player::RemoveFromGroup(Group* group, uint64 guid)
1993 if(group)
1995 if (group->RemoveMember(guid, 0) <= 1)
1997 // group->Disband(); already disbanded in RemoveMember
1998 objmgr.RemoveGroup(group);
1999 delete group;
2000 // removemember sets the player's group pointer to NULL
2005 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2007 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2008 data << uint64(victim ? victim->GetGUID() : 0); // guid
2009 data << uint32(GivenXP+RestXP); // given experience
2010 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2011 if(victim)
2013 data << uint32(GivenXP); // experience without rested bonus
2014 data << float(1); // 1 - none 0 - 100% group bonus output
2016 data << uint8(0); // new 2.4.0
2017 GetSession()->SendPacket(&data);
2020 void Player::GiveXP(uint32 xp, Unit* victim)
2022 if ( xp < 1 )
2023 return;
2025 if(!isAlive())
2026 return;
2028 uint32 level = getLevel();
2030 // XP to money conversion processed in Player::RewardQuest
2031 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2032 return;
2034 // handle SPELL_AURA_MOD_XP_PCT auras
2035 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2036 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2037 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2039 // XP resting bonus for kill
2040 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2042 SendLogXPGain(xp,victim,rested_bonus_xp);
2044 uint32 curXP = GetUInt32Value(PLAYER_XP);
2045 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2046 uint32 newXP = curXP + xp + rested_bonus_xp;
2048 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2050 newXP -= nextLvlXP;
2052 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2053 GiveLevel(level + 1);
2055 level = getLevel();
2056 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2059 SetUInt32Value(PLAYER_XP, newXP);
2062 // Update player to next level
2063 // Current player experience not update (must be update by caller)
2064 void Player::GiveLevel(uint32 level)
2066 if ( level == getLevel() )
2067 return;
2069 PlayerLevelInfo info;
2070 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2072 PlayerClassLevelInfo classInfo;
2073 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2075 // send levelup info to client
2076 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2077 data << uint32(level);
2078 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2079 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2080 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2081 data << uint32(0);
2082 data << uint32(0);
2083 data << uint32(0);
2084 data << uint32(0);
2085 // end for
2086 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2087 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2089 GetSession()->SendPacket(&data);
2091 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2093 //update level, max level of skills
2094 if(getLevel()!= level)
2095 m_Played_time[1] = 0; // Level Played Time reset
2096 SetLevel(level);
2097 UpdateMaxSkills();
2099 // save base values (bonuses already included in stored stats
2100 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2101 SetCreateStat(Stats(i), info.stats[i]);
2103 SetCreateHealth(classInfo.basehealth);
2104 SetCreateMana(classInfo.basemana);
2106 InitTalentForLevel();
2107 InitTaxiNodesForLevel();
2109 UpdateAllStats();
2111 // set current level health and mana/energy to maximum after applying all mods.
2112 SetHealth(GetMaxHealth());
2113 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2114 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2115 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2116 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2117 SetPower(POWER_FOCUS, 0);
2118 SetPower(POWER_HAPPINESS, 0);
2120 // give level to summoned pet
2121 Pet* pet = GetPet();
2122 if(pet && pet->getPetType()==SUMMON_PET)
2123 pet->GivePetLevel(level);
2126 void Player::InitTalentForLevel()
2128 uint32 level = getLevel();
2129 // talents base at level diff ( talents = level - 9 but some can be used already)
2130 if(level < 10)
2132 // Remove all talent points
2133 if(m_usedTalentCount > 0) // Free any used talents
2135 resetTalents(true);
2136 SetFreeTalentPoints(0);
2139 else
2141 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2142 // if used more that have then reset
2143 if(m_usedTalentCount > talentPointsForLevel)
2145 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2146 resetTalents(true);
2147 else
2148 SetFreeTalentPoints(0);
2150 // else update amount of free points
2151 else
2152 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2156 void Player::InitStatsForLevel(bool reapplyMods)
2158 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2159 _RemoveAllStatBonuses();
2161 PlayerClassLevelInfo classInfo;
2162 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2164 PlayerLevelInfo info;
2165 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2167 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2168 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2170 UpdateMaxSkills ();
2172 // set default cast time multiplier
2173 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2175 // reset size before reapply auras
2176 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2178 // save base values (bonuses already included in stored stats
2179 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2180 SetCreateStat(Stats(i), info.stats[i]);
2182 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2183 SetStat(Stats(i), info.stats[i]);
2185 SetCreateHealth(classInfo.basehealth);
2187 //set create powers
2188 SetCreateMana(classInfo.basemana);
2190 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2192 InitStatBuffMods();
2194 //reset rating fields values
2195 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2196 SetUInt32Value(index, 0);
2198 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2199 for (int i = 0; i < 7; i++)
2201 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2202 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2203 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2206 //reset attack power, damage and attack speed fields
2207 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2208 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2209 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2211 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2212 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2213 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2214 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2215 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2216 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2218 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2219 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2220 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2221 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2222 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2223 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2225 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2226 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2227 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2228 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2230 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2231 for (uint8 i = 0; i < 7; ++i)
2232 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2234 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2235 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2236 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2238 // Dodge percentage
2239 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2241 // set armor (resistance 0) to original value (create_agility*2)
2242 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2243 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2244 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2245 // set other resistance to original value (0)
2246 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2248 SetResistance(SpellSchools(i), 0);
2249 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2250 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2253 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2254 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2255 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2257 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2258 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2260 // Init data for form but skip reapply item mods for form
2261 InitDataForForm(reapplyMods);
2263 // save new stats
2264 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2265 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2267 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2269 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2270 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2272 // cleanup unit flags (will be re-applied if need at aura load).
2273 RemoveFlag( UNIT_FIELD_FLAGS,
2274 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2275 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2276 UNIT_FLAG_DISABLE_ROTATE | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2277 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2278 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2279 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2281 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2282 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2284 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2286 // restore if need some important flags
2287 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2289 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2290 _ApplyAllStatBonuses();
2292 // set current level health and mana/energy to maximum after applying all mods.
2293 SetHealth(GetMaxHealth());
2294 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2295 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2296 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2297 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2298 SetPower(POWER_FOCUS, 0);
2299 SetPower(POWER_HAPPINESS, 0);
2302 void Player::SendInitialSpells()
2304 uint16 spellCount = 0;
2306 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2307 data << uint8(0);
2309 size_t countPos = data.wpos();
2310 data << uint16(spellCount); // spell count placeholder
2312 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2314 if(itr->second->state == PLAYERSPELL_REMOVED)
2315 continue;
2317 if(!itr->second->active || itr->second->disabled)
2318 continue;
2320 data << uint16(itr->first);
2321 //data << uint16(itr->second->slotId);
2322 data << uint16(0); // it's not slot id
2324 spellCount +=1;
2327 data.put<uint16>(countPos,spellCount); // write real count value
2329 uint16 spellCooldowns = m_spellCooldowns.size();
2330 data << uint16(spellCooldowns);
2331 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
2333 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2334 if(!sEntry)
2335 continue;
2337 data << uint16(itr->first);
2339 time_t cooldown = 0;
2340 time_t curTime = time(NULL);
2341 if(itr->second.end > curTime)
2342 cooldown = (itr->second.end-curTime)*1000;
2344 data << uint16(itr->second.itemid); // cast item id
2345 data << uint16(sEntry->Category); // spell category
2346 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2348 data << uint32(0);
2349 data << uint32(cooldown);
2351 else
2353 data << uint32(cooldown);
2354 data << uint32(0);
2358 GetSession()->SendPacket(&data);
2360 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2363 void Player::RemoveMail(uint32 id)
2365 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2367 if ((*itr)->messageID == id)
2369 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2370 m_mail.erase(itr);
2371 return;
2376 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2378 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2379 data << (uint32) mailId;
2380 data << (uint32) mailAction;
2381 data << (uint32) mailError;
2382 if ( mailError == MAIL_ERR_BAG_FULL )
2383 data << (uint32) equipError;
2384 else if( mailAction == MAIL_ITEM_TAKEN )
2386 data << (uint32) item_guid; // item guid low?
2387 data << (uint32) item_count; // item count?
2389 GetSession()->SendPacket(&data);
2392 void Player::SendNewMail()
2394 // deliver undelivered mail
2395 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2396 data << (uint32) 0;
2397 GetSession()->SendPacket(&data);
2400 void Player::UpdateNextMailTimeAndUnreads()
2402 // calculate next delivery time (min. from non-delivered mails
2403 // and recalculate unReadMail
2404 time_t cTime = time(NULL);
2405 m_nextMailDelivereTime = 0;
2406 unReadMails = 0;
2407 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2409 if((*itr)->deliver_time > cTime)
2411 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2412 m_nextMailDelivereTime = (*itr)->deliver_time;
2414 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2415 ++unReadMails;
2419 void Player::AddNewMailDeliverTime(time_t deliver_time)
2421 if(deliver_time <= time(NULL)) // ready now
2423 ++unReadMails;
2424 SendNewMail();
2426 else // not ready and no have ready mails
2428 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2429 m_nextMailDelivereTime = deliver_time;
2433 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2435 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2436 if (!spellInfo)
2438 // do character spell book cleanup (all characters)
2439 if(loading && !learning) // spell load case
2441 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2442 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2444 else
2445 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2447 return false;
2450 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2452 // do character spell book cleanup (all characters)
2453 if(loading && !learning) // spell load case
2455 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2456 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2458 else
2459 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2461 return false;
2464 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2466 bool disabled_case = false;
2467 bool superceded_old = false;
2469 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2470 if (itr != m_spells.end())
2472 // update active state for known spell
2473 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2475 itr->second->active = active;
2477 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2478 if(loading && !learning)
2479 itr->second->state = PLAYERSPELL_UNCHANGED;
2480 else if(itr->second->state != PLAYERSPELL_NEW)
2481 itr->second->state = PLAYERSPELL_CHANGED;
2483 if(!active)
2485 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2486 data << uint16(spell_id);
2487 GetSession()->SendPacket(&data);
2489 return active; // learn (show in spell book if active now)
2492 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2494 if(itr->second->state != PLAYERSPELL_NEW)
2495 itr->second->state = PLAYERSPELL_CHANGED;
2496 itr->second->disabled = disabled;
2498 if(disabled)
2499 return false;
2501 disabled_case = true;
2503 else switch(itr->second->state)
2505 case PLAYERSPELL_UNCHANGED: // known saved spell
2506 return false;
2507 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2509 delete itr->second;
2510 m_spells.erase(itr);
2511 state = PLAYERSPELL_CHANGED;
2512 break; // need re-add
2514 default: // known not saved yet spell (new or modified)
2516 // can be in case spell loading but learned at some previous spell loading
2517 if(loading && !learning)
2518 itr->second->state = PLAYERSPELL_UNCHANGED;
2520 return false;
2525 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2527 // talent: unlearn all other talent ranks (high and low)
2528 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2530 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2532 for(int i=0; i <5; ++i)
2534 // skip learning spell and no rank spell case
2535 uint32 rankSpellId = talentInfo->RankID[i];
2536 if(!rankSpellId || rankSpellId==spell_id)
2537 continue;
2539 // skip unknown ranks
2540 if(!HasSpell(rankSpellId))
2541 continue;
2543 removeSpell(rankSpellId);
2547 // non talent spell: learn low ranks (recursive call)
2548 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2550 if(loading) // at spells loading, no output, but allow save
2551 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2552 else // at normal learning
2553 learnSpell(prev_spell);
2556 PlayerSpell *newspell = new PlayerSpell;
2557 newspell->active = active;
2558 newspell->state = state;
2559 newspell->disabled = disabled;
2561 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2562 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2564 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2566 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2567 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2568 if(!i_spellInfo) continue;
2570 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2572 if(itr->second->active)
2574 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2576 if(!loading) // not send spell (re-/over-)learn packets at loading
2578 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2579 data << uint16(itr->first);
2580 data << uint16(spell_id);
2581 GetSession()->SendPacket( &data );
2584 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2585 itr->second->active = false;
2586 itr->second->state = PLAYERSPELL_CHANGED;
2587 superceded_old = true; // new spell replace old in action bars and spell book.
2589 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2591 if(!loading) // not send spell (re-/over-)learn packets at loading
2593 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2594 data << uint16(spell_id);
2595 data << uint16(itr->first);
2596 GetSession()->SendPacket( &data );
2599 // mark new spell as disable (not learned yet for client and will not learned)
2600 newspell->active = false;
2601 if(newspell->state != PLAYERSPELL_NEW)
2602 newspell->state = PLAYERSPELL_CHANGED;
2609 uint16 tmpslot=slot_id;
2611 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2613 uint16 maxid = 0;
2614 PlayerSpellMap::iterator itr;
2615 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2617 if(itr->second->state == PLAYERSPELL_REMOVED)
2618 continue;
2619 if (itr->second->slotId > maxid)
2620 maxid = itr->second->slotId;
2622 tmpslot = maxid + 1;
2625 newspell->slotId = tmpslot;
2626 m_spells[spell_id] = newspell;
2628 // return false if spell disabled
2629 if (newspell->disabled)
2630 return false;
2633 uint32 talentCost = GetTalentSpellCost(spell_id);
2635 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2636 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2637 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2639 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2640 CastSpell(this, spell_id, true);
2642 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2643 else if (IsPassiveSpell(spell_id))
2645 // if spell doesn't require a stance or the player is in the required stance
2646 if( ( !spellInfo->Stances &&
2647 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2648 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2649 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2650 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2651 (spell_id == 5420 && m_form == FORM_TREE) ||
2652 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2653 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2654 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2655 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2656 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2657 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2658 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2659 //Check CasterAuraStates
2660 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2661 CastSpell(this, spell_id, true);
2663 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2665 CastSpell(this, spell_id, true);
2666 return false;
2669 // update used talent points count
2670 m_usedTalentCount += talentCost;
2672 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2673 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2675 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2676 SetFreePrimaryProffesions(freeProfs-1);
2679 // add dependent skills
2680 uint16 maxskill = GetMaxSkillValueForLevel();
2682 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2684 if(spellLearnSkill)
2686 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2687 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2689 if(skill_value < spellLearnSkill->value)
2690 skill_value = spellLearnSkill->value;
2692 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2694 if(skill_max_value < new_skill_max_value)
2695 skill_max_value = new_skill_max_value;
2697 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2699 else
2701 // not ranked skills
2702 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2703 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2705 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2707 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2708 if(!pSkill)
2709 continue;
2711 if(HasSkill(pSkill->id))
2712 continue;
2714 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2715 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2716 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2717 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2718 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2720 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2722 case SKILL_RANGE_LANGUAGE:
2723 SetSkill(pSkill->id, 300, 300 );
2724 break;
2725 case SKILL_RANGE_LEVEL:
2726 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2727 break;
2728 case SKILL_RANGE_MONO:
2729 SetSkill(pSkill->id, 1, 1 );
2730 break;
2731 default:
2732 break;
2738 // learn dependent spells
2739 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2740 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2742 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2744 if(!itr->second.autoLearned)
2746 if(loading) // at spells loading, no output, but allow save
2747 addSpell(itr->second.spell,true,true,loading);
2748 else // at normal learning
2749 learnSpell(itr->second.spell);
2753 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2754 return active && !disabled && !superceded_old;
2757 void Player::learnSpell(uint32 spell_id)
2759 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2761 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2762 bool active = disabled ? itr->second->active : true;
2764 bool learning = addSpell(spell_id,active);
2766 // learn all disabled higher ranks (recursive)
2767 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2768 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2770 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2771 if (disabled && iter != m_spells.end() && iter->second->disabled)
2772 learnSpell(i->second);
2775 // prevent duplicated entires in spell book
2776 if(!learning)
2777 return;
2779 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2780 data << uint32(spell_id);
2781 GetSession()->SendPacket(&data);
2784 void Player::removeSpell(uint32 spell_id, bool disabled)
2786 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2787 if (itr == m_spells.end())
2788 return;
2790 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2791 return;
2793 // unlearn non talent higher ranks (recursive)
2794 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2795 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2796 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2797 removeSpell(itr2->second,disabled);
2799 // removing
2800 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2801 data << uint16(spell_id);
2802 GetSession()->SendPacket(&data);
2804 if (disabled)
2806 itr->second->disabled = disabled;
2807 if(itr->second->state != PLAYERSPELL_NEW)
2808 itr->second->state = PLAYERSPELL_CHANGED;
2810 else
2812 if(itr->second->state == PLAYERSPELL_NEW)
2814 delete itr->second;
2815 m_spells.erase(itr);
2817 else
2818 itr->second->state = PLAYERSPELL_REMOVED;
2821 RemoveAurasDueToSpell(spell_id);
2823 // remove pet auras
2824 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2825 RemovePetAura(petSpell);
2827 // free talent points
2828 uint32 talentCosts = GetTalentSpellCost(spell_id);
2829 if(talentCosts > 0)
2831 if(talentCosts < m_usedTalentCount)
2832 m_usedTalentCount -= talentCosts;
2833 else
2834 m_usedTalentCount = 0;
2837 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2838 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2840 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2841 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2842 SetFreePrimaryProffesions(freeProfs);
2845 // remove dependent skill
2846 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2847 if(spellLearnSkill)
2849 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2850 if(!prev_spell) // first rank, remove skill
2851 SetSkill(spellLearnSkill->skill,0,0);
2852 else
2854 // search prev. skill setting by spell ranks chain
2855 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2856 while(!prevSkill && prev_spell)
2858 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2859 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2862 if(!prevSkill) // not found prev skill setting, remove skill
2863 SetSkill(spellLearnSkill->skill,0,0);
2864 else // set to prev. skill setting values
2866 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2867 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2869 if(skill_value > prevSkill->value)
2870 skill_value = prevSkill->value;
2872 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2874 if(skill_max_value > new_skill_max_value)
2875 skill_max_value = new_skill_max_value;
2877 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2882 else
2884 // not ranked skills
2885 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2886 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2888 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2890 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2891 if(!pSkill)
2892 continue;
2894 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2895 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2896 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2897 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2898 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2900 // not reset skills for professions and racial abilities
2901 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2902 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2903 continue;
2905 SetSkill(pSkill->id, 0, 0 );
2910 // remove dependent spells
2911 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2912 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2914 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2915 removeSpell(itr2->second.spell, disabled);
2918 void Player::RemoveArenaSpellCooldowns()
2920 // remove cooldowns on spells that has < 15 min CD
2921 SpellCooldowns::iterator itr, next;
2922 // iterate spell cooldowns
2923 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2925 next = itr;
2926 ++next;
2927 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
2928 // check if spellentry is present and if the cooldown is less than 15 mins
2929 if( entry &&
2930 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
2931 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
2933 // notify player
2934 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2935 data << uint32(itr->first);
2936 data << GetGUID();
2937 GetSession()->SendPacket(&data);
2938 // remove cooldown
2939 m_spellCooldowns.erase(itr);
2944 void Player::RemoveAllSpellCooldown()
2946 if(!m_spellCooldowns.empty())
2948 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
2950 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2951 data << uint32(itr->first);
2952 data << uint64(GetGUID());
2953 GetSession()->SendPacket(&data);
2955 m_spellCooldowns.clear();
2959 void Player::_LoadSpellCooldowns(QueryResult *result)
2961 m_spellCooldowns.clear();
2963 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2965 if(result)
2967 time_t curTime = time(NULL);
2971 Field *fields = result->Fetch();
2973 uint32 spell_id = fields[0].GetUInt32();
2974 uint32 item_id = fields[1].GetUInt32();
2975 time_t db_time = (time_t)fields[2].GetUInt64();
2977 if(!sSpellStore.LookupEntry(spell_id))
2979 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
2980 continue;
2983 // skip outdated cooldown
2984 if(db_time <= curTime)
2985 continue;
2987 AddSpellCooldown(spell_id, item_id, db_time);
2989 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
2991 while( result->NextRow() );
2993 delete result;
2997 void Player::_SaveSpellCooldowns()
2999 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3001 time_t curTime = time(NULL);
3003 // remove outdated and save active
3004 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3006 if(itr->second.end <= curTime)
3007 m_spellCooldowns.erase(itr++);
3008 else
3010 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));
3011 ++itr;
3016 uint32 Player::resetTalentsCost() const
3018 // The first time reset costs 1 gold
3019 if(m_resetTalentsCost < 1*GOLD)
3020 return 1*GOLD;
3021 // then 5 gold
3022 else if(m_resetTalentsCost < 5*GOLD)
3023 return 5*GOLD;
3024 // After that it increases in increments of 5 gold
3025 else if(m_resetTalentsCost < 10*GOLD)
3026 return 10*GOLD;
3027 else
3029 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3030 if(months > 0)
3032 // This cost will be reduced by a rate of 5 gold per month
3033 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3034 // to a minimum of 10 gold.
3035 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3037 else
3039 // After that it increases in increments of 5 gold
3040 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3041 // until it hits a cap of 50 gold.
3042 if(new_cost > 50*GOLD)
3043 new_cost = 50*GOLD;
3044 return new_cost;
3049 bool Player::resetTalents(bool no_cost)
3051 // not need after this call
3052 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3054 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3055 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3058 uint32 level = getLevel();
3059 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3061 if (m_usedTalentCount == 0)
3063 SetFreeTalentPoints(talentPointsForLevel);
3064 return false;
3067 uint32 cost = 0;
3069 if(!no_cost)
3071 cost = resetTalentsCost();
3073 if (GetMoney() < cost)
3075 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3076 return false;
3080 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3082 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3084 if (!talentInfo) continue;
3086 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3088 if(!talentTabInfo)
3089 continue;
3091 // unlearn only talents for character class
3092 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3093 // to prevent unexpected lost normal learned spell skip another class talents
3094 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3095 continue;
3097 for (int j = 0; j < 5; j++)
3099 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3101 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3103 ++itr;
3104 continue;
3107 // remove learned spells (all ranks)
3108 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3110 // unlearn if first rank is talent or learned by talent
3111 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3113 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3114 itr = GetSpellMap().begin();
3115 continue;
3117 else
3118 ++itr;
3123 SetFreeTalentPoints(talentPointsForLevel);
3125 if(!no_cost)
3127 ModifyMoney(-(int32)cost);
3129 m_resetTalentsCost = cost;
3130 m_resetTalentsTime = time(NULL);
3133 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3134 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3136 return true;
3139 bool Player::_removeSpell(uint16 spell_id)
3141 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3142 if (itr != m_spells.end())
3144 delete itr->second;
3145 m_spells.erase(itr);
3146 return true;
3148 return false;
3151 Mail* Player::GetMail(uint32 id)
3153 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
3155 if ((*itr)->messageID == id)
3157 return (*itr);
3160 return NULL;
3163 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3165 if(target == this)
3167 Object::_SetCreateBits(updateMask, target);
3169 else
3171 for(uint16 index = 0; index < m_valuesCount; index++)
3173 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3174 updateMask->SetBit(index);
3179 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3181 if(target == this)
3183 Object::_SetUpdateBits(updateMask, target);
3185 else
3187 Object::_SetUpdateBits(updateMask, target);
3188 *updateMask &= updateVisualBits;
3192 void Player::InitVisibleBits()
3194 updateVisualBits.SetCount(PLAYER_END);
3196 // TODO: really implement OWNER_ONLY and GROUP_ONLY. Flags can be found in UpdateFields.h
3198 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3199 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3200 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3202 updateVisualBits.SetBit(UNIT_FIELD_CHARM);
3203 updateVisualBits.SetBit(UNIT_FIELD_CHARM+1);
3205 updateVisualBits.SetBit(UNIT_FIELD_SUMMON);
3206 updateVisualBits.SetBit(UNIT_FIELD_SUMMON+1);
3208 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY);
3209 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY+1);
3211 updateVisualBits.SetBit(UNIT_FIELD_TARGET);
3212 updateVisualBits.SetBit(UNIT_FIELD_TARGET+1);
3214 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT);
3215 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT+1);
3217 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3218 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3219 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3220 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3221 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3222 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3224 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3225 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3226 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3227 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3228 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3229 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3231 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3232 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3233 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3234 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3235 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3236 for(uint16 i = UNIT_FIELD_AURA; i < UNIT_FIELD_AURASTATE; ++i)
3237 updateVisualBits.SetBit(i);
3238 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3239 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME);
3240 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3241 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3242 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3243 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3244 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3245 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3246 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3247 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3248 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3249 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3250 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3251 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3252 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3254 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER);
3255 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER+1);
3256 updateVisualBits.SetBit(PLAYER_FLAGS);
3257 updateVisualBits.SetBit(PLAYER_GUILDID);
3258 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3259 updateVisualBits.SetBit(PLAYER_BYTES);
3260 updateVisualBits.SetBit(PLAYER_BYTES_2);
3261 updateVisualBits.SetBit(PLAYER_BYTES_3);
3262 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3263 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3265 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3266 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i+=4)
3267 updateVisualBits.SetBit(i);
3269 //Players visible items are not inventory stuff
3270 //431) = 884 (0x374) = main weapon
3271 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; i++)
3273 // item creator
3274 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + (i*MAX_VISIBLE_ITEM_OFFSET) + 0);
3275 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + (i*MAX_VISIBLE_ITEM_OFFSET) + 1);
3277 uint16 visual_base = PLAYER_VISIBLE_ITEM_1_0 + (i*MAX_VISIBLE_ITEM_OFFSET);
3279 // item entry
3280 updateVisualBits.SetBit(visual_base + 0);
3282 // item enchantment IDs
3283 for(uint8 j = 0; j < MAX_INSPECTED_ENCHANTMENT_SLOT; ++j)
3284 updateVisualBits.SetBit(visual_base + 1 + j);
3286 // random properties
3287 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (i*MAX_VISIBLE_ITEM_OFFSET));
3288 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (i*MAX_VISIBLE_ITEM_OFFSET));
3291 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3294 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3296 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3298 if(m_items[i] == NULL)
3299 continue;
3301 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3304 if(target == this)
3307 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3309 if(m_items[i] == NULL)
3310 continue;
3312 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3314 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3316 if(m_items[i] == NULL)
3317 continue;
3319 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3323 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3326 void Player::DestroyForPlayer( Player *target ) const
3328 Unit::DestroyForPlayer( target );
3330 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3332 if(m_items[i] == NULL)
3333 continue;
3335 m_items[i]->DestroyForPlayer( target );
3338 if(target == this)
3341 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3343 if(m_items[i] == NULL)
3344 continue;
3346 m_items[i]->DestroyForPlayer( target );
3348 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3350 if(m_items[i] == NULL)
3351 continue;
3353 m_items[i]->DestroyForPlayer( target );
3358 bool Player::HasSpell(uint32 spell) const
3360 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3361 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3364 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3366 if (!trainer_spell)
3367 return TRAINER_SPELL_RED;
3369 if (!trainer_spell->spell)
3370 return TRAINER_SPELL_RED;
3372 // known spell
3373 if(HasSpell(trainer_spell->spell))
3374 return TRAINER_SPELL_GRAY;
3376 // check race/class requirement
3377 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3378 return TRAINER_SPELL_RED;
3380 // check level requirement
3381 if(getLevel() < trainer_spell->reqlevel)
3382 return TRAINER_SPELL_RED;
3384 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3386 // check prev.rank requirement
3387 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3388 return TRAINER_SPELL_RED;
3390 // check additional spell requirement
3391 if(spell_chain->req && !HasSpell(spell_chain->req))
3392 return TRAINER_SPELL_RED;
3395 // check skill requirement
3396 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3397 return TRAINER_SPELL_RED;
3399 // exist, already checked at loading
3400 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3402 // secondary prof. or not prof. spell
3403 uint32 skill = spell->EffectMiscValue[1];
3405 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3406 return TRAINER_SPELL_GREEN;
3408 // check primary prof. limit
3409 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3410 return TRAINER_SPELL_RED;
3412 return TRAINER_SPELL_GREEN;
3415 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3417 uint32 guid = GUID_LOPART(playerguid);
3419 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3420 // bones will be deleted by corpse/bones deleting thread shortly
3421 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3423 // remove from guild
3424 uint32 guildId = GetGuildIdFromDB(playerguid);
3425 if(guildId != 0)
3427 Guild* guild = objmgr.GetGuildById(guildId);
3428 if(guild)
3429 guild->DelMember(guid);
3432 // the player was uninvited already on logout so just remove from group
3433 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3434 if(resultGroup)
3436 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3437 delete resultGroup;
3438 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3439 if(group)
3441 RemoveFromGroup(group, playerguid);
3445 // remove signs from petitions (also remove petitions if owner);
3446 RemovePetitionsAndSigns(playerguid, 10);
3448 // return back all mails with COD and Item 0 1 2 3 4 5 6
3449 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);
3450 if(resultMail)
3454 Field *fields = resultMail->Fetch();
3456 uint32 mail_id = fields[0].GetUInt32();
3457 uint16 mailTemplateId= fields[1].GetUInt16();
3458 uint32 sender = fields[2].GetUInt32();
3459 std::string subject = fields[3].GetCppString();
3460 uint32 itemTextId = fields[4].GetUInt32();
3461 uint32 money = fields[5].GetUInt32();
3462 bool has_items = fields[6].GetBool();
3464 //we can return mail now
3465 //so firstly delete the old one
3466 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3468 MailItemsInfo mi;
3469 if(has_items)
3471 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3472 if(resultItems)
3476 Field *fields2 = resultItems->Fetch();
3478 uint32 item_guidlow = fields2[0].GetUInt32();
3479 uint32 item_template = fields2[1].GetUInt32();
3481 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3482 if(!itemProto)
3484 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3485 continue;
3488 Item *pItem = NewItemOrBag(itemProto);
3489 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3491 pItem->FSetState(ITEM_REMOVED);
3492 pItem->SaveToDB(); // it also deletes item object !
3493 continue;
3496 mi.AddItem(item_guidlow, item_template, pItem);
3498 while (resultItems->NextRow());
3500 delete resultItems;
3504 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3506 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3508 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, 0, mailTemplateId);
3510 while (resultMail->NextRow());
3512 delete resultMail;
3515 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3516 // Get guids of character's pets, will deleted in transaction
3517 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3519 // NOW we can finally clear other DB data related to character
3520 CharacterDatabase.BeginTransaction();
3521 if (resultPets)
3525 Field *fields3 = resultPets->Fetch();
3526 uint32 petguidlow = fields3[0].GetUInt32();
3527 Pet::DeleteFromDB(petguidlow);
3528 } while (resultPets->NextRow());
3529 delete resultPets;
3532 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3533 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3534 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3535 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3536 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3537 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3538 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3539 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3540 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3541 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3542 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3543 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3544 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3545 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3546 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3547 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3548 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3549 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3550 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3551 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3552 CharacterDatabase.CommitTransaction();
3554 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3555 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3558 void Player::SetMovement(PlayerMovementType pType)
3560 WorldPacket data;
3561 switch(pType)
3563 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3564 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3565 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3566 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3567 default:
3568 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3569 return;
3571 data.append(GetPackGUID());
3572 data << uint32(0);
3573 GetSession()->SendPacket( &data );
3576 /* Preconditions:
3577 - a resurrectable corpse must not be loaded for the player (only bones)
3578 - the player must be in world
3580 void Player::BuildPlayerRepop()
3582 if(getRace() == RACE_NIGHTELF)
3583 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)
3584 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3586 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3587 // there must be SMSG.STOP_MIRROR_TIMER
3588 // there we must send 888 opcode
3590 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3591 if(GetCorpse())
3593 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3594 assert(false);
3597 // create a corpse and place it at the player's location
3598 CreateCorpse();
3599 Corpse *corpse = GetCorpse();
3600 if(!corpse)
3602 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3603 return;
3605 GetMap()->Add(corpse);
3607 // convert player body to ghost
3608 SetHealth( 1 );
3610 SetMovement(MOVE_WATER_WALK);
3611 if(!GetSession()->isLogingOut())
3612 SetMovement(MOVE_UNROOT);
3614 // BG - remove insignia related
3615 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3617 SendCorpseReclaimDelay();
3619 // to prevent cheating
3620 corpse->ResetGhostTime();
3622 StopMirrorTimers(); //disable timers(bars)
3624 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3626 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3629 void Player::SendDelayResponse(const uint32 ml_seconds)
3631 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3632 data << (uint32)time(NULL);
3633 data << (uint32)0;
3634 GetSession()->SendPacket( &data );
3637 void Player::ResurrectPlayer(float restore_percent, bool updateToWorld, bool applySickness)
3639 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3640 data << uint32(-1);
3641 data << float(0);
3642 data << float(0);
3643 data << float(0);
3644 GetSession()->SendPacket(&data);
3646 // speed change, land walk
3648 // remove death flag + set aura
3649 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3650 if(getRace() == RACE_NIGHTELF)
3651 RemoveAurasDueToSpell(20584); // speed bonuses
3652 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3654 setDeathState(ALIVE);
3656 SetMovement(MOVE_LAND_WALK);
3657 SetMovement(MOVE_UNROOT);
3659 m_deathTimer = 0;
3661 // set health/powers (0- will be set in caller)
3662 if(restore_percent>0.0f)
3664 SetHealth(uint32(GetMaxHealth()*restore_percent));
3665 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3666 SetPower(POWER_RAGE, 0);
3667 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3670 // update visbility
3671 ObjectAccessor::UpdateVisibilityForPlayer(this);
3673 // some items limited to specific map
3674 DestroyZoneLimitedItem( true, GetZoneId());
3676 if(!applySickness || getLevel() <= 10)
3677 return;
3679 //Characters from level 1-10 are not affected by resurrection sickness.
3680 //Characters from level 11-19 will suffer from one minute of sickness
3681 //for each level they are above 10.
3682 //Characters level 20 and up suffer from ten minutes of sickness.
3683 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3685 if(int32(getLevel()) >= startLevel)
3687 // set resurrection sickness
3688 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3690 // not full duration
3691 if(int32(getLevel()) < startLevel+9)
3693 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3695 for(int i =0; i < 3; ++i)
3697 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3699 Aur->SetAuraDuration(delta*1000);
3700 Aur->UpdateAuraDuration();
3707 void Player::KillPlayer()
3709 SetMovement(MOVE_ROOT);
3711 StopMirrorTimers(); //disable timers(bars)
3713 setDeathState(CORPSE);
3714 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3716 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3717 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3719 // 6 minutes until repop at graveyard
3720 m_deathTimer = 6*MINUTE*1000;
3722 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3724 // don't create corpse at this moment, player might be falling
3726 // update visibility
3727 ObjectAccessor::UpdateObjectVisibility(this);
3730 void Player::CreateCorpse()
3732 // prevent existence 2 corpse for player
3733 SpawnCorpseBones();
3735 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3737 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3738 SetPvPDeath(false);
3740 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3741 GetPositionY(), GetPositionZ(), GetOrientation()))
3743 delete corpse;
3744 return;
3747 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3748 _pb = GetUInt32Value(PLAYER_BYTES);
3749 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3751 uint8 race = (uint8)(_uf);
3752 uint8 skin = (uint8)(_pb);
3753 uint8 face = (uint8)(_pb >> 8);
3754 uint8 hairstyle = (uint8)(_pb >> 16);
3755 uint8 haircolor = (uint8)(_pb >> 24);
3756 uint8 facialhair = (uint8)(_pb2);
3758 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3759 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3761 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3762 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3764 uint32 flags = CORPSE_FLAG_UNK2;
3765 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3766 flags |= CORPSE_FLAG_HIDE_HELM;
3767 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3768 flags |= CORPSE_FLAG_HIDE_CLOAK;
3769 if(InBattleGround())
3770 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3771 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3773 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3775 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3777 uint32 iDisplayID;
3778 uint16 iIventoryType;
3779 uint32 _cfi;
3780 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3782 if(m_items[i])
3784 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3785 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3787 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3788 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3792 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3793 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3794 assert(entry);
3795 if(entry->map_type != MAP_BATTLEGROUND)
3796 corpse->SaveToDB();
3798 // register for player, but not show
3799 ObjectAccessor::Instance().AddCorpse(corpse);
3802 void Player::SpawnCorpseBones()
3804 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3805 SaveToDB(); // prevent loading as ghost without corpse
3808 Corpse* Player::GetCorpse() const
3810 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3813 void Player::DurabilityLossAll(double percent, bool inventory)
3815 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3816 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3817 DurabilityLoss(pItem,percent);
3819 if(inventory)
3821 // bags not have durability
3822 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3824 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3825 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3826 DurabilityLoss(pItem,percent);
3828 // keys not have durability
3829 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3831 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3832 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3833 if(ItemPrototype const *pBagProto = pBag->GetProto())
3834 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
3835 if(Item* pItem = GetItemByPos( i, j ))
3836 DurabilityLoss(pItem,percent);
3840 void Player::DurabilityLoss(Item* item, double percent)
3842 if(!item )
3843 return;
3845 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3847 if(!pMaxDurability)
3848 return;
3850 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3852 if(pDurabilityLoss < 1 )
3853 pDurabilityLoss = 1;
3855 DurabilityPointsLoss(item,pDurabilityLoss);
3858 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3860 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3861 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3862 DurabilityPointsLoss(pItem,points);
3864 if(inventory)
3866 // bags not have durability
3867 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3869 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3870 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3871 DurabilityPointsLoss(pItem,points);
3873 // keys not have durability
3874 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3876 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3877 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3878 if(ItemPrototype const *pBagProto = pBag->GetProto())
3879 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
3880 if(Item* pItem = GetItemByPos( i, j ))
3881 DurabilityPointsLoss(pItem,points);
3885 void Player::DurabilityPointsLoss(Item* item, int32 points)
3887 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3888 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3889 int32 pNewDurability = pOldDurability - points;
3891 if (pNewDurability < 0)
3892 pNewDurability = 0;
3893 else if (pNewDurability > pMaxDurability)
3894 pNewDurability = pMaxDurability;
3896 if (pOldDurability != pNewDurability)
3898 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3899 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3900 _ApplyItemMods(item,item->GetSlot(), false);
3902 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3904 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3905 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3906 _ApplyItemMods(item,item->GetSlot(), true);
3908 item->SetState(ITEM_CHANGED, this);
3912 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3914 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3915 DurabilityPointsLoss(pItem,1);
3918 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3920 uint32 TotalCost = 0;
3921 // equipped, backpack, bags itself
3922 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3923 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3925 // bank, buyback and keys not repaired
3927 // items in inventory bags
3928 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3929 for(int i = 0; i < MAX_BAG_SIZE; i++)
3930 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3931 return TotalCost;
3934 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3936 Item* item = GetItemByPos(pos);
3938 uint32 TotalCost = 0;
3939 if(!item)
3940 return TotalCost;
3942 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3943 if(!maxDurability)
3944 return TotalCost;
3946 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3948 if(cost)
3950 uint32 LostDurability = maxDurability - curDurability;
3951 if(LostDurability>0)
3953 ItemPrototype const *ditemProto = sItemStorage.LookupEntry<ItemPrototype>(item->GetEntry());
3954 if(!ditemProto)
3956 sLog.outError("ERROR: RepairDurability: Unknown item id %u", ditemProto);
3957 return TotalCost;
3960 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
3961 if(!dcost)
3963 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", dcost);
3964 return TotalCost;
3967 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry((ditemProto->Quality+1)*2);
3968 if(!dQualitymodEntry)
3970 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntry);
3971 return TotalCost;
3974 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
3975 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
3977 costs = uint32(costs * discountMod);
3979 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
3980 costs = 1;
3982 if (guildBank)
3984 if (GetGuildId()==0)
3986 DEBUG_LOG("You are not member of a guild");
3987 return TotalCost;
3990 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
3991 if (!pGuild)
3992 return TotalCost;
3994 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
3996 DEBUG_LOG("You do not have rights to withdraw for repairs");
3997 return TotalCost;
4000 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4002 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4003 return TotalCost;
4006 if (pGuild->GetGuildBankMoney() < costs)
4008 DEBUG_LOG("There is not enough money in bank");
4009 return TotalCost;
4012 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4013 TotalCost = costs;
4015 else if (GetMoney() < costs)
4017 DEBUG_LOG("You do not have enough money");
4018 return TotalCost;
4020 else
4021 ModifyMoney( -int32(costs) );
4025 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4026 item->SetState(ITEM_CHANGED, this);
4028 // reapply mods for total broken and repaired item if equipped
4029 if(IsEquipmentPos(pos) && !curDurability)
4030 _ApplyItemMods(item,pos & 255, true);
4031 return TotalCost;
4034 void Player::RepopAtGraveyard()
4036 // note: this can be called also when the player is alive
4037 // for example from WorldSession::HandleMovementOpcodes
4039 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4041 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4042 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4044 ResurrectPlayer(0.5f);
4045 SpawnCorpseBones();
4048 WorldSafeLocsEntry const *ClosestGrave = NULL;
4050 // Special handle for battleground maps
4051 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4053 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4054 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4055 else
4056 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4058 // stop countdown until repop
4059 m_deathTimer = 0;
4061 // if no grave found, stay at the current location
4062 // and don't show spirit healer location
4063 if(ClosestGrave)
4065 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4066 if(isDead()) // not send if alive, because it used in TeleportTo()
4068 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4069 data << ClosestGrave->map_id;
4070 data << ClosestGrave->x;
4071 data << ClosestGrave->y;
4072 data << ClosestGrave->z;
4073 GetSession()->SendPacket(&data);
4078 void Player::JoinedChannel(Channel *c)
4080 m_channels.push_back(c);
4083 void Player::LeftChannel(Channel *c)
4085 m_channels.remove(c);
4088 void Player::CleanupChannels()
4090 while(!m_channels.empty())
4092 Channel* ch = *m_channels.begin();
4093 m_channels.erase(m_channels.begin()); // remove from player's channel list
4094 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4095 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4096 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4099 sLog.outDebug("Player: channels cleaned up!");
4102 void Player::UpdateLocalChannels(uint32 newZone )
4104 if(m_channels.empty())
4105 return;
4107 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4108 if(!current_zone)
4109 return;
4111 ChannelMgr* cMgr = channelMgr(GetTeam());
4112 if(!cMgr)
4113 return;
4115 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4117 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4119 next = i; ++next;
4121 // skip non built-in channels
4122 if(!(*i)->IsConstant())
4123 continue;
4125 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4126 if(!ch)
4127 continue;
4129 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4130 continue;
4132 // new channel
4133 char new_channel_name_buf[100];
4134 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4135 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4137 if((*i)!=new_channel)
4139 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4141 // leave old channel
4142 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4143 std::string name = (*i)->GetName(); // stroe name, (*i)erase in LeftChannel
4144 LeftChannel(*i); // remove from player's channel list
4145 cMgr->LeftChannel(name); // delete if empty
4148 sLog.outDebug("Player: channels cleaned up!");
4151 void Player::LeaveLFGChannel()
4153 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4155 if((*i)->IsLFG())
4157 (*i)->Leave(GetGUID());
4158 break;
4163 void Player::UpdateDefense()
4165 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4167 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4169 // update dependent from defense skill part
4170 UpdateDefenseBonusesMod();
4174 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats)
4176 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4178 sLog.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
4179 return;
4182 float val = 1.0f;
4184 switch(modType)
4186 case FLAT_MOD:
4187 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4188 break;
4189 case PCT_MOD:
4190 if(amount <= -100.0f)
4191 amount = -200.0f;
4193 val = (100.0f + amount) / 100.0f;
4194 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4195 break;
4198 if(!CanModifyStats())
4199 return;
4201 switch(modGroup)
4203 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4204 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4205 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4206 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4207 default: break;
4211 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4213 if(modGroup >= BASEMOD_END || modType > MOD_END)
4215 sLog.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
4216 return 0.0f;
4219 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4220 return 0.0f;
4222 return m_auraBaseMod[modGroup][modType];
4225 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4227 if(modGroup >= BASEMOD_END)
4229 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4230 return 0.0f;
4233 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4234 return 0.0f;
4236 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4239 uint32 Player::GetShieldBlockValue() const
4241 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4243 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4245 value = (value < 0) ? 0 : value;
4247 return uint32(value);
4250 float Player::GetMeleeCritFromAgility()
4252 uint32 level = getLevel();
4253 uint32 pclass = getClass();
4255 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4257 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4258 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4259 if (critBase==NULL || critRatio==NULL)
4260 return 0.0f;
4262 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4263 return crit*100.0f;
4266 float Player::GetDodgeFromAgility()
4268 // Table for base dodge values
4269 float dodge_base[MAX_CLASSES] = {
4270 0.0075f, // Warrior
4271 0.00652f, // Paladin
4272 -0.0545f, // Hunter
4273 -0.0059f, // Rogue
4274 0.03183f, // Priest
4275 0.0114f, // DK
4276 0.0167f, // Shaman
4277 0.034575f, // Mage
4278 0.02011f, // Warlock
4279 0.0f, // ??
4280 -0.0187f // Druid
4282 // Crit/agility to dodge/agility coefficient multipliers
4283 float crit_to_dodge[MAX_CLASSES] = {
4284 1.1f, // Warrior
4285 1.0f, // Paladin
4286 1.6f, // Hunter
4287 2.0f, // Rogue
4288 1.0f, // Priest
4289 1.0f, // DK?
4290 1.0f, // Shaman
4291 1.0f, // Mage
4292 1.0f, // Warlock
4293 0.0f, // ??
4294 1.7f // Druid
4297 uint32 level = getLevel();
4298 uint32 pclass = getClass();
4300 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4302 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4303 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4304 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4305 return 0.0f;
4307 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4308 return dodge*100.0f;
4311 float Player::GetSpellCritFromIntellect()
4313 uint32 level = getLevel();
4314 uint32 pclass = getClass();
4316 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4318 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4319 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4320 if (critBase==NULL || critRatio==NULL)
4321 return 0.0f;
4323 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4324 return crit*100.0f;
4327 float Player::GetRatingCoefficient(CombatRating cr) const
4329 uint32 level = getLevel();
4331 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4333 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4334 if (Rating == NULL)
4335 return 1.0f; // By default use minimum coefficient (not must be called)
4337 return Rating->ratio;
4340 float Player::GetRatingBonusValue(CombatRating cr) const
4342 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4345 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4347 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4348 if (melee>25.0f) melee = 25.0f;
4349 return uint32 (melee * damage /100.0f);
4352 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4354 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4355 if (ranged>25.0f) ranged=25.0f;
4356 return uint32 (ranged * damage /100.0f);
4359 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4361 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4362 // In wow script resilience limited to 25%
4363 if (spell>25.0f)
4364 spell = 25.0f;
4365 return uint32 (spell * damage / 100.0f);
4368 uint32 Player::GetDotDamageReduction(uint32 damage) const
4370 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4371 // Dot resilience not limited (limit it by 100%)
4372 if (spellDot > 100.0f)
4373 spellDot = 100.0f;
4374 return uint32 (spellDot * damage / 100.0f);
4377 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4379 switch (attType)
4381 case BASE_ATTACK:
4382 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4383 case OFF_ATTACK:
4384 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4385 default:
4386 break;
4388 return 0.0f;
4391 float Player::OCTRegenHPPerSpirit()
4393 uint32 level = getLevel();
4394 uint32 pclass = getClass();
4396 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4398 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4399 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4400 if (baseRatio==NULL || moreRatio==NULL)
4401 return 0.0f;
4403 // Formula from PaperDollFrame script
4404 float spirit = GetStat(STAT_SPIRIT);
4405 float baseSpirit = spirit;
4406 if (baseSpirit>50) baseSpirit = 50;
4407 float moreSpirit = spirit - baseSpirit;
4408 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4409 return regen;
4412 float Player::OCTRegenMPPerSpirit()
4414 uint32 level = getLevel();
4415 uint32 pclass = getClass();
4417 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4419 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4420 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4421 if (moreRatio==NULL)
4422 return 0.0f;
4424 // Formula get from PaperDollFrame script
4425 float spirit = GetStat(STAT_SPIRIT);
4426 float regen = spirit * moreRatio->ratio;
4427 return regen;
4430 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4432 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4434 float RatingCoeffecient = GetRatingCoefficient(cr);
4435 float RatingChange = 0.0f;
4437 bool affectStats = CanModifyStats();
4439 switch (cr)
4441 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4442 case CR_DEFENSE_SKILL:
4443 UpdateDefenseBonusesMod();
4444 break;
4445 case CR_DODGE:
4446 UpdateDodgePercentage();
4447 break;
4448 case CR_PARRY:
4449 UpdateParryPercentage();
4450 break;
4451 case CR_BLOCK:
4452 UpdateBlockPercentage();
4453 break;
4454 case CR_HIT_MELEE:
4455 RatingChange = value / RatingCoeffecient;
4456 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4457 break;
4458 case CR_HIT_RANGED:
4459 RatingChange = value / RatingCoeffecient;
4460 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4461 break;
4462 case CR_HIT_SPELL:
4463 RatingChange = value / RatingCoeffecient;
4464 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4465 break;
4466 case CR_CRIT_MELEE:
4467 if(affectStats)
4469 UpdateCritPercentage(BASE_ATTACK);
4470 UpdateCritPercentage(OFF_ATTACK);
4472 break;
4473 case CR_CRIT_RANGED:
4474 if(affectStats)
4475 UpdateCritPercentage(RANGED_ATTACK);
4476 break;
4477 case CR_CRIT_SPELL:
4478 if(affectStats)
4479 UpdateAllSpellCritChances();
4480 break;
4481 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4482 case CR_HIT_TAKEN_RANGED:
4483 break;
4484 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4485 break;
4486 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4487 case CR_CRIT_TAKEN_RANGED:
4488 break;
4489 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4490 break;
4491 case CR_HASTE_MELEE:
4492 RatingChange = value / RatingCoeffecient;
4493 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4494 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4495 break;
4496 case CR_HASTE_RANGED:
4497 RatingChange = value / RatingCoeffecient;
4498 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4499 break;
4500 case CR_HASTE_SPELL:
4501 RatingChange = value / RatingCoeffecient;
4502 ApplyCastTimePercentMod(RatingChange,apply);
4503 break;
4504 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4505 case CR_WEAPON_SKILL_OFFHAND:
4506 case CR_WEAPON_SKILL_RANGED:
4507 break;
4508 case CR_EXPERTISE:
4509 if(affectStats)
4511 UpdateExpertise(BASE_ATTACK);
4512 UpdateExpertise(OFF_ATTACK);
4514 break;
4518 void Player::SetRegularAttackTime()
4520 for(int i = 0; i < MAX_ATTACK; ++i)
4522 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4523 if(tmpitem && !tmpitem->IsBroken())
4525 ItemPrototype const *proto = tmpitem->GetProto();
4526 if(proto->Delay)
4527 SetAttackTime(WeaponAttackType(i), proto->Delay);
4528 else
4529 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4534 //skill+step, checking for max value
4535 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4537 if(!skill_id)
4538 return false;
4540 uint16 i=0;
4541 for (; i < PLAYER_MAX_SKILLS; i++)
4542 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4543 break;
4545 if(i>=PLAYER_MAX_SKILLS)
4546 return false;
4548 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4549 uint32 value = SKILL_VALUE(data);
4550 uint32 max = SKILL_MAX(data);
4552 if ((!max) || (!value) || (value >= max))
4553 return false;
4555 if (value*512 < max*urand(0,512))
4557 uint32 new_value = value+step;
4558 if(new_value > max)
4559 new_value = max;
4561 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4562 return true;
4565 return false;
4568 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4570 if ( SkillValue >= GrayLevel )
4571 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4572 if ( SkillValue >= GreenLevel )
4573 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4574 if ( SkillValue >= YellowLevel )
4575 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4576 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4579 bool Player::UpdateCraftSkill(uint32 spellid)
4581 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4583 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4584 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4586 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4588 if(_spell_idx->second->skillId)
4590 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4592 // Alchemy Discoveries here
4593 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4594 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4596 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4597 learnSpell(discoveredSpell);
4600 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4602 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4603 _spell_idx->second->max_value,
4604 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4605 _spell_idx->second->min_value),
4606 craft_skill_gain);
4609 return false;
4612 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4614 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4616 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4618 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4619 switch (SkillId)
4621 case SKILL_HERBALISM:
4622 case SKILL_LOCKPICKING:
4623 case SKILL_JEWELCRAFTING:
4624 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4625 case SKILL_SKINNING:
4626 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4627 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4628 else
4629 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4630 case SKILL_MINING:
4631 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4632 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4633 else
4634 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4636 return false;
4639 bool Player::UpdateFishingSkill()
4641 sLog.outDebug("UpdateFishingSkill");
4643 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4645 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4647 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4649 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4652 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4654 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4655 if ( !SkillId )
4656 return false;
4658 if(Chance <= 0) // speedup in 0 chance case
4660 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4661 return false;
4664 uint16 i=0;
4665 for (; i < PLAYER_MAX_SKILLS; i++)
4666 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4667 if ( i >= PLAYER_MAX_SKILLS )
4668 return false;
4670 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4671 uint16 SkillValue = SKILL_VALUE(data);
4672 uint16 MaxValue = SKILL_MAX(data);
4674 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4675 return false;
4677 int32 Roll = irand(1,1000);
4679 if ( Roll <= Chance )
4681 uint32 new_value = SkillValue+step;
4682 if(new_value > MaxValue)
4683 new_value = MaxValue;
4685 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4686 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4687 return true;
4690 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4691 return false;
4694 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4696 // no skill gain in pvp
4697 Unit *pVictim = getVictim();
4698 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4699 return;
4701 if(IsInFeralForm())
4702 return; // always maximized SKILL_FERAL_COMBAT in fact
4704 if(m_form == FORM_TREE)
4705 return; // use weapon but not skill up
4707 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4709 switch(attType)
4711 case BASE_ATTACK:
4713 Item *tmpitem = GetWeaponForAttack(attType,true);
4715 if (!tmpitem)
4716 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4717 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4718 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4719 break;
4721 case OFF_ATTACK:
4722 case RANGED_ATTACK:
4724 Item *tmpitem = GetWeaponForAttack(attType,true);
4725 if (tmpitem)
4726 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4727 break;
4730 UpdateAllCritPercentages();
4733 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4735 switch(outcome)
4737 case MELEE_HIT_CRIT:
4738 case MELEE_HIT_DODGE:
4739 case MELEE_HIT_PARRY:
4740 case MELEE_HIT_BLOCK:
4741 case MELEE_HIT_BLOCK_CRIT:
4742 return;
4744 default:
4745 break;
4748 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4749 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4750 uint32 moblevel = pVictim->getLevelForTarget(this);
4751 if(moblevel < greylevel)
4752 return;
4754 if (moblevel > plevel + 5)
4755 moblevel = plevel + 5;
4757 uint32 lvldif = moblevel - greylevel;
4758 if(lvldif < 3)
4759 lvldif = 3;
4761 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4762 if(skilldif <= 0)
4763 return;
4765 float chance = float(3 * lvldif * skilldif) / plevel;
4766 if(!defence)
4768 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4769 chance *= 0.1f * GetStat(STAT_INTELLECT);
4772 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4774 if(roll_chance_f(chance))
4776 if(defence)
4777 UpdateDefense();
4778 else
4779 UpdateWeaponSkill(attType);
4781 else
4782 return;
4785 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4787 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4788 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4790 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4791 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4792 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4794 if(talent) // permanent bonus stored in high part
4795 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4796 else // temporary/item bonus stored in low part
4797 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4798 return;
4802 void Player::UpdateMaxSkills()
4804 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4806 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4807 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4809 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4811 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4812 if(!pSkill)
4813 continue;
4815 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4816 continue;
4818 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4819 uint32 max = SKILL_MAX(data);
4820 uint32 val = SKILL_VALUE(data);
4822 // update only level dependent max skill values
4823 if(max!=1 && max != maxconfskill)
4825 uint32 max_Skill = GetMaxSkillValueForLevel();
4826 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
4831 void Player::UpdateSkillsToMaxSkillsForLevel()
4833 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4834 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4836 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4837 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4838 continue;
4839 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4841 uint32 max = SKILL_MAX(data);
4843 if(max > 1)
4844 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4846 if(pskill == SKILL_DEFENSE)
4847 UpdateDefenseBonusesMod();
4851 // This functions sets a skill line value (and adds if doesn't exist yet)
4852 // To "remove" a skill line, set it's values to zero
4853 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4855 if(!id)
4856 return;
4858 uint16 i=0;
4859 for (; i < PLAYER_MAX_SKILLS; i++)
4860 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4862 if(i<PLAYER_MAX_SKILLS) //has skill
4864 if(currVal)
4865 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4866 else //remove
4868 // clear skill fields
4869 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4870 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4871 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4873 // remove spells that depend on this skill when removing the skill
4874 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4876 ++next;
4877 if(itr->second->state == PLAYERSPELL_REMOVED)
4878 continue;
4880 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4881 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4883 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4885 if (_spell_idx->second->skillId == id)
4887 // this may remove more than one spell (dependants)
4888 removeSpell(itr->first);
4889 next = m_spells.begin();
4890 break;
4896 else if(currVal) //add
4898 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4899 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4901 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4902 if(!pSkill)
4904 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4905 return;
4907 // enable unlearn button for primary professions only
4908 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4909 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4910 else
4911 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4912 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4914 // apply skill bonuses
4915 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4917 // temporary bonuses
4918 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4919 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4920 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4921 (*i)->ApplyModifier(true);
4923 // permanent bonuses
4924 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4925 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4926 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4927 (*i)->ApplyModifier(true);
4929 // Learn all spells for skill
4930 learnSkillRewardedSpells(id);
4931 return;
4936 bool Player::HasSkill(uint32 skill) const
4938 if(!skill)return false;
4939 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4941 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4943 return true;
4946 return false;
4949 uint16 Player::GetSkillValue(uint32 skill) const
4951 if(!skill)
4952 return 0;
4954 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4956 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4958 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4960 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4961 result += SKILL_TEMP_BONUS(bonus);
4962 result += SKILL_PERM_BONUS(bonus);
4963 return result < 0 ? 0 : result;
4966 return 0;
4969 uint16 Player::GetMaxSkillValue(uint32 skill) const
4971 if(!skill)return 0;
4972 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4974 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4976 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4978 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4979 result += SKILL_TEMP_BONUS(bonus);
4980 result += SKILL_PERM_BONUS(bonus);
4981 return result < 0 ? 0 : result;
4984 return 0;
4987 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
4989 if(!skill)return 0;
4990 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4992 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4994 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
4997 return 0;
5000 uint16 Player::GetBaseSkillValue(uint32 skill) const
5002 if(!skill)return 0;
5003 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5005 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5007 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5008 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5009 return result < 0 ? 0 : result;
5012 return 0;
5015 uint16 Player::GetPureSkillValue(uint32 skill) const
5017 if(!skill)return 0;
5018 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5020 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5022 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5025 return 0;
5028 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5030 if(!skill)
5031 return 0;
5033 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5035 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5037 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5041 return 0;
5044 void Player::SendInitialActionButtons()
5046 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5048 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5049 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5051 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5052 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5054 data << uint16(itr->second.action);
5055 data << uint8(itr->second.misc);
5056 data << uint8(itr->second.type);
5058 else
5060 data << uint32(0);
5064 GetSession()->SendPacket( &data );
5065 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5068 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5070 if(button >= MAX_ACTION_BUTTONS)
5072 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5073 return;
5076 // check cheating with adding non-known spells to action bar
5077 if(type==ACTION_BUTTON_SPELL)
5079 if(!sSpellStore.LookupEntry(action))
5081 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5082 return;
5085 if(!HasSpell(action))
5087 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5088 return;
5092 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5094 if (buttonItr==m_actionButtons.end())
5095 { // just add new button
5096 m_actionButtons[button] = ActionButton(action,type,misc);
5098 else
5099 { // change state of current button
5100 ActionButtonUpdateState uState = buttonItr->second.uState;
5101 buttonItr->second = ActionButton(action,type,misc);
5102 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5105 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5108 void Player::removeActionButton(uint8 button)
5110 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5111 if (buttonItr==m_actionButtons.end())
5112 return;
5114 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5115 m_actionButtons.erase(buttonItr); // new and not saved
5116 else
5117 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5119 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5122 void Player::SetDontMove(bool dontMove)
5124 m_dontMove = dontMove;
5127 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5129 // prevent crash when a bad coord is sent by the client
5130 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5132 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5133 return false;
5136 Map *m = MapManager::Instance().GetMap(GetMapId(), this);
5138 const float old_x = GetPositionX();
5139 const float old_y = GetPositionY();
5140 const float old_z = GetPositionZ();
5141 const float old_r = GetOrientation();
5143 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5145 if (teleport || old_x != x || old_y != y || old_z != z)
5146 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5147 else
5148 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5150 // move and update visible state if need
5151 m->PlayerRelocation(this, x, y, z, orientation);
5153 // reread after Map::Relocation
5154 m = MapManager::Instance().GetMap(GetMapId(), this);
5155 x = GetPositionX();
5156 y = GetPositionY();
5157 z = GetPositionZ();
5160 // code block for underwater state update
5161 UpdateUnderwaterState(m, x, y, z);
5163 CheckExploreSystem();
5165 // group update
5166 if(GetGroup())
5167 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5169 return true;
5172 void Player::SaveRecallPosition()
5174 m_recallMap = GetMapId();
5175 m_recallX = GetPositionX();
5176 m_recallY = GetPositionY();
5177 m_recallZ = GetPositionZ();
5178 m_recallO = GetOrientation();
5181 void Player::SendMessageToSet(WorldPacket *data, bool self)
5183 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
5186 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5188 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self);
5191 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5193 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self,own_team_only);
5196 void Player::SendDirectMessage(WorldPacket *data)
5198 GetSession()->SendPacket(data);
5201 void Player::CheckExploreSystem()
5203 if (!isAlive())
5204 return;
5206 if (isInFlight())
5207 return;
5209 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5210 if(areaFlag==0xffff)
5211 return;
5212 int offset = areaFlag / 32;
5214 if(offset >= 128)
5216 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);
5217 return;
5220 uint32 val = (uint32)(1 << (areaFlag % 32));
5221 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5223 if( !(currFields & val) )
5225 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5227 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5228 if(!p)
5230 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5232 else if(p->area_level > 0)
5234 uint32 area = p->ID;
5235 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5237 SendExplorationExperience(area,0);
5239 else
5241 int32 diff = int32(getLevel()) - p->area_level;
5242 uint32 XP = 0;
5243 if (diff < -5)
5245 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5247 else if (diff > 5)
5249 int32 exploration_percent = (100-((diff-5)*5));
5250 if (exploration_percent > 100)
5251 exploration_percent = 100;
5252 else if (exploration_percent < 0)
5253 exploration_percent = 0;
5255 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5257 else
5259 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5262 GiveXP( XP, NULL );
5263 SendExplorationExperience(area,XP);
5265 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5270 uint32 Player::TeamForRace(uint8 race)
5272 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5273 if(!rEntry)
5275 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5276 return ALLIANCE;
5279 switch(rEntry->TeamID)
5281 case 7: return ALLIANCE;
5282 case 1: return HORDE;
5285 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5286 return ALLIANCE;
5289 uint32 Player::getFactionForRace(uint8 race)
5291 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5292 if(!rEntry)
5294 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5295 return 0;
5298 return rEntry->FactionID;
5301 void Player::setFactionForRace(uint8 race)
5303 m_team = TeamForRace(race);
5304 setFaction( getFactionForRace(race) );
5307 void Player::UpdateReputation() const
5309 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5311 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5313 SendFactionState(&(itr->second));
5317 void Player::SendFactionState(FactionState const* faction) const
5319 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5321 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5322 data << (float) 0; // unk 2.4.0
5323 data << (uint32) 1; // count
5324 // for
5325 data << (uint32) faction->ReputationListID;
5326 data << (uint32) faction->Standing;
5327 // end for
5328 GetSession()->SendPacket(&data);
5332 void Player::SendInitialReputations()
5334 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5335 data << uint32 (0x00000080);
5337 RepListID a = 0;
5339 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5341 // fill in absent fields
5342 for (; a != itr->first; a++)
5344 data << uint8 (0x00);
5345 data << uint32 (0x00000000);
5348 // fill in encountered data
5349 data << uint8 (itr->second.Flags);
5350 data << uint32 (itr->second.Standing);
5352 ++a;
5355 // fill in absent fields
5356 for (; a != 128; a++)
5358 data << uint8 (0x00);
5359 data << uint32 (0x00000000);
5362 GetSession()->SendPacket(&data);
5365 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5367 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5368 if (itr != m_factions.end())
5369 return &itr->second;
5371 return NULL;
5374 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5376 // not allow declare war to own faction
5377 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5378 return;
5380 // already set
5381 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5382 return;
5384 if( atWar )
5385 faction->Flags |= FACTION_FLAG_AT_WAR;
5386 else
5387 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5389 faction->Changed = true;
5392 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5394 // always invisible or hidden faction can't be inactive
5395 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5396 return;
5398 // already set
5399 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5400 return;
5402 if(inactive)
5403 faction->Flags |= FACTION_FLAG_INACTIVE;
5404 else
5405 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5407 faction->Changed = true;
5410 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5412 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5414 if(!factionTemplateEntry)
5415 return;
5417 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5420 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5422 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5423 if(!factionEntry)
5424 return;
5426 if(factionEntry->reputationListID < 0)
5427 return;
5429 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5430 if (itr == m_factions.end())
5431 return;
5433 SetFactionVisible(&itr->second);
5436 void Player::SetFactionVisible(FactionState* faction)
5438 // always invisible or hidden faction can't be make visible
5439 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5440 return;
5442 // already set
5443 if(faction->Flags & FACTION_FLAG_VISIBLE)
5444 return;
5446 faction->Flags |= FACTION_FLAG_VISIBLE;
5447 faction->Changed = true;
5449 if(!m_session->PlayerLoading())
5451 // make faction visible in reputation list at client
5452 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5453 data << faction->ReputationListID;
5454 GetSession()->SendPacket(&data);
5458 void Player::SetInitialFactions()
5460 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5462 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5464 if( factionEntry && (factionEntry->reputationListID >= 0))
5466 FactionState newFaction;
5467 newFaction.ID = factionEntry->ID;
5468 newFaction.ReputationListID = factionEntry->reputationListID;
5469 newFaction.Standing = 0;
5470 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5471 newFaction.Changed = true;
5473 m_factions[newFaction.ReputationListID] = newFaction;
5478 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5480 if (!factionEntry)
5481 return 0;
5483 uint32 raceMask = getRaceMask();
5484 uint32 classMask = getClassMask();
5485 for (int i=0; i < 4; i++)
5487 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5488 (factionEntry->BaseRepClassMask[i]==0 ||
5489 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5490 return factionEntry->ReputationFlags[i];
5492 return 0;
5495 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5497 if (!factionEntry)
5498 return 0;
5500 uint32 raceMask = getRaceMask();
5501 uint32 classMask = getClassMask();
5502 for (int i=0; i < 4; i++)
5504 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5505 (factionEntry->BaseRepClassMask[i]==0 ||
5506 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5507 return factionEntry->BaseRepValue[i];
5510 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5511 return 0;
5514 int32 Player::GetReputation(uint32 faction_id) const
5516 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5518 if (!factionEntry)
5520 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5521 return 0;
5524 return GetReputation(factionEntry);
5527 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5529 // Faction without recorded reputation. Just ignore.
5530 if(!factionEntry)
5531 return 0;
5533 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5534 if (itr != m_factions.end())
5535 return GetBaseReputation(factionEntry) + itr->second.Standing;
5537 return 0;
5540 ReputationRank Player::GetReputationRank(uint32 faction) const
5542 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5543 if(!factionEntry)
5544 return MIN_REPUTATION_RANK;
5546 return GetReputationRank(factionEntry);
5549 ReputationRank Player::ReputationToRank(int32 standing) const
5551 int32 Limit = Reputation_Cap + 1;
5552 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5554 Limit -= ReputationRank_Length[i];
5555 if (standing >= Limit )
5556 return ReputationRank(i);
5558 return MIN_REPUTATION_RANK;
5561 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5563 int32 Reputation = GetReputation(factionEntry);
5564 return ReputationToRank(Reputation);
5567 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5569 int32 Reputation = GetBaseReputation(factionEntry);
5570 return ReputationToRank(Reputation);
5573 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5575 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5577 if(!factionTemplateEntry)
5579 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5580 return false;
5583 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5585 // Faction without recorded reputation. Just ignore.
5586 if(!factionEntry)
5587 return false;
5589 return ModifyFactionReputation(factionEntry, DeltaReputation);
5592 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5594 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5595 if (flist)
5597 bool res = false;
5598 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5600 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5601 if(factionEntryCalc)
5602 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5604 return res;
5606 else
5607 return ModifyOneFactionReputation(factionEntry, standing);
5610 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5612 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5613 if (itr != m_factions.end())
5615 int32 BaseRep = GetBaseReputation(factionEntry);
5616 int32 new_rep = BaseRep + itr->second.Standing + standing;
5618 if (new_rep > Reputation_Cap)
5619 new_rep = Reputation_Cap;
5620 else
5621 if (new_rep < Reputation_Bottom)
5622 new_rep = Reputation_Bottom;
5624 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5625 SetFactionAtWar(&itr->second,true);
5627 itr->second.Standing = new_rep - BaseRep;
5628 itr->second.Changed = true;
5630 SetFactionVisible(&itr->second);
5632 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5634 if(uint32 questid = GetQuestSlotQuestId(i))
5636 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5637 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5639 QuestStatusData& q_status = mQuestStatus[questid];
5640 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5642 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5643 if ( CanCompleteQuest( questid ) )
5644 CompleteQuest( questid );
5646 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5648 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5649 IncompleteQuest( questid );
5655 SendFactionState(&(itr->second));
5657 return true;
5659 return false;
5662 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5664 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5666 if(!factionTemplateEntry)
5668 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5669 return false;
5672 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5674 // Faction without recorded reputation. Just ignore.
5675 if(!factionEntry)
5676 return false;
5678 return SetFactionReputation(factionEntry, standing);
5681 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5683 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5684 if (flist)
5686 bool res = false;
5687 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5689 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5690 if(factionEntryCalc)
5691 res = SetOneFactionReputation(factionEntryCalc, standing);
5693 return res;
5695 else
5696 return SetOneFactionReputation(factionEntry, standing);
5699 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5701 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5702 if (itr != m_factions.end())
5704 if (standing > Reputation_Cap)
5705 standing = Reputation_Cap;
5706 else
5707 if (standing < Reputation_Bottom)
5708 standing = Reputation_Bottom;
5710 int32 BaseRep = GetBaseReputation(factionEntry);
5711 itr->second.Standing = standing - BaseRep;
5712 itr->second.Changed = true;
5714 SetFactionVisible(&itr->second);
5716 if(ReputationToRank(standing) <= REP_HOSTILE)
5717 SetFactionAtWar(&itr->second,true);
5719 SendFactionState(&(itr->second));
5720 return true;
5722 return false;
5725 //Calculate total reputation percent player gain with quest/creature level
5726 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5728 // for grey creature kill received 20%, in other case 100.
5729 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5731 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5733 percent += rep > 0 ? repMod : -repMod;
5735 if(percent <=0)
5736 return 0;
5738 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5741 //Calculates how many reputation points player gains in victim's enemy factions
5742 void Player::RewardReputation(Unit *pVictim, float rate)
5744 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5745 return;
5747 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5749 if(!Rep)
5750 return;
5752 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5754 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5755 donerep1 = int32(donerep1*rate);
5756 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5757 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5758 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5759 ModifyFactionReputation(factionEntry1, donerep1);
5761 // Wiki: Team factions value divided by 2
5762 if(Rep->is_teamaward1)
5764 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5765 if(team1_factionEntry)
5766 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5770 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5772 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5773 donerep2 = int32(donerep2*rate);
5774 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5775 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5776 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5777 ModifyFactionReputation(factionEntry2, donerep2);
5779 // Wiki: Team factions value divided by 2
5780 if(Rep->is_teamaward2)
5782 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5783 if(team2_factionEntry)
5784 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5789 //Calculate how many reputation points player gain with the quest
5790 void Player::RewardReputation(Quest const *pQuest)
5792 // quest reputation reward/loss
5793 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5795 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5797 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5798 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5799 if(factionEntry)
5800 ModifyFactionReputation(factionEntry, rep);
5804 // TODO: implement reputation spillover
5807 void Player::UpdateArenaFields(void)
5809 /* arena calcs go here */
5812 void Player::UpdateHonorFields()
5814 /// called when rewarding honor and at each save
5815 uint64 now = time(NULL);
5816 uint64 today = uint64(time(NULL) / DAY) * DAY;
5818 if(m_lastHonorUpdateTime < today)
5820 uint64 yesterday = today - DAY;
5822 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5824 // update yesterday's contribution
5825 if(m_lastHonorUpdateTime >= yesterday )
5827 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5829 // this is the first update today, reset today's contribution
5830 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5831 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5833 else
5835 // no honor/kills yesterday or today, reset
5836 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5837 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5841 m_lastHonorUpdateTime = now;
5844 ///Calculate the amount of honor gained based on the victim
5845 ///and the size of the group for which the honor is divided
5846 ///An exact honor value can also be given (overriding the calcs)
5847 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5849 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5850 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5851 return false;
5853 uint64 victim_guid = 0;
5854 uint32 victim_rank = 0;
5855 time_t now = time(NULL);
5857 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5858 UpdateHonorFields();
5860 if(honor <= 0)
5862 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5863 return false;
5865 victim_guid = uVictim->GetGUID();
5867 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5869 Player *pVictim = (Player *)uVictim;
5871 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5872 return false;
5874 float f = 1; //need for total kills (?? need more info)
5875 uint32 k_grey = 0;
5876 uint32 k_level = getLevel();
5877 uint32 v_level = pVictim->getLevel();
5880 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5881 // [0] Just name
5882 // [1..14] Alliance honor titles and player name
5883 // [15..28] Horde honor titles and player name
5884 // [29..38] Other title and player name
5885 // [39+] Nothing
5886 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5887 // Get Killer titles, CharTitlesEntry::bit_index
5888 // Ranks:
5889 // title[1..14] -> rank[5..18]
5890 // title[15..28] -> rank[5..18]
5891 // title[other] -> 0
5892 if (victim_title == 0)
5893 victim_guid = 0; // Don't show HK: <rank> message, only log.
5894 else if (victim_title < 15)
5895 victim_rank = victim_title + 4;
5896 else if (victim_title < 29)
5897 victim_rank = victim_title - 14 + 4;
5898 else
5899 victim_guid = 0; // Don't show HK: <rank> message, only log.
5902 if(k_level <= 5)
5903 k_grey = 0;
5904 else if( k_level <= 39 )
5905 k_grey = k_level - 5 - k_level/10;
5906 else
5907 k_grey = k_level - 1 - k_level/5;
5909 if(v_level<=k_grey)
5910 return false;
5912 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5914 int32 v_rank =1; //need more info
5916 honor = ((f * diff_level * (190 + v_rank*10))/6);
5917 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5919 // count the number of playerkills in one day
5920 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5921 // and those in a lifetime
5922 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5924 else
5926 Creature *cVictim = (Creature *)uVictim;
5928 if (!cVictim->isRacialLeader())
5929 return false;
5931 honor = 100; // ??? need more info
5932 victim_rank = 19; // HK: Leader
5936 if (uVictim != NULL)
5938 honor *= sWorld.getRate(RATE_HONOR);
5940 if(groupsize > 1)
5941 honor /= groupsize;
5943 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5946 // honor - for show honor points in log
5947 // victim_guid - for show victim name in log
5948 // victim_rank [1..4] HK: <dishonored rank>
5949 // victim_rank [5..19] HK: <alliance\horde rank>
5950 // victim_rank [0,20+] HK: <>
5951 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5952 data << (uint32) honor;
5953 data << (uint64) victim_guid;
5954 data << (uint32) victim_rank;
5956 GetSession()->SendPacket(&data);
5958 // add honor points
5959 ModifyHonorPoints(int32(honor));
5961 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5962 return true;
5965 void Player::ModifyHonorPoints( int32 value )
5967 if(value < 0)
5969 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5970 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5971 else
5972 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5974 else
5975 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5978 void Player::ModifyArenaPoints( int32 value )
5980 if(value < 0)
5982 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5983 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5984 else
5985 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5987 else
5988 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5991 uint32 Player::GetGuildIdFromDB(uint64 guid)
5993 std::ostringstream ss;
5994 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
5995 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
5996 if( result )
5998 uint32 v = result->Fetch()[0].GetUInt32();
5999 delete result;
6000 return v;
6002 else
6003 return 0;
6006 uint32 Player::GetRankFromDB(uint64 guid)
6008 std::ostringstream ss;
6009 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6010 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6011 if( result )
6013 uint32 v = result->Fetch()[0].GetUInt32();
6014 delete result;
6015 return v;
6017 else
6018 return 0;
6021 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6023 // need fix it!
6024 QueryResult *result = CharacterDatabase.PQuery("SELECT arenateamid FROM arena_team_member WHERE guid='%u'", GUID_LOPART(guid));
6025 if(result)
6027 // init id to 0, check the arena type before assigning a value to id
6028 uint32 id = 0;
6031 QueryResult *result2 = CharacterDatabase.PQuery("SELECT type FROM arena_team WHERE arenateamid='%u'", id);
6032 if(result2)
6034 uint8 dbtype = (*result2)[0].GetUInt32();
6035 delete result2;
6036 if(dbtype == type)
6038 // if the type matches, we've found the id
6039 id = (*result)[0].GetUInt32();
6040 break;
6043 } while(result->NextRow());
6044 delete result;
6045 return id;
6047 // no arenateam for the specified guid, return 0
6048 return 0;
6051 uint32 Player::GetZoneIdFromDB(uint64 guid)
6053 std::ostringstream ss;
6055 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6056 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6057 if (!result)
6058 return 0;
6059 Field* fields = result->Fetch();
6060 uint32 zone = fields[0].GetUInt32();
6061 delete result;
6063 if (!zone)
6065 // stored zone is zero, use generic and slow zone detection
6066 ss.str("");
6067 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6068 result = CharacterDatabase.Query(ss.str().c_str());
6069 if( !result )
6070 return 0;
6071 fields = result->Fetch();
6072 uint32 map = fields[0].GetUInt32();
6073 float posx = fields[1].GetFloat();
6074 float posy = fields[2].GetFloat();
6075 delete result;
6077 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6079 ss.str("");
6080 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6081 CharacterDatabase.Execute(ss.str().c_str());
6084 return zone;
6087 void Player::UpdateArea(uint32 newArea)
6089 // FFA_PVP flags are area and not zone id dependent
6090 // so apply them accordingly
6091 m_areaUpdateId = newArea;
6093 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6095 if(area && (area->flags & AREA_FLAG_ARENA))
6097 if(!isGameMaster())
6098 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6100 else
6102 // remove ffa flag only if not ffapvp realm
6103 // removal in sanctuaries and capitals is handled in zone update
6104 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6105 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6108 UpdateAreaDependentAuras(newArea);
6111 void Player::UpdateZone(uint32 newZone)
6113 m_zoneUpdateId = newZone;
6114 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6116 // zone changed, so area changed as well, update it
6117 UpdateArea(GetAreaId());
6119 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6120 if(!zone)
6121 return;
6123 if (sWorld.getConfig(CONFIG_WEATHER))
6125 Weather *wth = sWorld.FindWeather(zone->ID);
6126 if(wth)
6128 wth->SendWeatherUpdateToPlayer(this);
6130 else
6132 if(!sWorld.AddWeather(zone->ID))
6134 // send fine weather packet to remove old zone's weather
6135 Weather::SendFineWeatherUpdateToPlayer(this);
6140 pvpInfo.inHostileArea =
6141 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6142 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6143 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6144 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6146 if(pvpInfo.inHostileArea) // in hostile area
6148 if(!IsPvP() || pvpInfo.endTimer != 0)
6149 UpdatePvP(true, true);
6151 else // in friendly area
6153 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6154 pvpInfo.endTimer = time(0); // start toggle-off
6157 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6159 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6160 if(sWorld.IsFFAPvPRealm())
6161 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6163 else
6165 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6168 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6170 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6171 SetRestType(REST_TYPE_IN_CITY);
6172 InnEnter(time(0),GetMapId(),0,0,0);
6174 if(sWorld.IsFFAPvPRealm())
6175 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6177 else // anywhere else
6179 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6181 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6183 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6185 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6186 SetRestType(REST_TYPE_NO);
6188 if(sWorld.IsFFAPvPRealm())
6189 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6192 else // not in tavern (leave city then)
6194 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6195 SetRestType(REST_TYPE_NO);
6197 // Set player to FFA PVP when not in rested enviroment.
6198 if(sWorld.IsFFAPvPRealm())
6199 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6204 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6205 // if player resurrected at teleport this will be applied in resurrect code
6206 if(isAlive())
6207 DestroyZoneLimitedItem( true, newZone );
6209 // recent client version not send leave/join channel packets for built-in local channels
6210 UpdateLocalChannels( newZone );
6212 // group update
6213 if(GetGroup())
6214 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6216 UpdateZoneDependentAuras(newZone);
6219 //If players are too far way of duel flag... then player loose the duel
6220 void Player::CheckDuelDistance(time_t currTime)
6222 if(!duel)
6223 return;
6225 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6226 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6227 if(!obj)
6228 return;
6230 if(duel->outOfBound == 0)
6232 if(!IsWithinDistInMap(obj, 50))
6234 duel->outOfBound = currTime;
6236 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6237 GetSession()->SendPacket(&data);
6240 else
6242 if(IsWithinDistInMap(obj, 40))
6244 duel->outOfBound = 0;
6246 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6247 GetSession()->SendPacket(&data);
6249 else if(currTime >= (duel->outOfBound+10))
6251 DuelComplete(DUEL_FLED);
6256 void Player::DuelComplete(DuelCompleteType type)
6258 // duel not requested
6259 if(!duel)
6260 return;
6262 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6263 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6264 GetSession()->SendPacket(&data);
6265 duel->opponent->GetSession()->SendPacket(&data);
6267 if(type != DUEL_INTERUPTED)
6269 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6270 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6271 data << duel->opponent->GetName();
6272 data << GetName();
6273 SendMessageToSet(&data,true);
6276 // cool-down duel spell
6277 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6279 data<<GetGUID();
6280 data<<uint8(0x0);
6282 data<<(uint32)7266;
6283 data<<uint32(0x0);
6284 GetSession()->SendPacket(&data);
6285 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6286 data<<duel->opponent->GetGUID();
6287 data<<uint8(0x0);
6288 data<<(uint32)7266;
6289 data<<uint32(0x0);
6290 duel->opponent->GetSession()->SendPacket(&data);*/
6292 //Remove Duel Flag object
6293 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6294 if(obj)
6295 duel->initiator->RemoveGameObject(obj,true);
6297 /* remove auras */
6298 std::vector<uint32> auras2remove;
6299 AuraMap const& vAuras = duel->opponent->GetAuras();
6300 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6302 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6303 auras2remove.push_back(i->second->GetId());
6306 for(size_t i=0; i<auras2remove.size(); i++)
6307 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6309 auras2remove.clear();
6310 AuraMap const& auras = GetAuras();
6311 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6313 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6314 auras2remove.push_back(i->second->GetId());
6316 for(size_t i=0; i<auras2remove.size(); i++)
6317 RemoveAurasDueToSpell(auras2remove[i]);
6319 // cleanup combo points
6320 if(GetComboTarget()==duel->opponent->GetGUID())
6321 ClearComboPoints();
6322 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6323 ClearComboPoints();
6325 if(duel->opponent->GetComboTarget()==GetGUID())
6326 duel->opponent->ClearComboPoints();
6327 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6328 duel->opponent->ClearComboPoints();
6330 //cleanups
6331 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6332 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6333 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6334 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6336 delete duel->opponent->duel;
6337 duel->opponent->duel = NULL;
6338 delete duel;
6339 duel = NULL;
6342 //---------------------------------------------------------//
6344 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6346 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6347 return;
6349 // not apply/remove mods for broken item
6350 if(item->IsBroken())
6351 return;
6353 ItemPrototype const *proto = item->GetProto();
6355 if(!proto)
6356 return;
6358 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6360 uint32 attacktype = Player::GetAttackBySlot(slot);
6361 if(attacktype < MAX_ATTACK)
6362 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6364 _ApplyItemBonuses(proto,slot,apply);
6366 if( slot==EQUIPMENT_SLOT_RANGED )
6367 _ApplyAmmoBonuses();
6369 ApplyItemEquipSpell(item,apply);
6370 ApplyEnchantment(item, apply);
6372 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6373 CorrectMetaGemEnchants(slot, apply);
6375 sLog.outDebug("_ApplyItemMods complete.");
6378 void Player::_ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply)
6380 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6381 return;
6383 for (int i = 0; i < 10; i++)
6385 float val = float (proto->ItemStat[i].ItemStatValue);
6387 if(val==0)
6388 continue;
6390 switch (proto->ItemStat[i].ItemStatType)
6392 case ITEM_MOD_MANA:
6393 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6394 break;
6395 case ITEM_MOD_HEALTH: // modify HP
6396 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6397 break;
6398 case ITEM_MOD_AGILITY: // modify agility
6399 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6400 ApplyStatBuffMod(STAT_AGILITY, val, apply);
6401 break;
6402 case ITEM_MOD_STRENGTH: //modify strength
6403 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6404 ApplyStatBuffMod(STAT_STRENGTH, val, apply);
6405 break;
6406 case ITEM_MOD_INTELLECT: //modify intellect
6407 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6408 ApplyStatBuffMod(STAT_INTELLECT, val, apply);
6409 break;
6410 case ITEM_MOD_SPIRIT: //modify spirit
6411 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6412 ApplyStatBuffMod(STAT_SPIRIT, val, apply);
6413 break;
6414 case ITEM_MOD_STAMINA: //modify stamina
6415 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6416 ApplyStatBuffMod(STAT_STAMINA, val, apply);
6417 break;
6418 case ITEM_MOD_DEFENSE_SKILL_RATING:
6419 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6420 break;
6421 case ITEM_MOD_DODGE_RATING:
6422 ApplyRatingMod(CR_DODGE, int32(val), apply);
6423 break;
6424 case ITEM_MOD_PARRY_RATING:
6425 ApplyRatingMod(CR_PARRY, int32(val), apply);
6426 break;
6427 case ITEM_MOD_BLOCK_RATING:
6428 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6429 break;
6430 case ITEM_MOD_HIT_MELEE_RATING:
6431 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6432 break;
6433 case ITEM_MOD_HIT_RANGED_RATING:
6434 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6435 break;
6436 case ITEM_MOD_HIT_SPELL_RATING:
6437 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6438 break;
6439 case ITEM_MOD_CRIT_MELEE_RATING:
6440 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6441 break;
6442 case ITEM_MOD_CRIT_RANGED_RATING:
6443 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6444 break;
6445 case ITEM_MOD_CRIT_SPELL_RATING:
6446 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6447 break;
6448 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6449 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6450 break;
6451 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6452 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6453 break;
6454 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6455 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6456 break;
6457 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6458 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6459 break;
6460 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6461 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6462 break;
6463 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6464 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6465 break;
6466 case ITEM_MOD_HASTE_MELEE_RATING:
6467 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6468 break;
6469 case ITEM_MOD_HASTE_RANGED_RATING:
6470 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6471 break;
6472 case ITEM_MOD_HASTE_SPELL_RATING:
6473 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6474 break;
6475 case ITEM_MOD_HIT_RATING:
6476 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6477 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6478 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6479 break;
6480 case ITEM_MOD_CRIT_RATING:
6481 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6482 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6483 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6484 break;
6485 case ITEM_MOD_HIT_TAKEN_RATING:
6486 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6487 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6488 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6489 break;
6490 case ITEM_MOD_CRIT_TAKEN_RATING:
6491 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6492 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6493 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6494 break;
6495 case ITEM_MOD_RESILIENCE_RATING:
6496 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6497 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6498 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6499 break;
6500 case ITEM_MOD_HASTE_RATING:
6501 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6502 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6503 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6504 break;
6505 case ITEM_MOD_EXPERTISE_RATING:
6506 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6507 break;
6511 if (proto->Armor)
6512 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6514 if (proto->Block)
6515 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6517 if (proto->HolyRes)
6518 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6520 if (proto->FireRes)
6521 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6523 if (proto->NatureRes)
6524 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6526 if (proto->FrostRes)
6527 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6529 if (proto->ShadowRes)
6530 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6532 if (proto->ArcaneRes)
6533 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6535 WeaponAttackType attType = BASE_ATTACK;
6536 float damage = 0.0f;
6538 if( slot == EQUIPMENT_SLOT_RANGED && (
6539 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6540 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6542 attType = RANGED_ATTACK;
6544 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6546 attType = OFF_ATTACK;
6549 if (proto->Damage[0].DamageMin > 0 )
6551 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6552 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6553 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6556 if (proto->Damage[0].DamageMax > 0 )
6558 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6559 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6562 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6563 return;
6565 if (proto->Delay)
6567 if(slot == EQUIPMENT_SLOT_RANGED)
6568 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6569 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6570 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6571 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6572 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6575 if(CanModifyStats() && (damage || proto->Delay))
6576 UpdateDamagePhysical(attType);
6579 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6581 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6582 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6583 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6585 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6586 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6587 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6589 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6590 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6591 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6594 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6596 // generic not weapon specific case processes in aura code
6597 if(aura->GetSpellProto()->EquippedItemClass == -1)
6598 return;
6600 BaseModGroup mod = BASEMOD_END;
6601 switch(attackType)
6603 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6604 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6605 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6606 default: return;
6609 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6611 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6615 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6617 // ignore spell mods for not wands
6618 Modifier const* modifier = aura->GetModifier();
6619 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6620 return;
6622 // generic not weapon specific case processes in aura code
6623 if(aura->GetSpellProto()->EquippedItemClass == -1)
6624 return;
6626 UnitMods unitMod = UNIT_MOD_END;
6627 switch(attackType)
6629 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6630 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6631 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6632 default: return;
6635 UnitModifierType unitModType = TOTAL_VALUE;
6636 switch(modifier->m_auraname)
6638 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6639 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6640 default: return;
6643 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6645 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6649 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6651 if(!item)
6652 return;
6654 ItemPrototype const *proto = item->GetProto();
6655 if(!proto)
6656 return;
6658 for (int i = 0; i < 5; i++)
6660 _Spell const& spellData = proto->Spells[i];
6662 // no spell
6663 if(!spellData.SpellId )
6664 continue;
6666 // wrong triggering type
6667 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6668 continue;
6670 // check if it is valid spell
6671 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6672 if(!spellproto)
6673 continue;
6675 ApplyEquipSpell(spellproto,item,apply,form_change);
6679 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6681 if(apply)
6683 // Cannot be used in this stance/form
6684 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6685 return;
6687 if(form_change) // check aura active state from other form
6689 bool found = false;
6690 for (int k=0; k < 3; ++k)
6692 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6693 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6695 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6697 found = true;
6698 break;
6701 if(found)
6702 break;
6705 if(found) // and skip re-cast already active aura at form change
6706 return;
6709 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6711 CastSpell(this,spellInfo,true,item);
6713 else
6715 if(form_change) // check aura compatibility
6717 // Cannot be used in this stance/form
6718 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6719 return; // and remove only not compatible at form change
6722 if(item)
6723 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6724 else
6725 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6729 void Player::UpdateEquipSpellsAtFormChange()
6731 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6733 if(m_items[i] && !m_items[i]->IsBroken())
6735 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6736 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6740 // item set bonuses not dependent from item broken state
6741 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6743 ItemSetEffect* eff = ItemSetEff[setindex];
6744 if(!eff)
6745 continue;
6747 for(uint32 y=0;y<8; ++y)
6749 SpellEntry const* spellInfo = eff->spells[y];
6750 if(!spellInfo)
6751 continue;
6753 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6754 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6759 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6761 if(!item || item->IsBroken())
6762 return;
6764 ItemPrototype const *proto = item->GetProto();
6765 if(!proto)
6766 return;
6768 if (!Target || Target == this )
6769 return;
6771 for (int i = 0; i < 5; i++)
6773 _Spell const& spellData = proto->Spells[i];
6775 // no spell
6776 if(!spellData.SpellId )
6777 continue;
6779 // wrong triggering type
6780 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6781 continue;
6783 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6784 if(!spellInfo)
6786 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6787 continue;
6790 // not allow proc extra attack spell at extra attack
6791 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6792 return;
6794 float chance = spellInfo->procChance;
6796 if(spellData.SpellPPMRate)
6798 uint32 WeaponSpeed = GetAttackTime(attType);
6799 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6801 else if(chance > 100.0f)
6803 chance = GetWeaponProcChance();
6806 if (roll_chance_f(chance))
6807 this->CastSpell(Target, spellInfo->Id, true, item);
6810 // item combat enchantments
6811 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6813 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6814 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6815 if(!pEnchant) continue;
6816 for (int s=0;s<3;s++)
6818 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6819 continue;
6821 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6822 if (!spellInfo)
6824 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6825 continue;
6828 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6829 if (roll_chance_f(chance))
6831 if(IsPositiveSpell(pEnchant->spellid[s]))
6832 CastSpell(this, pEnchant->spellid[s], true, item);
6833 else
6834 CastSpell(Target, pEnchant->spellid[s], true, item);
6840 void Player::_RemoveAllItemMods()
6842 sLog.outDebug("_RemoveAllItemMods start.");
6844 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6846 if(m_items[i])
6848 ItemPrototype const *proto = m_items[i]->GetProto();
6849 if(!proto)
6850 continue;
6852 // item set bonuses not dependent from item broken state
6853 if(proto->ItemSet)
6854 RemoveItemsSetItem(this,proto);
6856 if(m_items[i]->IsBroken())
6857 continue;
6859 ApplyItemEquipSpell(m_items[i],false);
6860 ApplyEnchantment(m_items[i], false);
6864 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6866 if(m_items[i])
6868 if(m_items[i]->IsBroken())
6869 continue;
6870 ItemPrototype const *proto = m_items[i]->GetProto();
6871 if(!proto)
6872 continue;
6874 uint32 attacktype = Player::GetAttackBySlot(i);
6875 if(attacktype < MAX_ATTACK)
6876 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6878 _ApplyItemBonuses(proto,i, false);
6880 if( i == EQUIPMENT_SLOT_RANGED )
6881 _ApplyAmmoBonuses();
6885 sLog.outDebug("_RemoveAllItemMods complete.");
6888 void Player::_ApplyAllItemMods()
6890 sLog.outDebug("_ApplyAllItemMods start.");
6892 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6894 if(m_items[i])
6896 if(m_items[i]->IsBroken())
6897 continue;
6899 ItemPrototype const *proto = m_items[i]->GetProto();
6900 if(!proto)
6901 continue;
6903 uint32 attacktype = Player::GetAttackBySlot(i);
6904 if(attacktype < MAX_ATTACK)
6905 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6907 _ApplyItemBonuses(proto,i, true);
6909 if( i == EQUIPMENT_SLOT_RANGED )
6910 _ApplyAmmoBonuses();
6914 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6916 if(m_items[i])
6918 ItemPrototype const *proto = m_items[i]->GetProto();
6919 if(!proto)
6920 continue;
6922 // item set bonuses not dependent from item broken state
6923 if(proto->ItemSet)
6924 AddItemsSetItem(this,m_items[i]);
6926 if(m_items[i]->IsBroken())
6927 continue;
6929 ApplyItemEquipSpell(m_items[i],true);
6930 ApplyEnchantment(m_items[i], true);
6934 sLog.outDebug("_ApplyAllItemMods complete.");
6937 void Player::_ApplyAmmoBonuses()
6939 // check ammo
6940 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6941 if(!ammo_id)
6942 return;
6944 float currentAmmoDPS;
6946 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6947 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6948 currentAmmoDPS = 0.0f;
6949 else
6950 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6952 if(currentAmmoDPS == GetAmmoDPS())
6953 return;
6955 m_ammoDPS = currentAmmoDPS;
6957 if(CanModifyStats())
6958 UpdateDamagePhysical(RANGED_ATTACK);
6961 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
6963 if(!ammo_proto)
6964 return false;
6966 // check ranged weapon
6967 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
6968 if(!weapon || weapon->IsBroken() )
6969 return false;
6971 ItemPrototype const* weapon_proto = weapon->GetProto();
6972 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
6973 return false;
6975 // check ammo ws. weapon compatibility
6976 switch(weapon_proto->SubClass)
6978 case ITEM_SUBCLASS_WEAPON_BOW:
6979 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
6980 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
6981 return false;
6982 break;
6983 case ITEM_SUBCLASS_WEAPON_GUN:
6984 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
6985 return false;
6986 break;
6987 default:
6988 return false;
6991 return true;
6994 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
6995 Called by remove insignia spell effect */
6996 void Player::RemovedInsignia(Player* looterPlr)
6998 if (!GetBattleGroundId())
6999 return;
7001 // If not released spirit, do it !
7002 if(m_deathTimer > 0)
7004 m_deathTimer = 0;
7005 BuildPlayerRepop();
7006 RepopAtGraveyard();
7009 Corpse *corpse = GetCorpse();
7010 if (!corpse)
7011 return;
7013 // We have to convert player corpse to bones, not to be able to resurrect there
7014 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7015 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7016 if (!bones)
7017 return;
7019 // Now we must make bones lootable, and send player loot
7020 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7022 // We store the level of our player in the gold field
7023 // We retrieve this information at Player::SendLoot()
7024 bones->loot.gold = getLevel();
7025 bones->lootRecipient = looterPlr;
7026 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7029 /*Loot type MUST be
7030 1-corpse, go
7031 2-skinning
7032 3-Fishing
7035 void Player::SendLootRelease( uint64 guid )
7037 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7038 data << uint64(guid) << uint8(1);
7039 SendDirectMessage( &data );
7042 void Player::SendLoot(uint64 guid, LootType loot_type)
7044 Loot *loot = 0;
7045 PermissionTypes permission = ALL_PERMISSION;
7047 sLog.outDebug("Player::SendLoot");
7048 if (IS_GAMEOBJECT_GUID(guid))
7050 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7051 GameObject *go =
7052 ObjectAccessor::GetGameObject(*this, guid);
7054 // not check distance for GO in case owned GO (fishing bobber case, for example)
7055 // And permit out of range GO with no owner in case fishing hole
7056 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7058 SendLootRelease(guid);
7059 return;
7062 loot = &go->loot;
7064 if(go->getLootState() == GO_READY)
7066 uint32 lootid = go->GetLootId();
7068 if(lootid)
7070 sLog.outDebug(" if(lootid)");
7071 loot->clear();
7072 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7075 if(loot_type == LOOT_FISHING)
7076 go->getFishLoot(loot);
7078 go->SetLootState(GO_ACTIVATED);
7081 else if (IS_ITEM_GUID(guid))
7083 Item *item = GetItemByGuid( guid );
7085 if (!item)
7087 SendLootRelease(guid);
7088 return;
7091 if(loot_type == LOOT_DISENCHANTING)
7093 loot = &item->loot;
7095 if(!item->m_lootGenerated)
7097 item->m_lootGenerated = true;
7098 loot->clear();
7099 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7102 else if(loot_type == LOOT_PROSPECTING)
7104 loot = &item->loot;
7106 if(!item->m_lootGenerated)
7108 item->m_lootGenerated = true;
7109 loot->clear();
7110 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7113 else
7115 loot = &item->loot;
7117 if(!item->m_lootGenerated)
7119 item->m_lootGenerated = true;
7120 loot->clear();
7121 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7123 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7127 else if (IS_CORPSE_GUID(guid)) // remove insignia
7129 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7131 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7133 SendLootRelease(guid);
7134 return;
7137 loot = &bones->loot;
7139 if (!bones->lootForBody)
7141 bones->lootForBody = true;
7142 uint32 pLevel = bones->loot.gold;
7143 bones->loot.clear();
7144 // It may need a better formula
7145 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7146 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7149 if (bones->lootRecipient != this)
7150 permission = NONE_PERMISSION;
7152 else
7154 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7156 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7157 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7159 SendLootRelease(guid);
7160 return;
7163 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7165 SendLootRelease(guid);
7166 return;
7169 loot = &creature->loot;
7171 if(loot_type == LOOT_PICKPOCKETING)
7173 if ( !creature->lootForPickPocketed )
7175 creature->lootForPickPocketed = true;
7176 loot->clear();
7178 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7179 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7181 // Generate extra money for pick pocket loot
7182 const uint32 a = urand(0, creature->getLevel()/2);
7183 const uint32 b = urand(0, getLevel()/2);
7184 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7187 else
7189 // the player whose group may loot the corpse
7190 Player *recipient = creature->GetLootRecipient();
7191 if (!recipient)
7193 creature->SetLootRecipient(this);
7194 recipient = this;
7197 if (creature->lootForPickPocketed)
7199 creature->lootForPickPocketed = false;
7200 loot->clear();
7203 if(!creature->lootForBody)
7205 creature->lootForBody = true;
7206 loot->clear();
7208 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7209 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7211 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7213 if(Group* group = recipient->GetGroup())
7215 group->UpdateLooterGuid(creature,true);
7217 switch (group->GetLootMethod())
7219 case GROUP_LOOT:
7220 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7221 group->GroupLoot(recipient->GetGUID(), loot, creature);
7222 break;
7223 case NEED_BEFORE_GREED:
7224 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7225 break;
7226 case MASTER_LOOT:
7227 group->MasterLoot(recipient->GetGUID(), loot, creature);
7228 break;
7229 default:
7230 break;
7235 // possible only if creature->lootForBody && loot->empty() at spell cast check
7236 if (loot_type == LOOT_SKINNING)
7238 loot->clear();
7239 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7241 // set group rights only for loot_type != LOOT_SKINNING
7242 else
7244 if(Group* group = GetGroup())
7246 if( group == recipient->GetGroup() )
7248 if(group->GetLootMethod() == FREE_FOR_ALL)
7249 permission = ALL_PERMISSION;
7250 else if(group->GetLooterGuid() == GetGUID())
7252 if(group->GetLootMethod() == MASTER_LOOT)
7253 permission = MASTER_PERMISSION;
7254 else
7255 permission = ALL_PERMISSION;
7257 else
7258 permission = GROUP_PERMISSION;
7260 else
7261 permission = NONE_PERMISSION;
7263 else if(recipient == this)
7264 permission = ALL_PERMISSION;
7265 else
7266 permission = NONE_PERMISSION;
7271 SetLootGUID(guid);
7273 QuestItemList *q_list = 0;
7274 if (permission != NONE_PERMISSION)
7276 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7277 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7278 if (itr == lootPlayerQuestItems.end())
7279 q_list = loot->FillQuestLoot(this);
7280 else
7281 q_list = itr->second;
7284 QuestItemList *ffa_list = 0;
7285 if (permission != NONE_PERMISSION)
7287 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7288 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7289 if (itr == lootPlayerFFAItems.end())
7290 ffa_list = loot->FillFFALoot(this);
7291 else
7292 ffa_list = itr->second;
7295 QuestItemList *conditional_list = 0;
7296 if (permission != NONE_PERMISSION)
7298 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7299 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7300 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7301 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7302 else
7303 conditional_list = itr->second;
7306 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7307 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7308 loot_type = LOOT_SKINNING;
7310 if(loot_type == LOOT_FISHINGHOLE)
7311 loot_type = LOOT_FISHING;
7313 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7315 data << uint64(guid);
7316 data << uint8(loot_type);
7317 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7319 SendDirectMessage(&data);
7321 // add 'this' player as one of the players that are looting 'loot'
7322 if (permission != NONE_PERMISSION)
7323 loot->AddLooter(GetGUID());
7325 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7326 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7329 void Player::SendNotifyLootMoneyRemoved()
7331 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7332 GetSession()->SendPacket( &data );
7335 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7337 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7338 data << uint8(lootSlot);
7339 GetSession()->SendPacket( &data );
7342 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7344 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7345 data << Field;
7346 data << Value;
7347 GetSession()->SendPacket(&data);
7350 void Player::SendInitWorldStates()
7352 // data depends on zoneid/mapid...
7353 BattleGround* bg = GetBattleGround();
7354 uint16 NumberOfFields = 0;
7355 uint32 mapid = GetMapId();
7356 uint32 zoneid = GetZoneId();
7357 uint32 areaid = GetAreaId();
7358 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7359 // may be exist better way to do this...
7360 switch(zoneid)
7362 case 0:
7363 case 1:
7364 case 4:
7365 case 8:
7366 case 10:
7367 case 11:
7368 case 12:
7369 case 36:
7370 case 38:
7371 case 40:
7372 case 41:
7373 case 51:
7374 case 267:
7375 case 1519:
7376 case 1537:
7377 case 2257:
7378 case 2918:
7379 NumberOfFields = 6;
7380 break;
7381 case 2597:
7382 NumberOfFields = 81;
7383 break;
7384 case 3277:
7385 NumberOfFields = 14;
7386 break;
7387 case 3358:
7388 case 3820:
7389 NumberOfFields = 38;
7390 break;
7391 case 3483:
7392 NumberOfFields = 22;
7393 break;
7394 case 3519:
7395 NumberOfFields = 36;
7396 break;
7397 case 3521:
7398 NumberOfFields = 35;
7399 break;
7400 case 3698:
7401 case 3702:
7402 case 3968:
7403 NumberOfFields = 9;
7404 break;
7405 case 3703:
7406 NumberOfFields = 9;
7407 break;
7408 default:
7409 NumberOfFields = 10;
7410 break;
7413 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7414 data << uint32(mapid); // mapid
7415 data << uint32(zoneid); // zone id
7416 data << uint32(areaid); // area id, new 2.1.0
7417 data << uint16(NumberOfFields); // count of uint64 blocks
7418 data << uint32(0x8d8) << uint32(0x0); // 1
7419 data << uint32(0x8d7) << uint32(0x0); // 2
7420 data << uint32(0x8d6) << uint32(0x0); // 3
7421 data << uint32(0x8d5) << uint32(0x0); // 4
7422 data << uint32(0x8d4) << uint32(0x0); // 5
7423 data << uint32(0x8d3) << uint32(0x0); // 6
7424 if(mapid == 530) // Outland
7426 data << uint32(0x9bf) << uint32(0x0); // 7
7427 data << uint32(0x9bd) << uint32(0xF); // 8
7428 data << uint32(0x9bb) << uint32(0xF); // 9
7430 switch(zoneid)
7432 case 1:
7433 case 11:
7434 case 12:
7435 case 38:
7436 case 40:
7437 case 51:
7438 case 1519:
7439 case 1537:
7440 case 2257:
7441 break;
7442 case 2597: // AV
7443 data << uint32(0x7ae) << uint32(0x1); // 7
7444 data << uint32(0x532) << uint32(0x1); // 8
7445 data << uint32(0x531) << uint32(0x0); // 9
7446 data << uint32(0x52e) << uint32(0x0); // 10
7447 data << uint32(0x571) << uint32(0x0); // 11
7448 data << uint32(0x570) << uint32(0x0); // 12
7449 data << uint32(0x567) << uint32(0x1); // 13
7450 data << uint32(0x566) << uint32(0x1); // 14
7451 data << uint32(0x550) << uint32(0x1); // 15
7452 data << uint32(0x544) << uint32(0x0); // 16
7453 data << uint32(0x536) << uint32(0x0); // 17
7454 data << uint32(0x535) << uint32(0x1); // 18
7455 data << uint32(0x518) << uint32(0x0); // 19
7456 data << uint32(0x517) << uint32(0x0); // 20
7457 data << uint32(0x574) << uint32(0x0); // 21
7458 data << uint32(0x573) << uint32(0x0); // 22
7459 data << uint32(0x572) << uint32(0x0); // 23
7460 data << uint32(0x56f) << uint32(0x0); // 24
7461 data << uint32(0x56e) << uint32(0x0); // 25
7462 data << uint32(0x56d) << uint32(0x0); // 26
7463 data << uint32(0x56c) << uint32(0x0); // 27
7464 data << uint32(0x56b) << uint32(0x0); // 28
7465 data << uint32(0x56a) << uint32(0x1); // 29
7466 data << uint32(0x569) << uint32(0x1); // 30
7467 data << uint32(0x568) << uint32(0x1); // 13
7468 data << uint32(0x565) << uint32(0x0); // 32
7469 data << uint32(0x564) << uint32(0x0); // 33
7470 data << uint32(0x563) << uint32(0x0); // 34
7471 data << uint32(0x562) << uint32(0x0); // 35
7472 data << uint32(0x561) << uint32(0x0); // 36
7473 data << uint32(0x560) << uint32(0x0); // 37
7474 data << uint32(0x55f) << uint32(0x0); // 38
7475 data << uint32(0x55e) << uint32(0x0); // 39
7476 data << uint32(0x55d) << uint32(0x0); // 40
7477 data << uint32(0x3c6) << uint32(0x4); // 41
7478 data << uint32(0x3c4) << uint32(0x6); // 42
7479 data << uint32(0x3c2) << uint32(0x4); // 43
7480 data << uint32(0x516) << uint32(0x1); // 44
7481 data << uint32(0x515) << uint32(0x0); // 45
7482 data << uint32(0x3b6) << uint32(0x6); // 46
7483 data << uint32(0x55c) << uint32(0x0); // 47
7484 data << uint32(0x55b) << uint32(0x0); // 48
7485 data << uint32(0x55a) << uint32(0x0); // 49
7486 data << uint32(0x559) << uint32(0x0); // 50
7487 data << uint32(0x558) << uint32(0x0); // 51
7488 data << uint32(0x557) << uint32(0x0); // 52
7489 data << uint32(0x556) << uint32(0x0); // 53
7490 data << uint32(0x555) << uint32(0x0); // 54
7491 data << uint32(0x554) << uint32(0x1); // 55
7492 data << uint32(0x553) << uint32(0x1); // 56
7493 data << uint32(0x552) << uint32(0x1); // 57
7494 data << uint32(0x551) << uint32(0x1); // 58
7495 data << uint32(0x54f) << uint32(0x0); // 59
7496 data << uint32(0x54e) << uint32(0x0); // 60
7497 data << uint32(0x54d) << uint32(0x1); // 61
7498 data << uint32(0x54c) << uint32(0x0); // 62
7499 data << uint32(0x54b) << uint32(0x0); // 63
7500 data << uint32(0x545) << uint32(0x0); // 64
7501 data << uint32(0x543) << uint32(0x1); // 65
7502 data << uint32(0x542) << uint32(0x0); // 66
7503 data << uint32(0x540) << uint32(0x0); // 67
7504 data << uint32(0x53f) << uint32(0x0); // 68
7505 data << uint32(0x53e) << uint32(0x0); // 69
7506 data << uint32(0x53d) << uint32(0x0); // 70
7507 data << uint32(0x53c) << uint32(0x0); // 71
7508 data << uint32(0x53b) << uint32(0x0); // 72
7509 data << uint32(0x53a) << uint32(0x1); // 73
7510 data << uint32(0x539) << uint32(0x0); // 74
7511 data << uint32(0x538) << uint32(0x0); // 75
7512 data << uint32(0x537) << uint32(0x0); // 76
7513 data << uint32(0x534) << uint32(0x0); // 77
7514 data << uint32(0x533) << uint32(0x0); // 78
7515 data << uint32(0x530) << uint32(0x0); // 79
7516 data << uint32(0x52f) << uint32(0x0); // 80
7517 data << uint32(0x52d) << uint32(0x1); // 81
7518 break;
7519 case 3277: // WS
7520 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7521 bg->FillInitialWorldStates(data);
7522 else
7524 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7525 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7526 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7527 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7528 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7529 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7530 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7531 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7533 break;
7534 case 3358: // AB
7535 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7536 bg->FillInitialWorldStates(data);
7537 else
7539 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7540 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7541 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7542 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7543 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7544 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7545 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7546 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7547 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7548 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7549 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7550 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7551 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7552 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7553 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7554 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7555 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7556 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7557 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7558 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7559 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7560 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7561 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7562 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7563 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7564 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7565 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7566 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7567 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7568 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7569 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7570 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7572 break;
7573 case 3820: // EY
7574 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7575 bg->FillInitialWorldStates(data);
7576 else
7578 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7579 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7580 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7581 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7582 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7583 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7584 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7585 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7586 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7587 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7588 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7589 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7590 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7591 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7592 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7593 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7594 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7595 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7596 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontroled (1 - yes, 0 - no)
7597 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7598 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7599 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7600 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7601 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7602 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7603 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7604 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7605 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7606 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7607 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7608 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7609 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7610 // and some more ... unknown
7612 break;
7613 case 3483: // Hellfire Peninsula
7614 data << uint32(0x9ba) << uint32(0x1); // 10
7615 data << uint32(0x9b9) << uint32(0x1); // 11
7616 data << uint32(0x9b5) << uint32(0x0); // 12
7617 data << uint32(0x9b4) << uint32(0x1); // 13
7618 data << uint32(0x9b3) << uint32(0x0); // 14
7619 data << uint32(0x9b2) << uint32(0x0); // 15
7620 data << uint32(0x9b1) << uint32(0x1); // 16
7621 data << uint32(0x9b0) << uint32(0x0); // 17
7622 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7623 data << uint32(0x9ac) << uint32(0x0); // 19
7624 data << uint32(0x9a8) << uint32(0x0); // 20
7625 data << uint32(0x9a7) << uint32(0x0); // 21
7626 data << uint32(0x9a6) << uint32(0x1); // 22
7627 break;
7628 case 3519: // Terokkar Forest
7629 data << uint32(0xa41) << uint32(0x0); // 10
7630 data << uint32(0xa40) << uint32(0x14); // 11
7631 data << uint32(0xa3f) << uint32(0x0); // 12
7632 data << uint32(0xa3e) << uint32(0x0); // 13
7633 data << uint32(0xa3d) << uint32(0x5); // 14
7634 data << uint32(0xa3c) << uint32(0x0); // 15
7635 data << uint32(0xa87) << uint32(0x0); // 16
7636 data << uint32(0xa86) << uint32(0x0); // 17
7637 data << uint32(0xa85) << uint32(0x0); // 18
7638 data << uint32(0xa84) << uint32(0x0); // 19
7639 data << uint32(0xa83) << uint32(0x0); // 20
7640 data << uint32(0xa82) << uint32(0x0); // 21
7641 data << uint32(0xa81) << uint32(0x0); // 22
7642 data << uint32(0xa80) << uint32(0x0); // 23
7643 data << uint32(0xa7e) << uint32(0x0); // 24
7644 data << uint32(0xa7d) << uint32(0x0); // 25
7645 data << uint32(0xa7c) << uint32(0x0); // 26
7646 data << uint32(0xa7b) << uint32(0x0); // 27
7647 data << uint32(0xa7a) << uint32(0x0); // 28
7648 data << uint32(0xa79) << uint32(0x0); // 29
7649 data << uint32(0x9d0) << uint32(0x5); // 30
7650 data << uint32(0x9ce) << uint32(0x0); // 31
7651 data << uint32(0x9cd) << uint32(0x0); // 32
7652 data << uint32(0x9cc) << uint32(0x0); // 33
7653 data << uint32(0xa88) << uint32(0x0); // 34
7654 data << uint32(0xad0) << uint32(0x0); // 35
7655 data << uint32(0xacf) << uint32(0x1); // 36
7656 break;
7657 case 3521: // Zangarmarsh
7658 data << uint32(0x9e1) << uint32(0x0); // 10
7659 data << uint32(0x9e0) << uint32(0x0); // 11
7660 data << uint32(0x9df) << uint32(0x0); // 12
7661 data << uint32(0xa5d) << uint32(0x1); // 13
7662 data << uint32(0xa5c) << uint32(0x0); // 14
7663 data << uint32(0xa5b) << uint32(0x1); // 15
7664 data << uint32(0xa5a) << uint32(0x0); // 16
7665 data << uint32(0xa59) << uint32(0x1); // 17
7666 data << uint32(0xa58) << uint32(0x0); // 18
7667 data << uint32(0xa57) << uint32(0x0); // 19
7668 data << uint32(0xa56) << uint32(0x0); // 20
7669 data << uint32(0xa55) << uint32(0x1); // 21
7670 data << uint32(0xa54) << uint32(0x0); // 22
7671 data << uint32(0x9e7) << uint32(0x0); // 23
7672 data << uint32(0x9e6) << uint32(0x0); // 24
7673 data << uint32(0x9e5) << uint32(0x0); // 25
7674 data << uint32(0xa00) << uint32(0x0); // 26
7675 data << uint32(0x9ff) << uint32(0x1); // 27
7676 data << uint32(0x9fe) << uint32(0x0); // 28
7677 data << uint32(0x9fd) << uint32(0x0); // 29
7678 data << uint32(0x9fc) << uint32(0x1); // 30
7679 data << uint32(0x9fb) << uint32(0x0); // 31
7680 data << uint32(0xa62) << uint32(0x0); // 32
7681 data << uint32(0xa61) << uint32(0x1); // 33
7682 data << uint32(0xa60) << uint32(0x1); // 34
7683 data << uint32(0xa5f) << uint32(0x0); // 35
7684 break;
7685 case 3698: // Nagrand Arena
7686 data << uint32(0xa0f) << uint32(0x0); // 7
7687 data << uint32(0xa10) << uint32(0x0); // 8
7688 data << uint32(0xa11) << uint32(0x0); // 9
7689 break;
7690 case 3702: // Blade's Edge Arena
7691 data << uint32(0x9f0) << uint32(0x0); // 7
7692 data << uint32(0x9f1) << uint32(0x0); // 8
7693 data << uint32(0x9f3) << uint32(0x0); // 9
7694 break;
7695 case 3968: // Ruins of Lordaeron
7696 data << uint32(0xbb8) << uint32(0x0); // 7
7697 data << uint32(0xbb9) << uint32(0x0); // 8
7698 data << uint32(0xbba) << uint32(0x0); // 9
7699 break;
7700 case 3703: // Shattrath City
7701 break;
7702 default:
7703 data << uint32(0x914) << uint32(0x0); // 7
7704 data << uint32(0x913) << uint32(0x0); // 8
7705 data << uint32(0x912) << uint32(0x0); // 9
7706 data << uint32(0x915) << uint32(0x0); // 10
7707 break;
7709 GetSession()->SendPacket(&data);
7712 uint32 Player::GetXPRestBonus(uint32 xp)
7714 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7716 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7717 rested_bonus = xp;
7719 SetRestBonus( GetRestBonus() - rested_bonus);
7721 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7722 return rested_bonus;
7725 void Player::SetBindPoint(uint64 guid)
7727 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7728 data << uint64(guid);
7729 GetSession()->SendPacket( &data );
7732 void Player::SendTalentWipeConfirm(uint64 guid)
7734 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7735 data << uint64(guid);
7736 data << uint32(resetTalentsCost());
7737 GetSession()->SendPacket( &data );
7740 void Player::SendPetSkillWipeConfirm()
7742 Pet* pet = GetPet();
7743 if(!pet)
7744 return;
7745 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7746 data << pet->GetGUID();
7747 data << uint32(pet->resetTalentsCost());
7748 GetSession()->SendPacket( &data );
7751 /*********************************************************/
7752 /*** STORAGE SYSTEM ***/
7753 /*********************************************************/
7755 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7757 assert(i < 3);
7758 if(i < 2 && item)
7760 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7761 return;
7762 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7763 if(charges == 0)
7764 return;
7765 if(charges > 1)
7766 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7767 else if(charges <= 1)
7769 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7770 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7775 void Player::SetSheath( uint32 sheathed )
7777 switch (sheathed)
7779 case SHEATH_STATE_UNARMED: // no prepared weapon
7780 SetVirtualItemSlot(0,NULL);
7781 SetVirtualItemSlot(1,NULL);
7782 SetVirtualItemSlot(2,NULL);
7783 break;
7784 case SHEATH_STATE_MELEE: // prepared melee weapon
7786 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7787 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7788 SetVirtualItemSlot(2,NULL);
7789 }; break;
7790 case SHEATH_STATE_RANGED: // prepared ranged weapon
7791 SetVirtualItemSlot(0,NULL);
7792 SetVirtualItemSlot(1,NULL);
7793 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7794 break;
7795 default:
7796 SetVirtualItemSlot(0,NULL);
7797 SetVirtualItemSlot(1,NULL);
7798 SetVirtualItemSlot(2,NULL);
7799 break;
7801 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7804 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7806 uint8 pClass = getClass();
7808 uint8 slots[4];
7809 slots[0] = NULL_SLOT;
7810 slots[1] = NULL_SLOT;
7811 slots[2] = NULL_SLOT;
7812 slots[3] = NULL_SLOT;
7813 switch( proto->InventoryType )
7815 case INVTYPE_HEAD:
7816 slots[0] = EQUIPMENT_SLOT_HEAD;
7817 break;
7818 case INVTYPE_NECK:
7819 slots[0] = EQUIPMENT_SLOT_NECK;
7820 break;
7821 case INVTYPE_SHOULDERS:
7822 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7823 break;
7824 case INVTYPE_BODY:
7825 slots[0] = EQUIPMENT_SLOT_BODY;
7826 break;
7827 case INVTYPE_CHEST:
7828 slots[0] = EQUIPMENT_SLOT_CHEST;
7829 break;
7830 case INVTYPE_ROBE:
7831 slots[0] = EQUIPMENT_SLOT_CHEST;
7832 break;
7833 case INVTYPE_WAIST:
7834 slots[0] = EQUIPMENT_SLOT_WAIST;
7835 break;
7836 case INVTYPE_LEGS:
7837 slots[0] = EQUIPMENT_SLOT_LEGS;
7838 break;
7839 case INVTYPE_FEET:
7840 slots[0] = EQUIPMENT_SLOT_FEET;
7841 break;
7842 case INVTYPE_WRISTS:
7843 slots[0] = EQUIPMENT_SLOT_WRISTS;
7844 break;
7845 case INVTYPE_HANDS:
7846 slots[0] = EQUIPMENT_SLOT_HANDS;
7847 break;
7848 case INVTYPE_FINGER:
7849 slots[0] = EQUIPMENT_SLOT_FINGER1;
7850 slots[1] = EQUIPMENT_SLOT_FINGER2;
7851 break;
7852 case INVTYPE_TRINKET:
7853 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7854 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7855 break;
7856 case INVTYPE_CLOAK:
7857 slots[0] = EQUIPMENT_SLOT_BACK;
7858 break;
7859 case INVTYPE_WEAPON:
7861 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7863 // suggest offhand slot only if know dual wielding
7864 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7865 if(CanDualWield())
7866 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7867 };break;
7868 case INVTYPE_SHIELD:
7869 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7870 break;
7871 case INVTYPE_RANGED:
7872 slots[0] = EQUIPMENT_SLOT_RANGED;
7873 break;
7874 case INVTYPE_2HWEAPON:
7875 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7876 break;
7877 case INVTYPE_TABARD:
7878 slots[0] = EQUIPMENT_SLOT_TABARD;
7879 break;
7880 case INVTYPE_WEAPONMAINHAND:
7881 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7882 break;
7883 case INVTYPE_WEAPONOFFHAND:
7884 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7885 break;
7886 case INVTYPE_HOLDABLE:
7887 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7888 break;
7889 case INVTYPE_THROWN:
7890 slots[0] = EQUIPMENT_SLOT_RANGED;
7891 break;
7892 case INVTYPE_RANGEDRIGHT:
7893 slots[0] = EQUIPMENT_SLOT_RANGED;
7894 break;
7895 case INVTYPE_BAG:
7896 slots[0] = INVENTORY_SLOT_BAG_1;
7897 slots[1] = INVENTORY_SLOT_BAG_2;
7898 slots[2] = INVENTORY_SLOT_BAG_3;
7899 slots[3] = INVENTORY_SLOT_BAG_4;
7900 break;
7901 case INVTYPE_RELIC:
7903 switch(proto->SubClass)
7905 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7906 if (pClass == CLASS_PALADIN)
7907 slots[0] = EQUIPMENT_SLOT_RANGED;
7908 break;
7909 case ITEM_SUBCLASS_ARMOR_IDOL:
7910 if (pClass == CLASS_DRUID)
7911 slots[0] = EQUIPMENT_SLOT_RANGED;
7912 break;
7913 case ITEM_SUBCLASS_ARMOR_TOTEM:
7914 if (pClass == CLASS_SHAMAN)
7915 slots[0] = EQUIPMENT_SLOT_RANGED;
7916 break;
7917 case ITEM_SUBCLASS_ARMOR_MISC:
7918 if (pClass == CLASS_WARLOCK)
7919 slots[0] = EQUIPMENT_SLOT_RANGED;
7920 break;
7922 break;
7924 default :
7925 return NULL_SLOT;
7928 if( slot != NULL_SLOT )
7930 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7932 for (int i = 0; i < 4; i++)
7934 if ( slots[i] == slot )
7935 return slot;
7939 else
7941 // search free slot at first
7942 for (int i = 0; i < 4; i++)
7944 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7946 // in case 2hand equipped weapon offhand slot empty but not free
7947 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7949 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7950 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7951 return slots[i];
7953 else
7954 return slots[i];
7958 // if not found free and can swap return first appropriate from used
7959 for (int i = 0; i < 4; i++)
7961 if ( slots[i] != NULL_SLOT && swap )
7962 return slots[i];
7966 // no free position
7967 return NULL_SLOT;
7970 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
7972 Item *pItem;
7973 uint32 tempcount = 0;
7975 uint8 res = EQUIP_ERR_OK;
7977 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
7979 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7980 if( pItem && pItem->GetEntry() == item )
7982 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
7983 if(ires==EQUIP_ERR_OK)
7985 tempcount += pItem->GetCount();
7986 if( tempcount >= count )
7987 return EQUIP_ERR_OK;
7989 else
7990 res = ires;
7993 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
7995 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7996 if( pItem && pItem->GetEntry() == item )
7998 tempcount += pItem->GetCount();
7999 if( tempcount >= count )
8000 return EQUIP_ERR_OK;
8003 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8005 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8006 if( pItem && pItem->GetEntry() == item )
8008 tempcount += pItem->GetCount();
8009 if( tempcount >= count )
8010 return EQUIP_ERR_OK;
8013 Bag *pBag;
8014 ItemPrototype const *pBagProto;
8015 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8017 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8018 if( pBag )
8020 pBagProto = pBag->GetProto();
8021 if( pBagProto )
8023 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8025 pItem = GetItemByPos( i, j );
8026 if( pItem && pItem->GetEntry() == item )
8028 tempcount += pItem->GetCount();
8029 if( tempcount >= count )
8030 return EQUIP_ERR_OK;
8037 // not found req. item count and have unequippable items
8038 return res;
8041 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8043 uint32 count = 0;
8044 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8046 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8047 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8048 count += pItem->GetCount();
8050 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8052 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8053 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8054 count += pItem->GetCount();
8056 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8058 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8059 if( pBag )
8060 count += pBag->GetItemCount(item,skipItem);
8063 if(skipItem && skipItem->GetProto()->GemProperties)
8065 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8067 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8068 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8069 count += pItem->GetGemCountWithID(item);
8073 if(inBankAlso)
8075 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8077 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8078 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8079 count += pItem->GetCount();
8081 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8083 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8084 if( pBag )
8085 count += pBag->GetItemCount(item,skipItem);
8088 if(skipItem && skipItem->GetProto()->GemProperties)
8090 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8092 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8093 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8094 count += pItem->GetGemCountWithID(item);
8099 return count;
8102 Item* Player::GetItemByGuid( uint64 guid ) const
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->GetGUID() == guid )
8108 return pItem;
8110 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8112 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8113 if( pItem && pItem->GetGUID() == guid )
8114 return pItem;
8117 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8119 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8120 if( pBag )
8122 ItemPrototype const *pBagProto = pBag->GetProto();
8123 if( pBagProto )
8125 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8127 Item* pItem = pBag->GetItemByPos( j );
8128 if( pItem && pItem->GetGUID() == guid )
8129 return pItem;
8134 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8136 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8137 if( pBag )
8139 ItemPrototype const *pBagProto = pBag->GetProto();
8140 if( pBagProto )
8142 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8144 Item* pItem = pBag->GetItemByPos( j );
8145 if( pItem && pItem->GetGUID() == guid )
8146 return pItem;
8152 return NULL;
8155 Item* Player::GetItemByPos( uint16 pos ) const
8157 uint8 bag = pos >> 8;
8158 uint8 slot = pos & 255;
8159 return GetItemByPos( bag, slot );
8162 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8164 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8165 return m_items[slot];
8166 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8167 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8169 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8170 if ( pBag )
8171 return pBag->GetItemByPos(slot);
8173 return NULL;
8176 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8178 uint16 slot;
8179 switch (attackType)
8181 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8182 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8183 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8184 default: return NULL;
8187 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8188 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8189 return NULL;
8191 if(!useable)
8192 return item;
8194 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8195 return NULL;
8197 return item;
8200 Item* Player::GetShield(bool useable) const
8202 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8203 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8204 return NULL;
8206 if(!useable)
8207 return item;
8209 if( item->IsBroken())
8210 return NULL;
8212 return item;
8215 uint32 Player::GetAttackBySlot( uint8 slot )
8217 switch(slot)
8219 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8220 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8221 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8222 default: return MAX_ATTACK;
8226 bool Player::HasBankBagSlot( uint8 slot ) const
8228 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8229 if( slot < maxslot )
8230 return true;
8231 return false;
8234 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8236 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8237 return true;
8238 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8239 return true;
8240 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8241 return true;
8242 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8243 return true;
8244 return false;
8247 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8249 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8250 return true;
8251 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8252 return true;
8253 return false;
8256 bool Player::IsBankPos( uint8 bag, uint8 slot )
8258 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8259 return true;
8260 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8261 return true;
8262 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8263 return true;
8264 return false;
8267 bool Player::IsBagPos( uint16 pos )
8269 uint8 bag = pos >> 8;
8270 uint8 slot = pos & 255;
8271 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8272 return true;
8273 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8274 return true;
8275 return false;
8278 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8280 uint32 tempcount = 0;
8281 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8283 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8284 if( pItem && pItem->GetEntry() == item )
8286 tempcount += pItem->GetCount();
8287 if( tempcount >= count )
8288 return true;
8291 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8293 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8294 if( pItem && pItem->GetEntry() == item )
8296 tempcount += pItem->GetCount();
8297 if( tempcount >= count )
8298 return true;
8301 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8303 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8305 if(ItemPrototype const *pBagProto = pBag->GetProto())
8307 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8309 Item* pItem = GetItemByPos( i, j );
8310 if( pItem && pItem->GetEntry() == item )
8312 tempcount += pItem->GetCount();
8313 if( tempcount >= count )
8314 return true;
8321 if(inBankAlso)
8323 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8325 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8326 if( pItem && pItem->GetEntry() == item )
8328 tempcount += pItem->GetCount();
8329 if( tempcount >= count )
8330 return true;
8333 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8335 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8337 if(ItemPrototype const *pBagProto = pBag->GetProto())
8339 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8341 Item* pItem = GetItemByPos( i, j );
8342 if( pItem && pItem->GetEntry() == item )
8344 tempcount += pItem->GetCount();
8345 if( tempcount >= count )
8346 return true;
8354 return false;
8357 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8359 Item *pItem;
8360 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8362 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8363 if( pItem && pItem->GetEntry() == item )
8364 return pItem;
8367 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8368 if (pProto && pProto->GemProperties)
8370 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8372 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8373 if( pItem && pItem->GetProto()->Socket[0].Color )
8375 if (pItem->GetGemCountWithID(item) > 0 )
8376 return pItem;
8381 return NULL;
8384 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8386 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8387 if( !pProto )
8389 if(no_space_count)
8390 *no_space_count = count;
8391 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8394 // no maximum
8395 if(pProto->MaxCount == 0)
8396 return EQUIP_ERR_OK;
8398 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8400 if( curcount + count > pProto->MaxCount )
8402 if(no_space_count)
8403 *no_space_count = count +curcount - pProto->MaxCount;
8404 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8407 return EQUIP_ERR_OK;
8410 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8412 Item *pItem;
8413 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8415 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8416 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8417 return true;
8419 for(uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
8421 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8422 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8423 return true;
8425 Bag *pBag;
8426 ItemPrototype const *pBagProto;
8427 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8429 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8430 if( pBag )
8432 pBagProto = pBag->GetProto();
8433 if( pBagProto )
8435 for(uint32 j = 0; j < pBagProto->ContainerSlots; ++j)
8437 pItem = GetItemByPos( i, j );
8438 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8439 return true;
8444 return false;
8447 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8449 Item* pItem2 = GetItemByPos( bag, slot );
8451 // ignore move item (this slot will be empty at move)
8452 if(pItem2==pSrcItem)
8453 pItem2 = NULL;
8455 uint32 need_space;
8457 // empty specific slot - check item fit to slot
8458 if( !pItem2 || swap )
8460 if( bag == INVENTORY_SLOT_BAG_0 )
8462 // keyring case
8463 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8464 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8466 // prevent cheating
8467 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8468 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8470 else
8472 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8473 if( !pBag )
8474 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8476 ItemPrototype const* pBagProto = pBag->GetProto();
8477 if( !pBagProto )
8478 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8480 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8481 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8484 // non empty stack with space
8485 need_space = pProto->Stackable;
8487 // non empty slot, check item type
8488 else
8490 // check item type
8491 if(pItem2->GetEntry() != pProto->ItemId)
8492 return EQUIP_ERR_ITEM_CANT_STACK;
8494 // check free space
8495 if(pItem2->GetCount() >= pProto->Stackable)
8496 return EQUIP_ERR_ITEM_CANT_STACK;
8498 need_space = pProto->Stackable - pItem2->GetCount();
8501 if(need_space > count)
8502 need_space = count;
8504 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8505 if(!newPosition.isContainedIn(dest))
8507 dest.push_back(newPosition);
8508 count -= need_space;
8510 return EQUIP_ERR_OK;
8513 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
8515 // skip specific bag already processed in first called _CanStoreItem_InBag
8516 if(bag==skip_bag)
8517 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8519 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8520 if( !pBag )
8521 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8523 ItemPrototype const* pBagProto = pBag->GetProto();
8524 if( !pBagProto )
8525 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8527 // specialized bag mode or non-specilized
8528 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8529 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8531 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8532 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8534 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8536 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8537 if(j==skip_slot)
8538 continue;
8540 Item* pItem2 = GetItemByPos( bag, j );
8542 // ignore move item (this slot will be empty at move)
8543 if(pItem2==pSrcItem)
8544 pItem2 = NULL;
8546 // if merge skip empty, if !merge skip non-empty
8547 if((pItem2!=NULL)!=merge)
8548 continue;
8550 if( pItem2 )
8552 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8554 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8555 if(need_space > count)
8556 need_space = count;
8558 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8559 if(!newPosition.isContainedIn(dest))
8561 dest.push_back(newPosition);
8562 count -= need_space;
8564 if(count==0)
8565 return EQUIP_ERR_OK;
8569 else
8571 uint32 need_space = pProto->Stackable;
8572 if(need_space > count)
8573 need_space = count;
8575 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8576 if(!newPosition.isContainedIn(dest))
8578 dest.push_back(newPosition);
8579 count -= need_space;
8581 if(count==0)
8582 return EQUIP_ERR_OK;
8586 return EQUIP_ERR_OK;
8589 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
8591 for(uint32 j = slot_begin; j < slot_end; j++)
8593 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8594 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8595 continue;
8597 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8599 // ignore move item (this slot will be empty at move)
8600 if(pItem2==pSrcItem)
8601 pItem2 = NULL;
8603 // if merge skip empty, if !merge skip non-empty
8604 if((pItem2!=NULL)!=merge)
8605 continue;
8607 if( pItem2 )
8609 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8611 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8612 if(need_space > count)
8613 need_space = count;
8614 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8615 if(!newPosition.isContainedIn(dest))
8617 dest.push_back(newPosition);
8618 count -= need_space;
8620 if(count==0)
8621 return EQUIP_ERR_OK;
8625 else
8627 uint32 need_space = pProto->Stackable;
8628 if(need_space > count)
8629 need_space = count;
8631 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8632 if(!newPosition.isContainedIn(dest))
8634 dest.push_back(newPosition);
8635 count -= need_space;
8637 if(count==0)
8638 return EQUIP_ERR_OK;
8642 return EQUIP_ERR_OK;
8645 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8647 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8649 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8650 if( !pProto )
8652 if(no_space_count)
8653 *no_space_count = count;
8654 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8657 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8659 if(no_space_count)
8660 *no_space_count = count;
8661 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8664 // check count of items (skip for auto move for same player from bank)
8665 uint32 no_similar_count = 0; // can't store this amount similar items
8666 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8667 if(res!=EQUIP_ERR_OK)
8669 if(count==no_similar_count)
8671 if(no_space_count)
8672 *no_space_count = no_similar_count;
8673 return res;
8675 count -= no_similar_count;
8678 // in specific slot
8679 if( bag != NULL_BAG && slot != NULL_SLOT )
8681 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8682 if(res!=EQUIP_ERR_OK)
8684 if(no_space_count)
8685 *no_space_count = count + no_similar_count;
8686 return res;
8689 if(count==0)
8691 if(no_similar_count==0)
8692 return EQUIP_ERR_OK;
8694 if(no_space_count)
8695 *no_space_count = count + no_similar_count;
8696 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8700 // not specific slot or have spece for partly store only in specific slot
8702 // in specific bag
8703 if( bag != NULL_BAG )
8705 // search stack in bag for merge to
8706 if( pProto->Stackable > 1 )
8708 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8710 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8711 if(res!=EQUIP_ERR_OK)
8713 if(no_space_count)
8714 *no_space_count = count + no_similar_count;
8715 return res;
8718 if(count==0)
8720 if(no_similar_count==0)
8721 return EQUIP_ERR_OK;
8723 if(no_space_count)
8724 *no_space_count = count + no_similar_count;
8725 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8728 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8729 if(res!=EQUIP_ERR_OK)
8731 if(no_space_count)
8732 *no_space_count = count + no_similar_count;
8733 return res;
8736 if(count==0)
8738 if(no_similar_count==0)
8739 return EQUIP_ERR_OK;
8741 if(no_space_count)
8742 *no_space_count = count + no_similar_count;
8743 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8746 else // equipped bag
8748 // we need check 2 time (specilized/non_specialized), use NULL_BAG to prevent skipping bag
8749 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8750 if(res!=EQUIP_ERR_OK)
8751 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8753 if(res!=EQUIP_ERR_OK)
8755 if(no_space_count)
8756 *no_space_count = count + no_similar_count;
8757 return res;
8760 if(count==0)
8762 if(no_similar_count==0)
8763 return EQUIP_ERR_OK;
8765 if(no_space_count)
8766 *no_space_count = count + no_similar_count;
8767 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8772 // search free slot in bag for place to
8773 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8775 // search free slot - keyring case
8776 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8778 uint32 keyringSize = GetMaxKeyringSize();
8779 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8780 if(res!=EQUIP_ERR_OK)
8782 if(no_space_count)
8783 *no_space_count = count + no_similar_count;
8784 return res;
8787 if(count==0)
8789 if(no_similar_count==0)
8790 return EQUIP_ERR_OK;
8792 if(no_space_count)
8793 *no_space_count = count + no_similar_count;
8794 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8798 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8799 if(res!=EQUIP_ERR_OK)
8801 if(no_space_count)
8802 *no_space_count = count + no_similar_count;
8803 return res;
8806 if(count==0)
8808 if(no_similar_count==0)
8809 return EQUIP_ERR_OK;
8811 if(no_space_count)
8812 *no_space_count = count + no_similar_count;
8813 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8816 else // equipped bag
8818 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8819 if(res!=EQUIP_ERR_OK)
8820 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8822 if(res!=EQUIP_ERR_OK)
8824 if(no_space_count)
8825 *no_space_count = count + no_similar_count;
8826 return res;
8829 if(count==0)
8831 if(no_similar_count==0)
8832 return EQUIP_ERR_OK;
8834 if(no_space_count)
8835 *no_space_count = count + no_similar_count;
8836 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8841 // not specific bag or have space for partly store only in specific bag
8843 // search stack for merge to
8844 if( pProto->Stackable > 1 )
8846 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8847 if(res!=EQUIP_ERR_OK)
8849 if(no_space_count)
8850 *no_space_count = count + no_similar_count;
8851 return res;
8854 if(count==0)
8856 if(no_similar_count==0)
8857 return EQUIP_ERR_OK;
8859 if(no_space_count)
8860 *no_space_count = count + no_similar_count;
8861 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8864 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8865 if(res!=EQUIP_ERR_OK)
8867 if(no_space_count)
8868 *no_space_count = count + no_similar_count;
8869 return res;
8872 if(count==0)
8874 if(no_similar_count==0)
8875 return EQUIP_ERR_OK;
8877 if(no_space_count)
8878 *no_space_count = count + no_similar_count;
8879 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8882 if( pProto->BagFamily )
8884 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8886 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
8887 if(res!=EQUIP_ERR_OK)
8888 continue;
8890 if(count==0)
8892 if(no_similar_count==0)
8893 return EQUIP_ERR_OK;
8895 if(no_space_count)
8896 *no_space_count = count + no_similar_count;
8897 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8902 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8904 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
8905 if(res!=EQUIP_ERR_OK)
8906 continue;
8908 if(count==0)
8910 if(no_similar_count==0)
8911 return EQUIP_ERR_OK;
8913 if(no_space_count)
8914 *no_space_count = count + no_similar_count;
8915 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8920 // search free slot - special bag case
8921 if( pProto->BagFamily )
8923 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8925 uint32 keyringSize = GetMaxKeyringSize();
8926 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8927 if(res!=EQUIP_ERR_OK)
8929 if(no_space_count)
8930 *no_space_count = count + no_similar_count;
8931 return res;
8934 if(count==0)
8936 if(no_similar_count==0)
8937 return EQUIP_ERR_OK;
8939 if(no_space_count)
8940 *no_space_count = count + no_similar_count;
8941 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8945 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8947 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
8948 if(res!=EQUIP_ERR_OK)
8949 continue;
8951 if(count==0)
8953 if(no_similar_count==0)
8954 return EQUIP_ERR_OK;
8956 if(no_space_count)
8957 *no_space_count = count + no_similar_count;
8958 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8963 // search free slot
8964 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8965 if(res!=EQUIP_ERR_OK)
8967 if(no_space_count)
8968 *no_space_count = count + no_similar_count;
8969 return res;
8972 if(count==0)
8974 if(no_similar_count==0)
8975 return EQUIP_ERR_OK;
8977 if(no_space_count)
8978 *no_space_count = count + no_similar_count;
8979 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8982 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8984 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
8985 if(res!=EQUIP_ERR_OK)
8986 continue;
8988 if(count==0)
8990 if(no_similar_count==0)
8991 return EQUIP_ERR_OK;
8993 if(no_space_count)
8994 *no_space_count = count + no_similar_count;
8995 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8999 if(no_space_count)
9000 *no_space_count = count + no_similar_count;
9002 return EQUIP_ERR_INVENTORY_FULL;
9005 //////////////////////////////////////////////////////////////////////////
9006 uint8 Player::CanStoreItems( Item **pItems,int count) const
9008 Item *pItem2;
9010 // fill space table
9011 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9012 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9013 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9015 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9016 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9017 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9019 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9021 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9023 if (pItem2 && !pItem2->IsInTrade())
9025 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9029 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9031 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9033 if (pItem2 && !pItem2->IsInTrade())
9035 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9039 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9041 Bag *pBag;
9042 ItemPrototype const *pBagProto;
9044 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9045 if( pBag )
9047 pBagProto = pBag->GetProto();
9049 if( pBagProto )
9051 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9053 pItem2 = GetItemByPos( i, j );
9054 if (pItem2 && !pItem2->IsInTrade())
9056 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9063 // check free space for all items
9064 for (int k=0;k<count;k++)
9066 Item *pItem = pItems[k];
9068 // no item
9069 if (!pItem) continue;
9071 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9072 ItemPrototype const *pProto = pItem->GetProto();
9074 // strange item
9075 if( !pProto )
9076 return EQUIP_ERR_ITEM_NOT_FOUND;
9078 // item it 'bind'
9079 if(pItem->IsBindedNotWith(GetGUID()))
9080 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9082 Bag *pBag;
9083 ItemPrototype const *pBagProto;
9085 // item is 'one item only'
9086 uint8 res = CanTakeMoreSimilarItems(pItem);
9087 if(res != EQUIP_ERR_OK)
9088 return res;
9090 // search stack for merge to
9091 if( pProto->Stackable > 1 )
9093 bool b_found = false;
9095 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9097 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9098 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9100 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9101 b_found = true;
9102 break;
9105 if (b_found) continue;
9107 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9109 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9110 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9112 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9113 b_found = true;
9114 break;
9117 if (b_found) continue;
9119 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9121 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9122 if( pBag )
9124 pBagProto = pBag->GetProto();
9125 if( pBagProto )
9127 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9129 pItem2 = GetItemByPos( t, j );
9130 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9132 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9133 b_found = true;
9134 break;
9140 if (b_found) continue;
9143 // special bag case
9144 if( pProto->BagFamily )
9146 bool b_found = false;
9147 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9149 uint32 keyringSize = GetMaxKeyringSize();
9150 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9152 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9154 inv_keys[t-KEYRING_SLOT_START] = 1;
9155 b_found = true;
9156 break;
9161 if (b_found) continue;
9163 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9165 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9166 if( pBag )
9168 pBagProto = pBag->GetProto();
9170 // not plain container check
9171 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9172 ItemCanGoIntoBag(pProto,pBagProto) )
9174 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9176 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9178 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9179 b_found = true;
9180 break;
9186 if (b_found) continue;
9189 // search free slot
9190 bool b_found = false;
9191 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9193 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9195 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9196 b_found = true;
9197 break;
9200 if (b_found) continue;
9202 // search free slot in bags
9203 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9205 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9206 if( pBag )
9208 pBagProto = pBag->GetProto();
9209 if( pBagProto && ItemCanGoIntoBag(pProto,pBagProto))
9211 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9213 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9215 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9216 b_found = true;
9217 break;
9224 // no free slot found?
9225 if (!b_found)
9226 return EQUIP_ERR_INVENTORY_FULL;
9229 return EQUIP_ERR_OK;
9232 //////////////////////////////////////////////////////////////////////////
9233 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9235 dest = 0;
9236 Item *pItem = Item::CreateItem( item, count, this );
9237 if( pItem )
9239 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9240 delete pItem;
9241 return result;
9244 return EQUIP_ERR_ITEM_NOT_FOUND;
9247 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9249 dest = 0;
9250 if( pItem )
9252 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9253 ItemPrototype const *pProto = pItem->GetProto();
9254 if( pProto )
9256 // May be here should be more stronger checks; STUNNED checked
9257 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9258 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9259 return EQUIP_ERR_YOU_ARE_STUNNED;
9261 if(pItem->IsBindedNotWith(GetGUID()))
9262 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9264 // check count of items (skip for auto move for same player from bank)
9265 uint8 res = CanTakeMoreSimilarItems(pItem);
9266 if(res != EQUIP_ERR_OK)
9267 return res;
9269 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9270 // - combat
9271 // - in-progress arenas
9272 if( !pProto->CanChangeEquipStateInCombat() )
9274 if( isInCombat() )
9275 return EQUIP_ERR_NOT_IN_COMBAT;
9277 if(BattleGround* bg = GetBattleGround())
9278 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9279 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9282 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9283 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9285 if(IsNonMeleeSpellCasted(false))
9286 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9288 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9289 if( eslot == NULL_SLOT )
9290 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9292 uint8 msg = CanUseItem( pItem , not_loading );
9293 if( msg != EQUIP_ERR_OK )
9294 return msg;
9295 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9296 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9298 // check unique-equipped on item
9299 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9301 // there is an equip limit on this item
9302 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9303 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9304 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9307 // check unique-equipped on gems
9308 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9310 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9311 if(!enchant_id)
9312 continue;
9313 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9314 if(!enchantEntry)
9315 continue;
9317 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9318 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9320 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9321 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9322 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9326 // check unique-equipped special item classes
9327 if (pProto->Class == ITEM_CLASS_QUIVER)
9329 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9331 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9333 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9335 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9336 (!swap || pBag->GetSlot() != eslot ) )
9338 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9339 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9340 else
9341 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9348 uint32 type = pProto->InventoryType;
9350 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9352 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9354 if(!CanDualWield())
9355 return EQUIP_ERR_CANT_DUAL_WIELD;
9358 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9359 if(mainItem)
9361 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9362 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9366 // equip two-hand weapon case (with possible unequip 2 items)
9367 if( type == INVTYPE_2HWEAPON )
9369 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9370 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9372 // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
9373 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9374 ItemPosCountVec off_dest;
9375 if( offItem && (!not_loading ||
9376 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9377 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9378 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9380 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9381 return EQUIP_ERR_OK;
9384 if( !swap )
9385 return EQUIP_ERR_ITEM_NOT_FOUND;
9386 else
9387 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9390 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9392 // Applied only to equipped items and bank bags
9393 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9394 return EQUIP_ERR_OK;
9396 Item* pItem = GetItemByPos(pos);
9398 // Applied only to existed equipped item
9399 if( !pItem )
9400 return EQUIP_ERR_OK;
9402 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9404 ItemPrototype const *pProto = pItem->GetProto();
9405 if( !pProto )
9406 return EQUIP_ERR_ITEM_NOT_FOUND;
9408 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9409 // - combat
9410 // - in-progress arenas
9411 if( !pProto->CanChangeEquipStateInCombat() )
9413 if( isInCombat() )
9414 return EQUIP_ERR_NOT_IN_COMBAT;
9416 if(BattleGround* bg = GetBattleGround())
9417 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9418 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9421 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9422 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9424 return EQUIP_ERR_OK;
9427 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9429 if( !pItem )
9430 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9432 uint32 count = pItem->GetCount();
9434 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9435 ItemPrototype const *pProto = pItem->GetProto();
9436 if( !pProto )
9437 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9439 if( pItem->IsBindedNotWith(GetGUID()) )
9440 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9442 // check count of items (skip for auto move for same player from bank)
9443 uint8 res = CanTakeMoreSimilarItems(pItem);
9444 if(res != EQUIP_ERR_OK)
9445 return res;
9447 // in specific slot
9448 if( bag != NULL_BAG && slot != NULL_SLOT )
9450 if( pProto->InventoryType == INVTYPE_BAG )
9452 Bag *pBag = (Bag*)pItem;
9453 if( pBag )
9455 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9457 if( !HasBankBagSlot( slot ) )
9458 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9459 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9460 return cantuse;
9462 else
9464 if( !pBag->IsEmpty() )
9465 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9469 else
9471 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9472 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9475 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9476 if(res!=EQUIP_ERR_OK)
9477 return res;
9479 if(count==0)
9480 return EQUIP_ERR_OK;
9483 // not specific slot or have spece for partly store only in specific slot
9485 // in specific bag
9486 if( bag != NULL_BAG )
9488 if( pProto->InventoryType == INVTYPE_BAG )
9490 Bag *pBag = (Bag*)pItem;
9491 if( pBag && !pBag->IsEmpty() )
9492 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9495 // search stack in bag for merge to
9496 if( pProto->Stackable > 1 )
9498 if( bag == INVENTORY_SLOT_BAG_0 )
9500 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9501 if(res!=EQUIP_ERR_OK)
9502 return res;
9504 if(count==0)
9505 return EQUIP_ERR_OK;
9507 else
9509 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9510 if(res!=EQUIP_ERR_OK)
9511 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9513 if(res!=EQUIP_ERR_OK)
9514 return res;
9516 if(count==0)
9517 return EQUIP_ERR_OK;
9521 // search free slot in bag
9522 if( bag == INVENTORY_SLOT_BAG_0 )
9524 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9525 if(res!=EQUIP_ERR_OK)
9526 return res;
9528 if(count==0)
9529 return EQUIP_ERR_OK;
9531 else
9533 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9534 if(res!=EQUIP_ERR_OK)
9535 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9537 if(res!=EQUIP_ERR_OK)
9538 return res;
9540 if(count==0)
9541 return EQUIP_ERR_OK;
9545 // not specific bag or have spece for partly store only in specific bag
9547 // search stack for merge to
9548 if( pProto->Stackable > 1 )
9550 // in slots
9551 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9552 if(res!=EQUIP_ERR_OK)
9553 return res;
9555 if(count==0)
9556 return EQUIP_ERR_OK;
9558 // in special bags
9559 if( pProto->BagFamily )
9561 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9563 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9564 if(res!=EQUIP_ERR_OK)
9565 continue;
9567 if(count==0)
9568 return EQUIP_ERR_OK;
9572 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9574 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9575 if(res!=EQUIP_ERR_OK)
9576 continue;
9578 if(count==0)
9579 return EQUIP_ERR_OK;
9583 // search free place in special bag
9584 if( pProto->BagFamily )
9586 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9588 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9589 if(res!=EQUIP_ERR_OK)
9590 continue;
9592 if(count==0)
9593 return EQUIP_ERR_OK;
9597 // search free space
9598 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9599 if(res!=EQUIP_ERR_OK)
9600 return res;
9602 if(count==0)
9603 return EQUIP_ERR_OK;
9605 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9607 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9608 if(res!=EQUIP_ERR_OK)
9609 continue;
9611 if(count==0)
9612 return EQUIP_ERR_OK;
9614 return EQUIP_ERR_BANK_FULL;
9617 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9619 if( pItem )
9621 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9622 if( !isAlive() && not_loading )
9623 return EQUIP_ERR_YOU_ARE_DEAD;
9624 //if( isStunned() )
9625 // return EQUIP_ERR_YOU_ARE_STUNNED;
9626 ItemPrototype const *pProto = pItem->GetProto();
9627 if( pProto )
9629 if( pItem->IsBindedNotWith(GetGUID()) )
9630 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9631 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9632 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9633 if( pItem->GetSkill() != 0 )
9635 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9636 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9638 if( pProto->RequiredSkill != 0 )
9640 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9641 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9642 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9643 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9645 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9646 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9647 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9648 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9649 if( getLevel() < pProto->RequiredLevel )
9650 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9651 return EQUIP_ERR_OK;
9654 return EQUIP_ERR_ITEM_NOT_FOUND;
9657 bool Player::CanUseItem( ItemPrototype const *pProto )
9659 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9661 if( pProto )
9663 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9664 return false;
9665 if( pProto->RequiredSkill != 0 )
9667 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9668 return false;
9669 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9670 return false;
9672 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9673 return false;
9674 if( getLevel() < pProto->RequiredLevel )
9675 return false;
9676 return true;
9678 return false;
9681 uint8 Player::CanUseAmmo( uint32 item ) const
9683 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9684 if( !isAlive() )
9685 return EQUIP_ERR_YOU_ARE_DEAD;
9686 //if( isStunned() )
9687 // return EQUIP_ERR_YOU_ARE_STUNNED;
9688 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9689 if( pProto )
9691 if( pProto->InventoryType!= INVTYPE_AMMO )
9692 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9693 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9694 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9695 if( pProto->RequiredSkill != 0 )
9697 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9698 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9699 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9700 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9702 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9703 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9704 /*if( GetReputation() < pProto->RequiredReputation )
9705 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9707 if( getLevel() < pProto->RequiredLevel )
9708 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9710 // Requires No Ammo
9711 if(GetDummyAura(46699))
9712 return EQUIP_ERR_BAG_FULL6;
9714 return EQUIP_ERR_OK;
9716 return EQUIP_ERR_ITEM_NOT_FOUND;
9719 void Player::SetAmmo( uint32 item )
9721 if(!item)
9722 return;
9724 // already set
9725 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9726 return;
9728 // check ammo
9729 if(item)
9731 uint8 msg = CanUseAmmo( item );
9732 if( msg != EQUIP_ERR_OK )
9734 SendEquipError( msg, NULL, NULL );
9735 return;
9739 SetUInt32Value(PLAYER_AMMO_ID, item);
9741 _ApplyAmmoBonuses();
9744 void Player::RemoveAmmo()
9746 SetUInt32Value(PLAYER_AMMO_ID, 0);
9748 m_ammoDPS = 0.0f;
9750 if(CanModifyStats())
9751 UpdateDamagePhysical(RANGED_ATTACK);
9754 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9755 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9757 uint32 count = 0;
9758 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9759 count += itr->count;
9761 Item *pItem = Item::CreateItem( item, count, this );
9762 if( pItem )
9764 ItemAddedQuestCheck( item, count );
9765 if(randomPropertyId)
9766 pItem->SetItemRandomProperties(randomPropertyId);
9767 pItem = StoreItem( dest, pItem, update );
9769 return pItem;
9772 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9774 if( !pItem )
9775 return NULL;
9777 Item* lastItem = pItem;
9779 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9781 uint16 pos = itr->pos;
9782 uint32 count = itr->count;
9784 ++itr;
9786 if(itr == dest.end())
9788 lastItem = _StoreItem(pos,pItem,count,false,update);
9789 break;
9792 lastItem = _StoreItem(pos,pItem,count,true,update);
9795 return lastItem;
9798 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9799 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
9801 if( !pItem )
9802 return NULL;
9804 uint8 bag = pos >> 8;
9805 uint8 slot = pos & 255;
9807 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
9809 Item *pItem2 = GetItemByPos( bag, slot );
9811 if( !pItem2 )
9813 if(clone)
9814 pItem = pItem->CloneItem(count,this);
9815 else
9816 pItem->SetCount(count);
9818 if(!pItem)
9819 return NULL;
9821 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9822 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
9823 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9824 pItem->SetBinding( true );
9826 if( bag == INVENTORY_SLOT_BAG_0 )
9828 m_items[slot] = pItem;
9829 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
9830 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
9831 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
9833 pItem->SetSlot( slot );
9834 pItem->SetContainer( NULL );
9836 if( IsInWorld() && update )
9838 pItem->AddToWorld();
9839 pItem->SendUpdateToPlayer( this );
9842 pItem->SetState(ITEM_CHANGED, this);
9844 else
9846 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9847 if( pBag )
9849 pBag->StoreItem( slot, pItem, update );
9850 if( IsInWorld() && update )
9852 pItem->AddToWorld();
9853 pItem->SendUpdateToPlayer( this );
9855 pItem->SetState(ITEM_CHANGED, this);
9856 pBag->SetState(ITEM_CHANGED, this);
9860 AddEnchantmentDurations(pItem);
9861 AddItemDurations(pItem);
9863 return pItem;
9865 else
9867 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9868 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
9869 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9870 pItem2->SetBinding( true );
9872 pItem2->SetCount( pItem2->GetCount() + count );
9873 if( IsInWorld() && update )
9874 pItem2->SendUpdateToPlayer( this );
9876 if(!clone)
9878 // delete item (it not in any slot currently)
9879 if( IsInWorld() && update )
9881 pItem->RemoveFromWorld();
9882 pItem->DestroyForPlayer( this );
9885 RemoveEnchantmentDurations(pItem);
9886 RemoveItemDurations(pItem);
9888 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9889 pItem->SetState(ITEM_REMOVED, this);
9891 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
9892 AddEnchantmentDurations(pItem2);
9894 pItem2->SetState(ITEM_CHANGED, this);
9896 return pItem2;
9900 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
9902 Item *pItem = Item::CreateItem( item, count, this );
9903 if( pItem )
9905 ItemAddedQuestCheck( item, count );
9906 Item * retItem = EquipItem( pos, pItem, update );
9908 return retItem;
9910 return NULL;
9913 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
9915 if( pItem )
9917 AddEnchantmentDurations(pItem);
9918 AddItemDurations(pItem);
9920 uint8 bag = pos >> 8;
9921 uint8 slot = pos & 255;
9923 Item *pItem2 = GetItemByPos( bag, slot );
9925 if( !pItem2 )
9927 VisualizeItem( slot, pItem);
9929 if(isAlive())
9931 ItemPrototype const *pProto = pItem->GetProto();
9933 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
9934 if(pProto && pProto->ItemSet)
9935 AddItemsSetItem(this,pItem);
9937 _ApplyItemMods(pItem, slot, true);
9939 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
9941 m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
9942 if (getClass() == CLASS_ROGUE)
9943 m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
9947 if( IsInWorld() && update )
9949 pItem->AddToWorld();
9950 pItem->SendUpdateToPlayer( this );
9953 ApplyEquipCooldown(pItem);
9955 if( slot == EQUIPMENT_SLOT_MAINHAND )
9956 UpdateExpertise(BASE_ATTACK);
9957 else if( slot == EQUIPMENT_SLOT_OFFHAND )
9958 UpdateExpertise(OFF_ATTACK);
9960 else
9962 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
9963 if( IsInWorld() && update )
9964 pItem2->SendUpdateToPlayer( this );
9966 // delete item (it not in any slot currently)
9967 //pItem->DeleteFromDB();
9968 if( IsInWorld() && update )
9970 pItem->RemoveFromWorld();
9971 pItem->DestroyForPlayer( this );
9974 RemoveEnchantmentDurations(pItem);
9975 RemoveItemDurations(pItem);
9977 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9978 pItem->SetState(ITEM_REMOVED, this);
9979 pItem2->SetState(ITEM_CHANGED, this);
9981 ApplyEquipCooldown(pItem2);
9983 return pItem2;
9987 return pItem;
9990 void Player::QuickEquipItem( uint16 pos, Item *pItem)
9992 if( pItem )
9994 AddEnchantmentDurations(pItem);
9995 AddItemDurations(pItem);
9997 uint8 slot = pos & 255;
9998 VisualizeItem( slot, pItem);
10000 if( IsInWorld() )
10002 pItem->AddToWorld();
10003 pItem->SendUpdateToPlayer( this );
10008 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10010 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10011 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10012 // entry // Size: 1
10013 // inspected enchantments // Size: 6
10014 // ? // Size: 5
10015 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10016 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10017 // // = 16
10019 if(pItem)
10021 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10023 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10024 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10026 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10027 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10029 // Use SetInt16Value to prevent set high part to FFFF for negative value
10030 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10031 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10033 else
10035 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10037 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10038 SetUInt32Value(VisibleBase + 0, 0);
10040 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10041 SetUInt32Value(VisibleBase + 1 + i, 0);
10043 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10044 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10048 void Player::VisualizeItem( uint8 slot, Item *pItem)
10050 if(!pItem)
10051 return;
10053 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10054 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10055 pItem->SetBinding( true );
10057 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10059 m_items[slot] = pItem;
10060 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10061 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10062 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10063 pItem->SetSlot( slot );
10064 pItem->SetContainer( NULL );
10066 if( slot < EQUIPMENT_SLOT_END )
10067 SetVisibleItemSlot(slot,pItem);
10069 pItem->SetState(ITEM_CHANGED, this);
10072 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10074 // note: removeitem does not actually change the item
10075 // it only takes the item out of storage temporarily
10076 // note2: if removeitem is to be used for delinking
10077 // the item must be removed from the player's updatequeue
10079 Item *pItem = GetItemByPos( bag, slot );
10080 if( pItem )
10082 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10084 RemoveEnchantmentDurations(pItem);
10085 RemoveItemDurations(pItem);
10087 if( bag == INVENTORY_SLOT_BAG_0 )
10089 if ( slot < INVENTORY_SLOT_BAG_END )
10091 ItemPrototype const *pProto = pItem->GetProto();
10092 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10094 if(pProto && pProto->ItemSet)
10095 RemoveItemsSetItem(this,pProto);
10097 _ApplyItemMods(pItem, slot, false);
10099 // remove item dependent auras and casts (only weapon and armor slots)
10100 if(slot < EQUIPMENT_SLOT_END)
10101 RemoveItemDependentAurasAndCasts(pItem);
10103 // remove held enchantments
10104 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10106 if (pItem->GetItemSuffixFactor())
10108 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10109 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10111 else
10113 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10114 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10119 m_items[slot] = NULL;
10120 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10122 if ( slot < EQUIPMENT_SLOT_END )
10123 SetVisibleItemSlot(slot,NULL);
10125 else
10127 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10128 if( pBag )
10129 pBag->RemoveItem(slot, update);
10131 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10132 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10133 pItem->SetSlot( NULL_SLOT );
10134 if( IsInWorld() && update )
10135 pItem->SendUpdateToPlayer( this );
10137 if( slot == EQUIPMENT_SLOT_MAINHAND )
10138 UpdateExpertise(BASE_ATTACK);
10139 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10140 UpdateExpertise(OFF_ATTACK);
10144 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10145 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10147 if(Item* it = GetItemByPos(bag,slot))
10149 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10150 RemoveItem( bag,slot,update);
10151 it->RemoveFromUpdateQueueOf(this);
10152 if(it->IsInWorld())
10154 it->RemoveFromWorld();
10155 it->DestroyForPlayer( this );
10160 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10161 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10163 // update quest counters
10164 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10166 // store item
10167 Item* pLastItem = StoreItem( dest, pItem, update);
10169 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10170 if(pLastItem==pItem)
10172 // update owner for last item (this can be original item with wrong owner
10173 if(pLastItem->GetOwnerGUID() != GetGUID())
10174 pLastItem->SetOwnerGUID(GetGUID());
10176 // if this original item then it need create record in inventory
10177 // in case trade we laready have item in other player inventory
10178 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10182 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10184 Item *pItem = GetItemByPos( bag, slot );
10185 if( pItem )
10187 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10189 // start from destroy contained items (only equipped bag can have its)
10190 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10192 for (int i = 0; i < MAX_BAG_SIZE; i++)
10193 DestroyItem(slot,i,update);
10196 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10197 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10199 ItemPrototype const *pProto = pItem->GetProto();
10201 RemoveEnchantmentDurations(pItem);
10202 RemoveItemDurations(pItem);
10204 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10206 if( bag == INVENTORY_SLOT_BAG_0 )
10209 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10211 // equipment and equipped bags can have applied bonuses
10212 if ( slot < INVENTORY_SLOT_BAG_END )
10214 ItemPrototype const *pProto = pItem->GetProto();
10216 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10217 if(pProto && pProto->ItemSet)
10218 RemoveItemsSetItem(this,pProto);
10220 _ApplyItemMods(pItem, slot, false);
10223 if ( slot < EQUIPMENT_SLOT_END )
10225 // remove item dependent auras and casts (only weapon and armor slots)
10226 RemoveItemDependentAurasAndCasts(pItem);
10228 // equipment visual show
10229 SetVisibleItemSlot(slot,NULL);
10232 m_items[slot] = NULL;
10234 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10235 pBag->RemoveItem(slot, update);
10237 if( IsInWorld() && update )
10239 pItem->RemoveFromWorld();
10240 pItem->DestroyForPlayer(this);
10243 //pItem->SetOwnerGUID(0);
10244 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10245 pItem->SetSlot( NULL_SLOT );
10246 pItem->SetState(ITEM_REMOVED, this);
10250 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10252 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10253 Item *pItem;
10254 ItemPrototype const *pProto;
10255 uint32 remcount = 0;
10257 // in inventory
10258 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10260 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10261 if( pItem && pItem->GetEntry() == item )
10263 if( pItem->GetCount() + remcount <= count )
10265 // all items in inventory can unequipped
10266 remcount += pItem->GetCount();
10267 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10269 if(remcount >=count)
10270 return;
10272 else
10274 pProto = pItem->GetProto();
10275 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10276 pItem->SetCount( pItem->GetCount() - count + remcount );
10277 if( IsInWorld() & update )
10278 pItem->SendUpdateToPlayer( this );
10279 pItem->SetState(ITEM_CHANGED, this);
10280 return;
10284 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10286 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10287 if( pItem && pItem->GetEntry() == item )
10289 if( pItem->GetCount() + remcount <= count )
10291 // all keys can be unequipped
10292 remcount += pItem->GetCount();
10293 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10295 if(remcount >=count)
10296 return;
10298 else
10300 pProto = pItem->GetProto();
10301 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10302 pItem->SetCount( pItem->GetCount() - count + remcount );
10303 if( IsInWorld() & update )
10304 pItem->SendUpdateToPlayer( this );
10305 pItem->SetState(ITEM_CHANGED, this);
10306 return;
10311 // in inventory bags
10312 Bag *pBag;
10313 ItemPrototype const *pBagProto;
10314 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10316 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10317 if( pBag )
10319 pBagProto = pBag->GetProto();
10320 if( pBagProto )
10322 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
10324 pItem = pBag->GetItemByPos(j);
10325 if( pItem && pItem->GetEntry() == item )
10327 // all items in bags can be unequipped
10328 if( pItem->GetCount() + remcount <= count )
10330 remcount += pItem->GetCount();
10331 DestroyItem( i, j, update );
10333 if(remcount >=count)
10334 return;
10336 else
10338 pProto = pItem->GetProto();
10339 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10340 pItem->SetCount( pItem->GetCount() - count + remcount );
10341 if( IsInWorld() && update )
10342 pItem->SendUpdateToPlayer( this );
10343 pItem->SetState(ITEM_CHANGED, this);
10344 return;
10352 // in equipment and bag list
10353 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10355 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10356 if( pItem && pItem->GetEntry() == item )
10358 if( pItem->GetCount() + remcount <= count )
10360 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10362 remcount += pItem->GetCount();
10363 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10365 if(remcount >=count)
10366 return;
10369 else
10371 pProto = pItem->GetProto();
10372 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10373 pItem->SetCount( pItem->GetCount() - count + remcount );
10374 if( IsInWorld() & update )
10375 pItem->SendUpdateToPlayer( this );
10376 pItem->SetState(ITEM_CHANGED, this);
10377 return;
10383 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10385 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10387 // in inventory
10388 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10390 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10391 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10392 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10394 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10396 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10397 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10398 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10401 // in inventory bags
10402 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10404 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10405 if( pBag )
10407 ItemPrototype const *pBagProto = pBag->GetProto();
10408 if( pBagProto )
10410 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
10412 Item* pItem = pBag->GetItemByPos(j);
10413 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10414 DestroyItem( i, j, update);
10420 // in equipment and bag list
10421 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10423 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10424 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10425 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10429 void Player::DestroyConjuredItems( bool update )
10431 // used when entering arena
10432 // distroys all conjured items
10433 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10435 // in inventory
10436 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10438 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10439 if( pItem && pItem->GetProto() &&
10440 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10441 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10442 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10445 // in inventory bags
10446 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10448 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10449 if( pBag )
10451 ItemPrototype const *pBagProto = pBag->GetProto();
10452 if( pBagProto )
10454 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
10456 Item* pItem = pBag->GetItemByPos(j);
10457 if( pItem && pItem->GetProto() &&
10458 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10459 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10460 DestroyItem( i, j, update);
10466 // in equipment and bag list
10467 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10469 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10470 if( pItem && pItem->GetProto() &&
10471 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10472 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10473 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10477 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10479 if(!pItem)
10480 return;
10482 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10484 if( pItem->GetCount() <= count )
10486 count-= pItem->GetCount();
10488 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10490 else
10492 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10493 pItem->SetCount( pItem->GetCount() - count );
10494 count = 0;
10495 if( IsInWorld() & update )
10496 pItem->SendUpdateToPlayer( this );
10497 pItem->SetState(ITEM_CHANGED, this);
10501 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10503 uint8 srcbag = src >> 8;
10504 uint8 srcslot = src & 255;
10506 uint8 dstbag = dst >> 8;
10507 uint8 dstslot = dst & 255;
10509 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10510 if( !pSrcItem )
10512 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10513 return;
10516 // not let split all items (can be only at cheating)
10517 if(pSrcItem->GetCount() == count)
10519 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10520 return;
10523 // not let split more existed items (can be only at cheating)
10524 if(pSrcItem->GetCount() < count)
10526 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10527 return;
10530 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10532 //best error message found for attempting to split while looting
10533 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10534 return;
10537 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10538 Item *pNewItem = pSrcItem->CloneItem( count, this );
10539 if( !pNewItem )
10541 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10542 return;
10545 if( IsInventoryPos( dst ) )
10547 // change item amount before check (for unique max count check)
10548 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10550 ItemPosCountVec dest;
10551 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10552 if( msg != EQUIP_ERR_OK )
10554 delete pNewItem;
10555 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10556 SendEquipError( msg, pSrcItem, NULL );
10557 return;
10560 if( IsInWorld() )
10561 pSrcItem->SendUpdateToPlayer( this );
10562 pSrcItem->SetState(ITEM_CHANGED, this);
10563 StoreItem( dest, pNewItem, true);
10565 else if( IsBankPos ( dst ) )
10567 // change item amount before check (for unique max count check)
10568 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10570 ItemPosCountVec dest;
10571 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10572 if( msg != EQUIP_ERR_OK )
10574 delete pNewItem;
10575 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10576 SendEquipError( msg, pSrcItem, NULL );
10577 return;
10580 if( IsInWorld() )
10581 pSrcItem->SendUpdateToPlayer( this );
10582 pSrcItem->SetState(ITEM_CHANGED, this);
10583 BankItem( dest, pNewItem, true);
10585 else if( IsEquipmentPos ( dst ) )
10587 // change item amount before check (for unique max count check), provide space for splitted items
10588 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10590 uint16 dest;
10591 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10592 if( msg != EQUIP_ERR_OK )
10594 delete pNewItem;
10595 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10596 SendEquipError( msg, pSrcItem, NULL );
10597 return;
10600 if( IsInWorld() )
10601 pSrcItem->SendUpdateToPlayer( this );
10602 pSrcItem->SetState(ITEM_CHANGED, this);
10603 EquipItem( dest, pNewItem, true);
10604 AutoUnequipOffhandIfNeed();
10608 void Player::SwapItem( uint16 src, uint16 dst )
10610 uint8 srcbag = src >> 8;
10611 uint8 srcslot = src & 255;
10613 uint8 dstbag = dst >> 8;
10614 uint8 dstslot = dst & 255;
10616 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10617 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10619 if( !pSrcItem )
10620 return;
10622 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10624 if(!isAlive() )
10626 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10627 return;
10630 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10632 //best error message found for attempting to swap while looting
10633 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10634 return;
10637 // check unequip potability for equipped items and bank bags
10638 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10640 // bags can be swapped with empty bag slots
10641 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10642 if(msg != EQUIP_ERR_OK)
10644 SendEquipError( msg, pSrcItem, pDstItem );
10645 return;
10649 // prevent put equipped/bank bag in self
10650 if( IsBagPos ( src ) && srcslot == dstbag)
10652 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10653 return;
10656 if( !pDstItem )
10658 if( IsInventoryPos( dst ) )
10660 ItemPosCountVec dest;
10661 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10662 if( msg != EQUIP_ERR_OK )
10664 SendEquipError( msg, pSrcItem, NULL );
10665 return;
10668 RemoveItem(srcbag, srcslot, true);
10669 StoreItem( dest, pSrcItem, true);
10671 else if( IsBankPos ( dst ) )
10673 ItemPosCountVec dest;
10674 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10675 if( msg != EQUIP_ERR_OK )
10677 SendEquipError( msg, pSrcItem, NULL );
10678 return;
10681 RemoveItem(srcbag, srcslot, true);
10682 BankItem( dest, pSrcItem, true);
10684 else if( IsEquipmentPos ( dst ) )
10686 uint16 dest;
10687 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10688 if( msg != EQUIP_ERR_OK )
10690 SendEquipError( msg, pSrcItem, NULL );
10691 return;
10694 RemoveItem(srcbag, srcslot, true);
10695 EquipItem( dest, pSrcItem, true);
10696 AutoUnequipOffhandIfNeed();
10699 else // if (!pDstItem)
10701 if(pDstItem->m_lootGenerated) // prevent swap looting item
10703 //best error message found for attempting to swap while looting
10704 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10705 return;
10708 // check unequip potability for equipped items and bank bags
10709 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10711 // bags can be swapped with empty bag slots
10712 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
10713 if(msg != EQUIP_ERR_OK)
10715 SendEquipError( msg, pSrcItem, pDstItem );
10716 return;
10720 // attempt merge to / fill target item
10722 uint8 msg;
10723 ItemPosCountVec sDest;
10724 uint16 eDest;
10725 if( IsInventoryPos( dst ) )
10726 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10727 else if( IsBankPos ( dst ) )
10728 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10729 else if( IsEquipmentPos ( dst ) )
10730 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10731 else
10732 return;
10734 // can be merge/fill
10735 if(msg == EQUIP_ERR_OK)
10737 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
10739 RemoveItem(srcbag, srcslot, true);
10741 if( IsInventoryPos( dst ) )
10742 StoreItem( sDest, pSrcItem, true);
10743 else if( IsBankPos ( dst ) )
10744 BankItem( sDest, pSrcItem, true);
10745 else if( IsEquipmentPos ( dst ) )
10747 EquipItem( eDest, pSrcItem, true);
10748 AutoUnequipOffhandIfNeed();
10751 else
10753 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
10754 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
10755 pSrcItem->SetState(ITEM_CHANGED, this);
10756 pDstItem->SetState(ITEM_CHANGED, this);
10757 if( IsInWorld() )
10759 pSrcItem->SendUpdateToPlayer( this );
10760 pDstItem->SendUpdateToPlayer( this );
10763 return;
10767 // impossible merge/fill, do real swap
10768 uint8 msg;
10770 // check src->dest move possibility
10771 ItemPosCountVec sDest;
10772 uint16 eDest;
10773 if( IsInventoryPos( dst ) )
10774 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10775 else if( IsBankPos( dst ) )
10776 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10777 else if( IsEquipmentPos( dst ) )
10779 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10780 if( msg == EQUIP_ERR_OK )
10781 msg = CanUnequipItem( eDest, true );
10784 if( msg != EQUIP_ERR_OK )
10786 SendEquipError( msg, pSrcItem, pDstItem );
10787 return;
10790 // check dest->src move possibility
10791 ItemPosCountVec sDest2;
10792 uint16 eDest2;
10793 if( IsInventoryPos( src ) )
10794 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10795 else if( IsBankPos( src ) )
10796 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10797 else if( IsEquipmentPos( src ) )
10799 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10800 if( msg == EQUIP_ERR_OK )
10801 msg = CanUnequipItem( eDest2, true);
10804 if( msg != EQUIP_ERR_OK )
10806 SendEquipError( msg, pDstItem, pSrcItem );
10807 return;
10810 // now do moves, remove...
10811 RemoveItem(dstbag, dstslot, false);
10812 RemoveItem(srcbag, srcslot, false);
10814 // add to dest
10815 if( IsInventoryPos( dst ) )
10816 StoreItem(sDest, pSrcItem, true);
10817 else if( IsBankPos( dst ) )
10818 BankItem(sDest, pSrcItem, true);
10819 else if( IsEquipmentPos( dst ) )
10820 EquipItem(eDest, pSrcItem, true);
10822 // add to src
10823 if( IsInventoryPos( src ) )
10824 StoreItem(sDest2, pDstItem, true);
10825 else if( IsBankPos( src ) )
10826 BankItem(sDest2, pDstItem, true);
10827 else if( IsEquipmentPos( src ) )
10828 EquipItem(eDest2, pDstItem, true);
10830 AutoUnequipOffhandIfNeed();
10834 void Player::AddItemToBuyBackSlot( Item *pItem )
10836 if( pItem )
10838 uint32 slot = m_currentBuybackSlot;
10839 // if current back slot non-empty search oldest or free
10840 if(m_items[slot])
10842 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
10843 uint32 oldest_slot = BUYBACK_SLOT_START;
10845 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
10847 // found empty
10848 if(!m_items[i])
10850 slot = i;
10851 break;
10854 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
10856 if(oldest_time > i_time)
10858 oldest_time = i_time;
10859 oldest_slot = i;
10863 // find oldest
10864 slot = oldest_slot;
10867 RemoveItemFromBuyBackSlot( slot, true );
10868 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
10870 m_items[slot] = pItem;
10871 time_t base = time(NULL);
10872 uint32 etime = uint32(base - m_logintime + (30 * 3600));
10873 uint32 eslot = slot - BUYBACK_SLOT_START;
10875 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
10876 ItemPrototype const *pProto = pItem->GetProto();
10877 if( pProto )
10878 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
10879 else
10880 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10881 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
10883 // move to next (for non filled list is move most optimized choice)
10884 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
10885 ++m_currentBuybackSlot;
10889 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
10891 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
10892 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10893 return m_items[slot];
10894 return NULL;
10897 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
10899 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
10900 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10902 Item *pItem = m_items[slot];
10903 if( pItem )
10905 pItem->RemoveFromWorld();
10906 if(del) pItem->SetState(ITEM_REMOVED, this);
10909 m_items[slot] = NULL;
10911 uint32 eslot = slot - BUYBACK_SLOT_START;
10912 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
10913 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10914 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
10916 // if current backslot is filled set to now free slot
10917 if(m_items[m_currentBuybackSlot])
10918 m_currentBuybackSlot = slot;
10922 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
10924 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
10925 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
10926 data << uint8(msg);
10928 if(msg)
10930 data << uint64(pItem ? pItem->GetGUID() : 0);
10931 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
10932 data << uint8(0); // not 0 there...
10934 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
10936 uint32 level = 0;
10938 if(pItem)
10939 if(ItemPrototype const* proto = pItem->GetProto())
10940 level = proto->RequiredLevel;
10942 data << uint32(level); // new 2.4.0
10945 GetSession()->SendPacket(&data);
10948 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
10950 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
10951 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
10952 data << uint64(pCreature ? pCreature->GetGUID() : 0);
10953 data << uint32(item);
10954 if( param > 0 )
10955 data << uint32(param);
10956 data << uint8(msg);
10957 GetSession()->SendPacket(&data);
10960 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
10962 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
10963 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
10964 data << uint64(pCreature ? pCreature->GetGUID() : 0);
10965 data << uint64(guid);
10966 if( param > 0 )
10967 data << uint32(param);
10968 data << uint8(msg);
10969 GetSession()->SendPacket(&data);
10972 void Player::ClearTrade()
10974 tradeGold = 0;
10975 acceptTrade = false;
10976 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
10977 tradeItems[i] = NULL_SLOT;
10980 void Player::TradeCancel(bool sendback)
10982 if(pTrader)
10984 // send yellow "Trade cancelled" message to both traders
10985 WorldSession* ws;
10986 ws = GetSession();
10987 if(sendback)
10988 ws->SendCancelTrade();
10989 ws = pTrader->GetSession();
10990 if(!ws->PlayerLogout())
10991 ws->SendCancelTrade();
10993 // cleanup
10994 ClearTrade();
10995 pTrader->ClearTrade();
10996 // prevent loss of reference
10997 pTrader->pTrader = NULL;
10998 pTrader = NULL;
11002 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11004 if(m_itemDuration.empty())
11005 return;
11007 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11009 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11011 Item* item = *itr;
11012 ++itr; // current element can be erased in UpdateDuration
11014 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11015 item->UpdateDuration(this,time);
11019 void Player::UpdateEnchantTime(uint32 time)
11021 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11023 assert(itr->item);
11024 next=itr;
11025 if(!itr->item->GetEnchantmentId(itr->slot))
11027 next = m_enchantDuration.erase(itr);
11029 else if(itr->leftduration <= time)
11031 ApplyEnchantment(itr->item,itr->slot,false,false);
11032 itr->item->ClearEnchantment(itr->slot);
11033 next = m_enchantDuration.erase(itr);
11035 else if(itr->leftduration > time)
11037 itr->leftduration -= time;
11038 ++next;
11043 void Player::AddEnchantmentDurations(Item *item)
11045 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11047 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11048 continue;
11050 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11051 if( duration > 0 )
11052 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11056 void Player::RemoveEnchantmentDurations(Item *item)
11058 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11060 if(itr->item == item)
11062 // save duration in item
11063 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11064 itr = m_enchantDuration.erase(itr);
11066 else
11067 ++itr;
11071 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11073 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11074 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11076 next = itr;
11077 if(itr->slot==slot)
11079 if(itr->item && itr->item->GetEnchantmentId(slot))
11081 // remove from stats
11082 ApplyEnchantment(itr->item,slot,false,false);
11083 // remove visual
11084 itr->item->ClearEnchantment(slot);
11086 // remove from update list
11087 next = m_enchantDuration.erase(itr);
11089 else
11090 ++next;
11093 // remove enchants from inventory items
11094 // NOTE: no need to remove these from stats, since these aren't equipped
11095 // in inventory
11096 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11098 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11099 if( pItem && pItem->GetEnchantmentId(slot) )
11100 pItem->ClearEnchantment(slot);
11103 // in inventory bags
11104 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11106 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11107 if( pBag )
11109 ItemPrototype const *pBagProto = pBag->GetProto();
11110 if( pBagProto )
11112 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
11114 Item* pItem = pBag->GetItemByPos(j);
11115 if( pItem && pItem->GetEnchantmentId(slot) )
11116 pItem->ClearEnchantment(slot);
11123 // duration == 0 will remove item enchant
11124 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11126 if(!item)
11127 return;
11129 if(slot >= MAX_ENCHANTMENT_SLOT)
11130 return;
11132 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11134 if(itr->item == item && itr->slot == slot)
11136 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11137 m_enchantDuration.erase(itr);
11138 break;
11141 if(item && duration > 0 )
11143 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11144 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11148 void Player::ApplyEnchantment(Item *item,bool apply)
11150 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11151 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11154 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11156 if(!item)
11157 return;
11159 if(!item->IsEquipped())
11160 return;
11162 if(slot >= MAX_ENCHANTMENT_SLOT)
11163 return;
11165 uint32 enchant_id = item->GetEnchantmentId(slot);
11166 if(!enchant_id)
11167 return;
11169 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11170 if(!pEnchant)
11171 return;
11173 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11174 return;
11176 for (int s=0; s<3; s++)
11178 uint32 enchant_display_type = pEnchant->type[s];
11179 uint32 enchant_amount = pEnchant->amount[s];
11180 uint32 enchant_spell_id = pEnchant->spellid[s];
11182 switch(enchant_display_type)
11184 case ITEM_ENCHANTMENT_TYPE_NONE:
11185 break;
11186 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11187 // processed in Player::CastItemCombatSpell
11188 break;
11189 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11190 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11191 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11192 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11193 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11194 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11195 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11196 break;
11197 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11198 if(enchant_spell_id)
11200 if(apply)
11202 int32 basepoints = int32(enchant_amount);
11203 // Random Property Exist - try found basepoints for spell (basepoints depencs from item suffix factor)
11204 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11206 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11207 if (item_rand)
11209 // Search enchant_amount
11210 for (int k=0; k<3; k++)
11212 if(item_rand->enchant_id[k] == enchant_id)
11214 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11215 break;
11220 // Cast custom spell vs all equal basepoints getted from enchant_amount
11221 if (basepoints)
11222 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11223 else
11224 CastSpell(this,enchant_spell_id,true,item);
11226 else
11227 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11229 break;
11230 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11231 if (!enchant_amount)
11233 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11234 if(item_rand)
11236 for (int k=0; k<3; k++)
11238 if(item_rand->enchant_id[k] == enchant_id)
11240 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11241 break;
11247 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11248 break;
11249 case ITEM_ENCHANTMENT_TYPE_STAT:
11251 if (!enchant_amount)
11253 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11254 if(item_rand_suffix)
11256 for (int k=0; k<3; k++)
11258 if(item_rand_suffix->enchant_id[k] == enchant_id)
11260 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11261 break;
11267 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11268 switch (enchant_spell_id)
11270 case ITEM_MOD_AGILITY:
11271 sLog.outDebug("+ %u AGILITY",enchant_amount);
11272 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11273 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11274 break;
11275 case ITEM_MOD_STRENGTH:
11276 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11277 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11278 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11279 break;
11280 case ITEM_MOD_INTELLECT:
11281 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11282 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11283 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11284 break;
11285 case ITEM_MOD_SPIRIT:
11286 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11287 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11288 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11289 break;
11290 case ITEM_MOD_STAMINA:
11291 sLog.outDebug("+ %u STAMINA",enchant_amount);
11292 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11293 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11294 break;
11295 case ITEM_MOD_DEFENSE_SKILL_RATING:
11296 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11297 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11298 break;
11299 case ITEM_MOD_DODGE_RATING:
11300 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11301 sLog.outDebug("+ %u DODGE", enchant_amount);
11302 break;
11303 case ITEM_MOD_PARRY_RATING:
11304 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11305 sLog.outDebug("+ %u PARRY", enchant_amount);
11306 break;
11307 case ITEM_MOD_BLOCK_RATING:
11308 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11309 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11310 break;
11311 case ITEM_MOD_HIT_MELEE_RATING:
11312 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11313 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11314 break;
11315 case ITEM_MOD_HIT_RANGED_RATING:
11316 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11317 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11318 break;
11319 case ITEM_MOD_HIT_SPELL_RATING:
11320 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11321 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11322 break;
11323 case ITEM_MOD_CRIT_MELEE_RATING:
11324 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11325 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11326 break;
11327 case ITEM_MOD_CRIT_RANGED_RATING:
11328 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11329 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11330 break;
11331 case ITEM_MOD_CRIT_SPELL_RATING:
11332 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11333 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11334 break;
11335 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11336 // in Enchantments
11337 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11338 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11339 // break;
11340 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11341 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11342 // break;
11343 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11344 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11345 // break;
11346 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11347 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11348 // break;
11349 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11350 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11351 // break;
11352 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11353 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11354 // break;
11355 // case ITEM_MOD_HASTE_MELEE_RATING:
11356 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11357 // break;
11358 // case ITEM_MOD_HASTE_RANGED_RATING:
11359 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11360 // break;
11361 case ITEM_MOD_HASTE_SPELL_RATING:
11362 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11363 break;
11364 case ITEM_MOD_HIT_RATING:
11365 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11366 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11367 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11368 sLog.outDebug("+ %u HIT", enchant_amount);
11369 break;
11370 case ITEM_MOD_CRIT_RATING:
11371 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11372 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11373 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11374 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11375 break;
11376 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11377 // case ITEM_MOD_HIT_TAKEN_RATING:
11378 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11379 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11380 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11381 // break;
11382 // case ITEM_MOD_CRIT_TAKEN_RATING:
11383 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11384 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11385 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11386 // break;
11387 case ITEM_MOD_RESILIENCE_RATING:
11388 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11389 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11390 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11391 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11392 break;
11393 case ITEM_MOD_HASTE_RATING:
11394 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11395 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11396 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11397 sLog.outDebug("+ %u HASTE", enchant_amount);
11398 break;
11399 case ITEM_MOD_EXPERTISE_RATING:
11400 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11401 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11402 break;
11403 default:
11404 break;
11406 break;
11408 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11410 if(getClass() == CLASS_SHAMAN)
11412 float addValue = 0.0f;
11413 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11415 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11416 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11418 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11420 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11421 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11424 break;
11426 default:
11427 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11428 break;
11429 } /*switch(enchant_display_type)*/
11430 } /*for*/
11432 // visualize enchantment at player and equipped items
11433 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11435 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11436 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11439 if(apply_dur)
11441 if(apply)
11443 // set duration
11444 uint32 duration = item->GetEnchantmentDuration(slot);
11445 if(duration > 0)
11446 AddEnchantmentDuration(item,slot,duration);
11448 else
11450 // duration == 0 will remove EnchantDuration
11451 AddEnchantmentDuration(item,slot,0);
11456 void Player::SendEnchantmentDurations()
11458 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11460 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11464 void Player::SendItemDurations()
11466 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11468 (*itr)->SendTimeUpdate(this);
11472 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11474 if(!item) // prevent crash
11475 return;
11477 // last check 2.0.10
11478 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11479 data << GetGUID(); // player GUID
11480 data << uint32(received); // 0=looted, 1=from npc
11481 data << uint32(created); // 0=received, 1=created
11482 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11483 data << (uint8)item->GetBagSlot(); // bagslot
11484 // item slot, but when added to stack: 0xFFFFFFFF
11485 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11486 data << uint32(item->GetEntry()); // item id
11487 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11488 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11489 data << uint32(count); // count of items
11490 data << GetItemCount(item->GetEntry()); // count of items in inventory
11492 if (broadcast && GetGroup())
11493 GetGroup()->BroadcastPacket(&data);
11494 else
11495 GetSession()->SendPacket(&data);
11498 /*********************************************************/
11499 /*** QUEST SYSTEM ***/
11500 /*********************************************************/
11502 void Player::PrepareQuestMenu( uint64 guid )
11504 Object *pObject;
11505 QuestRelations* pObjectQR;
11506 QuestRelations* pObjectQIR;
11507 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11508 if( pCreature )
11510 pObject = (Object*)pCreature;
11511 pObjectQR = &objmgr.mCreatureQuestRelations;
11512 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11514 else
11516 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11517 if( pGameObject )
11519 pObject = (Object*)pGameObject;
11520 pObjectQR = &objmgr.mGOQuestRelations;
11521 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11523 else
11524 return;
11527 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11528 qm.ClearMenu();
11530 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11532 uint32 quest_id = i->second;
11533 QuestStatus status = GetQuestStatus( quest_id );
11534 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11535 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11536 else if ( status == QUEST_STATUS_INCOMPLETE )
11537 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11538 else if (status == QUEST_STATUS_AVAILABLE )
11539 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11542 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11544 uint32 quest_id = i->second;
11545 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11546 if(!pQuest) continue;
11548 QuestStatus status = GetQuestStatus( quest_id );
11550 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11551 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11552 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11553 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11557 void Player::SendPreparedQuest( uint64 guid )
11559 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11560 if( questMenu.Empty() )
11561 return;
11563 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11565 uint32 status = qmi0.m_qIcon;
11567 // single element case
11568 if ( questMenu.MenuItemCount() == 1 )
11570 // Auto open -- maybe also should verify there is no greeting
11571 uint32 quest_id = qmi0.m_qId;
11572 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11573 if ( pQuest )
11575 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11576 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11577 else if( status == DIALOG_STATUS_INCOMPLETE )
11578 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11579 // Send completable on repeatable quest if player don't have quest
11580 else if( pQuest->IsRepeatable() )
11581 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11582 else
11583 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11586 // multiply entries
11587 else
11589 QEmote qe;
11590 qe._Delay = 0;
11591 qe._Emote = 0;
11592 std::string title = "";
11593 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11594 if( pCreature )
11596 uint32 textid = pCreature->GetNpcTextId();
11597 GossipText * gossiptext = objmgr.GetGossipText(textid);
11598 if( !gossiptext )
11600 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11601 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11602 title = "";
11604 else
11606 qe = gossiptext->Options[0].Emotes[0];
11608 if(!gossiptext->Options[0].Text_0.empty())
11610 title = gossiptext->Options[0].Text_0;
11612 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11613 if (loc_idx >= 0)
11615 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11616 if (nl)
11618 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11619 title = nl->Text_0[0][loc_idx];
11623 else
11625 title = gossiptext->Options[0].Text_1;
11627 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11628 if (loc_idx >= 0)
11630 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11631 if (nl)
11633 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11634 title = nl->Text_1[0][loc_idx];
11640 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11644 bool Player::IsActiveQuest( uint32 quest_id ) const
11646 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11648 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11651 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11653 Object *pObject;
11654 QuestRelations* pObjectQR;
11655 QuestRelations* pObjectQIR;
11657 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11658 if( pCreature )
11660 pObject = (Object*)pCreature;
11661 pObjectQR = &objmgr.mCreatureQuestRelations;
11662 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11664 else
11666 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11667 if( pGameObject )
11669 pObject = (Object*)pGameObject;
11670 pObjectQR = &objmgr.mGOQuestRelations;
11671 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11673 else
11674 return NULL;
11677 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11678 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11680 if (itr->second == nextQuestID)
11681 return objmgr.GetQuestTemplate(nextQuestID);
11684 return NULL;
11687 bool Player::CanSeeStartQuest( Quest const *pQuest )
11689 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11690 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11691 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11692 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11694 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11697 return false;
11700 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11702 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
11703 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
11704 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
11705 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
11706 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
11707 && SatisfyQuestDay( pQuest, msg );
11710 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
11712 if( !SatisfyQuestLog( msg ) )
11713 return false;
11715 uint32 srcitem = pQuest->GetSrcItemId();
11716 if( srcitem > 0 )
11718 uint32 count = pQuest->GetSrcItemCount();
11719 ItemPosCountVec dest;
11720 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
11722 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11723 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
11724 return true;
11725 else if( msg != EQUIP_ERR_OK )
11727 SendEquipError( msg, NULL, NULL );
11728 return false;
11731 return true;
11734 bool Player::CanCompleteQuest( uint32 quest_id )
11736 if( quest_id )
11738 QuestStatusData& q_status = mQuestStatus[quest_id];
11739 if( q_status.m_status == QUEST_STATUS_COMPLETE )
11740 return false; // not allow re-complete quest
11742 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
11744 if(!qInfo)
11745 return false;
11747 // auto complete quest
11748 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
11749 return true;
11751 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
11754 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11756 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11758 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
11759 return false;
11763 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11765 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11767 if( qInfo->ReqCreatureOrGOId[i] == 0 )
11768 continue;
11770 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
11771 return false;
11775 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
11776 return false;
11778 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
11779 return false;
11781 if ( qInfo->GetRewOrReqMoney() < 0 )
11783 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
11784 return false;
11787 uint32 repFacId = qInfo->GetRepObjectiveFaction();
11788 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
11789 return false;
11791 return true;
11794 return false;
11797 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
11799 // Solve problem that player don't have the quest and try complete it.
11800 // if repeatable she must be able to complete event if player don't have it.
11801 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
11802 if( !CanTakeQuest(pQuest, false) )
11803 return false;
11805 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
11806 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11807 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
11808 return false;
11810 if( !CanRewardQuest(pQuest, false) )
11811 return false;
11813 return true;
11816 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
11818 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
11819 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
11820 return false;
11822 // daily quest can't be rewarded (10 daily quest already completed)
11823 if(!SatisfyQuestDay(pQuest,true))
11824 return false;
11826 // rewarded and not repeatable quest (only cheating case, then ignore without message)
11827 if(GetQuestRewardStatus(pQuest->GetQuestId()))
11828 return false;
11830 // prevent receive reward with quest items in bank
11831 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11833 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11835 if( pQuest->ReqItemCount[i]!= 0 &&
11836 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
11838 if(msg)
11839 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
11840 return false;
11845 // prevent receive reward with low money and GetRewOrReqMoney() < 0
11846 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
11847 return false;
11849 return true;
11852 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
11854 // prevent receive reward with quest items in bank or for not completed quest
11855 if(!CanRewardQuest(pQuest,msg))
11856 return false;
11858 if ( pQuest->GetRewChoiceItemsCount() > 0 )
11860 if( pQuest->RewChoiceItemId[reward] )
11862 ItemPosCountVec dest;
11863 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
11864 if( res != EQUIP_ERR_OK )
11866 SendEquipError( res, NULL, NULL );
11867 return false;
11872 if ( pQuest->GetRewItemsCount() > 0 )
11874 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
11876 if( pQuest->RewItemId[i] )
11878 ItemPosCountVec dest;
11879 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
11880 if( res != EQUIP_ERR_OK )
11882 SendEquipError( res, NULL, NULL );
11883 return false;
11889 return true;
11892 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
11894 uint16 log_slot = FindQuestSlot( 0 );
11895 assert(log_slot < MAX_QUEST_LOG_SIZE);
11897 uint32 quest_id = pQuest->GetQuestId();
11899 // if not exist then created with set uState==NEW and rewarded=false
11900 QuestStatusData& questStatusData = mQuestStatus[quest_id];
11901 if (questStatusData.uState != QUEST_NEW)
11902 questStatusData.uState = QUEST_CHANGED;
11904 // check for repeatable quests status reset
11905 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
11906 questStatusData.m_explored = false;
11908 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11910 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11911 questStatusData.m_itemcount[i] = 0;
11914 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11916 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11917 questStatusData.m_creatureOrGOcount[i] = 0;
11920 GiveQuestSourceItem( pQuest );
11921 AdjustQuestReqItemCount( pQuest );
11923 if( pQuest->GetRepObjectiveFaction() )
11924 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
11926 uint32 qtime = 0;
11927 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
11929 uint32 limittime = pQuest->GetLimitTime();
11931 // shared timed quest
11932 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
11933 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
11935 AddTimedQuest( quest_id );
11936 questStatusData.m_timer = limittime * 1000;
11937 qtime = static_cast<uint32>(time(NULL)) + limittime;
11939 else
11940 questStatusData.m_timer = 0;
11942 SetQuestSlot(log_slot, quest_id, qtime);
11944 //starting initial quest script
11945 if(questGiver && pQuest->GetQuestStartScript()!=0)
11946 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
11948 UpdateForQuestsGO();
11951 void Player::CompleteQuest( uint32 quest_id )
11953 if( quest_id )
11955 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
11957 uint16 log_slot = FindQuestSlot( quest_id );
11958 if( log_slot < MAX_QUEST_LOG_SIZE)
11959 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
11961 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
11963 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
11964 RewardQuest(qInfo,0,this,false);
11965 else
11966 SendQuestComplete( quest_id );
11971 void Player::IncompleteQuest( uint32 quest_id )
11973 if( quest_id )
11975 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
11977 uint16 log_slot = FindQuestSlot( quest_id );
11978 if( log_slot < MAX_QUEST_LOG_SIZE)
11979 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
11983 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
11985 uint32 quest_id = pQuest->GetQuestId();
11987 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
11989 if ( pQuest->ReqItemId[i] )
11990 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
11993 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
11994 // SetTimedQuest( 0 );
11995 m_timedquests.erase(pQuest->GetQuestId());
11997 if ( pQuest->GetRewChoiceItemsCount() > 0 )
11999 if( pQuest->RewChoiceItemId[reward] )
12001 ItemPosCountVec dest;
12002 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12004 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12005 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12010 if ( pQuest->GetRewItemsCount() > 0 )
12012 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12014 if( pQuest->RewItemId[i] )
12016 ItemPosCountVec dest;
12017 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12019 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12020 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12026 RewardReputation( pQuest );
12028 if( pQuest->GetRewSpellCast() > 0 )
12029 CastSpell( this, pQuest->GetRewSpellCast(), true);
12030 else if( pQuest->GetRewSpell() > 0)
12031 CastSpell( this, pQuest->GetRewSpell(), true);
12033 uint16 log_slot = FindQuestSlot( quest_id );
12034 if( log_slot < MAX_QUEST_LOG_SIZE)
12035 SetQuestSlot(log_slot,0);
12037 QuestStatusData& q_status = mQuestStatus[quest_id];
12039 // Not give XP in case already completed once repeatable quest
12040 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12042 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12043 GiveXP( XP , NULL );
12044 else
12045 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12047 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12048 ModifyMoney( pQuest->GetRewOrReqMoney() );
12050 // honor reward
12051 if(pQuest->GetRewHonorableKills())
12052 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12054 // title reward
12055 if(pQuest->GetCharTitleId())
12057 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12058 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12061 // Send reward mail
12062 if(pQuest->GetRewMailTemplateId())
12064 MailMessageType mailType;
12065 uint32 senderGuidOrEntry;
12066 switch(questGiver->GetTypeId())
12068 case TYPEID_UNIT:
12069 mailType = MAIL_CREATURE;
12070 senderGuidOrEntry = questGiver->GetEntry();
12071 break;
12072 case TYPEID_GAMEOBJECT:
12073 mailType = MAIL_GAMEOBJECT;
12074 senderGuidOrEntry = questGiver->GetEntry();
12075 break;
12076 case TYPEID_ITEM:
12077 mailType = MAIL_ITEM;
12078 senderGuidOrEntry = questGiver->GetEntry();
12079 break;
12080 case TYPEID_PLAYER:
12081 mailType = MAIL_NORMAL;
12082 senderGuidOrEntry = questGiver->GetGUIDLow();
12083 break;
12084 default:
12085 mailType = MAIL_NORMAL;
12086 senderGuidOrEntry = GetGUIDLow();
12087 break;
12090 Loot questMailLoot;
12092 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12094 // fill mail
12095 MailItemsInfo mi; // item list preparing
12097 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12099 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12101 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12103 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12104 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12109 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12111 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12113 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12115 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12116 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12121 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12124 if(pQuest->IsDaily())
12125 SetDailyQuestStatus(quest_id);
12127 if ( !pQuest->IsRepeatable() )
12128 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12129 else
12130 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12132 q_status.m_rewarded = true;
12134 if(announce)
12135 SendQuestReward( pQuest, XP, questGiver );
12137 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12140 void Player::FailQuest( uint32 quest_id )
12142 if( quest_id )
12144 IncompleteQuest( quest_id );
12146 uint16 log_slot = FindQuestSlot( quest_id );
12147 if( log_slot < MAX_QUEST_LOG_SIZE)
12149 SetQuestSlotTimer(log_slot, 1 );
12150 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12152 SendQuestFailed( quest_id );
12156 void Player::FailTimedQuest( uint32 quest_id )
12158 if( quest_id )
12160 QuestStatusData& q_status = mQuestStatus[quest_id];
12162 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12163 q_status.m_timer = 0;
12165 IncompleteQuest( quest_id );
12167 uint16 log_slot = FindQuestSlot( quest_id );
12168 if( log_slot < MAX_QUEST_LOG_SIZE)
12170 SetQuestSlotTimer(log_slot, 1 );
12171 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12173 SendQuestTimerFailed( quest_id );
12177 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12179 int32 zoneOrSort = qInfo->GetZoneOrSort();
12180 int32 skillOrClass = qInfo->GetSkillOrClass();
12182 // skip zone zoneOrSort and 0 case skillOrClass
12183 if( zoneOrSort >= 0 && skillOrClass == 0 )
12184 return true;
12186 int32 questSort = -zoneOrSort;
12187 uint8 reqSortClass = ClassByQuestSort(questSort);
12189 // check class sort cases in zoneOrSort
12190 if( reqSortClass != 0 && getClass() != reqSortClass)
12192 if( msg )
12193 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12194 return false;
12197 // check class
12198 if( skillOrClass < 0 )
12200 uint8 reqClass = -int32(skillOrClass);
12201 if(getClass() != reqClass)
12203 if( msg )
12204 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12205 return false;
12208 // check skill
12209 else if( skillOrClass > 0 )
12211 uint32 reqSkill = skillOrClass;
12212 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12214 if( msg )
12215 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12216 return false;
12220 return true;
12223 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12225 if( getLevel() < qInfo->GetMinLevel() )
12227 if( msg )
12228 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12229 return false;
12231 return true;
12234 bool Player::SatisfyQuestLog( bool msg )
12236 // exist free slot
12237 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12238 return true;
12240 if( msg )
12242 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12243 GetSession()->SendPacket( &data );
12244 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12246 return false;
12249 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12251 // No previous quest (might be first quest in a series)
12252 if( qInfo->prevQuests.empty())
12253 return true;
12255 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12257 uint32 prevId = abs(*iter);
12259 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12260 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12262 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12264 // If any of the positive previous quests completed, return true
12265 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12267 // skip one-from-all exclusive group
12268 if(qPrevInfo->GetExclusiveGroup() >= 0)
12269 return true;
12271 // each-from-all exclusive group ( < 0)
12272 // can be start if only all quests in prev quest exclusive group complited and rewarded
12273 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12274 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12276 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12278 for(; iter != end; ++iter)
12280 uint32 exclude_Id = iter->second;
12282 // skip checked quest id, only state of other quests in group is interesting
12283 if(exclude_Id == prevId)
12284 continue;
12286 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12288 // alternative quest from group also must be completed and rewarded(reported)
12289 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12291 if( msg )
12292 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12293 return false;
12296 return true;
12298 // If any of the negative previous quests active, return true
12299 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12300 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12302 // skip one-from-all exclusive group
12303 if(qPrevInfo->GetExclusiveGroup() >= 0)
12304 return true;
12306 // each-from-all exclusive group ( < 0)
12307 // can be start if only all quests in prev quest exclusive group active
12308 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12309 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12311 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12313 for(; iter != end; ++iter)
12315 uint32 exclude_Id = iter->second;
12317 // skip checked quest id, only state of other quests in group is interesting
12318 if(exclude_Id == prevId)
12319 continue;
12321 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12323 // alternative quest from group also must be active
12324 if( i_exstatus == mQuestStatus.end() ||
12325 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12326 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12328 if( msg )
12329 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12330 return false;
12333 return true;
12338 // Has only positive prev. quests in non-rewarded state
12339 // and negative prev. quests in non-active state
12340 if( msg )
12341 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12343 return false;
12346 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12348 uint32 reqraces = qInfo->GetRequiredRaces();
12349 if ( reqraces == 0 )
12350 return true;
12351 if( (reqraces & getRaceMask()) == 0 )
12353 if( msg )
12354 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12355 return false;
12357 return true;
12360 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12362 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12363 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12365 if( msg )
12366 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12367 return false;
12370 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12371 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12373 if( msg )
12374 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12375 return false;
12378 return true;
12381 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12383 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12384 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12386 if( msg )
12387 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12388 return false;
12390 return true;
12393 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12395 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12397 if( msg )
12398 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12399 return false;
12401 return true;
12404 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12406 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12407 if(qInfo->GetExclusiveGroup() <= 0)
12408 return true;
12410 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12411 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12413 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12415 for(; iter != end; ++iter)
12417 uint32 exclude_Id = iter->second;
12419 // skip checked quest id, only state of other quests in group is interesting
12420 if(exclude_Id == qInfo->GetQuestId())
12421 continue;
12423 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12425 // alternative quest already started or completed
12426 if( i_exstatus != mQuestStatus.end()
12427 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12429 if( msg )
12430 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12431 return false;
12434 return true;
12437 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12439 if(!qInfo->GetNextQuestInChain())
12440 return true;
12442 // next quest in chain already started or completed
12443 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12444 if( itr != mQuestStatus.end()
12445 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12447 if( msg )
12448 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12449 return false;
12452 // check for all quests further up the chain
12453 // only necessary if there are quest chains with more than one quest that can be skipped
12454 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12455 return true;
12458 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12460 // No previous quest in chain
12461 if( qInfo->prevChainQuests.empty())
12462 return true;
12464 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12466 uint32 prevId = *iter;
12468 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12470 if( i_prevstatus != mQuestStatus.end() )
12472 // If any of the previous quests in chain active, return false
12473 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12474 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12476 if( msg )
12477 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12478 return false;
12482 // check for all quests further down the chain
12483 // only necessary if there are quest chains with more than one quest that can be skipped
12484 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12485 // return false;
12488 // No previous quest in chain active
12489 return true;
12492 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12494 if(!qInfo->IsDaily())
12495 return true;
12497 bool have_slot = false;
12498 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12500 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12501 if(qInfo->GetQuestId()==id)
12502 return false;
12504 if(!id)
12505 have_slot = true;
12508 if(!have_slot)
12510 if( msg )
12511 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12512 return false;
12515 return true;
12518 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12520 uint32 srcitem = pQuest->GetSrcItemId();
12521 if( srcitem > 0 )
12523 uint32 count = pQuest->GetSrcItemCount();
12524 if( count <= 0 )
12525 count = 1;
12527 ItemPosCountVec dest;
12528 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12529 if( msg == EQUIP_ERR_OK )
12531 Item * item = StoreNewItem(dest, srcitem, true);
12532 SendNewItem(item, count, true, false);
12533 return true;
12535 // player already have max amount required item, just report success
12536 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12537 return true;
12538 else
12539 SendEquipError( msg, NULL, NULL );
12540 return false;
12543 return true;
12546 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12548 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12549 if( qInfo )
12551 uint32 srcitem = qInfo->GetSrcItemId();
12552 if( srcitem > 0 )
12554 uint32 count = qInfo->GetSrcItemCount();
12555 if( count <= 0 )
12556 count = 1;
12558 // exist one case when destroy source quest item not possible:
12559 // non un-equippable item (equipped non-empty bag, for example)
12560 uint8 res = CanUnequipItems(srcitem,count);
12561 if(res != EQUIP_ERR_OK)
12563 if(msg)
12564 SendEquipError( res, NULL, NULL );
12565 return false;
12568 DestroyItemCount(srcitem, count, true, true);
12571 return true;
12574 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12576 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12577 if( qInfo )
12579 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12580 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12581 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12582 && !qInfo->IsRepeatable() )
12583 return itr->second.m_rewarded;
12585 return false;
12587 return false;
12590 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12592 if( quest_id )
12594 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12595 if( itr != mQuestStatus.end() )
12596 return itr->second.m_status;
12598 return QUEST_STATUS_NONE;
12601 bool Player::CanShareQuest(uint32 quest_id) const
12603 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12604 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12606 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12607 if( itr != mQuestStatus.end() )
12608 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12610 return false;
12613 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12615 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12616 if( qInfo )
12618 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12620 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12621 m_timedquests.erase(qInfo->GetQuestId());
12624 QuestStatusData& q_status = mQuestStatus[quest_id];
12626 q_status.m_status = status;
12627 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12630 UpdateForQuestsGO();
12633 // not used in MaNGOS, but used in scripting code
12634 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12636 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12637 if( !qInfo )
12638 return 0;
12640 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12641 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12642 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12644 return 0;
12647 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12649 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12651 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12653 uint32 reqitemcount = pQuest->ReqItemCount[i];
12654 if( reqitemcount != 0 )
12656 uint32 quest_id = pQuest->GetQuestId();
12657 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12659 QuestStatusData& q_status = mQuestStatus[quest_id];
12660 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12661 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12667 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12669 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12670 if ( GetQuestSlotQuestId(i) == quest_id )
12671 return i;
12673 return MAX_QUEST_LOG_SIZE;
12676 void Player::AreaExploredOrEventHappens( uint32 questId )
12678 if( questId )
12680 uint16 log_slot = FindQuestSlot( questId );
12681 if( log_slot < MAX_QUEST_LOG_SIZE)
12683 QuestStatusData& q_status = mQuestStatus[questId];
12685 if(!q_status.m_explored)
12687 q_status.m_explored = true;
12688 if (q_status.uState != QUEST_NEW)
12689 q_status.uState = QUEST_CHANGED;
12692 if( CanCompleteQuest( questId ) )
12693 CompleteQuest( questId );
12697 //not used in mangosd, function for external script library
12698 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
12700 if( Group *pGroup = GetGroup() )
12702 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
12704 Player *pGroupGuy = itr->getSource();
12706 // for any leave or dead (with not released body) group member at appropriate distance
12707 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
12708 pGroupGuy->AreaExploredOrEventHappens(questId);
12711 else
12712 AreaExploredOrEventHappens(questId);
12715 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
12717 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12719 uint32 questid = GetQuestSlotQuestId(i);
12720 if ( questid == 0 )
12721 continue;
12723 QuestStatusData& q_status = mQuestStatus[questid];
12725 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
12726 continue;
12728 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12729 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12730 continue;
12732 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12734 uint32 reqitem = qInfo->ReqItemId[j];
12735 if ( reqitem == entry )
12737 uint32 reqitemcount = qInfo->ReqItemCount[j];
12738 uint32 curitemcount = q_status.m_itemcount[j];
12739 if ( curitemcount < reqitemcount )
12741 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
12742 q_status.m_itemcount[j] += additemcount;
12743 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12745 SendQuestUpdateAddItem( qInfo, j, additemcount );
12747 if ( CanCompleteQuest( questid ) )
12748 CompleteQuest( questid );
12749 return;
12753 UpdateForQuestsGO();
12756 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
12758 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12760 uint32 questid = GetQuestSlotQuestId(i);
12761 if(!questid)
12762 continue;
12763 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12764 if ( !qInfo )
12765 continue;
12766 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12767 continue;
12769 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12771 uint32 reqitem = qInfo->ReqItemId[j];
12772 if ( reqitem == entry )
12774 QuestStatusData& q_status = mQuestStatus[questid];
12776 uint32 reqitemcount = qInfo->ReqItemCount[j];
12777 uint32 curitemcount;
12778 if( q_status.m_status != QUEST_STATUS_COMPLETE )
12779 curitemcount = q_status.m_itemcount[j];
12780 else
12781 curitemcount = GetItemCount(entry,true);
12782 if ( curitemcount < reqitemcount + count )
12784 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
12785 q_status.m_itemcount[j] = curitemcount - remitemcount;
12786 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12788 IncompleteQuest( questid );
12790 return;
12794 UpdateForQuestsGO();
12797 void Player::KilledMonster( uint32 entry, uint64 guid )
12799 uint32 addkillcount = 1;
12800 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12802 uint32 questid = GetQuestSlotQuestId(i);
12803 if(!questid)
12804 continue;
12806 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12807 if( !qInfo )
12808 continue;
12809 // just if !ingroup || !noraidgroup || raidgroup
12810 QuestStatusData& q_status = mQuestStatus[questid];
12811 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
12813 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
12815 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12817 // skip GO activate objective or none
12818 if(qInfo->ReqCreatureOrGOId[j] <=0)
12819 continue;
12821 // skip Cast at creature objective
12822 if(qInfo->ReqSpell[j] !=0 )
12823 continue;
12825 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
12827 if ( reqkill == entry )
12829 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
12830 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
12831 if ( curkillcount < reqkillcount )
12833 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
12834 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12836 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
12838 if ( CanCompleteQuest( questid ) )
12839 CompleteQuest( questid );
12841 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12842 continue;
12850 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
12852 bool isCreature = IS_CREATURE_GUID(guid);
12854 uint32 addCastCount = 1;
12855 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12857 uint32 questid = GetQuestSlotQuestId(i);
12858 if(!questid)
12859 continue;
12861 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12862 if ( !qInfo )
12863 continue;
12865 QuestStatusData& q_status = mQuestStatus[questid];
12867 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12869 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
12871 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12873 // skip kill creature objective (0) or wrong spell casts
12874 if(qInfo->ReqSpell[j] != spell_id )
12875 continue;
12877 uint32 reqTarget = 0;
12879 if(isCreature)
12881 // creature activate objectives
12882 if(qInfo->ReqCreatureOrGOId[j] > 0)
12883 // checked at quest_template loading
12884 reqTarget = qInfo->ReqCreatureOrGOId[j];
12886 else
12888 // GO activate objective
12889 if(qInfo->ReqCreatureOrGOId[j] < 0)
12890 // checked at quest_template loading
12891 reqTarget = - qInfo->ReqCreatureOrGOId[j];
12894 // other not this creature/GO related objectives
12895 if( reqTarget != entry )
12896 continue;
12898 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
12899 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
12900 if ( curCastCount < reqCastCount )
12902 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
12903 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12905 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
12908 if ( CanCompleteQuest( questid ) )
12909 CompleteQuest( questid );
12911 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12912 break;
12919 void Player::TalkedToCreature( uint32 entry, uint64 guid )
12921 uint32 addTalkCount = 1;
12922 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12924 uint32 questid = GetQuestSlotQuestId(i);
12925 if(!questid)
12926 continue;
12928 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12929 if ( !qInfo )
12930 continue;
12932 QuestStatusData& q_status = mQuestStatus[questid];
12934 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12936 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
12938 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12940 // skip spell casts and Gameobject objectives
12941 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
12942 continue;
12944 uint32 reqTarget = 0;
12946 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
12947 // checked at quest_template loading
12948 reqTarget = qInfo->ReqCreatureOrGOId[j];
12949 else
12950 continue;
12952 if ( reqTarget == entry )
12954 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
12955 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
12956 if ( curTalkCount < reqTalkCount )
12958 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
12959 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12961 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
12963 if ( CanCompleteQuest( questid ) )
12964 CompleteQuest( questid );
12966 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12967 continue;
12975 void Player::MoneyChanged( uint32 count )
12977 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12979 uint32 questid = GetQuestSlotQuestId(i);
12980 if (!questid)
12981 continue;
12983 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12984 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
12986 QuestStatusData& q_status = mQuestStatus[questid];
12988 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12990 if(int32(count) >= -qInfo->GetRewOrReqMoney())
12992 if ( CanCompleteQuest( questid ) )
12993 CompleteQuest( questid );
12996 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
12998 if(int32(count) < -qInfo->GetRewOrReqMoney())
12999 IncompleteQuest( questid );
13005 bool Player::HasQuestForItem( uint32 itemid ) const
13007 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13009 QuestStatusData const& q_status = i->second;
13011 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13013 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13014 if(!qinfo)
13015 continue;
13017 // hide quest if player is in raid-group and quest is no raid quest
13018 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13019 continue;
13021 // There should be no mixed ReqItem/ReqSource drop
13022 // This part for ReqItem drop
13023 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13025 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13026 return true;
13028 // This part - for ReqSource
13029 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13031 // examined item is a source item
13032 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13034 uint32 idx = qinfo->ReqSourceRef[j]-1;
13036 // total count of created ReqItems and SourceItems is less than ReqItemCount
13037 if(qinfo->ReqItemId[idx] != 0 &&
13038 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13039 return true;
13041 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13042 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13044 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13045 return true;
13047 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13048 else if(qinfo->ReqSpell[idx] != 0)
13050 // not casted and need more reagents/item for use.
13051 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13052 return true;
13058 return false;
13061 void Player::SendQuestComplete( uint32 quest_id )
13063 if( quest_id )
13065 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13066 data << quest_id;
13067 GetSession()->SendPacket( &data );
13068 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13072 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13074 uint32 questid = pQuest->GetQuestId();
13075 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13076 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4+4+pQuest->GetRewItemsCount()*8) );
13077 data << questid;
13078 data << uint32(0x03);
13080 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13082 data << XP;
13083 data << uint32(pQuest->GetRewOrReqMoney());
13085 else
13087 data << uint32(0);
13088 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13090 data << uint32(0); // new 2.3.0, HonorPoints?
13091 data << uint32( pQuest->GetRewItemsCount() ); // max is 5
13093 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13095 if ( pQuest->RewItemId[i] > 0 )
13096 data << pQuest->RewItemId[i] << pQuest->RewItemCount[i];
13097 else
13098 data << uint32(0) << uint32(0);
13100 GetSession()->SendPacket( &data );
13102 if (pQuest->GetQuestCompleteScript() != 0)
13103 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13106 void Player::SendQuestFailed( uint32 quest_id )
13108 if( quest_id )
13110 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4 );
13111 data << quest_id;
13112 GetSession()->SendPacket( &data );
13113 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13117 void Player::SendQuestTimerFailed( uint32 quest_id )
13119 if( quest_id )
13121 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13122 data << quest_id;
13123 GetSession()->SendPacket( &data );
13124 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13128 void Player::SendCanTakeQuestResponse( uint32 msg )
13130 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13131 data << uint32(msg);
13132 GetSession()->SendPacket( &data );
13133 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13136 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13138 if( pPlayer )
13140 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13141 data << uint64(pPlayer->GetGUID());
13142 data << uint8(msg); // valid values: 0-8
13143 GetSession()->SendPacket( &data );
13144 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13148 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13150 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, (4+4) );
13151 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13152 data << pQuest->ReqItemId[item_idx];
13153 data << count;
13154 GetSession()->SendPacket( &data );
13157 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13159 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13161 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13162 if (entry < 0)
13163 // client expected gameobject template id in form (id|0x80000000)
13164 entry = (-entry) | 0x80000000;
13166 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13167 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13168 data << uint32(pQuest->GetQuestId());
13169 data << uint32(entry);
13170 data << uint32(old_count + add_count);
13171 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13172 data << uint64(guid);
13173 GetSession()->SendPacket(&data);
13175 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13176 if( log_slot < MAX_QUEST_LOG_SIZE)
13177 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13180 /*********************************************************/
13181 /*** LOAD SYSTEM ***/
13182 /*********************************************************/
13184 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13186 bool delete_result = true;
13187 if(!result)
13189 // 0 1 2 3 4 5 6 7 8
13190 result = CharacterDatabase.PQuery("SELECT data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13191 if(!result) return false;
13193 else delete_result = false;
13195 Field *fields = result->Fetch();
13197 if(!LoadValues( fields[0].GetString()))
13199 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13200 if(delete_result) delete result;
13201 return false;
13204 // overwrite possible wrong/corrupted guid
13205 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13207 m_name = fields[1].GetCppString();
13209 Relocate(fields[2].GetFloat(),fields[3].GetFloat(),fields[4].GetFloat());
13210 SetMapId(fields[5].GetUInt32());
13211 // the instance id is not needed at character enum
13213 m_Played_time[0] = fields[6].GetUInt32();
13214 m_Played_time[1] = fields[7].GetUInt32();
13216 m_atLoginFlags = fields[8].GetUInt32();
13218 // I don't see these used anywhere ..
13219 /*_LoadGroup();
13221 _LoadBoundInstances();*/
13223 if (delete_result) delete result;
13225 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13226 m_items[i] = NULL;
13228 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13229 m_deathState = DEAD;
13231 return true;
13234 void Player::_LoadDeclinedNames(QueryResult* result)
13236 if(!result)
13237 return;
13239 if(m_declinedname)
13240 delete m_declinedname;
13242 m_declinedname = new DeclinedName;
13243 Field *fields = result->Fetch();
13244 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13245 m_declinedname->name[i] = fields[i].GetCppString();
13247 delete result;
13250 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13252 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13253 if(!result)
13254 return false;
13256 Field *fields = result->Fetch();
13258 x = fields[0].GetFloat();
13259 y = fields[1].GetFloat();
13260 z = fields[2].GetFloat();
13261 o = fields[3].GetFloat();
13262 mapid = fields[4].GetUInt32();
13263 in_flight = !fields[5].GetCppString().empty();
13265 delete result;
13266 return true;
13269 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13271 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13272 if( !result )
13273 return false;
13275 Field *fields = result->Fetch();
13277 data = StrSplit(fields[0].GetCppString(), " ");
13279 delete result;
13281 return true;
13284 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13286 if(index >= data.size())
13287 return 0;
13289 return (uint32)atoi(data[index].c_str());
13292 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13294 float result;
13295 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13296 memcpy(&result, &temp, sizeof(result));
13298 return result;
13301 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13303 Tokens data;
13304 if(!LoadValuesArrayFromDB(data,guid))
13305 return 0;
13307 return GetUInt32ValueFromArray(data,index);
13310 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13312 float result;
13313 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13314 memcpy(&result, &temp, sizeof(result));
13316 return result;
13319 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13321 //// 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
13322 //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);
13323 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13325 if(!result)
13327 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13328 return false;
13331 Field *fields = result->Fetch();
13333 uint32 dbAccountId = fields[1].GetUInt32();
13335 // check if the character's account in the db and the logged in account match.
13336 // player should be able to load/delete character only with correct account!
13337 if( dbAccountId != GetSession()->GetAccountId() )
13339 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13340 delete result;
13341 return false;
13344 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13346 m_name = fields[3].GetCppString();
13348 // check name limitations
13349 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13351 delete result;
13352 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13353 return false;
13356 if(!LoadValues( fields[2].GetString()))
13358 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13359 delete result;
13360 return false;
13363 // overwrite possible wrong/corrupted guid
13364 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13366 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13367 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13369 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13370 SetVisibleItemSlot(slot,NULL);
13372 if (m_items[slot])
13374 delete m_items[slot];
13375 m_items[slot] = NULL;
13379 // update money limits
13380 if(GetMoney() > MAX_MONEY_AMOUNT)
13381 SetMoney(MAX_MONEY_AMOUNT);
13383 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13384 outDebugValues();
13386 m_race = fields[4].GetUInt8();
13387 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13388 //Other way is to saves m_team into characters table.
13389 setFactionForRace(m_race);
13390 SetCharm(0);
13392 m_class = fields[5].GetUInt8();
13394 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13395 if(!info)
13397 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13398 delete result;
13399 return false;
13402 InitPrimaryProffesions(); // to max set before any spell loaded
13404 uint32 transGUID = fields[24].GetUInt32();
13405 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13406 SetMapId(fields[9].GetUInt32());
13407 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13409 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13411 // check arena teams integrity
13412 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13414 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13415 if(!arena_team_id)
13416 continue;
13418 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13419 if(at->HaveMember(GetGUID()))
13420 continue;
13422 // arena team not exist or not member, cleanup fields
13423 for(int j =0; j < 6; ++j)
13424 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13427 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13429 if(!IsPositionValid())
13431 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());
13433 SetMapId(info->mapId);
13434 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13436 transGUID = 0;
13438 m_movementInfo.t_x = 0.0f;
13439 m_movementInfo.t_y = 0.0f;
13440 m_movementInfo.t_z = 0.0f;
13441 m_movementInfo.t_o = 0.0f;
13444 // load the player's map here if it's not already loaded
13445 Map *map = GetMap();
13446 // since the player may not be bound to the map yet, make sure subsequent
13447 // getmap calls won't create new maps
13448 SetInstanceId(map->GetInstanceId());
13450 SaveRecallPosition();
13452 if (transGUID != 0)
13454 m_movementInfo.t_x = fields[20].GetFloat();
13455 m_movementInfo.t_y = fields[21].GetFloat();
13456 m_movementInfo.t_z = fields[22].GetFloat();
13457 m_movementInfo.t_o = fields[23].GetFloat();
13459 if( !MaNGOS::IsValidMapCoord(
13460 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13461 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13462 // transport size limited
13463 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13465 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13466 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13467 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13469 SetMapId(info->mapId);
13470 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13472 m_movementInfo.t_x = 0.0f;
13473 m_movementInfo.t_y = 0.0f;
13474 m_movementInfo.t_z = 0.0f;
13475 m_movementInfo.t_o = 0.0f;
13477 transGUID = 0;
13481 if (transGUID != 0)
13483 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13485 if( (*iter)->GetGUIDLow() == transGUID)
13487 m_transport = *iter;
13488 m_transport->AddPassenger(this);
13489 SetMapId(m_transport->GetMapId());
13490 break;
13494 if(!m_transport)
13496 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13497 guid,transGUID);
13499 SetMapId(info->mapId);
13500 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13502 m_movementInfo.t_x = 0.0f;
13503 m_movementInfo.t_y = 0.0f;
13504 m_movementInfo.t_z = 0.0f;
13505 m_movementInfo.t_o = 0.0f;
13507 transGUID = 0;
13511 time_t now = time(NULL);
13512 time_t logoutTime = time_t(fields[16].GetUInt64());
13514 // since last logout (in seconds)
13515 uint64 time_diff = uint64(now - logoutTime);
13517 // set value, including drunk invisibility detection
13518 // calculate sobering. after 15 minutes logged out, the player will be sober again
13519 float soberFactor;
13520 if(time_diff > 15*MINUTE)
13521 soberFactor = 0;
13522 else
13523 soberFactor = 1-time_diff/(15.0f*MINUTE);
13524 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13525 SetDrunkValue(newDrunkenValue);
13527 m_rest_bonus = fields[15].GetFloat();
13528 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13529 float bubble0 = 0.031;
13530 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13531 float bubble1 = 0.125;
13533 if((int32)fields[16].GetUInt32() > 0)
13535 float bubble = fields[17].GetUInt32() > 0
13536 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13537 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13539 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13542 m_cinematic = fields[12].GetUInt32();
13543 m_Played_time[0]= fields[13].GetUInt32();
13544 m_Played_time[1]= fields[14].GetUInt32();
13546 m_resetTalentsCost = fields[18].GetUInt32();
13547 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13549 // reserve some flags
13550 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13552 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13553 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13555 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13557 uint32 extraflags = fields[25].GetUInt32();
13559 m_stableSlots = fields[26].GetUInt32();
13560 if(m_stableSlots > 2)
13562 sLog.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots));
13563 m_stableSlots = 2;
13566 m_atLoginFlags = fields[27].GetUInt32();
13568 // Honor system
13569 // Update Honor kills data
13570 m_lastHonorUpdateTime = logoutTime;
13571 UpdateHonorFields();
13573 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13574 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13575 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13577 std::string taxi_nodes = fields[31].GetCppString();
13579 delete result;
13581 // clear channel spell data (if saved at channel spell casting)
13582 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13583 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13585 // clear charm/summon related fields
13586 SetUInt64Value(UNIT_FIELD_CHARM,0);
13587 SetUInt64Value(UNIT_FIELD_SUMMON,0);
13588 SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
13589 SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
13590 SetUInt64Value(UNIT_FIELD_CREATEDBY,0);
13592 // reset some aura modifiers before aura apply
13593 SetUInt64Value(PLAYER_FARSIGHT, 0);
13594 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
13595 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
13597 // reset skill modifiers and set correct unlearn flags
13598 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
13600 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
13602 // set correct unlearn bit
13603 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
13604 if(!id) continue;
13606 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
13607 if(!pSkill) continue;
13609 // enable unlearn button for primary professions only
13610 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
13611 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
13612 else
13613 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
13616 // make sure the unit is considered out of combat for proper loading
13617 ClearInCombat();
13619 // make sure the unit is considered not in duel for proper loading
13620 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
13621 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
13623 // remember loaded power/health values to restore after stats initialization and modifier applying
13624 uint32 savedHealth = GetHealth();
13625 uint32 savedPower[MAX_POWERS];
13626 for(uint32 i = 0; i < MAX_POWERS; ++i)
13627 savedPower[i] = GetPower(Powers(i));
13629 // reset stats before loading any modifiers
13630 InitStatsForLevel();
13631 InitTaxiNodesForLevel();
13633 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13635 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13636 //_LoadMail();
13638 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
13640 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13641 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13642 m_deathState = DEAD;
13644 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
13646 // after spell load
13647 InitTalentForLevel();
13648 learnSkillRewardedSpells();
13650 // after spell load, learn rewarded spell if need also
13651 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
13652 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
13654 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
13656 // must be before inventory (some items required reputation check)
13657 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
13659 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
13661 // update items with duration and realtime
13662 UpdateItemDuration(time_diff, true);
13664 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
13666 // unread mails and next delivery time, actual mails not loaded
13667 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
13669 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
13671 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13672 return false;
13674 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13675 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13676 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
13678 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << curTitle))
13679 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
13682 // Not finish taxi flight path
13683 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
13685 // problems with taxi path loading
13686 TaxiNodesEntry const* nodeEntry = NULL;
13687 if(uint32 node_id = m_taxi.GetTaxiSource())
13688 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13690 if(!nodeEntry) // don't know taxi start node, to homebind
13692 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13693 SetMapId(m_homebindMapId);
13694 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
13695 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13697 else // have start node, to it
13699 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13700 SetMapId(nodeEntry->map_id);
13701 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
13702 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13704 m_taxi.ClearTaxiDestinations();
13706 else if(uint32 node_id = m_taxi.GetTaxiSource())
13708 // save source node as recall coord to prevent recall and fall from sky
13709 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13710 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
13711 m_recallMap = nodeEntry->map_id;
13712 m_recallX = nodeEntry->x;
13713 m_recallY = nodeEntry->y;
13714 m_recallZ = nodeEntry->z;
13716 // flight will started later
13719 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
13721 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
13722 // Do now before stats re-calculation cleanup for ghost state unexpected auras
13723 if(!isAlive())
13724 RemoveAllAurasOnDeath();
13726 //apply all stat bonuses from items and auras
13727 SetCanModifyStats(true);
13728 UpdateAllStats();
13730 // restore remembered power/health values (but not more max values)
13731 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
13732 for(uint32 i = 0; i < MAX_POWERS; ++i)
13733 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
13735 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
13736 outDebugValues();
13738 // GM state
13739 if(GetSession()->GetSecurity() > SEC_PLAYER)
13741 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
13743 default:
13744 case 0: break; // disable
13745 case 1: SetGameMaster(true); break; // enable
13746 case 2: // save state
13747 if(extraflags & PLAYER_EXTRA_GM_ON)
13748 SetGameMaster(true);
13749 break;
13752 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
13754 default:
13755 case 0: break; // disable
13756 case 1: SetAcceptTicket(true); break; // enable
13757 case 2: // save state
13758 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
13759 SetAcceptTicket(true);
13760 break;
13763 switch(sWorld.getConfig(CONFIG_GM_CHAT))
13765 default:
13766 case 0: break; // disable
13767 case 1: SetGMChat(true); break; // enable
13768 case 2: // save state
13769 if(extraflags & PLAYER_EXTRA_GM_CHAT)
13770 SetGMChat(true);
13771 break;
13774 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
13776 default:
13777 case 0: break; // disable
13778 case 1: SetAcceptWhispers(true); break; // enable
13779 case 2: // save state
13780 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
13781 SetAcceptWhispers(true);
13782 break;
13786 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
13788 return true;
13791 bool Player::isAllowedToLoot(Creature* creature)
13793 if(Player* recipient = creature->GetLootRecipient())
13795 if (recipient == this)
13796 return true;
13797 if( Group* otherGroup = recipient->GetGroup())
13799 Group* thisGroup = GetGroup();
13800 if(!thisGroup)
13801 return false;
13802 return thisGroup == otherGroup;
13804 return false;
13806 else
13807 // prevent other players from looting if the recipient got disconnected
13808 return !creature->hasLootRecipient();
13811 void Player::_LoadActions(QueryResult *result)
13813 m_actionButtons.clear();
13815 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
13817 if(result)
13821 Field *fields = result->Fetch();
13823 uint8 button = fields[0].GetUInt8();
13825 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
13827 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
13829 while( result->NextRow() );
13831 delete result;
13835 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
13837 m_Auras.clear();
13838 for (int i = 0; i < TOTAL_AURAS; i++)
13839 m_modAuras[i].clear();
13841 // all aura related fields
13842 for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
13843 SetUInt32Value(i, 0);
13845 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
13847 if(result)
13851 Field *fields = result->Fetch();
13852 uint64 caster_guid = fields[0].GetUInt64();
13853 uint32 spellid = fields[1].GetUInt32();
13854 uint32 effindex = fields[2].GetUInt32();
13855 int32 damage = (int32)fields[3].GetUInt32();
13856 int32 maxduration = (int32)fields[4].GetUInt32();
13857 int32 remaintime = (int32)fields[5].GetUInt32();
13858 int32 remaincharges = (int32)fields[6].GetUInt32();
13860 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
13861 if(!spellproto)
13863 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
13864 continue;
13867 if(effindex >= 3)
13869 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
13870 continue;
13873 // negative effects should continue counting down after logout
13874 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
13876 if(remaintime <= int32(timediff))
13877 continue;
13879 remaintime -= timediff;
13882 // prevent wrong values of remaincharges
13883 if(spellproto->procCharges)
13885 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
13886 remaincharges = spellproto->procCharges;
13888 else
13889 remaincharges = -1;
13891 //do not load single target auras (unless they were cast by the player)
13892 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
13893 continue;
13895 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
13896 if(!damage)
13897 damage = aura->GetModifier()->m_amount;
13898 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
13899 AddAura(aura);
13901 while( result->NextRow() );
13903 delete result;
13906 if(m_class == CLASS_WARRIOR)
13907 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
13910 void Player::LoadCorpse()
13912 if( isAlive() )
13914 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
13916 else
13918 if(Corpse *corpse = GetCorpse())
13920 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
13922 else
13924 //Prevent Dead Player login without corpse
13925 ResurrectPlayer(0.5f);
13930 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
13932 //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());
13933 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
13934 //NOTE: the "order by `bag`" is important because it makes sure
13935 //the bagMap is filled before items in the bags are loaded
13936 //NOTE2: the "order by `slot`" is needed becaue mainhand weapons are (wrongly?)
13937 //expected to be equipped before offhand items (TODO: fixme)
13939 uint32 zone = GetZoneId();
13941 if (result)
13943 std::list<Item*> problematicItems;
13945 // prevent items from being added to the queue when stored
13946 m_itemUpdateQueueBlocked = true;
13949 Field *fields = result->Fetch();
13950 uint32 bag_guid = fields[1].GetUInt32();
13951 uint8 slot = fields[2].GetUInt8();
13952 uint32 item_guid = fields[3].GetUInt32();
13953 uint32 item_id = fields[4].GetUInt32();
13955 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
13957 if(!proto)
13959 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13960 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
13961 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
13962 continue;
13965 Item *item = NewItemOrBag(proto);
13967 if(!item->LoadFromDB(item_guid, GetGUID(), result))
13969 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
13970 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13971 item->FSetState(ITEM_REMOVED);
13972 item->SaveToDB(); // it also deletes item object !
13973 continue;
13976 // not allow have in alive state item limited to another map/zone
13977 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
13979 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13980 item->FSetState(ITEM_REMOVED);
13981 item->SaveToDB(); // it also deletes item object !
13982 continue;
13985 // "Conjured items disappear if you are logged out for more than 15 minutes"
13986 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
13988 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13989 item->FSetState(ITEM_REMOVED);
13990 item->SaveToDB(); // it also deletes item object !
13991 continue;
13994 bool success = true;
13996 if (!bag_guid)
13998 // the item is not in a bag
13999 item->SetContainer( NULL );
14000 item->SetSlot(slot);
14002 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14004 ItemPosCountVec dest;
14005 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14006 item = StoreItem(dest, item, true);
14007 else
14008 success = false;
14010 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14012 uint16 dest;
14013 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14014 QuickEquipItem(dest, item);
14015 else
14016 success = false;
14018 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14020 ItemPosCountVec dest;
14021 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14022 item = BankItem(dest, item, true);
14023 else
14024 success = false;
14027 if(success)
14029 // store bags that may contain items in them
14030 if(item->IsBag() && IsBagPos(item->GetPos()))
14031 bagMap[item_guid] = (Bag*)item;
14034 else
14036 item->SetSlot(NULL_SLOT);
14037 // the item is in a bag, find the bag
14038 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14039 if(itr != bagMap.end())
14040 itr->second->StoreItem(slot, item, true );
14041 else
14042 success = false;
14045 // item's state may have changed after stored
14046 if (success)
14047 item->SetState(ITEM_UNCHANGED, this);
14048 else
14050 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);
14051 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14052 problematicItems.push_back(item);
14054 } while (result->NextRow());
14056 delete result;
14057 m_itemUpdateQueueBlocked = false;
14059 // send by mail problematic items
14060 while(!problematicItems.empty())
14062 // fill mail
14063 MailItemsInfo mi; // item list prepering
14065 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14067 Item* item = problematicItems.front();
14068 problematicItems.pop_front();
14070 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14073 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14075 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14078 //if(isAlive())
14079 _ApplyAllItemMods();
14082 // load mailed item which should receive current player
14083 void Player::_LoadMailedItems(Mail *mail)
14085 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14086 if(!result)
14087 return;
14091 Field *fields = result->Fetch();
14092 uint32 item_guid_low = fields[0].GetUInt32();
14093 uint32 item_template = fields[1].GetUInt32();
14095 mail->AddItem(item_guid_low, item_template);
14097 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14099 if(!proto)
14101 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);
14102 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14103 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14104 continue;
14107 Item *item = NewItemOrBag(proto);
14109 if(!item->LoadFromDB(item_guid_low, 0))
14111 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14112 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14113 item->FSetState(ITEM_REMOVED);
14114 item->SaveToDB(); // it also deletes item object !
14115 continue;
14118 AddMItem(item);
14119 } while (result->NextRow());
14121 delete result;
14124 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14126 //set a count of unread mails
14127 //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);
14128 if (resultUnread)
14130 Field *fieldMail = resultUnread->Fetch();
14131 unReadMails = fieldMail[0].GetUInt8();
14132 delete resultUnread;
14135 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14136 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14137 if (resultDelivery)
14139 Field *fieldMail = resultDelivery->Fetch();
14140 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14141 delete resultDelivery;
14145 void Player::_LoadMail()
14147 m_mail.clear();
14148 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14149 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());
14150 if(result)
14154 Field *fields = result->Fetch();
14155 Mail *m = new Mail;
14156 m->messageID = fields[0].GetUInt32();
14157 m->messageType = fields[1].GetUInt8();
14158 m->sender = fields[2].GetUInt32();
14159 m->receiver = fields[3].GetUInt32();
14160 m->subject = fields[4].GetCppString();
14161 m->itemTextId = fields[5].GetUInt32();
14162 bool has_items = fields[6].GetBool();
14163 m->expire_time = (time_t)fields[7].GetUInt64();
14164 m->deliver_time = (time_t)fields[8].GetUInt64();
14165 m->money = fields[9].GetUInt32();
14166 m->COD = fields[10].GetUInt32();
14167 m->checked = fields[11].GetUInt32();
14168 m->stationery = fields[12].GetUInt8();
14169 m->mailTemplateId = fields[13].GetInt16();
14171 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14173 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14174 m->mailTemplateId = 0;
14177 m->state = MAIL_STATE_UNCHANGED;
14179 if (has_items)
14180 _LoadMailedItems(m);
14182 m_mail.push_back(m);
14183 } while( result->NextRow() );
14184 delete result;
14186 m_mailsLoaded = true;
14189 void Player::LoadPet()
14191 //fixme: the pet should still be loaded if the player is not in world
14192 // just not added to the map
14193 if(IsInWorld())
14195 Pet *pet = new Pet;
14196 if(!pet->LoadPetFromDB(this,0,0,true))
14197 delete pet;
14201 void Player::_LoadQuestStatus(QueryResult *result)
14203 mQuestStatus.clear();
14205 uint32 slot = 0;
14207 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14208 //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());
14210 if(result)
14214 Field *fields = result->Fetch();
14216 uint32 quest_id = fields[0].GetUInt32();
14217 // used to be new, no delete?
14218 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14219 if( pQuest )
14221 // find or create
14222 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14224 uint32 qstatus = fields[1].GetUInt32();
14225 if(qstatus < MAX_QUEST_STATUS)
14226 questStatusData.m_status = QuestStatus(qstatus);
14227 else
14229 questStatusData.m_status = QUEST_STATUS_NONE;
14230 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14233 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14234 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14236 time_t quest_time = time_t(fields[4].GetUInt64());
14238 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14240 AddTimedQuest( quest_id );
14242 if (quest_time <= sWorld.GetGameTime())
14243 questStatusData.m_timer = 1;
14244 else
14245 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14247 else
14248 quest_time = 0;
14250 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14251 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14252 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14253 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14254 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14255 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14256 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14257 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14259 questStatusData.uState = QUEST_UNCHANGED;
14261 // add to quest log
14262 if( slot < MAX_QUEST_LOG_SIZE &&
14263 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14264 questStatusData.m_status==QUEST_STATUS_COMPLETE && !questStatusData.m_rewarded ) )
14266 SetQuestSlot(slot,quest_id,quest_time);
14268 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14269 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14271 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14272 if(questStatusData.m_creatureOrGOcount[idx])
14273 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14275 ++slot;
14278 if(questStatusData.m_rewarded)
14280 // learn rewarded spell if unknown
14281 learnQuestRewardedSpells(pQuest);
14283 // set rewarded title if any
14284 if(pQuest->GetCharTitleId())
14286 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14287 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
14291 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14294 while( result->NextRow() );
14296 delete result;
14299 // clear quest log tail
14300 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14301 SetQuestSlot(i,0);
14304 void Player::_LoadDailyQuestStatus(QueryResult *result)
14306 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14307 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14309 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14311 if(result)
14313 uint32 quest_daily_idx = 0;
14317 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14319 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14320 break;
14323 Field *fields = result->Fetch();
14325 uint32 quest_id = fields[0].GetUInt32();
14327 // save _any_ from daily quest times (it must be after last reset anyway)
14328 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14330 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14331 if( !pQuest )
14332 continue;
14334 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14335 ++quest_daily_idx;
14337 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14339 while( result->NextRow() );
14341 delete result;
14344 m_DailyQuestChanged = false;
14347 void Player::_LoadReputation(QueryResult *result)
14349 m_factions.clear();
14351 // Set initial reputations (so everything is nifty before DB data load)
14352 SetInitialFactions();
14354 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14356 if(result)
14360 Field *fields = result->Fetch();
14362 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14363 if( factionEntry && (factionEntry->reputationListID >= 0))
14365 FactionState* faction = &m_factions[factionEntry->reputationListID];
14367 // update standing to current
14368 faction->Standing = int32(fields[1].GetUInt32());
14370 uint32 dbFactionFlags = fields[2].GetUInt32();
14372 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14373 SetFactionVisible(faction); // have internal checks for forced invisibility
14375 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14376 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14378 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14379 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14380 else // DB not at war
14382 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14383 if( faction->Flags & FACTION_FLAG_VISIBLE )
14384 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14387 // set atWar for hostile
14388 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14389 SetFactionAtWar(faction,true);
14391 // reset changed flag if values similar to saved in DB
14392 if(faction->Flags==dbFactionFlags)
14393 faction->Changed = false;
14396 while( result->NextRow() );
14398 delete result;
14402 void Player::_LoadSpells(QueryResult *result)
14404 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14405 delete itr->second;
14406 m_spells.clear();
14408 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14410 if(result)
14414 Field *fields = result->Fetch();
14416 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14418 while( result->NextRow() );
14420 delete result;
14424 void Player::_LoadTutorials(QueryResult *result)
14426 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14428 if(result)
14432 Field *fields = result->Fetch();
14434 for (int iI=0; iI<8; iI++)
14435 m_Tutorials[iI] = fields[iI].GetUInt32();
14437 while( result->NextRow() );
14439 delete result;
14442 m_TutorialsChanged = false;
14445 void Player::_LoadGroup(QueryResult *result)
14447 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14448 if(result)
14450 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14451 delete result;
14452 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14453 if(group)
14455 uint8 subgroup = group->GetMemberGroup(GetGUID());
14456 SetGroup(group, subgroup);
14457 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14459 // the group leader may change the instance difficulty while the player is offline
14460 SetDifficulty(group->GetDifficulty());
14466 void Player::_LoadBoundInstances(QueryResult *result)
14468 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14469 m_boundInstances[i].clear();
14471 Group *group = GetGroup();
14473 //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));
14474 if(result)
14478 Field *fields = result->Fetch();
14479 bool perm = fields[1].GetBool();
14480 uint32 mapId = fields[2].GetUInt32();
14481 uint32 instanceId = fields[0].GetUInt32();
14482 uint8 difficulty = fields[3].GetUInt8();
14483 time_t resetTime = (time_t)fields[4].GetUInt64();
14484 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14485 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14486 // and in that case it is not used
14488 if(!perm && group)
14490 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);
14491 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14492 continue;
14495 // since non permanent binds are always solo bind, they can always be reset
14496 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14497 if(save) BindToInstance(save, perm, true);
14498 } while(result->NextRow());
14499 delete result;
14503 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14505 // some instances only have one difficulty
14506 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14507 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14509 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14510 if(itr != m_boundInstances[difficulty].end())
14511 return &itr->second;
14512 else
14513 return NULL;
14516 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14518 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14519 UnbindInstance(itr, difficulty, unload);
14522 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14524 if(itr != m_boundInstances[difficulty].end())
14526 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14527 itr->second.save->RemovePlayer(this); // save can become invalid
14528 m_boundInstances[difficulty].erase(itr++);
14532 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14534 if(save)
14536 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14537 if(bind.save)
14539 // update the save when the group kills a boss
14540 if(permanent != bind.perm || save != bind.save)
14541 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());
14543 else
14544 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14546 if(bind.save != save)
14548 if(bind.save) bind.save->RemovePlayer(this);
14549 save->AddPlayer(this);
14552 if(permanent) save->SetCanReset(false);
14554 bind.save = save;
14555 bind.perm = permanent;
14556 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());
14557 return &bind;
14559 else
14560 return NULL;
14563 void Player::SendRaidInfo()
14565 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14567 uint32 counter = 0, i;
14568 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14569 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14570 if(itr->second.perm) counter++;
14572 data << counter;
14573 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14575 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14577 if(itr->second.perm)
14579 InstanceSave *save = itr->second.save;
14580 data << (save->GetMapId());
14581 data << (uint32)(save->GetResetTime() - time(NULL));
14582 data << save->GetInstanceId();
14583 data << uint32(counter);
14584 counter--;
14588 GetSession()->SendPacket(&data);
14592 - called on every successful teleportation to a map
14594 void Player::SendSavedInstances()
14596 bool hasBeenSaved = false;
14597 WorldPacket data;
14599 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14601 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14603 if(itr->second.perm) // only permanent binds are sent
14605 hasBeenSaved = true;
14606 break;
14611 //Send opcode 811. true or flase means, whether you have current raid/heroic instances
14612 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
14613 data << uint32(hasBeenSaved);
14614 GetSession()->SendPacket(&data);
14616 if(!hasBeenSaved)
14617 return;
14619 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14621 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14623 if(itr->second.perm)
14625 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
14626 data << uint32(itr->second.save->GetMapId());
14627 GetSession()->SendPacket(&data);
14633 /// convert the player's binds to the group
14634 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
14636 bool has_binds = false;
14637 bool has_solo = false;
14639 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
14640 assert(player_guid);
14642 // copy all binds to the group, when changing leader it's assumed the character
14643 // will not have any solo binds
14645 if(player)
14647 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14649 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
14651 has_binds = true;
14652 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
14653 // permanent binds are not removed
14654 if(!itr->second.perm)
14656 player->UnbindInstance(itr, i, true); // increments itr
14657 has_solo = true;
14659 else
14660 ++itr;
14665 // if the player's not online we don't know what binds it has
14666 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));
14667 // the following should not get executed when changing leaders
14668 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
14671 bool Player::_LoadHomeBind(QueryResult *result)
14673 bool ok = false;
14674 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14675 if (result)
14677 Field *fields = result->Fetch();
14678 m_homebindMapId = fields[0].GetUInt32();
14679 m_homebindZoneId = fields[1].GetUInt16();
14680 m_homebindX = fields[2].GetFloat();
14681 m_homebindY = fields[3].GetFloat();
14682 m_homebindZ = fields[4].GetFloat();
14683 delete result;
14685 // accept saved data only for valid position (and non instanceable)
14686 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
14687 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
14689 ok = true;
14691 else
14692 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14695 if(!ok)
14697 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
14698 if(!info) return false;
14700 m_homebindMapId = info->mapId;
14701 m_homebindZoneId = info->zoneId;
14702 m_homebindX = info->positionX;
14703 m_homebindY = info->positionY;
14704 m_homebindZ = info->positionZ;
14706 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);
14709 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
14710 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
14712 return true;
14715 /*********************************************************/
14716 /*** SAVE SYSTEM ***/
14717 /*********************************************************/
14719 void Player::SaveToDB()
14721 // delay auto save at any saves (manual, in code, or autosave)
14722 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
14724 // first save/honor gain after midnight will also update the player's honor fields
14725 UpdateHonorFields();
14727 // Must saved before enter into BattleGround
14728 if(InBattleGround())
14729 return;
14731 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
14732 //save, far from tavern/city
14733 //save, but in tavern/city
14734 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
14735 outDebugValues();
14737 // save state (after auras removing), if aura remove some flags then it must set it back by self)
14738 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
14739 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
14740 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
14741 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
14742 uint32 tmp_displayid = GetDisplayId();
14744 // Set player sit state to standing on save, also stealth and shifted form
14745 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
14746 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
14747 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
14748 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
14749 SetDisplayId(GetNativeDisplayId());
14751 bool inworld = IsInWorld();
14753 CharacterDatabase.BeginTransaction();
14755 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
14757 std::string sql_name = m_name;
14758 CharacterDatabase.escape_string(sql_name);
14760 std::ostringstream ss;
14761 ss << "INSERT INTO characters (guid,account,name,race,class,"
14762 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
14763 "taximask, online, cinematic, "
14764 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
14765 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
14766 "death_expire_time, taxi_path) VALUES ("
14767 << GetGUIDLow() << ", "
14768 << GetSession()->GetAccountId() << ", '"
14769 << sql_name << "', "
14770 << m_race << ", "
14771 << m_class << ", ";
14773 bool save_to_dest = false;
14774 if(IsBeingTeleported())
14776 // don't save to battlegrounds or arenas
14777 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
14778 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
14779 save_to_dest = true;
14782 if(!save_to_dest)
14784 ss << GetMapId() << ", "
14785 << (uint32)GetDifficulty() << ", "
14786 << finiteAlways(GetPositionX()) << ", "
14787 << finiteAlways(GetPositionY()) << ", "
14788 << finiteAlways(GetPositionZ()) << ", "
14789 << finiteAlways(GetOrientation()) << ", '";
14791 else
14793 ss << GetTeleportDest().mapid << ", "
14794 << (uint32)GetDifficulty() << ", "
14795 << finiteAlways(GetTeleportDest().x) << ", "
14796 << finiteAlways(GetTeleportDest().y) << ", "
14797 << finiteAlways(GetTeleportDest().z) << ", "
14798 << finiteAlways(GetTeleportDest().o) << ", '";
14801 uint16 i;
14802 for( i = 0; i < m_valuesCount; i++ )
14804 ss << GetUInt32Value(i) << " ";
14807 ss << "', '";
14809 for( i = 0; i < 8; i++ )
14810 ss << m_taxi.GetTaximask(i) << " ";
14812 ss << "', ";
14813 ss << (inworld ? 1 : 0);
14815 ss << ", ";
14816 ss << m_cinematic;
14818 ss << ", ";
14819 ss << m_Played_time[0];
14820 ss << ", ";
14821 ss << m_Played_time[1];
14823 ss << ", ";
14824 ss << finiteAlways(m_rest_bonus);
14825 ss << ", ";
14826 ss << (uint64)time(NULL);
14827 ss << ", ";
14828 ss << is_save_resting;
14829 ss << ", ";
14830 ss << m_resetTalentsCost;
14831 ss << ", ";
14832 ss << (uint64)m_resetTalentsTime;
14834 ss << ", ";
14835 ss << finiteAlways(m_movementInfo.t_x);
14836 ss << ", ";
14837 ss << finiteAlways(m_movementInfo.t_y);
14838 ss << ", ";
14839 ss << finiteAlways(m_movementInfo.t_z);
14840 ss << ", ";
14841 ss << finiteAlways(m_movementInfo.t_o);
14842 ss << ", ";
14843 if (m_transport)
14844 ss << m_transport->GetGUIDLow();
14845 else
14846 ss << "0";
14848 ss << ", ";
14849 ss << m_ExtraFlags;
14851 ss << ", ";
14852 ss << uint32(m_stableSlots); // to prevent save uint8 as char
14854 ss << ", ";
14855 ss << uint32(m_atLoginFlags);
14857 ss << ", ";
14858 ss << GetZoneId();
14860 ss << ", ";
14861 ss << (uint64)m_deathExpireTime;
14863 ss << ", '";
14864 ss << m_taxi.SaveTaxiDestinationsToString();
14865 ss << "' )";
14867 CharacterDatabase.Execute( ss.str().c_str() );
14869 if(m_mailsUpdated) //save mails only when needed
14870 _SaveMail();
14872 _SaveInventory();
14873 _SaveQuestStatus();
14874 _SaveDailyQuestStatus();
14875 _SaveTutorials();
14876 _SaveSpells();
14877 _SaveSpellCooldowns();
14878 _SaveActions();
14879 _SaveAuras();
14880 _SaveReputation();
14882 CharacterDatabase.CommitTransaction();
14884 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
14885 SetDisplayId(tmp_displayid);
14886 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
14887 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
14888 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
14889 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
14891 // save pet (hunter pet level and experience and all type pets health/mana).
14892 if(Pet* pet = GetPet())
14893 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
14896 // fast save function for item/money cheating preventing - save only inventory and money state
14897 void Player::SaveInventoryAndGoldToDB()
14899 _SaveInventory();
14900 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
14903 void Player::_SaveActions()
14905 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
14907 switch (itr->second.uState)
14909 case ACTIONBUTTON_NEW:
14910 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
14911 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
14912 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14913 ++itr;
14914 break;
14915 case ACTIONBUTTON_CHANGED:
14916 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
14917 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
14918 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14919 ++itr;
14920 break;
14921 case ACTIONBUTTON_DELETED:
14922 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
14923 m_actionButtons.erase(itr++);
14924 break;
14925 default:
14926 ++itr;
14927 break;
14932 void Player::_SaveAuras()
14934 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14936 AuraMap const& auras = GetAuras();
14937 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
14939 SpellEntry const *spellInfo = itr->second->GetSpellProto();
14941 //skip all auras from spells that are passive or need a shapeshift
14942 if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
14943 continue;
14945 //do not save single target auras (unless they were cast by the player)
14946 if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
14947 continue;
14949 uint8 i;
14950 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
14951 for (i = 0; i < 3; i++)
14952 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
14953 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
14954 break;
14956 if (i == 3)
14958 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u' and spell = '%u' and effect_index= '%u'",GetGUIDLow(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex());
14959 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
14960 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
14961 GetGUIDLow(), itr->second->GetCasterGUID(), (uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(), (*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
14966 void Player::_SaveInventory()
14968 // force items in buyback slots to new state
14969 // and remove those that aren't already
14970 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
14972 Item *item = m_items[i];
14973 if (!item || item->GetState() == ITEM_NEW) continue;
14974 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
14975 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
14976 m_items[i]->FSetState(ITEM_NEW);
14979 // update enchantment durations
14980 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
14982 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
14985 // if no changes
14986 if (m_itemUpdateQueue.empty()) return;
14988 // do not save if the update queue is corrupt
14989 bool error = false;
14990 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
14992 Item *item = m_itemUpdateQueue[i];
14993 if(!item || item->GetState() == ITEM_REMOVED) continue;
14994 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
14996 if (test == NULL)
14998 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());
14999 error = true;
15001 else if (test != item)
15003 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());
15004 error = true;
15008 if (error)
15010 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15011 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15012 return;
15015 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15017 Item *item = m_itemUpdateQueue[i];
15018 if(!item) continue;
15020 Bag *container = item->GetContainer();
15021 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15023 switch(item->GetState())
15025 case ITEM_NEW:
15026 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());
15027 break;
15028 case ITEM_CHANGED:
15029 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());
15030 break;
15031 case ITEM_REMOVED:
15032 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15033 break;
15034 case ITEM_UNCHANGED:
15035 break;
15038 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15040 m_itemUpdateQueue.clear();
15043 void Player::_SaveMail()
15045 if (!m_mailsLoaded)
15046 return;
15048 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
15050 Mail *m = (*itr);
15051 if (m->state == MAIL_STATE_CHANGED)
15053 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'",
15054 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15055 if(m->removedItems.size())
15057 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15058 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15059 m->removedItems.clear();
15061 m->state = MAIL_STATE_UNCHANGED;
15063 else if (m->state == MAIL_STATE_DELETED)
15065 if (m->HasItems())
15066 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15067 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15068 if (m->itemTextId)
15069 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15070 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15071 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15075 //deallocate deleted mails...
15076 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15078 if ((*itr)->state == MAIL_STATE_DELETED)
15080 Mail* m = *itr;
15081 m_mail.erase(itr);
15082 delete m;
15083 itr = m_mail.begin();
15085 else
15086 ++itr;
15089 m_mailsUpdated = false;
15092 void Player::_SaveQuestStatus()
15094 // we don't need transactions here.
15095 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15097 switch (i->second.uState)
15099 case QUEST_NEW :
15100 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15101 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15102 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]);
15103 break;
15104 case QUEST_CHANGED :
15105 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' ",
15106 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 );
15107 break;
15108 case QUEST_UNCHANGED:
15109 break;
15111 i->second.uState = QUEST_UNCHANGED;
15115 void Player::_SaveDailyQuestStatus()
15117 if(!m_DailyQuestChanged)
15118 return;
15120 m_DailyQuestChanged = false;
15122 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15124 // we don't need transactions here.
15125 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15126 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15127 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15128 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15129 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15132 void Player::_SaveReputation()
15134 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15136 if (itr->second.Changed)
15138 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15139 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);
15140 itr->second.Changed = false;
15145 void Player::_SaveSpells()
15147 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15149 ++next;
15150 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15151 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15152 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15153 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);
15155 if (itr->second->state == PLAYERSPELL_REMOVED)
15156 _removeSpell(itr->first);
15157 else
15158 itr->second->state = PLAYERSPELL_UNCHANGED;
15162 void Player::_SaveTutorials()
15164 if(!m_TutorialsChanged)
15165 return;
15167 uint32 Rows=0;
15168 // it's better than rebuilding indexes multiple times
15169 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15170 if(result)
15172 Rows = result->Fetch()[0].GetUInt32();
15173 delete result;
15176 if (Rows)
15178 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'",
15179 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 );
15181 else
15183 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]);
15186 m_TutorialsChanged = false;
15189 void Player::outDebugValues() const
15191 if(!sLog.IsOutDebug()) // optimize disabled debug output
15192 return;
15194 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15195 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15196 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15197 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15198 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15199 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15200 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15201 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15202 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15203 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15204 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15205 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15208 /*********************************************************/
15209 /*** FLOOD FILTER SYSTEM ***/
15210 /*********************************************************/
15212 void Player::UpdateSpeakTime()
15214 // ignore chat spam protection for GMs in any mode
15215 if(GetSession()->GetSecurity() > SEC_PLAYER)
15216 return;
15218 time_t current = time (NULL);
15219 if(m_speakTime > current)
15221 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15222 if(!max_count)
15223 return;
15225 ++m_speakCount;
15226 if(m_speakCount >= max_count)
15228 // prevent overwrite mute time, if message send just before mutes set, for example.
15229 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15230 if(GetSession()->m_muteTime < new_mute)
15231 GetSession()->m_muteTime = new_mute;
15233 m_speakCount = 0;
15236 else
15237 m_speakCount = 0;
15239 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15242 bool Player::CanSpeak() const
15244 return GetSession()->m_muteTime <= time (NULL);
15247 /*********************************************************/
15248 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15249 /*********************************************************/
15251 void Player::SendAttackSwingNotInRange()
15253 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15254 GetSession()->SendPacket( &data );
15257 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15259 std::ostringstream ss;
15260 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15261 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15262 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15263 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15264 sLog.outDebug(ss.str().c_str());
15265 CharacterDatabase.Execute(ss.str().c_str());
15268 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15270 std::ostringstream ss2;
15271 ss2<<"UPDATE characters SET data='";
15272 int i=0;
15273 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15275 ss2<<tokens[i]<<" ";
15277 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15279 return CharacterDatabase.Execute(ss2.str().c_str());
15282 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15284 char buf[11];
15285 snprintf(buf,11,"%u",value);
15287 if(index >= tokens.size())
15288 return;
15290 tokens[index] = buf;
15293 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15295 Tokens tokens;
15296 if(!LoadValuesArrayFromDB(tokens,guid))
15297 return;
15299 if(index >= tokens.size())
15300 return;
15302 char buf[11];
15303 snprintf(buf,11,"%u",value);
15304 tokens[index] = buf;
15306 SaveValuesArrayInDB(tokens,guid);
15309 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15311 uint32 temp;
15312 memcpy(&temp, &value, sizeof(value));
15313 Player::SetUInt32ValueInDB(index, temp, guid);
15316 void Player::SendAttackSwingNotStanding()
15318 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15319 GetSession()->SendPacket( &data );
15322 void Player::SendAttackSwingDeadTarget()
15324 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15325 GetSession()->SendPacket( &data );
15328 void Player::SendAttackSwingCantAttack()
15330 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15331 GetSession()->SendPacket( &data );
15334 void Player::SendAttackSwingCancelAttack()
15336 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15337 GetSession()->SendPacket( &data );
15340 void Player::SendAttackSwingBadFacingAttack()
15342 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15343 GetSession()->SendPacket( &data );
15346 void Player::SendAutoRepeatCancel()
15348 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, 0);
15349 GetSession()->SendPacket( &data );
15352 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15354 WorldPacket data(SMSG_PLAY_SOUND, 4);
15355 data << Sound;
15356 if (OnlySelf)
15357 GetSession()->SendPacket( &data );
15358 else
15359 SendMessageToSet( &data, true );
15362 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15364 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15365 data << Area;
15366 data << Experience;
15367 GetSession()->SendPacket(&data);
15370 void Player::SendDungeonDifficulty(bool IsInGroup)
15372 uint8 val = 0x00000001;
15373 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15374 data << (uint32)GetDifficulty();
15375 data << uint32(val);
15376 data << uint32(IsInGroup);
15377 GetSession()->SendPacket(&data);
15380 void Player::SendResetFailedNotify(uint32 mapid)
15382 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15383 data << uint32(mapid);
15384 GetSession()->SendPacket(&data);
15387 /// Reset all solo instances and optionally send a message on success for each
15388 void Player::ResetInstances(uint8 method)
15390 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15392 // we assume that when the difficulty changes, all instances that can be reset will be
15393 uint8 dif = GetDifficulty();
15395 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15397 InstanceSave *p = itr->second.save;
15398 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15399 if(!entry || !p->CanReset())
15401 ++itr;
15402 continue;
15405 if(method == INSTANCE_RESET_ALL)
15407 // the "reset all instances" method can only reset normal maps
15408 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15410 ++itr;
15411 continue;
15415 // if the map is loaded, reset it
15416 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15417 if(map && map->IsDungeon())
15418 ((InstanceMap*)map)->Reset(method);
15420 // since this is a solo instance there should not be any players inside
15421 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15422 SendResetInstanceSuccess(p->GetMapId());
15424 p->DeleteFromDB();
15425 m_boundInstances[dif].erase(itr++);
15427 // the following should remove the instance save from the manager and delete it as well
15428 p->RemovePlayer(this);
15432 void Player::SendResetInstanceSuccess(uint32 MapId)
15434 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15435 data << MapId;
15436 GetSession()->SendPacket(&data);
15439 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15441 // TODO: find what other fail reasons there are besides players in the instance
15442 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15443 data << reason;
15444 data << MapId;
15445 GetSession()->SendPacket(&data);
15448 /*********************************************************/
15449 /*** Update timers ***/
15450 /*********************************************************/
15452 ///checks the 15 afk reports per 5 minutes limit
15453 void Player::UpdateAfkReport(time_t currTime)
15455 if(m_bgAfkReportedTimer <= currTime)
15457 m_bgAfkReportedCount = 0;
15458 m_bgAfkReportedTimer = currTime+5*MINUTE;
15462 void Player::UpdateContestedPvP(uint32 diff)
15464 if(!m_contestedPvPTimer||isInCombat())
15465 return;
15466 if(m_contestedPvPTimer <= diff)
15468 ResetContestedPvP();
15470 else
15471 m_contestedPvPTimer -= diff;
15474 void Player::UpdatePvPFlag(time_t currTime)
15476 if(!IsPvP())
15477 return;
15478 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15479 return;
15481 UpdatePvP(false);
15484 void Player::UpdateDuelFlag(time_t currTime)
15486 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15487 return;
15489 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15490 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15492 duel->startTimer = 0;
15493 duel->startTime = currTime;
15494 duel->opponent->duel->startTimer = 0;
15495 duel->opponent->duel->startTime = currTime;
15498 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15500 if(!pet)
15501 pet = GetPet();
15503 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15505 //returning of reagents only for players, so best done here
15506 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
15507 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15509 if(spellInfo)
15511 for(uint32 i = 0; i < 7; ++i)
15513 if(spellInfo->Reagent[i] > 0)
15515 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15516 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
15517 if( msg == EQUIP_ERR_OK )
15519 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
15520 if(IsInWorld())
15521 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
15526 m_temporaryUnsummonedPetNumber = 0;
15529 if(!pet || pet->GetOwnerGUID()!=GetGUID())
15530 return;
15532 // only if current pet in slot
15533 switch(pet->getPetType())
15535 case MINI_PET:
15536 m_miniPet = 0;
15537 break;
15538 case GUARDIAN_PET:
15539 m_guardianPets.erase(pet->GetGUID());
15540 break;
15541 default:
15542 if(GetPetGUID()==pet->GetGUID())
15543 SetPet(0);
15544 break;
15547 pet->CombatStop();
15549 if(returnreagent)
15551 switch(pet->GetEntry())
15553 //warlock pets except imp are removed(?) when logging out
15554 case 1860:
15555 case 1863:
15556 case 417:
15557 case 17252:
15558 mode = PET_SAVE_NOT_IN_SLOT;
15559 break;
15563 pet->SavePetToDB(mode);
15565 pet->CleanupsBeforeDelete();
15566 pet->AddObjectToRemoveList();
15567 pet->m_removed = true;
15569 if(pet->isControlled())
15571 WorldPacket data(SMSG_PET_SPELLS, 8);
15572 data << uint64(0);
15573 GetSession()->SendPacket(&data);
15575 if(GetGroup())
15576 SetGroupUpdateFlag(GROUP_UPDATE_PET);
15580 void Player::RemoveMiniPet()
15582 if(Pet* pet = GetMiniPet())
15584 pet->Remove(PET_SAVE_AS_DELETED);
15585 m_miniPet = 0;
15589 Pet* Player::GetMiniPet()
15591 if(!m_miniPet)
15592 return NULL;
15593 return ObjectAccessor::GetPet(m_miniPet);
15596 void Player::RemoveGuardians()
15598 while(!m_guardianPets.empty())
15600 uint64 guid = *m_guardianPets.begin();
15601 if(Pet* pet = ObjectAccessor::GetPet(guid))
15602 pet->Remove(PET_SAVE_AS_DELETED);
15604 m_guardianPets.erase(guid);
15608 bool Player::HasGuardianWithEntry(uint32 entry)
15610 // pet guid middle part is entry (and creature also)
15611 // and in guardian list must be guardians with same entry _always_
15612 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
15613 if(GUID_ENPART(*itr)==entry)
15614 return true;
15616 return false;
15619 void Player::Uncharm()
15621 Unit* charm = GetCharm();
15622 if(!charm)
15623 return;
15625 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
15626 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
15629 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, std::string text, uint32 language) const
15631 *data << (uint8)msgtype;
15632 *data << (uint32)language;
15633 *data << (uint64)GetGUID();
15634 *data << (uint32)language; //language 2.1.0 ?
15635 *data << (uint64)GetGUID();
15636 *data << (uint32)(text.length()+1);
15637 *data << text;
15638 *data << (uint8)chatTag();
15641 void Player::Say(const std::string text, const uint32 language)
15643 WorldPacket data(SMSG_MESSAGECHAT, 200);
15644 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
15645 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
15648 void Player::Yell(const std::string text, const uint32 language)
15650 WorldPacket data(SMSG_MESSAGECHAT, 200);
15651 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
15652 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
15655 void Player::TextEmote(const std::string text)
15657 WorldPacket data(SMSG_MESSAGECHAT, 200);
15658 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
15659 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
15662 void Player::Whisper(std::string text, uint32 language,uint64 receiver)
15664 if (language != LANG_ADDON) // if not addon data
15665 language = LANG_UNIVERSAL; // whispers should always be readable
15667 Player *rPlayer = objmgr.GetPlayer(receiver);
15669 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15670 if(!rPlayer->isDND() || isGameMaster())
15672 WorldPacket data(SMSG_MESSAGECHAT, 200);
15673 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
15674 rPlayer->GetSession()->SendPacket(&data);
15676 data.Initialize(SMSG_MESSAGECHAT, 200);
15677 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
15678 GetSession()->SendPacket(&data);
15680 else
15682 // announce to player that player he is whispering to is dnd and cannot receive his message
15683 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
15686 if(!isAcceptWhispers())
15688 SetAcceptWhispers(true);
15689 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
15692 // announce to player that player he is whispering to is afk
15693 if(rPlayer->isAFK())
15694 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
15696 // if player whisper someone, auto turn of dnd to be able to receive an answer
15697 if(isDND() && !rPlayer->isGameMaster())
15698 ToggleDND();
15701 void Player::PetSpellInitialize()
15703 Pet* pet = GetPet();
15705 if(pet)
15707 uint8 addlist = 0;
15709 sLog.outDebug("Pet Spells Groups");
15711 CreatureInfo const *cinfo = pet->GetCreatureInfo();
15713 if(pet->isControlled() && (pet->getPetType() == HUNTER_PET || cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK))
15715 for(PetSpellMap::iterator itr = pet->m_spells.begin();itr != pet->m_spells.end();itr++)
15717 if(itr->second->state == PETSPELL_REMOVED)
15718 continue;
15719 ++addlist;
15723 // first line + actionbar + spellcount + spells + last adds
15724 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);
15726 CharmInfo *charmInfo = pet->GetCharmInfo();
15728 //16
15729 data << (uint64)pet->GetGUID() << uint32(0x00000000) << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
15731 for(uint32 i = 0; i < 10; i++) //40
15733 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15736 data << uint8(addlist); //1
15738 if(addlist && pet->isControlled())
15740 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
15742 if(itr->second->state == PETSPELL_REMOVED)
15743 continue;
15745 data << uint16(itr->first);
15746 data << uint16(itr->second->active); // pet spell active state isn't boolean
15750 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
15751 uint8 count = 3; //1+8+8+8=25
15753 // if count = 0, then end of packet...
15754 data << count;
15755 // uint32 value is spell id...
15756 // uint64 value is constant 0, unknown...
15757 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15758 //data << uint32(0x5fd1) << uint64(0); // if count = 2
15759 data << uint32(0x8e8c) << uint64(0); // if count = 3
15760 data << uint32(0x8e8b) << uint64(0); // if count = 3
15762 GetSession()->SendPacket(&data);
15766 void Player::PossessSpellInitialize()
15768 Unit* charm = GetCharm();
15770 if(!charm)
15771 return;
15773 CharmInfo *charmInfo = charm->GetCharmInfo();
15775 if(!charmInfo)
15777 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15778 return;
15781 uint8 addlist = 0;
15782 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15784 //16
15785 data << (uint64)charm->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);
15787 for(uint32 i = 0; i < 10; i++) //40
15789 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15792 data << uint8(addlist); //1
15794 uint8 count = 3;
15795 data << count;
15796 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15797 data << uint32(0x8e8c) << uint64(0); // if count = 3
15798 data << uint32(0x8e8b) << uint64(0); // if count = 3
15800 GetSession()->SendPacket(&data);
15803 void Player::CharmSpellInitialize()
15805 Unit* charm = GetCharm();
15807 if(!charm)
15808 return;
15810 CharmInfo *charmInfo = charm->GetCharmInfo();
15811 if(!charmInfo)
15813 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15814 return;
15817 uint8 addlist = 0;
15819 if(charm->GetTypeId() != TYPEID_PLAYER)
15821 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
15823 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
15825 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15827 if(charmInfo->GetCharmSpell(i)->spellId)
15828 ++addlist;
15833 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15835 data << (uint64)charm->GetGUID() << uint32(0x00000000);
15837 if(charm->GetTypeId() != TYPEID_PLAYER)
15838 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
15839 else
15840 data << uint8(0) << uint8(0);
15842 data << uint16(0);
15844 for(uint32 i = 0; i < 10; i++) //40
15846 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15849 data << uint8(addlist); //1
15851 if(addlist)
15853 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15855 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
15856 if(cspell->spellId)
15858 data << uint16(cspell->spellId);
15859 data << uint16(cspell->active);
15864 uint8 count = 3;
15865 data << count;
15866 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15867 data << uint32(0x8e8c) << uint64(0); // if count = 3
15868 data << uint32(0x8e8b) << uint64(0); // if count = 3
15870 GetSession()->SendPacket(&data);
15873 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
15875 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15876 if (!spellInfo) return 0;
15877 int32 total = 0;
15878 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15880 SpellModifier *mod = *itr;
15882 if(!IsAffectedBySpellmod(spellInfo,mod))
15883 continue;
15885 if (mod->type == SPELLMOD_FLAT)
15886 total += mod->value;
15888 return total;
15891 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
15893 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15894 if (!spellInfo) return 0;
15895 int32 total = 0;
15896 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15898 SpellModifier *mod = *itr;
15900 if(!IsAffectedBySpellmod(spellInfo,mod))
15901 continue;
15903 if (mod->type == SPELLMOD_PCT)
15904 total += mod->value;
15906 return total;
15909 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
15911 if (!mod || !spellInfo)
15912 return false;
15914 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
15916 // prevent apply to any spell except spell that trigger expire
15917 if(spell)
15919 if(mod->lastAffected != spell)
15920 return false;
15922 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
15923 return false;
15926 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
15929 void Player::AddSpellMod(SpellModifier* mod, bool apply)
15931 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
15933 for(int eff=0;eff<64;++eff)
15935 uint64 _mask = uint64(1) << eff;
15936 if ( mod->mask & _mask)
15938 int32 val = 0;
15939 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
15941 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
15942 val += (*itr)->value;
15944 val += apply ? mod->value : -(mod->value);
15945 WorldPacket data(Opcode, (1+1+4));
15946 data << uint8(eff);
15947 data << uint8(mod->op);
15948 data << int32(val);
15949 SendDirectMessage(&data);
15953 if (apply)
15954 m_spellMods[mod->op].push_back(mod);
15955 else
15957 if (mod->charges == -1)
15958 --m_SpellModRemoveCount;
15959 m_spellMods[mod->op].remove(mod);
15960 delete mod;
15964 void Player::RemoveSpellMods(Spell const* spell)
15966 if(!spell || (m_SpellModRemoveCount == 0))
15967 return;
15969 for(int i=0;i<MAX_SPELLMOD;++i)
15971 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
15973 SpellModifier *mod = *itr;
15974 ++itr;
15976 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
15978 RemoveAurasDueToSpell(mod->spellId);
15979 if (m_spellMods[i].empty())
15980 break;
15981 else
15982 itr = m_spellMods[i].begin();
15988 // send Proficiency
15989 void Player::SendProficiency(uint8 pr1, uint32 pr2)
15991 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
15992 data << pr1 << pr2;
15993 GetSession()->SendPacket (&data);
15996 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
15998 QueryResult *result = NULL;
15999 if(type==10)
16000 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16001 else
16002 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16003 if(result)
16005 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.
16006 { // and SendPetitionQueryOpcode reads data from the DB
16007 Field *fields = result->Fetch();
16008 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16009 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16011 // send update if charter owner in game
16012 Player* owner = objmgr.GetPlayer(ownerguid);
16013 if(owner)
16014 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16016 } while ( result->NextRow() );
16018 delete result;
16020 if(type==10)
16021 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16022 else
16023 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16026 CharacterDatabase.BeginTransaction();
16027 if(type == 10)
16029 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16030 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16032 else
16034 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16035 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16037 CharacterDatabase.CommitTransaction();
16040 void Player::SetRestBonus (float rest_bonus_new)
16042 // Prevent resting on max level
16043 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16044 rest_bonus_new = 0;
16046 if(rest_bonus_new < 0)
16047 rest_bonus_new = 0;
16049 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16051 if(rest_bonus_new > rest_bonus_max)
16052 m_rest_bonus = rest_bonus_max;
16053 else
16054 m_rest_bonus = rest_bonus_new;
16056 // update data for client
16057 if(m_rest_bonus>10)
16058 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16059 else if(m_rest_bonus<=1)
16060 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16062 //RestTickUpdate
16063 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16066 void Player::HandleStealthedUnitsDetection()
16068 std::list<Unit*> stealthedUnits;
16070 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16071 Cell cell(p);
16072 cell.data.Part.reserved = ALL_DISTRICT;
16073 cell.SetNoCreate();
16075 MaNGOS::AnyStealthedCheck u_check;
16076 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16078 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16079 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16081 CellLock<GridReadGuard> cell_lock(cell, p);
16082 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16083 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16085 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16087 if((*i)==this)
16089 i = stealthedUnits.erase(i);
16090 continue;
16093 if ((*i)->isVisibleForOrDetect(this,true))
16096 (*i)->SendUpdateToPlayer(this);
16097 m_clientGUIDs.insert((*i)->GetGUID());
16099 #ifdef MANGOS_DEBUG
16100 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16101 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16102 #endif
16104 // target aura duration for caster show only if target exist at caster client
16105 // send data at target visibility change (adding to client)
16106 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16107 SendAuraDurationsForTarget(*i);
16109 i = stealthedUnits.erase(i);
16110 continue;
16113 ++i;
16117 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16119 if(nodes.size() < 2)
16120 return false;
16122 // not let cheating with start flight mounted
16123 if(IsMounted())
16125 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16126 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16127 GetSession()->SendPacket(&data);
16128 return false;
16131 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16133 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16134 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16135 GetSession()->SendPacket(&data);
16136 return false;
16139 // 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
16140 if(GetSession()->isLogingOut() ||
16141 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16142 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16143 IsNonMeleeSpellCasted(false) ||
16144 isInCombat())
16146 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16147 data << uint32(ERR_TAXIPLAYERBUSY);
16148 GetSession()->SendPacket(&data);
16149 return false;
16152 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16153 return false;
16155 uint32 sourcenode = nodes[0];
16157 // starting node too far away (cheat?)
16158 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16159 if( !node || node->map_id != GetMapId() ||
16160 (node->x - GetPositionX())*(node->x - GetPositionX())+
16161 (node->y - GetPositionY())*(node->y - GetPositionY())+
16162 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16163 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16165 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16166 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16167 GetSession()->SendPacket(&data);
16168 return false;
16171 // Prepare to flight start now
16173 // stop combat at start taxi flight if any
16174 CombatStop();
16176 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16177 TradeCancel(true);
16179 // clean not finished taxi path if any
16180 m_taxi.ClearTaxiDestinations();
16182 // 0 element current node
16183 m_taxi.AddTaxiDestination(sourcenode);
16185 // fill destinations path tail
16186 uint32 sourcepath = 0;
16187 uint32 totalcost = 0;
16189 uint32 prevnode = sourcenode;
16190 uint32 lastnode = 0;
16192 for(uint32 i = 1; i < nodes.size(); ++i)
16194 uint32 path, cost;
16196 lastnode = nodes[i];
16197 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16199 if(!path)
16201 m_taxi.ClearTaxiDestinations();
16202 return false;
16205 totalcost += cost;
16207 if(prevnode == sourcenode)
16208 sourcepath = path;
16210 m_taxi.AddTaxiDestination(lastnode);
16212 prevnode = lastnode;
16215 if(!mount_id) // if not provide then attempt use default.
16216 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16218 if (mount_id == 0 || sourcepath == 0)
16220 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16221 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16222 GetSession()->SendPacket(&data);
16223 m_taxi.ClearTaxiDestinations();
16224 return false;
16227 uint32 money = GetMoney();
16229 if(npc)
16231 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16234 if(money < totalcost)
16236 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16237 data << uint32(ERR_TAXINOTENOUGHMONEY);
16238 GetSession()->SendPacket(&data);
16239 m_taxi.ClearTaxiDestinations();
16240 return false;
16243 //Checks and preparations done, DO FLIGHT
16244 ModifyMoney(-(int32)totalcost);
16246 // prevent stealth flight
16247 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16249 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16250 data << uint32(ERR_TAXIOK);
16251 GetSession()->SendPacket(&data);
16253 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16255 GetSession()->SendDoFlight(mount_id, sourcepath);
16257 return true;
16260 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16262 // last check 2.0.10
16263 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16264 data << GetGUID();
16265 data << uint8(0x0); // flags (0x1, 0x2)
16266 time_t curTime = time(NULL);
16267 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16269 if (itr->second->state == PLAYERSPELL_REMOVED)
16270 continue;
16271 uint32 unSpellId = itr->first;
16272 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16273 if (!spellInfo)
16275 ASSERT(spellInfo);
16276 continue;
16279 // Not send cooldown for this spells
16280 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16281 continue;
16283 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16285 data << unSpellId;
16286 data << unTimeMs; // in m.secs
16287 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16290 GetSession()->SendPacket(&data);
16293 void Player::InitDataForForm(bool reapplyMods)
16295 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16296 if(ssEntry && ssEntry->attackSpeed)
16298 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16299 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16300 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16302 else
16303 SetRegularAttackTime();
16305 switch(m_form)
16307 case FORM_CAT:
16309 if(getPowerType()!=POWER_ENERGY)
16310 setPowerType(POWER_ENERGY);
16311 break;
16313 case FORM_BEAR:
16314 case FORM_DIREBEAR:
16316 if(getPowerType()!=POWER_RAGE)
16317 setPowerType(POWER_RAGE);
16318 break;
16320 default: // 0, for example
16322 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16323 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16324 setPowerType(Powers(cEntry->powerType));
16325 break;
16329 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16330 if (!reapplyMods)
16331 UpdateEquipSpellsAtFormChange();
16333 UpdateAttackPowerAndDamage();
16334 UpdateAttackPowerAndDamage(true);
16337 // Return true is the bought item has a max count to force refresh of window by caller
16338 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16340 // cheating attempt
16341 if(count < 1) count = 1;
16343 if(!isAlive())
16344 return false;
16346 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16347 if( !pProto )
16349 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16350 return false;
16353 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16354 if (!pCreature)
16356 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16357 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16358 return false;
16361 VendorItemData const* vItems = pCreature->GetVendorItems();
16362 if(!vItems || vItems->Empty())
16364 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16365 return false;
16368 size_t vendor_slot = vItems->FindItemSlot(item);
16369 if(vendor_slot >= vItems->GetItemCount())
16371 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16372 return false;
16375 VendorItem const* crItem = vItems->m_items[vendor_slot];
16377 // check current item amount if it limited
16378 if( crItem->maxcount != 0 )
16380 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16382 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16383 return false;
16387 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16389 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16390 return false;
16393 if(crItem->ExtendedCost)
16395 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16396 if(!iece)
16398 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16399 return false;
16402 // honor points price
16403 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16405 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16406 return false;
16409 // arena points price
16410 if(GetArenaPoints() < (iece->reqarenapoints * count))
16412 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16413 return false;
16416 // item base price
16417 for (uint8 i = 0; i < 5; ++i)
16419 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16421 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16422 return false;
16426 // check for personal arena rating requirement
16427 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16429 // probably not the proper equip err
16430 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16431 return false;
16435 uint32 price = pProto->BuyPrice * count;
16437 // reputation discount
16438 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16440 if( GetMoney() < price )
16442 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16443 return false;
16446 uint8 bag = 0; // init for case invalid bagGUID
16448 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16450 Bag *pBag;
16451 if( bagguid == GetGUID() )
16453 bag = INVENTORY_SLOT_BAG_0;
16455 else
16457 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16459 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16460 if( pBag )
16462 if( bagguid == pBag->GetGUID() )
16464 bag = i;
16465 break;
16472 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16474 ItemPosCountVec dest;
16475 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16476 if( msg != EQUIP_ERR_OK )
16478 SendEquipError( msg, NULL, NULL );
16479 return false;
16482 ModifyMoney( -(int32)price );
16483 if(crItem->ExtendedCost) // case for new honor system
16485 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16486 if(iece->reqhonorpoints)
16487 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16488 if(iece->reqarenapoints)
16489 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16490 for (uint8 i = 0; i < 5; ++i)
16492 if(iece->reqitem[i])
16493 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16497 if(Item *it = StoreNewItem( dest, item, true ))
16499 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16501 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16502 data << pCreature->GetGUID();
16503 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16504 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16505 data << (uint32)count;
16506 GetSession()->SendPacket(&data);
16508 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16511 else if( IsEquipmentPos( bag, slot ) )
16513 uint16 dest;
16514 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16515 if( msg != EQUIP_ERR_OK )
16517 SendEquipError( msg, NULL, NULL );
16518 return false;
16521 ModifyMoney( -(int32)price );
16522 if(crItem->ExtendedCost) // case for new honor system
16524 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16525 if(iece->reqhonorpoints)
16526 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16527 if(iece->reqarenapoints)
16528 ModifyArenaPoints( - int32(iece->reqarenapoints));
16529 for (uint8 i = 0; i < 5; ++i)
16531 if(iece->reqitem[i])
16532 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16536 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16538 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16540 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16541 data << pCreature->GetGUID();
16542 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16543 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16544 data << (uint32)count;
16545 GetSession()->SendPacket(&data);
16547 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16549 AutoUnequipOffhandIfNeed();
16552 else
16554 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16555 return false;
16558 return crItem->maxcount!=0;
16561 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16563 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16564 // the personal rating of the arena team must match the required limit as well
16565 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16566 uint32 max_personal_rating = 0;
16567 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16569 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16571 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16572 uint32 t_rating = at->GetRating();
16573 p_rating = p_rating<t_rating? p_rating : t_rating;
16574 if(max_personal_rating < p_rating)
16575 max_personal_rating = p_rating;
16578 return max_personal_rating;
16581 void Player::UpdateHomebindTime(uint32 time)
16583 // GMs never get homebind timer online
16584 if (m_InstanceValid || isGameMaster())
16586 if(m_HomebindTimer) // instance valid, but timer not reset
16588 // hide reminder
16589 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16590 data << uint32(0);
16591 data << uint32(0);
16592 GetSession()->SendPacket(&data);
16594 // instance is valid, reset homebind timer
16595 m_HomebindTimer = 0;
16597 else if (m_HomebindTimer > 0)
16599 if (time >= m_HomebindTimer)
16601 // teleport to homebind location
16602 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16604 else
16605 m_HomebindTimer -= time;
16607 else
16609 // instance is invalid, start homebind timer
16610 m_HomebindTimer = 60000;
16611 // send message to player
16612 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16613 data << m_HomebindTimer;
16614 data << uint32(1);
16615 GetSession()->SendPacket(&data);
16616 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16620 void Player::UpdatePvP(bool state, bool ovrride)
16622 if(!state || ovrride)
16624 SetPvP(state);
16625 if(Pet* pet = GetPet())
16626 pet->SetPvP(state);
16627 if(Unit* charmed = GetCharm())
16628 charmed->SetPvP(state);
16630 pvpInfo.endTimer = 0;
16632 else
16634 if(pvpInfo.endTimer != 0)
16635 pvpInfo.endTimer = time(NULL);
16636 else
16638 SetPvP(state);
16640 if(Pet* pet = GetPet())
16641 pet->SetPvP(state);
16642 if(Unit* charmed = GetCharm())
16643 charmed->SetPvP(state);
16648 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16650 SpellCooldown sc;
16651 sc.end = end_time;
16652 sc.itemid = itemid;
16653 m_spellCooldowns[spellid] = sc;
16656 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16658 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16659 return;
16661 // Get spell cooldwn
16662 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16663 // Apply spellmods
16664 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16665 if (cooldown < 0)
16666 cooldown = 0;
16667 // Add cooldown
16668 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16669 // Send activate
16670 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16671 data << spellInfo->Id;
16672 data << GetGUID();
16673 SendDirectMessage(&data);
16675 //slot to be excluded while counting
16676 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16678 if(!enchantmentcondition)
16679 return true;
16681 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16683 if(!Condition)
16684 return true;
16686 uint8 curcount[4] = {0, 0, 0, 0};
16688 //counting current equipped gem colors
16689 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
16691 if(i == slot)
16692 continue;
16693 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
16694 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
16696 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16698 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16699 if(!enchant_id)
16700 continue;
16702 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16703 if(!enchantEntry)
16704 continue;
16706 uint32 gemid = enchantEntry->GemID;
16707 if(!gemid)
16708 continue;
16710 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
16711 if(!gemProto)
16712 continue;
16714 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
16715 if(!gemProperty)
16716 continue;
16718 uint8 GemColor = gemProperty->color;
16720 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
16722 if(tmpcolormask & GemColor)
16723 ++curcount[b];
16729 bool activate = true;
16731 for(int i = 0; i < 5; i++)
16733 if(!Condition->Color[i])
16734 continue;
16736 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
16738 // if have <CompareColor> use them as count, else use <value> from Condition
16739 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
16741 switch(Condition->Comparator[i])
16743 case 2: // requires less <color> than (<value> || <comparecolor>) gems
16744 activate &= (_cur_gem < _cmp_gem) ? true : false;
16745 break;
16746 case 3: // requires more <color> than (<value> || <comparecolor>) gems
16747 activate &= (_cur_gem > _cmp_gem) ? true : false;
16748 break;
16749 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
16750 activate &= (_cur_gem >= _cmp_gem) ? true : false;
16751 break;
16755 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");
16757 return activate;
16760 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
16762 //cycle all equipped items
16763 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16765 //enchants for the slot being socketed are handled by Player::ApplyItemMods
16766 if(slot == exceptslot)
16767 continue;
16769 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16771 if(!pItem || !pItem->GetProto()->Socket[0].Color)
16772 continue;
16774 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16776 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16777 if(!enchant_id)
16778 continue;
16780 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16781 if(!enchantEntry)
16782 continue;
16784 uint32 condition = enchantEntry->EnchantmentCondition;
16785 if(condition)
16787 //was enchant active with/without item?
16788 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
16789 //should it now be?
16790 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
16792 // ignore item gem conditions
16793 //if state changed, (dis)apply enchant
16794 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
16801 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
16802 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
16804 //cycle all equipped items
16805 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16807 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
16808 if(slot == exceptslot)
16809 continue;
16811 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16813 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
16814 continue;
16816 //cycle all (gem)enchants
16817 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16819 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16820 if(!enchant_id) //if no enchant go to next enchant(slot)
16821 continue;
16823 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16824 if(!enchantEntry)
16825 continue;
16827 //only metagems to be (de)activated, so only enchants with condition
16828 uint32 condition = enchantEntry->EnchantmentCondition;
16829 if(condition)
16830 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
16835 void Player::LeaveBattleground(bool teleportToEntryPoint)
16837 if(BattleGround *bg = GetBattleGround())
16839 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
16841 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
16843 // call after remove to be sure that player resurrected for correct cast
16844 if(need_debuf)
16845 CastSpell(this, 26013, true); // Deserter
16849 bool Player::CanJoinToBattleground() const
16851 // check Deserter debuff
16852 if(GetDummyAura(26013))
16853 return false;
16855 return true;
16858 bool Player::CanReportAfkDueToLimit()
16860 // a player can complain about 15 people per 5 minutes
16861 if(m_bgAfkReportedCount >= 15)
16862 return false;
16863 ++m_bgAfkReportedCount;
16864 return true;
16867 ///This player has been blamed to be inactive in a battleground
16868 void Player::ReportedAfkBy(Player* reporter)
16870 BattleGround *bg = GetBattleGround();
16871 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
16872 return;
16874 // check if player has 'Idle' or 'Inactive' debuff
16875 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
16877 m_bgAfkReporter.insert(reporter->GetGUIDLow());
16878 // 3 players have to complain to apply debuff
16879 if(m_bgAfkReporter.size() >= 3)
16881 // cast 'Idle' spell
16882 CastSpell(this, 43680, true);
16883 m_bgAfkReporter.clear();
16888 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
16890 // gamemaster in GM mode see all, including ghosts
16891 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
16892 return true;
16894 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
16895 if (InBattleGround())
16897 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
16898 return false;
16899 return true;
16902 // Live player see live player or dead player with not realized corpse
16903 if(pl->isAlive() || pl->m_deathTimer > 0)
16905 return isAlive() || m_deathTimer > 0;
16908 // Ghost see other friendly ghosts, that's for sure
16909 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
16910 return true;
16912 // Dead player see live players near own corpse
16913 if(isAlive())
16915 Corpse *corpse = pl->GetCorpse();
16916 if(corpse)
16918 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
16919 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
16920 return true;
16924 // and not see any other
16925 return false;
16928 bool Player::IsVisibleGloballyFor( Player* u ) const
16930 if(!u)
16931 return false;
16933 // Always can see self
16934 if (u==this)
16935 return true;
16937 // Visible units, always are visible for all players
16938 if (GetVisibility() == VISIBILITY_ON)
16939 return true;
16941 // GMs are visible for higher gms (or players are visible for gms)
16942 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
16943 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
16945 // non faction visibility non-breakable for non-GMs
16946 if (GetVisibility() == VISIBILITY_OFF)
16947 return false;
16949 // non-gm stealth/invisibility not hide from global player lists
16950 return true;
16953 void Player::UpdateVisibilityOf(WorldObject* target)
16955 if(HaveAtClient(target))
16957 if(!target->isVisibleForInState(this,true))
16959 target->DestroyForPlayer(this);
16960 m_clientGUIDs.erase(target->GetGUID());
16962 #ifdef MANGOS_DEBUG
16963 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16964 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
16965 #endif
16968 else
16970 if(target->isVisibleForInState(this,false))
16972 target->SendUpdateToPlayer(this);
16973 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
16974 m_clientGUIDs.insert(target->GetGUID());
16976 #ifdef MANGOS_DEBUG
16977 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16978 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
16979 #endif
16981 // target aura duration for caster show only if target exist at caster client
16982 // send data at target visibility change (adding to client)
16983 if(target!=this && target->isType(TYPEMASK_UNIT))
16984 SendAuraDurationsForTarget((Unit*)target);
16986 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
16987 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
16992 template<class T>
16993 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
16995 s64.insert(target->GetGUID());
16998 template<>
16999 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17001 if(!target->IsTransport())
17002 s64.insert(target->GetGUID());
17005 template<class T>
17006 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17008 if(HaveAtClient(target))
17010 if(!target->isVisibleForInState(this,true))
17012 target->BuildOutOfRangeUpdateBlock(&data);
17013 m_clientGUIDs.erase(target->GetGUID());
17015 #ifdef MANGOS_DEBUG
17016 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17017 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));
17018 #endif
17021 else
17023 if(target->isVisibleForInState(this,false))
17025 visibleNow.insert(target);
17026 target->BuildUpdate(data_updates);
17027 target->BuildCreateUpdateBlockForPlayer(&data, this);
17028 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17030 #ifdef MANGOS_DEBUG
17031 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17032 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));
17033 #endif
17038 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17039 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17040 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17041 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17042 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17044 void Player::InitPrimaryProffesions()
17046 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17049 void Player::SendComboPoints()
17051 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17052 if (combotarget)
17054 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17055 data.append(combotarget->GetPackGUID());
17056 data << uint8(m_comboPoints);
17057 GetSession()->SendPacket(&data);
17061 void Player::AddComboPoints(Unit* target, int8 count)
17063 if(!count)
17064 return;
17066 // without combo points lost (duration checked in aura)
17067 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17069 if(target->GetGUID() == m_comboTarget)
17071 m_comboPoints += count;
17073 else
17075 if(m_comboTarget)
17076 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17077 target->RemoveComboPointHolder(GetGUIDLow());
17079 m_comboTarget = target->GetGUID();
17080 m_comboPoints = count;
17082 target->AddComboPointHolder(GetGUIDLow());
17085 if (m_comboPoints > 5) m_comboPoints = 5;
17086 if (m_comboPoints < 0) m_comboPoints = 0;
17088 SendComboPoints();
17091 void Player::ClearComboPoints()
17093 if(!m_comboTarget)
17094 return;
17096 // without combopoints lost (duration checked in aura)
17097 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17099 m_comboPoints = 0;
17101 SendComboPoints();
17103 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17104 target->RemoveComboPointHolder(GetGUIDLow());
17106 m_comboTarget = 0;
17109 void Player::SetGroup(Group *group, int8 subgroup)
17111 if(group == NULL) m_group.unlink();
17112 else
17114 // never use SetGroup without a subgroup unless you specify NULL for group
17115 assert(subgroup >= 0);
17116 m_group.link(group, this);
17117 m_group.setSubGroup((uint8)subgroup);
17121 void Player::SendInitialPacketsBeforeAddToMap()
17123 WorldPacket data(SMSG_SET_REST_START, 4);
17124 data << uint32(0); // unknown, may be rest state time or expirience
17125 GetSession()->SendPacket(&data);
17127 // Homebind
17128 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17129 data << m_homebindX << m_homebindY << m_homebindZ;
17130 data << (uint32) m_homebindMapId;
17131 data << (uint32) m_homebindZoneId;
17132 GetSession()->SendPacket(&data);
17134 // SMSG_SET_PROFICIENCY
17135 // SMSG_UPDATE_AURA_DURATION
17137 // tutorial stuff
17138 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17139 for (int i = 0; i < 8; ++i)
17140 data << uint32( GetTutorialInt(i) );
17141 GetSession()->SendPacket(&data);
17143 SendInitialSpells();
17145 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17146 data << uint32(0); // count, for(count) uint32;
17147 GetSession()->SendPacket(&data);
17149 SendInitialActionButtons();
17150 SendInitialReputations();
17151 UpdateZone(GetZoneId());
17152 SendInitWorldStates();
17154 // SMSG_SET_AURA_SINGLE
17156 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17157 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17158 data << (float)0.01666667f; // game speed
17159 GetSession()->SendPacket( &data );
17161 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17162 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17163 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17166 void Player::SendInitialPacketsAfterAddToMap()
17168 CastSpell(this, 836, true); // LOGINEFFECT
17170 // set some aura effects that send packet to player client after add player to map
17171 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17172 // same auras state lost at far teleport, send it one more time in this case also
17173 static const AuraType auratypes[] =
17175 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17176 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17177 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17179 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17181 Unit::AuraList const& auraList = GetAurasByType(*itr);
17182 if(!auraList.empty())
17183 auraList.front()->ApplyModifier(true,true);
17186 if(HasAuraType(SPELL_AURA_MOD_STUN))
17187 SetMovement(MOVE_ROOT);
17189 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17190 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17192 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17193 data.append(GetPackGUID());
17194 data << (uint32)2;
17195 SendMessageToSet(&data,true);
17198 SendEnchantmentDurations(); // must be after add to map
17199 SendItemDurations(); // must be after add to map
17202 void Player::SendUpdateToOutOfRangeGroupMembers()
17204 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17205 return;
17206 if(Group* group = GetGroup())
17207 group->UpdatePlayerOutOfRange(this);
17209 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17210 m_auraUpdateMask = 0;
17211 if(Pet *pet = GetPet())
17212 pet->ResetAuraUpdateMask();
17215 void Player::SendTransferAborted(uint32 mapid, uint16 reason)
17217 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17218 data << uint32(mapid);
17219 data << uint16(reason); // transfer abort reason
17220 GetSession()->SendPacket(&data);
17223 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17225 // type of warning, based on the time remaining until reset
17226 uint32 type;
17227 if(time > 3600)
17228 type = RAID_INSTANCE_WELCOME;
17229 else if(time > 900 && time <= 3600)
17230 type = RAID_INSTANCE_WARNING_HOURS;
17231 else if(time > 300 && time <= 900)
17232 type = RAID_INSTANCE_WARNING_MIN;
17233 else
17234 type = RAID_INSTANCE_WARNING_MIN_SOON;
17235 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17236 data << uint32(type);
17237 data << uint32(mapid);
17238 data << uint32(time);
17239 GetSession()->SendPacket(&data);
17242 void Player::ApplyEquipCooldown( Item * pItem )
17244 for(int i = 0; i <5; ++i)
17246 _Spell const& spellData = pItem->GetProto()->Spells[i];
17248 // no spell
17249 if( !spellData.SpellId )
17250 continue;
17252 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17253 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17254 continue;
17256 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17258 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17259 data << pItem->GetGUID();
17260 data << uint32(spellData.SpellId);
17261 GetSession()->SendPacket(&data);
17265 void Player::resetSpells()
17267 // not need after this call
17268 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17270 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17271 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17274 // make full copy of map (spells removed and marked as deleted at another spell remove
17275 // and we can't use original map for safe iterative with visit each spell at loop end
17276 PlayerSpellMap smap = GetSpellMap();
17278 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17279 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17281 learnDefaultSpells();
17282 learnQuestRewardedSpells();
17285 void Player::learnDefaultSpells(bool loading)
17287 // learn default race/class spells
17288 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17289 std::list<CreateSpellPair>::const_iterator spell_itr;
17290 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17292 uint16 tspell = spell_itr->first;
17293 if (tspell)
17295 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17296 if(loading || !spell_itr->second) // not care about passive spells or loading case
17297 addSpell(tspell,spell_itr->second);
17298 else // but send in normal spell in game learn case
17299 learnSpell(tspell);
17304 void Player::learnQuestRewardedSpells(Quest const* quest)
17306 uint32 spell_id = quest->GetRewSpellCast();
17308 // skip quests without rewarded spell
17309 if( !spell_id )
17310 return;
17312 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17313 if(!spellInfo)
17314 return;
17316 // check learned spells state
17317 bool found = false;
17318 for(int i=0; i < 3; ++i)
17320 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17322 found = true;
17323 break;
17327 // skip quests with not teaching spell or already known spell
17328 if(!found)
17329 return;
17331 // prevent learn non first rank unknown profession and second specialization for same profession)
17332 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17333 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17335 // not have first rank learned (unlearned prof?)
17336 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17337 if( !HasSpell(first_spell) )
17338 return;
17340 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17341 if(!learnedInfo)
17342 return;
17344 // specialization
17345 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17347 // search other specialization for same prof
17348 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17350 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17351 continue;
17353 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17354 if(!itrInfo)
17355 return;
17357 // compare only specializations
17358 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17359 continue;
17361 // compare same chain spells
17362 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17363 continue;
17365 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17366 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17367 return;
17372 CastSpell( this, spell_id, true);
17375 void Player::learnQuestRewardedSpells()
17377 // learn spells received from quest completing
17378 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17380 // skip no rewarded quests
17381 if(!itr->second.m_rewarded)
17382 continue;
17384 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17385 if( !quest )
17386 continue;
17388 learnQuestRewardedSpells(quest);
17392 void Player::learnSkillRewardedSpells(uint32 skill_id )
17394 uint32 raceMask = getRaceMask();
17395 uint32 classMask = getClassMask();
17396 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17398 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17399 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17400 continue;
17401 // Check race if set
17402 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17403 continue;
17404 // Check class if set
17405 if (pAbility->classmask && !(pAbility->classmask & classMask))
17406 continue;
17408 if (SpellEntry const* spellentry = sSpellStore.LookupEntry(pAbility->spellId))
17410 // Ok need learn spell
17411 learnSpell(pAbility->spellId);
17416 void Player::learnSkillRewardedSpells()
17418 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17420 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17421 continue;
17423 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17425 learnSkillRewardedSpells(pskill);
17429 void Player::SendAuraDurationsForTarget(Unit* target)
17431 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17433 Aura* aura = itr->second;
17434 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17435 continue;
17437 aura->SendAuraDurationForCaster(this);
17441 void Player::SetDailyQuestStatus( uint32 quest_id )
17443 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17445 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17447 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17448 m_lastDailyQuestTime = time(NULL); // last daily quest time
17449 m_DailyQuestChanged = true;
17450 break;
17455 void Player::ResetDailyQuestStatus()
17457 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17458 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17460 // DB data deleted in caller
17461 m_DailyQuestChanged = false;
17462 m_lastDailyQuestTime = 0;
17465 BattleGround* Player::GetBattleGround() const
17467 if(GetBattleGroundId()==0)
17468 return NULL;
17470 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17473 bool Player::InArena() const
17475 BattleGround *bg = GetBattleGround();
17476 if(!bg || !bg->isArena())
17477 return false;
17479 return true;
17482 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17484 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17485 if(!bg)
17486 return false;
17488 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17489 return false;
17491 return true;
17494 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17496 if(queue_id < 1)
17497 return 0;
17499 if(queue_id >=6)
17500 queue_id = 6;
17502 return 10*(queue_id+1);
17505 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17507 if(queue_id >=6)
17508 return 255; // hardcoded max level
17510 return 10*(queue_id+2)-1;
17513 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17515 uint32 level = getLevel();
17516 if(level <= 19)
17517 return 0;
17518 else if (level > 69)
17519 return 6;
17520 else
17521 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17524 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17526 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17527 if(!vendor_faction)
17528 return 1.0f;
17530 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17531 if(rank <= REP_NEUTRAL)
17532 return 1.0f;
17534 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17537 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17539 uint32 racemask = getRaceMask();
17540 uint32 classmask = getClassMask();
17542 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17543 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17545 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17547 // skip wrong race skills
17548 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17549 return false;
17551 // skip wrong class skills
17552 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17553 return false;
17555 return true;
17558 bool Player::HasQuestForGO(int32 GOId)
17560 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17562 QuestStatusData qs=i->second;
17563 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17565 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17566 if(!qinfo)
17567 continue;
17569 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17570 continue;
17572 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17574 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17575 continue;
17577 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17578 return true;
17582 return false;
17585 void Player::UpdateForQuestsGO()
17587 if(m_clientGUIDs.empty())
17588 return;
17590 UpdateData udata;
17591 WorldPacket packet;
17592 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17594 if(IS_GAMEOBJECT_GUID(*itr))
17596 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17597 if(obj)
17598 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17601 udata.BuildPacket(&packet);
17602 GetSession()->SendPacket(&packet);
17605 void Player::SummonIfPossible(bool agree)
17607 if(!agree)
17609 m_summon_expire = 0;
17610 return;
17613 // expire and auto declined
17614 if(m_summon_expire < time(NULL))
17615 return;
17617 // stop taxi flight at summon
17618 if(isInFlight())
17620 GetMotionMaster()->MovementExpired();
17621 m_taxi.ClearTaxiDestinations();
17624 // drop flag at summon
17625 if(BattleGround *bg = GetBattleGround())
17626 bg->EventPlayerDroppedFlag(this);
17628 m_summon_expire = 0;
17630 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17633 void Player::RemoveItemDurations( Item *item )
17635 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17637 if(*itr==item)
17639 m_itemDuration.erase(itr);
17640 break;
17645 void Player::AddItemDurations( Item *item )
17647 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17649 m_itemDuration.push_back(item);
17650 item->SendTimeUpdate(this);
17654 void Player::AutoUnequipOffhandIfNeed()
17656 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
17657 if(!offItem)
17658 return;
17660 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
17662 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
17663 return;
17665 ItemPosCountVec off_dest;
17666 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
17667 if( off_msg == EQUIP_ERR_OK )
17669 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
17670 StoreItem( off_dest, offItem, true );
17672 else
17674 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
17678 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
17680 if(spellInfo->EquippedItemClass < 0)
17681 return true;
17683 // scan other equipped items for same requirements (mostly 2 daggers/etc)
17684 // for optimize check 2 used cases only
17685 switch(spellInfo->EquippedItemClass)
17687 case ITEM_CLASS_WEAPON:
17689 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
17690 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17691 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17692 return true;
17693 break;
17695 case ITEM_CLASS_ARMOR:
17697 // tabard not have dependent spells
17698 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
17699 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17700 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17701 return true;
17703 // shields can be equipped to offhand slot
17704 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
17705 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17706 return true;
17708 // ranged slot can have some armor subclasses
17709 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
17710 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17711 return true;
17713 break;
17715 default:
17716 sLog.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo->EquippedItemClass);
17717 break;
17720 return false;
17723 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
17725 AuraMap& auras = GetAuras();
17726 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
17728 Aura* aura = itr->second;
17730 // skip passive (passive item dependent spells work in another way) and not self applied auras
17731 SpellEntry const* spellInfo = aura->GetSpellProto();
17732 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17734 ++itr;
17735 continue;
17738 // skip if not item dependent or have alternative item
17739 if(HasItemFitToSpellReqirements(spellInfo,pItem))
17741 ++itr;
17742 continue;
17745 // no alt item, remove aura, restart check
17746 RemoveAurasDueToSpell(aura->GetId());
17747 itr = auras.begin();
17750 // currently casted spells can be dependent from item
17751 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
17753 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
17754 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
17755 InterruptSpell(i);
17759 uint32 Player::GetResurrectionSpellId()
17761 // search priceless resurrection possabilities
17762 uint32 prio = 0;
17763 uint32 spell_id = 0;
17764 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
17765 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
17767 // Soulstone Resurrection // prio: 3 (max, non death persistent)
17768 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
17770 switch((*itr)->GetId())
17772 case 20707: spell_id = 3026; break; // rank 1
17773 case 20762: spell_id = 20758; break; // rank 2
17774 case 20763: spell_id = 20759; break; // rank 3
17775 case 20764: spell_id = 20760; break; // rank 4
17776 case 20765: spell_id = 20761; break; // rank 5
17777 case 27239: spell_id = 27240; break; // rank 6
17778 default:
17779 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
17780 continue;
17783 prio = 3;
17785 // Twisting Nether // prio: 2 (max)
17786 else if((*itr)->GetId()==23701 && roll_chance_i(10))
17788 prio = 2;
17789 spell_id = 23700;
17793 // Reincarnation (passive spell) // prio: 1
17794 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
17795 spell_id = 21169;
17797 return spell_id;
17800 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
17802 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
17804 // prepare data for near group iteration (PvP and !PvP cases)
17805 uint32 xp = 0;
17806 bool honored_kill = false;
17808 if(Group *pGroup = GetGroup())
17810 uint32 count = 0;
17811 uint32 sum_level = 0;
17812 Player* member_with_max_level = NULL;
17814 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level);
17816 if(member_with_max_level)
17818 xp = PvP ? 0 : MaNGOS::XP::Gain(member_with_max_level, pVictim);
17820 // skip in check PvP case (for speed, not used)
17821 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
17822 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
17823 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
17825 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
17827 Player* pGroupGuy = itr->getSource();
17828 if(!pGroupGuy)
17829 continue;
17831 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
17832 continue; // member (alive or dead) or his corpse at req. distance
17834 // honor can be in PvP and !PvP (racial leader) cases (for alive)
17835 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
17836 honored_kill = true;
17838 // xp and reputation only in !PvP case
17839 if(!PvP)
17841 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
17843 // if is in dungeon then all receive full reputation at kill
17844 // rewarded any alive/dead/near_corpse group member
17845 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
17847 // XP updated only for alive group member
17848 if(pGroupGuy->isAlive())
17850 uint32 itr_xp = uint32(xp*rate);
17852 pGroupGuy->GiveXP(itr_xp, pVictim);
17853 if(Pet* pet = pGroupGuy->GetPet())
17854 pet->GivePetXP(itr_xp/2);
17857 // quest objectives updated only for alive group member or dead but with not released body
17858 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
17860 // normal creature (not pet/etc) can be only in !PvP case
17861 if(pVictim->GetTypeId()==TYPEID_UNIT)
17862 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
17868 else // if (!pGroup)
17870 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
17872 // honor can be in PvP and !PvP (racial leader) cases
17873 if(RewardHonor(pVictim,1))
17874 honored_kill = true;
17876 // xp and reputation only in !PvP case
17877 if(!PvP)
17879 RewardReputation(pVictim,1);
17880 GiveXP(xp, pVictim);
17882 if(Pet* pet = GetPet())
17883 pet->GivePetXP(xp);
17885 // normal creature (not pet/etc) can be only in !PvP case
17886 if(pVictim->GetTypeId()==TYPEID_UNIT)
17887 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
17890 return xp || honored_kill;
17893 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
17895 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
17896 return true;
17898 if(isAlive())
17899 return false;
17901 Corpse* corpse = GetCorpse();
17902 if(!corpse)
17903 return false;
17905 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
17908 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
17910 Item* item = GetWeaponForAttack(attType,true);
17912 // unarmmed only with base attack
17913 if(attType != BASE_ATTACK && !item)
17914 return 0;
17916 // weapon skill or (unarmed for base attack)
17917 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
17918 return GetBaseSkillValue(skill);
17921 void Player::ResurectUsingRequestData()
17923 ResurrectPlayer(0.0f,false);
17925 if(GetMaxHealth() > m_resurrectHealth)
17926 SetHealth( m_resurrectHealth );
17927 else
17928 SetHealth( GetMaxHealth() );
17930 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
17931 SetPower(POWER_MANA, m_resurrectMana );
17932 else
17933 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
17935 SetPower(POWER_RAGE, 0 );
17937 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
17939 SpawnCorpseBones();
17941 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
17944 void Player::SetClientControl(Unit* target, uint8 allowMove)
17946 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
17947 data.append(target->GetPackGUID());
17948 data << uint8(allowMove);
17949 GetSession()->SendPacket(&data);
17952 void Player::UpdateZoneDependentAuras( uint32 newZone )
17954 // remove new continent flight forms
17955 if( !isGameMaster() &&
17956 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
17958 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
17959 RemoveSpellsCausingAura(SPELL_AURA_FLY);
17962 // Some spells applied at enter into zone (with subzones)
17963 // Human Illusion
17964 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
17965 if ( newZone == 2367 ) // Old Hillsbrad Foothills
17967 uint32 spellid = 0;
17968 // all horde races
17969 if( GetTeam() == HORDE )
17970 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
17971 // and some alliance races
17972 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
17973 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
17975 if(spellid && !HasAura(spellid,0) )
17976 CastSpell(this,spellid,true);
17980 void Player::UpdateAreaDependentAuras( uint32 newArea )
17982 // remove auras from spells with area limitations
17983 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
17985 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
17986 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
17987 RemoveAura(iter);
17988 else
17989 ++iter;
17992 // unmount if enter in this subzone
17993 if( newArea == 35)
17994 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17995 // Dragonmaw Illusion
17996 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
17998 if( GetDummyAura(40214) )
18000 if( !HasAura(40216,0) )
18001 CastSpell(this,40216,true);
18002 if( !HasAura(42016,0) )
18003 CastSpell(this,42016,true);
18008 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18010 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18011 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18013 return copseReclaimDelay[0];
18016 time_t now = time(NULL);
18017 // 0..2 full period
18018 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18019 return copseReclaimDelay[count];
18022 void Player::UpdateCorpseReclaimDelay()
18024 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18026 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18027 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18028 return;
18030 time_t now = time(NULL);
18031 if(now < m_deathExpireTime)
18033 // full and partly periods 1..3
18034 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18035 if(count < MAX_DEATH_COUNT)
18036 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18037 else
18038 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18040 else
18041 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18044 void Player::SendCorpseReclaimDelay(bool load)
18046 Corpse* corpse = GetCorpse();
18047 if(!corpse)
18048 return;
18050 uint32 delay;
18051 if(load)
18053 if(corpse->GetGhostTime() > m_deathExpireTime)
18054 return;
18056 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18058 uint32 count;
18059 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18060 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18062 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18063 if(count>=MAX_DEATH_COUNT)
18064 count = MAX_DEATH_COUNT-1;
18066 else
18067 count=0;
18069 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18071 time_t now = time(NULL);
18072 if(now >= expected_time)
18073 return;
18075 delay = expected_time-now;
18077 else
18078 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18080 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18081 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18082 data << uint32(delay*1000);
18083 GetSession()->SendPacket( &data );
18086 Player* Player::GetNextRandomRaidMember(float radius)
18088 Group *pGroup = GetGroup();
18089 if(!pGroup)
18090 return NULL;
18092 std::vector<Player*> nearMembers;
18093 nearMembers.reserve(pGroup->GetMembersCount());
18095 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18097 Player* Target = itr->getSource();
18099 // IsHostileTo check duel and controlled by enemy
18100 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18101 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18102 nearMembers.push_back(Target);
18105 if (nearMembers.empty())
18106 return NULL;
18108 uint32 randTarget = urand(0,nearMembers.size()-1);
18109 return nearMembers[randTarget];
18112 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18114 float water_z = m->GetWaterLevel(x,y);
18115 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18116 uint8 flag1 = m->GetTerrainType(x,y);
18118 //!Underwater check, not in water if underground or above water level
18119 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18120 m_isunderwater &= 0x7A;
18121 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18122 m_isunderwater |= 0x01;
18124 //!in lava check, anywhere under lava level
18125 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18126 m_isunderwater |= 0x80;
18129 void Player::SetCanParry( bool value )
18131 if(m_canParry==value)
18132 return;
18134 m_canParry = value;
18135 UpdateParryPercentage();
18138 void Player::SetCanBlock( bool value )
18140 if(m_canBlock==value)
18141 return;
18143 m_canBlock = value;
18144 UpdateBlockPercentage();
18147 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18149 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18150 if(itr->pos == this->pos)
18151 return true;
18153 return false;
18156 bool Player::isAllowUseBattleGroundObject()
18158 return ( //InBattleGround() && // in battleground - not need, check in other cases
18159 !IsMounted() && // not mounted
18160 !HasStealthAura() && // not stealthed
18161 !HasInvisibilityAura() && // not invisible
18162 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18163 isAlive() // live player