Merge branch 'master' into 303
[getmangos.git] / src / game / Player.cpp
blob444785e112e3601bd4868e614a743443add92cad
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
147 // new continent starting masks (It will be accessible only at new map)
148 switch(Player::TeamForRace(race))
150 case ALLIANCE: SetTaximaskNode(100); break;
151 case HORDE: SetTaximaskNode(99); break;
153 // level dependent taxi hubs
154 if(level>=68)
155 SetTaximaskNode(213); //Shattered Sun Staging Area
158 void PlayerTaxi::LoadTaxiMask(const char* data)
160 Tokens tokens = StrSplit(data, " ");
162 int index;
163 Tokens::iterator iter;
164 for (iter = tokens.begin(), index = 0;
165 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
167 // load and set bits only for existed taxi nodes
168 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
172 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
174 if(all)
176 for (uint8 i=0; i<TaxiMaskSize; i++)
177 data << uint32(sTaxiNodesMask[i]); // all existed nodes
179 else
181 for (uint8 i=0; i<TaxiMaskSize; i++)
182 data << uint32(m_taximask[i]); // known nodes
186 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values )
188 ClearTaxiDestinations();
190 Tokens tokens = StrSplit(values," ");
192 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
194 uint32 node = uint32(atol(iter->c_str()));
195 AddTaxiDestination(node);
198 if(m_TaxiDestinations.empty())
199 return true;
201 // Check integrity
202 if(m_TaxiDestinations.size() < 2)
203 return false;
205 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
207 uint32 cost;
208 uint32 path;
209 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
210 if(!path)
211 return false;
214 return true;
217 std::string PlayerTaxi::SaveTaxiDestinationsToString()
219 if(m_TaxiDestinations.empty())
220 return "";
222 std::ostringstream ss;
224 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
225 ss << m_TaxiDestinations[i] << " ";
227 return ss.str();
230 uint32 PlayerTaxi::GetCurrentTaxiPath() const
232 if(m_TaxiDestinations.size() < 2)
233 return 0;
235 uint32 path;
236 uint32 cost;
238 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
240 return path;
243 //== Player ====================================================
245 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
247 UpdateMask Player::updateVisualBits;
249 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
251 m_transport = 0;
253 m_speakTime = 0;
254 m_speakCount = 0;
256 m_objectType |= TYPEMASK_PLAYER;
257 m_objectTypeId = TYPEID_PLAYER;
259 m_valuesCount = PLAYER_END;
261 m_session = session;
263 m_divider = 0;
265 m_ExtraFlags = 0;
266 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
267 SetAcceptTicket(true);
269 // players always accept
270 if(GetSession()->GetSecurity() == SEC_PLAYER)
271 SetAcceptWhispers(true);
273 m_curSelection = 0;
274 m_lootGuid = 0;
276 m_comboTarget = 0;
277 m_comboPoints = 0;
279 m_usedTalentCount = 0;
281 m_regenTimer = 0;
282 m_weaponChangeTimer = 0;
284 m_zoneUpdateId = 0;
285 m_zoneUpdateTimer = 0;
287 m_areaUpdateId = 0;
289 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
291 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
292 // this must help in case next save after mass player load after server startup
293 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
295 clearResurrectRequestData();
297 m_SpellModRemoveCount = 0;
299 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
301 m_social = NULL;
303 // group is initialized in the reference constructor
304 SetGroupInvite(NULL);
305 m_groupUpdateMask = 0;
306 m_auraUpdateMask = 0;
308 duel = NULL;
310 m_GuildIdInvited = 0;
311 m_ArenaTeamIdInvited = 0;
313 m_atLoginFlags = AT_LOGIN_NONE;
315 m_dontMove = false;
317 pTrader = 0;
318 ClearTrade();
320 m_cinematic = 0;
322 PlayerTalkClass = new PlayerMenu( GetSession() );
323 m_currentBuybackSlot = BUYBACK_SLOT_START;
325 for ( int aX = 0 ; aX < 8 ; aX++ )
326 m_Tutorials[ aX ] = 0x00;
327 m_TutorialsChanged = false;
329 m_DailyQuestChanged = false;
330 m_lastDailyQuestTime = 0;
332 m_regenTimer = 0;
333 m_weaponChangeTimer = 0;
334 m_breathTimer = 0;
335 m_isunderwater = 0;
336 m_isInWater = false;
337 m_drunkTimer = 0;
338 m_drunk = 0;
339 m_restTime = 0;
340 m_deathTimer = 0;
341 m_deathExpireTime = 0;
343 m_swingErrorMsg = 0;
345 m_DetectInvTimer = 1000;
347 m_bgBattleGroundID = 0;
348 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
350 m_bgBattleGroundQueueID[j].bgType = 0;
351 m_bgBattleGroundQueueID[j].invited = false;
353 m_bgTeam = 0;
355 m_logintime = time(NULL);
356 m_Last_tick = m_logintime;
357 m_WeaponProficiency = 0;
358 m_ArmorProficiency = 0;
359 m_canParry = false;
360 m_canBlock = false;
361 m_canDualWield = false;
362 m_ammoDPS = 0.0f;
364 m_temporaryUnsummonedPetNumber = 0;
365 //cache for UNIT_CREATED_BY_SPELL to allow
366 //returning reagents for temporarily removed pets
367 //when dying/logging out
368 m_oldpetspell = 0;
370 ////////////////////Rest System/////////////////////
371 time_inn_enter=0;
372 inn_pos_mapid=0;
373 inn_pos_x=0;
374 inn_pos_y=0;
375 inn_pos_z=0;
376 m_rest_bonus=0;
377 rest_type=REST_TYPE_NO;
378 ////////////////////Rest System/////////////////////
380 m_mailsLoaded = false;
381 m_mailsUpdated = false;
382 unReadMails = 0;
383 m_nextMailDelivereTime = 0;
385 m_resetTalentsCost = 0;
386 m_resetTalentsTime = 0;
387 m_itemUpdateQueueBlocked = false;
389 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
390 m_forced_speed_changes[i] = 0;
392 m_stableSlots = 0;
394 /////////////////// Instance System /////////////////////
396 m_HomebindTimer = 0;
397 m_InstanceValid = true;
398 m_dungeonDifficulty = DIFFICULTY_NORMAL;
400 for (int i = 0; i < BASEMOD_END; i++)
402 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
403 m_auraBaseMod[i][PCT_MOD] = 1.0f;
406 // Honor System
407 m_lastHonorUpdateTime = time(NULL);
409 // Player summoning
410 m_summon_expire = 0;
411 m_summon_mapid = 0;
412 m_summon_x = 0.0f;
413 m_summon_y = 0.0f;
414 m_summon_z = 0.0f;
416 //Default movement to run mode
417 m_unit_movement_flags = 0;
419 m_miniPet = 0;
420 m_bgAfkReportedTimer = 0;
421 m_contestedPvPTimer = 0;
423 m_declinedname = NULL;
426 Player::~Player ()
428 CleanupsBeforeDelete();
430 // it must be unloaded already in PlayerLogout and accessed only for loggined player
431 //m_social = NULL;
433 // Note: buy back item already deleted from DB when player was saved
434 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
436 if(m_items[i])
437 delete m_items[i];
439 CleanupChannels();
441 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
442 delete itr->second;
444 //all mailed items should be deleted, also all mail should be deallocated
445 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
446 delete *itr;
448 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
449 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
451 delete PlayerTalkClass;
453 if (m_transport)
455 m_transport->RemovePassenger(this);
458 for(size_t x = 0; x < ItemSetEff.size(); x++)
459 if(ItemSetEff[x])
460 delete ItemSetEff[x];
462 // clean up player-instance binds, may unload some instance saves
463 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
464 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
465 itr->second.save->RemovePlayer(this);
467 delete m_declinedname;
470 void Player::CleanupsBeforeDelete()
472 if(m_uint32Values) // only for fully created Object
474 TradeCancel(false);
475 DuelComplete(DUEL_INTERUPTED);
477 Unit::CleanupsBeforeDelete();
480 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 )
482 //FIXME: outfitId not used in player creating
484 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
486 m_name = name;
488 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
489 if(!info)
491 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
492 return false;
495 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
496 m_items[i] = NULL;
498 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
500 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
501 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
502 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
505 m_race = race;
506 m_class = class_;
508 SetMapId(info->mapId);
509 Relocate(info->positionX,info->positionY,info->positionZ);
511 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
512 if(!cEntry)
514 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
515 return false;
518 uint8 powertype = cEntry->powerType;
520 uint32 unitfield;
522 switch(powertype)
524 case POWER_ENERGY:
525 case POWER_MANA:
526 unitfield = 0x00000000;
527 break;
528 case POWER_RAGE:
529 unitfield = 0x00110000;
530 break;
531 case POWER_RUNIC_POWER:
532 unitfield = 0x0000EE00; //TODO: find correct unitfield here
533 break;
534 default:
535 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
536 return false;
539 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
540 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
542 switch(gender)
544 case GENDER_FEMALE:
545 SetDisplayId(info->displayId_f );
546 SetNativeDisplayId(info->displayId_f );
547 break;
548 case GENDER_MALE:
549 SetDisplayId(info->displayId_m );
550 SetNativeDisplayId(info->displayId_m );
551 break;
552 default:
553 sLog.outError("Invalid gender %u for player",gender);
554 return false;
555 break;
558 setFactionForRace(m_race);
560 SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
561 SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
562 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
563 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
564 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
566 //-1 is default value
567 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
569 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
570 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
571 SetByteValue(PLAYER_BYTES_3, 0, gender);
573 SetUInt32Value( PLAYER_GUILDID, 0 );
574 SetUInt32Value( PLAYER_GUILDRANK, 0 );
575 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
577 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
578 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
579 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
580 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
581 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
582 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
584 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
586 GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i);
587 if(gs && gs->Order)
588 SetGlyphSlot(gs->Order - 1, gs->Id);
591 // set starting level
592 if(getClass() == CLASS_DEATH_KNIGHT)
593 SetUInt32Value(UNIT_FIELD_LEVEL, 55);
594 else
595 SetUInt32Value( UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) );
597 // Played time
598 m_Last_tick = time(NULL);
599 m_Played_time[0] = 0;
600 m_Played_time[1] = 0;
602 // base stats and related field values
603 InitStatsForLevel();
604 InitTaxiNodesForLevel();
605 InitGlyphsForLevel();
606 InitTalentForLevel();
607 InitPrimaryProffesions(); // to max set before any spell added
609 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
610 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
611 SetHealth(GetMaxHealth());
612 if (getPowerType()==POWER_MANA)
614 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
615 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
618 learnDefaultSpells(true);
620 std::list<uint16>::const_iterator action_itr[4];
621 for(int i=0; i<4; i++)
622 action_itr[i] = info->action[i].begin();
624 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
626 uint16 taction[4];
627 for(int i=0; i<4 ;i++)
628 taction[i] = (*action_itr[i]);
630 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
632 for(int i=0; i<4 ;i++)
633 ++action_itr[i];
636 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
638 uint32 titem_id = item_id_itr->item_id;
639 uint32 titem_amount = item_id_itr->item_amount;
641 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
643 // attempt equip
644 uint16 eDest;
645 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
646 if( msg == EQUIP_ERR_OK )
648 EquipNewItem( eDest, titem_id, titem_amount, true);
649 AutoUnequipOffhandIfNeed();
650 continue; // equipped, to next
653 // attempt store
654 ItemPosCountVec sDest;
655 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
656 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
657 if( msg == EQUIP_ERR_OK )
659 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
660 continue; // stored, to next
663 // item can't be added
664 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,race,class_,msg);
667 // bags and main-hand weapon must equipped at this moment
668 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
669 // or ammo not equipped in special bag
670 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
672 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
674 uint16 eDest;
675 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
676 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
677 if( msg == EQUIP_ERR_OK )
679 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
680 EquipItem( eDest, pItem, true);
682 // move other items to more appropriate slots (ammo not equipped in special bag)
683 else
685 ItemPosCountVec sDest;
686 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
687 if( msg == EQUIP_ERR_OK )
689 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
690 pItem = StoreItem( sDest, pItem, true);
693 // if this is ammo then use it
694 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
695 if( msg == EQUIP_ERR_OK )
696 SetAmmo( pItem->GetProto()->ItemId );
700 // all item positions resolved
702 return true;
705 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
707 uint32 BreathRegen = (uint32)-1;
709 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
710 data << (uint32)Type;
711 data << MaxValue;
712 data << MaxValue;
713 data << BreathRegen;
714 data << (uint8)0;
715 data << (uint32)0; // spell id
716 GetSession()->SendPacket(&data);
719 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
721 if(Type==BREATH_TIMER)
722 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
724 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
725 data << (uint32)Type;
726 data << CurrentValue;
727 data << MaxValue;
728 data << Regen;
729 data << (uint8)0;
730 data << (uint32)0; // spell id
731 GetSession()->SendPacket( &data );
734 void Player::StopMirrorTimer(MirrorTimerType Type)
736 if(Type==BREATH_TIMER)
737 m_breathTimer = 0;
739 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
740 data << (uint32)Type;
741 GetSession()->SendPacket( &data );
744 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
746 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
747 data << (uint64)guid;
748 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
749 data << (uint32)damage;
750 data << (uint32)0;
751 data << (uint32)0;
752 SendMessageToSet(&data, true);
754 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
756 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
758 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
759 DurabilityLossAll(0.10f,false);
760 // durability lost message
761 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
762 GetSession()->SendPacket(&data);
766 void Player::HandleDrowning()
768 if(!m_isunderwater)
769 return;
771 //if have water breath , then remove bar
772 if(waterbreath || isGameMaster() || !isAlive())
774 StopMirrorTimer(BREATH_TIMER);
775 m_isunderwater = 0;
776 return;
779 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
781 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
782 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
783 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
785 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
787 //single trigger timer
788 if (!(m_isunderwater & 0x02))
790 m_isunderwater|= 0x02;
791 m_breathTimer = UnderWaterTime + 1000;
793 //single trigger "Breathbar"
794 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
796 m_isunderwater|= 0x04;
797 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
799 //continius trigger drowning "Damage"
800 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
802 //TODO: Check this formula
803 uint64 guid = GetGUID();
804 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
806 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
807 m_breathTimer = 2000;
810 //single trigger retract bar
811 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
813 m_isunderwater = 0x08;
815 uint32 BreathRegen = 10;
816 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
817 m_isunderwater = 0x10;
819 //remove bar
820 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
822 StopMirrorTimer(BREATH_TIMER);
823 m_isunderwater = 0;
827 void Player::HandleLava()
829 bool ValidArea = false;
831 if ((m_isunderwater & 0x80) && isAlive())
833 //Single trigger Set BreathTimer
834 if (!(m_isunderwater & 0x80))
836 m_isunderwater|= 0x04;
837 m_breathTimer = 1000;
839 //Reset BreathTimer and still in the lava
840 if (!m_breathTimer)
842 uint64 guid = GetGUID();
843 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
844 uint32 dmgZone = GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
846 // Deal lava damage only in lava zones.
847 switch(dmgZone)
849 case 0x8D:
850 ValidArea = false;
851 break;
852 case 0x94:
853 ValidArea = false;
854 break;
855 case 0x2CE:
856 ValidArea = false;
857 break;
858 case 0x2CF:
859 ValidArea = false;
860 break;
861 default:
862 if (dmgZone / 5 & 0x408)
863 ValidArea = true;
866 // if is valid area and is not gamemaster then deal damage
867 if ( ValidArea && !isGameMaster() )
868 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
870 m_breathTimer = 1000;
874 //Death timer disabled and WaterFlags reset
875 else if (m_deathState == DEAD)
877 m_breathTimer = 0;
878 m_isunderwater = 0;
882 ///The player sobers by 256 every 10 seconds
883 void Player::HandleSobering()
885 m_drunkTimer = 0;
887 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
888 SetDrunkValue(drunk);
891 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
893 if(value >= 23000)
894 return DRUNKEN_SMASHED;
895 if(value >= 12800)
896 return DRUNKEN_DRUNK;
897 if(value & 0xFFFE)
898 return DRUNKEN_TIPSY;
899 return DRUNKEN_SOBER;
902 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
904 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
906 m_drunk = newDrunkenValue;
907 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
909 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
911 // special drunk invisibility detection
912 if(newDrunkenState >= DRUNKEN_DRUNK)
913 m_detectInvisibilityMask |= (1<<6);
914 else
915 m_detectInvisibilityMask &= ~(1<<6);
917 if(newDrunkenState == oldDrunkenState)
918 return;
920 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
921 data << GetGUID();
922 data << uint32(newDrunkenState);
923 data << uint32(itemId);
925 SendMessageToSet(&data, true);
928 void Player::Update( uint32 p_time )
930 if(!IsInWorld())
931 return;
933 // undelivered mail
934 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
936 SendNewMail();
937 ++unReadMails;
939 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
940 m_nextMailDelivereTime = 0;
943 Unit::Update( p_time );
945 // update player only attacks
946 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
948 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
951 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
953 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
956 time_t now = time (NULL);
958 UpdatePvPFlag(now);
960 UpdateContestedPvP(p_time);
962 UpdateDuelFlag(now);
964 CheckDuelDistance(now);
966 UpdateAfkReport(now);
968 CheckExploreSystem();
970 // Update items that have just a limited lifetime
971 if (now>m_Last_tick)
972 UpdateItemDuration(uint32(now- m_Last_tick));
974 if (!m_timedquests.empty())
976 std::set<uint32>::iterator iter = m_timedquests.begin();
977 while (iter != m_timedquests.end())
979 QuestStatusData& q_status = mQuestStatus[*iter];
980 if( q_status.m_timer <= p_time )
982 uint32 quest_id = *iter;
983 ++iter; // current iter will be removed in FailTimedQuest
984 FailTimedQuest( quest_id );
986 else
988 q_status.m_timer -= p_time;
989 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
990 ++iter;
995 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
997 Unit *pVictim = getVictim();
998 if( !IsNonMeleeSpellCasted(false) && pVictim)
1000 // default combat reach 10
1001 // TODO add weapon,skill check
1003 float pldistance = ATTACK_DISTANCE;
1005 if (isAttackReady(BASE_ATTACK))
1007 if(!IsWithinDistInMap(pVictim, pldistance))
1009 setAttackTimer(BASE_ATTACK,100);
1010 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1012 SendAttackSwingNotInRange();
1013 m_swingErrorMsg = 1;
1016 //120 degrees of radiant range
1017 else if( !HasInArc( 2*M_PI/3, pVictim ))
1019 setAttackTimer(BASE_ATTACK,100);
1020 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1022 SendAttackSwingBadFacingAttack();
1023 m_swingErrorMsg = 2;
1026 else
1028 m_swingErrorMsg = 0; // reset swing error state
1030 // prevent base and off attack in same time, delay attack at 0.2 sec
1031 if(haveOffhandWeapon())
1033 uint32 off_att = getAttackTimer(OFF_ATTACK);
1034 if(off_att < ATTACK_DISPLAY_DELAY)
1035 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1037 AttackerStateUpdate(pVictim, BASE_ATTACK);
1038 resetAttackTimer(BASE_ATTACK);
1042 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1044 if(!IsWithinDistInMap(pVictim, pldistance))
1046 setAttackTimer(OFF_ATTACK,100);
1048 else if( !HasInArc( 2*M_PI/3, pVictim ))
1050 setAttackTimer(OFF_ATTACK,100);
1052 else
1054 // prevent base and off attack in same time, delay attack at 0.2 sec
1055 uint32 base_att = getAttackTimer(BASE_ATTACK);
1056 if(base_att < ATTACK_DISPLAY_DELAY)
1057 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1058 // do attack
1059 AttackerStateUpdate(pVictim, OFF_ATTACK);
1060 resetAttackTimer(OFF_ATTACK);
1064 Unit *owner = pVictim->GetOwner();
1065 Unit *u = owner ? owner : pVictim;
1066 if(u->IsPvP() && (!duel || duel->opponent != u))
1068 UpdatePvP(true);
1069 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1074 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1076 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1078 int time_inn = time(NULL)-GetTimeInnEnter();
1079 if (time_inn >= 10) //freeze update
1081 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1082 //speed collect rest bonus (section/in hour)
1083 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1084 UpdateInnerTime(time(NULL));
1089 if(m_regenTimer > 0)
1091 if(p_time >= m_regenTimer)
1092 m_regenTimer = 0;
1093 else
1094 m_regenTimer -= p_time;
1097 if (m_weaponChangeTimer > 0)
1099 if(p_time >= m_weaponChangeTimer)
1100 m_weaponChangeTimer = 0;
1101 else
1102 m_weaponChangeTimer -= p_time;
1105 if (m_zoneUpdateTimer > 0)
1107 if(p_time >= m_zoneUpdateTimer)
1109 uint32 newzone = GetZoneId();
1110 if( m_zoneUpdateId != newzone )
1111 UpdateZone(newzone); // also update area
1112 else
1114 // use area updates as well
1115 // needed for free far all arenas for example
1116 uint32 newarea = GetAreaId();
1117 if( m_areaUpdateId != newarea )
1118 UpdateArea(newarea);
1120 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1123 else
1124 m_zoneUpdateTimer -= p_time;
1127 if (isAlive())
1129 RegenerateAll();
1132 if (m_deathState == JUST_DIED)
1134 KillPlayer();
1137 if(m_nextSave > 0)
1139 if(p_time >= m_nextSave)
1141 // m_nextSave reseted in SaveToDB call
1142 SaveToDB();
1143 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1145 else
1147 m_nextSave -= p_time;
1151 //Breathtimer
1152 if(m_breathTimer > 0)
1154 if(p_time >= m_breathTimer)
1155 m_breathTimer = 0;
1156 else
1157 m_breathTimer -= p_time;
1161 //Handle Water/drowning
1162 HandleDrowning();
1164 //Handle lava
1165 HandleLava();
1167 //Handle detect stealth players
1168 if (m_DetectInvTimer > 0)
1170 if (p_time >= m_DetectInvTimer)
1172 m_DetectInvTimer = 3000;
1173 HandleStealthedUnitsDetection();
1175 else
1176 m_DetectInvTimer -= p_time;
1179 // Played time
1180 if (now > m_Last_tick)
1182 uint32 elapsed = uint32(now - m_Last_tick);
1183 m_Played_time[0] += elapsed; // Total played time
1184 m_Played_time[1] += elapsed; // Level played time
1185 m_Last_tick = now;
1188 if (m_drunk)
1190 m_drunkTimer += p_time;
1192 if (m_drunkTimer > 10000)
1193 HandleSobering();
1196 // not auto-free ghost from body in instances
1197 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1199 if(p_time >= m_deathTimer)
1201 m_deathTimer = 0;
1202 BuildPlayerRepop();
1203 RepopAtGraveyard();
1205 else
1206 m_deathTimer -= p_time;
1209 UpdateEnchantTime(p_time);
1210 UpdateHomebindTime(p_time);
1212 // group update
1213 SendUpdateToOutOfRangeGroupMembers();
1215 Pet* pet = GetPet();
1216 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1218 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1219 return;
1223 void Player::setDeathState(DeathState s)
1225 uint32 ressSpellId = 0;
1227 bool cur = isAlive();
1229 if(s == JUST_DIED && cur)
1231 // drunken state is cleared on death
1232 SetDrunkValue(0);
1233 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1234 ClearComboPoints();
1236 clearResurrectRequestData();
1238 // remove form before other mods to prevent incorrect stats calculation
1239 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1241 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1242 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1244 // remove uncontrolled pets
1245 RemoveMiniPet();
1246 RemoveGuardians();
1248 // save value before aura remove in Unit::setDeathState
1249 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1251 // passive spell
1252 if(!ressSpellId)
1253 ressSpellId = GetResurrectionSpellId();
1254 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1256 Unit::setDeathState(s);
1258 // restore resurrection spell id for player after aura remove
1259 if(s == JUST_DIED && cur && ressSpellId)
1260 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1262 if(isAlive() && !cur)
1264 //clear aura case after resurrection by another way (spells will be applied before next death)
1265 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1267 // restore default warrior stance
1268 if(getClass()== CLASS_WARRIOR)
1269 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1273 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1275 *p_data << GetGUID();
1276 *p_data << m_name;
1278 *p_data << getRace();
1279 uint8 pClass = getClass();
1280 *p_data << pClass;
1281 *p_data << getGender();
1283 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1284 *p_data << uint8(bytes);
1285 *p_data << uint8(bytes >> 8);
1286 *p_data << uint8(bytes >> 16);
1287 *p_data << uint8(bytes >> 24);
1289 bytes = GetUInt32Value(PLAYER_BYTES_2);
1290 *p_data << uint8(bytes);
1292 *p_data << uint8(getLevel()); // player level
1293 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1294 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1295 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1296 *p_data << zoneId;
1297 *p_data << GetMapId();
1299 *p_data << GetPositionX();
1300 *p_data << GetPositionY();
1301 *p_data << GetPositionZ();
1303 *p_data << GetUInt32Value(PLAYER_GUILDID); // guild id
1305 uint32 char_flags = 0;
1306 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1307 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1308 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1309 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1310 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1311 char_flags |= CHARACTER_FLAG_GHOST;
1312 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1313 char_flags |= CHARACTER_FLAG_RENAME;
1314 // always send the flag if declined names aren't used
1315 // to let the client select a default method of declining the name
1316 if(!sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) || (result && result->Fetch()[13].GetCppString() != ""))
1317 char_flags |= CHARACTER_FLAG_DECLINED;
1319 *p_data << (uint32)char_flags; // character flags
1320 *p_data << (uint32)0; // new wotlk
1321 *p_data << (uint8)1; // unknown
1323 // Pets info
1325 uint32 petDisplayId = 0;
1326 uint32 petLevel = 0;
1327 uint32 petFamily = 0;
1329 // show pet at selection character in character list only for non-ghost character
1330 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1332 Field* fields = result->Fetch();
1334 uint32 entry = fields[10].GetUInt32();
1335 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1336 if(cInfo)
1338 petDisplayId = fields[11].GetUInt32();
1339 petLevel = fields[12].GetUInt32();
1340 petFamily = cInfo->family;
1344 *p_data << (uint32)petDisplayId;
1345 *p_data << (uint32)petLevel;
1346 *p_data << (uint32)petFamily;
1349 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1350 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1351 items[i] = NULL;
1353 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1354 if (result)
1358 Field *fields = result->Fetch();
1359 uint8 slot = fields[0].GetUInt8() & 255;
1360 uint32 item_id = fields[1].GetUInt32();
1361 if( slot >= EQUIPMENT_SLOT_END )
1362 continue;
1364 items[slot] = objmgr.GetItemPrototype(item_id);
1365 if(!items[slot])
1367 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1368 continue;
1370 } while (result->NextRow());
1371 delete result;
1374 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1376 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1377 uint32 item_id = GetUInt32Value(visualbase);
1378 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1379 SpellItemEnchantmentEntry const *enchant = NULL;
1381 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1383 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1384 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1385 break;
1388 if (proto != NULL)
1390 *p_data << (uint32)proto->DisplayInfoID;
1391 *p_data << (uint8)proto->InventoryType;
1392 *p_data << (uint32)(enchant?enchant->aura_id:0);
1394 else
1396 *p_data << (uint32)0;
1397 *p_data << (uint8)0;
1398 *p_data << (uint32)0; // enchant?
1401 *p_data << (uint32)0; // first bag display id
1402 *p_data << (uint8)0; // first bag inventory type
1403 *p_data << (uint32)0; // enchant?
1406 bool Player::ToggleAFK()
1408 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1410 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1412 // afk player not allowed in battleground
1413 if(state && InBattleGround())
1414 LeaveBattleground();
1416 return state;
1419 bool Player::ToggleDND()
1421 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1423 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1426 uint8 Player::chatTag() const
1428 // it's bitmask
1429 // 0x8 - ??
1430 // 0x4 - gm
1431 // 0x2 - dnd
1432 // 0x1 - afk
1433 if(isGMChat())
1434 return 4;
1435 else if(isDND())
1436 return 3;
1437 if(isAFK())
1438 return 1;
1439 else
1440 return 0;
1443 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1445 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1447 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1448 return false;
1451 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1452 Pet* pet = GetPet();
1454 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1456 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1457 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1458 return false;
1460 // client without expansion support
1461 if(GetSession()->Expansion() < mEntry->Expansion())
1463 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1465 if(GetTransport())
1466 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1468 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1470 return false; // normal client can't teleport to this map...
1472 else
1474 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1477 // if we were on a transport, leave
1478 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1480 m_transport->RemovePassenger(this);
1481 m_transport = NULL;
1482 m_movementInfo.t_x = 0.0f;
1483 m_movementInfo.t_y = 0.0f;
1484 m_movementInfo.t_z = 0.0f;
1485 m_movementInfo.t_o = 0.0f;
1486 m_movementInfo.t_time = 0;
1489 SetSemaphoreTeleport(true);
1491 // The player was ported to another map and looses the duel immediately.
1492 // We have to perform this check before the teleport, otherwise the
1493 // ObjectAccessor won't find the flag.
1494 if (duel && GetMapId()!=mapid)
1496 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1497 if (obj)
1498 DuelComplete(DUEL_FLED);
1501 // reset movement flags at teleport, because player will continue move with these flags after teleport
1502 SetUnitMovementFlags(0);
1504 if ((GetMapId() == mapid) && (!m_transport))
1506 // prepare zone change detect
1507 uint32 old_zone = GetZoneId();
1509 // near teleport
1510 if(!GetSession()->PlayerLogout())
1512 WorldPacket data;
1513 BuildTeleportAckMsg(&data, x, y, z, orientation);
1514 GetSession()->SendPacket(&data);
1515 SetPosition( x, y, z, orientation, true);
1517 else
1518 // this will be used instead of the current location in SaveToDB
1519 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1521 //BuildHeartBeatMsg(&data);
1522 //SendMessageToSet(&data, true);
1523 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1525 //same map, only remove pet if out of range
1526 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1528 if(pet->isControlled() && !pet->isTemporarySummoned() )
1529 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1530 else
1531 m_temporaryUnsummonedPetNumber = 0;
1533 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1537 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1538 CombatStop();
1540 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1542 // resummon pet
1543 if(pet && m_temporaryUnsummonedPetNumber)
1545 Pet* NewPet = new Pet;
1546 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1547 delete NewPet;
1549 m_temporaryUnsummonedPetNumber = 0;
1553 if(!GetSession()->PlayerLogout())
1555 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1556 SetSemaphoreTeleport(false);
1558 UpdateZone(GetZoneId());
1561 // new zone
1562 if(old_zone != GetZoneId())
1564 // honorless target
1565 if(pvpInfo.inHostileArea)
1566 CastSpell(this, 2479, true);
1569 else
1571 // far teleport to another map
1572 Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
1573 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1575 // Check enter rights before map getting to avoid creating instance copy for player
1576 // this check not dependent from map instance copy and same for all instance copies of selected map
1577 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1579 SetSemaphoreTeleport(false);
1580 return false;
1583 // If the map is not created, assume it is possible to enter it.
1584 // It will be created in the WorldPortAck.
1585 Map *map = MapManager::Instance().FindMap(mapid);
1586 if (!map || map->CanEnter(this))
1588 SetSelection(0);
1590 CombatStop();
1592 ResetContestedPvP();
1594 // remove player from battleground on far teleport (when changing maps)
1595 if(BattleGround const* bg = GetBattleGround())
1597 // Note: at battleground join battleground id set before teleport
1598 // and we already will found "current" battleground
1599 // just need check that this is targeted map or leave
1600 if(bg->GetMapId() != mapid)
1601 LeaveBattleground(false); // don't teleport to entry point
1604 // remove pet on map change
1605 if (pet)
1607 //leaving map -> delete pet right away (doing this later will cause problems)
1608 if(pet->isControlled() && !pet->isTemporarySummoned())
1609 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1610 else
1611 m_temporaryUnsummonedPetNumber = 0;
1613 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1616 // remove all dyn objects
1617 RemoveAllDynObjects();
1619 // stop spellcasting
1620 // not attempt interrupt teleportation spell at caster teleport
1621 if(!(options & TELE_TO_SPELL))
1622 if(IsNonMeleeSpellCasted(true))
1623 InterruptNonMeleeSpells(true);
1625 if(!GetSession()->PlayerLogout())
1627 // send transfer packets
1628 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1629 data << uint32(mapid);
1630 if (m_transport)
1632 data << m_transport->GetEntry() << GetMapId();
1634 GetSession()->SendPacket(&data);
1636 data.Initialize(SMSG_NEW_WORLD, (20));
1637 if (m_transport)
1639 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1641 else
1643 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1645 GetSession()->SendPacket( &data );
1646 SendSavedInstances();
1648 // remove from old map now
1649 if(oldmap) oldmap->Remove(this, false);
1652 // new final coordinates
1653 float final_x = x;
1654 float final_y = y;
1655 float final_z = z;
1656 float final_o = orientation;
1658 if(m_transport)
1660 final_x += m_movementInfo.t_x;
1661 final_y += m_movementInfo.t_y;
1662 final_z += m_movementInfo.t_z;
1663 final_o += m_movementInfo.t_o;
1666 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1667 // if the player is saved before worldportack (at logout for example)
1668 // this will be used instead of the current location in SaveToDB
1670 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1672 // move packet sent by client always after far teleport
1673 // SetPosition(final_x, final_y, final_z, final_o, true);
1674 SetDontMove(true);
1676 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1678 else
1679 return false;
1681 return true;
1684 void Player::AddToWorld()
1686 ///- Do not add/remove the player from the object storage
1687 ///- It will crash when updating the ObjectAccessor
1688 ///- The player should only be added when logging in
1689 Unit::AddToWorld();
1691 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1693 if(m_items[i])
1694 m_items[i]->AddToWorld();
1698 void Player::RemoveFromWorld()
1700 // cleanup
1701 if(IsInWorld())
1703 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1704 Uncharm();
1705 UnsummonAllTotems();
1706 RemoveMiniPet();
1707 RemoveGuardians();
1710 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1712 if(m_items[i])
1713 m_items[i]->RemoveFromWorld();
1716 ///- Do not add/remove the player from the object storage
1717 ///- It will crash when updating the ObjectAccessor
1718 ///- The player should only be removed when logging out
1719 Unit::RemoveFromWorld();
1722 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1724 float addRage;
1726 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1728 if(attacker)
1730 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1732 // talent who gave more rage on attack
1733 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1735 else
1737 addRage = damage/rageconversion*2.5;
1739 // Berserker Rage effect
1740 if(HasAura(18499,0))
1741 addRage *= 1.3;
1744 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1746 ModifyPower(POWER_RAGE, uint32(addRage*10));
1749 void Player::RegenerateAll()
1751 if (m_regenTimer != 0)
1752 return;
1753 uint32 regenDelay = 2000;
1755 // Not in combat or they have regeneration
1756 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1757 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1759 RegenerateHealth();
1760 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1761 Regenerate(POWER_RAGE);
1764 Regenerate( POWER_ENERGY );
1766 Regenerate( POWER_MANA );
1768 Regenerate( POWER_RUNIC_POWER );
1770 m_regenTimer = regenDelay;
1773 void Player::Regenerate(Powers power)
1775 uint32 curValue = GetPower(power);
1776 uint32 maxValue = GetMaxPower(power);
1778 float addvalue = 0.0f;
1780 switch (power)
1782 case POWER_MANA:
1784 bool recentCast = IsUnderLastManaUseEffect();
1785 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1786 if (recentCast)
1788 // Mangos Updates Mana in intervals of 2s, which is correct
1789 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1791 else
1793 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1795 } break;
1796 case POWER_RAGE: // Regenerate rage
1798 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1799 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1800 } break;
1801 case POWER_ENERGY: // Regenerate energy (rogue)
1802 addvalue = 20;
1803 break;
1804 case POWER_RUNIC_POWER:
1805 addvalue = 100; // TODO: find correct regen rate
1806 break;
1807 case POWER_FOCUS:
1808 case POWER_HAPPINESS:
1809 break;
1812 // Mana regen calculated in Player::UpdateManaRegen()
1813 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1814 if(power != POWER_MANA)
1816 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1817 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1818 if ((*i)->GetModifier()->m_miscvalue == power)
1819 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1822 if (power != POWER_RAGE)
1824 curValue += uint32(addvalue);
1825 if (curValue > maxValue)
1826 curValue = maxValue;
1828 else
1830 if(curValue <= uint32(addvalue))
1831 curValue = 0;
1832 else
1833 curValue -= uint32(addvalue);
1835 SetPower(power, curValue);
1838 void Player::RegenerateHealth()
1840 uint32 curValue = GetHealth();
1841 uint32 maxValue = GetMaxHealth();
1843 if (curValue >= maxValue) return;
1845 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1847 float addvalue = 0.0f;
1849 // polymorphed case
1850 if ( IsPolymorphed() )
1851 addvalue = GetMaxHealth()/3;
1852 // normal regen case (maybe partly in combat case)
1853 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1855 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1856 if (!isInCombat())
1858 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1859 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1860 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1862 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1863 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1865 if(!IsStandState())
1866 addvalue *= 1.5;
1869 // always regeneration bonus (including combat)
1870 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1872 if(addvalue < 0)
1873 addvalue = 0;
1875 ModifyHealth(int32(addvalue));
1878 bool Player::CanInteractWithNPCs(bool alive) const
1880 if(alive && !isAlive())
1881 return false;
1882 if(isInFlight())
1883 return false;
1885 return true;
1888 bool Player::IsUnderWater() const
1890 return IsInWater() &&
1891 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1894 void Player::SetInWater(bool apply)
1896 if(m_isInWater==apply)
1897 return;
1899 //define player in water by opcodes
1900 //move player's guid into HateOfflineList of those mobs
1901 //which can't swim and move guid back into ThreatList when
1902 //on surface.
1903 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1904 m_isInWater = apply;
1906 // remove auras that need water/land
1907 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1909 getHostilRefManager().updateThreatTables();
1912 void Player::SetGameMaster(bool on)
1914 if(on)
1916 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1917 setFaction(35);
1918 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1920 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1921 ResetContestedPvP();
1923 getHostilRefManager().setOnlineOfflineState(false);
1924 CombatStop();
1926 else
1928 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1929 setFactionForRace(getRace());
1930 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1932 // restore FFA PvP Server state
1933 if(sWorld.IsFFAPvPRealm())
1934 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1936 // restore FFA PvP area state, remove not allowed for GM mounts
1937 UpdateArea(m_areaUpdateId);
1939 getHostilRefManager().setOnlineOfflineState(true);
1942 ObjectAccessor::UpdateVisibilityForPlayer(this);
1945 void Player::SetGMVisible(bool on)
1947 if(on)
1949 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1951 // Reapply stealth/invisibility if active or show if not any
1952 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
1953 SetVisibility(VISIBILITY_GROUP_STEALTH);
1954 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
1955 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
1956 else
1957 SetVisibility(VISIBILITY_ON);
1959 else
1961 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
1963 SetAcceptWhispers(false);
1964 SetGameMaster(true);
1966 SetVisibility(VISIBILITY_OFF);
1970 bool Player::IsGroupVisibleFor(Player* p) const
1972 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
1974 default: return IsInSameGroupWith(p);
1975 case 1: return IsInSameRaidWith(p);
1976 case 2: return GetTeam()==p->GetTeam();
1980 bool Player::IsInSameGroupWith(Player const* p) const
1982 return p==this || GetGroup() != NULL &&
1983 GetGroup() == p->GetGroup() &&
1984 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
1987 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1988 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1989 void Player::UninviteFromGroup()
1991 if(GetGroupInvite()) // uninvited invitee
1993 Group* group = GetGroupInvite();
1994 group->RemoveInvite(this);
1996 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
1998 if(group->IsCreated())
2000 group->Disband(true);
2001 objmgr.RemoveGroup(group);
2003 else
2004 group->RemoveAllInvites();
2006 delete group;
2011 void Player::RemoveFromGroup(Group* group, uint64 guid)
2013 if(group)
2015 if (group->RemoveMember(guid, 0) <= 1)
2017 // group->Disband(); already disbanded in RemoveMember
2018 objmgr.RemoveGroup(group);
2019 delete group;
2020 // removemember sets the player's group pointer to NULL
2025 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2027 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2028 data << uint64(victim ? victim->GetGUID() : 0); // guid
2029 data << uint32(GivenXP+RestXP); // given experience
2030 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2031 if(victim)
2033 data << uint32(GivenXP); // experience without rested bonus
2034 data << float(1); // 1 - none 0 - 100% group bonus output
2036 data << uint8(0); // new 2.4.0
2037 GetSession()->SendPacket(&data);
2040 void Player::GiveXP(uint32 xp, Unit* victim)
2042 if ( xp < 1 )
2043 return;
2045 if(!isAlive())
2046 return;
2048 uint32 level = getLevel();
2050 // XP to money conversion processed in Player::RewardQuest
2051 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2052 return;
2054 // handle SPELL_AURA_MOD_XP_PCT auras
2055 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2056 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2057 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2059 // XP resting bonus for kill
2060 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2062 SendLogXPGain(xp,victim,rested_bonus_xp);
2064 uint32 curXP = GetUInt32Value(PLAYER_XP);
2065 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2066 uint32 newXP = curXP + xp + rested_bonus_xp;
2068 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2070 newXP -= nextLvlXP;
2072 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2073 GiveLevel(level + 1);
2075 level = getLevel();
2076 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2079 SetUInt32Value(PLAYER_XP, newXP);
2082 // Update player to next level
2083 // Current player experience not update (must be update by caller)
2084 void Player::GiveLevel(uint32 level)
2086 if ( level == getLevel() )
2087 return;
2089 PlayerLevelInfo info;
2090 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2092 PlayerClassLevelInfo classInfo;
2093 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2095 // send levelup info to client
2096 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2097 data << uint32(level);
2098 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2099 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2100 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2101 data << uint32(0);
2102 data << uint32(0);
2103 data << uint32(0);
2104 data << uint32(0);
2105 data << uint32(0);
2106 data << uint32(0);
2107 // end for
2108 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2109 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2111 GetSession()->SendPacket(&data);
2113 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2115 //update level, max level of skills
2116 if(getLevel()!= level)
2117 m_Played_time[1] = 0; // Level Played Time reset
2118 SetLevel(level);
2119 UpdateMaxSkills();
2121 // save base values (bonuses already included in stored stats
2122 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2123 SetCreateStat(Stats(i), info.stats[i]);
2125 SetCreateHealth(classInfo.basehealth);
2126 SetCreateMana(classInfo.basemana);
2128 InitTalentForLevel();
2129 InitTaxiNodesForLevel();
2130 InitGlyphsForLevel();
2132 UpdateAllStats();
2134 // set current level health and mana/energy to maximum after applying all mods.
2135 SetHealth(GetMaxHealth());
2136 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2137 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2138 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2139 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2140 SetPower(POWER_FOCUS, 0);
2141 SetPower(POWER_HAPPINESS, 0);
2143 // give level to summoned pet
2144 Pet* pet = GetPet();
2145 if(pet && pet->getPetType()==SUMMON_PET)
2146 pet->GivePetLevel(level);
2147 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2150 void Player::InitTalentForLevel()
2152 uint32 level = getLevel();
2153 // talents base at level diff ( talents = level - 9 but some can be used already)
2154 if(level < 10)
2156 // Remove all talent points
2157 if(m_usedTalentCount > 0) // Free any used talents
2159 resetTalents(true);
2160 SetFreeTalentPoints(0);
2163 else
2165 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2166 // if used more that have then reset
2167 if(m_usedTalentCount > talentPointsForLevel)
2169 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2170 resetTalents(true);
2171 else
2172 SetFreeTalentPoints(0);
2174 // else update amount of free points
2175 else
2176 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2180 void Player::InitStatsForLevel(bool reapplyMods)
2182 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2183 _RemoveAllStatBonuses();
2185 PlayerClassLevelInfo classInfo;
2186 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2188 PlayerLevelInfo info;
2189 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2191 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2192 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2194 UpdateMaxSkills ();
2196 // set default cast time multiplier
2197 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2199 // reset size before reapply auras
2200 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2202 // save base values (bonuses already included in stored stats
2203 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2204 SetCreateStat(Stats(i), info.stats[i]);
2206 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2207 SetStat(Stats(i), info.stats[i]);
2209 SetCreateHealth(classInfo.basehealth);
2211 //set create powers
2212 SetCreateMana(classInfo.basemana);
2214 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2216 InitStatBuffMods();
2218 //reset rating fields values
2219 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2220 SetUInt32Value(index, 0);
2222 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2223 for (int i = 0; i < 7; i++)
2225 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2226 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2227 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2230 //reset attack power, damage and attack speed fields
2231 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2232 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2233 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2235 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2236 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2237 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2238 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2239 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2240 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2242 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2243 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2244 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2245 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2246 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2247 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2249 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2250 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2251 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2252 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2254 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2255 for (uint8 i = 0; i < 7; ++i)
2256 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2258 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2259 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2260 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2262 // Dodge percentage
2263 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2265 // set armor (resistance 0) to original value (create_agility*2)
2266 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2267 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2268 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2269 // set other resistance to original value (0)
2270 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2272 SetResistance(SpellSchools(i), 0);
2273 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2274 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2277 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2278 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2279 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2281 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2282 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2284 // Init data for form but skip reapply item mods for form
2285 InitDataForForm(reapplyMods);
2287 // save new stats
2288 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2289 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2291 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2293 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2294 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2296 // cleanup unit flags (will be re-applied if need at aura load).
2297 RemoveFlag( UNIT_FIELD_FLAGS,
2298 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2299 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2300 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2301 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2302 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2303 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2305 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2306 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2308 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2310 // restore if need some important flags
2311 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2313 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2314 _ApplyAllStatBonuses();
2316 // set current level health and mana/energy to maximum after applying all mods.
2317 SetHealth(GetMaxHealth());
2318 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2319 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2320 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2321 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2322 SetPower(POWER_FOCUS, 0);
2323 SetPower(POWER_HAPPINESS, 0);
2324 SetPower(POWER_RUNIC_POWER, 0);
2327 void Player::SendInitialSpells()
2329 uint16 spellCount = 0;
2331 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2332 data << uint8(0);
2334 size_t countPos = data.wpos();
2335 data << uint16(spellCount); // spell count placeholder
2337 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2339 if(itr->second->state == PLAYERSPELL_REMOVED)
2340 continue;
2342 if(!itr->second->active || itr->second->disabled)
2343 continue;
2345 data << uint16(itr->first);
2346 data << uint16(0); // it's not slot id
2348 spellCount +=1;
2351 data.put<uint16>(countPos,spellCount); // write real count value
2353 uint16 spellCooldowns = m_spellCooldowns.size();
2354 data << uint16(spellCooldowns);
2355 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
2357 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2358 if(!sEntry)
2359 continue;
2361 data << uint16(itr->first);
2363 time_t cooldown = 0;
2364 time_t curTime = time(NULL);
2365 if(itr->second.end > curTime)
2366 cooldown = (itr->second.end-curTime)*1000;
2368 data << uint16(itr->second.itemid); // cast item id
2369 data << uint16(sEntry->Category); // spell category
2370 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2372 data << uint32(0); // cooldown
2373 data << uint32(cooldown); // category cooldown
2375 else
2377 data << uint32(cooldown); // cooldown
2378 data << uint32(0); // category cooldown
2382 GetSession()->SendPacket(&data);
2384 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2387 void Player::RemoveMail(uint32 id)
2389 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2391 if ((*itr)->messageID == id)
2393 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2394 m_mail.erase(itr);
2395 return;
2400 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2402 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2403 data << (uint32) mailId;
2404 data << (uint32) mailAction;
2405 data << (uint32) mailError;
2406 if ( mailError == MAIL_ERR_BAG_FULL )
2407 data << (uint32) equipError;
2408 else if( mailAction == MAIL_ITEM_TAKEN )
2410 data << (uint32) item_guid; // item guid low?
2411 data << (uint32) item_count; // item count?
2413 GetSession()->SendPacket(&data);
2416 void Player::SendNewMail()
2418 // deliver undelivered mail
2419 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2420 data << (uint32) 0;
2421 GetSession()->SendPacket(&data);
2424 void Player::UpdateNextMailTimeAndUnreads()
2426 // calculate next delivery time (min. from non-delivered mails
2427 // and recalculate unReadMail
2428 time_t cTime = time(NULL);
2429 m_nextMailDelivereTime = 0;
2430 unReadMails = 0;
2431 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2433 if((*itr)->deliver_time > cTime)
2435 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2436 m_nextMailDelivereTime = (*itr)->deliver_time;
2438 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2439 ++unReadMails;
2443 void Player::AddNewMailDeliverTime(time_t deliver_time)
2445 if(deliver_time <= time(NULL)) // ready now
2447 ++unReadMails;
2448 SendNewMail();
2450 else // not ready and no have ready mails
2452 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2453 m_nextMailDelivereTime = deliver_time;
2457 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2459 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2460 if (!spellInfo)
2462 // do character spell book cleanup (all characters)
2463 if(loading && !learning) // spell load case
2465 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2466 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2468 else
2469 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2471 return false;
2474 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2476 // do character spell book cleanup (all characters)
2477 if(loading && !learning) // spell load case
2479 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2480 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2482 else
2483 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2485 return false;
2488 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2490 bool disabled_case = false;
2491 bool superceded_old = false;
2493 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2494 if (itr != m_spells.end())
2496 // update active state for known spell
2497 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2499 itr->second->active = active;
2501 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2502 if(loading && !learning)
2503 itr->second->state = PLAYERSPELL_UNCHANGED;
2504 else if(itr->second->state != PLAYERSPELL_NEW)
2505 itr->second->state = PLAYERSPELL_CHANGED;
2507 if(!active)
2509 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2510 data << uint16(spell_id);
2511 GetSession()->SendPacket(&data);
2513 return active; // learn (show in spell book if active now)
2516 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2518 if(itr->second->state != PLAYERSPELL_NEW)
2519 itr->second->state = PLAYERSPELL_CHANGED;
2520 itr->second->disabled = disabled;
2522 if(disabled)
2523 return false;
2525 disabled_case = true;
2527 else switch(itr->second->state)
2529 case PLAYERSPELL_UNCHANGED: // known saved spell
2530 return false;
2531 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2533 delete itr->second;
2534 m_spells.erase(itr);
2535 state = PLAYERSPELL_CHANGED;
2536 break; // need re-add
2538 default: // known not saved yet spell (new or modified)
2540 // can be in case spell loading but learned at some previous spell loading
2541 if(loading && !learning)
2542 itr->second->state = PLAYERSPELL_UNCHANGED;
2544 return false;
2549 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2551 // talent: unlearn all other talent ranks (high and low)
2552 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2554 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2556 for(int i=0; i <5; ++i)
2558 // skip learning spell and no rank spell case
2559 uint32 rankSpellId = talentInfo->RankID[i];
2560 if(!rankSpellId || rankSpellId==spell_id)
2561 continue;
2563 // skip unknown ranks
2564 if(!HasSpell(rankSpellId))
2565 continue;
2567 removeSpell(rankSpellId);
2571 // non talent spell: learn low ranks (recursive call)
2572 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2574 if(loading) // at spells loading, no output, but allow save
2575 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2576 else // at normal learning
2577 learnSpell(prev_spell);
2580 PlayerSpell *newspell = new PlayerSpell;
2581 newspell->active = active;
2582 newspell->state = state;
2583 newspell->disabled = disabled;
2585 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2586 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2588 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2590 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2591 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2592 if(!i_spellInfo) continue;
2594 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2596 if(itr->second->active)
2598 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2600 if(!loading) // not send spell (re-/over-)learn packets at loading
2602 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2603 data << uint16(itr->first);
2604 data << uint16(spell_id);
2605 GetSession()->SendPacket( &data );
2608 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2609 itr->second->active = false;
2610 itr->second->state = PLAYERSPELL_CHANGED;
2611 superceded_old = true; // new spell replace old in action bars and spell book.
2613 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2615 if(!loading) // not send spell (re-/over-)learn packets at loading
2617 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2618 data << uint16(spell_id);
2619 data << uint16(itr->first);
2620 GetSession()->SendPacket( &data );
2623 // mark new spell as disable (not learned yet for client and will not learned)
2624 newspell->active = false;
2625 if(newspell->state != PLAYERSPELL_NEW)
2626 newspell->state = PLAYERSPELL_CHANGED;
2633 uint16 tmpslot=slot_id;
2635 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2637 uint16 maxid = 0;
2638 PlayerSpellMap::iterator itr;
2639 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2641 if(itr->second->state == PLAYERSPELL_REMOVED)
2642 continue;
2643 if (itr->second->slotId > maxid)
2644 maxid = itr->second->slotId;
2646 tmpslot = maxid + 1;
2649 newspell->slotId = tmpslot;
2650 m_spells[spell_id] = newspell;
2652 // return false if spell disabled
2653 if (newspell->disabled)
2654 return false;
2657 uint32 talentCost = GetTalentSpellCost(spell_id);
2659 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2660 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2661 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2663 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2664 CastSpell(this, spell_id, true);
2666 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2667 else if (IsPassiveSpell(spell_id))
2669 // if spell doesn't require a stance or the player is in the required stance
2670 if( ( !spellInfo->Stances &&
2671 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2672 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2673 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2674 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2675 (spell_id == 5420 && m_form == FORM_TREE) ||
2676 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2677 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2678 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2679 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2680 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2681 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2682 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2683 //Check CasterAuraStates
2684 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2685 CastSpell(this, spell_id, true);
2687 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2689 CastSpell(this, spell_id, true);
2690 return false;
2693 // update used talent points count
2694 m_usedTalentCount += talentCost;
2696 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2697 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2699 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2700 SetFreePrimaryProffesions(freeProfs-1);
2703 // add dependent skills
2704 uint16 maxskill = GetMaxSkillValueForLevel();
2706 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2708 if(spellLearnSkill)
2710 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2711 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2713 if(skill_value < spellLearnSkill->value)
2714 skill_value = spellLearnSkill->value;
2716 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2718 if(skill_max_value < new_skill_max_value)
2719 skill_max_value = new_skill_max_value;
2721 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2723 else
2725 // not ranked skills
2726 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2727 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2729 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2731 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2732 if(!pSkill)
2733 continue;
2735 if(HasSkill(pSkill->id))
2736 continue;
2738 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2739 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2740 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2741 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2742 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2744 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2746 case SKILL_RANGE_LANGUAGE:
2747 SetSkill(pSkill->id, 300, 300 );
2748 break;
2749 case SKILL_RANGE_LEVEL:
2750 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2751 break;
2752 case SKILL_RANGE_MONO:
2753 SetSkill(pSkill->id, 1, 1 );
2754 break;
2755 default:
2756 break;
2762 // learn dependent spells
2763 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2764 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2766 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2768 if(!itr->second.autoLearned)
2770 if(loading) // at spells loading, no output, but allow save
2771 addSpell(itr->second.spell,true,true,loading);
2772 else // at normal learning
2773 learnSpell(itr->second.spell);
2777 if(!loading)
2778 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2780 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2781 return active && !disabled && !superceded_old;
2784 void Player::learnSpell(uint32 spell_id)
2786 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2788 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2789 bool active = disabled ? itr->second->active : true;
2791 bool learning = addSpell(spell_id,active);
2793 // learn all disabled higher ranks (recursive)
2794 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2795 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2797 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2798 if (disabled && iter != m_spells.end() && iter->second->disabled)
2799 learnSpell(i->second);
2802 // prevent duplicated entires in spell book
2803 if(!learning)
2804 return;
2806 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2807 data << uint32(spell_id);
2808 GetSession()->SendPacket(&data);
2811 void Player::removeSpell(uint32 spell_id, bool disabled)
2813 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2814 if (itr == m_spells.end())
2815 return;
2817 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2818 return;
2820 // unlearn non talent higher ranks (recursive)
2821 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2822 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2823 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2824 removeSpell(itr2->second,disabled);
2826 // removing
2827 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2828 data << uint16(spell_id);
2829 GetSession()->SendPacket(&data);
2831 if (disabled)
2833 itr->second->disabled = disabled;
2834 if(itr->second->state != PLAYERSPELL_NEW)
2835 itr->second->state = PLAYERSPELL_CHANGED;
2837 else
2839 if(itr->second->state == PLAYERSPELL_NEW)
2841 delete itr->second;
2842 m_spells.erase(itr);
2844 else
2845 itr->second->state = PLAYERSPELL_REMOVED;
2848 RemoveAurasDueToSpell(spell_id);
2850 // remove pet auras
2851 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2852 RemovePetAura(petSpell);
2854 // free talent points
2855 uint32 talentCosts = GetTalentSpellCost(spell_id);
2856 if(talentCosts > 0)
2858 if(talentCosts < m_usedTalentCount)
2859 m_usedTalentCount -= talentCosts;
2860 else
2861 m_usedTalentCount = 0;
2864 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2865 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2867 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2868 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2869 SetFreePrimaryProffesions(freeProfs);
2872 // remove dependent skill
2873 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2874 if(spellLearnSkill)
2876 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2877 if(!prev_spell) // first rank, remove skill
2878 SetSkill(spellLearnSkill->skill,0,0);
2879 else
2881 // search prev. skill setting by spell ranks chain
2882 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2883 while(!prevSkill && prev_spell)
2885 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2886 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2889 if(!prevSkill) // not found prev skill setting, remove skill
2890 SetSkill(spellLearnSkill->skill,0,0);
2891 else // set to prev. skill setting values
2893 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2894 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2896 if(skill_value > prevSkill->value)
2897 skill_value = prevSkill->value;
2899 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2901 if(skill_max_value > new_skill_max_value)
2902 skill_max_value = new_skill_max_value;
2904 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2909 else
2911 // not ranked skills
2912 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2913 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2915 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2917 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2918 if(!pSkill)
2919 continue;
2921 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2922 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2923 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2924 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2925 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2927 // not reset skills for professions and racial abilities
2928 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2929 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2930 continue;
2932 SetSkill(pSkill->id, 0, 0 );
2937 // remove dependent spells
2938 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2939 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2941 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2942 removeSpell(itr2->second.spell, disabled);
2945 void Player::RemoveArenaSpellCooldowns()
2947 // remove cooldowns on spells that has < 15 min CD
2948 SpellCooldowns::iterator itr, next;
2949 // iterate spell cooldowns
2950 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2952 next = itr;
2953 ++next;
2954 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
2955 // check if spellentry is present and if the cooldown is less than 15 mins
2956 if( entry &&
2957 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
2958 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
2960 // notify player
2961 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2962 data << uint32(itr->first);
2963 data << GetGUID();
2964 GetSession()->SendPacket(&data);
2965 // remove cooldown
2966 m_spellCooldowns.erase(itr);
2971 void Player::RemoveAllSpellCooldown()
2973 if(!m_spellCooldowns.empty())
2975 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
2977 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2978 data << uint32(itr->first);
2979 data << uint64(GetGUID());
2980 GetSession()->SendPacket(&data);
2982 m_spellCooldowns.clear();
2986 void Player::_LoadSpellCooldowns(QueryResult *result)
2988 m_spellCooldowns.clear();
2990 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2992 if(result)
2994 time_t curTime = time(NULL);
2998 Field *fields = result->Fetch();
3000 uint32 spell_id = fields[0].GetUInt32();
3001 uint32 item_id = fields[1].GetUInt32();
3002 time_t db_time = (time_t)fields[2].GetUInt64();
3004 if(!sSpellStore.LookupEntry(spell_id))
3006 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3007 continue;
3010 // skip outdated cooldown
3011 if(db_time <= curTime)
3012 continue;
3014 AddSpellCooldown(spell_id, item_id, db_time);
3016 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3018 while( result->NextRow() );
3020 delete result;
3024 void Player::_SaveSpellCooldowns()
3026 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3028 time_t curTime = time(NULL);
3030 // remove outdated and save active
3031 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3033 if(itr->second.end <= curTime)
3034 m_spellCooldowns.erase(itr++);
3035 else
3037 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));
3038 ++itr;
3043 uint32 Player::resetTalentsCost() const
3045 // The first time reset costs 1 gold
3046 if(m_resetTalentsCost < 1*GOLD)
3047 return 1*GOLD;
3048 // then 5 gold
3049 else if(m_resetTalentsCost < 5*GOLD)
3050 return 5*GOLD;
3051 // After that it increases in increments of 5 gold
3052 else if(m_resetTalentsCost < 10*GOLD)
3053 return 10*GOLD;
3054 else
3056 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3057 if(months > 0)
3059 // This cost will be reduced by a rate of 5 gold per month
3060 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3061 // to a minimum of 10 gold.
3062 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3064 else
3066 // After that it increases in increments of 5 gold
3067 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3068 // until it hits a cap of 50 gold.
3069 if(new_cost > 50*GOLD)
3070 new_cost = 50*GOLD;
3071 return new_cost;
3076 bool Player::resetTalents(bool no_cost)
3078 // not need after this call
3079 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3081 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3082 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3085 uint32 level = getLevel();
3086 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3088 if (m_usedTalentCount == 0)
3090 SetFreeTalentPoints(talentPointsForLevel);
3091 return false;
3094 uint32 cost = 0;
3096 if(!no_cost)
3098 cost = resetTalentsCost();
3100 if (GetMoney() < cost)
3102 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3103 return false;
3107 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3109 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3111 if (!talentInfo) continue;
3113 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3115 if(!talentTabInfo)
3116 continue;
3118 // unlearn only talents for character class
3119 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3120 // to prevent unexpected lost normal learned spell skip another class talents
3121 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3122 continue;
3124 for (int j = 0; j < 5; j++)
3126 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3128 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3130 ++itr;
3131 continue;
3134 // remove learned spells (all ranks)
3135 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3137 // unlearn if first rank is talent or learned by talent
3138 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3140 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3141 itr = GetSpellMap().begin();
3142 continue;
3144 else
3145 ++itr;
3150 SetFreeTalentPoints(talentPointsForLevel);
3152 if(!no_cost)
3154 ModifyMoney(-(int32)cost);
3156 m_resetTalentsCost = cost;
3157 m_resetTalentsTime = time(NULL);
3160 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3161 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3163 return true;
3166 bool Player::_removeSpell(uint16 spell_id)
3168 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3169 if (itr != m_spells.end())
3171 delete itr->second;
3172 m_spells.erase(itr);
3173 return true;
3175 return false;
3178 Mail* Player::GetMail(uint32 id)
3180 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
3182 if ((*itr)->messageID == id)
3184 return (*itr);
3187 return NULL;
3190 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3192 if(target == this)
3194 Object::_SetCreateBits(updateMask, target);
3196 else
3198 for(uint16 index = 0; index < m_valuesCount; index++)
3200 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3201 updateMask->SetBit(index);
3206 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3208 if(target == this)
3210 Object::_SetUpdateBits(updateMask, target);
3212 else
3214 Object::_SetUpdateBits(updateMask, target);
3215 *updateMask &= updateVisualBits;
3219 void Player::InitVisibleBits()
3221 updateVisualBits.SetCount(PLAYER_END);
3223 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3224 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3225 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3226 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3227 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3228 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3229 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3230 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3231 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3232 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3233 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3234 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3235 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3236 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3237 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3238 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3239 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3240 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3241 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3242 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3243 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3244 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3245 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3246 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3247 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3248 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3249 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3250 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3251 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3252 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3253 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3254 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3255 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3256 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3257 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3258 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3259 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3260 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3261 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3262 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3263 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3264 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3265 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3266 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3267 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3268 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3269 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3270 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3271 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3272 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3273 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3274 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3275 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3276 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3277 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3279 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3280 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3281 updateVisualBits.SetBit(PLAYER_FLAGS);
3282 updateVisualBits.SetBit(PLAYER_GUILDID);
3283 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3284 updateVisualBits.SetBit(PLAYER_BYTES);
3285 updateVisualBits.SetBit(PLAYER_BYTES_2);
3286 updateVisualBits.SetBit(PLAYER_BYTES_3);
3287 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3288 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3290 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3291 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3292 updateVisualBits.SetBit(i);
3294 // Players visible items are not inventory stuff
3295 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3297 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3299 // item creator
3300 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3301 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3303 // item entry
3304 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3306 // item enchantments
3307 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3308 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3310 // random properties
3311 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3312 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3313 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3316 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3319 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3321 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3323 if(m_items[i] == NULL)
3324 continue;
3326 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3329 if(target == this)
3331 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3333 if(m_items[i] == NULL)
3334 continue;
3336 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3338 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3340 if(m_items[i] == NULL)
3341 continue;
3343 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3347 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3350 void Player::DestroyForPlayer( Player *target ) const
3352 Unit::DestroyForPlayer( target );
3354 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3356 if(m_items[i] == NULL)
3357 continue;
3359 m_items[i]->DestroyForPlayer( target );
3362 if(target == this)
3364 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3366 if(m_items[i] == NULL)
3367 continue;
3369 m_items[i]->DestroyForPlayer( target );
3371 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3373 if(m_items[i] == NULL)
3374 continue;
3376 m_items[i]->DestroyForPlayer( target );
3381 bool Player::HasSpell(uint32 spell) const
3383 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3384 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3387 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3389 if (!trainer_spell)
3390 return TRAINER_SPELL_RED;
3392 if (!trainer_spell->spell)
3393 return TRAINER_SPELL_RED;
3395 // known spell
3396 if(HasSpell(trainer_spell->spell))
3397 return TRAINER_SPELL_GRAY;
3399 // check race/class requirement
3400 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3401 return TRAINER_SPELL_RED;
3403 // check level requirement
3404 if(getLevel() < trainer_spell->reqlevel)
3405 return TRAINER_SPELL_RED;
3407 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3409 // check prev.rank requirement
3410 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3411 return TRAINER_SPELL_RED;
3413 // check additional spell requirement
3414 if(spell_chain->req && !HasSpell(spell_chain->req))
3415 return TRAINER_SPELL_RED;
3418 // check skill requirement
3419 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3420 return TRAINER_SPELL_RED;
3422 // exist, already checked at loading
3423 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3425 // secondary prof. or not prof. spell
3426 uint32 skill = spell->EffectMiscValue[1];
3428 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3429 return TRAINER_SPELL_GREEN;
3431 // check primary prof. limit
3432 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3433 return TRAINER_SPELL_RED;
3435 return TRAINER_SPELL_GREEN;
3438 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3440 uint32 guid = GUID_LOPART(playerguid);
3442 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3443 // bones will be deleted by corpse/bones deleting thread shortly
3444 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3446 // remove from guild
3447 uint32 guildId = GetGuildIdFromDB(playerguid);
3448 if(guildId != 0)
3450 Guild* guild = objmgr.GetGuildById(guildId);
3451 if(guild)
3452 guild->DelMember(guid);
3455 // the player was uninvited already on logout so just remove from group
3456 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3457 if(resultGroup)
3459 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3460 delete resultGroup;
3461 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3462 if(group)
3464 RemoveFromGroup(group, playerguid);
3468 // remove signs from petitions (also remove petitions if owner);
3469 RemovePetitionsAndSigns(playerguid, 10);
3471 // return back all mails with COD and Item 0 1 2 3 4 5 6
3472 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);
3473 if(resultMail)
3477 Field *fields = resultMail->Fetch();
3479 uint32 mail_id = fields[0].GetUInt32();
3480 uint16 mailTemplateId= fields[1].GetUInt16();
3481 uint32 sender = fields[2].GetUInt32();
3482 std::string subject = fields[3].GetCppString();
3483 uint32 itemTextId = fields[4].GetUInt32();
3484 uint32 money = fields[5].GetUInt32();
3485 bool has_items = fields[6].GetBool();
3487 //we can return mail now
3488 //so firstly delete the old one
3489 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3491 MailItemsInfo mi;
3492 if(has_items)
3494 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3495 if(resultItems)
3499 Field *fields2 = resultItems->Fetch();
3501 uint32 item_guidlow = fields2[0].GetUInt32();
3502 uint32 item_template = fields2[1].GetUInt32();
3504 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3505 if(!itemProto)
3507 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3508 continue;
3511 Item *pItem = NewItemOrBag(itemProto);
3512 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3514 pItem->FSetState(ITEM_REMOVED);
3515 pItem->SaveToDB(); // it also deletes item object !
3516 continue;
3519 mi.AddItem(item_guidlow, item_template, pItem);
3521 while (resultItems->NextRow());
3523 delete resultItems;
3527 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3529 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3531 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3533 while (resultMail->NextRow());
3535 delete resultMail;
3538 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3539 // Get guids of character's pets, will deleted in transaction
3540 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3542 // NOW we can finally clear other DB data related to character
3543 CharacterDatabase.BeginTransaction();
3544 if (resultPets)
3548 Field *fields3 = resultPets->Fetch();
3549 uint32 petguidlow = fields3[0].GetUInt32();
3550 Pet::DeleteFromDB(petguidlow);
3551 } while (resultPets->NextRow());
3552 delete resultPets;
3555 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3556 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3557 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3558 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3559 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3560 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3561 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3562 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3563 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3564 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3565 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3566 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3567 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3568 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3569 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3570 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3571 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3572 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3573 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3574 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3575 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3576 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3577 CharacterDatabase.CommitTransaction();
3579 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3580 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3583 void Player::SetMovement(PlayerMovementType pType)
3585 WorldPacket data;
3586 switch(pType)
3588 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3589 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3590 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3591 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3592 default:
3593 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3594 return;
3596 data.append(GetPackGUID());
3597 data << uint32(0);
3598 GetSession()->SendPacket( &data );
3601 /* Preconditions:
3602 - a resurrectable corpse must not be loaded for the player (only bones)
3603 - the player must be in world
3605 void Player::BuildPlayerRepop()
3607 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3608 data.append(GetPackGUID());
3609 GetSession()->SendPacket(&data);
3611 if(getRace() == RACE_NIGHTELF)
3612 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)
3613 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3615 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3616 // there must be SMSG.STOP_MIRROR_TIMER
3617 // there we must send 888 opcode
3619 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3620 if(GetCorpse())
3622 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3623 assert(false);
3626 // create a corpse and place it at the player's location
3627 CreateCorpse();
3628 Corpse *corpse = GetCorpse();
3629 if(!corpse)
3631 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3632 return;
3634 GetMap()->Add(corpse);
3636 // convert player body to ghost
3637 SetHealth( 1 );
3639 SetMovement(MOVE_WATER_WALK);
3640 if(!GetSession()->isLogingOut())
3641 SetMovement(MOVE_UNROOT);
3643 // BG - remove insignia related
3644 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3646 SendCorpseReclaimDelay();
3648 // to prevent cheating
3649 corpse->ResetGhostTime();
3651 StopMirrorTimers(); //disable timers(bars)
3653 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3655 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3658 void Player::SendDelayResponse(const uint32 ml_seconds)
3660 //FIXME: is this delay time arg really need? 50msec by default in code
3661 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3662 data << (uint32)time(NULL);
3663 data << (uint32)0;
3664 GetSession()->SendPacket( &data );
3667 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3669 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3670 data << uint32(-1);
3671 data << float(0);
3672 data << float(0);
3673 data << float(0);
3674 GetSession()->SendPacket(&data);
3676 // speed change, land walk
3678 // remove death flag + set aura
3679 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3680 if(getRace() == RACE_NIGHTELF)
3681 RemoveAurasDueToSpell(20584); // speed bonuses
3682 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3684 setDeathState(ALIVE);
3686 SetMovement(MOVE_LAND_WALK);
3687 SetMovement(MOVE_UNROOT);
3689 m_deathTimer = 0;
3691 // set health/powers (0- will be set in caller)
3692 if(restore_percent>0.0f)
3694 SetHealth(uint32(GetMaxHealth()*restore_percent));
3695 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3696 SetPower(POWER_RAGE, 0);
3697 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3700 // update visibility
3701 ObjectAccessor::UpdateVisibilityForPlayer(this);
3703 // some items limited to specific map
3704 DestroyZoneLimitedItem( true, GetZoneId());
3706 if(!applySickness || getLevel() <= 10)
3707 return;
3709 //Characters from level 1-10 are not affected by resurrection sickness.
3710 //Characters from level 11-19 will suffer from one minute of sickness
3711 //for each level they are above 10.
3712 //Characters level 20 and up suffer from ten minutes of sickness.
3713 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3715 if(int32(getLevel()) >= startLevel)
3717 // set resurrection sickness
3718 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3720 // not full duration
3721 if(int32(getLevel()) < startLevel+9)
3723 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3725 for(int i =0; i < 3; ++i)
3727 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3729 Aur->SetAuraDuration(delta*1000);
3730 Aur->SendAuraUpdate(false);
3737 void Player::KillPlayer()
3739 SetMovement(MOVE_ROOT);
3741 StopMirrorTimers(); //disable timers(bars)
3743 setDeathState(CORPSE);
3744 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3746 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3747 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3749 // 6 minutes until repop at graveyard
3750 m_deathTimer = 6*MINUTE*1000;
3752 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3754 // don't create corpse at this moment, player might be falling
3756 // update visibility
3757 ObjectAccessor::UpdateObjectVisibility(this);
3760 void Player::CreateCorpse()
3762 // prevent existence 2 corpse for player
3763 SpawnCorpseBones();
3765 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3767 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3768 SetPvPDeath(false);
3770 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3771 GetPositionY(), GetPositionZ(), GetOrientation()))
3773 delete corpse;
3774 return;
3777 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3778 _pb = GetUInt32Value(PLAYER_BYTES);
3779 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3781 uint8 race = (uint8)(_uf);
3782 uint8 skin = (uint8)(_pb);
3783 uint8 face = (uint8)(_pb >> 8);
3784 uint8 hairstyle = (uint8)(_pb >> 16);
3785 uint8 haircolor = (uint8)(_pb >> 24);
3786 uint8 facialhair = (uint8)(_pb2);
3788 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3789 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3791 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3792 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3794 uint32 flags = CORPSE_FLAG_UNK2;
3795 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3796 flags |= CORPSE_FLAG_HIDE_HELM;
3797 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3798 flags |= CORPSE_FLAG_HIDE_CLOAK;
3799 if(InBattleGround())
3800 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3801 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3803 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3805 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3807 uint32 iDisplayID;
3808 uint16 iIventoryType;
3809 uint32 _cfi;
3810 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3812 if(m_items[i])
3814 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3815 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3817 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3818 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3822 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3823 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3824 assert(entry);
3825 if(entry->map_type != MAP_BATTLEGROUND)
3826 corpse->SaveToDB();
3828 // register for player, but not show
3829 ObjectAccessor::Instance().AddCorpse(corpse);
3832 void Player::SpawnCorpseBones()
3834 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3835 SaveToDB(); // prevent loading as ghost without corpse
3838 Corpse* Player::GetCorpse() const
3840 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3843 void Player::DurabilityLossAll(double percent, bool inventory)
3845 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3846 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3847 DurabilityLoss(pItem,percent);
3849 if(inventory)
3851 // bags not have durability
3852 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3854 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3855 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3856 DurabilityLoss(pItem,percent);
3858 // keys not have durability
3859 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3861 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3862 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3863 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3864 if(Item* pItem = GetItemByPos( i, j ))
3865 DurabilityLoss(pItem,percent);
3869 void Player::DurabilityLoss(Item* item, double percent)
3871 if(!item )
3872 return;
3874 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3876 if(!pMaxDurability)
3877 return;
3879 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3881 if(pDurabilityLoss < 1 )
3882 pDurabilityLoss = 1;
3884 DurabilityPointsLoss(item,pDurabilityLoss);
3887 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3889 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3890 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3891 DurabilityPointsLoss(pItem,points);
3893 if(inventory)
3895 // bags not have durability
3896 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3898 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3899 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3900 DurabilityPointsLoss(pItem,points);
3902 // keys not have durability
3903 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3905 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3906 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3907 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3908 if(Item* pItem = GetItemByPos( i, j ))
3909 DurabilityPointsLoss(pItem,points);
3913 void Player::DurabilityPointsLoss(Item* item, int32 points)
3915 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3916 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3917 int32 pNewDurability = pOldDurability - points;
3919 if (pNewDurability < 0)
3920 pNewDurability = 0;
3921 else if (pNewDurability > pMaxDurability)
3922 pNewDurability = pMaxDurability;
3924 if (pOldDurability != pNewDurability)
3926 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3927 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3928 _ApplyItemMods(item,item->GetSlot(), false);
3930 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3932 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3933 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3934 _ApplyItemMods(item,item->GetSlot(), true);
3936 item->SetState(ITEM_CHANGED, this);
3940 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3942 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3943 DurabilityPointsLoss(pItem,1);
3946 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3948 uint32 TotalCost = 0;
3949 // equipped, backpack, bags itself
3950 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3951 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3953 // bank, buyback and keys not repaired
3955 // items in inventory bags
3956 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3957 for(int i = 0; i < MAX_BAG_SIZE; i++)
3958 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3959 return TotalCost;
3962 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3964 Item* item = GetItemByPos(pos);
3966 uint32 TotalCost = 0;
3967 if(!item)
3968 return TotalCost;
3970 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3971 if(!maxDurability)
3972 return TotalCost;
3974 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3976 if(cost)
3978 uint32 LostDurability = maxDurability - curDurability;
3979 if(LostDurability>0)
3981 ItemPrototype const *ditemProto = item->GetProto();
3983 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
3984 if(!dcost)
3986 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
3987 return TotalCost;
3990 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
3991 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
3992 if(!dQualitymodEntry)
3994 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
3995 return TotalCost;
3998 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
3999 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4001 costs = uint32(costs * discountMod);
4003 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4004 costs = 1;
4006 if (guildBank)
4008 if (GetGuildId()==0)
4010 DEBUG_LOG("You are not member of a guild");
4011 return TotalCost;
4014 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4015 if (!pGuild)
4016 return TotalCost;
4018 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4020 DEBUG_LOG("You do not have rights to withdraw for repairs");
4021 return TotalCost;
4024 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4026 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4027 return TotalCost;
4030 if (pGuild->GetGuildBankMoney() < costs)
4032 DEBUG_LOG("There is not enough money in bank");
4033 return TotalCost;
4036 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4037 TotalCost = costs;
4039 else if (GetMoney() < costs)
4041 DEBUG_LOG("You do not have enough money");
4042 return TotalCost;
4044 else
4045 ModifyMoney( -int32(costs) );
4049 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4050 item->SetState(ITEM_CHANGED, this);
4052 // reapply mods for total broken and repaired item if equipped
4053 if(IsEquipmentPos(pos) && !curDurability)
4054 _ApplyItemMods(item,pos & 255, true);
4055 return TotalCost;
4058 void Player::RepopAtGraveyard()
4060 // note: this can be called also when the player is alive
4061 // for example from WorldSession::HandleMovementOpcodes
4063 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4065 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4066 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4068 ResurrectPlayer(0.5f);
4069 SpawnCorpseBones();
4072 WorldSafeLocsEntry const *ClosestGrave = NULL;
4074 // Special handle for battleground maps
4075 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4077 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4078 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4079 else
4080 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4082 // stop countdown until repop
4083 m_deathTimer = 0;
4085 // if no grave found, stay at the current location
4086 // and don't show spirit healer location
4087 if(ClosestGrave)
4089 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4090 if(isDead()) // not send if alive, because it used in TeleportTo()
4092 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4093 data << ClosestGrave->map_id;
4094 data << ClosestGrave->x;
4095 data << ClosestGrave->y;
4096 data << ClosestGrave->z;
4097 GetSession()->SendPacket(&data);
4102 void Player::JoinedChannel(Channel *c)
4104 m_channels.push_back(c);
4107 void Player::LeftChannel(Channel *c)
4109 m_channels.remove(c);
4112 void Player::CleanupChannels()
4114 while(!m_channels.empty())
4116 Channel* ch = *m_channels.begin();
4117 m_channels.erase(m_channels.begin()); // remove from player's channel list
4118 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4119 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4120 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4123 sLog.outDebug("Player: channels cleaned up!");
4126 void Player::UpdateLocalChannels(uint32 newZone )
4128 if(m_channels.empty())
4129 return;
4131 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4132 if(!current_zone)
4133 return;
4135 ChannelMgr* cMgr = channelMgr(GetTeam());
4136 if(!cMgr)
4137 return;
4139 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4141 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4143 next = i; ++next;
4145 // skip non built-in channels
4146 if(!(*i)->IsConstant())
4147 continue;
4149 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4150 if(!ch)
4151 continue;
4153 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4154 continue;
4156 // new channel
4157 char new_channel_name_buf[100];
4158 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4159 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4161 if((*i)!=new_channel)
4163 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4165 // leave old channel
4166 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4167 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4168 LeftChannel(*i); // remove from player's channel list
4169 cMgr->LeftChannel(name); // delete if empty
4172 sLog.outDebug("Player: channels cleaned up!");
4175 void Player::LeaveLFGChannel()
4177 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4179 if((*i)->IsLFG())
4181 (*i)->Leave(GetGUID());
4182 break;
4187 void Player::UpdateDefense()
4189 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4191 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4193 // update dependent from defense skill part
4194 UpdateDefenseBonusesMod();
4198 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4200 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4202 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4203 return;
4206 float val = 1.0f;
4208 switch(modType)
4210 case FLAT_MOD:
4211 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4212 break;
4213 case PCT_MOD:
4214 if(amount <= -100.0f)
4215 amount = -200.0f;
4217 val = (100.0f + amount) / 100.0f;
4218 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4219 break;
4222 if(!CanModifyStats())
4223 return;
4225 switch(modGroup)
4227 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4228 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4229 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4230 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4231 default: break;
4235 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4237 if(modGroup >= BASEMOD_END || modType > MOD_END)
4239 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4240 return 0.0f;
4243 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4244 return 0.0f;
4246 return m_auraBaseMod[modGroup][modType];
4249 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4251 if(modGroup >= BASEMOD_END)
4253 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4254 return 0.0f;
4257 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4258 return 0.0f;
4260 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4263 uint32 Player::GetShieldBlockValue() const
4265 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4267 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4269 value = (value < 0) ? 0 : value;
4271 return uint32(value);
4274 float Player::GetMeleeCritFromAgility()
4276 uint32 level = getLevel();
4277 uint32 pclass = getClass();
4279 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4281 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4282 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4283 if (critBase==NULL || critRatio==NULL)
4284 return 0.0f;
4286 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4287 return crit*100.0f;
4290 float Player::GetDodgeFromAgility()
4292 // Table for base dodge values
4293 float dodge_base[MAX_CLASSES] = {
4294 0.0075f, // Warrior
4295 0.00652f, // Paladin
4296 -0.0545f, // Hunter
4297 -0.0059f, // Rogue
4298 0.03183f, // Priest
4299 0.0114f, // DK
4300 0.0167f, // Shaman
4301 0.034575f, // Mage
4302 0.02011f, // Warlock
4303 0.0f, // ??
4304 -0.0187f // Druid
4306 // Crit/agility to dodge/agility coefficient multipliers
4307 float crit_to_dodge[MAX_CLASSES] = {
4308 1.1f, // Warrior
4309 1.0f, // Paladin
4310 1.6f, // Hunter
4311 2.0f, // Rogue
4312 1.0f, // Priest
4313 1.0f, // DK?
4314 1.0f, // Shaman
4315 1.0f, // Mage
4316 1.0f, // Warlock
4317 0.0f, // ??
4318 1.7f // Druid
4321 uint32 level = getLevel();
4322 uint32 pclass = getClass();
4324 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4326 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4327 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4328 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4329 return 0.0f;
4331 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4332 return dodge*100.0f;
4335 float Player::GetSpellCritFromIntellect()
4337 uint32 level = getLevel();
4338 uint32 pclass = getClass();
4340 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4342 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4343 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4344 if (critBase==NULL || critRatio==NULL)
4345 return 0.0f;
4347 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4348 return crit*100.0f;
4351 float Player::GetRatingCoefficient(CombatRating cr) const
4353 uint32 level = getLevel();
4355 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4357 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4358 if (Rating == NULL)
4359 return 1.0f; // By default use minimum coefficient (not must be called)
4361 return Rating->ratio;
4364 float Player::GetRatingBonusValue(CombatRating cr) const
4366 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4369 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4371 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4372 if (melee>25.0f) melee = 25.0f;
4373 return uint32 (melee * damage /100.0f);
4376 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4378 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4379 if (ranged>25.0f) ranged=25.0f;
4380 return uint32 (ranged * damage /100.0f);
4383 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4385 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4386 // In wow script resilience limited to 25%
4387 if (spell>25.0f)
4388 spell = 25.0f;
4389 return uint32 (spell * damage / 100.0f);
4392 uint32 Player::GetDotDamageReduction(uint32 damage) const
4394 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4395 // Dot resilience not limited (limit it by 100%)
4396 if (spellDot > 100.0f)
4397 spellDot = 100.0f;
4398 return uint32 (spellDot * damage / 100.0f);
4401 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4403 switch (attType)
4405 case BASE_ATTACK:
4406 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4407 case OFF_ATTACK:
4408 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4409 default:
4410 break;
4412 return 0.0f;
4415 float Player::OCTRegenHPPerSpirit()
4417 uint32 level = getLevel();
4418 uint32 pclass = getClass();
4420 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4422 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4423 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4424 if (baseRatio==NULL || moreRatio==NULL)
4425 return 0.0f;
4427 // Formula from PaperDollFrame script
4428 float spirit = GetStat(STAT_SPIRIT);
4429 float baseSpirit = spirit;
4430 if (baseSpirit>50) baseSpirit = 50;
4431 float moreSpirit = spirit - baseSpirit;
4432 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4433 return regen;
4436 float Player::OCTRegenMPPerSpirit()
4438 uint32 level = getLevel();
4439 uint32 pclass = getClass();
4441 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4443 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4444 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4445 if (moreRatio==NULL)
4446 return 0.0f;
4448 // Formula get from PaperDollFrame script
4449 float spirit = GetStat(STAT_SPIRIT);
4450 float regen = spirit * moreRatio->ratio;
4451 return regen;
4454 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4456 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4458 float RatingCoeffecient = GetRatingCoefficient(cr);
4459 float RatingChange = 0.0f;
4461 bool affectStats = CanModifyStats();
4463 switch (cr)
4465 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4466 case CR_DEFENSE_SKILL:
4467 UpdateDefenseBonusesMod();
4468 break;
4469 case CR_DODGE:
4470 UpdateDodgePercentage();
4471 break;
4472 case CR_PARRY:
4473 UpdateParryPercentage();
4474 break;
4475 case CR_BLOCK:
4476 UpdateBlockPercentage();
4477 break;
4478 case CR_HIT_MELEE:
4479 RatingChange = value / RatingCoeffecient;
4480 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4481 break;
4482 case CR_HIT_RANGED:
4483 RatingChange = value / RatingCoeffecient;
4484 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4485 break;
4486 case CR_HIT_SPELL:
4487 RatingChange = value / RatingCoeffecient;
4488 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4489 break;
4490 case CR_CRIT_MELEE:
4491 if(affectStats)
4493 UpdateCritPercentage(BASE_ATTACK);
4494 UpdateCritPercentage(OFF_ATTACK);
4496 break;
4497 case CR_CRIT_RANGED:
4498 if(affectStats)
4499 UpdateCritPercentage(RANGED_ATTACK);
4500 break;
4501 case CR_CRIT_SPELL:
4502 if(affectStats)
4503 UpdateAllSpellCritChances();
4504 break;
4505 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4506 case CR_HIT_TAKEN_RANGED:
4507 break;
4508 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4509 break;
4510 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4511 case CR_CRIT_TAKEN_RANGED:
4512 break;
4513 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4514 break;
4515 case CR_HASTE_MELEE:
4516 RatingChange = value / RatingCoeffecient;
4517 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4518 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4519 break;
4520 case CR_HASTE_RANGED:
4521 RatingChange = value / RatingCoeffecient;
4522 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4523 break;
4524 case CR_HASTE_SPELL:
4525 RatingChange = value / RatingCoeffecient;
4526 ApplyCastTimePercentMod(RatingChange,apply);
4527 break;
4528 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4529 case CR_WEAPON_SKILL_OFFHAND:
4530 case CR_WEAPON_SKILL_RANGED:
4531 break;
4532 case CR_EXPERTISE:
4533 if(affectStats)
4535 UpdateExpertise(BASE_ATTACK);
4536 UpdateExpertise(OFF_ATTACK);
4538 break;
4542 void Player::SetRegularAttackTime()
4544 for(int i = 0; i < MAX_ATTACK; ++i)
4546 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4547 if(tmpitem && !tmpitem->IsBroken())
4549 ItemPrototype const *proto = tmpitem->GetProto();
4550 if(proto->Delay)
4551 SetAttackTime(WeaponAttackType(i), proto->Delay);
4552 else
4553 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4558 //skill+step, checking for max value
4559 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4561 if(!skill_id)
4562 return false;
4564 uint16 i=0;
4565 for (; i < PLAYER_MAX_SKILLS; i++)
4566 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4567 break;
4569 if(i>=PLAYER_MAX_SKILLS)
4570 return false;
4572 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4573 uint32 value = SKILL_VALUE(data);
4574 uint32 max = SKILL_MAX(data);
4576 if ((!max) || (!value) || (value >= max))
4577 return false;
4579 if (value*512 < max*urand(0,512))
4581 uint32 new_value = value+step;
4582 if(new_value > max)
4583 new_value = max;
4585 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4586 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4587 return true;
4590 return false;
4593 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4595 if ( SkillValue >= GrayLevel )
4596 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4597 if ( SkillValue >= GreenLevel )
4598 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4599 if ( SkillValue >= YellowLevel )
4600 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4601 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4604 bool Player::UpdateCraftSkill(uint32 spellid)
4606 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4608 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4609 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4611 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4613 if(_spell_idx->second->skillId)
4615 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4617 // Alchemy Discoveries here
4618 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4619 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4621 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4622 learnSpell(discoveredSpell);
4625 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4627 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4628 _spell_idx->second->max_value,
4629 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4630 _spell_idx->second->min_value),
4631 craft_skill_gain);
4634 return false;
4637 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4639 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4641 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4643 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4644 switch (SkillId)
4646 case SKILL_HERBALISM:
4647 case SKILL_LOCKPICKING:
4648 case SKILL_JEWELCRAFTING:
4649 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4650 case SKILL_SKINNING:
4651 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4652 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4653 else
4654 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4655 case SKILL_MINING:
4656 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4657 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4658 else
4659 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4661 return false;
4664 bool Player::UpdateFishingSkill()
4666 sLog.outDebug("UpdateFishingSkill");
4668 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4670 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4672 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4674 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4677 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4679 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4680 if ( !SkillId )
4681 return false;
4683 if(Chance <= 0) // speedup in 0 chance case
4685 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4686 return false;
4689 uint16 i=0;
4690 for (; i < PLAYER_MAX_SKILLS; i++)
4691 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4692 if ( i >= PLAYER_MAX_SKILLS )
4693 return false;
4695 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4696 uint16 SkillValue = SKILL_VALUE(data);
4697 uint16 MaxValue = SKILL_MAX(data);
4699 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4700 return false;
4702 int32 Roll = irand(1,1000);
4704 if ( Roll <= Chance )
4706 uint32 new_value = SkillValue+step;
4707 if(new_value > MaxValue)
4708 new_value = MaxValue;
4710 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4711 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4712 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4713 return true;
4716 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4717 return false;
4720 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4722 // no skill gain in pvp
4723 Unit *pVictim = getVictim();
4724 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4725 return;
4727 if(IsInFeralForm())
4728 return; // always maximized SKILL_FERAL_COMBAT in fact
4730 if(m_form == FORM_TREE)
4731 return; // use weapon but not skill up
4733 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4735 switch(attType)
4737 case BASE_ATTACK:
4739 Item *tmpitem = GetWeaponForAttack(attType,true);
4741 if (!tmpitem)
4742 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4743 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4744 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4745 break;
4747 case OFF_ATTACK:
4748 case RANGED_ATTACK:
4750 Item *tmpitem = GetWeaponForAttack(attType,true);
4751 if (tmpitem)
4752 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4753 break;
4756 UpdateAllCritPercentages();
4759 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4761 switch(outcome)
4763 case MELEE_HIT_CRIT:
4764 case MELEE_HIT_DODGE:
4765 case MELEE_HIT_PARRY:
4766 case MELEE_HIT_BLOCK:
4767 case MELEE_HIT_BLOCK_CRIT:
4768 return;
4770 default:
4771 break;
4774 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4775 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4776 uint32 moblevel = pVictim->getLevelForTarget(this);
4777 if(moblevel < greylevel)
4778 return;
4780 if (moblevel > plevel + 5)
4781 moblevel = plevel + 5;
4783 uint32 lvldif = moblevel - greylevel;
4784 if(lvldif < 3)
4785 lvldif = 3;
4787 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4788 if(skilldif <= 0)
4789 return;
4791 float chance = float(3 * lvldif * skilldif) / plevel;
4792 if(!defence)
4794 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4795 chance *= 0.1f * GetStat(STAT_INTELLECT);
4798 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4800 if(roll_chance_f(chance))
4802 if(defence)
4803 UpdateDefense();
4804 else
4805 UpdateWeaponSkill(attType);
4807 else
4808 return;
4811 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4813 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4814 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4816 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4817 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4818 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4820 if(talent) // permanent bonus stored in high part
4821 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4822 else // temporary/item bonus stored in low part
4823 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4824 return;
4828 void Player::UpdateMaxSkills()
4830 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4832 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4833 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4835 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4837 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4838 if(!pSkill)
4839 continue;
4841 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4842 continue;
4844 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4845 uint32 max = SKILL_MAX(data);
4846 uint32 val = SKILL_VALUE(data);
4848 // update only level dependent max skill values
4849 if(max!=1 && max != maxconfskill)
4851 uint32 max_Skill = GetMaxSkillValueForLevel();
4852 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
4857 void Player::UpdateSkillsToMaxSkillsForLevel()
4859 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4860 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4862 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4863 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4864 continue;
4865 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4867 uint32 max = SKILL_MAX(data);
4869 if(max > 1)
4870 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4872 if(pskill == SKILL_DEFENSE)
4873 UpdateDefenseBonusesMod();
4877 // This functions sets a skill line value (and adds if doesn't exist yet)
4878 // To "remove" a skill line, set it's values to zero
4879 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4881 if(!id)
4882 return;
4884 uint16 i=0;
4885 for (; i < PLAYER_MAX_SKILLS; i++)
4886 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4888 if(i<PLAYER_MAX_SKILLS) //has skill
4890 if(currVal)
4892 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4893 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4895 else //remove
4897 // clear skill fields
4898 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4899 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4900 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4902 // remove spells that depend on this skill when removing the skill
4903 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4905 ++next;
4906 if(itr->second->state == PLAYERSPELL_REMOVED)
4907 continue;
4909 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4910 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4912 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4914 if (_spell_idx->second->skillId == id)
4916 // this may remove more than one spell (dependents)
4917 removeSpell(itr->first);
4918 next = m_spells.begin();
4919 break;
4925 else if(currVal) //add
4927 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4928 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4930 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4931 if(!pSkill)
4933 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4934 return;
4936 // enable unlearn button for primary professions only
4937 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4938 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4939 else
4940 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4941 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4942 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4944 // apply skill bonuses
4945 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4947 // temporary bonuses
4948 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4949 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4950 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4951 (*i)->ApplyModifier(true);
4953 // permanent bonuses
4954 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4955 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4956 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4957 (*i)->ApplyModifier(true);
4959 // Learn all spells for skill
4960 learnSkillRewardedSpells(id);
4961 return;
4966 bool Player::HasSkill(uint32 skill) const
4968 if(!skill)return false;
4969 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4971 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4973 return true;
4976 return false;
4979 uint16 Player::GetSkillValue(uint32 skill) const
4981 if(!skill)
4982 return 0;
4984 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4986 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4988 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4990 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4991 result += SKILL_TEMP_BONUS(bonus);
4992 result += SKILL_PERM_BONUS(bonus);
4993 return result < 0 ? 0 : result;
4996 return 0;
4999 uint16 Player::GetMaxSkillValue(uint32 skill) const
5001 if(!skill)return 0;
5002 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5004 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5006 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5008 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5009 result += SKILL_TEMP_BONUS(bonus);
5010 result += SKILL_PERM_BONUS(bonus);
5011 return result < 0 ? 0 : result;
5014 return 0;
5017 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5019 if(!skill)return 0;
5020 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5022 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5024 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5027 return 0;
5030 uint16 Player::GetBaseSkillValue(uint32 skill) const
5032 if(!skill)return 0;
5033 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5035 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5037 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5038 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5039 return result < 0 ? 0 : result;
5042 return 0;
5045 uint16 Player::GetPureSkillValue(uint32 skill) const
5047 if(!skill)return 0;
5048 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5050 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5052 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5055 return 0;
5058 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5060 if(!skill)
5061 return 0;
5063 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5065 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5067 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5071 return 0;
5074 void Player::SendInitialActionButtons()
5076 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5078 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5079 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5081 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5082 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5084 data << uint16(itr->second.action);
5085 data << uint8(itr->second.misc);
5086 data << uint8(itr->second.type);
5088 else
5090 data << uint32(0);
5094 GetSession()->SendPacket( &data );
5095 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5098 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5100 if(button >= MAX_ACTION_BUTTONS)
5102 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5103 return;
5106 // check cheating with adding non-known spells to action bar
5107 if(type==ACTION_BUTTON_SPELL)
5109 if(!sSpellStore.LookupEntry(action))
5111 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5112 return;
5115 if(!HasSpell(action))
5117 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5118 return;
5122 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5124 if (buttonItr==m_actionButtons.end())
5125 { // just add new button
5126 m_actionButtons[button] = ActionButton(action,type,misc);
5128 else
5129 { // change state of current button
5130 ActionButtonUpdateState uState = buttonItr->second.uState;
5131 buttonItr->second = ActionButton(action,type,misc);
5132 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5135 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5138 void Player::removeActionButton(uint8 button)
5140 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5141 if (buttonItr==m_actionButtons.end())
5142 return;
5144 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5145 m_actionButtons.erase(buttonItr); // new and not saved
5146 else
5147 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5149 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5152 void Player::SetDontMove(bool dontMove)
5154 m_dontMove = dontMove;
5157 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5159 // prevent crash when a bad coord is sent by the client
5160 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5162 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5163 return false;
5166 Map *m = MapManager::Instance().GetMap(GetMapId(), this);
5168 const float old_x = GetPositionX();
5169 const float old_y = GetPositionY();
5170 const float old_z = GetPositionZ();
5171 const float old_r = GetOrientation();
5173 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5175 if (teleport || old_x != x || old_y != y || old_z != z)
5176 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5177 else
5178 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5180 // move and update visible state if need
5181 m->PlayerRelocation(this, x, y, z, orientation);
5183 // reread after Map::Relocation
5184 m = MapManager::Instance().GetMap(GetMapId(), this);
5185 x = GetPositionX();
5186 y = GetPositionY();
5187 z = GetPositionZ();
5190 // code block for underwater state update
5191 UpdateUnderwaterState(m, x, y, z);
5193 CheckExploreSystem();
5195 // group update
5196 if(GetGroup())
5197 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5199 return true;
5202 void Player::SaveRecallPosition()
5204 m_recallMap = GetMapId();
5205 m_recallX = GetPositionX();
5206 m_recallY = GetPositionY();
5207 m_recallZ = GetPositionZ();
5208 m_recallO = GetOrientation();
5211 void Player::SendMessageToSet(WorldPacket *data, bool self)
5213 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
5216 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5218 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self);
5221 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5223 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self,own_team_only);
5226 void Player::SendDirectMessage(WorldPacket *data)
5228 GetSession()->SendPacket(data);
5231 void Player::CheckExploreSystem()
5233 if (!isAlive())
5234 return;
5236 if (isInFlight())
5237 return;
5239 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5240 if(areaFlag==0xffff)
5241 return;
5242 int offset = areaFlag / 32;
5244 if(offset >= 128)
5246 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);
5247 return;
5250 uint32 val = (uint32)(1 << (areaFlag % 32));
5251 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5253 if( !(currFields & val) )
5255 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5257 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5258 if(!p)
5260 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5262 else if(p->area_level > 0)
5264 uint32 area = p->ID;
5265 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5267 SendExplorationExperience(area,0);
5269 else
5271 int32 diff = int32(getLevel()) - p->area_level;
5272 uint32 XP = 0;
5273 if (diff < -5)
5275 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5277 else if (diff > 5)
5279 int32 exploration_percent = (100-((diff-5)*5));
5280 if (exploration_percent > 100)
5281 exploration_percent = 100;
5282 else if (exploration_percent < 0)
5283 exploration_percent = 0;
5285 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5287 else
5289 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5292 GiveXP( XP, NULL );
5293 SendExplorationExperience(area,XP);
5295 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5300 uint32 Player::TeamForRace(uint8 race)
5302 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5303 if(!rEntry)
5305 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5306 return ALLIANCE;
5309 switch(rEntry->TeamID)
5311 case 7: return ALLIANCE;
5312 case 1: return HORDE;
5315 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5316 return ALLIANCE;
5319 uint32 Player::getFactionForRace(uint8 race)
5321 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5322 if(!rEntry)
5324 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5325 return 0;
5328 return rEntry->FactionID;
5331 void Player::setFactionForRace(uint8 race)
5333 m_team = TeamForRace(race);
5334 setFaction( getFactionForRace(race) );
5337 void Player::UpdateReputation() const
5339 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5341 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5343 SendFactionState(&(itr->second));
5347 void Player::SendFactionState(FactionState const* faction) const
5349 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5351 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5352 data << (float) 0; // unk 2.4.0
5353 data << (uint8) 0; // wotlk 8634
5354 data << (uint32) 1; // count
5355 // for
5356 data << (uint32) faction->ReputationListID;
5357 data << (uint32) faction->Standing;
5358 // end for
5359 GetSession()->SendPacket(&data);
5363 void Player::SendInitialReputations()
5365 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5366 data << uint32 (0x00000080);
5368 RepListID a = 0;
5370 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5372 // fill in absent fields
5373 for (; a != itr->first; a++)
5375 data << uint8 (0x00);
5376 data << uint32 (0x00000000);
5379 // fill in encountered data
5380 data << uint8 (itr->second.Flags);
5381 data << uint32 (itr->second.Standing);
5383 ++a;
5386 // fill in absent fields
5387 for (; a != 128; a++)
5389 data << uint8 (0x00);
5390 data << uint32 (0x00000000);
5393 GetSession()->SendPacket(&data);
5396 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5398 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5399 if (itr != m_factions.end())
5400 return &itr->second;
5402 return NULL;
5405 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5407 // not allow declare war to own faction
5408 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5409 return;
5411 // already set
5412 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5413 return;
5415 if( atWar )
5416 faction->Flags |= FACTION_FLAG_AT_WAR;
5417 else
5418 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5420 faction->Changed = true;
5423 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5425 // always invisible or hidden faction can't be inactive
5426 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5427 return;
5429 // already set
5430 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5431 return;
5433 if(inactive)
5434 faction->Flags |= FACTION_FLAG_INACTIVE;
5435 else
5436 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5438 faction->Changed = true;
5441 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5443 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5445 if(!factionTemplateEntry)
5446 return;
5448 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5451 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5453 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5454 if(!factionEntry)
5455 return;
5457 if(factionEntry->reputationListID < 0)
5458 return;
5460 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5461 if (itr == m_factions.end())
5462 return;
5464 SetFactionVisible(&itr->second);
5467 void Player::SetFactionVisible(FactionState* faction)
5469 // always invisible or hidden faction can't be make visible
5470 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5471 return;
5473 // already set
5474 if(faction->Flags & FACTION_FLAG_VISIBLE)
5475 return;
5477 faction->Flags |= FACTION_FLAG_VISIBLE;
5478 faction->Changed = true;
5480 if(!m_session->PlayerLoading())
5482 // make faction visible in reputation list at client
5483 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5484 data << faction->ReputationListID;
5485 GetSession()->SendPacket(&data);
5489 void Player::SetInitialFactions()
5491 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5493 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5495 if( factionEntry && (factionEntry->reputationListID >= 0))
5497 FactionState newFaction;
5498 newFaction.ID = factionEntry->ID;
5499 newFaction.ReputationListID = factionEntry->reputationListID;
5500 newFaction.Standing = 0;
5501 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5502 newFaction.Changed = true;
5504 m_factions[newFaction.ReputationListID] = newFaction;
5509 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5511 if (!factionEntry)
5512 return 0;
5514 uint32 raceMask = getRaceMask();
5515 uint32 classMask = getClassMask();
5516 for (int i=0; i < 4; i++)
5518 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5519 (factionEntry->BaseRepClassMask[i]==0 ||
5520 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5521 return factionEntry->ReputationFlags[i];
5523 return 0;
5526 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5528 if (!factionEntry)
5529 return 0;
5531 uint32 raceMask = getRaceMask();
5532 uint32 classMask = getClassMask();
5533 for (int i=0; i < 4; i++)
5535 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5536 (factionEntry->BaseRepClassMask[i]==0 ||
5537 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5538 return factionEntry->BaseRepValue[i];
5541 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5542 return 0;
5545 int32 Player::GetReputation(uint32 faction_id) const
5547 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5549 if (!factionEntry)
5551 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5552 return 0;
5555 return GetReputation(factionEntry);
5558 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5560 // Faction without recorded reputation. Just ignore.
5561 if(!factionEntry)
5562 return 0;
5564 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5565 if (itr != m_factions.end())
5566 return GetBaseReputation(factionEntry) + itr->second.Standing;
5568 return 0;
5571 ReputationRank Player::GetReputationRank(uint32 faction) const
5573 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5574 if(!factionEntry)
5575 return MIN_REPUTATION_RANK;
5577 return GetReputationRank(factionEntry);
5580 ReputationRank Player::ReputationToRank(int32 standing) const
5582 int32 Limit = Reputation_Cap + 1;
5583 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5585 Limit -= ReputationRank_Length[i];
5586 if (standing >= Limit )
5587 return ReputationRank(i);
5589 return MIN_REPUTATION_RANK;
5592 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5594 int32 Reputation = GetReputation(factionEntry);
5595 return ReputationToRank(Reputation);
5598 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5600 int32 Reputation = GetBaseReputation(factionEntry);
5601 return ReputationToRank(Reputation);
5604 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5606 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5608 if(!factionTemplateEntry)
5610 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5611 return false;
5614 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5616 // Faction without recorded reputation. Just ignore.
5617 if(!factionEntry)
5618 return false;
5620 return ModifyFactionReputation(factionEntry, DeltaReputation);
5623 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5625 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5626 if (flist)
5628 bool res = false;
5629 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5631 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5632 if(factionEntryCalc)
5633 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5635 return res;
5637 else
5638 return ModifyOneFactionReputation(factionEntry, standing);
5641 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5643 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5644 if (itr != m_factions.end())
5646 int32 BaseRep = GetBaseReputation(factionEntry);
5647 int32 new_rep = BaseRep + itr->second.Standing + standing;
5649 if (new_rep > Reputation_Cap)
5650 new_rep = Reputation_Cap;
5651 else
5652 if (new_rep < Reputation_Bottom)
5653 new_rep = Reputation_Bottom;
5655 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5656 SetFactionAtWar(&itr->second,true);
5658 itr->second.Standing = new_rep - BaseRep;
5659 itr->second.Changed = true;
5661 SetFactionVisible(&itr->second);
5663 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5665 if(uint32 questid = GetQuestSlotQuestId(i))
5667 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5668 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5670 QuestStatusData& q_status = mQuestStatus[questid];
5671 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5673 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5674 if ( CanCompleteQuest( questid ) )
5675 CompleteQuest( questid );
5677 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5679 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5680 IncompleteQuest( questid );
5686 SendFactionState(&(itr->second));
5688 return true;
5690 return false;
5693 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5695 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5697 if(!factionTemplateEntry)
5699 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5700 return false;
5703 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5705 // Faction without recorded reputation. Just ignore.
5706 if(!factionEntry)
5707 return false;
5709 return SetFactionReputation(factionEntry, standing);
5712 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5714 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5715 if (flist)
5717 bool res = false;
5718 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5720 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5721 if(factionEntryCalc)
5722 res = SetOneFactionReputation(factionEntryCalc, standing);
5724 return res;
5726 else
5727 return SetOneFactionReputation(factionEntry, standing);
5730 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5732 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5733 if (itr != m_factions.end())
5735 if (standing > Reputation_Cap)
5736 standing = Reputation_Cap;
5737 else
5738 if (standing < Reputation_Bottom)
5739 standing = Reputation_Bottom;
5741 int32 BaseRep = GetBaseReputation(factionEntry);
5742 itr->second.Standing = standing - BaseRep;
5743 itr->second.Changed = true;
5745 SetFactionVisible(&itr->second);
5747 if(ReputationToRank(standing) <= REP_HOSTILE)
5748 SetFactionAtWar(&itr->second,true);
5750 SendFactionState(&(itr->second));
5751 return true;
5753 return false;
5756 //Calculate total reputation percent player gain with quest/creature level
5757 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5759 // for grey creature kill received 20%, in other case 100.
5760 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5762 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5764 percent += rep > 0 ? repMod : -repMod;
5766 if(percent <=0)
5767 return 0;
5769 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5772 //Calculates how many reputation points player gains in victim's enemy factions
5773 void Player::RewardReputation(Unit *pVictim, float rate)
5775 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5776 return;
5778 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5780 if(!Rep)
5781 return;
5783 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5785 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5786 donerep1 = int32(donerep1*rate);
5787 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5788 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5789 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5790 ModifyFactionReputation(factionEntry1, donerep1);
5792 // Wiki: Team factions value divided by 2
5793 if(Rep->is_teamaward1)
5795 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5796 if(team1_factionEntry)
5797 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5801 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5803 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5804 donerep2 = int32(donerep2*rate);
5805 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5806 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5807 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5808 ModifyFactionReputation(factionEntry2, donerep2);
5810 // Wiki: Team factions value divided by 2
5811 if(Rep->is_teamaward2)
5813 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5814 if(team2_factionEntry)
5815 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5820 //Calculate how many reputation points player gain with the quest
5821 void Player::RewardReputation(Quest const *pQuest)
5823 // quest reputation reward/loss
5824 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5826 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5828 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5829 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5830 if(factionEntry)
5831 ModifyFactionReputation(factionEntry, rep);
5835 // TODO: implement reputation spillover
5838 void Player::UpdateArenaFields(void)
5840 /* arena calcs go here */
5843 void Player::UpdateHonorFields()
5845 /// called when rewarding honor and at each save
5846 uint64 now = time(NULL);
5847 uint64 today = uint64(time(NULL) / DAY) * DAY;
5849 if(m_lastHonorUpdateTime < today)
5851 uint64 yesterday = today - DAY;
5853 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5855 // update yesterday's contribution
5856 if(m_lastHonorUpdateTime >= yesterday )
5858 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5860 // this is the first update today, reset today's contribution
5861 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5862 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5864 else
5866 // no honor/kills yesterday or today, reset
5867 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5868 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5872 m_lastHonorUpdateTime = now;
5875 ///Calculate the amount of honor gained based on the victim
5876 ///and the size of the group for which the honor is divided
5877 ///An exact honor value can also be given (overriding the calcs)
5878 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5880 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5881 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5882 return false;
5884 uint64 victim_guid = 0;
5885 uint32 victim_rank = 0;
5887 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5888 UpdateHonorFields();
5890 if(honor <= 0)
5892 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5893 return false;
5895 victim_guid = uVictim->GetGUID();
5897 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5899 Player *pVictim = (Player *)uVictim;
5901 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5902 return false;
5904 float f = 1; //need for total kills (?? need more info)
5905 uint32 k_grey = 0;
5906 uint32 k_level = getLevel();
5907 uint32 v_level = pVictim->getLevel();
5910 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5911 // [0] Just name
5912 // [1..14] Alliance honor titles and player name
5913 // [15..28] Horde honor titles and player name
5914 // [29..38] Other title and player name
5915 // [39+] Nothing
5916 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5917 // Get Killer titles, CharTitlesEntry::bit_index
5918 // Ranks:
5919 // title[1..14] -> rank[5..18]
5920 // title[15..28] -> rank[5..18]
5921 // title[other] -> 0
5922 if (victim_title == 0)
5923 victim_guid = 0; // Don't show HK: <rank> message, only log.
5924 else if (victim_title < 15)
5925 victim_rank = victim_title + 4;
5926 else if (victim_title < 29)
5927 victim_rank = victim_title - 14 + 4;
5928 else
5929 victim_guid = 0; // Don't show HK: <rank> message, only log.
5932 if(k_level <= 5)
5933 k_grey = 0;
5934 else if( k_level <= 39 )
5935 k_grey = k_level - 5 - k_level/10;
5936 else
5937 k_grey = k_level - 1 - k_level/5;
5939 if(v_level<=k_grey)
5940 return false;
5942 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5944 int32 v_rank =1; //need more info
5946 honor = ((f * diff_level * (190 + v_rank*10))/6);
5947 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5949 // count the number of playerkills in one day
5950 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5951 // and those in a lifetime
5952 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5954 else
5956 Creature *cVictim = (Creature *)uVictim;
5958 if (!cVictim->isRacialLeader())
5959 return false;
5961 honor = 100; // ??? need more info
5962 victim_rank = 19; // HK: Leader
5966 if (uVictim != NULL)
5968 honor *= sWorld.getRate(RATE_HONOR);
5970 if(groupsize > 1)
5971 honor /= groupsize;
5973 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5976 // honor - for show honor points in log
5977 // victim_guid - for show victim name in log
5978 // victim_rank [1..4] HK: <dishonored rank>
5979 // victim_rank [5..19] HK: <alliance\horde rank>
5980 // victim_rank [0,20+] HK: <>
5981 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5982 data << (uint32) honor;
5983 data << (uint64) victim_guid;
5984 data << (uint32) victim_rank;
5986 GetSession()->SendPacket(&data);
5988 // add honor points
5989 ModifyHonorPoints(int32(honor));
5991 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5992 return true;
5995 void Player::ModifyHonorPoints( int32 value )
5997 if(value < 0)
5999 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6000 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6001 else
6002 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6004 else
6005 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6008 void Player::ModifyArenaPoints( int32 value )
6010 if(value < 0)
6012 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6013 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6014 else
6015 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6017 else
6018 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6021 uint32 Player::GetGuildIdFromDB(uint64 guid)
6023 std::ostringstream ss;
6024 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
6025 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6026 if( result )
6028 uint32 v = result->Fetch()[0].GetUInt32();
6029 delete result;
6030 return v;
6032 else
6033 return 0;
6036 uint32 Player::GetRankFromDB(uint64 guid)
6038 std::ostringstream ss;
6039 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6040 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6041 if( result )
6043 uint32 v = result->Fetch()[0].GetUInt32();
6044 delete result;
6045 return v;
6047 else
6048 return 0;
6051 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6053 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid), type);
6054 if(!result)
6055 return 0;
6057 uint32 id = (*result)[0].GetUInt32();
6058 delete result;
6059 return id;
6062 uint32 Player::GetZoneIdFromDB(uint64 guid)
6064 std::ostringstream ss;
6066 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6067 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6068 if (!result)
6069 return 0;
6070 Field* fields = result->Fetch();
6071 uint32 zone = fields[0].GetUInt32();
6072 delete result;
6074 if (!zone)
6076 // stored zone is zero, use generic and slow zone detection
6077 ss.str("");
6078 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6079 result = CharacterDatabase.Query(ss.str().c_str());
6080 if( !result )
6081 return 0;
6082 fields = result->Fetch();
6083 uint32 map = fields[0].GetUInt32();
6084 float posx = fields[1].GetFloat();
6085 float posy = fields[2].GetFloat();
6086 delete result;
6088 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6090 ss.str("");
6091 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6092 CharacterDatabase.Execute(ss.str().c_str());
6095 return zone;
6098 void Player::UpdateArea(uint32 newArea)
6100 // FFA_PVP flags are area and not zone id dependent
6101 // so apply them accordingly
6102 m_areaUpdateId = newArea;
6104 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6106 if(area && (area->flags & AREA_FLAG_ARENA))
6108 if(!isGameMaster())
6109 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6111 else
6113 // remove ffa flag only if not ffapvp realm
6114 // removal in sanctuaries and capitals is handled in zone update
6115 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6116 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6119 UpdateAreaDependentAuras(newArea);
6122 void Player::UpdateZone(uint32 newZone)
6124 m_zoneUpdateId = newZone;
6125 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6127 // zone changed, so area changed as well, update it
6128 UpdateArea(GetAreaId());
6130 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6131 if(!zone)
6132 return;
6134 if (sWorld.getConfig(CONFIG_WEATHER))
6136 Weather *wth = sWorld.FindWeather(zone->ID);
6137 if(wth)
6139 wth->SendWeatherUpdateToPlayer(this);
6141 else
6143 if(!sWorld.AddWeather(zone->ID))
6145 // send fine weather packet to remove old zone's weather
6146 Weather::SendFineWeatherUpdateToPlayer(this);
6151 pvpInfo.inHostileArea =
6152 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6153 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6154 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6155 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6157 if(pvpInfo.inHostileArea) // in hostile area
6159 if(!IsPvP() || pvpInfo.endTimer != 0)
6160 UpdatePvP(true, true);
6162 else // in friendly area
6164 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6165 pvpInfo.endTimer = time(0); // start toggle-off
6168 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6170 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6171 if(sWorld.IsFFAPvPRealm())
6172 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6174 else
6176 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6179 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6181 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6182 SetRestType(REST_TYPE_IN_CITY);
6183 InnEnter(time(0),GetMapId(),0,0,0);
6185 if(sWorld.IsFFAPvPRealm())
6186 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6188 else // anywhere else
6190 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6192 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6194 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6196 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6197 SetRestType(REST_TYPE_NO);
6199 if(sWorld.IsFFAPvPRealm())
6200 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6203 else // not in tavern (leave city then)
6205 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6206 SetRestType(REST_TYPE_NO);
6208 // Set player to FFA PVP when not in rested environment.
6209 if(sWorld.IsFFAPvPRealm())
6210 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6215 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6216 // if player resurrected at teleport this will be applied in resurrect code
6217 if(isAlive())
6218 DestroyZoneLimitedItem( true, newZone );
6220 // recent client version not send leave/join channel packets for built-in local channels
6221 UpdateLocalChannels( newZone );
6223 // group update
6224 if(GetGroup())
6225 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6227 UpdateZoneDependentAuras(newZone);
6230 //If players are too far way of duel flag... then player loose the duel
6231 void Player::CheckDuelDistance(time_t currTime)
6233 if(!duel)
6234 return;
6236 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6237 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6238 if(!obj)
6239 return;
6241 if(duel->outOfBound == 0)
6243 if(!IsWithinDistInMap(obj, 50))
6245 duel->outOfBound = currTime;
6247 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6248 GetSession()->SendPacket(&data);
6251 else
6253 if(IsWithinDistInMap(obj, 40))
6255 duel->outOfBound = 0;
6257 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6258 GetSession()->SendPacket(&data);
6260 else if(currTime >= (duel->outOfBound+10))
6262 DuelComplete(DUEL_FLED);
6267 void Player::DuelComplete(DuelCompleteType type)
6269 // duel not requested
6270 if(!duel)
6271 return;
6273 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6274 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6275 GetSession()->SendPacket(&data);
6276 duel->opponent->GetSession()->SendPacket(&data);
6278 if(type != DUEL_INTERUPTED)
6280 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6281 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6282 data << duel->opponent->GetName();
6283 data << GetName();
6284 SendMessageToSet(&data,true);
6287 // cool-down duel spell
6288 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6290 data<<GetGUID();
6291 data<<uint8(0x0);
6293 data<<(uint32)7266;
6294 data<<uint32(0x0);
6295 GetSession()->SendPacket(&data);
6296 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6297 data<<duel->opponent->GetGUID();
6298 data<<uint8(0x0);
6299 data<<(uint32)7266;
6300 data<<uint32(0x0);
6301 duel->opponent->GetSession()->SendPacket(&data);*/
6303 //Remove Duel Flag object
6304 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6305 if(obj)
6306 duel->initiator->RemoveGameObject(obj,true);
6308 /* remove auras */
6309 std::vector<uint32> auras2remove;
6310 AuraMap const& vAuras = duel->opponent->GetAuras();
6311 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6313 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6314 auras2remove.push_back(i->second->GetId());
6317 for(size_t i=0; i<auras2remove.size(); i++)
6318 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6320 auras2remove.clear();
6321 AuraMap const& auras = GetAuras();
6322 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6324 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6325 auras2remove.push_back(i->second->GetId());
6327 for(size_t i=0; i<auras2remove.size(); i++)
6328 RemoveAurasDueToSpell(auras2remove[i]);
6330 // cleanup combo points
6331 if(GetComboTarget()==duel->opponent->GetGUID())
6332 ClearComboPoints();
6333 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6334 ClearComboPoints();
6336 if(duel->opponent->GetComboTarget()==GetGUID())
6337 duel->opponent->ClearComboPoints();
6338 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6339 duel->opponent->ClearComboPoints();
6341 //cleanups
6342 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6343 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6344 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6345 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6347 delete duel->opponent->duel;
6348 duel->opponent->duel = NULL;
6349 delete duel;
6350 duel = NULL;
6353 //---------------------------------------------------------//
6355 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6357 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6358 return;
6360 // not apply/remove mods for broken item
6361 if(item->IsBroken())
6362 return;
6364 ItemPrototype const *proto = item->GetProto();
6366 if(!proto)
6367 return;
6369 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6371 uint32 attacktype = Player::GetAttackBySlot(slot);
6372 if(attacktype < MAX_ATTACK)
6373 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6375 _ApplyItemBonuses(proto,slot,apply);
6377 if( slot==EQUIPMENT_SLOT_RANGED )
6378 _ApplyAmmoBonuses();
6380 ApplyItemEquipSpell(item,apply);
6381 ApplyEnchantment(item, apply);
6383 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6384 CorrectMetaGemEnchants(slot, apply);
6386 sLog.outDebug("_ApplyItemMods complete.");
6389 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6391 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6392 return;
6394 for (int i = 0; i < 10; i++)
6396 uint32 statType = 0;
6397 int32 val = 0;
6399 if(proto->ScalingStatDistribution)
6401 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6403 statType = ssd->StatMod[i];
6405 if(uint32 modifier = ssd->Modifier[i])
6407 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6408 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6410 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6411 val = (multiplier * modifier) / 10000;
6416 else
6418 statType = proto->ItemStat[i].ItemStatType;
6419 val = float(proto->ItemStat[i].ItemStatValue);
6422 if(val == 0)
6423 continue;
6425 switch (statType)
6427 case ITEM_MOD_MANA:
6428 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6429 break;
6430 case ITEM_MOD_HEALTH: // modify HP
6431 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6432 break;
6433 case ITEM_MOD_AGILITY: // modify agility
6434 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6435 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6436 break;
6437 case ITEM_MOD_STRENGTH: //modify strength
6438 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6439 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6440 break;
6441 case ITEM_MOD_INTELLECT: //modify intellect
6442 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6443 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6444 break;
6445 case ITEM_MOD_SPIRIT: //modify spirit
6446 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6447 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6448 break;
6449 case ITEM_MOD_STAMINA: //modify stamina
6450 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6451 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6452 break;
6453 case ITEM_MOD_DEFENSE_SKILL_RATING:
6454 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6455 break;
6456 case ITEM_MOD_DODGE_RATING:
6457 ApplyRatingMod(CR_DODGE, int32(val), apply);
6458 break;
6459 case ITEM_MOD_PARRY_RATING:
6460 ApplyRatingMod(CR_PARRY, int32(val), apply);
6461 break;
6462 case ITEM_MOD_BLOCK_RATING:
6463 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6464 break;
6465 case ITEM_MOD_HIT_MELEE_RATING:
6466 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6467 break;
6468 case ITEM_MOD_HIT_RANGED_RATING:
6469 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6470 break;
6471 case ITEM_MOD_HIT_SPELL_RATING:
6472 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6473 break;
6474 case ITEM_MOD_CRIT_MELEE_RATING:
6475 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6476 break;
6477 case ITEM_MOD_CRIT_RANGED_RATING:
6478 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6479 break;
6480 case ITEM_MOD_CRIT_SPELL_RATING:
6481 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6482 break;
6483 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6484 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6485 break;
6486 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6487 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6488 break;
6489 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6490 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6491 break;
6492 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6493 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6494 break;
6495 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6496 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6497 break;
6498 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6499 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6500 break;
6501 case ITEM_MOD_HASTE_MELEE_RATING:
6502 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6503 break;
6504 case ITEM_MOD_HASTE_RANGED_RATING:
6505 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6506 break;
6507 case ITEM_MOD_HASTE_SPELL_RATING:
6508 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6509 break;
6510 case ITEM_MOD_HIT_RATING:
6511 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6512 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6513 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6514 break;
6515 case ITEM_MOD_CRIT_RATING:
6516 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6517 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6518 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6519 break;
6520 case ITEM_MOD_HIT_TAKEN_RATING:
6521 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6522 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6523 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6524 break;
6525 case ITEM_MOD_CRIT_TAKEN_RATING:
6526 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6527 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6528 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6529 break;
6530 case ITEM_MOD_RESILIENCE_RATING:
6531 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6532 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6533 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6534 break;
6535 case ITEM_MOD_HASTE_RATING:
6536 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6537 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6538 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6539 break;
6540 case ITEM_MOD_EXPERTISE_RATING:
6541 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6542 break;
6543 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6544 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6545 break;
6549 if (proto->Armor)
6550 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6552 if (proto->Block)
6553 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6555 if (proto->HolyRes)
6556 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6558 if (proto->FireRes)
6559 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6561 if (proto->NatureRes)
6562 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6564 if (proto->FrostRes)
6565 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6567 if (proto->ShadowRes)
6568 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6570 if (proto->ArcaneRes)
6571 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6573 WeaponAttackType attType = BASE_ATTACK;
6574 float damage = 0.0f;
6576 if( slot == EQUIPMENT_SLOT_RANGED && (
6577 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6578 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6580 attType = RANGED_ATTACK;
6582 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6584 attType = OFF_ATTACK;
6587 if (proto->Damage[0].DamageMin > 0 )
6589 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6590 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6591 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6594 if (proto->Damage[0].DamageMax > 0 )
6596 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6597 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6600 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6601 return;
6603 if (proto->Delay)
6605 if(slot == EQUIPMENT_SLOT_RANGED)
6606 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6607 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6608 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6609 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6610 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6613 if(CanModifyStats() && (damage || proto->Delay))
6614 UpdateDamagePhysical(attType);
6617 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6619 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6620 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6621 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6623 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6624 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6625 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6627 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6628 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6629 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6632 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6634 // generic not weapon specific case processes in aura code
6635 if(aura->GetSpellProto()->EquippedItemClass == -1)
6636 return;
6638 BaseModGroup mod = BASEMOD_END;
6639 switch(attackType)
6641 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6642 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6643 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6644 default: return;
6647 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6649 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6653 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6655 // ignore spell mods for not wands
6656 Modifier const* modifier = aura->GetModifier();
6657 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6658 return;
6660 // generic not weapon specific case processes in aura code
6661 if(aura->GetSpellProto()->EquippedItemClass == -1)
6662 return;
6664 UnitMods unitMod = UNIT_MOD_END;
6665 switch(attackType)
6667 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6668 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6669 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6670 default: return;
6673 UnitModifierType unitModType = TOTAL_VALUE;
6674 switch(modifier->m_auraname)
6676 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6677 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6678 default: return;
6681 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6683 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6687 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6689 if(!item)
6690 return;
6692 ItemPrototype const *proto = item->GetProto();
6693 if(!proto)
6694 return;
6696 for (int i = 0; i < 5; i++)
6698 _Spell const& spellData = proto->Spells[i];
6700 // no spell
6701 if(!spellData.SpellId )
6702 continue;
6704 // wrong triggering type
6705 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6706 continue;
6708 // check if it is valid spell
6709 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6710 if(!spellproto)
6711 continue;
6713 ApplyEquipSpell(spellproto,item,apply,form_change);
6717 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6719 if(apply)
6721 // Cannot be used in this stance/form
6722 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6723 return;
6725 if(form_change) // check aura active state from other form
6727 bool found = false;
6728 for (int k=0; k < 3; ++k)
6730 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6731 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6733 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6735 found = true;
6736 break;
6739 if(found)
6740 break;
6743 if(found) // and skip re-cast already active aura at form change
6744 return;
6747 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6749 CastSpell(this,spellInfo,true,item);
6751 else
6753 if(form_change) // check aura compatibility
6755 // Cannot be used in this stance/form
6756 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6757 return; // and remove only not compatible at form change
6760 if(item)
6761 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6762 else
6763 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6767 void Player::UpdateEquipSpellsAtFormChange()
6769 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6771 if(m_items[i] && !m_items[i]->IsBroken())
6773 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6774 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6778 // item set bonuses not dependent from item broken state
6779 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6781 ItemSetEffect* eff = ItemSetEff[setindex];
6782 if(!eff)
6783 continue;
6785 for(uint32 y=0;y<8; ++y)
6787 SpellEntry const* spellInfo = eff->spells[y];
6788 if(!spellInfo)
6789 continue;
6791 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6792 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6797 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6799 if(!item || item->IsBroken())
6800 return;
6802 ItemPrototype const *proto = item->GetProto();
6803 if(!proto)
6804 return;
6806 if (!Target || Target == this )
6807 return;
6809 for (int i = 0; i < 5; i++)
6811 _Spell const& spellData = proto->Spells[i];
6813 // no spell
6814 if(!spellData.SpellId )
6815 continue;
6817 // wrong triggering type
6818 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6819 continue;
6821 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6822 if(!spellInfo)
6824 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6825 continue;
6828 // not allow proc extra attack spell at extra attack
6829 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6830 return;
6832 float chance = spellInfo->procChance;
6834 if(spellData.SpellPPMRate)
6836 uint32 WeaponSpeed = GetAttackTime(attType);
6837 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6839 else if(chance > 100.0f)
6841 chance = GetWeaponProcChance();
6844 if (roll_chance_f(chance))
6845 CastSpell(Target, spellInfo->Id, true, item);
6848 // item combat enchantments
6849 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6851 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6852 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6853 if(!pEnchant) continue;
6854 for (int s=0;s<3;s++)
6856 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6857 continue;
6859 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6860 if (!spellInfo)
6862 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6863 continue;
6866 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6867 if (roll_chance_f(chance))
6869 if(IsPositiveSpell(pEnchant->spellid[s]))
6870 CastSpell(this, pEnchant->spellid[s], true, item);
6871 else
6872 CastSpell(Target, pEnchant->spellid[s], true, item);
6878 void Player::_RemoveAllItemMods()
6880 sLog.outDebug("_RemoveAllItemMods start.");
6882 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6884 if(m_items[i])
6886 ItemPrototype const *proto = m_items[i]->GetProto();
6887 if(!proto)
6888 continue;
6890 // item set bonuses not dependent from item broken state
6891 if(proto->ItemSet)
6892 RemoveItemsSetItem(this,proto);
6894 if(m_items[i]->IsBroken())
6895 continue;
6897 ApplyItemEquipSpell(m_items[i],false);
6898 ApplyEnchantment(m_items[i], false);
6902 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6904 if(m_items[i])
6906 if(m_items[i]->IsBroken())
6907 continue;
6908 ItemPrototype const *proto = m_items[i]->GetProto();
6909 if(!proto)
6910 continue;
6912 uint32 attacktype = Player::GetAttackBySlot(i);
6913 if(attacktype < MAX_ATTACK)
6914 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6916 _ApplyItemBonuses(proto,i, false);
6918 if( i == EQUIPMENT_SLOT_RANGED )
6919 _ApplyAmmoBonuses();
6923 sLog.outDebug("_RemoveAllItemMods complete.");
6926 void Player::_ApplyAllItemMods()
6928 sLog.outDebug("_ApplyAllItemMods start.");
6930 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6932 if(m_items[i])
6934 if(m_items[i]->IsBroken())
6935 continue;
6937 ItemPrototype const *proto = m_items[i]->GetProto();
6938 if(!proto)
6939 continue;
6941 uint32 attacktype = Player::GetAttackBySlot(i);
6942 if(attacktype < MAX_ATTACK)
6943 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6945 _ApplyItemBonuses(proto,i, true);
6947 if( i == EQUIPMENT_SLOT_RANGED )
6948 _ApplyAmmoBonuses();
6952 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6954 if(m_items[i])
6956 ItemPrototype const *proto = m_items[i]->GetProto();
6957 if(!proto)
6958 continue;
6960 // item set bonuses not dependent from item broken state
6961 if(proto->ItemSet)
6962 AddItemsSetItem(this,m_items[i]);
6964 if(m_items[i]->IsBroken())
6965 continue;
6967 ApplyItemEquipSpell(m_items[i],true);
6968 ApplyEnchantment(m_items[i], true);
6972 sLog.outDebug("_ApplyAllItemMods complete.");
6975 void Player::_ApplyAmmoBonuses()
6977 // check ammo
6978 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6979 if(!ammo_id)
6980 return;
6982 float currentAmmoDPS;
6984 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6985 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6986 currentAmmoDPS = 0.0f;
6987 else
6988 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6990 if(currentAmmoDPS == GetAmmoDPS())
6991 return;
6993 m_ammoDPS = currentAmmoDPS;
6995 if(CanModifyStats())
6996 UpdateDamagePhysical(RANGED_ATTACK);
6999 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7001 if(!ammo_proto)
7002 return false;
7004 // check ranged weapon
7005 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7006 if(!weapon || weapon->IsBroken() )
7007 return false;
7009 ItemPrototype const* weapon_proto = weapon->GetProto();
7010 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7011 return false;
7013 // check ammo ws. weapon compatibility
7014 switch(weapon_proto->SubClass)
7016 case ITEM_SUBCLASS_WEAPON_BOW:
7017 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7018 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7019 return false;
7020 break;
7021 case ITEM_SUBCLASS_WEAPON_GUN:
7022 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7023 return false;
7024 break;
7025 default:
7026 return false;
7029 return true;
7032 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7033 Called by remove insignia spell effect */
7034 void Player::RemovedInsignia(Player* looterPlr)
7036 if (!GetBattleGroundId())
7037 return;
7039 // If not released spirit, do it !
7040 if(m_deathTimer > 0)
7042 m_deathTimer = 0;
7043 BuildPlayerRepop();
7044 RepopAtGraveyard();
7047 Corpse *corpse = GetCorpse();
7048 if (!corpse)
7049 return;
7051 // We have to convert player corpse to bones, not to be able to resurrect there
7052 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7053 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7054 if (!bones)
7055 return;
7057 // Now we must make bones lootable, and send player loot
7058 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7060 // We store the level of our player in the gold field
7061 // We retrieve this information at Player::SendLoot()
7062 bones->loot.gold = getLevel();
7063 bones->lootRecipient = looterPlr;
7064 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7067 /*Loot type MUST be
7068 1-corpse, go
7069 2-skinning
7070 3-Fishing
7073 void Player::SendLootRelease( uint64 guid )
7075 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7076 data << uint64(guid) << uint8(1);
7077 SendDirectMessage( &data );
7080 void Player::SendLoot(uint64 guid, LootType loot_type)
7082 Loot *loot = 0;
7083 PermissionTypes permission = ALL_PERMISSION;
7085 sLog.outDebug("Player::SendLoot");
7086 if (IS_GAMEOBJECT_GUID(guid))
7088 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7089 GameObject *go =
7090 ObjectAccessor::GetGameObject(*this, guid);
7092 // not check distance for GO in case owned GO (fishing bobber case, for example)
7093 // And permit out of range GO with no owner in case fishing hole
7094 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7096 SendLootRelease(guid);
7097 return;
7100 loot = &go->loot;
7102 if(go->getLootState() == GO_READY)
7104 uint32 lootid = go->GetLootId();
7106 if(lootid)
7108 sLog.outDebug(" if(lootid)");
7109 loot->clear();
7110 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7113 if(loot_type == LOOT_FISHING)
7114 go->getFishLoot(loot);
7116 go->SetLootState(GO_ACTIVATED);
7119 else if (IS_ITEM_GUID(guid))
7121 Item *item = GetItemByGuid( guid );
7123 if (!item)
7125 SendLootRelease(guid);
7126 return;
7129 if(loot_type == LOOT_DISENCHANTING)
7131 loot = &item->loot;
7133 if(!item->m_lootGenerated)
7135 item->m_lootGenerated = true;
7136 loot->clear();
7137 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7140 else if(loot_type == LOOT_PROSPECTING)
7142 loot = &item->loot;
7144 if(!item->m_lootGenerated)
7146 item->m_lootGenerated = true;
7147 loot->clear();
7148 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7151 else
7153 loot = &item->loot;
7155 if(!item->m_lootGenerated)
7157 item->m_lootGenerated = true;
7158 loot->clear();
7159 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7161 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7165 else if (IS_CORPSE_GUID(guid)) // remove insignia
7167 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7169 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7171 SendLootRelease(guid);
7172 return;
7175 loot = &bones->loot;
7177 if (!bones->lootForBody)
7179 bones->lootForBody = true;
7180 uint32 pLevel = bones->loot.gold;
7181 bones->loot.clear();
7182 // It may need a better formula
7183 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7184 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7187 if (bones->lootRecipient != this)
7188 permission = NONE_PERMISSION;
7190 else
7192 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7194 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7195 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7197 SendLootRelease(guid);
7198 return;
7201 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7203 SendLootRelease(guid);
7204 return;
7207 loot = &creature->loot;
7209 if(loot_type == LOOT_PICKPOCKETING)
7211 if ( !creature->lootForPickPocketed )
7213 creature->lootForPickPocketed = true;
7214 loot->clear();
7216 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7217 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7219 // Generate extra money for pick pocket loot
7220 const uint32 a = urand(0, creature->getLevel()/2);
7221 const uint32 b = urand(0, getLevel()/2);
7222 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7225 else
7227 // the player whose group may loot the corpse
7228 Player *recipient = creature->GetLootRecipient();
7229 if (!recipient)
7231 creature->SetLootRecipient(this);
7232 recipient = this;
7235 if (creature->lootForPickPocketed)
7237 creature->lootForPickPocketed = false;
7238 loot->clear();
7241 if(!creature->lootForBody)
7243 creature->lootForBody = true;
7244 loot->clear();
7246 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7247 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7249 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7251 if(Group* group = recipient->GetGroup())
7253 group->UpdateLooterGuid(creature,true);
7255 switch (group->GetLootMethod())
7257 case GROUP_LOOT:
7258 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7259 group->GroupLoot(recipient->GetGUID(), loot, creature);
7260 break;
7261 case NEED_BEFORE_GREED:
7262 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7263 break;
7264 case MASTER_LOOT:
7265 group->MasterLoot(recipient->GetGUID(), loot, creature);
7266 break;
7267 default:
7268 break;
7273 // possible only if creature->lootForBody && loot->empty() at spell cast check
7274 if (loot_type == LOOT_SKINNING)
7276 loot->clear();
7277 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7279 // set group rights only for loot_type != LOOT_SKINNING
7280 else
7282 if(Group* group = GetGroup())
7284 if( group == recipient->GetGroup() )
7286 if(group->GetLootMethod() == FREE_FOR_ALL)
7287 permission = ALL_PERMISSION;
7288 else if(group->GetLooterGuid() == GetGUID())
7290 if(group->GetLootMethod() == MASTER_LOOT)
7291 permission = MASTER_PERMISSION;
7292 else
7293 permission = ALL_PERMISSION;
7295 else
7296 permission = GROUP_PERMISSION;
7298 else
7299 permission = NONE_PERMISSION;
7301 else if(recipient == this)
7302 permission = ALL_PERMISSION;
7303 else
7304 permission = NONE_PERMISSION;
7309 SetLootGUID(guid);
7311 QuestItemList *q_list = 0;
7312 if (permission != NONE_PERMISSION)
7314 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7315 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7316 if (itr == lootPlayerQuestItems.end())
7317 q_list = loot->FillQuestLoot(this);
7318 else
7319 q_list = itr->second;
7322 QuestItemList *ffa_list = 0;
7323 if (permission != NONE_PERMISSION)
7325 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7326 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7327 if (itr == lootPlayerFFAItems.end())
7328 ffa_list = loot->FillFFALoot(this);
7329 else
7330 ffa_list = itr->second;
7333 QuestItemList *conditional_list = 0;
7334 if (permission != NONE_PERMISSION)
7336 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7337 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7338 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7339 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7340 else
7341 conditional_list = itr->second;
7344 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7345 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7346 loot_type = LOOT_SKINNING;
7348 if(loot_type == LOOT_FISHINGHOLE)
7349 loot_type = LOOT_FISHING;
7351 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7353 data << uint64(guid);
7354 data << uint8(loot_type);
7355 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7357 SendDirectMessage(&data);
7359 // add 'this' player as one of the players that are looting 'loot'
7360 if (permission != NONE_PERMISSION)
7361 loot->AddLooter(GetGUID());
7363 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7364 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7367 void Player::SendNotifyLootMoneyRemoved()
7369 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7370 GetSession()->SendPacket( &data );
7373 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7375 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7376 data << uint8(lootSlot);
7377 GetSession()->SendPacket( &data );
7380 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7382 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7383 data << Field;
7384 data << Value;
7385 GetSession()->SendPacket(&data);
7388 void Player::SendInitWorldStates()
7390 // data depends on zoneid/mapid...
7391 BattleGround* bg = GetBattleGround();
7392 uint16 NumberOfFields = 0;
7393 uint32 mapid = GetMapId();
7394 uint32 zoneid = GetZoneId();
7395 uint32 areaid = GetAreaId();
7396 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7397 // may be exist better way to do this...
7398 switch(zoneid)
7400 case 0:
7401 case 1:
7402 case 4:
7403 case 8:
7404 case 10:
7405 case 11:
7406 case 12:
7407 case 36:
7408 case 38:
7409 case 40:
7410 case 41:
7411 case 51:
7412 case 267:
7413 case 1519:
7414 case 1537:
7415 case 2257:
7416 case 2918:
7417 NumberOfFields = 6;
7418 break;
7419 case 2597:
7420 NumberOfFields = 81;
7421 break;
7422 case 3277:
7423 NumberOfFields = 14;
7424 break;
7425 case 3358:
7426 case 3820:
7427 NumberOfFields = 38;
7428 break;
7429 case 3483:
7430 NumberOfFields = 22;
7431 break;
7432 case 3519:
7433 NumberOfFields = 36;
7434 break;
7435 case 3521:
7436 NumberOfFields = 35;
7437 break;
7438 case 3698:
7439 case 3702:
7440 case 3968:
7441 NumberOfFields = 9;
7442 break;
7443 case 3703:
7444 NumberOfFields = 9;
7445 break;
7446 default:
7447 NumberOfFields = 10;
7448 break;
7451 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7452 data << uint32(mapid); // mapid
7453 data << uint32(zoneid); // zone id
7454 data << uint32(areaid); // area id, new 2.1.0
7455 data << uint16(NumberOfFields); // count of uint64 blocks
7456 data << uint32(0x8d8) << uint32(0x0); // 1
7457 data << uint32(0x8d7) << uint32(0x0); // 2
7458 data << uint32(0x8d6) << uint32(0x0); // 3
7459 data << uint32(0x8d5) << uint32(0x0); // 4
7460 data << uint32(0x8d4) << uint32(0x0); // 5
7461 data << uint32(0x8d3) << uint32(0x0); // 6
7462 if(mapid == 530) // Outland
7464 data << uint32(0x9bf) << uint32(0x0); // 7
7465 data << uint32(0x9bd) << uint32(0xF); // 8
7466 data << uint32(0x9bb) << uint32(0xF); // 9
7468 switch(zoneid)
7470 case 1:
7471 case 11:
7472 case 12:
7473 case 38:
7474 case 40:
7475 case 51:
7476 case 1519:
7477 case 1537:
7478 case 2257:
7479 break;
7480 case 2597: // AV
7481 data << uint32(0x7ae) << uint32(0x1); // 7
7482 data << uint32(0x532) << uint32(0x1); // 8
7483 data << uint32(0x531) << uint32(0x0); // 9
7484 data << uint32(0x52e) << uint32(0x0); // 10
7485 data << uint32(0x571) << uint32(0x0); // 11
7486 data << uint32(0x570) << uint32(0x0); // 12
7487 data << uint32(0x567) << uint32(0x1); // 13
7488 data << uint32(0x566) << uint32(0x1); // 14
7489 data << uint32(0x550) << uint32(0x1); // 15
7490 data << uint32(0x544) << uint32(0x0); // 16
7491 data << uint32(0x536) << uint32(0x0); // 17
7492 data << uint32(0x535) << uint32(0x1); // 18
7493 data << uint32(0x518) << uint32(0x0); // 19
7494 data << uint32(0x517) << uint32(0x0); // 20
7495 data << uint32(0x574) << uint32(0x0); // 21
7496 data << uint32(0x573) << uint32(0x0); // 22
7497 data << uint32(0x572) << uint32(0x0); // 23
7498 data << uint32(0x56f) << uint32(0x0); // 24
7499 data << uint32(0x56e) << uint32(0x0); // 25
7500 data << uint32(0x56d) << uint32(0x0); // 26
7501 data << uint32(0x56c) << uint32(0x0); // 27
7502 data << uint32(0x56b) << uint32(0x0); // 28
7503 data << uint32(0x56a) << uint32(0x1); // 29
7504 data << uint32(0x569) << uint32(0x1); // 30
7505 data << uint32(0x568) << uint32(0x1); // 13
7506 data << uint32(0x565) << uint32(0x0); // 32
7507 data << uint32(0x564) << uint32(0x0); // 33
7508 data << uint32(0x563) << uint32(0x0); // 34
7509 data << uint32(0x562) << uint32(0x0); // 35
7510 data << uint32(0x561) << uint32(0x0); // 36
7511 data << uint32(0x560) << uint32(0x0); // 37
7512 data << uint32(0x55f) << uint32(0x0); // 38
7513 data << uint32(0x55e) << uint32(0x0); // 39
7514 data << uint32(0x55d) << uint32(0x0); // 40
7515 data << uint32(0x3c6) << uint32(0x4); // 41
7516 data << uint32(0x3c4) << uint32(0x6); // 42
7517 data << uint32(0x3c2) << uint32(0x4); // 43
7518 data << uint32(0x516) << uint32(0x1); // 44
7519 data << uint32(0x515) << uint32(0x0); // 45
7520 data << uint32(0x3b6) << uint32(0x6); // 46
7521 data << uint32(0x55c) << uint32(0x0); // 47
7522 data << uint32(0x55b) << uint32(0x0); // 48
7523 data << uint32(0x55a) << uint32(0x0); // 49
7524 data << uint32(0x559) << uint32(0x0); // 50
7525 data << uint32(0x558) << uint32(0x0); // 51
7526 data << uint32(0x557) << uint32(0x0); // 52
7527 data << uint32(0x556) << uint32(0x0); // 53
7528 data << uint32(0x555) << uint32(0x0); // 54
7529 data << uint32(0x554) << uint32(0x1); // 55
7530 data << uint32(0x553) << uint32(0x1); // 56
7531 data << uint32(0x552) << uint32(0x1); // 57
7532 data << uint32(0x551) << uint32(0x1); // 58
7533 data << uint32(0x54f) << uint32(0x0); // 59
7534 data << uint32(0x54e) << uint32(0x0); // 60
7535 data << uint32(0x54d) << uint32(0x1); // 61
7536 data << uint32(0x54c) << uint32(0x0); // 62
7537 data << uint32(0x54b) << uint32(0x0); // 63
7538 data << uint32(0x545) << uint32(0x0); // 64
7539 data << uint32(0x543) << uint32(0x1); // 65
7540 data << uint32(0x542) << uint32(0x0); // 66
7541 data << uint32(0x540) << uint32(0x0); // 67
7542 data << uint32(0x53f) << uint32(0x0); // 68
7543 data << uint32(0x53e) << uint32(0x0); // 69
7544 data << uint32(0x53d) << uint32(0x0); // 70
7545 data << uint32(0x53c) << uint32(0x0); // 71
7546 data << uint32(0x53b) << uint32(0x0); // 72
7547 data << uint32(0x53a) << uint32(0x1); // 73
7548 data << uint32(0x539) << uint32(0x0); // 74
7549 data << uint32(0x538) << uint32(0x0); // 75
7550 data << uint32(0x537) << uint32(0x0); // 76
7551 data << uint32(0x534) << uint32(0x0); // 77
7552 data << uint32(0x533) << uint32(0x0); // 78
7553 data << uint32(0x530) << uint32(0x0); // 79
7554 data << uint32(0x52f) << uint32(0x0); // 80
7555 data << uint32(0x52d) << uint32(0x1); // 81
7556 break;
7557 case 3277: // WS
7558 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7559 bg->FillInitialWorldStates(data);
7560 else
7562 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7563 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7564 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7565 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7566 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7567 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7568 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7569 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7571 break;
7572 case 3358: // AB
7573 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7574 bg->FillInitialWorldStates(data);
7575 else
7577 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7578 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7579 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7580 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7581 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7582 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7583 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7584 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7585 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7586 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7587 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7588 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7589 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7590 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7591 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7592 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7593 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7594 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7595 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7596 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7597 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7598 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7599 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7600 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7601 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7602 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7603 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7604 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7605 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7606 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7607 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7608 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7610 break;
7611 case 3820: // EY
7612 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7613 bg->FillInitialWorldStates(data);
7614 else
7616 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7617 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7618 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7619 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7620 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7621 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7622 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7623 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7624 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7625 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7626 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7627 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7628 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7629 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7630 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7631 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7632 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7633 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7634 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7635 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7636 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7637 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7638 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7639 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7640 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7641 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7642 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7643 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7644 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7645 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7646 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7647 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7648 // and some more ... unknown
7650 break;
7651 case 3483: // Hellfire Peninsula
7652 data << uint32(0x9ba) << uint32(0x1); // 10
7653 data << uint32(0x9b9) << uint32(0x1); // 11
7654 data << uint32(0x9b5) << uint32(0x0); // 12
7655 data << uint32(0x9b4) << uint32(0x1); // 13
7656 data << uint32(0x9b3) << uint32(0x0); // 14
7657 data << uint32(0x9b2) << uint32(0x0); // 15
7658 data << uint32(0x9b1) << uint32(0x1); // 16
7659 data << uint32(0x9b0) << uint32(0x0); // 17
7660 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7661 data << uint32(0x9ac) << uint32(0x0); // 19
7662 data << uint32(0x9a8) << uint32(0x0); // 20
7663 data << uint32(0x9a7) << uint32(0x0); // 21
7664 data << uint32(0x9a6) << uint32(0x1); // 22
7665 break;
7666 case 3519: // Terokkar Forest
7667 data << uint32(0xa41) << uint32(0x0); // 10
7668 data << uint32(0xa40) << uint32(0x14); // 11
7669 data << uint32(0xa3f) << uint32(0x0); // 12
7670 data << uint32(0xa3e) << uint32(0x0); // 13
7671 data << uint32(0xa3d) << uint32(0x5); // 14
7672 data << uint32(0xa3c) << uint32(0x0); // 15
7673 data << uint32(0xa87) << uint32(0x0); // 16
7674 data << uint32(0xa86) << uint32(0x0); // 17
7675 data << uint32(0xa85) << uint32(0x0); // 18
7676 data << uint32(0xa84) << uint32(0x0); // 19
7677 data << uint32(0xa83) << uint32(0x0); // 20
7678 data << uint32(0xa82) << uint32(0x0); // 21
7679 data << uint32(0xa81) << uint32(0x0); // 22
7680 data << uint32(0xa80) << uint32(0x0); // 23
7681 data << uint32(0xa7e) << uint32(0x0); // 24
7682 data << uint32(0xa7d) << uint32(0x0); // 25
7683 data << uint32(0xa7c) << uint32(0x0); // 26
7684 data << uint32(0xa7b) << uint32(0x0); // 27
7685 data << uint32(0xa7a) << uint32(0x0); // 28
7686 data << uint32(0xa79) << uint32(0x0); // 29
7687 data << uint32(0x9d0) << uint32(0x5); // 30
7688 data << uint32(0x9ce) << uint32(0x0); // 31
7689 data << uint32(0x9cd) << uint32(0x0); // 32
7690 data << uint32(0x9cc) << uint32(0x0); // 33
7691 data << uint32(0xa88) << uint32(0x0); // 34
7692 data << uint32(0xad0) << uint32(0x0); // 35
7693 data << uint32(0xacf) << uint32(0x1); // 36
7694 break;
7695 case 3521: // Zangarmarsh
7696 data << uint32(0x9e1) << uint32(0x0); // 10
7697 data << uint32(0x9e0) << uint32(0x0); // 11
7698 data << uint32(0x9df) << uint32(0x0); // 12
7699 data << uint32(0xa5d) << uint32(0x1); // 13
7700 data << uint32(0xa5c) << uint32(0x0); // 14
7701 data << uint32(0xa5b) << uint32(0x1); // 15
7702 data << uint32(0xa5a) << uint32(0x0); // 16
7703 data << uint32(0xa59) << uint32(0x1); // 17
7704 data << uint32(0xa58) << uint32(0x0); // 18
7705 data << uint32(0xa57) << uint32(0x0); // 19
7706 data << uint32(0xa56) << uint32(0x0); // 20
7707 data << uint32(0xa55) << uint32(0x1); // 21
7708 data << uint32(0xa54) << uint32(0x0); // 22
7709 data << uint32(0x9e7) << uint32(0x0); // 23
7710 data << uint32(0x9e6) << uint32(0x0); // 24
7711 data << uint32(0x9e5) << uint32(0x0); // 25
7712 data << uint32(0xa00) << uint32(0x0); // 26
7713 data << uint32(0x9ff) << uint32(0x1); // 27
7714 data << uint32(0x9fe) << uint32(0x0); // 28
7715 data << uint32(0x9fd) << uint32(0x0); // 29
7716 data << uint32(0x9fc) << uint32(0x1); // 30
7717 data << uint32(0x9fb) << uint32(0x0); // 31
7718 data << uint32(0xa62) << uint32(0x0); // 32
7719 data << uint32(0xa61) << uint32(0x1); // 33
7720 data << uint32(0xa60) << uint32(0x1); // 34
7721 data << uint32(0xa5f) << uint32(0x0); // 35
7722 break;
7723 case 3698: // Nagrand Arena
7724 data << uint32(0xa0f) << uint32(0x0); // 7
7725 data << uint32(0xa10) << uint32(0x0); // 8
7726 data << uint32(0xa11) << uint32(0x0); // 9
7727 break;
7728 case 3702: // Blade's Edge Arena
7729 data << uint32(0x9f0) << uint32(0x0); // 7
7730 data << uint32(0x9f1) << uint32(0x0); // 8
7731 data << uint32(0x9f3) << uint32(0x0); // 9
7732 break;
7733 case 3968: // Ruins of Lordaeron
7734 data << uint32(0xbb8) << uint32(0x0); // 7
7735 data << uint32(0xbb9) << uint32(0x0); // 8
7736 data << uint32(0xbba) << uint32(0x0); // 9
7737 break;
7738 case 3703: // Shattrath City
7739 break;
7740 default:
7741 data << uint32(0x914) << uint32(0x0); // 7
7742 data << uint32(0x913) << uint32(0x0); // 8
7743 data << uint32(0x912) << uint32(0x0); // 9
7744 data << uint32(0x915) << uint32(0x0); // 10
7745 break;
7747 GetSession()->SendPacket(&data);
7750 uint32 Player::GetXPRestBonus(uint32 xp)
7752 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7754 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7755 rested_bonus = xp;
7757 SetRestBonus( GetRestBonus() - rested_bonus);
7759 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7760 return rested_bonus;
7763 void Player::SetBindPoint(uint64 guid)
7765 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7766 data << uint64(guid);
7767 GetSession()->SendPacket( &data );
7770 void Player::SendTalentWipeConfirm(uint64 guid)
7772 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7773 data << uint64(guid);
7774 data << uint32(resetTalentsCost());
7775 GetSession()->SendPacket( &data );
7778 void Player::SendPetSkillWipeConfirm()
7780 Pet* pet = GetPet();
7781 if(!pet)
7782 return;
7783 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7784 data << pet->GetGUID();
7785 data << uint32(pet->resetTalentsCost());
7786 GetSession()->SendPacket( &data );
7789 /*********************************************************/
7790 /*** STORAGE SYSTEM ***/
7791 /*********************************************************/
7793 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7795 assert(i < 3);
7796 if(i < 2 && item)
7798 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7799 return;
7800 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7801 if(charges == 0)
7802 return;
7803 if(charges > 1)
7804 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7805 else if(charges <= 1)
7807 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7808 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7813 void Player::SetSheath( uint32 sheathed )
7815 switch (sheathed)
7817 case SHEATH_STATE_UNARMED: // no prepared weapon
7818 SetVirtualItemSlot(0,NULL);
7819 SetVirtualItemSlot(1,NULL);
7820 SetVirtualItemSlot(2,NULL);
7821 break;
7822 case SHEATH_STATE_MELEE: // prepared melee weapon
7824 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7825 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7826 SetVirtualItemSlot(2,NULL);
7827 }; break;
7828 case SHEATH_STATE_RANGED: // prepared ranged weapon
7829 SetVirtualItemSlot(0,NULL);
7830 SetVirtualItemSlot(1,NULL);
7831 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7832 break;
7833 default:
7834 SetVirtualItemSlot(0,NULL);
7835 SetVirtualItemSlot(1,NULL);
7836 SetVirtualItemSlot(2,NULL);
7837 break;
7839 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7842 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7844 uint8 pClass = getClass();
7846 uint8 slots[4];
7847 slots[0] = NULL_SLOT;
7848 slots[1] = NULL_SLOT;
7849 slots[2] = NULL_SLOT;
7850 slots[3] = NULL_SLOT;
7851 switch( proto->InventoryType )
7853 case INVTYPE_HEAD:
7854 slots[0] = EQUIPMENT_SLOT_HEAD;
7855 break;
7856 case INVTYPE_NECK:
7857 slots[0] = EQUIPMENT_SLOT_NECK;
7858 break;
7859 case INVTYPE_SHOULDERS:
7860 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7861 break;
7862 case INVTYPE_BODY:
7863 slots[0] = EQUIPMENT_SLOT_BODY;
7864 break;
7865 case INVTYPE_CHEST:
7866 slots[0] = EQUIPMENT_SLOT_CHEST;
7867 break;
7868 case INVTYPE_ROBE:
7869 slots[0] = EQUIPMENT_SLOT_CHEST;
7870 break;
7871 case INVTYPE_WAIST:
7872 slots[0] = EQUIPMENT_SLOT_WAIST;
7873 break;
7874 case INVTYPE_LEGS:
7875 slots[0] = EQUIPMENT_SLOT_LEGS;
7876 break;
7877 case INVTYPE_FEET:
7878 slots[0] = EQUIPMENT_SLOT_FEET;
7879 break;
7880 case INVTYPE_WRISTS:
7881 slots[0] = EQUIPMENT_SLOT_WRISTS;
7882 break;
7883 case INVTYPE_HANDS:
7884 slots[0] = EQUIPMENT_SLOT_HANDS;
7885 break;
7886 case INVTYPE_FINGER:
7887 slots[0] = EQUIPMENT_SLOT_FINGER1;
7888 slots[1] = EQUIPMENT_SLOT_FINGER2;
7889 break;
7890 case INVTYPE_TRINKET:
7891 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7892 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7893 break;
7894 case INVTYPE_CLOAK:
7895 slots[0] = EQUIPMENT_SLOT_BACK;
7896 break;
7897 case INVTYPE_WEAPON:
7899 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7901 // suggest offhand slot only if know dual wielding
7902 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7903 if(CanDualWield())
7904 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7905 };break;
7906 case INVTYPE_SHIELD:
7907 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7908 break;
7909 case INVTYPE_RANGED:
7910 slots[0] = EQUIPMENT_SLOT_RANGED;
7911 break;
7912 case INVTYPE_2HWEAPON:
7913 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7914 break;
7915 case INVTYPE_TABARD:
7916 slots[0] = EQUIPMENT_SLOT_TABARD;
7917 break;
7918 case INVTYPE_WEAPONMAINHAND:
7919 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7920 break;
7921 case INVTYPE_WEAPONOFFHAND:
7922 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7923 break;
7924 case INVTYPE_HOLDABLE:
7925 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7926 break;
7927 case INVTYPE_THROWN:
7928 slots[0] = EQUIPMENT_SLOT_RANGED;
7929 break;
7930 case INVTYPE_RANGEDRIGHT:
7931 slots[0] = EQUIPMENT_SLOT_RANGED;
7932 break;
7933 case INVTYPE_BAG:
7934 slots[0] = INVENTORY_SLOT_BAG_1;
7935 slots[1] = INVENTORY_SLOT_BAG_2;
7936 slots[2] = INVENTORY_SLOT_BAG_3;
7937 slots[3] = INVENTORY_SLOT_BAG_4;
7938 break;
7939 case INVTYPE_RELIC:
7941 switch(proto->SubClass)
7943 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7944 if (pClass == CLASS_PALADIN)
7945 slots[0] = EQUIPMENT_SLOT_RANGED;
7946 break;
7947 case ITEM_SUBCLASS_ARMOR_IDOL:
7948 if (pClass == CLASS_DRUID)
7949 slots[0] = EQUIPMENT_SLOT_RANGED;
7950 break;
7951 case ITEM_SUBCLASS_ARMOR_TOTEM:
7952 if (pClass == CLASS_SHAMAN)
7953 slots[0] = EQUIPMENT_SLOT_RANGED;
7954 break;
7955 case ITEM_SUBCLASS_ARMOR_MISC:
7956 if (pClass == CLASS_WARLOCK)
7957 slots[0] = EQUIPMENT_SLOT_RANGED;
7958 break;
7960 break;
7962 default :
7963 return NULL_SLOT;
7966 if( slot != NULL_SLOT )
7968 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7970 for (int i = 0; i < 4; i++)
7972 if ( slots[i] == slot )
7973 return slot;
7977 else
7979 // search free slot at first
7980 for (int i = 0; i < 4; i++)
7982 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7984 // in case 2hand equipped weapon offhand slot empty but not free
7985 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7987 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7988 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7989 return slots[i];
7991 else
7992 return slots[i];
7996 // if not found free and can swap return first appropriate from used
7997 for (int i = 0; i < 4; i++)
7999 if ( slots[i] != NULL_SLOT && swap )
8000 return slots[i];
8004 // no free position
8005 return NULL_SLOT;
8008 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8010 Item *pItem;
8011 uint32 tempcount = 0;
8013 uint8 res = EQUIP_ERR_OK;
8015 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8017 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8018 if( pItem && pItem->GetEntry() == item )
8020 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8021 if(ires==EQUIP_ERR_OK)
8023 tempcount += pItem->GetCount();
8024 if( tempcount >= count )
8025 return EQUIP_ERR_OK;
8027 else
8028 res = ires;
8031 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8033 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8034 if( pItem && pItem->GetEntry() == item )
8036 tempcount += pItem->GetCount();
8037 if( tempcount >= count )
8038 return EQUIP_ERR_OK;
8041 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8043 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8044 if( pItem && pItem->GetEntry() == item )
8046 tempcount += pItem->GetCount();
8047 if( tempcount >= count )
8048 return EQUIP_ERR_OK;
8051 Bag *pBag;
8052 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8054 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8055 if( pBag )
8057 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8059 pItem = GetItemByPos( i, j );
8060 if( pItem && pItem->GetEntry() == item )
8062 tempcount += pItem->GetCount();
8063 if( tempcount >= count )
8064 return EQUIP_ERR_OK;
8070 // not found req. item count and have unequippable items
8071 return res;
8074 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8076 uint32 count = 0;
8077 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8079 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8080 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8081 count += pItem->GetCount();
8083 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8085 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8086 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8087 count += pItem->GetCount();
8089 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8091 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8092 if( pBag )
8093 count += pBag->GetItemCount(item,skipItem);
8096 if(skipItem && skipItem->GetProto()->GemProperties)
8098 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8100 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8101 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8102 count += pItem->GetGemCountWithID(item);
8106 if(inBankAlso)
8108 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8110 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8111 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8112 count += pItem->GetCount();
8114 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8116 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8117 if( pBag )
8118 count += pBag->GetItemCount(item,skipItem);
8121 if(skipItem && skipItem->GetProto()->GemProperties)
8123 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8125 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8126 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8127 count += pItem->GetGemCountWithID(item);
8132 return count;
8135 Item* Player::GetItemByGuid( uint64 guid ) const
8137 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8139 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8140 if( pItem && pItem->GetGUID() == guid )
8141 return pItem;
8143 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8145 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8146 if( pItem && pItem->GetGUID() == guid )
8147 return pItem;
8150 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8152 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8153 if( pBag )
8155 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8157 Item* pItem = pBag->GetItemByPos( j );
8158 if( pItem && pItem->GetGUID() == guid )
8159 return pItem;
8163 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8165 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8166 if( pBag )
8168 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8170 Item* pItem = pBag->GetItemByPos( j );
8171 if( pItem && pItem->GetGUID() == guid )
8172 return pItem;
8177 return NULL;
8180 Item* Player::GetItemByPos( uint16 pos ) const
8182 uint8 bag = pos >> 8;
8183 uint8 slot = pos & 255;
8184 return GetItemByPos( bag, slot );
8187 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8189 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8190 return m_items[slot];
8191 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8192 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8194 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8195 if ( pBag )
8196 return pBag->GetItemByPos(slot);
8198 return NULL;
8201 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8203 uint16 slot;
8204 switch (attackType)
8206 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8207 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8208 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8209 default: return NULL;
8212 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8213 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8214 return NULL;
8216 if(!useable)
8217 return item;
8219 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8220 return NULL;
8222 return item;
8225 Item* Player::GetShield(bool useable) const
8227 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8228 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8229 return NULL;
8231 if(!useable)
8232 return item;
8234 if( item->IsBroken())
8235 return NULL;
8237 return item;
8240 uint32 Player::GetAttackBySlot( uint8 slot )
8242 switch(slot)
8244 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8245 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8246 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8247 default: return MAX_ATTACK;
8251 bool Player::HasBankBagSlot( uint8 slot ) const
8253 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8254 if( slot < maxslot )
8255 return true;
8256 return false;
8259 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8261 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8262 return true;
8263 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8264 return true;
8265 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8266 return true;
8267 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8268 return true;
8269 return false;
8272 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8274 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8275 return true;
8276 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8277 return true;
8278 return false;
8281 bool Player::IsBankPos( uint8 bag, uint8 slot )
8283 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8284 return true;
8285 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8286 return true;
8287 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8288 return true;
8289 return false;
8292 bool Player::IsBagPos( uint16 pos )
8294 uint8 bag = pos >> 8;
8295 uint8 slot = pos & 255;
8296 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8297 return true;
8298 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8299 return true;
8300 return false;
8303 bool Player::IsValidPos( uint8 bag, uint8 slot )
8305 // post selected
8306 if(bag == NULL_BAG)
8307 return true;
8309 if (bag == INVENTORY_SLOT_BAG_0)
8311 // any post selected
8312 if (slot == NULL_SLOT)
8313 return true;
8315 // equipment
8316 if (slot < EQUIPMENT_SLOT_END)
8317 return true;
8319 // bag equip slots
8320 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8321 return true;
8323 // backpack slots
8324 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8325 return true;
8327 // keyring slots
8328 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8329 return true;
8331 // bank main slots
8332 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8333 return true;
8335 // bank bag slots
8336 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8337 return true;
8339 return false;
8342 // bag content slots
8343 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8345 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8346 if(!pBag)
8347 return false;
8349 // any post selected
8350 if (slot == NULL_SLOT)
8351 return true;
8353 return slot < pBag->GetBagSize();
8356 // bank bag content slots
8357 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8359 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8360 if(!pBag)
8361 return false;
8363 // any post selected
8364 if (slot == NULL_SLOT)
8365 return true;
8367 return slot < pBag->GetBagSize();
8370 // where this?
8371 return false;
8375 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8377 uint32 tempcount = 0;
8378 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8380 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8381 if( pItem && pItem->GetEntry() == item )
8383 tempcount += pItem->GetCount();
8384 if( tempcount >= count )
8385 return true;
8388 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8390 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8391 if( pItem && pItem->GetEntry() == item )
8393 tempcount += pItem->GetCount();
8394 if( tempcount >= count )
8395 return true;
8398 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8400 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8402 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8404 Item* pItem = GetItemByPos( i, j );
8405 if( pItem && pItem->GetEntry() == item )
8407 tempcount += pItem->GetCount();
8408 if( tempcount >= count )
8409 return true;
8415 if(inBankAlso)
8417 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8419 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8420 if( pItem && pItem->GetEntry() == item )
8422 tempcount += pItem->GetCount();
8423 if( tempcount >= count )
8424 return true;
8427 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8429 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8431 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8433 Item* pItem = GetItemByPos( i, j );
8434 if( pItem && pItem->GetEntry() == item )
8436 tempcount += pItem->GetCount();
8437 if( tempcount >= count )
8438 return true;
8445 return false;
8448 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8450 Item *pItem;
8451 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8453 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8454 if( pItem && pItem->GetEntry() == item )
8455 return pItem;
8458 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8459 if (pProto && pProto->GemProperties)
8461 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8463 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8464 if( pItem && pItem->GetProto()->Socket[0].Color )
8466 if (pItem->GetGemCountWithID(item) > 0 )
8467 return pItem;
8472 return NULL;
8475 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8477 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8478 if( !pProto )
8480 if(no_space_count)
8481 *no_space_count = count;
8482 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8485 // no maximum
8486 if(pProto->MaxCount == 0)
8487 return EQUIP_ERR_OK;
8489 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8491 if( curcount + count > pProto->MaxCount )
8493 if(no_space_count)
8494 *no_space_count = count +curcount - pProto->MaxCount;
8495 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8498 return EQUIP_ERR_OK;
8501 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8503 Item *pItem;
8504 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8506 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8507 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8508 return true;
8510 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8512 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8513 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8514 return true;
8516 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8518 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8520 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8522 pItem = GetItemByPos( i, j );
8523 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8524 return true;
8528 return false;
8531 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8533 Item* pItem2 = GetItemByPos( bag, slot );
8535 // ignore move item (this slot will be empty at move)
8536 if(pItem2==pSrcItem)
8537 pItem2 = NULL;
8539 uint32 need_space;
8541 // empty specific slot - check item fit to slot
8542 if( !pItem2 || swap )
8544 if( bag == INVENTORY_SLOT_BAG_0 )
8546 // keyring case
8547 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8548 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8550 // vanitypet case
8551 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS))
8552 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8554 // currencytoken case
8555 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8556 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8558 // guestbag case
8559 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS))
8560 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8562 // prevent cheating
8563 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8564 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8566 else
8568 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8569 if( !pBag )
8570 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8572 ItemPrototype const* pBagProto = pBag->GetProto();
8573 if( !pBagProto )
8574 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8576 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8577 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8580 // non empty stack with space
8581 need_space = pProto->Stackable;
8583 // non empty slot, check item type
8584 else
8586 // check item type
8587 if(pItem2->GetEntry() != pProto->ItemId)
8588 return EQUIP_ERR_ITEM_CANT_STACK;
8590 // check free space
8591 if(pItem2->GetCount() >= pProto->Stackable)
8592 return EQUIP_ERR_ITEM_CANT_STACK;
8594 need_space = pProto->Stackable - pItem2->GetCount();
8597 if(need_space > count)
8598 need_space = count;
8600 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8601 if(!newPosition.isContainedIn(dest))
8603 dest.push_back(newPosition);
8604 count -= need_space;
8606 return EQUIP_ERR_OK;
8609 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
8611 // skip specific bag already processed in first called _CanStoreItem_InBag
8612 if(bag==skip_bag)
8613 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8615 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8616 if( !pBag )
8617 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8619 ItemPrototype const* pBagProto = pBag->GetProto();
8620 if( !pBagProto )
8621 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8623 // specialized bag mode or non-specilized
8624 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8625 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8627 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8628 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8630 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8632 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8633 if(j==skip_slot)
8634 continue;
8636 Item* pItem2 = GetItemByPos( bag, j );
8638 // ignore move item (this slot will be empty at move)
8639 if(pItem2==pSrcItem)
8640 pItem2 = NULL;
8642 // if merge skip empty, if !merge skip non-empty
8643 if((pItem2!=NULL)!=merge)
8644 continue;
8646 if( pItem2 )
8648 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8650 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8651 if(need_space > count)
8652 need_space = count;
8654 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8655 if(!newPosition.isContainedIn(dest))
8657 dest.push_back(newPosition);
8658 count -= need_space;
8660 if(count==0)
8661 return EQUIP_ERR_OK;
8665 else
8667 uint32 need_space = pProto->Stackable;
8668 if(need_space > count)
8669 need_space = count;
8671 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8672 if(!newPosition.isContainedIn(dest))
8674 dest.push_back(newPosition);
8675 count -= need_space;
8677 if(count==0)
8678 return EQUIP_ERR_OK;
8682 return EQUIP_ERR_OK;
8685 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
8687 for(uint32 j = slot_begin; j < slot_end; j++)
8689 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8690 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8691 continue;
8693 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8695 // ignore move item (this slot will be empty at move)
8696 if(pItem2==pSrcItem)
8697 pItem2 = NULL;
8699 // if merge skip empty, if !merge skip non-empty
8700 if((pItem2!=NULL)!=merge)
8701 continue;
8703 if( pItem2 )
8705 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8707 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8708 if(need_space > count)
8709 need_space = count;
8710 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8711 if(!newPosition.isContainedIn(dest))
8713 dest.push_back(newPosition);
8714 count -= need_space;
8716 if(count==0)
8717 return EQUIP_ERR_OK;
8721 else
8723 uint32 need_space = pProto->Stackable;
8724 if(need_space > count)
8725 need_space = count;
8727 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8728 if(!newPosition.isContainedIn(dest))
8730 dest.push_back(newPosition);
8731 count -= need_space;
8733 if(count==0)
8734 return EQUIP_ERR_OK;
8738 return EQUIP_ERR_OK;
8741 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8743 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8745 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8746 if( !pProto )
8748 if(no_space_count)
8749 *no_space_count = count;
8750 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8753 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8755 if(no_space_count)
8756 *no_space_count = count;
8757 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8760 // check count of items (skip for auto move for same player from bank)
8761 uint32 no_similar_count = 0; // can't store this amount similar items
8762 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8763 if(res!=EQUIP_ERR_OK)
8765 if(count==no_similar_count)
8767 if(no_space_count)
8768 *no_space_count = no_similar_count;
8769 return res;
8771 count -= no_similar_count;
8774 // in specific slot
8775 if( bag != NULL_BAG && slot != NULL_SLOT )
8777 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8778 if(res!=EQUIP_ERR_OK)
8780 if(no_space_count)
8781 *no_space_count = count + no_similar_count;
8782 return res;
8785 if(count==0)
8787 if(no_similar_count==0)
8788 return EQUIP_ERR_OK;
8790 if(no_space_count)
8791 *no_space_count = count + no_similar_count;
8792 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8796 // not specific slot or have space for partly store only in specific slot
8798 // in specific bag
8799 if( bag != NULL_BAG )
8801 // search stack in bag for merge to
8802 if( pProto->Stackable > 1 )
8804 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8806 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8807 if(res!=EQUIP_ERR_OK)
8809 if(no_space_count)
8810 *no_space_count = count + no_similar_count;
8811 return res;
8814 if(count==0)
8816 if(no_similar_count==0)
8817 return EQUIP_ERR_OK;
8819 if(no_space_count)
8820 *no_space_count = count + no_similar_count;
8821 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8824 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8825 if(res!=EQUIP_ERR_OK)
8827 if(no_space_count)
8828 *no_space_count = count + no_similar_count;
8829 return res;
8832 if(count==0)
8834 if(no_similar_count==0)
8835 return EQUIP_ERR_OK;
8837 if(no_space_count)
8838 *no_space_count = count + no_similar_count;
8839 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8842 else // equipped bag
8844 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8845 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8846 if(res!=EQUIP_ERR_OK)
8847 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8849 if(res!=EQUIP_ERR_OK)
8851 if(no_space_count)
8852 *no_space_count = count + no_similar_count;
8853 return res;
8856 if(count==0)
8858 if(no_similar_count==0)
8859 return EQUIP_ERR_OK;
8861 if(no_space_count)
8862 *no_space_count = count + no_similar_count;
8863 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8868 // search free slot in bag for place to
8869 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8871 // search free slot - keyring case
8872 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8874 uint32 keyringSize = GetMaxKeyringSize();
8875 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8876 if(res!=EQUIP_ERR_OK)
8878 if(no_space_count)
8879 *no_space_count = count + no_similar_count;
8880 return res;
8883 if(count==0)
8885 if(no_similar_count==0)
8886 return EQUIP_ERR_OK;
8888 if(no_space_count)
8889 *no_space_count = count + no_similar_count;
8890 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8893 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
8895 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8896 if(res!=EQUIP_ERR_OK)
8898 if(no_space_count)
8899 *no_space_count = count + no_similar_count;
8900 return res;
8903 if(count==0)
8905 if(no_similar_count==0)
8906 return EQUIP_ERR_OK;
8908 if(no_space_count)
8909 *no_space_count = count + no_similar_count;
8910 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8913 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8915 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8916 if(res!=EQUIP_ERR_OK)
8918 if(no_space_count)
8919 *no_space_count = count + no_similar_count;
8920 return res;
8923 if(count==0)
8925 if(no_similar_count==0)
8926 return EQUIP_ERR_OK;
8928 if(no_space_count)
8929 *no_space_count = count + no_similar_count;
8930 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8933 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
8935 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8936 if(res!=EQUIP_ERR_OK)
8938 if(no_space_count)
8939 *no_space_count = count + no_similar_count;
8940 return res;
8943 if(count==0)
8945 if(no_similar_count==0)
8946 return EQUIP_ERR_OK;
8948 if(no_space_count)
8949 *no_space_count = count + no_similar_count;
8950 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8954 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8955 if(res!=EQUIP_ERR_OK)
8957 if(no_space_count)
8958 *no_space_count = count + no_similar_count;
8959 return res;
8962 if(count==0)
8964 if(no_similar_count==0)
8965 return EQUIP_ERR_OK;
8967 if(no_space_count)
8968 *no_space_count = count + no_similar_count;
8969 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8972 else // equipped bag
8974 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8975 if(res!=EQUIP_ERR_OK)
8976 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8978 if(res!=EQUIP_ERR_OK)
8980 if(no_space_count)
8981 *no_space_count = count + no_similar_count;
8982 return res;
8985 if(count==0)
8987 if(no_similar_count==0)
8988 return EQUIP_ERR_OK;
8990 if(no_space_count)
8991 *no_space_count = count + no_similar_count;
8992 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8997 // not specific bag or have space for partly store only in specific bag
8999 // search stack for merge to
9000 if( pProto->Stackable > 1 )
9002 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9003 if(res!=EQUIP_ERR_OK)
9005 if(no_space_count)
9006 *no_space_count = count + no_similar_count;
9007 return res;
9010 if(count==0)
9012 if(no_similar_count==0)
9013 return EQUIP_ERR_OK;
9015 if(no_space_count)
9016 *no_space_count = count + no_similar_count;
9017 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9020 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9021 if(res!=EQUIP_ERR_OK)
9023 if(no_space_count)
9024 *no_space_count = count + no_similar_count;
9025 return res;
9028 if(count==0)
9030 if(no_similar_count==0)
9031 return EQUIP_ERR_OK;
9033 if(no_space_count)
9034 *no_space_count = count + no_similar_count;
9035 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9038 if( pProto->BagFamily )
9040 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9042 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9043 if(res!=EQUIP_ERR_OK)
9044 continue;
9046 if(count==0)
9048 if(no_similar_count==0)
9049 return EQUIP_ERR_OK;
9051 if(no_space_count)
9052 *no_space_count = count + no_similar_count;
9053 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9058 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9060 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9061 if(res!=EQUIP_ERR_OK)
9062 continue;
9064 if(count==0)
9066 if(no_similar_count==0)
9067 return EQUIP_ERR_OK;
9069 if(no_space_count)
9070 *no_space_count = count + no_similar_count;
9071 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9076 // search free slot - special bag case
9077 if( pProto->BagFamily )
9079 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9081 uint32 keyringSize = GetMaxKeyringSize();
9082 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9083 if(res!=EQUIP_ERR_OK)
9085 if(no_space_count)
9086 *no_space_count = count + no_similar_count;
9087 return res;
9090 if(count==0)
9092 if(no_similar_count==0)
9093 return EQUIP_ERR_OK;
9095 if(no_space_count)
9096 *no_space_count = count + no_similar_count;
9097 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9100 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9102 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9103 if(res!=EQUIP_ERR_OK)
9105 if(no_space_count)
9106 *no_space_count = count + no_similar_count;
9107 return res;
9110 if(count==0)
9112 if(no_similar_count==0)
9113 return EQUIP_ERR_OK;
9115 if(no_space_count)
9116 *no_space_count = count + no_similar_count;
9117 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9120 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9122 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9123 if(res!=EQUIP_ERR_OK)
9125 if(no_space_count)
9126 *no_space_count = count + no_similar_count;
9127 return res;
9130 if(count==0)
9132 if(no_similar_count==0)
9133 return EQUIP_ERR_OK;
9135 if(no_space_count)
9136 *no_space_count = count + no_similar_count;
9137 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9140 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9142 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9143 if(res!=EQUIP_ERR_OK)
9145 if(no_space_count)
9146 *no_space_count = count + no_similar_count;
9147 return res;
9150 if(count==0)
9152 if(no_similar_count==0)
9153 return EQUIP_ERR_OK;
9155 if(no_space_count)
9156 *no_space_count = count + no_similar_count;
9157 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9161 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9163 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9164 if(res!=EQUIP_ERR_OK)
9165 continue;
9167 if(count==0)
9169 if(no_similar_count==0)
9170 return EQUIP_ERR_OK;
9172 if(no_space_count)
9173 *no_space_count = count + no_similar_count;
9174 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9179 // search free slot
9180 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9181 if(res!=EQUIP_ERR_OK)
9183 if(no_space_count)
9184 *no_space_count = count + no_similar_count;
9185 return res;
9188 if(count==0)
9190 if(no_similar_count==0)
9191 return EQUIP_ERR_OK;
9193 if(no_space_count)
9194 *no_space_count = count + no_similar_count;
9195 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9198 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9200 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9201 if(res!=EQUIP_ERR_OK)
9202 continue;
9204 if(count==0)
9206 if(no_similar_count==0)
9207 return EQUIP_ERR_OK;
9209 if(no_space_count)
9210 *no_space_count = count + no_similar_count;
9211 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9215 if(no_space_count)
9216 *no_space_count = count + no_similar_count;
9218 return EQUIP_ERR_INVENTORY_FULL;
9221 //////////////////////////////////////////////////////////////////////////
9222 uint8 Player::CanStoreItems( Item **pItems,int count) const
9224 Item *pItem2;
9226 // fill space table
9227 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9228 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9229 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9230 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9231 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9232 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9234 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9235 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9236 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9237 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9238 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9239 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9241 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9243 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9245 if (pItem2 && !pItem2->IsInTrade())
9247 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9251 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9253 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9255 if (pItem2 && !pItem2->IsInTrade())
9257 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9261 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9263 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9265 if (pItem2 && !pItem2->IsInTrade())
9267 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9271 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9273 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9275 if (pItem2 && !pItem2->IsInTrade())
9277 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9281 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9283 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9285 if (pItem2 && !pItem2->IsInTrade())
9287 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9291 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9293 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9295 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9297 pItem2 = GetItemByPos( i, j );
9298 if (pItem2 && !pItem2->IsInTrade())
9300 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9306 // check free space for all items
9307 for (int k=0;k<count;k++)
9309 Item *pItem = pItems[k];
9311 // no item
9312 if (!pItem) continue;
9314 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9315 ItemPrototype const *pProto = pItem->GetProto();
9317 // strange item
9318 if( !pProto )
9319 return EQUIP_ERR_ITEM_NOT_FOUND;
9321 // item it 'bind'
9322 if(pItem->IsBindedNotWith(GetGUID()))
9323 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9325 Bag *pBag;
9326 ItemPrototype const *pBagProto;
9328 // item is 'one item only'
9329 uint8 res = CanTakeMoreSimilarItems(pItem);
9330 if(res != EQUIP_ERR_OK)
9331 return res;
9333 // search stack for merge to
9334 if( pProto->Stackable > 1 )
9336 bool b_found = false;
9338 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9340 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9341 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9343 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9344 b_found = true;
9345 break;
9348 if (b_found) continue;
9350 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9352 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9353 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9355 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9356 b_found = true;
9357 break;
9360 if (b_found) continue;
9362 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9364 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9365 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9367 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9368 b_found = true;
9369 break;
9372 if (b_found) continue;
9374 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9376 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9377 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9379 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9380 b_found = true;
9381 break;
9384 if (b_found) continue;
9386 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9388 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9389 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9391 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9392 b_found = true;
9393 break;
9396 if (b_found) continue;
9398 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9400 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9401 if( pBag )
9403 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9405 pItem2 = GetItemByPos( t, j );
9406 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9408 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9409 b_found = true;
9410 break;
9415 if (b_found) continue;
9418 // special bag case
9419 if( pProto->BagFamily )
9421 bool b_found = false;
9422 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9424 uint32 keyringSize = GetMaxKeyringSize();
9425 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9427 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9429 inv_keys[t-KEYRING_SLOT_START] = 1;
9430 b_found = true;
9431 break;
9436 if (b_found) continue;
9438 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9440 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9442 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9444 inv_pets[t-VANITYPET_SLOT_START] = 1;
9445 b_found = true;
9446 break;
9451 if (b_found) continue;
9453 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9455 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9457 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9459 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9460 b_found = true;
9461 break;
9466 if (b_found) continue;
9468 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9470 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9472 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9474 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9475 b_found = true;
9476 break;
9481 if (b_found) continue;
9483 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9485 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9486 if( pBag )
9488 pBagProto = pBag->GetProto();
9490 // not plain container check
9491 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9492 ItemCanGoIntoBag(pProto,pBagProto) )
9494 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9496 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9498 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9499 b_found = true;
9500 break;
9506 if (b_found) continue;
9509 // search free slot
9510 bool b_found = false;
9511 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9513 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9515 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9516 b_found = true;
9517 break;
9520 if (b_found) continue;
9522 // search free slot in bags
9523 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9525 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9526 if( pBag )
9528 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9530 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9532 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9533 b_found = true;
9534 break;
9540 // no free slot found?
9541 if (!b_found)
9542 return EQUIP_ERR_INVENTORY_FULL;
9545 return EQUIP_ERR_OK;
9548 //////////////////////////////////////////////////////////////////////////
9549 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9551 dest = 0;
9552 Item *pItem = Item::CreateItem( item, count, this );
9553 if( pItem )
9555 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9556 delete pItem;
9557 return result;
9560 return EQUIP_ERR_ITEM_NOT_FOUND;
9563 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9565 dest = 0;
9566 if( pItem )
9568 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9569 ItemPrototype const *pProto = pItem->GetProto();
9570 if( pProto )
9572 // May be here should be more stronger checks; STUNNED checked
9573 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9574 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9575 return EQUIP_ERR_YOU_ARE_STUNNED;
9577 if(pItem->IsBindedNotWith(GetGUID()))
9578 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9580 // check count of items (skip for auto move for same player from bank)
9581 uint8 res = CanTakeMoreSimilarItems(pItem);
9582 if(res != EQUIP_ERR_OK)
9583 return res;
9585 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9586 // - combat
9587 // - in-progress arenas
9588 if( !pProto->CanChangeEquipStateInCombat() )
9590 if( isInCombat() )
9591 return EQUIP_ERR_NOT_IN_COMBAT;
9593 if(BattleGround* bg = GetBattleGround())
9594 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9595 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9598 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9599 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9601 if(IsNonMeleeSpellCasted(false))
9602 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9604 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9605 if( eslot == NULL_SLOT )
9606 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9608 uint8 msg = CanUseItem( pItem , not_loading );
9609 if( msg != EQUIP_ERR_OK )
9610 return msg;
9611 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9612 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9614 // check unique-equipped on item
9615 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9617 // there is an equip limit on this item
9618 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9619 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9620 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9623 // check unique-equipped on gems
9624 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9626 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9627 if(!enchant_id)
9628 continue;
9629 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9630 if(!enchantEntry)
9631 continue;
9633 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9634 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9636 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9637 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9638 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9642 // check unique-equipped special item classes
9643 if (pProto->Class == ITEM_CLASS_QUIVER)
9645 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9647 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9649 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9651 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9652 (!swap || pBag->GetSlot() != eslot ) )
9654 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9655 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9656 else
9657 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9664 uint32 type = pProto->InventoryType;
9666 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9668 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9670 if(!CanDualWield())
9671 return EQUIP_ERR_CANT_DUAL_WIELD;
9674 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9675 if(mainItem)
9677 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9678 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9682 // equip two-hand weapon case (with possible unequip 2 items)
9683 if( type == INVTYPE_2HWEAPON )
9685 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9686 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9688 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9689 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9690 ItemPosCountVec off_dest;
9691 if( offItem && (!not_loading ||
9692 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9693 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9694 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9696 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9697 return EQUIP_ERR_OK;
9700 if( !swap )
9701 return EQUIP_ERR_ITEM_NOT_FOUND;
9702 else
9703 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9706 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9708 // Applied only to equipped items and bank bags
9709 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9710 return EQUIP_ERR_OK;
9712 Item* pItem = GetItemByPos(pos);
9714 // Applied only to existed equipped item
9715 if( !pItem )
9716 return EQUIP_ERR_OK;
9718 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9720 ItemPrototype const *pProto = pItem->GetProto();
9721 if( !pProto )
9722 return EQUIP_ERR_ITEM_NOT_FOUND;
9724 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9725 // - combat
9726 // - in-progress arenas
9727 if( !pProto->CanChangeEquipStateInCombat() )
9729 if( isInCombat() )
9730 return EQUIP_ERR_NOT_IN_COMBAT;
9732 if(BattleGround* bg = GetBattleGround())
9733 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9734 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9737 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9738 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9740 return EQUIP_ERR_OK;
9743 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9745 if( !pItem )
9746 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9748 uint32 count = pItem->GetCount();
9750 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9751 ItemPrototype const *pProto = pItem->GetProto();
9752 if( !pProto )
9753 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9755 if( pItem->IsBindedNotWith(GetGUID()) )
9756 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9758 // check count of items (skip for auto move for same player from bank)
9759 uint8 res = CanTakeMoreSimilarItems(pItem);
9760 if(res != EQUIP_ERR_OK)
9761 return res;
9763 // in specific slot
9764 if( bag != NULL_BAG && slot != NULL_SLOT )
9766 if( pProto->InventoryType == INVTYPE_BAG )
9768 Bag *pBag = (Bag*)pItem;
9769 if( pBag )
9771 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9773 if( !HasBankBagSlot( slot ) )
9774 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9775 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9776 return cantuse;
9778 else
9780 if( !pBag->IsEmpty() )
9781 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9785 else
9787 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9788 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9791 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9792 if(res!=EQUIP_ERR_OK)
9793 return res;
9795 if(count==0)
9796 return EQUIP_ERR_OK;
9799 // not specific slot or have space for partly store only in specific slot
9801 // in specific bag
9802 if( bag != NULL_BAG )
9804 if( pProto->InventoryType == INVTYPE_BAG )
9806 Bag *pBag = (Bag*)pItem;
9807 if( pBag && !pBag->IsEmpty() )
9808 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9811 // search stack in bag for merge to
9812 if( pProto->Stackable > 1 )
9814 if( bag == INVENTORY_SLOT_BAG_0 )
9816 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9817 if(res!=EQUIP_ERR_OK)
9818 return res;
9820 if(count==0)
9821 return EQUIP_ERR_OK;
9823 else
9825 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9826 if(res!=EQUIP_ERR_OK)
9827 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9829 if(res!=EQUIP_ERR_OK)
9830 return res;
9832 if(count==0)
9833 return EQUIP_ERR_OK;
9837 // search free slot in bag
9838 if( bag == INVENTORY_SLOT_BAG_0 )
9840 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9841 if(res!=EQUIP_ERR_OK)
9842 return res;
9844 if(count==0)
9845 return EQUIP_ERR_OK;
9847 else
9849 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9850 if(res!=EQUIP_ERR_OK)
9851 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9853 if(res!=EQUIP_ERR_OK)
9854 return res;
9856 if(count==0)
9857 return EQUIP_ERR_OK;
9861 // not specific bag or have space for partly store only in specific bag
9863 // search stack for merge to
9864 if( pProto->Stackable > 1 )
9866 // in slots
9867 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9868 if(res!=EQUIP_ERR_OK)
9869 return res;
9871 if(count==0)
9872 return EQUIP_ERR_OK;
9874 // in special bags
9875 if( pProto->BagFamily )
9877 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9879 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9880 if(res!=EQUIP_ERR_OK)
9881 continue;
9883 if(count==0)
9884 return EQUIP_ERR_OK;
9888 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9890 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9891 if(res!=EQUIP_ERR_OK)
9892 continue;
9894 if(count==0)
9895 return EQUIP_ERR_OK;
9899 // search free place in special bag
9900 if( pProto->BagFamily )
9902 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9904 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9905 if(res!=EQUIP_ERR_OK)
9906 continue;
9908 if(count==0)
9909 return EQUIP_ERR_OK;
9913 // search free space
9914 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9915 if(res!=EQUIP_ERR_OK)
9916 return res;
9918 if(count==0)
9919 return EQUIP_ERR_OK;
9921 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9923 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9924 if(res!=EQUIP_ERR_OK)
9925 continue;
9927 if(count==0)
9928 return EQUIP_ERR_OK;
9930 return EQUIP_ERR_BANK_FULL;
9933 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9935 if( pItem )
9937 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9938 if( !isAlive() && not_loading )
9939 return EQUIP_ERR_YOU_ARE_DEAD;
9940 //if( isStunned() )
9941 // return EQUIP_ERR_YOU_ARE_STUNNED;
9942 ItemPrototype const *pProto = pItem->GetProto();
9943 if( pProto )
9945 if( pItem->IsBindedNotWith(GetGUID()) )
9946 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9947 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9948 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9949 if( pItem->GetSkill() != 0 )
9951 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9952 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9954 if( pProto->RequiredSkill != 0 )
9956 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9957 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9958 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9959 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9961 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9962 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9963 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9964 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9965 if( getLevel() < pProto->RequiredLevel )
9966 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9967 return EQUIP_ERR_OK;
9970 return EQUIP_ERR_ITEM_NOT_FOUND;
9973 bool Player::CanUseItem( ItemPrototype const *pProto )
9975 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9977 if( pProto )
9979 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9980 return false;
9981 if( pProto->RequiredSkill != 0 )
9983 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9984 return false;
9985 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9986 return false;
9988 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9989 return false;
9990 if( getLevel() < pProto->RequiredLevel )
9991 return false;
9992 return true;
9994 return false;
9997 uint8 Player::CanUseAmmo( uint32 item ) const
9999 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10000 if( !isAlive() )
10001 return EQUIP_ERR_YOU_ARE_DEAD;
10002 //if( isStunned() )
10003 // return EQUIP_ERR_YOU_ARE_STUNNED;
10004 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10005 if( pProto )
10007 if( pProto->InventoryType!= INVTYPE_AMMO )
10008 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10009 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10010 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10011 if( pProto->RequiredSkill != 0 )
10013 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10014 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10015 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10016 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10018 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10019 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10020 /*if( GetReputation() < pProto->RequiredReputation )
10021 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10023 if( getLevel() < pProto->RequiredLevel )
10024 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10026 // Requires No Ammo
10027 if(GetDummyAura(46699))
10028 return EQUIP_ERR_BAG_FULL6;
10030 return EQUIP_ERR_OK;
10032 return EQUIP_ERR_ITEM_NOT_FOUND;
10035 void Player::SetAmmo( uint32 item )
10037 if(!item)
10038 return;
10040 // already set
10041 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10042 return;
10044 // check ammo
10045 if(item)
10047 uint8 msg = CanUseAmmo( item );
10048 if( msg != EQUIP_ERR_OK )
10050 SendEquipError( msg, NULL, NULL );
10051 return;
10055 SetUInt32Value(PLAYER_AMMO_ID, item);
10057 _ApplyAmmoBonuses();
10060 void Player::RemoveAmmo()
10062 SetUInt32Value(PLAYER_AMMO_ID, 0);
10064 m_ammoDPS = 0.0f;
10066 if(CanModifyStats())
10067 UpdateDamagePhysical(RANGED_ATTACK);
10070 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10071 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10073 uint32 count = 0;
10074 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10075 count += itr->count;
10077 Item *pItem = Item::CreateItem( item, count, this );
10078 if( pItem )
10080 ItemAddedQuestCheck( item, count );
10081 if(randomPropertyId)
10082 pItem->SetItemRandomProperties(randomPropertyId);
10083 pItem = StoreItem( dest, pItem, update );
10085 return pItem;
10088 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10090 if( !pItem )
10091 return NULL;
10093 Item* lastItem = pItem;
10095 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10097 uint16 pos = itr->pos;
10098 uint32 count = itr->count;
10100 ++itr;
10102 if(itr == dest.end())
10104 lastItem = _StoreItem(pos,pItem,count,false,update);
10105 break;
10108 lastItem = _StoreItem(pos,pItem,count,true,update);
10111 return lastItem;
10114 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10115 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10117 if( !pItem )
10118 return NULL;
10120 uint8 bag = pos >> 8;
10121 uint8 slot = pos & 255;
10123 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10125 Item *pItem2 = GetItemByPos( bag, slot );
10127 if( !pItem2 )
10129 if(clone)
10130 pItem = pItem->CloneItem(count,this);
10131 else
10132 pItem->SetCount(count);
10134 if(!pItem)
10135 return NULL;
10137 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10138 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10139 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10140 pItem->SetBinding( true );
10142 if( bag == INVENTORY_SLOT_BAG_0 )
10144 m_items[slot] = pItem;
10145 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10146 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10147 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10149 pItem->SetSlot( slot );
10150 pItem->SetContainer( NULL );
10152 if( IsInWorld() && update )
10154 pItem->AddToWorld();
10155 pItem->SendUpdateToPlayer( this );
10158 pItem->SetState(ITEM_CHANGED, this);
10160 else
10162 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10163 if( pBag )
10165 pBag->StoreItem( slot, pItem, update );
10166 if( IsInWorld() && update )
10168 pItem->AddToWorld();
10169 pItem->SendUpdateToPlayer( this );
10171 pItem->SetState(ITEM_CHANGED, this);
10172 pBag->SetState(ITEM_CHANGED, this);
10176 AddEnchantmentDurations(pItem);
10177 AddItemDurations(pItem);
10179 return pItem;
10181 else
10183 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10184 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10185 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10186 pItem2->SetBinding( true );
10188 pItem2->SetCount( pItem2->GetCount() + count );
10189 if( IsInWorld() && update )
10190 pItem2->SendUpdateToPlayer( this );
10192 if(!clone)
10194 // delete item (it not in any slot currently)
10195 if( IsInWorld() && update )
10197 pItem->RemoveFromWorld();
10198 pItem->DestroyForPlayer( this );
10201 RemoveEnchantmentDurations(pItem);
10202 RemoveItemDurations(pItem);
10204 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10205 pItem->SetState(ITEM_REMOVED, this);
10207 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10208 AddEnchantmentDurations(pItem2);
10210 pItem2->SetState(ITEM_CHANGED, this);
10212 return pItem2;
10216 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
10218 Item *pItem = Item::CreateItem( item, count, this );
10219 if( pItem )
10221 ItemAddedQuestCheck( item, count );
10222 Item * retItem = EquipItem( pos, pItem, update );
10224 return retItem;
10226 return NULL;
10229 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10231 if( pItem )
10233 AddEnchantmentDurations(pItem);
10234 AddItemDurations(pItem);
10236 uint8 bag = pos >> 8;
10237 uint8 slot = pos & 255;
10239 Item *pItem2 = GetItemByPos( bag, slot );
10241 if( !pItem2 )
10243 VisualizeItem( slot, pItem);
10245 if(isAlive())
10247 ItemPrototype const *pProto = pItem->GetProto();
10249 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10250 if(pProto && pProto->ItemSet)
10251 AddItemsSetItem(this,pItem);
10253 _ApplyItemMods(pItem, slot, true);
10255 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10257 m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
10258 if (getClass() == CLASS_ROGUE)
10259 m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
10263 if( IsInWorld() && update )
10265 pItem->AddToWorld();
10266 pItem->SendUpdateToPlayer( this );
10269 ApplyEquipCooldown(pItem);
10271 if( slot == EQUIPMENT_SLOT_MAINHAND )
10272 UpdateExpertise(BASE_ATTACK);
10273 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10274 UpdateExpertise(OFF_ATTACK);
10276 else
10278 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10279 if( IsInWorld() && update )
10280 pItem2->SendUpdateToPlayer( this );
10282 // delete item (it not in any slot currently)
10283 //pItem->DeleteFromDB();
10284 if( IsInWorld() && update )
10286 pItem->RemoveFromWorld();
10287 pItem->DestroyForPlayer( this );
10290 RemoveEnchantmentDurations(pItem);
10291 RemoveItemDurations(pItem);
10293 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10294 pItem->SetState(ITEM_REMOVED, this);
10295 pItem2->SetState(ITEM_CHANGED, this);
10297 ApplyEquipCooldown(pItem2);
10299 return pItem2;
10303 return pItem;
10306 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10308 if( pItem )
10310 AddEnchantmentDurations(pItem);
10311 AddItemDurations(pItem);
10313 uint8 slot = pos & 255;
10314 VisualizeItem( slot, pItem);
10316 if( IsInWorld() )
10318 pItem->AddToWorld();
10319 pItem->SendUpdateToPlayer( this );
10324 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10326 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10327 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10328 // entry // Size: 1
10329 // inspected enchantments // Size: 6
10330 // ? // Size: 5
10331 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10332 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10333 // // = 16
10335 if(pItem)
10337 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10339 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10340 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10342 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10343 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10345 // Use SetInt16Value to prevent set high part to FFFF for negative value
10346 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10347 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10349 else
10351 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10353 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10354 SetUInt32Value(VisibleBase + 0, 0);
10356 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10357 SetUInt32Value(VisibleBase + 1 + i, 0);
10359 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10360 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10364 void Player::VisualizeItem( uint8 slot, Item *pItem)
10366 if(!pItem)
10367 return;
10369 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10370 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10371 pItem->SetBinding( true );
10373 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10375 m_items[slot] = pItem;
10376 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10377 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10378 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10379 pItem->SetSlot( slot );
10380 pItem->SetContainer( NULL );
10382 if( slot < EQUIPMENT_SLOT_END )
10383 SetVisibleItemSlot(slot,pItem);
10385 pItem->SetState(ITEM_CHANGED, this);
10388 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10390 // note: removeitem does not actually change the item
10391 // it only takes the item out of storage temporarily
10392 // note2: if removeitem is to be used for delinking
10393 // the item must be removed from the player's updatequeue
10395 Item *pItem = GetItemByPos( bag, slot );
10396 if( pItem )
10398 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10400 RemoveEnchantmentDurations(pItem);
10401 RemoveItemDurations(pItem);
10403 if( bag == INVENTORY_SLOT_BAG_0 )
10405 if ( slot < INVENTORY_SLOT_BAG_END )
10407 ItemPrototype const *pProto = pItem->GetProto();
10408 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10410 if(pProto && pProto->ItemSet)
10411 RemoveItemsSetItem(this,pProto);
10413 _ApplyItemMods(pItem, slot, false);
10415 // remove item dependent auras and casts (only weapon and armor slots)
10416 if(slot < EQUIPMENT_SLOT_END)
10417 RemoveItemDependentAurasAndCasts(pItem);
10419 // remove held enchantments
10420 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10422 if (pItem->GetItemSuffixFactor())
10424 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10425 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10427 else
10429 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10430 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10435 m_items[slot] = NULL;
10436 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10438 if ( slot < EQUIPMENT_SLOT_END )
10439 SetVisibleItemSlot(slot,NULL);
10441 else
10443 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10444 if( pBag )
10445 pBag->RemoveItem(slot, update);
10447 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10448 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10449 pItem->SetSlot( NULL_SLOT );
10450 if( IsInWorld() && update )
10451 pItem->SendUpdateToPlayer( this );
10453 if( slot == EQUIPMENT_SLOT_MAINHAND )
10454 UpdateExpertise(BASE_ATTACK);
10455 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10456 UpdateExpertise(OFF_ATTACK);
10460 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10461 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10463 if(Item* it = GetItemByPos(bag,slot))
10465 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10466 RemoveItem( bag,slot,update);
10467 it->RemoveFromUpdateQueueOf(this);
10468 if(it->IsInWorld())
10470 it->RemoveFromWorld();
10471 it->DestroyForPlayer( this );
10476 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10477 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10479 // update quest counters
10480 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10482 // store item
10483 Item* pLastItem = StoreItem( dest, pItem, update);
10485 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10486 if(pLastItem==pItem)
10488 // update owner for last item (this can be original item with wrong owner
10489 if(pLastItem->GetOwnerGUID() != GetGUID())
10490 pLastItem->SetOwnerGUID(GetGUID());
10492 // if this original item then it need create record in inventory
10493 // in case trade we already have item in other player inventory
10494 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10498 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10500 Item *pItem = GetItemByPos( bag, slot );
10501 if( pItem )
10503 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10505 // start from destroy contained items (only equipped bag can have its)
10506 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10508 for (int i = 0; i < MAX_BAG_SIZE; i++)
10509 DestroyItem(slot,i,update);
10512 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10513 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10515 RemoveEnchantmentDurations(pItem);
10516 RemoveItemDurations(pItem);
10518 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10520 if( bag == INVENTORY_SLOT_BAG_0 )
10522 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10524 // equipment and equipped bags can have applied bonuses
10525 if ( slot < INVENTORY_SLOT_BAG_END )
10527 ItemPrototype const *pProto = pItem->GetProto();
10529 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10530 if(pProto && pProto->ItemSet)
10531 RemoveItemsSetItem(this,pProto);
10533 _ApplyItemMods(pItem, slot, false);
10536 if ( slot < EQUIPMENT_SLOT_END )
10538 // remove item dependent auras and casts (only weapon and armor slots)
10539 RemoveItemDependentAurasAndCasts(pItem);
10541 // equipment visual show
10542 SetVisibleItemSlot(slot,NULL);
10545 m_items[slot] = NULL;
10547 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10548 pBag->RemoveItem(slot, update);
10550 if( IsInWorld() && update )
10552 pItem->RemoveFromWorld();
10553 pItem->DestroyForPlayer(this);
10556 //pItem->SetOwnerGUID(0);
10557 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10558 pItem->SetSlot( NULL_SLOT );
10559 pItem->SetState(ITEM_REMOVED, this);
10563 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10565 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10566 Item *pItem;
10567 ItemPrototype const *pProto;
10568 uint32 remcount = 0;
10570 // in inventory
10571 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10573 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10574 if( pItem && pItem->GetEntry() == item )
10576 if( pItem->GetCount() + remcount <= count )
10578 // all items in inventory can unequipped
10579 remcount += pItem->GetCount();
10580 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10582 if(remcount >=count)
10583 return;
10585 else
10587 pProto = pItem->GetProto();
10588 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10589 pItem->SetCount( pItem->GetCount() - count + remcount );
10590 if( IsInWorld() & update )
10591 pItem->SendUpdateToPlayer( this );
10592 pItem->SetState(ITEM_CHANGED, this);
10593 return;
10597 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10599 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10600 if( pItem && pItem->GetEntry() == item )
10602 if( pItem->GetCount() + remcount <= count )
10604 // all keys can be unequipped
10605 remcount += pItem->GetCount();
10606 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10608 if(remcount >=count)
10609 return;
10611 else
10613 pProto = pItem->GetProto();
10614 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10615 pItem->SetCount( pItem->GetCount() - count + remcount );
10616 if( IsInWorld() & update )
10617 pItem->SendUpdateToPlayer( this );
10618 pItem->SetState(ITEM_CHANGED, this);
10619 return;
10624 // in inventory bags
10625 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10627 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10629 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10631 pItem = pBag->GetItemByPos(j);
10632 if( pItem && pItem->GetEntry() == item )
10634 // all items in bags can be unequipped
10635 if( pItem->GetCount() + remcount <= count )
10637 remcount += pItem->GetCount();
10638 DestroyItem( i, j, update );
10640 if(remcount >=count)
10641 return;
10643 else
10645 pProto = pItem->GetProto();
10646 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10647 pItem->SetCount( pItem->GetCount() - count + remcount );
10648 if( IsInWorld() && update )
10649 pItem->SendUpdateToPlayer( this );
10650 pItem->SetState(ITEM_CHANGED, this);
10651 return;
10658 // in equipment and bag list
10659 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10661 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10662 if( pItem && pItem->GetEntry() == item )
10664 if( pItem->GetCount() + remcount <= count )
10666 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10668 remcount += pItem->GetCount();
10669 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10671 if(remcount >=count)
10672 return;
10675 else
10677 pProto = pItem->GetProto();
10678 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10679 pItem->SetCount( pItem->GetCount() - count + remcount );
10680 if( IsInWorld() & update )
10681 pItem->SendUpdateToPlayer( this );
10682 pItem->SetState(ITEM_CHANGED, this);
10683 return;
10689 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10691 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10693 // in inventory
10694 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10696 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10697 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10698 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10700 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10702 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10703 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10704 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10707 // in inventory bags
10708 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10710 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10711 if( pBag )
10713 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10715 Item* pItem = pBag->GetItemByPos(j);
10716 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10717 DestroyItem( i, j, update);
10722 // in equipment and bag list
10723 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10725 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10726 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10727 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10731 void Player::DestroyConjuredItems( bool update )
10733 // used when entering arena
10734 // destroys all conjured items
10735 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10737 // in inventory
10738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10740 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10741 if( pItem && pItem->GetProto() &&
10742 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10743 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10744 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10747 // in inventory bags
10748 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10750 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10751 if( pBag )
10753 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10755 Item* pItem = pBag->GetItemByPos(j);
10756 if( pItem && pItem->GetProto() &&
10757 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10758 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10759 DestroyItem( i, j, update);
10764 // in equipment and bag list
10765 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10767 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10768 if( pItem && pItem->GetProto() &&
10769 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10770 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10771 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10775 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10777 if(!pItem)
10778 return;
10780 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10782 if( pItem->GetCount() <= count )
10784 count-= pItem->GetCount();
10786 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10788 else
10790 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10791 pItem->SetCount( pItem->GetCount() - count );
10792 count = 0;
10793 if( IsInWorld() & update )
10794 pItem->SendUpdateToPlayer( this );
10795 pItem->SetState(ITEM_CHANGED, this);
10799 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10801 uint8 srcbag = src >> 8;
10802 uint8 srcslot = src & 255;
10804 uint8 dstbag = dst >> 8;
10805 uint8 dstslot = dst & 255;
10807 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10808 if( !pSrcItem )
10810 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10811 return;
10814 // not let split all items (can be only at cheating)
10815 if(pSrcItem->GetCount() == count)
10817 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10818 return;
10821 // not let split more existed items (can be only at cheating)
10822 if(pSrcItem->GetCount() < count)
10824 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10825 return;
10828 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10830 //best error message found for attempting to split while looting
10831 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10832 return;
10835 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10836 Item *pNewItem = pSrcItem->CloneItem( count, this );
10837 if( !pNewItem )
10839 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10840 return;
10843 if( IsInventoryPos( dst ) )
10845 // change item amount before check (for unique max count check)
10846 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10848 ItemPosCountVec dest;
10849 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10850 if( msg != EQUIP_ERR_OK )
10852 delete pNewItem;
10853 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10854 SendEquipError( msg, pSrcItem, NULL );
10855 return;
10858 if( IsInWorld() )
10859 pSrcItem->SendUpdateToPlayer( this );
10860 pSrcItem->SetState(ITEM_CHANGED, this);
10861 StoreItem( dest, pNewItem, true);
10863 else if( IsBankPos ( dst ) )
10865 // change item amount before check (for unique max count check)
10866 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10868 ItemPosCountVec dest;
10869 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10870 if( msg != EQUIP_ERR_OK )
10872 delete pNewItem;
10873 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10874 SendEquipError( msg, pSrcItem, NULL );
10875 return;
10878 if( IsInWorld() )
10879 pSrcItem->SendUpdateToPlayer( this );
10880 pSrcItem->SetState(ITEM_CHANGED, this);
10881 BankItem( dest, pNewItem, true);
10883 else if( IsEquipmentPos ( dst ) )
10885 // change item amount before check (for unique max count check), provide space for splitted items
10886 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10888 uint16 dest;
10889 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10890 if( msg != EQUIP_ERR_OK )
10892 delete pNewItem;
10893 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10894 SendEquipError( msg, pSrcItem, NULL );
10895 return;
10898 if( IsInWorld() )
10899 pSrcItem->SendUpdateToPlayer( this );
10900 pSrcItem->SetState(ITEM_CHANGED, this);
10901 EquipItem( dest, pNewItem, true);
10902 AutoUnequipOffhandIfNeed();
10906 void Player::SwapItem( uint16 src, uint16 dst )
10908 uint8 srcbag = src >> 8;
10909 uint8 srcslot = src & 255;
10911 uint8 dstbag = dst >> 8;
10912 uint8 dstslot = dst & 255;
10914 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10915 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10917 if( !pSrcItem )
10918 return;
10920 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10922 if(!isAlive() )
10924 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10925 return;
10928 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10930 //best error message found for attempting to swap while looting
10931 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10932 return;
10935 // check unequip potability for equipped items and bank bags
10936 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10938 // bags can be swapped with empty bag slots
10939 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10940 if(msg != EQUIP_ERR_OK)
10942 SendEquipError( msg, pSrcItem, pDstItem );
10943 return;
10947 // prevent put equipped/bank bag in self
10948 if( IsBagPos ( src ) && srcslot == dstbag)
10950 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10951 return;
10954 if( !pDstItem )
10956 if( IsInventoryPos( dst ) )
10958 ItemPosCountVec dest;
10959 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10960 if( msg != EQUIP_ERR_OK )
10962 SendEquipError( msg, pSrcItem, NULL );
10963 return;
10966 RemoveItem(srcbag, srcslot, true);
10967 StoreItem( dest, pSrcItem, true);
10969 else if( IsBankPos ( dst ) )
10971 ItemPosCountVec dest;
10972 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10973 if( msg != EQUIP_ERR_OK )
10975 SendEquipError( msg, pSrcItem, NULL );
10976 return;
10979 RemoveItem(srcbag, srcslot, true);
10980 BankItem( dest, pSrcItem, true);
10982 else if( IsEquipmentPos ( dst ) )
10984 uint16 dest;
10985 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10986 if( msg != EQUIP_ERR_OK )
10988 SendEquipError( msg, pSrcItem, NULL );
10989 return;
10992 RemoveItem(srcbag, srcslot, true);
10993 EquipItem( dest, pSrcItem, true);
10994 AutoUnequipOffhandIfNeed();
10997 else // if (!pDstItem)
10999 if(pDstItem->m_lootGenerated) // prevent swap looting item
11001 //best error message found for attempting to swap while looting
11002 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11003 return;
11006 // check unequip potability for equipped items and bank bags
11007 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11009 // bags can be swapped with empty bag slots
11010 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11011 if(msg != EQUIP_ERR_OK)
11013 SendEquipError( msg, pSrcItem, pDstItem );
11014 return;
11018 // attempt merge to / fill target item
11020 uint8 msg;
11021 ItemPosCountVec sDest;
11022 uint16 eDest;
11023 if( IsInventoryPos( dst ) )
11024 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11025 else if( IsBankPos ( dst ) )
11026 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11027 else if( IsEquipmentPos ( dst ) )
11028 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11029 else
11030 return;
11032 // can be merge/fill
11033 if(msg == EQUIP_ERR_OK)
11035 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
11037 RemoveItem(srcbag, srcslot, true);
11039 if( IsInventoryPos( dst ) )
11040 StoreItem( sDest, pSrcItem, true);
11041 else if( IsBankPos ( dst ) )
11042 BankItem( sDest, pSrcItem, true);
11043 else if( IsEquipmentPos ( dst ) )
11045 EquipItem( eDest, pSrcItem, true);
11046 AutoUnequipOffhandIfNeed();
11049 else
11051 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
11052 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
11053 pSrcItem->SetState(ITEM_CHANGED, this);
11054 pDstItem->SetState(ITEM_CHANGED, this);
11055 if( IsInWorld() )
11057 pSrcItem->SendUpdateToPlayer( this );
11058 pDstItem->SendUpdateToPlayer( this );
11061 return;
11065 // impossible merge/fill, do real swap
11066 uint8 msg;
11068 // check src->dest move possibility
11069 ItemPosCountVec sDest;
11070 uint16 eDest;
11071 if( IsInventoryPos( dst ) )
11072 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11073 else if( IsBankPos( dst ) )
11074 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11075 else if( IsEquipmentPos( dst ) )
11077 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11078 if( msg == EQUIP_ERR_OK )
11079 msg = CanUnequipItem( eDest, true );
11082 if( msg != EQUIP_ERR_OK )
11084 SendEquipError( msg, pSrcItem, pDstItem );
11085 return;
11088 // check dest->src move possibility
11089 ItemPosCountVec sDest2;
11090 uint16 eDest2;
11091 if( IsInventoryPos( src ) )
11092 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11093 else if( IsBankPos( src ) )
11094 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11095 else if( IsEquipmentPos( src ) )
11097 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11098 if( msg == EQUIP_ERR_OK )
11099 msg = CanUnequipItem( eDest2, true);
11102 if( msg != EQUIP_ERR_OK )
11104 SendEquipError( msg, pDstItem, pSrcItem );
11105 return;
11108 // now do moves, remove...
11109 RemoveItem(dstbag, dstslot, false);
11110 RemoveItem(srcbag, srcslot, false);
11112 // add to dest
11113 if( IsInventoryPos( dst ) )
11114 StoreItem(sDest, pSrcItem, true);
11115 else if( IsBankPos( dst ) )
11116 BankItem(sDest, pSrcItem, true);
11117 else if( IsEquipmentPos( dst ) )
11118 EquipItem(eDest, pSrcItem, true);
11120 // add to src
11121 if( IsInventoryPos( src ) )
11122 StoreItem(sDest2, pDstItem, true);
11123 else if( IsBankPos( src ) )
11124 BankItem(sDest2, pDstItem, true);
11125 else if( IsEquipmentPos( src ) )
11126 EquipItem(eDest2, pDstItem, true);
11128 AutoUnequipOffhandIfNeed();
11132 void Player::AddItemToBuyBackSlot( Item *pItem )
11134 if( pItem )
11136 uint32 slot = m_currentBuybackSlot;
11137 // if current back slot non-empty search oldest or free
11138 if(m_items[slot])
11140 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11141 uint32 oldest_slot = BUYBACK_SLOT_START;
11143 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11145 // found empty
11146 if(!m_items[i])
11148 slot = i;
11149 break;
11152 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11154 if(oldest_time > i_time)
11156 oldest_time = i_time;
11157 oldest_slot = i;
11161 // find oldest
11162 slot = oldest_slot;
11165 RemoveItemFromBuyBackSlot( slot, true );
11166 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11168 m_items[slot] = pItem;
11169 time_t base = time(NULL);
11170 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11171 uint32 eslot = slot - BUYBACK_SLOT_START;
11173 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11174 ItemPrototype const *pProto = pItem->GetProto();
11175 if( pProto )
11176 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11177 else
11178 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11179 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11181 // move to next (for non filled list is move most optimized choice)
11182 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11183 ++m_currentBuybackSlot;
11187 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11189 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11190 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11191 return m_items[slot];
11192 return NULL;
11195 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11197 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11198 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11200 Item *pItem = m_items[slot];
11201 if( pItem )
11203 pItem->RemoveFromWorld();
11204 if(del) pItem->SetState(ITEM_REMOVED, this);
11207 m_items[slot] = NULL;
11209 uint32 eslot = slot - BUYBACK_SLOT_START;
11210 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11211 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11212 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11214 // if current backslot is filled set to now free slot
11215 if(m_items[m_currentBuybackSlot])
11216 m_currentBuybackSlot = slot;
11220 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11222 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11223 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11224 data << uint8(msg);
11226 if(msg)
11228 data << uint64(pItem ? pItem->GetGUID() : 0);
11229 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11230 data << uint8(0); // not 0 there...
11232 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11234 uint32 level = 0;
11236 if(pItem)
11237 if(ItemPrototype const* proto = pItem->GetProto())
11238 level = proto->RequiredLevel;
11240 data << uint32(level); // new 2.4.0
11243 GetSession()->SendPacket(&data);
11246 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11248 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11249 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11250 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11251 data << uint32(item);
11252 if( param > 0 )
11253 data << uint32(param);
11254 data << uint8(msg);
11255 GetSession()->SendPacket(&data);
11258 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11260 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11261 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11262 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11263 data << uint64(guid);
11264 if( param > 0 )
11265 data << uint32(param);
11266 data << uint8(msg);
11267 GetSession()->SendPacket(&data);
11270 void Player::ClearTrade()
11272 tradeGold = 0;
11273 acceptTrade = false;
11274 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11275 tradeItems[i] = NULL_SLOT;
11278 void Player::TradeCancel(bool sendback)
11280 if(pTrader)
11282 // send yellow "Trade canceled" message to both traders
11283 WorldSession* ws;
11284 ws = GetSession();
11285 if(sendback)
11286 ws->SendCancelTrade();
11287 ws = pTrader->GetSession();
11288 if(!ws->PlayerLogout())
11289 ws->SendCancelTrade();
11291 // cleanup
11292 ClearTrade();
11293 pTrader->ClearTrade();
11294 // prevent loss of reference
11295 pTrader->pTrader = NULL;
11296 pTrader = NULL;
11300 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11302 if(m_itemDuration.empty())
11303 return;
11305 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11307 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11309 Item* item = *itr;
11310 ++itr; // current element can be erased in UpdateDuration
11312 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11313 item->UpdateDuration(this,time);
11317 void Player::UpdateEnchantTime(uint32 time)
11319 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11321 assert(itr->item);
11322 next=itr;
11323 if(!itr->item->GetEnchantmentId(itr->slot))
11325 next = m_enchantDuration.erase(itr);
11327 else if(itr->leftduration <= time)
11329 ApplyEnchantment(itr->item,itr->slot,false,false);
11330 itr->item->ClearEnchantment(itr->slot);
11331 next = m_enchantDuration.erase(itr);
11333 else if(itr->leftduration > time)
11335 itr->leftduration -= time;
11336 ++next;
11341 void Player::AddEnchantmentDurations(Item *item)
11343 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11345 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11346 continue;
11348 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11349 if( duration > 0 )
11350 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11354 void Player::RemoveEnchantmentDurations(Item *item)
11356 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11358 if(itr->item == item)
11360 // save duration in item
11361 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11362 itr = m_enchantDuration.erase(itr);
11364 else
11365 ++itr;
11369 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11371 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11372 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11374 next = itr;
11375 if(itr->slot==slot)
11377 if(itr->item && itr->item->GetEnchantmentId(slot))
11379 // remove from stats
11380 ApplyEnchantment(itr->item,slot,false,false);
11381 // remove visual
11382 itr->item->ClearEnchantment(slot);
11384 // remove from update list
11385 next = m_enchantDuration.erase(itr);
11387 else
11388 ++next;
11391 // remove enchants from inventory items
11392 // NOTE: no need to remove these from stats, since these aren't equipped
11393 // in inventory
11394 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11396 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11397 if( pItem && pItem->GetEnchantmentId(slot) )
11398 pItem->ClearEnchantment(slot);
11401 // in inventory bags
11402 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11404 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11405 if( pBag )
11407 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11409 Item* pItem = pBag->GetItemByPos(j);
11410 if( pItem && pItem->GetEnchantmentId(slot) )
11411 pItem->ClearEnchantment(slot);
11417 // duration == 0 will remove item enchant
11418 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11420 if(!item)
11421 return;
11423 if(slot >= MAX_ENCHANTMENT_SLOT)
11424 return;
11426 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11428 if(itr->item == item && itr->slot == slot)
11430 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11431 m_enchantDuration.erase(itr);
11432 break;
11435 if(item && duration > 0 )
11437 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11438 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11442 void Player::ApplyEnchantment(Item *item,bool apply)
11444 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11445 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11448 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11450 if(!item)
11451 return;
11453 if(!item->IsEquipped())
11454 return;
11456 if(slot >= MAX_ENCHANTMENT_SLOT)
11457 return;
11459 uint32 enchant_id = item->GetEnchantmentId(slot);
11460 if(!enchant_id)
11461 return;
11463 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11464 if(!pEnchant)
11465 return;
11467 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11468 return;
11470 for (int s=0; s<3; s++)
11472 uint32 enchant_display_type = pEnchant->type[s];
11473 uint32 enchant_amount = pEnchant->amount[s];
11474 uint32 enchant_spell_id = pEnchant->spellid[s];
11476 switch(enchant_display_type)
11478 case ITEM_ENCHANTMENT_TYPE_NONE:
11479 break;
11480 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11481 // processed in Player::CastItemCombatSpell
11482 break;
11483 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11484 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11485 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11486 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11487 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11488 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11489 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11490 break;
11491 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11492 if(enchant_spell_id)
11494 if(apply)
11496 int32 basepoints = int32(enchant_amount);
11497 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11498 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11500 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11501 if (item_rand)
11503 // Search enchant_amount
11504 for (int k=0; k<3; k++)
11506 if(item_rand->enchant_id[k] == enchant_id)
11508 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11509 break;
11514 // Cast custom spell vs all equal basepoints getted from enchant_amount
11515 if (basepoints)
11516 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11517 else
11518 CastSpell(this,enchant_spell_id,true,item);
11520 else
11521 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11523 break;
11524 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11525 if (!enchant_amount)
11527 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11528 if(item_rand)
11530 for (int k=0; k<3; k++)
11532 if(item_rand->enchant_id[k] == enchant_id)
11534 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11535 break;
11541 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11542 break;
11543 case ITEM_ENCHANTMENT_TYPE_STAT:
11545 if (!enchant_amount)
11547 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11548 if(item_rand_suffix)
11550 for (int k=0; k<3; k++)
11552 if(item_rand_suffix->enchant_id[k] == enchant_id)
11554 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11555 break;
11561 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11562 switch (enchant_spell_id)
11564 case ITEM_MOD_AGILITY:
11565 sLog.outDebug("+ %u AGILITY",enchant_amount);
11566 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11567 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11568 break;
11569 case ITEM_MOD_STRENGTH:
11570 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11571 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11572 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11573 break;
11574 case ITEM_MOD_INTELLECT:
11575 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11576 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11577 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11578 break;
11579 case ITEM_MOD_SPIRIT:
11580 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11581 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11582 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11583 break;
11584 case ITEM_MOD_STAMINA:
11585 sLog.outDebug("+ %u STAMINA",enchant_amount);
11586 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11587 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11588 break;
11589 case ITEM_MOD_DEFENSE_SKILL_RATING:
11590 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11591 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11592 break;
11593 case ITEM_MOD_DODGE_RATING:
11594 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11595 sLog.outDebug("+ %u DODGE", enchant_amount);
11596 break;
11597 case ITEM_MOD_PARRY_RATING:
11598 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11599 sLog.outDebug("+ %u PARRY", enchant_amount);
11600 break;
11601 case ITEM_MOD_BLOCK_RATING:
11602 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11603 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11604 break;
11605 case ITEM_MOD_HIT_MELEE_RATING:
11606 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11607 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11608 break;
11609 case ITEM_MOD_HIT_RANGED_RATING:
11610 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11611 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11612 break;
11613 case ITEM_MOD_HIT_SPELL_RATING:
11614 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11615 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11616 break;
11617 case ITEM_MOD_CRIT_MELEE_RATING:
11618 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11619 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11620 break;
11621 case ITEM_MOD_CRIT_RANGED_RATING:
11622 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11623 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11624 break;
11625 case ITEM_MOD_CRIT_SPELL_RATING:
11626 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11627 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11628 break;
11629 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11630 // in Enchantments
11631 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11632 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11633 // break;
11634 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11635 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11636 // break;
11637 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11638 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11639 // break;
11640 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11641 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11642 // break;
11643 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11644 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11645 // break;
11646 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11647 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11648 // break;
11649 // case ITEM_MOD_HASTE_MELEE_RATING:
11650 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11651 // break;
11652 // case ITEM_MOD_HASTE_RANGED_RATING:
11653 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11654 // break;
11655 case ITEM_MOD_HASTE_SPELL_RATING:
11656 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11657 break;
11658 case ITEM_MOD_HIT_RATING:
11659 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11660 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11661 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11662 sLog.outDebug("+ %u HIT", enchant_amount);
11663 break;
11664 case ITEM_MOD_CRIT_RATING:
11665 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11666 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11667 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11668 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11669 break;
11670 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11671 // case ITEM_MOD_HIT_TAKEN_RATING:
11672 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11673 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11674 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11675 // break;
11676 // case ITEM_MOD_CRIT_TAKEN_RATING:
11677 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11678 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11679 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11680 // break;
11681 case ITEM_MOD_RESILIENCE_RATING:
11682 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11683 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11684 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11685 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11686 break;
11687 case ITEM_MOD_HASTE_RATING:
11688 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11689 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11690 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11691 sLog.outDebug("+ %u HASTE", enchant_amount);
11692 break;
11693 case ITEM_MOD_EXPERTISE_RATING:
11694 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11695 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11696 break;
11697 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11698 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11699 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11700 break;
11701 default:
11702 break;
11704 break;
11706 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11708 if(getClass() == CLASS_SHAMAN)
11710 float addValue = 0.0f;
11711 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11713 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11714 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11716 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11718 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11719 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11722 break;
11724 default:
11725 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11726 break;
11727 } /*switch(enchant_display_type)*/
11728 } /*for*/
11730 // visualize enchantment at player and equipped items
11731 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11733 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11734 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11737 if(apply_dur)
11739 if(apply)
11741 // set duration
11742 uint32 duration = item->GetEnchantmentDuration(slot);
11743 if(duration > 0)
11744 AddEnchantmentDuration(item,slot,duration);
11746 else
11748 // duration == 0 will remove EnchantDuration
11749 AddEnchantmentDuration(item,slot,0);
11754 void Player::SendEnchantmentDurations()
11756 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11758 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11762 void Player::SendItemDurations()
11764 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11766 (*itr)->SendTimeUpdate(this);
11770 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11772 if(!item) // prevent crash
11773 return;
11775 // last check 2.0.10
11776 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11777 data << GetGUID(); // player GUID
11778 data << uint32(received); // 0=looted, 1=from npc
11779 data << uint32(created); // 0=received, 1=created
11780 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11781 data << (uint8)item->GetBagSlot(); // bagslot
11782 // item slot, but when added to stack: 0xFFFFFFFF
11783 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11784 data << uint32(item->GetEntry()); // item id
11785 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11786 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11787 data << uint32(count); // count of items
11788 data << GetItemCount(item->GetEntry()); // count of items in inventory
11790 if (broadcast && GetGroup())
11791 GetGroup()->BroadcastPacket(&data);
11792 else
11793 GetSession()->SendPacket(&data);
11796 /*********************************************************/
11797 /*** QUEST SYSTEM ***/
11798 /*********************************************************/
11800 void Player::PrepareQuestMenu( uint64 guid )
11802 Object *pObject;
11803 QuestRelations* pObjectQR;
11804 QuestRelations* pObjectQIR;
11805 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11806 if( pCreature )
11808 pObject = (Object*)pCreature;
11809 pObjectQR = &objmgr.mCreatureQuestRelations;
11810 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11812 else
11814 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11815 if( pGameObject )
11817 pObject = (Object*)pGameObject;
11818 pObjectQR = &objmgr.mGOQuestRelations;
11819 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11821 else
11822 return;
11825 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11826 qm.ClearMenu();
11828 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11830 uint32 quest_id = i->second;
11831 QuestStatus status = GetQuestStatus( quest_id );
11832 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11833 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11834 else if ( status == QUEST_STATUS_INCOMPLETE )
11835 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11836 else if (status == QUEST_STATUS_AVAILABLE )
11837 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11840 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11842 uint32 quest_id = i->second;
11843 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11844 if(!pQuest) continue;
11846 QuestStatus status = GetQuestStatus( quest_id );
11848 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11849 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11850 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11851 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11855 void Player::SendPreparedQuest( uint64 guid )
11857 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11858 if( questMenu.Empty() )
11859 return;
11861 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11863 uint32 status = qmi0.m_qIcon;
11865 // single element case
11866 if ( questMenu.MenuItemCount() == 1 )
11868 // Auto open -- maybe also should verify there is no greeting
11869 uint32 quest_id = qmi0.m_qId;
11870 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11871 if ( pQuest )
11873 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11874 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11875 else if( status == DIALOG_STATUS_INCOMPLETE )
11876 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11877 // Send completable on repeatable quest if player don't have quest
11878 else if( pQuest->IsRepeatable() )
11879 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11880 else
11881 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11884 // multiply entries
11885 else
11887 QEmote qe;
11888 qe._Delay = 0;
11889 qe._Emote = 0;
11890 std::string title = "";
11891 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11892 if( pCreature )
11894 uint32 textid = pCreature->GetNpcTextId();
11895 GossipText * gossiptext = objmgr.GetGossipText(textid);
11896 if( !gossiptext )
11898 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11899 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11900 title = "";
11902 else
11904 qe = gossiptext->Options[0].Emotes[0];
11906 if(!gossiptext->Options[0].Text_0.empty())
11908 title = gossiptext->Options[0].Text_0;
11910 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11911 if (loc_idx >= 0)
11913 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11914 if (nl)
11916 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11917 title = nl->Text_0[0][loc_idx];
11921 else
11923 title = gossiptext->Options[0].Text_1;
11925 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11926 if (loc_idx >= 0)
11928 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11929 if (nl)
11931 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11932 title = nl->Text_1[0][loc_idx];
11938 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11942 bool Player::IsActiveQuest( uint32 quest_id ) const
11944 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11946 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11949 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11951 Object *pObject;
11952 QuestRelations* pObjectQR;
11953 QuestRelations* pObjectQIR;
11955 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11956 if( pCreature )
11958 pObject = (Object*)pCreature;
11959 pObjectQR = &objmgr.mCreatureQuestRelations;
11960 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11962 else
11964 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11965 if( pGameObject )
11967 pObject = (Object*)pGameObject;
11968 pObjectQR = &objmgr.mGOQuestRelations;
11969 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11971 else
11972 return NULL;
11975 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11976 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11978 if (itr->second == nextQuestID)
11979 return objmgr.GetQuestTemplate(nextQuestID);
11982 return NULL;
11985 bool Player::CanSeeStartQuest( Quest const *pQuest )
11987 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11988 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11989 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11990 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11992 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11995 return false;
11998 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12000 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12001 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12002 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12003 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12004 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12005 && SatisfyQuestDay( pQuest, msg );
12008 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12010 if( !SatisfyQuestLog( msg ) )
12011 return false;
12013 uint32 srcitem = pQuest->GetSrcItemId();
12014 if( srcitem > 0 )
12016 uint32 count = pQuest->GetSrcItemCount();
12017 ItemPosCountVec dest;
12018 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12020 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12021 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12022 return true;
12023 else if( msg != EQUIP_ERR_OK )
12025 SendEquipError( msg, NULL, NULL );
12026 return false;
12029 return true;
12032 bool Player::CanCompleteQuest( uint32 quest_id )
12034 if( quest_id )
12036 QuestStatusData& q_status = mQuestStatus[quest_id];
12037 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12038 return false; // not allow re-complete quest
12040 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12042 if(!qInfo)
12043 return false;
12045 // auto complete quest
12046 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12047 return true;
12049 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12052 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12054 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12056 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12057 return false;
12061 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12063 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12065 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12066 continue;
12068 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12069 return false;
12073 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12074 return false;
12076 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12077 return false;
12079 if ( qInfo->GetRewOrReqMoney() < 0 )
12081 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12082 return false;
12085 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12086 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12087 return false;
12089 return true;
12092 return false;
12095 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12097 // Solve problem that player don't have the quest and try complete it.
12098 // if repeatable she must be able to complete event if player don't have it.
12099 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12100 if( !CanTakeQuest(pQuest, false) )
12101 return false;
12103 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12104 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12105 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12106 return false;
12108 if( !CanRewardQuest(pQuest, false) )
12109 return false;
12111 return true;
12114 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12116 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12117 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12118 return false;
12120 // daily quest can't be rewarded (10 daily quest already completed)
12121 if(!SatisfyQuestDay(pQuest,true))
12122 return false;
12124 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12125 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12126 return false;
12128 // prevent receive reward with quest items in bank
12129 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12131 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12133 if( pQuest->ReqItemCount[i]!= 0 &&
12134 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12136 if(msg)
12137 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12138 return false;
12143 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12144 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12145 return false;
12147 return true;
12150 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12152 // prevent receive reward with quest items in bank or for not completed quest
12153 if(!CanRewardQuest(pQuest,msg))
12154 return false;
12156 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12158 if( pQuest->RewChoiceItemId[reward] )
12160 ItemPosCountVec dest;
12161 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12162 if( res != EQUIP_ERR_OK )
12164 SendEquipError( res, NULL, NULL );
12165 return false;
12170 if ( pQuest->GetRewItemsCount() > 0 )
12172 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12174 if( pQuest->RewItemId[i] )
12176 ItemPosCountVec dest;
12177 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12178 if( res != EQUIP_ERR_OK )
12180 SendEquipError( res, NULL, NULL );
12181 return false;
12187 return true;
12190 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12192 uint16 log_slot = FindQuestSlot( 0 );
12193 assert(log_slot < MAX_QUEST_LOG_SIZE);
12195 uint32 quest_id = pQuest->GetQuestId();
12197 // if not exist then created with set uState==NEW and rewarded=false
12198 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12199 if (questStatusData.uState != QUEST_NEW)
12200 questStatusData.uState = QUEST_CHANGED;
12202 // check for repeatable quests status reset
12203 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12204 questStatusData.m_explored = false;
12206 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12208 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12209 questStatusData.m_itemcount[i] = 0;
12212 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12214 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12215 questStatusData.m_creatureOrGOcount[i] = 0;
12218 GiveQuestSourceItem( pQuest );
12219 AdjustQuestReqItemCount( pQuest );
12221 if( pQuest->GetRepObjectiveFaction() )
12222 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12224 uint32 qtime = 0;
12225 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12227 uint32 limittime = pQuest->GetLimitTime();
12229 // shared timed quest
12230 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12231 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12233 AddTimedQuest( quest_id );
12234 questStatusData.m_timer = limittime * 1000;
12235 qtime = static_cast<uint32>(time(NULL)) + limittime;
12237 else
12238 questStatusData.m_timer = 0;
12240 SetQuestSlot(log_slot, quest_id, qtime);
12242 //starting initial quest script
12243 if(questGiver && pQuest->GetQuestStartScript()!=0)
12244 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12246 UpdateForQuestsGO();
12249 void Player::CompleteQuest( uint32 quest_id )
12251 if( quest_id )
12253 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12255 uint16 log_slot = FindQuestSlot( quest_id );
12256 if( log_slot < MAX_QUEST_LOG_SIZE)
12257 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12259 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12261 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12262 RewardQuest(qInfo,0,this,false);
12263 else
12264 SendQuestComplete( quest_id );
12269 void Player::IncompleteQuest( uint32 quest_id )
12271 if( quest_id )
12273 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12275 uint16 log_slot = FindQuestSlot( quest_id );
12276 if( log_slot < MAX_QUEST_LOG_SIZE)
12277 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12281 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12283 uint32 quest_id = pQuest->GetQuestId();
12285 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12287 if ( pQuest->ReqItemId[i] )
12288 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12291 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12292 // SetTimedQuest( 0 );
12293 m_timedquests.erase(pQuest->GetQuestId());
12295 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12297 if( pQuest->RewChoiceItemId[reward] )
12299 ItemPosCountVec dest;
12300 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12302 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12303 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12308 if ( pQuest->GetRewItemsCount() > 0 )
12310 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12312 if( pQuest->RewItemId[i] )
12314 ItemPosCountVec dest;
12315 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12317 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12318 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12324 RewardReputation( pQuest );
12326 if( pQuest->GetRewSpellCast() > 0 )
12327 CastSpell( this, pQuest->GetRewSpellCast(), true);
12328 else if( pQuest->GetRewSpell() > 0)
12329 CastSpell( this, pQuest->GetRewSpell(), true);
12331 uint16 log_slot = FindQuestSlot( quest_id );
12332 if( log_slot < MAX_QUEST_LOG_SIZE)
12333 SetQuestSlot(log_slot,0);
12335 QuestStatusData& q_status = mQuestStatus[quest_id];
12337 // Not give XP in case already completed once repeatable quest
12338 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12340 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12341 GiveXP( XP , NULL );
12342 else
12343 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12345 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12346 ModifyMoney( pQuest->GetRewOrReqMoney() );
12348 // honor reward
12349 if(pQuest->GetRewHonorableKills())
12350 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12352 // title reward
12353 if(pQuest->GetCharTitleId())
12355 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12356 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12359 // Send reward mail
12360 if(pQuest->GetRewMailTemplateId())
12362 MailMessageType mailType;
12363 uint32 senderGuidOrEntry;
12364 switch(questGiver->GetTypeId())
12366 case TYPEID_UNIT:
12367 mailType = MAIL_CREATURE;
12368 senderGuidOrEntry = questGiver->GetEntry();
12369 break;
12370 case TYPEID_GAMEOBJECT:
12371 mailType = MAIL_GAMEOBJECT;
12372 senderGuidOrEntry = questGiver->GetEntry();
12373 break;
12374 case TYPEID_ITEM:
12375 mailType = MAIL_ITEM;
12376 senderGuidOrEntry = questGiver->GetEntry();
12377 break;
12378 case TYPEID_PLAYER:
12379 mailType = MAIL_NORMAL;
12380 senderGuidOrEntry = questGiver->GetGUIDLow();
12381 break;
12382 default:
12383 mailType = MAIL_NORMAL;
12384 senderGuidOrEntry = GetGUIDLow();
12385 break;
12388 Loot questMailLoot;
12390 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12392 // fill mail
12393 MailItemsInfo mi; // item list preparing
12395 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12397 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12399 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12401 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12402 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12407 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12409 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12411 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12413 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12414 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12419 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12422 if(pQuest->IsDaily())
12424 SetDailyQuestStatus(quest_id);
12425 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12428 if ( !pQuest->IsRepeatable() )
12429 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12430 else
12431 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12433 q_status.m_rewarded = true;
12435 if(announce)
12436 SendQuestReward( pQuest, XP, questGiver );
12438 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12439 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12440 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12443 void Player::FailQuest( uint32 quest_id )
12445 if( quest_id )
12447 IncompleteQuest( quest_id );
12449 uint16 log_slot = FindQuestSlot( quest_id );
12450 if( log_slot < MAX_QUEST_LOG_SIZE)
12452 SetQuestSlotTimer(log_slot, 1 );
12453 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12455 SendQuestFailed( quest_id );
12459 void Player::FailTimedQuest( uint32 quest_id )
12461 if( quest_id )
12463 QuestStatusData& q_status = mQuestStatus[quest_id];
12465 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12466 q_status.m_timer = 0;
12468 IncompleteQuest( quest_id );
12470 uint16 log_slot = FindQuestSlot( quest_id );
12471 if( log_slot < MAX_QUEST_LOG_SIZE)
12473 SetQuestSlotTimer(log_slot, 1 );
12474 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12476 SendQuestTimerFailed( quest_id );
12480 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12482 int32 zoneOrSort = qInfo->GetZoneOrSort();
12483 int32 skillOrClass = qInfo->GetSkillOrClass();
12485 // skip zone zoneOrSort and 0 case skillOrClass
12486 if( zoneOrSort >= 0 && skillOrClass == 0 )
12487 return true;
12489 int32 questSort = -zoneOrSort;
12490 uint8 reqSortClass = ClassByQuestSort(questSort);
12492 // check class sort cases in zoneOrSort
12493 if( reqSortClass != 0 && getClass() != reqSortClass)
12495 if( msg )
12496 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12497 return false;
12500 // check class
12501 if( skillOrClass < 0 )
12503 uint8 reqClass = -int32(skillOrClass);
12504 if(getClass() != reqClass)
12506 if( msg )
12507 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12508 return false;
12511 // check skill
12512 else if( skillOrClass > 0 )
12514 uint32 reqSkill = skillOrClass;
12515 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12517 if( msg )
12518 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12519 return false;
12523 return true;
12526 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12528 if( getLevel() < qInfo->GetMinLevel() )
12530 if( msg )
12531 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12532 return false;
12534 return true;
12537 bool Player::SatisfyQuestLog( bool msg )
12539 // exist free slot
12540 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12541 return true;
12543 if( msg )
12545 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12546 GetSession()->SendPacket( &data );
12547 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12549 return false;
12552 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12554 // No previous quest (might be first quest in a series)
12555 if( qInfo->prevQuests.empty())
12556 return true;
12558 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12560 uint32 prevId = abs(*iter);
12562 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12563 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12565 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12567 // If any of the positive previous quests completed, return true
12568 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12570 // skip one-from-all exclusive group
12571 if(qPrevInfo->GetExclusiveGroup() >= 0)
12572 return true;
12574 // each-from-all exclusive group ( < 0)
12575 // can be start if only all quests in prev quest exclusive group completed and rewarded
12576 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12577 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12579 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12581 for(; iter != end; ++iter)
12583 uint32 exclude_Id = iter->second;
12585 // skip checked quest id, only state of other quests in group is interesting
12586 if(exclude_Id == prevId)
12587 continue;
12589 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12591 // alternative quest from group also must be completed and rewarded(reported)
12592 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12594 if( msg )
12595 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12596 return false;
12599 return true;
12601 // If any of the negative previous quests active, return true
12602 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12603 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12605 // skip one-from-all exclusive group
12606 if(qPrevInfo->GetExclusiveGroup() >= 0)
12607 return true;
12609 // each-from-all exclusive group ( < 0)
12610 // can be start if only all quests in prev quest exclusive group active
12611 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12612 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12614 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12616 for(; iter != end; ++iter)
12618 uint32 exclude_Id = iter->second;
12620 // skip checked quest id, only state of other quests in group is interesting
12621 if(exclude_Id == prevId)
12622 continue;
12624 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12626 // alternative quest from group also must be active
12627 if( i_exstatus == mQuestStatus.end() ||
12628 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12629 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12631 if( msg )
12632 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12633 return false;
12636 return true;
12641 // Has only positive prev. quests in non-rewarded state
12642 // and negative prev. quests in non-active state
12643 if( msg )
12644 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12646 return false;
12649 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12651 uint32 reqraces = qInfo->GetRequiredRaces();
12652 if ( reqraces == 0 )
12653 return true;
12654 if( (reqraces & getRaceMask()) == 0 )
12656 if( msg )
12657 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12658 return false;
12660 return true;
12663 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12665 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12666 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12668 if( msg )
12669 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12670 return false;
12673 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12674 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12676 if( msg )
12677 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12678 return false;
12681 return true;
12684 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12686 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12687 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12689 if( msg )
12690 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12691 return false;
12693 return true;
12696 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12698 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12700 if( msg )
12701 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12702 return false;
12704 return true;
12707 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12709 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12710 if(qInfo->GetExclusiveGroup() <= 0)
12711 return true;
12713 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12714 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12716 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12718 for(; iter != end; ++iter)
12720 uint32 exclude_Id = iter->second;
12722 // skip checked quest id, only state of other quests in group is interesting
12723 if(exclude_Id == qInfo->GetQuestId())
12724 continue;
12726 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12728 // alternative quest already started or completed
12729 if( i_exstatus != mQuestStatus.end()
12730 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12732 if( msg )
12733 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12734 return false;
12737 return true;
12740 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12742 if(!qInfo->GetNextQuestInChain())
12743 return true;
12745 // next quest in chain already started or completed
12746 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12747 if( itr != mQuestStatus.end()
12748 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12750 if( msg )
12751 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12752 return false;
12755 // check for all quests further up the chain
12756 // only necessary if there are quest chains with more than one quest that can be skipped
12757 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12758 return true;
12761 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12763 // No previous quest in chain
12764 if( qInfo->prevChainQuests.empty())
12765 return true;
12767 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12769 uint32 prevId = *iter;
12771 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12773 if( i_prevstatus != mQuestStatus.end() )
12775 // If any of the previous quests in chain active, return false
12776 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12777 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12779 if( msg )
12780 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12781 return false;
12785 // check for all quests further down the chain
12786 // only necessary if there are quest chains with more than one quest that can be skipped
12787 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12788 // return false;
12791 // No previous quest in chain active
12792 return true;
12795 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12797 if(!qInfo->IsDaily())
12798 return true;
12800 bool have_slot = false;
12801 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12803 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12804 if(qInfo->GetQuestId()==id)
12805 return false;
12807 if(!id)
12808 have_slot = true;
12811 if(!have_slot)
12813 if( msg )
12814 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12815 return false;
12818 return true;
12821 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12823 uint32 srcitem = pQuest->GetSrcItemId();
12824 if( srcitem > 0 )
12826 uint32 count = pQuest->GetSrcItemCount();
12827 if( count <= 0 )
12828 count = 1;
12830 ItemPosCountVec dest;
12831 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12832 if( msg == EQUIP_ERR_OK )
12834 Item * item = StoreNewItem(dest, srcitem, true);
12835 SendNewItem(item, count, true, false);
12836 return true;
12838 // player already have max amount required item, just report success
12839 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12840 return true;
12841 else
12842 SendEquipError( msg, NULL, NULL );
12843 return false;
12846 return true;
12849 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12851 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12852 if( qInfo )
12854 uint32 srcitem = qInfo->GetSrcItemId();
12855 if( srcitem > 0 )
12857 uint32 count = qInfo->GetSrcItemCount();
12858 if( count <= 0 )
12859 count = 1;
12861 // exist one case when destroy source quest item not possible:
12862 // non un-equippable item (equipped non-empty bag, for example)
12863 uint8 res = CanUnequipItems(srcitem,count);
12864 if(res != EQUIP_ERR_OK)
12866 if(msg)
12867 SendEquipError( res, NULL, NULL );
12868 return false;
12871 DestroyItemCount(srcitem, count, true, true);
12874 return true;
12877 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12879 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12880 if( qInfo )
12882 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12883 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12884 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12885 && !qInfo->IsRepeatable() )
12886 return itr->second.m_rewarded;
12888 return false;
12890 return false;
12893 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12895 if( quest_id )
12897 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12898 if( itr != mQuestStatus.end() )
12899 return itr->second.m_status;
12901 return QUEST_STATUS_NONE;
12904 bool Player::CanShareQuest(uint32 quest_id) const
12906 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12907 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12909 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12910 if( itr != mQuestStatus.end() )
12911 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12913 return false;
12916 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12918 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12919 if( qInfo )
12921 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12923 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12924 m_timedquests.erase(qInfo->GetQuestId());
12927 QuestStatusData& q_status = mQuestStatus[quest_id];
12929 q_status.m_status = status;
12930 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12933 UpdateForQuestsGO();
12936 // not used in MaNGOS, but used in scripting code
12937 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12939 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12940 if( !qInfo )
12941 return 0;
12943 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12944 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12945 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12947 return 0;
12950 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12952 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12954 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12956 uint32 reqitemcount = pQuest->ReqItemCount[i];
12957 if( reqitemcount != 0 )
12959 uint32 quest_id = pQuest->GetQuestId();
12960 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12962 QuestStatusData& q_status = mQuestStatus[quest_id];
12963 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12964 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12970 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12972 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12973 if ( GetQuestSlotQuestId(i) == quest_id )
12974 return i;
12976 return MAX_QUEST_LOG_SIZE;
12979 void Player::AreaExploredOrEventHappens( uint32 questId )
12981 if( questId )
12983 uint16 log_slot = FindQuestSlot( questId );
12984 if( log_slot < MAX_QUEST_LOG_SIZE)
12986 QuestStatusData& q_status = mQuestStatus[questId];
12988 if(!q_status.m_explored)
12990 q_status.m_explored = true;
12991 if (q_status.uState != QUEST_NEW)
12992 q_status.uState = QUEST_CHANGED;
12995 if( CanCompleteQuest( questId ) )
12996 CompleteQuest( questId );
13000 //not used in mangosd, function for external script library
13001 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13003 if( Group *pGroup = GetGroup() )
13005 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13007 Player *pGroupGuy = itr->getSource();
13009 // for any leave or dead (with not released body) group member at appropriate distance
13010 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13011 pGroupGuy->AreaExploredOrEventHappens(questId);
13014 else
13015 AreaExploredOrEventHappens(questId);
13018 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13020 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13022 uint32 questid = GetQuestSlotQuestId(i);
13023 if ( questid == 0 )
13024 continue;
13026 QuestStatusData& q_status = mQuestStatus[questid];
13028 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13029 continue;
13031 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13032 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13033 continue;
13035 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13037 uint32 reqitem = qInfo->ReqItemId[j];
13038 if ( reqitem == entry )
13040 uint32 reqitemcount = qInfo->ReqItemCount[j];
13041 uint32 curitemcount = q_status.m_itemcount[j];
13042 if ( curitemcount < reqitemcount )
13044 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13045 q_status.m_itemcount[j] += additemcount;
13046 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13048 SendQuestUpdateAddItem( qInfo, j, additemcount );
13050 if ( CanCompleteQuest( questid ) )
13051 CompleteQuest( questid );
13052 return;
13056 UpdateForQuestsGO();
13057 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13060 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13062 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13064 uint32 questid = GetQuestSlotQuestId(i);
13065 if(!questid)
13066 continue;
13067 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13068 if ( !qInfo )
13069 continue;
13070 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13071 continue;
13073 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13075 uint32 reqitem = qInfo->ReqItemId[j];
13076 if ( reqitem == entry )
13078 QuestStatusData& q_status = mQuestStatus[questid];
13080 uint32 reqitemcount = qInfo->ReqItemCount[j];
13081 uint32 curitemcount;
13082 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13083 curitemcount = q_status.m_itemcount[j];
13084 else
13085 curitemcount = GetItemCount(entry,true);
13086 if ( curitemcount < reqitemcount + count )
13088 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13089 q_status.m_itemcount[j] = curitemcount - remitemcount;
13090 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13092 IncompleteQuest( questid );
13094 return;
13098 UpdateForQuestsGO();
13101 void Player::KilledMonster( uint32 entry, uint64 guid )
13103 uint32 addkillcount = 1;
13104 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13105 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13107 uint32 questid = GetQuestSlotQuestId(i);
13108 if(!questid)
13109 continue;
13111 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13112 if( !qInfo )
13113 continue;
13114 // just if !ingroup || !noraidgroup || raidgroup
13115 QuestStatusData& q_status = mQuestStatus[questid];
13116 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13118 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13120 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13122 // skip GO activate objective or none
13123 if(qInfo->ReqCreatureOrGOId[j] <=0)
13124 continue;
13126 // skip Cast at creature objective
13127 if(qInfo->ReqSpell[j] !=0 )
13128 continue;
13130 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13132 if ( reqkill == entry )
13134 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13135 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13136 if ( curkillcount < reqkillcount )
13138 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13139 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13141 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13143 if ( CanCompleteQuest( questid ) )
13144 CompleteQuest( questid );
13146 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13147 continue;
13155 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13157 bool isCreature = IS_CREATURE_GUID(guid);
13159 uint32 addCastCount = 1;
13160 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13162 uint32 questid = GetQuestSlotQuestId(i);
13163 if(!questid)
13164 continue;
13166 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13167 if ( !qInfo )
13168 continue;
13170 QuestStatusData& q_status = mQuestStatus[questid];
13172 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13174 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13176 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13178 // skip kill creature objective (0) or wrong spell casts
13179 if(qInfo->ReqSpell[j] != spell_id )
13180 continue;
13182 uint32 reqTarget = 0;
13184 if(isCreature)
13186 // creature activate objectives
13187 if(qInfo->ReqCreatureOrGOId[j] > 0)
13188 // checked at quest_template loading
13189 reqTarget = qInfo->ReqCreatureOrGOId[j];
13191 else
13193 // GO activate objective
13194 if(qInfo->ReqCreatureOrGOId[j] < 0)
13195 // checked at quest_template loading
13196 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13199 // other not this creature/GO related objectives
13200 if( reqTarget != entry )
13201 continue;
13203 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13204 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13205 if ( curCastCount < reqCastCount )
13207 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13208 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13210 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13213 if ( CanCompleteQuest( questid ) )
13214 CompleteQuest( questid );
13216 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13217 break;
13224 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13226 uint32 addTalkCount = 1;
13227 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13229 uint32 questid = GetQuestSlotQuestId(i);
13230 if(!questid)
13231 continue;
13233 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13234 if ( !qInfo )
13235 continue;
13237 QuestStatusData& q_status = mQuestStatus[questid];
13239 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13241 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13243 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13245 // skip spell casts and Gameobject objectives
13246 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13247 continue;
13249 uint32 reqTarget = 0;
13251 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13252 // checked at quest_template loading
13253 reqTarget = qInfo->ReqCreatureOrGOId[j];
13254 else
13255 continue;
13257 if ( reqTarget == entry )
13259 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13260 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13261 if ( curTalkCount < reqTalkCount )
13263 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13264 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13266 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13268 if ( CanCompleteQuest( questid ) )
13269 CompleteQuest( questid );
13271 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13272 continue;
13280 void Player::MoneyChanged( uint32 count )
13282 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13284 uint32 questid = GetQuestSlotQuestId(i);
13285 if (!questid)
13286 continue;
13288 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13289 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13291 QuestStatusData& q_status = mQuestStatus[questid];
13293 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13295 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13297 if ( CanCompleteQuest( questid ) )
13298 CompleteQuest( questid );
13301 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13303 if(int32(count) < -qInfo->GetRewOrReqMoney())
13304 IncompleteQuest( questid );
13310 bool Player::HasQuestForItem( uint32 itemid ) const
13312 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13314 QuestStatusData const& q_status = i->second;
13316 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13318 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13319 if(!qinfo)
13320 continue;
13322 // hide quest if player is in raid-group and quest is no raid quest
13323 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13324 continue;
13326 // There should be no mixed ReqItem/ReqSource drop
13327 // This part for ReqItem drop
13328 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13330 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13331 return true;
13333 // This part - for ReqSource
13334 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13336 // examined item is a source item
13337 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13339 uint32 idx = qinfo->ReqSourceRef[j]-1;
13341 // total count of created ReqItems and SourceItems is less than ReqItemCount
13342 if(qinfo->ReqItemId[idx] != 0 &&
13343 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13344 return true;
13346 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13347 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13349 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13350 return true;
13352 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13353 else if(qinfo->ReqSpell[idx] != 0)
13355 // not casted and need more reagents/item for use.
13356 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13357 return true;
13363 return false;
13366 void Player::SendQuestComplete( uint32 quest_id )
13368 if( quest_id )
13370 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13371 data << uint32(quest_id);
13372 GetSession()->SendPacket( &data );
13373 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13377 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13379 uint32 questid = pQuest->GetQuestId();
13380 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13381 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13382 data << uint32(questid);
13384 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13386 data << uint32(XP);
13387 data << uint32(pQuest->GetRewOrReqMoney());
13389 else
13391 data << uint32(0);
13392 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13395 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13396 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13397 GetSession()->SendPacket( &data );
13399 if (pQuest->GetQuestCompleteScript() != 0)
13400 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13403 void Player::SendQuestFailed( uint32 quest_id )
13405 if( quest_id )
13407 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13408 data << quest_id;
13409 data << uint32(0); // failed reason (4 for inventory is full)
13410 GetSession()->SendPacket( &data );
13411 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13415 void Player::SendQuestTimerFailed( uint32 quest_id )
13417 if( quest_id )
13419 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13420 data << quest_id;
13421 GetSession()->SendPacket( &data );
13422 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13426 void Player::SendCanTakeQuestResponse( uint32 msg )
13428 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13429 data << uint32(msg);
13430 GetSession()->SendPacket( &data );
13431 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13434 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13436 if( pPlayer )
13438 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13439 data << uint64(pPlayer->GetGUID());
13440 data << uint8(msg); // valid values: 0-8
13441 GetSession()->SendPacket( &data );
13442 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13446 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13448 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13449 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13450 //data << pQuest->ReqItemId[item_idx];
13451 //data << count;
13452 GetSession()->SendPacket( &data );
13455 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13457 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13459 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13460 if (entry < 0)
13461 // client expected gameobject template id in form (id|0x80000000)
13462 entry = (-entry) | 0x80000000;
13464 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13465 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13466 data << uint32(pQuest->GetQuestId());
13467 data << uint32(entry);
13468 data << uint32(old_count + add_count);
13469 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13470 data << uint64(guid);
13471 GetSession()->SendPacket(&data);
13473 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13474 if( log_slot < MAX_QUEST_LOG_SIZE)
13475 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13478 /*********************************************************/
13479 /*** LOAD SYSTEM ***/
13480 /*********************************************************/
13482 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13484 bool delete_result = true;
13485 if(!result)
13487 // 0 1 2 3 4 5 6 7 8 9
13488 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13489 if(!result) return false;
13491 else delete_result = false;
13493 Field *fields = result->Fetch();
13495 if(!LoadValues( fields[1].GetString()))
13497 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13498 if(delete_result) delete result;
13499 return false;
13502 // overwrite possible wrong/corrupted guid
13503 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13505 m_name = fields[2].GetCppString();
13507 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13508 SetMapId(fields[6].GetUInt32());
13509 // the instance id is not needed at character enum
13511 m_Played_time[0] = fields[7].GetUInt32();
13512 m_Played_time[1] = fields[8].GetUInt32();
13514 m_atLoginFlags = fields[9].GetUInt32();
13516 // I don't see these used anywhere ..
13517 /*_LoadGroup();
13519 _LoadBoundInstances();*/
13521 if (delete_result) delete result;
13523 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13524 m_items[i] = NULL;
13526 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13527 m_deathState = DEAD;
13529 return true;
13532 void Player::_LoadDeclinedNames(QueryResult* result)
13534 if(!result)
13535 return;
13537 if(m_declinedname)
13538 delete m_declinedname;
13540 m_declinedname = new DeclinedName;
13541 Field *fields = result->Fetch();
13542 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13543 m_declinedname->name[i] = fields[i].GetCppString();
13545 delete result;
13548 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13550 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13551 if(!result)
13552 return false;
13554 Field *fields = result->Fetch();
13556 x = fields[0].GetFloat();
13557 y = fields[1].GetFloat();
13558 z = fields[2].GetFloat();
13559 o = fields[3].GetFloat();
13560 mapid = fields[4].GetUInt32();
13561 in_flight = !fields[5].GetCppString().empty();
13563 delete result;
13564 return true;
13567 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13569 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13570 if( !result )
13571 return false;
13573 Field *fields = result->Fetch();
13575 data = StrSplit(fields[0].GetCppString(), " ");
13577 delete result;
13579 return true;
13582 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13584 if(index >= data.size())
13585 return 0;
13587 return (uint32)atoi(data[index].c_str());
13590 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13592 float result;
13593 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13594 memcpy(&result, &temp, sizeof(result));
13596 return result;
13599 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13601 Tokens data;
13602 if(!LoadValuesArrayFromDB(data,guid))
13603 return 0;
13605 return GetUInt32ValueFromArray(data,index);
13608 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13610 float result;
13611 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13612 memcpy(&result, &temp, sizeof(result));
13614 return result;
13617 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13619 //// 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
13620 //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);
13621 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13623 if(!result)
13625 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13626 return false;
13629 Field *fields = result->Fetch();
13631 uint32 dbAccountId = fields[1].GetUInt32();
13633 // check if the character's account in the db and the logged in account match.
13634 // player should be able to load/delete character only with correct account!
13635 if( dbAccountId != GetSession()->GetAccountId() )
13637 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13638 delete result;
13639 return false;
13642 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13644 m_name = fields[3].GetCppString();
13646 // check name limitations
13647 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13649 delete result;
13650 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13651 return false;
13654 if(!LoadValues( fields[2].GetString()))
13656 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13657 delete result;
13658 return false;
13661 // overwrite possible wrong/corrupted guid
13662 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13664 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13665 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13667 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13668 SetVisibleItemSlot(slot,NULL);
13670 if (m_items[slot])
13672 delete m_items[slot];
13673 m_items[slot] = NULL;
13677 // update money limits
13678 if(GetMoney() > MAX_MONEY_AMOUNT)
13679 SetMoney(MAX_MONEY_AMOUNT);
13681 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13682 outDebugValues();
13684 m_race = fields[4].GetUInt8();
13685 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13686 //Other way is to saves m_team into characters table.
13687 setFactionForRace(m_race);
13688 SetCharm(0);
13690 m_class = fields[5].GetUInt8();
13692 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13693 if(!info)
13695 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13696 delete result;
13697 return false;
13700 InitPrimaryProffesions(); // to max set before any spell loaded
13702 uint32 transGUID = fields[24].GetUInt32();
13703 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13704 SetMapId(fields[9].GetUInt32());
13705 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13707 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13709 // check arena teams integrity
13710 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13712 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13713 if(!arena_team_id)
13714 continue;
13716 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13717 if(at->HaveMember(GetGUID()))
13718 continue;
13720 // arena team not exist or not member, cleanup fields
13721 for(int j =0; j < 6; ++j)
13722 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13725 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13727 if(!IsPositionValid())
13729 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());
13731 SetMapId(info->mapId);
13732 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13734 transGUID = 0;
13736 m_movementInfo.t_x = 0.0f;
13737 m_movementInfo.t_y = 0.0f;
13738 m_movementInfo.t_z = 0.0f;
13739 m_movementInfo.t_o = 0.0f;
13742 // load the player's map here if it's not already loaded
13743 Map *map = GetMap();
13744 // since the player may not be bound to the map yet, make sure subsequent
13745 // getmap calls won't create new maps
13746 SetInstanceId(map->GetInstanceId());
13748 SaveRecallPosition();
13750 if (transGUID != 0)
13752 m_movementInfo.t_x = fields[20].GetFloat();
13753 m_movementInfo.t_y = fields[21].GetFloat();
13754 m_movementInfo.t_z = fields[22].GetFloat();
13755 m_movementInfo.t_o = fields[23].GetFloat();
13757 if( !MaNGOS::IsValidMapCoord(
13758 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13759 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13760 // transport size limited
13761 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13763 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13764 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13765 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13767 SetMapId(info->mapId);
13768 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13770 m_movementInfo.t_x = 0.0f;
13771 m_movementInfo.t_y = 0.0f;
13772 m_movementInfo.t_z = 0.0f;
13773 m_movementInfo.t_o = 0.0f;
13775 transGUID = 0;
13779 if (transGUID != 0)
13781 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13783 if( (*iter)->GetGUIDLow() == transGUID)
13785 m_transport = *iter;
13786 m_transport->AddPassenger(this);
13787 SetMapId(m_transport->GetMapId());
13788 break;
13792 if(!m_transport)
13794 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13795 guid,transGUID);
13797 SetMapId(info->mapId);
13798 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13800 m_movementInfo.t_x = 0.0f;
13801 m_movementInfo.t_y = 0.0f;
13802 m_movementInfo.t_z = 0.0f;
13803 m_movementInfo.t_o = 0.0f;
13805 transGUID = 0;
13809 time_t now = time(NULL);
13810 time_t logoutTime = time_t(fields[16].GetUInt64());
13812 // since last logout (in seconds)
13813 uint64 time_diff = uint64(now - logoutTime);
13815 // set value, including drunk invisibility detection
13816 // calculate sobering. after 15 minutes logged out, the player will be sober again
13817 float soberFactor;
13818 if(time_diff > 15*MINUTE)
13819 soberFactor = 0;
13820 else
13821 soberFactor = 1-time_diff/(15.0f*MINUTE);
13822 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13823 SetDrunkValue(newDrunkenValue);
13825 m_rest_bonus = fields[15].GetFloat();
13826 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13827 float bubble0 = 0.031;
13828 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13829 float bubble1 = 0.125;
13831 if((int32)fields[16].GetUInt32() > 0)
13833 float bubble = fields[17].GetUInt32() > 0
13834 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13835 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13837 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13840 m_cinematic = fields[12].GetUInt32();
13841 m_Played_time[0]= fields[13].GetUInt32();
13842 m_Played_time[1]= fields[14].GetUInt32();
13844 m_resetTalentsCost = fields[18].GetUInt32();
13845 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13847 // reserve some flags
13848 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13850 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13851 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13853 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13855 uint32 extraflags = fields[25].GetUInt32();
13857 m_stableSlots = fields[26].GetUInt32();
13858 if(m_stableSlots > 4)
13860 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
13861 m_stableSlots = 4;
13864 m_atLoginFlags = fields[27].GetUInt32();
13866 // Honor system
13867 // Update Honor kills data
13868 m_lastHonorUpdateTime = logoutTime;
13869 UpdateHonorFields();
13871 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13872 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13873 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13875 std::string taxi_nodes = fields[31].GetCppString();
13877 delete result;
13879 // clear channel spell data (if saved at channel spell casting)
13880 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13881 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13883 // clear charm/summon related fields
13884 SetUInt64Value(UNIT_FIELD_CHARM,0);
13885 SetUInt64Value(UNIT_FIELD_SUMMON,0);
13886 SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
13887 SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
13888 SetUInt64Value(UNIT_FIELD_CREATEDBY,0);
13890 // reset some aura modifiers before aura apply
13891 SetUInt64Value(PLAYER_FARSIGHT, 0);
13892 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
13893 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
13895 // reset skill modifiers and set correct unlearn flags
13896 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
13898 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
13900 // set correct unlearn bit
13901 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
13902 if(!id) continue;
13904 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
13905 if(!pSkill) continue;
13907 // enable unlearn button for primary professions only
13908 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
13909 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
13910 else
13911 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
13914 // make sure the unit is considered out of combat for proper loading
13915 ClearInCombat();
13917 // make sure the unit is considered not in duel for proper loading
13918 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
13919 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
13921 // remember loaded power/health values to restore after stats initialization and modifier applying
13922 uint32 savedHealth = GetHealth();
13923 uint32 savedPower[MAX_POWERS];
13924 for(uint32 i = 0; i < MAX_POWERS; ++i)
13925 savedPower[i] = GetPower(Powers(i));
13927 // reset stats before loading any modifiers
13928 InitStatsForLevel();
13929 InitTaxiNodesForLevel();
13930 InitGlyphsForLevel();
13932 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13934 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13935 //_LoadMail();
13937 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
13939 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13940 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13941 m_deathState = DEAD;
13943 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
13945 // after spell load
13946 InitTalentForLevel();
13947 learnSkillRewardedSpells();
13949 // after spell load, learn rewarded spell if need also
13950 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
13951 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
13953 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
13955 // must be before inventory (some items required reputation check)
13956 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
13958 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
13960 // update items with duration and realtime
13961 UpdateItemDuration(time_diff, true);
13963 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
13965 // unread mails and next delivery time, actual mails not loaded
13966 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
13968 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
13970 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13971 return false;
13973 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13974 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13975 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
13977 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << curTitle))
13978 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
13981 // Not finish taxi flight path
13982 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
13984 // problems with taxi path loading
13985 TaxiNodesEntry const* nodeEntry = NULL;
13986 if(uint32 node_id = m_taxi.GetTaxiSource())
13987 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13989 if(!nodeEntry) // don't know taxi start node, to homebind
13991 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13992 SetMapId(m_homebindMapId);
13993 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
13994 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13996 else // have start node, to it
13998 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13999 SetMapId(nodeEntry->map_id);
14000 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14001 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14003 m_taxi.ClearTaxiDestinations();
14005 else if(uint32 node_id = m_taxi.GetTaxiSource())
14007 // save source node as recall coord to prevent recall and fall from sky
14008 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14009 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14010 m_recallMap = nodeEntry->map_id;
14011 m_recallX = nodeEntry->x;
14012 m_recallY = nodeEntry->y;
14013 m_recallZ = nodeEntry->z;
14015 // flight will started later
14018 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14020 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14021 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14022 if(!isAlive())
14023 RemoveAllAurasOnDeath();
14025 //apply all stat bonuses from items and auras
14026 SetCanModifyStats(true);
14027 UpdateAllStats();
14029 // restore remembered power/health values (but not more max values)
14030 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14031 for(uint32 i = 0; i < MAX_POWERS; ++i)
14032 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14034 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14035 outDebugValues();
14037 // GM state
14038 if(GetSession()->GetSecurity() > SEC_PLAYER)
14040 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14042 default:
14043 case 0: break; // disable
14044 case 1: SetGameMaster(true); break; // enable
14045 case 2: // save state
14046 if(extraflags & PLAYER_EXTRA_GM_ON)
14047 SetGameMaster(true);
14048 break;
14051 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14053 default:
14054 case 0: break; // disable
14055 case 1: SetAcceptTicket(true); break; // enable
14056 case 2: // save state
14057 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14058 SetAcceptTicket(true);
14059 break;
14062 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14064 default:
14065 case 0: break; // disable
14066 case 1: SetGMChat(true); break; // enable
14067 case 2: // save state
14068 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14069 SetGMChat(true);
14070 break;
14073 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14075 default:
14076 case 0: break; // disable
14077 case 1: SetAcceptWhispers(true); break; // enable
14078 case 2: // save state
14079 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14080 SetAcceptWhispers(true);
14081 break;
14085 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14087 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14088 m_achievementMgr.CheckAllAchievementCriteria();
14089 return true;
14092 bool Player::isAllowedToLoot(Creature* creature)
14094 if(Player* recipient = creature->GetLootRecipient())
14096 if (recipient == this)
14097 return true;
14098 if( Group* otherGroup = recipient->GetGroup())
14100 Group* thisGroup = GetGroup();
14101 if(!thisGroup)
14102 return false;
14103 return thisGroup == otherGroup;
14105 return false;
14107 else
14108 // prevent other players from looting if the recipient got disconnected
14109 return !creature->hasLootRecipient();
14112 void Player::_LoadActions(QueryResult *result)
14114 m_actionButtons.clear();
14116 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14118 if(result)
14122 Field *fields = result->Fetch();
14124 uint8 button = fields[0].GetUInt8();
14126 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14128 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14130 while( result->NextRow() );
14132 delete result;
14136 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14138 m_Auras.clear();
14139 for (int i = 0; i < TOTAL_AURAS; i++)
14140 m_modAuras[i].clear();
14142 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14144 if(result)
14148 Field *fields = result->Fetch();
14149 uint64 caster_guid = fields[0].GetUInt64();
14150 uint32 spellid = fields[1].GetUInt32();
14151 uint32 effindex = fields[2].GetUInt32();
14152 int32 damage = (int32)fields[3].GetUInt32();
14153 int32 maxduration = (int32)fields[4].GetUInt32();
14154 int32 remaintime = (int32)fields[5].GetUInt32();
14155 int32 remaincharges = (int32)fields[6].GetUInt32();
14157 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14158 if(!spellproto)
14160 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14161 continue;
14164 if(effindex >= 3)
14166 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14167 continue;
14170 // negative effects should continue counting down after logout
14171 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14173 if(remaintime <= int32(timediff))
14174 continue;
14176 remaintime -= timediff;
14179 // prevent wrong values of remaincharges
14180 if(spellproto->procCharges)
14182 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14183 remaincharges = spellproto->procCharges;
14185 else
14186 remaincharges = 0;
14188 //do not load single target auras (unless they were cast by the player)
14189 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14190 continue;
14192 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14193 if(!damage)
14194 damage = aura->GetModifier()->m_amount;
14195 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14196 AddAura(aura);
14198 while( result->NextRow() );
14200 delete result;
14203 if(m_class == CLASS_WARRIOR)
14204 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14207 void Player::LoadCorpse()
14209 if( isAlive() )
14211 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14213 else
14215 if(Corpse *corpse = GetCorpse())
14217 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14219 else
14221 //Prevent Dead Player login without corpse
14222 ResurrectPlayer(0.5f);
14227 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14229 //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());
14230 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14231 //NOTE: the "order by `bag`" is important because it makes sure
14232 //the bagMap is filled before items in the bags are loaded
14233 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14234 //expected to be equipped before offhand items (TODO: fixme)
14236 uint32 zone = GetZoneId();
14238 if (result)
14240 std::list<Item*> problematicItems;
14242 // prevent items from being added to the queue when stored
14243 m_itemUpdateQueueBlocked = true;
14246 Field *fields = result->Fetch();
14247 uint32 bag_guid = fields[1].GetUInt32();
14248 uint8 slot = fields[2].GetUInt8();
14249 uint32 item_guid = fields[3].GetUInt32();
14250 uint32 item_id = fields[4].GetUInt32();
14252 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14254 if(!proto)
14256 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14257 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14258 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14259 continue;
14262 Item *item = NewItemOrBag(proto);
14264 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14266 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14267 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14268 item->FSetState(ITEM_REMOVED);
14269 item->SaveToDB(); // it also deletes item object !
14270 continue;
14273 // not allow have in alive state item limited to another map/zone
14274 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14276 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14277 item->FSetState(ITEM_REMOVED);
14278 item->SaveToDB(); // it also deletes item object !
14279 continue;
14282 // "Conjured items disappear if you are logged out for more than 15 minutes"
14283 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14285 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14286 item->FSetState(ITEM_REMOVED);
14287 item->SaveToDB(); // it also deletes item object !
14288 continue;
14291 bool success = true;
14293 if (!bag_guid)
14295 // the item is not in a bag
14296 item->SetContainer( NULL );
14297 item->SetSlot(slot);
14299 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14301 ItemPosCountVec dest;
14302 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14303 item = StoreItem(dest, item, true);
14304 else
14305 success = false;
14307 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14309 uint16 dest;
14310 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14311 QuickEquipItem(dest, item);
14312 else
14313 success = false;
14315 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14317 ItemPosCountVec dest;
14318 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14319 item = BankItem(dest, item, true);
14320 else
14321 success = false;
14324 if(success)
14326 // store bags that may contain items in them
14327 if(item->IsBag() && IsBagPos(item->GetPos()))
14328 bagMap[item_guid] = (Bag*)item;
14331 else
14333 item->SetSlot(NULL_SLOT);
14334 // the item is in a bag, find the bag
14335 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14336 if(itr != bagMap.end())
14337 itr->second->StoreItem(slot, item, true );
14338 else
14339 success = false;
14342 // item's state may have changed after stored
14343 if (success)
14344 item->SetState(ITEM_UNCHANGED, this);
14345 else
14347 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);
14348 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14349 problematicItems.push_back(item);
14351 } while (result->NextRow());
14353 delete result;
14354 m_itemUpdateQueueBlocked = false;
14356 // send by mail problematic items
14357 while(!problematicItems.empty())
14359 // fill mail
14360 MailItemsInfo mi; // item list preparing
14362 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14364 Item* item = problematicItems.front();
14365 problematicItems.pop_front();
14367 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14370 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14372 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14375 //if(isAlive())
14376 _ApplyAllItemMods();
14379 // load mailed item which should receive current player
14380 void Player::_LoadMailedItems(Mail *mail)
14382 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14383 if(!result)
14384 return;
14388 Field *fields = result->Fetch();
14389 uint32 item_guid_low = fields[0].GetUInt32();
14390 uint32 item_template = fields[1].GetUInt32();
14392 mail->AddItem(item_guid_low, item_template);
14394 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14396 if(!proto)
14398 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);
14399 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14400 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14401 continue;
14404 Item *item = NewItemOrBag(proto);
14406 if(!item->LoadFromDB(item_guid_low, 0))
14408 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14409 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14410 item->FSetState(ITEM_REMOVED);
14411 item->SaveToDB(); // it also deletes item object !
14412 continue;
14415 AddMItem(item);
14416 } while (result->NextRow());
14418 delete result;
14421 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14423 //set a count of unread mails
14424 //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);
14425 if (resultUnread)
14427 Field *fieldMail = resultUnread->Fetch();
14428 unReadMails = fieldMail[0].GetUInt8();
14429 delete resultUnread;
14432 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14433 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14434 if (resultDelivery)
14436 Field *fieldMail = resultDelivery->Fetch();
14437 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14438 delete resultDelivery;
14442 void Player::_LoadMail()
14444 m_mail.clear();
14445 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14446 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());
14447 if(result)
14451 Field *fields = result->Fetch();
14452 Mail *m = new Mail;
14453 m->messageID = fields[0].GetUInt32();
14454 m->messageType = fields[1].GetUInt8();
14455 m->sender = fields[2].GetUInt32();
14456 m->receiver = fields[3].GetUInt32();
14457 m->subject = fields[4].GetCppString();
14458 m->itemTextId = fields[5].GetUInt32();
14459 bool has_items = fields[6].GetBool();
14460 m->expire_time = (time_t)fields[7].GetUInt64();
14461 m->deliver_time = (time_t)fields[8].GetUInt64();
14462 m->money = fields[9].GetUInt32();
14463 m->COD = fields[10].GetUInt32();
14464 m->checked = fields[11].GetUInt32();
14465 m->stationery = fields[12].GetUInt8();
14466 m->mailTemplateId = fields[13].GetInt16();
14468 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14470 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14471 m->mailTemplateId = 0;
14474 m->state = MAIL_STATE_UNCHANGED;
14476 if (has_items)
14477 _LoadMailedItems(m);
14479 m_mail.push_back(m);
14480 } while( result->NextRow() );
14481 delete result;
14483 m_mailsLoaded = true;
14486 void Player::LoadPet()
14488 //fixme: the pet should still be loaded if the player is not in world
14489 // just not added to the map
14490 if(IsInWorld())
14492 Pet *pet = new Pet;
14493 if(!pet->LoadPetFromDB(this,0,0,true))
14494 delete pet;
14498 void Player::_LoadQuestStatus(QueryResult *result)
14500 mQuestStatus.clear();
14502 uint32 slot = 0;
14504 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14505 //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());
14507 if(result)
14511 Field *fields = result->Fetch();
14513 uint32 quest_id = fields[0].GetUInt32();
14514 // used to be new, no delete?
14515 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14516 if( pQuest )
14518 // find or create
14519 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14521 uint32 qstatus = fields[1].GetUInt32();
14522 if(qstatus < MAX_QUEST_STATUS)
14523 questStatusData.m_status = QuestStatus(qstatus);
14524 else
14526 questStatusData.m_status = QUEST_STATUS_NONE;
14527 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14530 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14531 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14533 time_t quest_time = time_t(fields[4].GetUInt64());
14535 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14537 AddTimedQuest( quest_id );
14539 if (quest_time <= sWorld.GetGameTime())
14540 questStatusData.m_timer = 1;
14541 else
14542 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14544 else
14545 quest_time = 0;
14547 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14548 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14549 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14550 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14551 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14552 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14553 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14554 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14556 questStatusData.uState = QUEST_UNCHANGED;
14558 // add to quest log
14559 if( slot < MAX_QUEST_LOG_SIZE &&
14560 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14561 questStatusData.m_status==QUEST_STATUS_COMPLETE && !questStatusData.m_rewarded ) )
14563 SetQuestSlot(slot,quest_id,quest_time);
14565 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14566 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14568 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14569 if(questStatusData.m_creatureOrGOcount[idx])
14570 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14572 ++slot;
14575 if(questStatusData.m_rewarded)
14577 // learn rewarded spell if unknown
14578 learnQuestRewardedSpells(pQuest);
14580 // set rewarded title if any
14581 if(pQuest->GetCharTitleId())
14583 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14584 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
14588 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14591 while( result->NextRow() );
14593 delete result;
14596 // clear quest log tail
14597 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14598 SetQuestSlot(i,0);
14601 void Player::_LoadDailyQuestStatus(QueryResult *result)
14603 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14604 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14606 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14608 if(result)
14610 uint32 quest_daily_idx = 0;
14614 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14616 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14617 break;
14620 Field *fields = result->Fetch();
14622 uint32 quest_id = fields[0].GetUInt32();
14624 // save _any_ from daily quest times (it must be after last reset anyway)
14625 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14627 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14628 if( !pQuest )
14629 continue;
14631 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14632 ++quest_daily_idx;
14634 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14636 while( result->NextRow() );
14638 delete result;
14641 m_DailyQuestChanged = false;
14644 void Player::_LoadReputation(QueryResult *result)
14646 m_factions.clear();
14648 // Set initial reputations (so everything is nifty before DB data load)
14649 SetInitialFactions();
14651 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14653 if(result)
14657 Field *fields = result->Fetch();
14659 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14660 if( factionEntry && (factionEntry->reputationListID >= 0))
14662 FactionState* faction = &m_factions[factionEntry->reputationListID];
14664 // update standing to current
14665 faction->Standing = int32(fields[1].GetUInt32());
14667 uint32 dbFactionFlags = fields[2].GetUInt32();
14669 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14670 SetFactionVisible(faction); // have internal checks for forced invisibility
14672 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14673 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14675 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14676 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14677 else // DB not at war
14679 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14680 if( faction->Flags & FACTION_FLAG_VISIBLE )
14681 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14684 // set atWar for hostile
14685 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14686 SetFactionAtWar(faction,true);
14688 // reset changed flag if values similar to saved in DB
14689 if(faction->Flags==dbFactionFlags)
14690 faction->Changed = false;
14693 while( result->NextRow() );
14695 delete result;
14699 void Player::_LoadSpells(QueryResult *result)
14701 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14702 delete itr->second;
14703 m_spells.clear();
14705 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14707 if(result)
14711 Field *fields = result->Fetch();
14713 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14715 while( result->NextRow() );
14717 delete result;
14721 void Player::_LoadTutorials(QueryResult *result)
14723 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14725 if(result)
14729 Field *fields = result->Fetch();
14731 for (int iI=0; iI<8; iI++)
14732 m_Tutorials[iI] = fields[iI].GetUInt32();
14734 while( result->NextRow() );
14736 delete result;
14739 m_TutorialsChanged = false;
14742 void Player::_LoadGroup(QueryResult *result)
14744 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14745 if(result)
14747 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14748 delete result;
14749 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14750 if(group)
14752 uint8 subgroup = group->GetMemberGroup(GetGUID());
14753 SetGroup(group, subgroup);
14754 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14756 // the group leader may change the instance difficulty while the player is offline
14757 SetDifficulty(group->GetDifficulty());
14763 void Player::_LoadBoundInstances(QueryResult *result)
14765 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14766 m_boundInstances[i].clear();
14768 Group *group = GetGroup();
14770 //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));
14771 if(result)
14775 Field *fields = result->Fetch();
14776 bool perm = fields[1].GetBool();
14777 uint32 mapId = fields[2].GetUInt32();
14778 uint32 instanceId = fields[0].GetUInt32();
14779 uint8 difficulty = fields[3].GetUInt8();
14780 time_t resetTime = (time_t)fields[4].GetUInt64();
14781 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14782 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14783 // and in that case it is not used
14785 if(!perm && group)
14787 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);
14788 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14789 continue;
14792 // since non permanent binds are always solo bind, they can always be reset
14793 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14794 if(save) BindToInstance(save, perm, true);
14795 } while(result->NextRow());
14796 delete result;
14800 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14802 // some instances only have one difficulty
14803 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14804 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14806 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14807 if(itr != m_boundInstances[difficulty].end())
14808 return &itr->second;
14809 else
14810 return NULL;
14813 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14815 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14816 UnbindInstance(itr, difficulty, unload);
14819 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14821 if(itr != m_boundInstances[difficulty].end())
14823 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14824 itr->second.save->RemovePlayer(this); // save can become invalid
14825 m_boundInstances[difficulty].erase(itr++);
14829 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14831 if(save)
14833 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14834 if(bind.save)
14836 // update the save when the group kills a boss
14837 if(permanent != bind.perm || save != bind.save)
14838 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());
14840 else
14841 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14843 if(bind.save != save)
14845 if(bind.save) bind.save->RemovePlayer(this);
14846 save->AddPlayer(this);
14849 if(permanent) save->SetCanReset(false);
14851 bind.save = save;
14852 bind.perm = permanent;
14853 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());
14854 return &bind;
14856 else
14857 return NULL;
14860 void Player::SendRaidInfo()
14862 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14864 uint32 counter = 0, i;
14865 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14866 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14867 if(itr->second.perm) counter++;
14869 data << counter;
14870 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14872 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14874 if(itr->second.perm)
14876 InstanceSave *save = itr->second.save;
14877 data << (save->GetMapId());
14878 data << (uint32)(save->GetResetTime() - time(NULL));
14879 data << save->GetInstanceId();
14880 data << uint32(counter);
14881 counter--;
14885 GetSession()->SendPacket(&data);
14889 - called on every successful teleportation to a map
14891 void Player::SendSavedInstances()
14893 bool hasBeenSaved = false;
14894 WorldPacket data;
14896 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14898 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14900 if(itr->second.perm) // only permanent binds are sent
14902 hasBeenSaved = true;
14903 break;
14908 //Send opcode 811. true or false means, whether you have current raid/heroic instances
14909 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
14910 data << uint32(hasBeenSaved);
14911 GetSession()->SendPacket(&data);
14913 if(!hasBeenSaved)
14914 return;
14916 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14918 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14920 if(itr->second.perm)
14922 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
14923 data << uint32(itr->second.save->GetMapId());
14924 GetSession()->SendPacket(&data);
14930 /// convert the player's binds to the group
14931 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
14933 bool has_binds = false;
14934 bool has_solo = false;
14936 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
14937 assert(player_guid);
14939 // copy all binds to the group, when changing leader it's assumed the character
14940 // will not have any solo binds
14942 if(player)
14944 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14946 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
14948 has_binds = true;
14949 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
14950 // permanent binds are not removed
14951 if(!itr->second.perm)
14953 player->UnbindInstance(itr, i, true); // increments itr
14954 has_solo = true;
14956 else
14957 ++itr;
14962 // if the player's not online we don't know what binds it has
14963 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));
14964 // the following should not get executed when changing leaders
14965 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
14968 bool Player::_LoadHomeBind(QueryResult *result)
14970 bool ok = false;
14971 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14972 if (result)
14974 Field *fields = result->Fetch();
14975 m_homebindMapId = fields[0].GetUInt32();
14976 m_homebindZoneId = fields[1].GetUInt16();
14977 m_homebindX = fields[2].GetFloat();
14978 m_homebindY = fields[3].GetFloat();
14979 m_homebindZ = fields[4].GetFloat();
14980 delete result;
14982 // accept saved data only for valid position (and non instanceable)
14983 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
14984 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
14986 ok = true;
14988 else
14989 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14992 if(!ok)
14994 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
14995 if(!info) return false;
14997 m_homebindMapId = info->mapId;
14998 m_homebindZoneId = info->zoneId;
14999 m_homebindX = info->positionX;
15000 m_homebindY = info->positionY;
15001 m_homebindZ = info->positionZ;
15003 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);
15006 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15007 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15009 return true;
15012 /*********************************************************/
15013 /*** SAVE SYSTEM ***/
15014 /*********************************************************/
15016 void Player::SaveToDB()
15018 // delay auto save at any saves (manual, in code, or autosave)
15019 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15021 // first save/honor gain after midnight will also update the player's honor fields
15022 UpdateHonorFields();
15024 // Must saved before enter into BattleGround
15025 if(InBattleGround())
15026 return;
15028 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15029 //save, far from tavern/city
15030 //save, but in tavern/city
15031 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15032 outDebugValues();
15034 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15035 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15036 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15037 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15038 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15039 uint32 tmp_displayid = GetDisplayId();
15041 // Set player sit state to standing on save, also stealth and shifted form
15042 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15043 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15044 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15045 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15046 SetDisplayId(GetNativeDisplayId());
15048 bool inworld = IsInWorld();
15050 CharacterDatabase.BeginTransaction();
15052 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15054 std::string sql_name = m_name;
15055 CharacterDatabase.escape_string(sql_name);
15057 std::ostringstream ss;
15058 ss << "INSERT INTO characters (guid,account,name,race,class,"
15059 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15060 "taximask, online, cinematic, "
15061 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15062 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15063 "death_expire_time, taxi_path) VALUES ("
15064 << GetGUIDLow() << ", "
15065 << GetSession()->GetAccountId() << ", '"
15066 << sql_name << "', "
15067 << m_race << ", "
15068 << m_class << ", ";
15070 bool save_to_dest = false;
15071 if(IsBeingTeleported())
15073 // don't save to battlegrounds or arenas
15074 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15075 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15076 save_to_dest = true;
15079 if(!save_to_dest)
15081 ss << GetMapId() << ", "
15082 << (uint32)GetDifficulty() << ", "
15083 << finiteAlways(GetPositionX()) << ", "
15084 << finiteAlways(GetPositionY()) << ", "
15085 << finiteAlways(GetPositionZ()) << ", "
15086 << finiteAlways(GetOrientation()) << ", '";
15088 else
15090 ss << GetTeleportDest().mapid << ", "
15091 << (uint32)GetDifficulty() << ", "
15092 << finiteAlways(GetTeleportDest().x) << ", "
15093 << finiteAlways(GetTeleportDest().y) << ", "
15094 << finiteAlways(GetTeleportDest().z) << ", "
15095 << finiteAlways(GetTeleportDest().o) << ", '";
15098 uint16 i;
15099 for( i = 0; i < m_valuesCount; i++ )
15101 ss << GetUInt32Value(i) << " ";
15104 ss << "', '";
15106 for( i = 0; i < 8; i++ )
15107 ss << m_taxi.GetTaximask(i) << " ";
15109 ss << "', ";
15110 ss << (inworld ? 1 : 0);
15112 ss << ", ";
15113 ss << m_cinematic;
15115 ss << ", ";
15116 ss << m_Played_time[0];
15117 ss << ", ";
15118 ss << m_Played_time[1];
15120 ss << ", ";
15121 ss << finiteAlways(m_rest_bonus);
15122 ss << ", ";
15123 ss << (uint64)time(NULL);
15124 ss << ", ";
15125 ss << is_save_resting;
15126 ss << ", ";
15127 ss << m_resetTalentsCost;
15128 ss << ", ";
15129 ss << (uint64)m_resetTalentsTime;
15131 ss << ", ";
15132 ss << finiteAlways(m_movementInfo.t_x);
15133 ss << ", ";
15134 ss << finiteAlways(m_movementInfo.t_y);
15135 ss << ", ";
15136 ss << finiteAlways(m_movementInfo.t_z);
15137 ss << ", ";
15138 ss << finiteAlways(m_movementInfo.t_o);
15139 ss << ", ";
15140 if (m_transport)
15141 ss << m_transport->GetGUIDLow();
15142 else
15143 ss << "0";
15145 ss << ", ";
15146 ss << m_ExtraFlags;
15148 ss << ", ";
15149 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15151 ss << ", ";
15152 ss << uint32(m_atLoginFlags);
15154 ss << ", ";
15155 ss << GetZoneId();
15157 ss << ", ";
15158 ss << (uint64)m_deathExpireTime;
15160 ss << ", '";
15161 ss << m_taxi.SaveTaxiDestinationsToString();
15162 ss << "' )";
15164 CharacterDatabase.Execute( ss.str().c_str() );
15166 if(m_mailsUpdated) //save mails only when needed
15167 _SaveMail();
15169 _SaveInventory();
15170 _SaveQuestStatus();
15171 _SaveDailyQuestStatus();
15172 _SaveTutorials();
15173 _SaveSpells();
15174 _SaveSpellCooldowns();
15175 _SaveActions();
15176 _SaveAuras();
15177 _SaveReputation();
15179 CharacterDatabase.CommitTransaction();
15181 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15182 SetDisplayId(tmp_displayid);
15183 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15184 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15185 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15186 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15188 // save pet (hunter pet level and experience and all type pets health/mana).
15189 if(Pet* pet = GetPet())
15190 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15191 m_achievementMgr.SaveToDB();
15194 // fast save function for item/money cheating preventing - save only inventory and money state
15195 void Player::SaveInventoryAndGoldToDB()
15197 _SaveInventory();
15198 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
15201 void Player::_SaveActions()
15203 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15205 switch (itr->second.uState)
15207 case ACTIONBUTTON_NEW:
15208 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15209 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15210 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15211 ++itr;
15212 break;
15213 case ACTIONBUTTON_CHANGED:
15214 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15215 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15216 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15217 ++itr;
15218 break;
15219 case ACTIONBUTTON_DELETED:
15220 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15221 m_actionButtons.erase(itr++);
15222 break;
15223 default:
15224 ++itr;
15225 break;
15230 void Player::_SaveAuras()
15232 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15234 AuraMap const& auras = GetAuras();
15235 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
15237 SpellEntry const *spellInfo = itr->second->GetSpellProto();
15239 //skip all auras from spells that are passive or need a shapeshift
15240 if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
15241 continue;
15243 //do not save single target auras (unless they were cast by the player)
15244 if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
15245 continue;
15247 uint8 i;
15248 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15249 for (i = 0; i < 3; i++)
15250 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15251 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15252 break;
15254 if (i == 3)
15256 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());
15257 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
15258 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
15259 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));
15264 void Player::_SaveInventory()
15266 // force items in buyback slots to new state
15267 // and remove those that aren't already
15268 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15270 Item *item = m_items[i];
15271 if (!item || item->GetState() == ITEM_NEW) continue;
15272 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15273 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15274 m_items[i]->FSetState(ITEM_NEW);
15277 // update enchantment durations
15278 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15280 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15283 // if no changes
15284 if (m_itemUpdateQueue.empty()) return;
15286 // do not save if the update queue is corrupt
15287 bool error = false;
15288 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15290 Item *item = m_itemUpdateQueue[i];
15291 if(!item || item->GetState() == ITEM_REMOVED) continue;
15292 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15294 if (test == NULL)
15296 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());
15297 error = true;
15299 else if (test != item)
15301 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());
15302 error = true;
15306 if (error)
15308 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15309 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15310 return;
15313 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15315 Item *item = m_itemUpdateQueue[i];
15316 if(!item) continue;
15318 Bag *container = item->GetContainer();
15319 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15321 switch(item->GetState())
15323 case ITEM_NEW:
15324 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());
15325 break;
15326 case ITEM_CHANGED:
15327 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());
15328 break;
15329 case ITEM_REMOVED:
15330 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15331 break;
15332 case ITEM_UNCHANGED:
15333 break;
15336 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15338 m_itemUpdateQueue.clear();
15341 void Player::_SaveMail()
15343 if (!m_mailsLoaded)
15344 return;
15346 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
15348 Mail *m = (*itr);
15349 if (m->state == MAIL_STATE_CHANGED)
15351 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'",
15352 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15353 if(m->removedItems.size())
15355 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15356 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15357 m->removedItems.clear();
15359 m->state = MAIL_STATE_UNCHANGED;
15361 else if (m->state == MAIL_STATE_DELETED)
15363 if (m->HasItems())
15364 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15365 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15366 if (m->itemTextId)
15367 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15368 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15369 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15373 //deallocate deleted mails...
15374 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15376 if ((*itr)->state == MAIL_STATE_DELETED)
15378 Mail* m = *itr;
15379 m_mail.erase(itr);
15380 delete m;
15381 itr = m_mail.begin();
15383 else
15384 ++itr;
15387 m_mailsUpdated = false;
15390 void Player::_SaveQuestStatus()
15392 // we don't need transactions here.
15393 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15395 switch (i->second.uState)
15397 case QUEST_NEW :
15398 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15399 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15400 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]);
15401 break;
15402 case QUEST_CHANGED :
15403 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' ",
15404 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 );
15405 break;
15406 case QUEST_UNCHANGED:
15407 break;
15409 i->second.uState = QUEST_UNCHANGED;
15413 void Player::_SaveDailyQuestStatus()
15415 if(!m_DailyQuestChanged)
15416 return;
15418 m_DailyQuestChanged = false;
15420 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15422 // we don't need transactions here.
15423 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15424 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15425 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15426 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15427 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15430 void Player::_SaveReputation()
15432 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15434 if (itr->second.Changed)
15436 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15437 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);
15438 itr->second.Changed = false;
15443 void Player::_SaveSpells()
15445 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15447 ++next;
15448 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15449 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15450 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15451 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);
15453 if (itr->second->state == PLAYERSPELL_REMOVED)
15454 _removeSpell(itr->first);
15455 else
15456 itr->second->state = PLAYERSPELL_UNCHANGED;
15460 void Player::_SaveTutorials()
15462 if(!m_TutorialsChanged)
15463 return;
15465 uint32 Rows=0;
15466 // it's better than rebuilding indexes multiple times
15467 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15468 if(result)
15470 Rows = result->Fetch()[0].GetUInt32();
15471 delete result;
15474 if (Rows)
15476 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'",
15477 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 );
15479 else
15481 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]);
15484 m_TutorialsChanged = false;
15487 void Player::outDebugValues() const
15489 if(!sLog.IsOutDebug()) // optimize disabled debug output
15490 return;
15492 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15493 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15494 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15495 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15496 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15497 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15498 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15499 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15500 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15501 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15502 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15503 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15506 /*********************************************************/
15507 /*** FLOOD FILTER SYSTEM ***/
15508 /*********************************************************/
15510 void Player::UpdateSpeakTime()
15512 // ignore chat spam protection for GMs in any mode
15513 if(GetSession()->GetSecurity() > SEC_PLAYER)
15514 return;
15516 time_t current = time (NULL);
15517 if(m_speakTime > current)
15519 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15520 if(!max_count)
15521 return;
15523 ++m_speakCount;
15524 if(m_speakCount >= max_count)
15526 // prevent overwrite mute time, if message send just before mutes set, for example.
15527 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15528 if(GetSession()->m_muteTime < new_mute)
15529 GetSession()->m_muteTime = new_mute;
15531 m_speakCount = 0;
15534 else
15535 m_speakCount = 0;
15537 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15540 bool Player::CanSpeak() const
15542 return GetSession()->m_muteTime <= time (NULL);
15545 /*********************************************************/
15546 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15547 /*********************************************************/
15549 void Player::SendAttackSwingNotInRange()
15551 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15552 GetSession()->SendPacket( &data );
15555 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15557 std::ostringstream ss;
15558 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15559 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15560 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15561 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15562 sLog.outDebug(ss.str().c_str());
15563 CharacterDatabase.Execute(ss.str().c_str());
15566 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15568 std::ostringstream ss2;
15569 ss2<<"UPDATE characters SET data='";
15570 int i=0;
15571 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15573 ss2<<tokens[i]<<" ";
15575 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15577 return CharacterDatabase.Execute(ss2.str().c_str());
15580 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15582 char buf[11];
15583 snprintf(buf,11,"%u",value);
15585 if(index >= tokens.size())
15586 return;
15588 tokens[index] = buf;
15591 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15593 Tokens tokens;
15594 if(!LoadValuesArrayFromDB(tokens,guid))
15595 return;
15597 if(index >= tokens.size())
15598 return;
15600 char buf[11];
15601 snprintf(buf,11,"%u",value);
15602 tokens[index] = buf;
15604 SaveValuesArrayInDB(tokens,guid);
15607 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15609 uint32 temp;
15610 memcpy(&temp, &value, sizeof(value));
15611 Player::SetUInt32ValueInDB(index, temp, guid);
15614 void Player::SendAttackSwingNotStanding()
15616 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15617 GetSession()->SendPacket( &data );
15620 void Player::SendAttackSwingDeadTarget()
15622 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15623 GetSession()->SendPacket( &data );
15626 void Player::SendAttackSwingCantAttack()
15628 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15629 GetSession()->SendPacket( &data );
15632 void Player::SendAttackSwingCancelAttack()
15634 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15635 GetSession()->SendPacket( &data );
15638 void Player::SendAttackSwingBadFacingAttack()
15640 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15641 GetSession()->SendPacket( &data );
15644 void Player::SendAutoRepeatCancel()
15646 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15647 data.append(GetPackGUID()); // may be it's target guid
15648 GetSession()->SendPacket( &data );
15651 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15653 WorldPacket data(SMSG_PLAY_SOUND, 4);
15654 data << Sound;
15655 if (OnlySelf)
15656 GetSession()->SendPacket( &data );
15657 else
15658 SendMessageToSet( &data, true );
15661 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15663 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15664 data << Area;
15665 data << Experience;
15666 GetSession()->SendPacket(&data);
15669 void Player::SendDungeonDifficulty(bool IsInGroup)
15671 uint8 val = 0x00000001;
15672 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15673 data << (uint32)GetDifficulty();
15674 data << uint32(val);
15675 data << uint32(IsInGroup);
15676 GetSession()->SendPacket(&data);
15679 void Player::SendResetFailedNotify(uint32 mapid)
15681 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15682 data << uint32(mapid);
15683 GetSession()->SendPacket(&data);
15686 /// Reset all solo instances and optionally send a message on success for each
15687 void Player::ResetInstances(uint8 method)
15689 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15691 // we assume that when the difficulty changes, all instances that can be reset will be
15692 uint8 dif = GetDifficulty();
15694 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15696 InstanceSave *p = itr->second.save;
15697 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15698 if(!entry || !p->CanReset())
15700 ++itr;
15701 continue;
15704 if(method == INSTANCE_RESET_ALL)
15706 // the "reset all instances" method can only reset normal maps
15707 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15709 ++itr;
15710 continue;
15714 // if the map is loaded, reset it
15715 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15716 if(map && map->IsDungeon())
15717 ((InstanceMap*)map)->Reset(method);
15719 // since this is a solo instance there should not be any players inside
15720 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15721 SendResetInstanceSuccess(p->GetMapId());
15723 p->DeleteFromDB();
15724 m_boundInstances[dif].erase(itr++);
15726 // the following should remove the instance save from the manager and delete it as well
15727 p->RemovePlayer(this);
15731 void Player::SendResetInstanceSuccess(uint32 MapId)
15733 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15734 data << MapId;
15735 GetSession()->SendPacket(&data);
15738 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15740 // TODO: find what other fail reasons there are besides players in the instance
15741 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15742 data << reason;
15743 data << MapId;
15744 GetSession()->SendPacket(&data);
15747 /*********************************************************/
15748 /*** Update timers ***/
15749 /*********************************************************/
15751 ///checks the 15 afk reports per 5 minutes limit
15752 void Player::UpdateAfkReport(time_t currTime)
15754 if(m_bgAfkReportedTimer <= currTime)
15756 m_bgAfkReportedCount = 0;
15757 m_bgAfkReportedTimer = currTime+5*MINUTE;
15761 void Player::UpdateContestedPvP(uint32 diff)
15763 if(!m_contestedPvPTimer||isInCombat())
15764 return;
15765 if(m_contestedPvPTimer <= diff)
15767 ResetContestedPvP();
15769 else
15770 m_contestedPvPTimer -= diff;
15773 void Player::UpdatePvPFlag(time_t currTime)
15775 if(!IsPvP())
15776 return;
15777 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15778 return;
15780 UpdatePvP(false);
15783 void Player::UpdateDuelFlag(time_t currTime)
15785 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15786 return;
15788 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15789 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15791 duel->startTimer = 0;
15792 duel->startTime = currTime;
15793 duel->opponent->duel->startTimer = 0;
15794 duel->opponent->duel->startTime = currTime;
15797 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15799 if(!pet)
15800 pet = GetPet();
15802 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15804 //returning of reagents only for players, so best done here
15805 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
15806 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15808 if(spellInfo)
15810 for(uint32 i = 0; i < 7; ++i)
15812 if(spellInfo->Reagent[i] > 0)
15814 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15815 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
15816 if( msg == EQUIP_ERR_OK )
15818 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
15819 if(IsInWorld())
15820 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
15825 m_temporaryUnsummonedPetNumber = 0;
15828 if(!pet || pet->GetOwnerGUID()!=GetGUID())
15829 return;
15831 // only if current pet in slot
15832 switch(pet->getPetType())
15834 case MINI_PET:
15835 m_miniPet = 0;
15836 break;
15837 case GUARDIAN_PET:
15838 m_guardianPets.erase(pet->GetGUID());
15839 break;
15840 default:
15841 if(GetPetGUID()==pet->GetGUID())
15842 SetPet(0);
15843 break;
15846 pet->CombatStop();
15848 if(returnreagent)
15850 switch(pet->GetEntry())
15852 //warlock pets except imp are removed(?) when logging out
15853 case 1860:
15854 case 1863:
15855 case 417:
15856 case 17252:
15857 mode = PET_SAVE_NOT_IN_SLOT;
15858 break;
15862 pet->SavePetToDB(mode);
15864 pet->CleanupsBeforeDelete();
15865 pet->AddObjectToRemoveList();
15866 pet->m_removed = true;
15868 if(pet->isControlled())
15870 WorldPacket data(SMSG_PET_SPELLS, 8);
15871 data << uint64(0);
15872 data << uint32(0);
15873 GetSession()->SendPacket(&data);
15875 if(GetGroup())
15876 SetGroupUpdateFlag(GROUP_UPDATE_PET);
15880 void Player::RemoveMiniPet()
15882 if(Pet* pet = GetMiniPet())
15884 pet->Remove(PET_SAVE_AS_DELETED);
15885 m_miniPet = 0;
15889 Pet* Player::GetMiniPet()
15891 if(!m_miniPet)
15892 return NULL;
15893 return ObjectAccessor::GetPet(m_miniPet);
15896 void Player::RemoveGuardians()
15898 while(!m_guardianPets.empty())
15900 uint64 guid = *m_guardianPets.begin();
15901 if(Pet* pet = ObjectAccessor::GetPet(guid))
15902 pet->Remove(PET_SAVE_AS_DELETED);
15904 m_guardianPets.erase(guid);
15908 bool Player::HasGuardianWithEntry(uint32 entry)
15910 // pet guid middle part is entry (and creature also)
15911 // and in guardian list must be guardians with same entry _always_
15912 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
15913 if(GUID_ENPART(*itr)==entry)
15914 return true;
15916 return false;
15919 void Player::Uncharm()
15921 Unit* charm = GetCharm();
15922 if(!charm)
15923 return;
15925 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
15926 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
15929 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, std::string text, uint32 language) const
15931 *data << (uint8)msgtype;
15932 *data << (uint32)language;
15933 *data << (uint64)GetGUID();
15934 *data << (uint32)language; //language 2.1.0 ?
15935 *data << (uint64)GetGUID();
15936 *data << (uint32)(text.length()+1);
15937 *data << text;
15938 *data << (uint8)chatTag();
15941 void Player::Say(const std::string text, const uint32 language)
15943 WorldPacket data(SMSG_MESSAGECHAT, 200);
15944 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
15945 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
15948 void Player::Yell(const std::string text, const uint32 language)
15950 WorldPacket data(SMSG_MESSAGECHAT, 200);
15951 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
15952 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
15955 void Player::TextEmote(const std::string text)
15957 WorldPacket data(SMSG_MESSAGECHAT, 200);
15958 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
15959 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
15962 void Player::Whisper(std::string text, uint32 language,uint64 receiver)
15964 if (language != LANG_ADDON) // if not addon data
15965 language = LANG_UNIVERSAL; // whispers should always be readable
15967 Player *rPlayer = objmgr.GetPlayer(receiver);
15969 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15970 if(!rPlayer->isDND() || isGameMaster())
15972 WorldPacket data(SMSG_MESSAGECHAT, 200);
15973 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
15974 rPlayer->GetSession()->SendPacket(&data);
15976 data.Initialize(SMSG_MESSAGECHAT, 200);
15977 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
15978 GetSession()->SendPacket(&data);
15980 else
15982 // announce to player that player he is whispering to is dnd and cannot receive his message
15983 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
15986 if(!isAcceptWhispers())
15988 SetAcceptWhispers(true);
15989 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
15992 // announce to player that player he is whispering to is afk
15993 if(rPlayer->isAFK())
15994 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
15996 // if player whisper someone, auto turn of dnd to be able to receive an answer
15997 if(isDND() && !rPlayer->isGameMaster())
15998 ToggleDND();
16001 void Player::PetSpellInitialize()
16003 Pet* pet = GetPet();
16005 if(!pet)
16006 return;
16008 sLog.outDebug("Pet Spells Groups");
16010 CharmInfo *charmInfo = pet->GetCharmInfo();
16012 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16013 data << uint64(pet->GetGUID());
16014 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16015 data << uint32(0);
16016 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16018 // action bar loop
16019 for(uint32 i = 0; i < 10; i++)
16021 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16024 size_t spellsCountPos = data.wpos();
16026 // spells count
16027 uint8 addlist = 0;
16028 data << uint8(addlist); // placeholder
16030 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16032 // spells loop
16033 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16035 if(itr->second->state == PETSPELL_REMOVED)
16036 continue;
16038 data << uint16(itr->first);
16039 data << uint16(itr->second->active); // pet spell active state isn't boolean
16040 ++addlist;
16044 data.put<uint8>(spellsCountPos, addlist);
16046 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16047 data << uint8(cooldownsCount);
16049 time_t curTime = time(NULL);
16051 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16053 time_t cooldown = 0;
16055 if(itr->second > curTime)
16056 cooldown = (itr->second - curTime) * 1000;
16058 data << uint16(itr->first); // spellid
16059 data << uint16(0); // spell category?
16060 data << uint32(itr->second); // cooldown
16061 data << uint32(0); // category cooldown
16064 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16066 time_t cooldown = 0;
16068 if(itr->second > curTime)
16069 cooldown = (itr->second - curTime) * 1000;
16071 data << uint16(itr->first); // spellid
16072 data << uint16(0); // spell category?
16073 data << uint32(0); // cooldown
16074 data << uint32(itr->second); // category cooldown
16077 GetSession()->SendPacket(&data);
16080 void Player::PossessSpellInitialize()
16082 Unit* charm = GetCharm();
16084 if(!charm)
16085 return;
16087 CharmInfo *charmInfo = charm->GetCharmInfo();
16089 if(!charmInfo)
16091 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16092 return;
16095 uint8 addlist = 0;
16096 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16098 //16
16099 data << uint64(charm->GetGUID());
16100 data << uint32(0x00000000);
16101 data << uint32(0);
16102 data << uint8(0) << uint8(0) << uint16(0);
16104 for(uint32 i = 0; i < 10; i++) //40
16106 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16109 data << uint8(addlist); //1
16111 uint8 count = 0;
16112 data << uint8(count); // cooldowns count
16114 GetSession()->SendPacket(&data);
16117 void Player::CharmSpellInitialize()
16119 Unit* charm = GetCharm();
16121 if(!charm)
16122 return;
16124 CharmInfo *charmInfo = charm->GetCharmInfo();
16125 if(!charmInfo)
16127 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16128 return;
16131 uint8 addlist = 0;
16133 if(charm->GetTypeId() != TYPEID_PLAYER)
16135 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16137 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16139 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16141 if(charmInfo->GetCharmSpell(i)->spellId)
16142 ++addlist;
16147 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16149 data << uint64(charm->GetGUID());
16150 data << uint32(0x00000000);
16151 data << uint32(0);
16152 if(charm->GetTypeId() != TYPEID_PLAYER)
16153 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16154 else
16155 data << uint8(0) << uint8(0);
16156 data << uint16(0);
16158 for(uint32 i = 0; i < 10; i++) //40
16160 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16163 data << uint8(addlist); //1
16165 if(addlist)
16167 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16169 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16170 if(cspell->spellId)
16172 data << uint16(cspell->spellId);
16173 data << uint16(cspell->active);
16178 uint8 count = 0;
16179 data << uint8(count); // cooldowns count
16181 GetSession()->SendPacket(&data);
16184 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
16186 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16187 if (!spellInfo) return 0;
16188 int32 total = 0;
16189 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16191 SpellModifier *mod = *itr;
16193 if(!IsAffectedBySpellmod(spellInfo,mod))
16194 continue;
16196 if (mod->type == SPELLMOD_FLAT)
16197 total += mod->value;
16199 return total;
16202 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
16204 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16205 if (!spellInfo) return 0;
16206 int32 total = 0;
16207 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16209 SpellModifier *mod = *itr;
16211 if(!IsAffectedBySpellmod(spellInfo,mod))
16212 continue;
16214 if (mod->type == SPELLMOD_PCT)
16215 total += mod->value;
16217 return total;
16220 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16222 if (!mod || !spellInfo)
16223 return false;
16225 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16227 // prevent apply to any spell except spell that trigger expire
16228 if(spell)
16230 if(mod->lastAffected != spell)
16231 return false;
16233 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16234 return false;
16237 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
16240 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16242 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16244 for(int eff=0;eff<64;++eff)
16246 uint64 _mask = uint64(1) << eff;
16247 if ( mod->mask & _mask)
16249 int32 val = 0;
16250 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16252 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
16253 val += (*itr)->value;
16255 val += apply ? mod->value : -(mod->value);
16256 WorldPacket data(Opcode, (1+1+4));
16257 data << uint8(eff);
16258 data << uint8(mod->op);
16259 data << int32(val);
16260 SendDirectMessage(&data);
16264 if (apply)
16265 m_spellMods[mod->op].push_back(mod);
16266 else
16268 if (mod->charges == -1)
16269 --m_SpellModRemoveCount;
16270 m_spellMods[mod->op].remove(mod);
16271 delete mod;
16275 void Player::RemoveSpellMods(Spell const* spell)
16277 if(!spell || (m_SpellModRemoveCount == 0))
16278 return;
16280 for(int i=0;i<MAX_SPELLMOD;++i)
16282 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16284 SpellModifier *mod = *itr;
16285 ++itr;
16287 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16289 RemoveAurasDueToSpell(mod->spellId);
16290 if (m_spellMods[i].empty())
16291 break;
16292 else
16293 itr = m_spellMods[i].begin();
16299 // send Proficiency
16300 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16302 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16303 data << pr1 << pr2;
16304 GetSession()->SendPacket (&data);
16307 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16309 QueryResult *result = NULL;
16310 if(type==10)
16311 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16312 else
16313 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16314 if(result)
16316 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.
16317 { // and SendPetitionQueryOpcode reads data from the DB
16318 Field *fields = result->Fetch();
16319 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16320 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16322 // send update if charter owner in game
16323 Player* owner = objmgr.GetPlayer(ownerguid);
16324 if(owner)
16325 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16327 } while ( result->NextRow() );
16329 delete result;
16331 if(type==10)
16332 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16333 else
16334 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16337 CharacterDatabase.BeginTransaction();
16338 if(type == 10)
16340 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16341 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16343 else
16345 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16346 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16348 CharacterDatabase.CommitTransaction();
16351 void Player::SetRestBonus (float rest_bonus_new)
16353 // Prevent resting on max level
16354 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16355 rest_bonus_new = 0;
16357 if(rest_bonus_new < 0)
16358 rest_bonus_new = 0;
16360 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16362 if(rest_bonus_new > rest_bonus_max)
16363 m_rest_bonus = rest_bonus_max;
16364 else
16365 m_rest_bonus = rest_bonus_new;
16367 // update data for client
16368 if(m_rest_bonus>10)
16369 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16370 else if(m_rest_bonus<=1)
16371 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16373 //RestTickUpdate
16374 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16377 void Player::HandleStealthedUnitsDetection()
16379 std::list<Unit*> stealthedUnits;
16381 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16382 Cell cell(p);
16383 cell.data.Part.reserved = ALL_DISTRICT;
16384 cell.SetNoCreate();
16386 MaNGOS::AnyStealthedCheck u_check;
16387 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16389 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16390 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16392 CellLock<GridReadGuard> cell_lock(cell, p);
16393 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16394 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16396 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16398 if((*i)==this)
16400 i = stealthedUnits.erase(i);
16401 continue;
16404 if ((*i)->isVisibleForOrDetect(this,true))
16407 (*i)->SendUpdateToPlayer(this);
16408 m_clientGUIDs.insert((*i)->GetGUID());
16410 #ifdef MANGOS_DEBUG
16411 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16412 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16413 #endif
16415 // target aura duration for caster show only if target exist at caster client
16416 // send data at target visibility change (adding to client)
16417 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16418 SendAurasForTarget(*i);
16420 i = stealthedUnits.erase(i);
16421 continue;
16424 ++i;
16428 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16430 if(nodes.size() < 2)
16431 return false;
16433 // not let cheating with start flight mounted
16434 if(IsMounted())
16436 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16437 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16438 GetSession()->SendPacket(&data);
16439 return false;
16442 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16444 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16445 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16446 GetSession()->SendPacket(&data);
16447 return false;
16450 // 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
16451 if(GetSession()->isLogingOut() ||
16452 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16453 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16454 IsNonMeleeSpellCasted(false) ||
16455 isInCombat())
16457 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16458 data << uint32(ERR_TAXIPLAYERBUSY);
16459 GetSession()->SendPacket(&data);
16460 return false;
16463 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16464 return false;
16466 uint32 sourcenode = nodes[0];
16468 // starting node too far away (cheat?)
16469 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16470 if( !node || node->map_id != GetMapId() ||
16471 (node->x - GetPositionX())*(node->x - GetPositionX())+
16472 (node->y - GetPositionY())*(node->y - GetPositionY())+
16473 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16474 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16476 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16477 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16478 GetSession()->SendPacket(&data);
16479 return false;
16482 // Prepare to flight start now
16484 // stop combat at start taxi flight if any
16485 CombatStop();
16487 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16488 TradeCancel(true);
16490 // clean not finished taxi path if any
16491 m_taxi.ClearTaxiDestinations();
16493 // 0 element current node
16494 m_taxi.AddTaxiDestination(sourcenode);
16496 // fill destinations path tail
16497 uint32 sourcepath = 0;
16498 uint32 totalcost = 0;
16500 uint32 prevnode = sourcenode;
16501 uint32 lastnode = 0;
16503 for(uint32 i = 1; i < nodes.size(); ++i)
16505 uint32 path, cost;
16507 lastnode = nodes[i];
16508 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16510 if(!path)
16512 m_taxi.ClearTaxiDestinations();
16513 return false;
16516 totalcost += cost;
16518 if(prevnode == sourcenode)
16519 sourcepath = path;
16521 m_taxi.AddTaxiDestination(lastnode);
16523 prevnode = lastnode;
16526 if(!mount_id) // if not provide then attempt use default.
16527 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16529 if (mount_id == 0 || sourcepath == 0)
16531 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16532 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16533 GetSession()->SendPacket(&data);
16534 m_taxi.ClearTaxiDestinations();
16535 return false;
16538 uint32 money = GetMoney();
16540 if(npc)
16542 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16545 if(money < totalcost)
16547 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16548 data << uint32(ERR_TAXINOTENOUGHMONEY);
16549 GetSession()->SendPacket(&data);
16550 m_taxi.ClearTaxiDestinations();
16551 return false;
16554 //Checks and preparations done, DO FLIGHT
16555 ModifyMoney(-(int32)totalcost);
16557 // prevent stealth flight
16558 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16560 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16561 data << uint32(ERR_TAXIOK);
16562 GetSession()->SendPacket(&data);
16564 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16566 GetSession()->SendDoFlight(mount_id, sourcepath);
16568 return true;
16571 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16573 // last check 2.0.10
16574 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16575 data << GetGUID();
16576 data << uint8(0x0); // flags (0x1, 0x2)
16577 time_t curTime = time(NULL);
16578 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16580 if (itr->second->state == PLAYERSPELL_REMOVED)
16581 continue;
16582 uint32 unSpellId = itr->first;
16583 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16584 if (!spellInfo)
16586 ASSERT(spellInfo);
16587 continue;
16590 // Not send cooldown for this spells
16591 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16592 continue;
16594 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16596 data << unSpellId;
16597 data << unTimeMs; // in m.secs
16598 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16601 GetSession()->SendPacket(&data);
16604 void Player::InitDataForForm(bool reapplyMods)
16606 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16607 if(ssEntry && ssEntry->attackSpeed)
16609 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16610 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16611 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16613 else
16614 SetRegularAttackTime();
16616 switch(m_form)
16618 case FORM_CAT:
16620 if(getPowerType()!=POWER_ENERGY)
16621 setPowerType(POWER_ENERGY);
16622 break;
16624 case FORM_BEAR:
16625 case FORM_DIREBEAR:
16627 if(getPowerType()!=POWER_RAGE)
16628 setPowerType(POWER_RAGE);
16629 break;
16631 default: // 0, for example
16633 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16634 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16635 setPowerType(Powers(cEntry->powerType));
16636 break;
16640 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16641 if (!reapplyMods)
16642 UpdateEquipSpellsAtFormChange();
16644 UpdateAttackPowerAndDamage();
16645 UpdateAttackPowerAndDamage(true);
16648 // Return true is the bought item has a max count to force refresh of window by caller
16649 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16651 // cheating attempt
16652 if(count < 1) count = 1;
16654 if(!isAlive())
16655 return false;
16657 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16658 if( !pProto )
16660 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16661 return false;
16664 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16665 if (!pCreature)
16667 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16668 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16669 return false;
16672 VendorItemData const* vItems = pCreature->GetVendorItems();
16673 if(!vItems || vItems->Empty())
16675 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16676 return false;
16679 size_t vendor_slot = vItems->FindItemSlot(item);
16680 if(vendor_slot >= vItems->GetItemCount())
16682 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16683 return false;
16686 VendorItem const* crItem = vItems->m_items[vendor_slot];
16688 // check current item amount if it limited
16689 if( crItem->maxcount != 0 )
16691 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16693 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16694 return false;
16698 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16700 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16701 return false;
16704 if(crItem->ExtendedCost)
16706 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16707 if(!iece)
16709 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16710 return false;
16713 // honor points price
16714 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16716 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16717 return false;
16720 // arena points price
16721 if(GetArenaPoints() < (iece->reqarenapoints * count))
16723 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16724 return false;
16727 // item base price
16728 for (uint8 i = 0; i < 5; ++i)
16730 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16732 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16733 return false;
16737 // check for personal arena rating requirement
16738 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16740 // probably not the proper equip err
16741 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16742 return false;
16746 uint32 price = pProto->BuyPrice * count;
16748 // reputation discount
16749 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16751 if( GetMoney() < price )
16753 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16754 return false;
16757 uint8 bag = 0; // init for case invalid bagGUID
16759 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16761 Bag *pBag;
16762 if( bagguid == GetGUID() )
16764 bag = INVENTORY_SLOT_BAG_0;
16766 else
16768 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16770 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16771 if( pBag )
16773 if( bagguid == pBag->GetGUID() )
16775 bag = i;
16776 break;
16783 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16785 ItemPosCountVec dest;
16786 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16787 if( msg != EQUIP_ERR_OK )
16789 SendEquipError( msg, NULL, NULL );
16790 return false;
16793 ModifyMoney( -(int32)price );
16794 if(crItem->ExtendedCost) // case for new honor system
16796 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16797 if(iece->reqhonorpoints)
16798 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16799 if(iece->reqarenapoints)
16800 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16801 for (uint8 i = 0; i < 5; ++i)
16803 if(iece->reqitem[i])
16804 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16808 if(Item *it = StoreNewItem( dest, item, true ))
16810 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16812 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16813 data << pCreature->GetGUID();
16814 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16815 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16816 data << (uint32)count;
16817 GetSession()->SendPacket(&data);
16819 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16822 else if( IsEquipmentPos( bag, slot ) )
16824 uint16 dest;
16825 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16826 if( msg != EQUIP_ERR_OK )
16828 SendEquipError( msg, NULL, NULL );
16829 return false;
16832 ModifyMoney( -(int32)price );
16833 if(crItem->ExtendedCost) // case for new honor system
16835 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16836 if(iece->reqhonorpoints)
16837 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16838 if(iece->reqarenapoints)
16839 ModifyArenaPoints( - int32(iece->reqarenapoints));
16840 for (uint8 i = 0; i < 5; ++i)
16842 if(iece->reqitem[i])
16843 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16847 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16849 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16851 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16852 data << pCreature->GetGUID();
16853 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16854 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16855 data << (uint32)count;
16856 GetSession()->SendPacket(&data);
16858 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16860 AutoUnequipOffhandIfNeed();
16863 else
16865 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16866 return false;
16869 return crItem->maxcount!=0;
16872 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16874 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16875 // the personal rating of the arena team must match the required limit as well
16876 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16877 uint32 max_personal_rating = 0;
16878 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16880 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16882 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16883 uint32 t_rating = at->GetRating();
16884 p_rating = p_rating<t_rating? p_rating : t_rating;
16885 if(max_personal_rating < p_rating)
16886 max_personal_rating = p_rating;
16889 return max_personal_rating;
16892 void Player::UpdateHomebindTime(uint32 time)
16894 // GMs never get homebind timer online
16895 if (m_InstanceValid || isGameMaster())
16897 if(m_HomebindTimer) // instance valid, but timer not reset
16899 // hide reminder
16900 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16901 data << uint32(0);
16902 data << uint32(0);
16903 GetSession()->SendPacket(&data);
16905 // instance is valid, reset homebind timer
16906 m_HomebindTimer = 0;
16908 else if (m_HomebindTimer > 0)
16910 if (time >= m_HomebindTimer)
16912 // teleport to homebind location
16913 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16915 else
16916 m_HomebindTimer -= time;
16918 else
16920 // instance is invalid, start homebind timer
16921 m_HomebindTimer = 60000;
16922 // send message to player
16923 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16924 data << m_HomebindTimer;
16925 data << uint32(1);
16926 GetSession()->SendPacket(&data);
16927 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16931 void Player::UpdatePvP(bool state, bool ovrride)
16933 if(!state || ovrride)
16935 SetPvP(state);
16936 if(Pet* pet = GetPet())
16937 pet->SetPvP(state);
16938 if(Unit* charmed = GetCharm())
16939 charmed->SetPvP(state);
16941 pvpInfo.endTimer = 0;
16943 else
16945 if(pvpInfo.endTimer != 0)
16946 pvpInfo.endTimer = time(NULL);
16947 else
16949 SetPvP(state);
16951 if(Pet* pet = GetPet())
16952 pet->SetPvP(state);
16953 if(Unit* charmed = GetCharm())
16954 charmed->SetPvP(state);
16959 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16961 SpellCooldown sc;
16962 sc.end = end_time;
16963 sc.itemid = itemid;
16964 m_spellCooldowns[spellid] = sc;
16967 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16969 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16970 return;
16972 // Get spell cooldown
16973 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16974 // Apply spellmods
16975 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16976 if (cooldown < 0)
16977 cooldown = 0;
16978 // Add cooldown
16979 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16980 // Send activate
16981 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16982 data << spellInfo->Id;
16983 data << GetGUID();
16984 SendDirectMessage(&data);
16986 //slot to be excluded while counting
16987 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16989 if(!enchantmentcondition)
16990 return true;
16992 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16994 if(!Condition)
16995 return true;
16997 uint8 curcount[4] = {0, 0, 0, 0};
16999 //counting current equipped gem colors
17000 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17002 if(i == slot)
17003 continue;
17004 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17005 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17007 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17009 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17010 if(!enchant_id)
17011 continue;
17013 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17014 if(!enchantEntry)
17015 continue;
17017 uint32 gemid = enchantEntry->GemID;
17018 if(!gemid)
17019 continue;
17021 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17022 if(!gemProto)
17023 continue;
17025 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17026 if(!gemProperty)
17027 continue;
17029 uint8 GemColor = gemProperty->color;
17031 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17033 if(tmpcolormask & GemColor)
17034 ++curcount[b];
17040 bool activate = true;
17042 for(int i = 0; i < 5; i++)
17044 if(!Condition->Color[i])
17045 continue;
17047 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17049 // if have <CompareColor> use them as count, else use <value> from Condition
17050 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17052 switch(Condition->Comparator[i])
17054 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17055 activate &= (_cur_gem < _cmp_gem) ? true : false;
17056 break;
17057 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17058 activate &= (_cur_gem > _cmp_gem) ? true : false;
17059 break;
17060 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17061 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17062 break;
17066 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");
17068 return activate;
17071 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17073 //cycle all equipped items
17074 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17076 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17077 if(slot == exceptslot)
17078 continue;
17080 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17082 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17083 continue;
17085 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17087 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17088 if(!enchant_id)
17089 continue;
17091 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17092 if(!enchantEntry)
17093 continue;
17095 uint32 condition = enchantEntry->EnchantmentCondition;
17096 if(condition)
17098 //was enchant active with/without item?
17099 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17100 //should it now be?
17101 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17103 // ignore item gem conditions
17104 //if state changed, (dis)apply enchant
17105 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17112 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17113 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17115 //cycle all equipped items
17116 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17118 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17119 if(slot == exceptslot)
17120 continue;
17122 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17124 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17125 continue;
17127 //cycle all (gem)enchants
17128 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17130 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17131 if(!enchant_id) //if no enchant go to next enchant(slot)
17132 continue;
17134 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17135 if(!enchantEntry)
17136 continue;
17138 //only metagems to be (de)activated, so only enchants with condition
17139 uint32 condition = enchantEntry->EnchantmentCondition;
17140 if(condition)
17141 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17146 void Player::LeaveBattleground(bool teleportToEntryPoint)
17148 if(BattleGround *bg = GetBattleGround())
17150 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17152 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17154 // call after remove to be sure that player resurrected for correct cast
17155 if(need_debuf)
17156 CastSpell(this, 26013, true); // Deserter
17160 bool Player::CanJoinToBattleground() const
17162 // check Deserter debuff
17163 if(GetDummyAura(26013))
17164 return false;
17166 return true;
17169 bool Player::CanReportAfkDueToLimit()
17171 // a player can complain about 15 people per 5 minutes
17172 if(m_bgAfkReportedCount >= 15)
17173 return false;
17174 ++m_bgAfkReportedCount;
17175 return true;
17178 ///This player has been blamed to be inactive in a battleground
17179 void Player::ReportedAfkBy(Player* reporter)
17181 BattleGround *bg = GetBattleGround();
17182 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17183 return;
17185 // check if player has 'Idle' or 'Inactive' debuff
17186 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17188 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17189 // 3 players have to complain to apply debuff
17190 if(m_bgAfkReporter.size() >= 3)
17192 // cast 'Idle' spell
17193 CastSpell(this, 43680, true);
17194 m_bgAfkReporter.clear();
17199 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17201 // gamemaster in GM mode see all, including ghosts
17202 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17203 return true;
17205 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17206 if (InBattleGround())
17208 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17209 return false;
17210 return true;
17213 // Live player see live player or dead player with not realized corpse
17214 if(pl->isAlive() || pl->m_deathTimer > 0)
17216 return isAlive() || m_deathTimer > 0;
17219 // Ghost see other friendly ghosts, that's for sure
17220 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17221 return true;
17223 // Dead player see live players near own corpse
17224 if(isAlive())
17226 Corpse *corpse = pl->GetCorpse();
17227 if(corpse)
17229 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17230 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17231 return true;
17235 // and not see any other
17236 return false;
17239 bool Player::IsVisibleGloballyFor( Player* u ) const
17241 if(!u)
17242 return false;
17244 // Always can see self
17245 if (u==this)
17246 return true;
17248 // Visible units, always are visible for all players
17249 if (GetVisibility() == VISIBILITY_ON)
17250 return true;
17252 // GMs are visible for higher gms (or players are visible for gms)
17253 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17254 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17256 // non faction visibility non-breakable for non-GMs
17257 if (GetVisibility() == VISIBILITY_OFF)
17258 return false;
17260 // non-gm stealth/invisibility not hide from global player lists
17261 return true;
17264 void Player::UpdateVisibilityOf(WorldObject* target)
17266 if(HaveAtClient(target))
17268 if(!target->isVisibleForInState(this,true))
17270 target->DestroyForPlayer(this);
17271 m_clientGUIDs.erase(target->GetGUID());
17273 #ifdef MANGOS_DEBUG
17274 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17275 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17276 #endif
17279 else
17281 if(target->isVisibleForInState(this,false))
17283 target->SendUpdateToPlayer(this);
17284 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17285 m_clientGUIDs.insert(target->GetGUID());
17287 #ifdef MANGOS_DEBUG
17288 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17289 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17290 #endif
17292 // target aura duration for caster show only if target exist at caster client
17293 // send data at target visibility change (adding to client)
17294 if(target!=this && target->isType(TYPEMASK_UNIT))
17295 SendAurasForTarget((Unit*)target);
17297 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17298 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17303 template<class T>
17304 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17306 s64.insert(target->GetGUID());
17309 template<>
17310 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17312 if(!target->IsTransport())
17313 s64.insert(target->GetGUID());
17316 template<class T>
17317 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17319 if(HaveAtClient(target))
17321 if(!target->isVisibleForInState(this,true))
17323 target->BuildOutOfRangeUpdateBlock(&data);
17324 m_clientGUIDs.erase(target->GetGUID());
17326 #ifdef MANGOS_DEBUG
17327 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17328 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));
17329 #endif
17332 else
17334 if(target->isVisibleForInState(this,false))
17336 visibleNow.insert(target);
17337 target->BuildUpdate(data_updates);
17338 target->BuildCreateUpdateBlockForPlayer(&data, this);
17339 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17341 #ifdef MANGOS_DEBUG
17342 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17343 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));
17344 #endif
17349 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17350 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17351 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17352 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17353 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17355 void Player::InitPrimaryProffesions()
17357 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17360 void Player::SendComboPoints()
17362 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17363 if (combotarget)
17365 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17366 data.append(combotarget->GetPackGUID());
17367 data << uint8(m_comboPoints);
17368 GetSession()->SendPacket(&data);
17372 void Player::AddComboPoints(Unit* target, int8 count)
17374 if(!count)
17375 return;
17377 // without combo points lost (duration checked in aura)
17378 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17380 if(target->GetGUID() == m_comboTarget)
17382 m_comboPoints += count;
17384 else
17386 if(m_comboTarget)
17387 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17388 target->RemoveComboPointHolder(GetGUIDLow());
17390 m_comboTarget = target->GetGUID();
17391 m_comboPoints = count;
17393 target->AddComboPointHolder(GetGUIDLow());
17396 if (m_comboPoints > 5) m_comboPoints = 5;
17397 if (m_comboPoints < 0) m_comboPoints = 0;
17399 SendComboPoints();
17402 void Player::ClearComboPoints()
17404 if(!m_comboTarget)
17405 return;
17407 // without combopoints lost (duration checked in aura)
17408 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17410 m_comboPoints = 0;
17412 SendComboPoints();
17414 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17415 target->RemoveComboPointHolder(GetGUIDLow());
17417 m_comboTarget = 0;
17420 void Player::SetGroup(Group *group, int8 subgroup)
17422 if(group == NULL) m_group.unlink();
17423 else
17425 // never use SetGroup without a subgroup unless you specify NULL for group
17426 assert(subgroup >= 0);
17427 m_group.link(group, this);
17428 m_group.setSubGroup((uint8)subgroup);
17432 void Player::SendInitialPacketsBeforeAddToMap()
17434 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17435 data << uint32(0); // unknown, may be rest state time or experience
17436 GetSession()->SendPacket(&data);
17438 // Homebind
17439 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17440 data << m_homebindX << m_homebindY << m_homebindZ;
17441 data << (uint32) m_homebindMapId;
17442 data << (uint32) m_homebindZoneId;
17443 GetSession()->SendPacket(&data);
17445 // SMSG_SET_PROFICIENCY
17446 // SMSG_UPDATE_AURA_DURATION
17448 // tutorial stuff
17449 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17450 for (int i = 0; i < 8; ++i)
17451 data << uint32( GetTutorialInt(i) );
17452 GetSession()->SendPacket(&data);
17454 SendInitialSpells();
17456 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17457 data << uint32(0); // count, for(count) uint32;
17458 GetSession()->SendPacket(&data);
17460 SendInitialActionButtons();
17461 SendInitialReputations();
17462 m_achievementMgr.SendAllAchievementData();
17463 UpdateZone(GetZoneId());
17464 SendInitWorldStates();
17466 // SMSG_SET_AURA_SINGLE
17468 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17469 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17470 data << (float)0.01666667f; // game speed
17471 GetSession()->SendPacket( &data );
17473 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17474 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17475 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17478 void Player::SendInitialPacketsAfterAddToMap()
17480 CastSpell(this, 836, true); // LOGINEFFECT
17482 // set some aura effects that send packet to player client after add player to map
17483 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17484 // same auras state lost at far teleport, send it one more time in this case also
17485 static const AuraType auratypes[] =
17487 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17488 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17489 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17491 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17493 Unit::AuraList const& auraList = GetAurasByType(*itr);
17494 if(!auraList.empty())
17495 auraList.front()->ApplyModifier(true,true);
17498 if(HasAuraType(SPELL_AURA_MOD_STUN))
17499 SetMovement(MOVE_ROOT);
17501 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17502 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17504 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17505 data.append(GetPackGUID());
17506 data << (uint32)2;
17507 SendMessageToSet(&data,true);
17510 SendAurasForTarget(this);
17511 SendEnchantmentDurations(); // must be after add to map
17512 SendItemDurations(); // must be after add to map
17515 void Player::SendUpdateToOutOfRangeGroupMembers()
17517 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17518 return;
17519 if(Group* group = GetGroup())
17520 group->UpdatePlayerOutOfRange(this);
17522 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17523 m_auraUpdateMask = 0;
17524 if(Pet *pet = GetPet())
17525 pet->ResetAuraUpdateMask();
17528 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17530 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17531 data << uint32(mapid);
17532 data << uint8(reason); // transfer abort reason
17533 switch(reason)
17535 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17536 case TRANSFER_ABORT_DIFFICULTY:
17537 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17538 data << uint8(arg);
17539 break;
17541 GetSession()->SendPacket(&data);
17544 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17546 // type of warning, based on the time remaining until reset
17547 uint32 type;
17548 if(time > 3600)
17549 type = RAID_INSTANCE_WELCOME;
17550 else if(time > 900 && time <= 3600)
17551 type = RAID_INSTANCE_WARNING_HOURS;
17552 else if(time > 300 && time <= 900)
17553 type = RAID_INSTANCE_WARNING_MIN;
17554 else
17555 type = RAID_INSTANCE_WARNING_MIN_SOON;
17556 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17557 data << uint32(type);
17558 data << uint32(mapid);
17559 data << uint32(time);
17560 GetSession()->SendPacket(&data);
17563 void Player::ApplyEquipCooldown( Item * pItem )
17565 for(int i = 0; i <5; ++i)
17567 _Spell const& spellData = pItem->GetProto()->Spells[i];
17569 // no spell
17570 if( !spellData.SpellId )
17571 continue;
17573 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17574 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17575 continue;
17577 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17579 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17580 data << pItem->GetGUID();
17581 data << uint32(spellData.SpellId);
17582 GetSession()->SendPacket(&data);
17586 void Player::resetSpells()
17588 // not need after this call
17589 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17591 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17592 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17595 // make full copy of map (spells removed and marked as deleted at another spell remove
17596 // and we can't use original map for safe iterative with visit each spell at loop end
17597 PlayerSpellMap smap = GetSpellMap();
17599 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17600 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17602 learnDefaultSpells();
17603 learnQuestRewardedSpells();
17606 void Player::learnDefaultSpells(bool loading)
17608 // learn default race/class spells
17609 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17610 std::list<CreateSpellPair>::const_iterator spell_itr;
17611 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17613 uint16 tspell = spell_itr->first;
17614 if (tspell)
17616 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17617 if(loading || !spell_itr->second) // not care about passive spells or loading case
17618 addSpell(tspell,spell_itr->second);
17619 else // but send in normal spell in game learn case
17620 learnSpell(tspell);
17625 void Player::learnQuestRewardedSpells(Quest const* quest)
17627 uint32 spell_id = quest->GetRewSpellCast();
17629 // skip quests without rewarded spell
17630 if( !spell_id )
17631 return;
17633 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17634 if(!spellInfo)
17635 return;
17637 // check learned spells state
17638 bool found = false;
17639 for(int i=0; i < 3; ++i)
17641 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17643 found = true;
17644 break;
17648 // skip quests with not teaching spell or already known spell
17649 if(!found)
17650 return;
17652 // prevent learn non first rank unknown profession and second specialization for same profession)
17653 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17654 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17656 // not have first rank learned (unlearned prof?)
17657 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17658 if( !HasSpell(first_spell) )
17659 return;
17661 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17662 if(!learnedInfo)
17663 return;
17665 // specialization
17666 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17668 // search other specialization for same prof
17669 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17671 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17672 continue;
17674 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17675 if(!itrInfo)
17676 return;
17678 // compare only specializations
17679 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17680 continue;
17682 // compare same chain spells
17683 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17684 continue;
17686 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17687 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17688 return;
17693 CastSpell( this, spell_id, true);
17696 void Player::learnQuestRewardedSpells()
17698 // learn spells received from quest completing
17699 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17701 // skip no rewarded quests
17702 if(!itr->second.m_rewarded)
17703 continue;
17705 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17706 if( !quest )
17707 continue;
17709 learnQuestRewardedSpells(quest);
17713 void Player::learnSkillRewardedSpells(uint32 skill_id )
17715 uint32 raceMask = getRaceMask();
17716 uint32 classMask = getClassMask();
17717 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17719 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17720 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17721 continue;
17722 // Check race if set
17723 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17724 continue;
17725 // Check class if set
17726 if (pAbility->classmask && !(pAbility->classmask & classMask))
17727 continue;
17729 if (sSpellStore.LookupEntry(pAbility->spellId))
17731 // Ok need learn spell
17732 learnSpell(pAbility->spellId);
17737 void Player::learnSkillRewardedSpells()
17739 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17741 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17742 continue;
17744 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17746 learnSkillRewardedSpells(pskill);
17750 void Player::SendAurasForTarget(Unit *target)
17752 WorldPacket data(SMSG_AURA_UPDATE_ALL);
17753 data.append(target->GetPackGUID());
17755 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17757 Aura* aura = itr->second;
17758 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17759 continue;
17761 data << uint8(aura->GetAuraSlot());
17762 data << uint32(aura->GetId());
17764 if(aura->GetId())
17766 uint8 auraFlags = aura->GetAuraFlags();
17767 data << uint8(auraFlags); // flags
17768 data << uint8(aura->GetAuraLevel()); // level
17769 data << uint8(aura->m_procCharges); // charges
17771 /*if(!(auraFlags & AFLAG_NOT_GUID))
17773 data << uint8(0) // packed GUID of someone (caster?)
17776 if(auraFlags & AFLAG_DURATION) // include aura duration
17778 data << uint32(aura->GetAuraMaxDuration());
17779 data << uint32(aura->GetAuraDuration());
17784 GetSession()->SendPacket(&data);
17787 void Player::SetDailyQuestStatus( uint32 quest_id )
17789 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17791 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17793 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17794 m_lastDailyQuestTime = time(NULL); // last daily quest time
17795 m_DailyQuestChanged = true;
17796 break;
17801 void Player::ResetDailyQuestStatus()
17803 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17804 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17806 // DB data deleted in caller
17807 m_DailyQuestChanged = false;
17808 m_lastDailyQuestTime = 0;
17811 BattleGround* Player::GetBattleGround() const
17813 if(GetBattleGroundId()==0)
17814 return NULL;
17816 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17819 bool Player::InArena() const
17821 BattleGround *bg = GetBattleGround();
17822 if(!bg || !bg->isArena())
17823 return false;
17825 return true;
17828 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17830 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17831 if(!bg)
17832 return false;
17834 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17835 return false;
17837 return true;
17840 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17842 if(queue_id < 1)
17843 return 0;
17845 if(queue_id >=6)
17846 queue_id = 6;
17848 return 10*(queue_id+1);
17851 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17853 if(queue_id >=6)
17854 return 255; // hardcoded max level
17856 return 10*(queue_id+2)-1;
17859 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17861 uint32 level = getLevel();
17862 if(level <= 19)
17863 return 0;
17864 else if (level > 69)
17865 return 6;
17866 else
17867 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17870 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17872 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17873 if(!vendor_faction)
17874 return 1.0f;
17876 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17877 if(rank <= REP_NEUTRAL)
17878 return 1.0f;
17880 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17883 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17885 uint32 racemask = getRaceMask();
17886 uint32 classmask = getClassMask();
17888 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17889 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17891 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17893 // skip wrong race skills
17894 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17895 return false;
17897 // skip wrong class skills
17898 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17899 return false;
17901 return true;
17904 bool Player::HasQuestForGO(int32 GOId)
17906 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17908 QuestStatusData qs=i->second;
17909 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17911 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17912 if(!qinfo)
17913 continue;
17915 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17916 continue;
17918 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17920 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17921 continue;
17923 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17924 return true;
17928 return false;
17931 void Player::UpdateForQuestsGO()
17933 if(m_clientGUIDs.empty())
17934 return;
17936 UpdateData udata;
17937 WorldPacket packet;
17938 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17940 if(IS_GAMEOBJECT_GUID(*itr))
17942 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17943 if(obj)
17944 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17947 udata.BuildPacket(&packet);
17948 GetSession()->SendPacket(&packet);
17951 void Player::SummonIfPossible(bool agree)
17953 if(!agree)
17955 m_summon_expire = 0;
17956 return;
17959 // expire and auto declined
17960 if(m_summon_expire < time(NULL))
17961 return;
17963 // stop taxi flight at summon
17964 if(isInFlight())
17966 GetMotionMaster()->MovementExpired();
17967 m_taxi.ClearTaxiDestinations();
17970 // drop flag at summon
17971 if(BattleGround *bg = GetBattleGround())
17972 bg->EventPlayerDroppedFlag(this);
17974 m_summon_expire = 0;
17976 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17979 void Player::RemoveItemDurations( Item *item )
17981 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17983 if(*itr==item)
17985 m_itemDuration.erase(itr);
17986 break;
17991 void Player::AddItemDurations( Item *item )
17993 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17995 m_itemDuration.push_back(item);
17996 item->SendTimeUpdate(this);
18000 void Player::AutoUnequipOffhandIfNeed()
18002 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18003 if(!offItem)
18004 return;
18006 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
18008 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
18009 return;
18011 ItemPosCountVec off_dest;
18012 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18013 if( off_msg == EQUIP_ERR_OK )
18015 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18016 StoreItem( off_dest, offItem, true );
18018 else
18020 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18024 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18026 if(spellInfo->EquippedItemClass < 0)
18027 return true;
18029 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18030 // for optimize check 2 used cases only
18031 switch(spellInfo->EquippedItemClass)
18033 case ITEM_CLASS_WEAPON:
18035 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18036 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18037 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18038 return true;
18039 break;
18041 case ITEM_CLASS_ARMOR:
18043 // tabard not have dependent spells
18044 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18045 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18046 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18047 return true;
18049 // shields can be equipped to offhand slot
18050 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18051 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18052 return true;
18054 // ranged slot can have some armor subclasses
18055 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18056 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18057 return true;
18059 break;
18061 default:
18062 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18063 break;
18066 return false;
18069 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18071 AuraMap& auras = GetAuras();
18072 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18074 Aura* aura = itr->second;
18076 // skip passive (passive item dependent spells work in another way) and not self applied auras
18077 SpellEntry const* spellInfo = aura->GetSpellProto();
18078 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18080 ++itr;
18081 continue;
18084 // skip if not item dependent or have alternative item
18085 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18087 ++itr;
18088 continue;
18091 // no alt item, remove aura, restart check
18092 RemoveAurasDueToSpell(aura->GetId());
18093 itr = auras.begin();
18096 // currently casted spells can be dependent from item
18097 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18099 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18100 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18101 InterruptSpell(i);
18105 uint32 Player::GetResurrectionSpellId()
18107 // search priceless resurrection possibilities
18108 uint32 prio = 0;
18109 uint32 spell_id = 0;
18110 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18111 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18113 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18114 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18116 switch((*itr)->GetId())
18118 case 20707: spell_id = 3026; break; // rank 1
18119 case 20762: spell_id = 20758; break; // rank 2
18120 case 20763: spell_id = 20759; break; // rank 3
18121 case 20764: spell_id = 20760; break; // rank 4
18122 case 20765: spell_id = 20761; break; // rank 5
18123 case 27239: spell_id = 27240; break; // rank 6
18124 default:
18125 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18126 continue;
18129 prio = 3;
18131 // Twisting Nether // prio: 2 (max)
18132 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18134 prio = 2;
18135 spell_id = 23700;
18139 // Reincarnation (passive spell) // prio: 1
18140 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18141 spell_id = 21169;
18143 return spell_id;
18146 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18148 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18150 // prepare data for near group iteration (PvP and !PvP cases)
18151 uint32 xp = 0;
18152 bool honored_kill = false;
18154 if(Group *pGroup = GetGroup())
18156 uint32 count = 0;
18157 uint32 sum_level = 0;
18158 Player* member_with_max_level = NULL;
18159 Player* not_gray_member_with_max_level = NULL;
18161 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18163 if(member_with_max_level)
18165 /// not get Xp in PvP or no not gray players in group
18166 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18168 /// skip in check PvP case (for speed, not used)
18169 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18170 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18171 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18173 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18175 Player* pGroupGuy = itr->getSource();
18176 if(!pGroupGuy)
18177 continue;
18179 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18180 continue; // member (alive or dead) or his corpse at req. distance
18182 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18183 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18184 honored_kill = true;
18186 // xp and reputation only in !PvP case
18187 if(!PvP)
18189 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18191 // if is in dungeon then all receive full reputation at kill
18192 // rewarded any alive/dead/near_corpse group member
18193 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18195 // XP updated only for alive group member
18196 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18197 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18199 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18201 pGroupGuy->GiveXP(itr_xp, pVictim);
18202 if(Pet* pet = pGroupGuy->GetPet())
18203 pet->GivePetXP(itr_xp/2);
18206 // quest objectives updated only for alive group member or dead but with not released body
18207 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18209 // normal creature (not pet/etc) can be only in !PvP case
18210 if(pVictim->GetTypeId()==TYPEID_UNIT)
18211 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18217 else // if (!pGroup)
18219 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18221 // honor can be in PvP and !PvP (racial leader) cases
18222 if(RewardHonor(pVictim,1))
18223 honored_kill = true;
18225 // xp and reputation only in !PvP case
18226 if(!PvP)
18228 RewardReputation(pVictim,1);
18229 GiveXP(xp, pVictim);
18231 if(Pet* pet = GetPet())
18232 pet->GivePetXP(xp);
18234 // normal creature (not pet/etc) can be only in !PvP case
18235 if(pVictim->GetTypeId()==TYPEID_UNIT)
18236 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18239 return xp || honored_kill;
18242 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18244 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18245 return true;
18247 if(isAlive())
18248 return false;
18250 Corpse* corpse = GetCorpse();
18251 if(!corpse)
18252 return false;
18254 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18257 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18259 Item* item = GetWeaponForAttack(attType,true);
18261 // unarmed only with base attack
18262 if(attType != BASE_ATTACK && !item)
18263 return 0;
18265 // weapon skill or (unarmed for base attack)
18266 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18267 return GetBaseSkillValue(skill);
18270 void Player::ResurectUsingRequestData()
18272 ResurrectPlayer(0.0f,false);
18274 if(GetMaxHealth() > m_resurrectHealth)
18275 SetHealth( m_resurrectHealth );
18276 else
18277 SetHealth( GetMaxHealth() );
18279 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18280 SetPower(POWER_MANA, m_resurrectMana );
18281 else
18282 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18284 SetPower(POWER_RAGE, 0 );
18286 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18288 SpawnCorpseBones();
18290 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18293 void Player::SetClientControl(Unit* target, uint8 allowMove)
18295 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18296 data.append(target->GetPackGUID());
18297 data << uint8(allowMove);
18298 GetSession()->SendPacket(&data);
18301 void Player::UpdateZoneDependentAuras( uint32 newZone )
18303 // remove new continent flight forms
18304 if( !isGameMaster() &&
18305 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
18307 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18308 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18311 // Some spells applied at enter into zone (with subzones)
18312 // Human Illusion
18313 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18314 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18316 uint32 spellid = 0;
18317 // all horde races
18318 if( GetTeam() == HORDE )
18319 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18320 // and some alliance races
18321 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18322 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18324 if(spellid && !HasAura(spellid,0) )
18325 CastSpell(this,spellid,true);
18329 void Player::UpdateAreaDependentAuras( uint32 newArea )
18331 // remove auras from spells with area limitations
18332 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18334 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18335 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
18336 RemoveAura(iter);
18337 else
18338 ++iter;
18341 // unmount if enter in this subzone
18342 if( newArea == 35)
18343 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18344 // Dragonmaw Illusion
18345 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18347 if( GetDummyAura(40214) )
18349 if( !HasAura(40216,0) )
18350 CastSpell(this,40216,true);
18351 if( !HasAura(42016,0) )
18352 CastSpell(this,42016,true);
18357 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18359 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18360 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18362 return copseReclaimDelay[0];
18365 time_t now = time(NULL);
18366 // 0..2 full period
18367 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18368 return copseReclaimDelay[count];
18371 void Player::UpdateCorpseReclaimDelay()
18373 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18375 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18376 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18377 return;
18379 time_t now = time(NULL);
18380 if(now < m_deathExpireTime)
18382 // full and partly periods 1..3
18383 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18384 if(count < MAX_DEATH_COUNT)
18385 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18386 else
18387 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18389 else
18390 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18393 void Player::SendCorpseReclaimDelay(bool load)
18395 Corpse* corpse = GetCorpse();
18396 if(!corpse)
18397 return;
18399 uint32 delay;
18400 if(load)
18402 if(corpse->GetGhostTime() > m_deathExpireTime)
18403 return;
18405 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18407 uint32 count;
18408 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18409 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18411 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18412 if(count>=MAX_DEATH_COUNT)
18413 count = MAX_DEATH_COUNT-1;
18415 else
18416 count=0;
18418 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18420 time_t now = time(NULL);
18421 if(now >= expected_time)
18422 return;
18424 delay = expected_time-now;
18426 else
18427 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18429 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18430 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18431 data << uint32(delay*1000);
18432 GetSession()->SendPacket( &data );
18435 Player* Player::GetNextRandomRaidMember(float radius)
18437 Group *pGroup = GetGroup();
18438 if(!pGroup)
18439 return NULL;
18441 std::vector<Player*> nearMembers;
18442 nearMembers.reserve(pGroup->GetMembersCount());
18444 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18446 Player* Target = itr->getSource();
18448 // IsHostileTo check duel and controlled by enemy
18449 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18450 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18451 nearMembers.push_back(Target);
18454 if (nearMembers.empty())
18455 return NULL;
18457 uint32 randTarget = urand(0,nearMembers.size()-1);
18458 return nearMembers[randTarget];
18461 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18463 float water_z = m->GetWaterLevel(x,y);
18464 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18465 uint8 flag1 = m->GetTerrainType(x,y);
18467 //!Underwater check, not in water if underground or above water level
18468 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18469 m_isunderwater &= 0x7A;
18470 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18471 m_isunderwater |= 0x01;
18473 //!in lava check, anywhere under lava level
18474 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18475 m_isunderwater |= 0x80;
18478 void Player::SetCanParry( bool value )
18480 if(m_canParry==value)
18481 return;
18483 m_canParry = value;
18484 UpdateParryPercentage();
18487 void Player::SetCanBlock( bool value )
18489 if(m_canBlock==value)
18490 return;
18492 m_canBlock = value;
18493 UpdateBlockPercentage();
18496 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18498 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18499 if(itr->pos == pos)
18500 return true;
18502 return false;
18505 bool Player::isAllowUseBattleGroundObject()
18507 return ( //InBattleGround() && // in battleground - not need, check in other cases
18508 !IsMounted() && // not mounted
18509 !HasStealthAura() && // not stealthed
18510 !HasInvisibilityAura() && // not invisible
18511 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18512 isAlive() // live player
18516 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18518 uint32 level = getLevel();
18520 if(level > sGtBarberShopCostBaseStore.GetNumRows())
18521 level = GT_MAX_LEVEL; // max level in this dbc
18523 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18524 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18525 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18527 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18528 return 0;
18530 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18532 if(!bsc) // shouldn't happen
18533 return 0xFFFFFFFF;
18535 float cost = 0;
18537 if(hairstyle != newhairstyle)
18538 cost += bsc->cost; // full price
18540 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18541 cost += bsc->cost * 0.5f; // +1/2 of price
18543 if(facialhair != newfacialhair)
18544 cost += bsc->cost * 0.75f; // +3/4 of price
18546 return uint32(cost);
18549 void Player::InitGlyphsForLevel()
18551 uint32 level = getLevel();
18552 uint32 value = 0;
18554 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18555 if(level >= 15)
18556 value |= (0x01 | 0x02);
18557 if(level >= 30)
18558 value |= 0x04;
18559 if(level >= 50)
18560 value |= 0x08;
18561 if(level >= 70)
18562 value |= 0x10;
18563 if(level >= 80)
18564 value |= 0x20;
18566 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);