Packet fixes
[getmangos.git] / src / game / Player.cpp
blob4ee84ebc91435f5c0f9242a233606560650049eb
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 reagests 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 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
484 m_name = name;
486 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
487 if(!info)
489 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
490 return false;
493 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
494 m_items[i] = NULL;
496 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
498 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
499 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
500 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
503 m_race = race;
504 m_class = class_;
506 SetMapId(info->mapId);
507 Relocate(info->positionX,info->positionY,info->positionZ);
509 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
510 if(!cEntry)
512 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
513 return false;
516 uint8 powertype = cEntry->powerType;
518 uint32 unitfield;
520 switch(powertype)
522 case POWER_ENERGY:
523 case POWER_MANA:
524 unitfield = 0x00000000;
525 break;
526 case POWER_RAGE:
527 unitfield = 0x00110000;
528 break;
529 case POWER_RUNIC_POWER:
530 unitfield = 0x0000EE00; //TODO: find correct unitfield here
531 break;
532 default:
533 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
534 return false;
537 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
538 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
540 switch(gender)
542 case GENDER_FEMALE:
543 SetDisplayId(info->displayId_f );
544 SetNativeDisplayId(info->displayId_f );
545 break;
546 case GENDER_MALE:
547 SetDisplayId(info->displayId_m );
548 SetNativeDisplayId(info->displayId_m );
549 break;
550 default:
551 sLog.outError("Invalid gender %u for player",gender);
552 return false;
553 break;
556 setFactionForRace(m_race);
558 SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
559 SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
560 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
561 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
562 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
564 //-1 is default value
565 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
567 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
568 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
569 SetByteValue(PLAYER_BYTES_3, 0, gender);
571 SetUInt32Value( PLAYER_GUILDID, 0 );
572 SetUInt32Value( PLAYER_GUILDRANK, 0 );
573 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
575 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
576 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
577 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
578 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
579 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
580 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
582 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
584 GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i);
585 if(gs && gs->Order)
586 SetGlyphSlot(gs->Order - 1, gs->Id);
589 // set starting level
590 if(getClass() == CLASS_DEATH_KNIGHT)
591 SetUInt32Value(UNIT_FIELD_LEVEL, 55);
592 else
593 SetUInt32Value( UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) );
595 // Played time
596 m_Last_tick = time(NULL);
597 m_Played_time[0] = 0;
598 m_Played_time[1] = 0;
600 // base stats and related field values
601 InitStatsForLevel();
602 InitTaxiNodesForLevel();
603 InitGlyphsForLevel();
604 InitTalentForLevel();
605 InitPrimaryProffesions(); // to max set before any spell added
607 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
608 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
609 SetHealth(GetMaxHealth());
610 if (getPowerType()==POWER_MANA)
612 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intelect)
613 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
616 learnDefaultSpells(true);
618 std::list<uint16>::const_iterator action_itr[4];
619 for(int i=0; i<4; i++)
620 action_itr[i] = info->action[i].begin();
622 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
624 uint16 taction[4];
625 for(int i=0; i<4 ;i++)
626 taction[i] = (*action_itr[i]);
628 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
630 for(int i=0; i<4 ;i++)
631 ++action_itr[i];
634 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
636 uint32 titem_id = item_id_itr->item_id;
637 uint32 titem_amount = item_id_itr->item_amount;
639 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
641 // attempt equip
642 uint16 eDest;
643 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
644 if( msg == EQUIP_ERR_OK )
646 EquipNewItem( eDest, titem_id, titem_amount, true);
647 AutoUnequipOffhandIfNeed();
648 continue; // equipped, to next
651 // attempt store
652 ItemPosCountVec sDest;
653 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
654 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
655 if( msg == EQUIP_ERR_OK )
657 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
658 continue; // stored, to next
661 // item can't be added
662 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,race,class_,msg);
665 // bags and main-hand weapon must equipped at this moment
666 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
667 // or ammo not equipped in special bag
668 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
670 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
672 uint16 eDest;
673 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
674 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
675 if( msg == EQUIP_ERR_OK )
677 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
678 EquipItem( eDest, pItem, true);
680 // move other items to more appropriate slots (ammo not equipped in special bag)
681 else
683 ItemPosCountVec sDest;
684 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
685 if( msg == EQUIP_ERR_OK )
687 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
688 pItem = StoreItem( sDest, pItem, true);
691 // if this is ammo then use it
692 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
693 if( msg == EQUIP_ERR_OK )
694 SetAmmo( pItem->GetProto()->ItemId );
698 // all item positions resolved
700 return true;
703 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
705 uint32 BreathRegen = (uint32)-1;
707 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
708 data << (uint32)Type;
709 data << MaxValue;
710 data << MaxValue;
711 data << BreathRegen;
712 data << (uint8)0;
713 data << (uint32)0; // spell id
714 GetSession()->SendPacket(&data);
717 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
719 if(Type==BREATH_TIMER)
720 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
722 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
723 data << (uint32)Type;
724 data << CurrentValue;
725 data << MaxValue;
726 data << Regen;
727 data << (uint8)0;
728 data << (uint32)0; // spell id
729 GetSession()->SendPacket( &data );
732 void Player::StopMirrorTimer(MirrorTimerType Type)
734 if(Type==BREATH_TIMER)
735 m_breathTimer = 0;
737 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
738 data << (uint32)Type;
739 GetSession()->SendPacket( &data );
742 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
744 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
745 data << (uint64)guid;
746 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
747 data << (uint32)damage;
748 data << (uint32)0;
749 data << (uint32)0;
750 SendMessageToSet(&data, true);
752 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
754 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
756 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
757 DurabilityLossAll(0.10f,false);
758 // durability lost message
759 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
760 GetSession()->SendPacket(&data);
764 void Player::HandleDrowning()
766 if(!m_isunderwater)
767 return;
769 //if have water breath , then remove bar
770 if(waterbreath || isGameMaster() || !isAlive())
772 StopMirrorTimer(BREATH_TIMER);
773 m_isunderwater = 0;
774 return;
777 uint32 UnderWaterTime = 1*MINUTE*1000; // default leangthL 1 min
779 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
780 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
781 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
783 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
785 //single trigger timer
786 if (!(m_isunderwater & 0x02))
788 m_isunderwater|= 0x02;
789 m_breathTimer = UnderWaterTime + 1000;
791 //single trigger "Breathbar"
792 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
794 m_isunderwater|= 0x04;
795 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
797 //continius trigger drowning "Damage"
798 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
800 //TODO: Check this formula
801 uint64 guid = GetGUID();
802 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
804 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
805 m_breathTimer = 2000;
808 //single trigger retract bar
809 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
811 m_isunderwater = 0x08;
813 uint32 BreathRegen = 10;
814 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
815 m_isunderwater = 0x10;
817 //remove bar
818 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
820 StopMirrorTimer(BREATH_TIMER);
821 m_isunderwater = 0;
825 void Player::HandleLava()
827 bool ValidArea = false;
829 if ((m_isunderwater & 0x80) && isAlive())
831 //Single trigger Set BreathTimer
832 if (!(m_isunderwater & 0x80))
834 m_isunderwater|= 0x04;
835 m_breathTimer = 1000;
837 //Reset BreathTimer and still in the lava
838 if (!m_breathTimer)
840 uint64 guid = GetGUID();
841 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
842 uint32 dmgZone = GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
844 // Deal lava damage only in lava zones.
845 switch(dmgZone)
847 case 0x8D:
848 ValidArea = false;
849 break;
850 case 0x94:
851 ValidArea = false;
852 break;
853 case 0x2CE:
854 ValidArea = false;
855 break;
856 case 0x2CF:
857 ValidArea = false;
858 break;
859 default:
860 if (dmgZone / 5 & 0x408)
861 ValidArea = true;
864 // if is valid area and is not gamemaster then deal damage
865 if ( ValidArea && !isGameMaster() )
866 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
868 m_breathTimer = 1000;
872 //Death timer disabled and WaterFlags reset
873 else if (m_deathState == DEAD)
875 m_breathTimer = 0;
876 m_isunderwater = 0;
880 ///The player sobers by 256 every 10 seconds
881 void Player::HandleSobering()
883 m_drunkTimer = 0;
885 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
886 SetDrunkValue(drunk);
889 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
891 if(value >= 23000)
892 return DRUNKEN_SMASHED;
893 if(value >= 12800)
894 return DRUNKEN_DRUNK;
895 if(value & 0xFFFE)
896 return DRUNKEN_TIPSY;
897 return DRUNKEN_SOBER;
900 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
902 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
904 m_drunk = newDrunkenValue;
905 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
907 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
909 // special drunk invisibility detection
910 if(newDrunkenState >= DRUNKEN_DRUNK)
911 m_detectInvisibilityMask |= (1<<6);
912 else
913 m_detectInvisibilityMask &= ~(1<<6);
915 if(newDrunkenState == oldDrunkenState)
916 return;
918 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
919 data << GetGUID();
920 data << uint32(newDrunkenState);
921 data << uint32(itemId);
923 SendMessageToSet(&data, true);
926 void Player::Update( uint32 p_time )
928 if(!IsInWorld())
929 return;
931 // undelivered mail
932 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
934 SendNewMail();
935 ++unReadMails;
937 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
938 m_nextMailDelivereTime = 0;
941 Unit::Update( p_time );
943 // update player only attacks
944 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
946 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
949 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
951 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
954 time_t now = time (NULL);
956 UpdatePvPFlag(now);
958 UpdateContestedPvP(p_time);
960 UpdateDuelFlag(now);
962 CheckDuelDistance(now);
964 UpdateAfkReport(now);
966 CheckExploreSystem();
968 // Update items that have just a limited lifetime
969 if (now>m_Last_tick)
970 UpdateItemDuration(uint32(now- m_Last_tick));
972 if (!m_timedquests.empty())
974 std::set<uint32>::iterator iter = m_timedquests.begin();
975 while (iter != m_timedquests.end())
977 QuestStatusData& q_status = mQuestStatus[*iter];
978 if( q_status.m_timer <= p_time )
980 uint32 quest_id = *iter;
981 ++iter; // current iter will be removed in FailTimedQuest
982 FailTimedQuest( quest_id );
984 else
986 q_status.m_timer -= p_time;
987 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
988 ++iter;
993 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
995 Unit *pVictim = getVictim();
996 if( !IsNonMeleeSpellCasted(false) && pVictim)
998 // default combat reach 10
999 // TODO add weapon,skill check
1001 float pldistance = ATTACK_DISTANCE;
1003 if (isAttackReady(BASE_ATTACK))
1005 if(!IsWithinDistInMap(pVictim, pldistance))
1007 setAttackTimer(BASE_ATTACK,100);
1008 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1010 SendAttackSwingNotInRange();
1011 m_swingErrorMsg = 1;
1014 //120 degrees of radiant range
1015 else if( !HasInArc( 2*M_PI/3, pVictim ))
1017 setAttackTimer(BASE_ATTACK,100);
1018 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1020 SendAttackSwingBadFacingAttack();
1021 m_swingErrorMsg = 2;
1024 else
1026 m_swingErrorMsg = 0; // reset swing error state
1028 // prevent base and off attack in same time, delay attack at 0.2 sec
1029 if(haveOffhandWeapon())
1031 uint32 off_att = getAttackTimer(OFF_ATTACK);
1032 if(off_att < ATTACK_DISPLAY_DELAY)
1033 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1035 AttackerStateUpdate(pVictim, BASE_ATTACK);
1036 resetAttackTimer(BASE_ATTACK);
1040 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1042 if(!IsWithinDistInMap(pVictim, pldistance))
1044 setAttackTimer(OFF_ATTACK,100);
1046 else if( !HasInArc( 2*M_PI/3, pVictim ))
1048 setAttackTimer(OFF_ATTACK,100);
1050 else
1052 // prevent base and off attack in same time, delay attack at 0.2 sec
1053 uint32 base_att = getAttackTimer(BASE_ATTACK);
1054 if(base_att < ATTACK_DISPLAY_DELAY)
1055 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1056 // do attack
1057 AttackerStateUpdate(pVictim, OFF_ATTACK);
1058 resetAttackTimer(OFF_ATTACK);
1062 Unit *owner = pVictim->GetOwner();
1063 Unit *u = owner ? owner : pVictim;
1064 if(u->IsPvP() && (!duel || duel->opponent != u))
1066 UpdatePvP(true);
1067 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1072 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1074 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1076 int time_inn = time(NULL)-GetTimeInnEnter();
1077 if (time_inn >= 10) //freeze update
1079 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1080 //speed collect rest bonus (section/in hour)
1081 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1082 UpdateInnerTime(time(NULL));
1087 if(m_regenTimer > 0)
1089 if(p_time >= m_regenTimer)
1090 m_regenTimer = 0;
1091 else
1092 m_regenTimer -= p_time;
1095 if (m_weaponChangeTimer > 0)
1097 if(p_time >= m_weaponChangeTimer)
1098 m_weaponChangeTimer = 0;
1099 else
1100 m_weaponChangeTimer -= p_time;
1103 if (m_zoneUpdateTimer > 0)
1105 if(p_time >= m_zoneUpdateTimer)
1107 uint32 newzone = GetZoneId();
1108 if( m_zoneUpdateId != newzone )
1109 UpdateZone(newzone); // also update area
1110 else
1112 // use area updates as well
1113 // needed for free far all arenas for example
1114 uint32 newarea = GetAreaId();
1115 if( m_areaUpdateId != newarea )
1116 UpdateArea(newarea);
1118 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1121 else
1122 m_zoneUpdateTimer -= p_time;
1125 if (isAlive())
1127 RegenerateAll();
1130 if (m_deathState == JUST_DIED)
1132 KillPlayer();
1135 if(m_nextSave > 0)
1137 if(p_time >= m_nextSave)
1139 // m_nextSave reseted in SaveToDB call
1140 SaveToDB();
1141 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1143 else
1145 m_nextSave -= p_time;
1149 //Breathtimer
1150 if(m_breathTimer > 0)
1152 if(p_time >= m_breathTimer)
1153 m_breathTimer = 0;
1154 else
1155 m_breathTimer -= p_time;
1159 //Handle Water/drowning
1160 HandleDrowning();
1162 //Handle lava
1163 HandleLava();
1165 //Handle detect stealth players
1166 if (m_DetectInvTimer > 0)
1168 if (p_time >= m_DetectInvTimer)
1170 m_DetectInvTimer = 3000;
1171 HandleStealthedUnitsDetection();
1173 else
1174 m_DetectInvTimer -= p_time;
1177 // Played time
1178 if (now > m_Last_tick)
1180 uint32 elapsed = uint32(now - m_Last_tick);
1181 m_Played_time[0] += elapsed; // Total played time
1182 m_Played_time[1] += elapsed; // Level played time
1183 m_Last_tick = now;
1186 if (m_drunk)
1188 m_drunkTimer += p_time;
1190 if (m_drunkTimer > 10000)
1191 HandleSobering();
1194 // not auto-free ghost from body in instances
1195 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1197 if(p_time >= m_deathTimer)
1199 m_deathTimer = 0;
1200 BuildPlayerRepop();
1201 RepopAtGraveyard();
1203 else
1204 m_deathTimer -= p_time;
1207 UpdateEnchantTime(p_time);
1208 UpdateHomebindTime(p_time);
1210 // group update
1211 SendUpdateToOutOfRangeGroupMembers();
1213 Pet* pet = GetPet();
1214 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1216 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1217 return;
1221 void Player::setDeathState(DeathState s)
1223 uint32 ressSpellId = 0;
1225 bool cur = isAlive();
1227 if(s == JUST_DIED && cur)
1229 // drunken state is cleared on death
1230 SetDrunkValue(0);
1231 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1232 ClearComboPoints();
1234 clearResurrectRequestData();
1236 // remove form before other mods to prevent incorrect stats calculation
1237 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1239 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1240 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1242 // remove uncontrolled pets
1243 RemoveMiniPet();
1244 RemoveGuardians();
1246 // save value before aura remove in Unit::setDeathState
1247 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1249 // passive spell
1250 if(!ressSpellId)
1251 ressSpellId = GetResurrectionSpellId();
1252 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1254 Unit::setDeathState(s);
1256 // restore resurrection spell id for player after aura remove
1257 if(s == JUST_DIED && cur && ressSpellId)
1258 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1260 if(isAlive() && !cur)
1262 //clear aura case after resurrection by another way (spells will be applied before next death)
1263 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1265 // restore default warrior stance
1266 if(getClass()== CLASS_WARRIOR)
1267 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1271 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1273 *p_data << GetGUID();
1274 *p_data << m_name;
1276 *p_data << getRace();
1277 uint8 pClass = getClass();
1278 *p_data << pClass;
1279 *p_data << getGender();
1281 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1282 *p_data << uint8(bytes);
1283 *p_data << uint8(bytes >> 8);
1284 *p_data << uint8(bytes >> 16);
1285 *p_data << uint8(bytes >> 24);
1287 bytes = GetUInt32Value(PLAYER_BYTES_2);
1288 *p_data << uint8(bytes);
1290 *p_data << uint8(getLevel()); // player level
1291 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1292 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1293 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1294 *p_data << zoneId;
1295 *p_data << GetMapId();
1297 *p_data << GetPositionX();
1298 *p_data << GetPositionY();
1299 *p_data << GetPositionZ();
1301 *p_data << GetUInt32Value(PLAYER_GUILDID); // guild id
1303 uint32 char_flags = 0;
1304 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1305 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1306 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1307 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1308 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1309 char_flags |= CHARACTER_FLAG_GHOST;
1310 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1311 char_flags |= CHARACTER_FLAG_RENAME;
1312 // always send the flag if declined names aren't used
1313 // to let the client select a default method of declining the name
1314 if(!sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) || (result && result->Fetch()[13].GetCppString() != ""))
1315 char_flags |= CHARACTER_FLAG_DECLINED;
1317 *p_data << (uint32)char_flags; // character flags
1318 *p_data << (uint32)0; // new wotlk
1319 *p_data << (uint8)1; // unknown
1321 // Pets info
1323 uint32 petDisplayId = 0;
1324 uint32 petLevel = 0;
1325 uint32 petFamily = 0;
1327 // show pet at selection character in character list only for non-ghost character
1328 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1330 Field* fields = result->Fetch();
1332 uint32 entry = fields[10].GetUInt32();
1333 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1334 if(cInfo)
1336 petDisplayId = fields[11].GetUInt32();
1337 petLevel = fields[12].GetUInt32();
1338 petFamily = cInfo->family;
1342 *p_data << (uint32)petDisplayId;
1343 *p_data << (uint32)petLevel;
1344 *p_data << (uint32)petFamily;
1347 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1348 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1349 items[i] = NULL;
1351 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1352 if (result)
1356 Field *fields = result->Fetch();
1357 uint8 slot = fields[0].GetUInt8() & 255;
1358 uint32 item_id = fields[1].GetUInt32();
1359 if( slot >= EQUIPMENT_SLOT_END )
1360 continue;
1362 items[slot] = objmgr.GetItemPrototype(item_id);
1363 if(!items[slot])
1365 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1366 continue;
1368 } while (result->NextRow());
1369 delete result;
1372 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1374 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1375 uint32 item_id = GetUInt32Value(visualbase);
1376 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1377 SpellItemEnchantmentEntry const *enchant = NULL;
1379 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1381 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1382 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1383 break;
1386 if (proto != NULL)
1388 *p_data << (uint32)proto->DisplayInfoID;
1389 *p_data << (uint8)proto->InventoryType;
1390 *p_data << (uint32)(enchant?enchant->aura_id:0);
1392 else
1394 *p_data << (uint32)0;
1395 *p_data << (uint8)0;
1396 *p_data << (uint32)0; // enchant?
1399 *p_data << (uint32)0; // first bag display id
1400 *p_data << (uint8)0; // first bag inventory type
1401 *p_data << (uint32)0; // enchant?
1404 bool Player::ToggleAFK()
1406 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1408 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1410 // afk player not allowed in battleground
1411 if(state && InBattleGround())
1412 LeaveBattleground();
1414 return state;
1417 bool Player::ToggleDND()
1419 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1421 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1424 uint8 Player::chatTag() const
1426 // it's bitmask
1427 // 0x8 - ??
1428 // 0x4 - gm
1429 // 0x2 - dnd
1430 // 0x1 - afk
1431 if(isGMChat())
1432 return 4;
1433 else if(isDND())
1434 return 3;
1435 if(isAFK())
1436 return 1;
1437 else
1438 return 0;
1441 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1443 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1445 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1446 return false;
1449 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1450 Pet* pet = GetPet();
1452 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1454 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1455 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1456 return false;
1458 // client without expansion support
1459 if(GetSession()->Expansion() < mEntry->Expansion())
1461 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessable map %u", GetName(), mapid);
1463 if(GetTransport())
1464 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1466 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1468 return false; // normal client can't teleport to this map...
1470 else
1472 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1475 // if we were on a transport, leave
1476 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1478 m_transport->RemovePassenger(this);
1479 m_transport = NULL;
1480 m_movementInfo.t_x = 0.0f;
1481 m_movementInfo.t_y = 0.0f;
1482 m_movementInfo.t_z = 0.0f;
1483 m_movementInfo.t_o = 0.0f;
1484 m_movementInfo.t_time = 0;
1487 SetSemaphoreTeleport(true);
1489 // The player was ported to another map and looses the duel immediatly.
1490 // We have to perform this check before the teleport, otherwise the
1491 // ObjectAccessor won't find the flag.
1492 if (duel && this->GetMapId()!=mapid)
1494 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1495 if (obj)
1496 DuelComplete(DUEL_FLED);
1499 // reset movement flags at teleport, because player will continue move with these flags after teleport
1500 SetUnitMovementFlags(0);
1502 if ((this->GetMapId() == mapid) && (!m_transport))
1504 // prepare zone change detect
1505 uint32 old_zone = GetZoneId();
1507 // near teleport
1508 if(!GetSession()->PlayerLogout())
1510 WorldPacket data;
1511 BuildTeleportAckMsg(&data, x, y, z, orientation);
1512 GetSession()->SendPacket(&data);
1513 SetPosition( x, y, z, orientation, true);
1515 else
1516 // this will be used instead of the current location in SaveToDB
1517 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1519 //BuildHeartBeatMsg(&data);
1520 //SendMessageToSet(&data, true);
1521 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1523 //same map, only remove pet if out of range
1524 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1526 if(pet->isControlled() && !pet->isTemporarySummoned() )
1527 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1528 else
1529 m_temporaryUnsummonedPetNumber = 0;
1531 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1535 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1536 CombatStop();
1538 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1540 // resummon pet
1541 if(pet && m_temporaryUnsummonedPetNumber)
1543 Pet* NewPet = new Pet;
1544 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1545 delete NewPet;
1547 m_temporaryUnsummonedPetNumber = 0;
1551 if(!GetSession()->PlayerLogout())
1553 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1554 SetSemaphoreTeleport(false);
1556 UpdateZone(GetZoneId());
1559 // new zone
1560 if(old_zone != GetZoneId())
1562 // honorless target
1563 if(pvpInfo.inHostileArea)
1564 CastSpell(this, 2479, true);
1567 else
1569 // far teleport to another map
1570 Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
1571 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1573 // Check enter rights before map getting to avoid creating instance copy for player
1574 // this check not dependent from map instance copy and same for all instance copies of selected map
1575 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1577 SetSemaphoreTeleport(false);
1578 return false;
1581 // If the map is not created, assume it is possible to enter it.
1582 // It will be created in the WorldPortAck.
1583 Map *map = MapManager::Instance().FindMap(mapid);
1584 if (!map || map->CanEnter(this))
1586 SetSelection(0);
1588 CombatStop();
1590 ResetContestedPvP();
1592 // remove player from battleground on far teleport (when changing maps)
1593 if(BattleGround const* bg = GetBattleGround())
1595 // Note: at battleground join battleground id set before teleport
1596 // and we already will found "current" battleground
1597 // just need check that this is targeted map or leave
1598 if(bg->GetMapId() != mapid)
1599 LeaveBattleground(false); // don't teleport to entry point
1602 // remove pet on map change
1603 if (pet)
1605 //leaving map -> delete pet right away (doing this later will cause problems)
1606 if(pet->isControlled() && !pet->isTemporarySummoned())
1607 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1608 else
1609 m_temporaryUnsummonedPetNumber = 0;
1611 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1614 // remove all dyn objects
1615 RemoveAllDynObjects();
1617 // stop spellcasting
1618 // not attempt interrupt teleportation spell at caster teleport
1619 if(!(options & TELE_TO_SPELL))
1620 if(IsNonMeleeSpellCasted(true))
1621 InterruptNonMeleeSpells(true);
1623 if(!GetSession()->PlayerLogout())
1625 // send transfer packets
1626 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1627 data << uint32(mapid);
1628 if (m_transport)
1630 data << m_transport->GetEntry() << GetMapId();
1632 GetSession()->SendPacket(&data);
1634 data.Initialize(SMSG_NEW_WORLD, (20));
1635 if (m_transport)
1637 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1639 else
1641 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1643 GetSession()->SendPacket( &data );
1644 SendSavedInstances();
1646 // remove from old map now
1647 if(oldmap) oldmap->Remove(this, false);
1650 // new final coordinates
1651 float final_x = x;
1652 float final_y = y;
1653 float final_z = z;
1654 float final_o = orientation;
1656 if(m_transport)
1658 final_x += m_movementInfo.t_x;
1659 final_y += m_movementInfo.t_y;
1660 final_z += m_movementInfo.t_z;
1661 final_o += m_movementInfo.t_o;
1664 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1665 // if the player is saved before worldportack (at logout for example)
1666 // this will be used instead of the current location in SaveToDB
1668 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1670 // move packet sent by client always after far teleport
1671 // SetPosition(final_x, final_y, final_z, final_o, true);
1672 SetDontMove(true);
1674 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1676 else
1677 return false;
1679 return true;
1682 void Player::AddToWorld()
1684 ///- Do not add/remove the player from the object storage
1685 ///- It will crash when updating the ObjectAccessor
1686 ///- The player should only be added when logging in
1687 Unit::AddToWorld();
1689 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1691 if(m_items[i])
1692 m_items[i]->AddToWorld();
1696 void Player::RemoveFromWorld()
1698 // cleanup
1699 if(IsInWorld())
1701 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1702 Uncharm();
1703 UnsummonAllTotems();
1704 RemoveMiniPet();
1705 RemoveGuardians();
1708 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1710 if(m_items[i])
1711 m_items[i]->RemoveFromWorld();
1714 ///- Do not add/remove the player from the object storage
1715 ///- It will crash when updating the ObjectAccessor
1716 ///- The player should only be removed when logging out
1717 Unit::RemoveFromWorld();
1720 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1722 float addRage;
1724 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1726 if(attacker)
1728 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1730 // talent who gave more rage on attack
1731 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1733 else
1735 addRage = damage/rageconversion*2.5;
1737 // Berserker Rage effect
1738 if(HasAura(18499,0))
1739 addRage *= 1.3;
1742 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1744 ModifyPower(POWER_RAGE, uint32(addRage*10));
1747 void Player::RegenerateAll()
1749 if (m_regenTimer != 0)
1750 return;
1751 uint32 regenDelay = 2000;
1753 // Not in combat or they have regeneration
1754 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1755 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1757 RegenerateHealth();
1758 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1759 Regenerate(POWER_RAGE);
1762 Regenerate( POWER_ENERGY );
1764 Regenerate( POWER_MANA );
1766 Regenerate( POWER_RUNIC_POWER );
1768 m_regenTimer = regenDelay;
1771 void Player::Regenerate(Powers power)
1773 uint32 curValue = GetPower(power);
1774 uint32 maxValue = GetMaxPower(power);
1776 float addvalue = 0.0f;
1778 switch (power)
1780 case POWER_MANA:
1782 bool recentCast = IsUnderLastManaUseEffect();
1783 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1784 if (recentCast)
1786 // Mangos Updates Mana in intervals of 2s, which is correct
1787 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1789 else
1791 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1793 } break;
1794 case POWER_RAGE: // Regenerate rage
1796 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1797 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1798 } break;
1799 case POWER_ENERGY: // Regenerate energy (rogue)
1800 addvalue = 20;
1801 break;
1802 case POWER_RUNIC_POWER:
1803 addvalue = 100; // TODO: find correct regen rate
1804 break;
1805 case POWER_FOCUS:
1806 case POWER_HAPPINESS:
1807 break;
1810 // Mana regen calculated in Player::UpdateManaRegen()
1811 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1812 if(power != POWER_MANA)
1814 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1815 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1816 if ((*i)->GetModifier()->m_miscvalue == power)
1817 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1820 if (power != POWER_RAGE)
1822 curValue += uint32(addvalue);
1823 if (curValue > maxValue)
1824 curValue = maxValue;
1826 else
1828 if(curValue <= uint32(addvalue))
1829 curValue = 0;
1830 else
1831 curValue -= uint32(addvalue);
1833 SetPower(power, curValue);
1836 void Player::RegenerateHealth()
1838 uint32 curValue = GetHealth();
1839 uint32 maxValue = GetMaxHealth();
1841 if (curValue >= maxValue) return;
1843 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1845 float addvalue = 0.0f;
1847 // polymorphed case
1848 if ( IsPolymorphed() )
1849 addvalue = GetMaxHealth()/3;
1850 // normal regen case (maybe partly in combat case)
1851 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1853 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1854 if (!isInCombat())
1856 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1857 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1858 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1860 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1861 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1863 if(!IsStandState())
1864 addvalue *= 1.5;
1867 // always regeneration bonus (including combat)
1868 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1870 if(addvalue < 0)
1871 addvalue = 0;
1873 ModifyHealth(int32(addvalue));
1876 bool Player::CanInteractWithNPCs(bool alive) const
1878 if(alive && !isAlive())
1879 return false;
1880 if(isInFlight())
1881 return false;
1883 return true;
1886 bool Player::IsUnderWater() const
1888 return IsInWater() &&
1889 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1892 void Player::SetInWater(bool apply)
1894 if(m_isInWater==apply)
1895 return;
1897 //define player in water by opcodes
1898 //move player's guid into HateOfflineList of those mobs
1899 //which can't swim and move guid back into ThreatList when
1900 //on surface.
1901 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1902 m_isInWater = apply;
1904 // remove auras that need water/land
1905 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1907 getHostilRefManager().updateThreatTables();
1910 void Player::SetGameMaster(bool on)
1912 if(on)
1914 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1915 setFaction(35);
1916 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1918 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1919 ResetContestedPvP();
1921 getHostilRefManager().setOnlineOfflineState(false);
1922 CombatStop();
1924 else
1926 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1927 setFactionForRace(getRace());
1928 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1930 // restore FFA PvP Server state
1931 if(sWorld.IsFFAPvPRealm())
1932 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1934 // restore FFA PvP area state, remove not allowed for GM mounts
1935 UpdateArea(m_areaUpdateId);
1937 getHostilRefManager().setOnlineOfflineState(true);
1940 ObjectAccessor::UpdateVisibilityForPlayer(this);
1943 void Player::SetGMVisible(bool on)
1945 if(on)
1947 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1949 // Reapply stealth/invisibility if active or show if not any
1950 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
1951 SetVisibility(VISIBILITY_GROUP_STEALTH);
1952 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
1953 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
1954 else
1955 SetVisibility(VISIBILITY_ON);
1957 else
1959 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
1961 SetAcceptWhispers(false);
1962 SetGameMaster(true);
1964 SetVisibility(VISIBILITY_OFF);
1968 bool Player::IsGroupVisibleFor(Player* p) const
1970 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
1972 default: return IsInSameGroupWith(p);
1973 case 1: return IsInSameRaidWith(p);
1974 case 2: return GetTeam()==p->GetTeam();
1978 bool Player::IsInSameGroupWith(Player const* p) const
1980 return p==this || GetGroup() != NULL &&
1981 GetGroup() == p->GetGroup() &&
1982 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
1985 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1986 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1987 void Player::UninviteFromGroup()
1989 if(GetGroupInvite()) // uninvited invitee
1991 Group* group = GetGroupInvite();
1992 group->RemoveInvite(this);
1994 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
1996 if(group->IsCreated())
1998 group->Disband(true);
1999 objmgr.RemoveGroup(group);
2001 else
2002 group->RemoveAllInvites();
2004 delete group;
2009 void Player::RemoveFromGroup(Group* group, uint64 guid)
2011 if(group)
2013 if (group->RemoveMember(guid, 0) <= 1)
2015 // group->Disband(); already disbanded in RemoveMember
2016 objmgr.RemoveGroup(group);
2017 delete group;
2018 // removemember sets the player's group pointer to NULL
2023 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2025 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2026 data << uint64(victim ? victim->GetGUID() : 0); // guid
2027 data << uint32(GivenXP+RestXP); // given experience
2028 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2029 if(victim)
2031 data << uint32(GivenXP); // experience without rested bonus
2032 data << float(1); // 1 - none 0 - 100% group bonus output
2034 data << uint8(0); // new 2.4.0
2035 GetSession()->SendPacket(&data);
2038 void Player::GiveXP(uint32 xp, Unit* victim)
2040 if ( xp < 1 )
2041 return;
2043 if(!isAlive())
2044 return;
2046 uint32 level = getLevel();
2048 // XP to money conversion processed in Player::RewardQuest
2049 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2050 return;
2052 // handle SPELL_AURA_MOD_XP_PCT auras
2053 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2054 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2055 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2057 // XP resting bonus for kill
2058 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2060 SendLogXPGain(xp,victim,rested_bonus_xp);
2062 uint32 curXP = GetUInt32Value(PLAYER_XP);
2063 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2064 uint32 newXP = curXP + xp + rested_bonus_xp;
2066 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2068 newXP -= nextLvlXP;
2070 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2071 GiveLevel(level + 1);
2073 level = getLevel();
2074 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2077 SetUInt32Value(PLAYER_XP, newXP);
2080 // Update player to next level
2081 // Current player experience not update (must be update by caller)
2082 void Player::GiveLevel(uint32 level)
2084 if ( level == getLevel() )
2085 return;
2087 PlayerLevelInfo info;
2088 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2090 PlayerClassLevelInfo classInfo;
2091 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2093 // send levelup info to client
2094 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2095 data << uint32(level);
2096 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2097 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2098 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2099 data << uint32(0);
2100 data << uint32(0);
2101 data << uint32(0);
2102 data << uint32(0);
2103 data << uint32(0);
2104 data << uint32(0);
2105 // end for
2106 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2107 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2109 GetSession()->SendPacket(&data);
2111 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2113 //update level, max level of skills
2114 if(getLevel()!= level)
2115 m_Played_time[1] = 0; // Level Played Time reset
2116 SetLevel(level);
2117 UpdateMaxSkills();
2119 // save base values (bonuses already included in stored stats
2120 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2121 SetCreateStat(Stats(i), info.stats[i]);
2123 SetCreateHealth(classInfo.basehealth);
2124 SetCreateMana(classInfo.basemana);
2126 InitTalentForLevel();
2127 InitTaxiNodesForLevel();
2128 InitGlyphsForLevel();
2130 UpdateAllStats();
2132 // set current level health and mana/energy to maximum after applying all mods.
2133 SetHealth(GetMaxHealth());
2134 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2135 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2136 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2137 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2138 SetPower(POWER_FOCUS, 0);
2139 SetPower(POWER_HAPPINESS, 0);
2141 // give level to summoned pet
2142 Pet* pet = GetPet();
2143 if(pet && pet->getPetType()==SUMMON_PET)
2144 pet->GivePetLevel(level);
2145 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2148 void Player::InitTalentForLevel()
2150 uint32 level = getLevel();
2151 // talents base at level diff ( talents = level - 9 but some can be used already)
2152 if(level < 10)
2154 // Remove all talent points
2155 if(m_usedTalentCount > 0) // Free any used talents
2157 resetTalents(true);
2158 SetFreeTalentPoints(0);
2161 else
2163 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2164 // if used more that have then reset
2165 if(m_usedTalentCount > talentPointsForLevel)
2167 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2168 resetTalents(true);
2169 else
2170 SetFreeTalentPoints(0);
2172 // else update amount of free points
2173 else
2174 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2178 void Player::InitStatsForLevel(bool reapplyMods)
2180 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2181 _RemoveAllStatBonuses();
2183 PlayerClassLevelInfo classInfo;
2184 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2186 PlayerLevelInfo info;
2187 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2189 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2190 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2192 UpdateMaxSkills ();
2194 // set default cast time multiplier
2195 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2197 // reset size before reapply auras
2198 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2200 // save base values (bonuses already included in stored stats
2201 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2202 SetCreateStat(Stats(i), info.stats[i]);
2204 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2205 SetStat(Stats(i), info.stats[i]);
2207 SetCreateHealth(classInfo.basehealth);
2209 //set create powers
2210 SetCreateMana(classInfo.basemana);
2212 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2214 InitStatBuffMods();
2216 //reset rating fields values
2217 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2218 SetUInt32Value(index, 0);
2220 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2221 for (int i = 0; i < 7; i++)
2223 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2224 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2225 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2228 //reset attack power, damage and attack speed fields
2229 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2230 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2231 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2233 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2234 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2235 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2236 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2237 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2238 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2240 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2241 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2242 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2243 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2244 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2245 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2247 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2248 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2249 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2250 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2252 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2253 for (uint8 i = 0; i < 7; ++i)
2254 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2256 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2257 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2258 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2260 // Dodge percentage
2261 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2263 // set armor (resistance 0) to original value (create_agility*2)
2264 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2265 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2266 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2267 // set other resistance to original value (0)
2268 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2270 SetResistance(SpellSchools(i), 0);
2271 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2272 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2275 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2276 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2277 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2279 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2280 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2282 // Init data for form but skip reapply item mods for form
2283 InitDataForForm(reapplyMods);
2285 // save new stats
2286 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2287 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2289 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2291 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2292 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2294 // cleanup unit flags (will be re-applied if need at aura load).
2295 RemoveFlag( UNIT_FIELD_FLAGS,
2296 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2297 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2298 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2299 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2300 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2301 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2303 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2304 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2306 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2308 // restore if need some important flags
2309 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2311 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2312 _ApplyAllStatBonuses();
2314 // set current level health and mana/energy to maximum after applying all mods.
2315 SetHealth(GetMaxHealth());
2316 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2317 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2318 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2319 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2320 SetPower(POWER_FOCUS, 0);
2321 SetPower(POWER_HAPPINESS, 0);
2322 SetPower(POWER_RUNIC_POWER, 0);
2325 void Player::SendInitialSpells()
2327 uint16 spellCount = 0;
2329 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2330 data << uint8(0);
2332 size_t countPos = data.wpos();
2333 data << uint16(spellCount); // spell count placeholder
2335 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2337 if(itr->second->state == PLAYERSPELL_REMOVED)
2338 continue;
2340 if(!itr->second->active || itr->second->disabled)
2341 continue;
2343 data << uint16(itr->first);
2344 //data << uint16(itr->second->slotId);
2345 data << uint16(0); // it's not slot id
2347 spellCount +=1;
2350 data.put<uint16>(countPos,spellCount); // write real count value
2352 uint16 spellCooldowns = m_spellCooldowns.size();
2353 data << uint16(spellCooldowns);
2354 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
2356 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2357 if(!sEntry)
2358 continue;
2360 data << uint16(itr->first);
2362 time_t cooldown = 0;
2363 time_t curTime = time(NULL);
2364 if(itr->second.end > curTime)
2365 cooldown = (itr->second.end-curTime)*1000;
2367 data << uint16(itr->second.itemid); // cast item id
2368 data << uint16(sEntry->Category); // spell category
2369 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2371 data << uint32(0);
2372 data << uint32(cooldown);
2374 else
2376 data << uint32(cooldown);
2377 data << uint32(0);
2381 GetSession()->SendPacket(&data);
2383 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2386 void Player::RemoveMail(uint32 id)
2388 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2390 if ((*itr)->messageID == id)
2392 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2393 m_mail.erase(itr);
2394 return;
2399 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2401 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2402 data << (uint32) mailId;
2403 data << (uint32) mailAction;
2404 data << (uint32) mailError;
2405 if ( mailError == MAIL_ERR_BAG_FULL )
2406 data << (uint32) equipError;
2407 else if( mailAction == MAIL_ITEM_TAKEN )
2409 data << (uint32) item_guid; // item guid low?
2410 data << (uint32) item_count; // item count?
2412 GetSession()->SendPacket(&data);
2415 void Player::SendNewMail()
2417 // deliver undelivered mail
2418 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2419 data << (uint32) 0;
2420 GetSession()->SendPacket(&data);
2423 void Player::UpdateNextMailTimeAndUnreads()
2425 // calculate next delivery time (min. from non-delivered mails
2426 // and recalculate unReadMail
2427 time_t cTime = time(NULL);
2428 m_nextMailDelivereTime = 0;
2429 unReadMails = 0;
2430 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2432 if((*itr)->deliver_time > cTime)
2434 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2435 m_nextMailDelivereTime = (*itr)->deliver_time;
2437 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2438 ++unReadMails;
2442 void Player::AddNewMailDeliverTime(time_t deliver_time)
2444 if(deliver_time <= time(NULL)) // ready now
2446 ++unReadMails;
2447 SendNewMail();
2449 else // not ready and no have ready mails
2451 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2452 m_nextMailDelivereTime = deliver_time;
2456 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2458 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2459 if (!spellInfo)
2461 // do character spell book cleanup (all characters)
2462 if(loading && !learning) // spell load case
2464 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2465 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2467 else
2468 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2470 return false;
2473 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2475 // do character spell book cleanup (all characters)
2476 if(loading && !learning) // spell load case
2478 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2479 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2481 else
2482 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2484 return false;
2487 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2489 bool disabled_case = false;
2490 bool superceded_old = false;
2492 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2493 if (itr != m_spells.end())
2495 // update active state for known spell
2496 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2498 itr->second->active = active;
2500 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2501 if(loading && !learning)
2502 itr->second->state = PLAYERSPELL_UNCHANGED;
2503 else if(itr->second->state != PLAYERSPELL_NEW)
2504 itr->second->state = PLAYERSPELL_CHANGED;
2506 if(!active)
2508 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2509 data << uint16(spell_id);
2510 GetSession()->SendPacket(&data);
2512 return active; // learn (show in spell book if active now)
2515 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2517 if(itr->second->state != PLAYERSPELL_NEW)
2518 itr->second->state = PLAYERSPELL_CHANGED;
2519 itr->second->disabled = disabled;
2521 if(disabled)
2522 return false;
2524 disabled_case = true;
2526 else switch(itr->second->state)
2528 case PLAYERSPELL_UNCHANGED: // known saved spell
2529 return false;
2530 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2532 delete itr->second;
2533 m_spells.erase(itr);
2534 state = PLAYERSPELL_CHANGED;
2535 break; // need re-add
2537 default: // known not saved yet spell (new or modified)
2539 // can be in case spell loading but learned at some previous spell loading
2540 if(loading && !learning)
2541 itr->second->state = PLAYERSPELL_UNCHANGED;
2543 return false;
2548 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2550 // talent: unlearn all other talent ranks (high and low)
2551 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2553 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2555 for(int i=0; i <5; ++i)
2557 // skip learning spell and no rank spell case
2558 uint32 rankSpellId = talentInfo->RankID[i];
2559 if(!rankSpellId || rankSpellId==spell_id)
2560 continue;
2562 // skip unknown ranks
2563 if(!HasSpell(rankSpellId))
2564 continue;
2566 removeSpell(rankSpellId);
2570 // non talent spell: learn low ranks (recursive call)
2571 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2573 if(loading) // at spells loading, no output, but allow save
2574 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2575 else // at normal learning
2576 learnSpell(prev_spell);
2579 PlayerSpell *newspell = new PlayerSpell;
2580 newspell->active = active;
2581 newspell->state = state;
2582 newspell->disabled = disabled;
2584 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2585 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2587 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2589 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2590 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2591 if(!i_spellInfo) continue;
2593 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2595 if(itr->second->active)
2597 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2599 if(!loading) // not send spell (re-/over-)learn packets at loading
2601 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2602 data << uint16(itr->first);
2603 data << uint16(spell_id);
2604 GetSession()->SendPacket( &data );
2607 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2608 itr->second->active = false;
2609 itr->second->state = PLAYERSPELL_CHANGED;
2610 superceded_old = true; // new spell replace old in action bars and spell book.
2612 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2614 if(!loading) // not send spell (re-/over-)learn packets at loading
2616 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2617 data << uint16(spell_id);
2618 data << uint16(itr->first);
2619 GetSession()->SendPacket( &data );
2622 // mark new spell as disable (not learned yet for client and will not learned)
2623 newspell->active = false;
2624 if(newspell->state != PLAYERSPELL_NEW)
2625 newspell->state = PLAYERSPELL_CHANGED;
2632 uint16 tmpslot=slot_id;
2634 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2636 uint16 maxid = 0;
2637 PlayerSpellMap::iterator itr;
2638 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2640 if(itr->second->state == PLAYERSPELL_REMOVED)
2641 continue;
2642 if (itr->second->slotId > maxid)
2643 maxid = itr->second->slotId;
2645 tmpslot = maxid + 1;
2648 newspell->slotId = tmpslot;
2649 m_spells[spell_id] = newspell;
2651 // return false if spell disabled
2652 if (newspell->disabled)
2653 return false;
2656 uint32 talentCost = GetTalentSpellCost(spell_id);
2658 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2659 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2660 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2662 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2663 CastSpell(this, spell_id, true);
2665 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2666 else if (IsPassiveSpell(spell_id))
2668 // if spell doesn't require a stance or the player is in the required stance
2669 if( ( !spellInfo->Stances &&
2670 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2671 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2672 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2673 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2674 (spell_id == 5420 && m_form == FORM_TREE) ||
2675 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2676 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2677 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2678 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2679 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2680 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2681 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2682 //Check CasterAuraStates
2683 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2684 CastSpell(this, spell_id, true);
2686 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2688 CastSpell(this, spell_id, true);
2689 return false;
2692 // update used talent points count
2693 m_usedTalentCount += talentCost;
2695 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2696 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2698 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2699 SetFreePrimaryProffesions(freeProfs-1);
2702 // add dependent skills
2703 uint16 maxskill = GetMaxSkillValueForLevel();
2705 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2707 if(spellLearnSkill)
2709 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2710 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2712 if(skill_value < spellLearnSkill->value)
2713 skill_value = spellLearnSkill->value;
2715 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2717 if(skill_max_value < new_skill_max_value)
2718 skill_max_value = new_skill_max_value;
2720 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2722 else
2724 // not ranked skills
2725 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2726 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2728 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2730 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2731 if(!pSkill)
2732 continue;
2734 if(HasSkill(pSkill->id))
2735 continue;
2737 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2738 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2739 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2740 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2741 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2743 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2745 case SKILL_RANGE_LANGUAGE:
2746 SetSkill(pSkill->id, 300, 300 );
2747 break;
2748 case SKILL_RANGE_LEVEL:
2749 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2750 break;
2751 case SKILL_RANGE_MONO:
2752 SetSkill(pSkill->id, 1, 1 );
2753 break;
2754 default:
2755 break;
2761 // learn dependent spells
2762 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2763 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2765 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2767 if(!itr->second.autoLearned)
2769 if(loading) // at spells loading, no output, but allow save
2770 addSpell(itr->second.spell,true,true,loading);
2771 else // at normal learning
2772 learnSpell(itr->second.spell);
2776 if(!loading)
2777 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2779 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2780 return active && !disabled && !superceded_old;
2783 void Player::learnSpell(uint32 spell_id)
2785 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2787 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2788 bool active = disabled ? itr->second->active : true;
2790 bool learning = addSpell(spell_id,active);
2792 // learn all disabled higher ranks (recursive)
2793 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2794 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2796 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2797 if (disabled && iter != m_spells.end() && iter->second->disabled)
2798 learnSpell(i->second);
2801 // prevent duplicated entires in spell book
2802 if(!learning)
2803 return;
2805 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2806 data << uint32(spell_id);
2807 GetSession()->SendPacket(&data);
2810 void Player::removeSpell(uint32 spell_id, bool disabled)
2812 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2813 if (itr == m_spells.end())
2814 return;
2816 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2817 return;
2819 // unlearn non talent higher ranks (recursive)
2820 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2821 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2822 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2823 removeSpell(itr2->second,disabled);
2825 // removing
2826 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2827 data << uint16(spell_id);
2828 GetSession()->SendPacket(&data);
2830 if (disabled)
2832 itr->second->disabled = disabled;
2833 if(itr->second->state != PLAYERSPELL_NEW)
2834 itr->second->state = PLAYERSPELL_CHANGED;
2836 else
2838 if(itr->second->state == PLAYERSPELL_NEW)
2840 delete itr->second;
2841 m_spells.erase(itr);
2843 else
2844 itr->second->state = PLAYERSPELL_REMOVED;
2847 RemoveAurasDueToSpell(spell_id);
2849 // remove pet auras
2850 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2851 RemovePetAura(petSpell);
2853 // free talent points
2854 uint32 talentCosts = GetTalentSpellCost(spell_id);
2855 if(talentCosts > 0)
2857 if(talentCosts < m_usedTalentCount)
2858 m_usedTalentCount -= talentCosts;
2859 else
2860 m_usedTalentCount = 0;
2863 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2864 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2866 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2867 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2868 SetFreePrimaryProffesions(freeProfs);
2871 // remove dependent skill
2872 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2873 if(spellLearnSkill)
2875 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2876 if(!prev_spell) // first rank, remove skill
2877 SetSkill(spellLearnSkill->skill,0,0);
2878 else
2880 // search prev. skill setting by spell ranks chain
2881 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2882 while(!prevSkill && prev_spell)
2884 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2885 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2888 if(!prevSkill) // not found prev skill setting, remove skill
2889 SetSkill(spellLearnSkill->skill,0,0);
2890 else // set to prev. skill setting values
2892 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2893 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2895 if(skill_value > prevSkill->value)
2896 skill_value = prevSkill->value;
2898 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2900 if(skill_max_value > new_skill_max_value)
2901 skill_max_value = new_skill_max_value;
2903 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2908 else
2910 // not ranked skills
2911 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2912 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2914 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2916 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2917 if(!pSkill)
2918 continue;
2920 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2921 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2922 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2923 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2924 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2926 // not reset skills for professions and racial abilities
2927 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2928 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2929 continue;
2931 SetSkill(pSkill->id, 0, 0 );
2936 // remove dependent spells
2937 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2938 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2940 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2941 removeSpell(itr2->second.spell, disabled);
2944 void Player::RemoveArenaSpellCooldowns()
2946 // remove cooldowns on spells that has < 15 min CD
2947 SpellCooldowns::iterator itr, next;
2948 // iterate spell cooldowns
2949 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2951 next = itr;
2952 ++next;
2953 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
2954 // check if spellentry is present and if the cooldown is less than 15 mins
2955 if( entry &&
2956 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
2957 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
2959 // notify player
2960 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2961 data << uint32(itr->first);
2962 data << GetGUID();
2963 GetSession()->SendPacket(&data);
2964 // remove cooldown
2965 m_spellCooldowns.erase(itr);
2970 void Player::RemoveAllSpellCooldown()
2972 if(!m_spellCooldowns.empty())
2974 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
2976 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2977 data << uint32(itr->first);
2978 data << uint64(GetGUID());
2979 GetSession()->SendPacket(&data);
2981 m_spellCooldowns.clear();
2985 void Player::_LoadSpellCooldowns(QueryResult *result)
2987 m_spellCooldowns.clear();
2989 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2991 if(result)
2993 time_t curTime = time(NULL);
2997 Field *fields = result->Fetch();
2999 uint32 spell_id = fields[0].GetUInt32();
3000 uint32 item_id = fields[1].GetUInt32();
3001 time_t db_time = (time_t)fields[2].GetUInt64();
3003 if(!sSpellStore.LookupEntry(spell_id))
3005 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3006 continue;
3009 // skip outdated cooldown
3010 if(db_time <= curTime)
3011 continue;
3013 AddSpellCooldown(spell_id, item_id, db_time);
3015 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3017 while( result->NextRow() );
3019 delete result;
3023 void Player::_SaveSpellCooldowns()
3025 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3027 time_t curTime = time(NULL);
3029 // remove outdated and save active
3030 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3032 if(itr->second.end <= curTime)
3033 m_spellCooldowns.erase(itr++);
3034 else
3036 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));
3037 ++itr;
3042 uint32 Player::resetTalentsCost() const
3044 // The first time reset costs 1 gold
3045 if(m_resetTalentsCost < 1*GOLD)
3046 return 1*GOLD;
3047 // then 5 gold
3048 else if(m_resetTalentsCost < 5*GOLD)
3049 return 5*GOLD;
3050 // After that it increases in increments of 5 gold
3051 else if(m_resetTalentsCost < 10*GOLD)
3052 return 10*GOLD;
3053 else
3055 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3056 if(months > 0)
3058 // This cost will be reduced by a rate of 5 gold per month
3059 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3060 // to a minimum of 10 gold.
3061 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3063 else
3065 // After that it increases in increments of 5 gold
3066 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3067 // until it hits a cap of 50 gold.
3068 if(new_cost > 50*GOLD)
3069 new_cost = 50*GOLD;
3070 return new_cost;
3075 bool Player::resetTalents(bool no_cost)
3077 // not need after this call
3078 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3080 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3081 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3084 uint32 level = getLevel();
3085 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3087 if (m_usedTalentCount == 0)
3089 SetFreeTalentPoints(talentPointsForLevel);
3090 return false;
3093 uint32 cost = 0;
3095 if(!no_cost)
3097 cost = resetTalentsCost();
3099 if (GetMoney() < cost)
3101 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3102 return false;
3106 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3108 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3110 if (!talentInfo) continue;
3112 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3114 if(!talentTabInfo)
3115 continue;
3117 // unlearn only talents for character class
3118 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3119 // to prevent unexpected lost normal learned spell skip another class talents
3120 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3121 continue;
3123 for (int j = 0; j < 5; j++)
3125 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3127 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3129 ++itr;
3130 continue;
3133 // remove learned spells (all ranks)
3134 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3136 // unlearn if first rank is talent or learned by talent
3137 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3139 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3140 itr = GetSpellMap().begin();
3141 continue;
3143 else
3144 ++itr;
3149 SetFreeTalentPoints(talentPointsForLevel);
3151 if(!no_cost)
3153 ModifyMoney(-(int32)cost);
3155 m_resetTalentsCost = cost;
3156 m_resetTalentsTime = time(NULL);
3159 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3160 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3162 return true;
3165 bool Player::_removeSpell(uint16 spell_id)
3167 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3168 if (itr != m_spells.end())
3170 delete itr->second;
3171 m_spells.erase(itr);
3172 return true;
3174 return false;
3177 Mail* Player::GetMail(uint32 id)
3179 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
3181 if ((*itr)->messageID == id)
3183 return (*itr);
3186 return NULL;
3189 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3191 if(target == this)
3193 Object::_SetCreateBits(updateMask, target);
3195 else
3197 for(uint16 index = 0; index < m_valuesCount; index++)
3199 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3200 updateMask->SetBit(index);
3205 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3207 if(target == this)
3209 Object::_SetUpdateBits(updateMask, target);
3211 else
3213 Object::_SetUpdateBits(updateMask, target);
3214 *updateMask &= updateVisualBits;
3218 void Player::InitVisibleBits()
3220 updateVisualBits.SetCount(PLAYER_END);
3222 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3223 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3224 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3225 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3226 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3227 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3228 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3229 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3230 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3231 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3232 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3233 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3234 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3235 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3236 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3237 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3238 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3239 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3240 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3241 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3242 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3243 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3244 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3245 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3246 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3247 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3248 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3249 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3250 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3251 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3252 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3253 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3254 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3255 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3256 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3257 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3258 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3259 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3260 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3261 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3262 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3263 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3264 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3265 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3266 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3267 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3268 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3269 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3270 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3271 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3272 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3273 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3274 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3275 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3276 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3278 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3279 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3280 updateVisualBits.SetBit(PLAYER_FLAGS);
3281 updateVisualBits.SetBit(PLAYER_GUILDID);
3282 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3283 updateVisualBits.SetBit(PLAYER_BYTES);
3284 updateVisualBits.SetBit(PLAYER_BYTES_2);
3285 updateVisualBits.SetBit(PLAYER_BYTES_3);
3286 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3287 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3289 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3290 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3291 updateVisualBits.SetBit(i);
3293 // Players visible items are not inventory stuff
3294 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3296 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3298 // item creator
3299 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3300 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3302 // item entry
3303 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3305 // item enchantments
3306 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3307 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3309 // random properties
3310 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3311 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3312 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3315 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3318 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3320 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3322 if(m_items[i] == NULL)
3323 continue;
3325 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3328 if(target == this)
3330 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3332 if(m_items[i] == NULL)
3333 continue;
3335 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3337 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3339 if(m_items[i] == NULL)
3340 continue;
3342 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3346 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3349 void Player::DestroyForPlayer( Player *target ) const
3351 Unit::DestroyForPlayer( target );
3353 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3355 if(m_items[i] == NULL)
3356 continue;
3358 m_items[i]->DestroyForPlayer( target );
3361 if(target == this)
3363 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3365 if(m_items[i] == NULL)
3366 continue;
3368 m_items[i]->DestroyForPlayer( target );
3370 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3372 if(m_items[i] == NULL)
3373 continue;
3375 m_items[i]->DestroyForPlayer( target );
3380 bool Player::HasSpell(uint32 spell) const
3382 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3383 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3386 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3388 if (!trainer_spell)
3389 return TRAINER_SPELL_RED;
3391 if (!trainer_spell->spell)
3392 return TRAINER_SPELL_RED;
3394 // known spell
3395 if(HasSpell(trainer_spell->spell))
3396 return TRAINER_SPELL_GRAY;
3398 // check race/class requirement
3399 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3400 return TRAINER_SPELL_RED;
3402 // check level requirement
3403 if(getLevel() < trainer_spell->reqlevel)
3404 return TRAINER_SPELL_RED;
3406 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3408 // check prev.rank requirement
3409 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3410 return TRAINER_SPELL_RED;
3412 // check additional spell requirement
3413 if(spell_chain->req && !HasSpell(spell_chain->req))
3414 return TRAINER_SPELL_RED;
3417 // check skill requirement
3418 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3419 return TRAINER_SPELL_RED;
3421 // exist, already checked at loading
3422 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3424 // secondary prof. or not prof. spell
3425 uint32 skill = spell->EffectMiscValue[1];
3427 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3428 return TRAINER_SPELL_GREEN;
3430 // check primary prof. limit
3431 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3432 return TRAINER_SPELL_RED;
3434 return TRAINER_SPELL_GREEN;
3437 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3439 uint32 guid = GUID_LOPART(playerguid);
3441 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3442 // bones will be deleted by corpse/bones deleting thread shortly
3443 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3445 // remove from guild
3446 uint32 guildId = GetGuildIdFromDB(playerguid);
3447 if(guildId != 0)
3449 Guild* guild = objmgr.GetGuildById(guildId);
3450 if(guild)
3451 guild->DelMember(guid);
3454 // the player was uninvited already on logout so just remove from group
3455 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3456 if(resultGroup)
3458 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3459 delete resultGroup;
3460 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3461 if(group)
3463 RemoveFromGroup(group, playerguid);
3467 // remove signs from petitions (also remove petitions if owner);
3468 RemovePetitionsAndSigns(playerguid, 10);
3470 // return back all mails with COD and Item 0 1 2 3 4 5 6
3471 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);
3472 if(resultMail)
3476 Field *fields = resultMail->Fetch();
3478 uint32 mail_id = fields[0].GetUInt32();
3479 uint16 mailTemplateId= fields[1].GetUInt16();
3480 uint32 sender = fields[2].GetUInt32();
3481 std::string subject = fields[3].GetCppString();
3482 uint32 itemTextId = fields[4].GetUInt32();
3483 uint32 money = fields[5].GetUInt32();
3484 bool has_items = fields[6].GetBool();
3486 //we can return mail now
3487 //so firstly delete the old one
3488 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3490 MailItemsInfo mi;
3491 if(has_items)
3493 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3494 if(resultItems)
3498 Field *fields2 = resultItems->Fetch();
3500 uint32 item_guidlow = fields2[0].GetUInt32();
3501 uint32 item_template = fields2[1].GetUInt32();
3503 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3504 if(!itemProto)
3506 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3507 continue;
3510 Item *pItem = NewItemOrBag(itemProto);
3511 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3513 pItem->FSetState(ITEM_REMOVED);
3514 pItem->SaveToDB(); // it also deletes item object !
3515 continue;
3518 mi.AddItem(item_guidlow, item_template, pItem);
3520 while (resultItems->NextRow());
3522 delete resultItems;
3526 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3528 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3530 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, 0, mailTemplateId);
3532 while (resultMail->NextRow());
3534 delete resultMail;
3537 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3538 // Get guids of character's pets, will deleted in transaction
3539 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3541 // NOW we can finally clear other DB data related to character
3542 CharacterDatabase.BeginTransaction();
3543 if (resultPets)
3547 Field *fields3 = resultPets->Fetch();
3548 uint32 petguidlow = fields3[0].GetUInt32();
3549 Pet::DeleteFromDB(petguidlow);
3550 } while (resultPets->NextRow());
3551 delete resultPets;
3554 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3555 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3556 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3557 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3558 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3559 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3560 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3561 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3562 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3563 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3564 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3565 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3566 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3567 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3568 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3569 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3570 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3571 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3572 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3573 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3574 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3575 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3576 CharacterDatabase.CommitTransaction();
3578 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3579 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3582 void Player::SetMovement(PlayerMovementType pType)
3584 WorldPacket data;
3585 switch(pType)
3587 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3588 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3589 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3590 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3591 default:
3592 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3593 return;
3595 data.append(GetPackGUID());
3596 data << uint32(0);
3597 GetSession()->SendPacket( &data );
3600 /* Preconditions:
3601 - a resurrectable corpse must not be loaded for the player (only bones)
3602 - the player must be in world
3604 void Player::BuildPlayerRepop()
3606 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3607 data.append(GetPackGUID());
3608 GetSession()->SendPacket(&data);
3610 if(getRace() == RACE_NIGHTELF)
3611 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)
3612 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3614 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3615 // there must be SMSG.STOP_MIRROR_TIMER
3616 // there we must send 888 opcode
3618 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3619 if(GetCorpse())
3621 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3622 assert(false);
3625 // create a corpse and place it at the player's location
3626 CreateCorpse();
3627 Corpse *corpse = GetCorpse();
3628 if(!corpse)
3630 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3631 return;
3633 GetMap()->Add(corpse);
3635 // convert player body to ghost
3636 SetHealth( 1 );
3638 SetMovement(MOVE_WATER_WALK);
3639 if(!GetSession()->isLogingOut())
3640 SetMovement(MOVE_UNROOT);
3642 // BG - remove insignia related
3643 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3645 SendCorpseReclaimDelay();
3647 // to prevent cheating
3648 corpse->ResetGhostTime();
3650 StopMirrorTimers(); //disable timers(bars)
3652 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3654 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3657 void Player::SendDelayResponse(const uint32 ml_seconds)
3659 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3660 data << (uint32)time(NULL);
3661 data << (uint32)0;
3662 GetSession()->SendPacket( &data );
3665 void Player::ResurrectPlayer(float restore_percent, bool updateToWorld, bool applySickness)
3667 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3668 data << uint32(-1);
3669 data << float(0);
3670 data << float(0);
3671 data << float(0);
3672 GetSession()->SendPacket(&data);
3674 // speed change, land walk
3676 // remove death flag + set aura
3677 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3678 if(getRace() == RACE_NIGHTELF)
3679 RemoveAurasDueToSpell(20584); // speed bonuses
3680 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3682 setDeathState(ALIVE);
3684 SetMovement(MOVE_LAND_WALK);
3685 SetMovement(MOVE_UNROOT);
3687 m_deathTimer = 0;
3689 // set health/powers (0- will be set in caller)
3690 if(restore_percent>0.0f)
3692 SetHealth(uint32(GetMaxHealth()*restore_percent));
3693 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3694 SetPower(POWER_RAGE, 0);
3695 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3698 // update visibility
3699 ObjectAccessor::UpdateVisibilityForPlayer(this);
3701 // some items limited to specific map
3702 DestroyZoneLimitedItem( true, GetZoneId());
3704 if(!applySickness || getLevel() <= 10)
3705 return;
3707 //Characters from level 1-10 are not affected by resurrection sickness.
3708 //Characters from level 11-19 will suffer from one minute of sickness
3709 //for each level they are above 10.
3710 //Characters level 20 and up suffer from ten minutes of sickness.
3711 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3713 if(int32(getLevel()) >= startLevel)
3715 // set resurrection sickness
3716 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3718 // not full duration
3719 if(int32(getLevel()) < startLevel+9)
3721 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3723 for(int i =0; i < 3; ++i)
3725 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3727 Aur->SetAuraDuration(delta*1000);
3728 Aur->SendAuraUpdate(false);
3735 void Player::KillPlayer()
3737 SetMovement(MOVE_ROOT);
3739 StopMirrorTimers(); //disable timers(bars)
3741 setDeathState(CORPSE);
3742 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3744 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3745 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3747 // 6 minutes until repop at graveyard
3748 m_deathTimer = 6*MINUTE*1000;
3750 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3752 // don't create corpse at this moment, player might be falling
3754 // update visibility
3755 ObjectAccessor::UpdateObjectVisibility(this);
3758 void Player::CreateCorpse()
3760 // prevent existence 2 corpse for player
3761 SpawnCorpseBones();
3763 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3765 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3766 SetPvPDeath(false);
3768 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3769 GetPositionY(), GetPositionZ(), GetOrientation()))
3771 delete corpse;
3772 return;
3775 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3776 _pb = GetUInt32Value(PLAYER_BYTES);
3777 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3779 uint8 race = (uint8)(_uf);
3780 uint8 skin = (uint8)(_pb);
3781 uint8 face = (uint8)(_pb >> 8);
3782 uint8 hairstyle = (uint8)(_pb >> 16);
3783 uint8 haircolor = (uint8)(_pb >> 24);
3784 uint8 facialhair = (uint8)(_pb2);
3786 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3787 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3789 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3790 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3792 uint32 flags = CORPSE_FLAG_UNK2;
3793 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3794 flags |= CORPSE_FLAG_HIDE_HELM;
3795 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3796 flags |= CORPSE_FLAG_HIDE_CLOAK;
3797 if(InBattleGround())
3798 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3799 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3801 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3803 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3805 uint32 iDisplayID;
3806 uint16 iIventoryType;
3807 uint32 _cfi;
3808 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3810 if(m_items[i])
3812 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3813 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3815 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3816 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3820 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3821 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3822 assert(entry);
3823 if(entry->map_type != MAP_BATTLEGROUND)
3824 corpse->SaveToDB();
3826 // register for player, but not show
3827 ObjectAccessor::Instance().AddCorpse(corpse);
3830 void Player::SpawnCorpseBones()
3832 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3833 SaveToDB(); // prevent loading as ghost without corpse
3836 Corpse* Player::GetCorpse() const
3838 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3841 void Player::DurabilityLossAll(double percent, bool inventory)
3843 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3844 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3845 DurabilityLoss(pItem,percent);
3847 if(inventory)
3849 // bags not have durability
3850 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3852 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3853 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3854 DurabilityLoss(pItem,percent);
3856 // keys not have durability
3857 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3859 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3860 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3861 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3862 if(Item* pItem = GetItemByPos( i, j ))
3863 DurabilityLoss(pItem,percent);
3867 void Player::DurabilityLoss(Item* item, double percent)
3869 if(!item )
3870 return;
3872 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3874 if(!pMaxDurability)
3875 return;
3877 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3879 if(pDurabilityLoss < 1 )
3880 pDurabilityLoss = 1;
3882 DurabilityPointsLoss(item,pDurabilityLoss);
3885 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3887 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3888 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3889 DurabilityPointsLoss(pItem,points);
3891 if(inventory)
3893 // bags not have durability
3894 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3896 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3897 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3898 DurabilityPointsLoss(pItem,points);
3900 // keys not have durability
3901 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3903 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3904 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3905 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3906 if(Item* pItem = GetItemByPos( i, j ))
3907 DurabilityPointsLoss(pItem,points);
3911 void Player::DurabilityPointsLoss(Item* item, int32 points)
3913 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3914 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3915 int32 pNewDurability = pOldDurability - points;
3917 if (pNewDurability < 0)
3918 pNewDurability = 0;
3919 else if (pNewDurability > pMaxDurability)
3920 pNewDurability = pMaxDurability;
3922 if (pOldDurability != pNewDurability)
3924 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3925 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3926 _ApplyItemMods(item,item->GetSlot(), false);
3928 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3930 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3931 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3932 _ApplyItemMods(item,item->GetSlot(), true);
3934 item->SetState(ITEM_CHANGED, this);
3938 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3940 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3941 DurabilityPointsLoss(pItem,1);
3944 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3946 uint32 TotalCost = 0;
3947 // equipped, backpack, bags itself
3948 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3949 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3951 // bank, buyback and keys not repaired
3953 // items in inventory bags
3954 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3955 for(int i = 0; i < MAX_BAG_SIZE; i++)
3956 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3957 return TotalCost;
3960 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3962 Item* item = GetItemByPos(pos);
3964 uint32 TotalCost = 0;
3965 if(!item)
3966 return TotalCost;
3968 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3969 if(!maxDurability)
3970 return TotalCost;
3972 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3974 if(cost)
3976 uint32 LostDurability = maxDurability - curDurability;
3977 if(LostDurability>0)
3979 ItemPrototype const *ditemProto = item->GetProto();
3981 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
3982 if(!dcost)
3984 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
3985 return TotalCost;
3988 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
3989 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
3990 if(!dQualitymodEntry)
3992 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
3993 return TotalCost;
3996 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
3997 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
3999 costs = uint32(costs * discountMod);
4001 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4002 costs = 1;
4004 if (guildBank)
4006 if (GetGuildId()==0)
4008 DEBUG_LOG("You are not member of a guild");
4009 return TotalCost;
4012 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4013 if (!pGuild)
4014 return TotalCost;
4016 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4018 DEBUG_LOG("You do not have rights to withdraw for repairs");
4019 return TotalCost;
4022 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4024 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4025 return TotalCost;
4028 if (pGuild->GetGuildBankMoney() < costs)
4030 DEBUG_LOG("There is not enough money in bank");
4031 return TotalCost;
4034 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4035 TotalCost = costs;
4037 else if (GetMoney() < costs)
4039 DEBUG_LOG("You do not have enough money");
4040 return TotalCost;
4042 else
4043 ModifyMoney( -int32(costs) );
4047 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4048 item->SetState(ITEM_CHANGED, this);
4050 // reapply mods for total broken and repaired item if equipped
4051 if(IsEquipmentPos(pos) && !curDurability)
4052 _ApplyItemMods(item,pos & 255, true);
4053 return TotalCost;
4056 void Player::RepopAtGraveyard()
4058 // note: this can be called also when the player is alive
4059 // for example from WorldSession::HandleMovementOpcodes
4061 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4063 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4064 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4066 ResurrectPlayer(0.5f);
4067 SpawnCorpseBones();
4070 WorldSafeLocsEntry const *ClosestGrave = NULL;
4072 // Special handle for battleground maps
4073 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4075 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4076 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4077 else
4078 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4080 // stop countdown until repop
4081 m_deathTimer = 0;
4083 // if no grave found, stay at the current location
4084 // and don't show spirit healer location
4085 if(ClosestGrave)
4087 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4088 if(isDead()) // not send if alive, because it used in TeleportTo()
4090 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4091 data << ClosestGrave->map_id;
4092 data << ClosestGrave->x;
4093 data << ClosestGrave->y;
4094 data << ClosestGrave->z;
4095 GetSession()->SendPacket(&data);
4100 void Player::JoinedChannel(Channel *c)
4102 m_channels.push_back(c);
4105 void Player::LeftChannel(Channel *c)
4107 m_channels.remove(c);
4110 void Player::CleanupChannels()
4112 while(!m_channels.empty())
4114 Channel* ch = *m_channels.begin();
4115 m_channels.erase(m_channels.begin()); // remove from player's channel list
4116 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4117 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4118 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4121 sLog.outDebug("Player: channels cleaned up!");
4124 void Player::UpdateLocalChannels(uint32 newZone )
4126 if(m_channels.empty())
4127 return;
4129 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4130 if(!current_zone)
4131 return;
4133 ChannelMgr* cMgr = channelMgr(GetTeam());
4134 if(!cMgr)
4135 return;
4137 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4139 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4141 next = i; ++next;
4143 // skip non built-in channels
4144 if(!(*i)->IsConstant())
4145 continue;
4147 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4148 if(!ch)
4149 continue;
4151 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4152 continue;
4154 // new channel
4155 char new_channel_name_buf[100];
4156 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4157 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4159 if((*i)!=new_channel)
4161 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4163 // leave old channel
4164 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4165 std::string name = (*i)->GetName(); // stroe name, (*i)erase in LeftChannel
4166 LeftChannel(*i); // remove from player's channel list
4167 cMgr->LeftChannel(name); // delete if empty
4170 sLog.outDebug("Player: channels cleaned up!");
4173 void Player::LeaveLFGChannel()
4175 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4177 if((*i)->IsLFG())
4179 (*i)->Leave(GetGUID());
4180 break;
4185 void Player::UpdateDefense()
4187 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4189 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4191 // update dependent from defense skill part
4192 UpdateDefenseBonusesMod();
4196 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats)
4198 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4200 sLog.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
4201 return;
4204 float val = 1.0f;
4206 switch(modType)
4208 case FLAT_MOD:
4209 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4210 break;
4211 case PCT_MOD:
4212 if(amount <= -100.0f)
4213 amount = -200.0f;
4215 val = (100.0f + amount) / 100.0f;
4216 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4217 break;
4220 if(!CanModifyStats())
4221 return;
4223 switch(modGroup)
4225 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4226 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4227 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4228 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4229 default: break;
4233 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4235 if(modGroup >= BASEMOD_END || modType > MOD_END)
4237 sLog.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
4238 return 0.0f;
4241 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4242 return 0.0f;
4244 return m_auraBaseMod[modGroup][modType];
4247 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4249 if(modGroup >= BASEMOD_END)
4251 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4252 return 0.0f;
4255 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4256 return 0.0f;
4258 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4261 uint32 Player::GetShieldBlockValue() const
4263 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4265 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4267 value = (value < 0) ? 0 : value;
4269 return uint32(value);
4272 float Player::GetMeleeCritFromAgility()
4274 uint32 level = getLevel();
4275 uint32 pclass = getClass();
4277 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4279 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4280 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4281 if (critBase==NULL || critRatio==NULL)
4282 return 0.0f;
4284 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4285 return crit*100.0f;
4288 float Player::GetDodgeFromAgility()
4290 // Table for base dodge values
4291 float dodge_base[MAX_CLASSES] = {
4292 0.0075f, // Warrior
4293 0.00652f, // Paladin
4294 -0.0545f, // Hunter
4295 -0.0059f, // Rogue
4296 0.03183f, // Priest
4297 0.0114f, // DK
4298 0.0167f, // Shaman
4299 0.034575f, // Mage
4300 0.02011f, // Warlock
4301 0.0f, // ??
4302 -0.0187f // Druid
4304 // Crit/agility to dodge/agility coefficient multipliers
4305 float crit_to_dodge[MAX_CLASSES] = {
4306 1.1f, // Warrior
4307 1.0f, // Paladin
4308 1.6f, // Hunter
4309 2.0f, // Rogue
4310 1.0f, // Priest
4311 1.0f, // DK?
4312 1.0f, // Shaman
4313 1.0f, // Mage
4314 1.0f, // Warlock
4315 0.0f, // ??
4316 1.7f // Druid
4319 uint32 level = getLevel();
4320 uint32 pclass = getClass();
4322 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4324 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4325 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4326 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4327 return 0.0f;
4329 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4330 return dodge*100.0f;
4333 float Player::GetSpellCritFromIntellect()
4335 uint32 level = getLevel();
4336 uint32 pclass = getClass();
4338 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4340 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4341 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4342 if (critBase==NULL || critRatio==NULL)
4343 return 0.0f;
4345 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4346 return crit*100.0f;
4349 float Player::GetRatingCoefficient(CombatRating cr) const
4351 uint32 level = getLevel();
4353 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4355 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4356 if (Rating == NULL)
4357 return 1.0f; // By default use minimum coefficient (not must be called)
4359 return Rating->ratio;
4362 float Player::GetRatingBonusValue(CombatRating cr) const
4364 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4367 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4369 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4370 if (melee>25.0f) melee = 25.0f;
4371 return uint32 (melee * damage /100.0f);
4374 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4376 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4377 if (ranged>25.0f) ranged=25.0f;
4378 return uint32 (ranged * damage /100.0f);
4381 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4383 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4384 // In wow script resilience limited to 25%
4385 if (spell>25.0f)
4386 spell = 25.0f;
4387 return uint32 (spell * damage / 100.0f);
4390 uint32 Player::GetDotDamageReduction(uint32 damage) const
4392 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4393 // Dot resilience not limited (limit it by 100%)
4394 if (spellDot > 100.0f)
4395 spellDot = 100.0f;
4396 return uint32 (spellDot * damage / 100.0f);
4399 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4401 switch (attType)
4403 case BASE_ATTACK:
4404 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4405 case OFF_ATTACK:
4406 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4407 default:
4408 break;
4410 return 0.0f;
4413 float Player::OCTRegenHPPerSpirit()
4415 uint32 level = getLevel();
4416 uint32 pclass = getClass();
4418 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4420 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4421 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4422 if (baseRatio==NULL || moreRatio==NULL)
4423 return 0.0f;
4425 // Formula from PaperDollFrame script
4426 float spirit = GetStat(STAT_SPIRIT);
4427 float baseSpirit = spirit;
4428 if (baseSpirit>50) baseSpirit = 50;
4429 float moreSpirit = spirit - baseSpirit;
4430 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4431 return regen;
4434 float Player::OCTRegenMPPerSpirit()
4436 uint32 level = getLevel();
4437 uint32 pclass = getClass();
4439 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4441 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4442 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4443 if (moreRatio==NULL)
4444 return 0.0f;
4446 // Formula get from PaperDollFrame script
4447 float spirit = GetStat(STAT_SPIRIT);
4448 float regen = spirit * moreRatio->ratio;
4449 return regen;
4452 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4454 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4456 float RatingCoeffecient = GetRatingCoefficient(cr);
4457 float RatingChange = 0.0f;
4459 bool affectStats = CanModifyStats();
4461 switch (cr)
4463 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4464 case CR_DEFENSE_SKILL:
4465 UpdateDefenseBonusesMod();
4466 break;
4467 case CR_DODGE:
4468 UpdateDodgePercentage();
4469 break;
4470 case CR_PARRY:
4471 UpdateParryPercentage();
4472 break;
4473 case CR_BLOCK:
4474 UpdateBlockPercentage();
4475 break;
4476 case CR_HIT_MELEE:
4477 RatingChange = value / RatingCoeffecient;
4478 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4479 break;
4480 case CR_HIT_RANGED:
4481 RatingChange = value / RatingCoeffecient;
4482 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4483 break;
4484 case CR_HIT_SPELL:
4485 RatingChange = value / RatingCoeffecient;
4486 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4487 break;
4488 case CR_CRIT_MELEE:
4489 if(affectStats)
4491 UpdateCritPercentage(BASE_ATTACK);
4492 UpdateCritPercentage(OFF_ATTACK);
4494 break;
4495 case CR_CRIT_RANGED:
4496 if(affectStats)
4497 UpdateCritPercentage(RANGED_ATTACK);
4498 break;
4499 case CR_CRIT_SPELL:
4500 if(affectStats)
4501 UpdateAllSpellCritChances();
4502 break;
4503 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4504 case CR_HIT_TAKEN_RANGED:
4505 break;
4506 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4507 break;
4508 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4509 case CR_CRIT_TAKEN_RANGED:
4510 break;
4511 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4512 break;
4513 case CR_HASTE_MELEE:
4514 RatingChange = value / RatingCoeffecient;
4515 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4516 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4517 break;
4518 case CR_HASTE_RANGED:
4519 RatingChange = value / RatingCoeffecient;
4520 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4521 break;
4522 case CR_HASTE_SPELL:
4523 RatingChange = value / RatingCoeffecient;
4524 ApplyCastTimePercentMod(RatingChange,apply);
4525 break;
4526 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4527 case CR_WEAPON_SKILL_OFFHAND:
4528 case CR_WEAPON_SKILL_RANGED:
4529 break;
4530 case CR_EXPERTISE:
4531 if(affectStats)
4533 UpdateExpertise(BASE_ATTACK);
4534 UpdateExpertise(OFF_ATTACK);
4536 break;
4540 void Player::SetRegularAttackTime()
4542 for(int i = 0; i < MAX_ATTACK; ++i)
4544 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4545 if(tmpitem && !tmpitem->IsBroken())
4547 ItemPrototype const *proto = tmpitem->GetProto();
4548 if(proto->Delay)
4549 SetAttackTime(WeaponAttackType(i), proto->Delay);
4550 else
4551 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4556 //skill+step, checking for max value
4557 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4559 if(!skill_id)
4560 return false;
4562 uint16 i=0;
4563 for (; i < PLAYER_MAX_SKILLS; i++)
4564 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4565 break;
4567 if(i>=PLAYER_MAX_SKILLS)
4568 return false;
4570 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4571 uint32 value = SKILL_VALUE(data);
4572 uint32 max = SKILL_MAX(data);
4574 if ((!max) || (!value) || (value >= max))
4575 return false;
4577 if (value*512 < max*urand(0,512))
4579 uint32 new_value = value+step;
4580 if(new_value > max)
4581 new_value = max;
4583 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4584 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4585 return true;
4588 return false;
4591 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4593 if ( SkillValue >= GrayLevel )
4594 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4595 if ( SkillValue >= GreenLevel )
4596 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4597 if ( SkillValue >= YellowLevel )
4598 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4599 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4602 bool Player::UpdateCraftSkill(uint32 spellid)
4604 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4606 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4607 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4609 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4611 if(_spell_idx->second->skillId)
4613 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4615 // Alchemy Discoveries here
4616 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4617 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4619 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4620 learnSpell(discoveredSpell);
4623 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4625 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4626 _spell_idx->second->max_value,
4627 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4628 _spell_idx->second->min_value),
4629 craft_skill_gain);
4632 return false;
4635 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4637 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4639 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4641 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4642 switch (SkillId)
4644 case SKILL_HERBALISM:
4645 case SKILL_LOCKPICKING:
4646 case SKILL_JEWELCRAFTING:
4647 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4648 case SKILL_SKINNING:
4649 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4650 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4651 else
4652 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4653 case SKILL_MINING:
4654 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4655 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4656 else
4657 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4659 return false;
4662 bool Player::UpdateFishingSkill()
4664 sLog.outDebug("UpdateFishingSkill");
4666 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4668 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4670 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4672 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4675 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4677 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4678 if ( !SkillId )
4679 return false;
4681 if(Chance <= 0) // speedup in 0 chance case
4683 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4684 return false;
4687 uint16 i=0;
4688 for (; i < PLAYER_MAX_SKILLS; i++)
4689 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4690 if ( i >= PLAYER_MAX_SKILLS )
4691 return false;
4693 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4694 uint16 SkillValue = SKILL_VALUE(data);
4695 uint16 MaxValue = SKILL_MAX(data);
4697 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4698 return false;
4700 int32 Roll = irand(1,1000);
4702 if ( Roll <= Chance )
4704 uint32 new_value = SkillValue+step;
4705 if(new_value > MaxValue)
4706 new_value = MaxValue;
4708 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4709 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4710 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4711 return true;
4714 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4715 return false;
4718 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4720 // no skill gain in pvp
4721 Unit *pVictim = getVictim();
4722 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4723 return;
4725 if(IsInFeralForm())
4726 return; // always maximized SKILL_FERAL_COMBAT in fact
4728 if(m_form == FORM_TREE)
4729 return; // use weapon but not skill up
4731 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4733 switch(attType)
4735 case BASE_ATTACK:
4737 Item *tmpitem = GetWeaponForAttack(attType,true);
4739 if (!tmpitem)
4740 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4741 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4742 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4743 break;
4745 case OFF_ATTACK:
4746 case RANGED_ATTACK:
4748 Item *tmpitem = GetWeaponForAttack(attType,true);
4749 if (tmpitem)
4750 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4751 break;
4754 UpdateAllCritPercentages();
4757 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4759 switch(outcome)
4761 case MELEE_HIT_CRIT:
4762 case MELEE_HIT_DODGE:
4763 case MELEE_HIT_PARRY:
4764 case MELEE_HIT_BLOCK:
4765 case MELEE_HIT_BLOCK_CRIT:
4766 return;
4768 default:
4769 break;
4772 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4773 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4774 uint32 moblevel = pVictim->getLevelForTarget(this);
4775 if(moblevel < greylevel)
4776 return;
4778 if (moblevel > plevel + 5)
4779 moblevel = plevel + 5;
4781 uint32 lvldif = moblevel - greylevel;
4782 if(lvldif < 3)
4783 lvldif = 3;
4785 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4786 if(skilldif <= 0)
4787 return;
4789 float chance = float(3 * lvldif * skilldif) / plevel;
4790 if(!defence)
4792 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4793 chance *= 0.1f * GetStat(STAT_INTELLECT);
4796 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4798 if(roll_chance_f(chance))
4800 if(defence)
4801 UpdateDefense();
4802 else
4803 UpdateWeaponSkill(attType);
4805 else
4806 return;
4809 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4811 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4812 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4814 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4815 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4816 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4818 if(talent) // permanent bonus stored in high part
4819 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4820 else // temporary/item bonus stored in low part
4821 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4822 return;
4826 void Player::UpdateMaxSkills()
4828 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4830 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4831 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4833 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4835 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4836 if(!pSkill)
4837 continue;
4839 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4840 continue;
4842 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4843 uint32 max = SKILL_MAX(data);
4844 uint32 val = SKILL_VALUE(data);
4846 // update only level dependent max skill values
4847 if(max!=1 && max != maxconfskill)
4849 uint32 max_Skill = GetMaxSkillValueForLevel();
4850 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
4855 void Player::UpdateSkillsToMaxSkillsForLevel()
4857 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4858 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4860 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4861 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4862 continue;
4863 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4865 uint32 max = SKILL_MAX(data);
4867 if(max > 1)
4868 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4870 if(pskill == SKILL_DEFENSE)
4871 UpdateDefenseBonusesMod();
4875 // This functions sets a skill line value (and adds if doesn't exist yet)
4876 // To "remove" a skill line, set it's values to zero
4877 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4879 if(!id)
4880 return;
4882 uint16 i=0;
4883 for (; i < PLAYER_MAX_SKILLS; i++)
4884 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4886 if(i<PLAYER_MAX_SKILLS) //has skill
4888 if(currVal)
4890 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4891 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4893 else //remove
4895 // clear skill fields
4896 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4897 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4898 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4900 // remove spells that depend on this skill when removing the skill
4901 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4903 ++next;
4904 if(itr->second->state == PLAYERSPELL_REMOVED)
4905 continue;
4907 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4908 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4910 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4912 if (_spell_idx->second->skillId == id)
4914 // this may remove more than one spell (dependants)
4915 removeSpell(itr->first);
4916 next = m_spells.begin();
4917 break;
4923 else if(currVal) //add
4925 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4926 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4928 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4929 if(!pSkill)
4931 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4932 return;
4934 // enable unlearn button for primary professions only
4935 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4936 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4937 else
4938 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4939 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4940 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4942 // apply skill bonuses
4943 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4945 // temporary bonuses
4946 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4947 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4948 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4949 (*i)->ApplyModifier(true);
4951 // permanent bonuses
4952 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4953 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4954 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4955 (*i)->ApplyModifier(true);
4957 // Learn all spells for skill
4958 learnSkillRewardedSpells(id);
4959 return;
4964 bool Player::HasSkill(uint32 skill) const
4966 if(!skill)return false;
4967 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4969 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4971 return true;
4974 return false;
4977 uint16 Player::GetSkillValue(uint32 skill) const
4979 if(!skill)
4980 return 0;
4982 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4984 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4986 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4988 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4989 result += SKILL_TEMP_BONUS(bonus);
4990 result += SKILL_PERM_BONUS(bonus);
4991 return result < 0 ? 0 : result;
4994 return 0;
4997 uint16 Player::GetMaxSkillValue(uint32 skill) const
4999 if(!skill)return 0;
5000 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5002 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5004 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5006 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5007 result += SKILL_TEMP_BONUS(bonus);
5008 result += SKILL_PERM_BONUS(bonus);
5009 return result < 0 ? 0 : result;
5012 return 0;
5015 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5017 if(!skill)return 0;
5018 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5020 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5022 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5025 return 0;
5028 uint16 Player::GetBaseSkillValue(uint32 skill) const
5030 if(!skill)return 0;
5031 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5033 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5035 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5036 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5037 return result < 0 ? 0 : result;
5040 return 0;
5043 uint16 Player::GetPureSkillValue(uint32 skill) const
5045 if(!skill)return 0;
5046 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5048 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5050 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5053 return 0;
5056 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5058 if(!skill)
5059 return 0;
5061 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5063 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5065 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5069 return 0;
5072 void Player::SendInitialActionButtons()
5074 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5076 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5077 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5079 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5080 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5082 data << uint16(itr->second.action);
5083 data << uint8(itr->second.misc);
5084 data << uint8(itr->second.type);
5086 else
5088 data << uint32(0);
5092 GetSession()->SendPacket( &data );
5093 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5096 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5098 if(button >= MAX_ACTION_BUTTONS)
5100 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5101 return;
5104 // check cheating with adding non-known spells to action bar
5105 if(type==ACTION_BUTTON_SPELL)
5107 if(!sSpellStore.LookupEntry(action))
5109 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5110 return;
5113 if(!HasSpell(action))
5115 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5116 return;
5120 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5122 if (buttonItr==m_actionButtons.end())
5123 { // just add new button
5124 m_actionButtons[button] = ActionButton(action,type,misc);
5126 else
5127 { // change state of current button
5128 ActionButtonUpdateState uState = buttonItr->second.uState;
5129 buttonItr->second = ActionButton(action,type,misc);
5130 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5133 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5136 void Player::removeActionButton(uint8 button)
5138 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5139 if (buttonItr==m_actionButtons.end())
5140 return;
5142 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5143 m_actionButtons.erase(buttonItr); // new and not saved
5144 else
5145 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5147 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5150 void Player::SetDontMove(bool dontMove)
5152 m_dontMove = dontMove;
5155 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5157 // prevent crash when a bad coord is sent by the client
5158 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5160 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5161 return false;
5164 Map *m = MapManager::Instance().GetMap(GetMapId(), this);
5166 const float old_x = GetPositionX();
5167 const float old_y = GetPositionY();
5168 const float old_z = GetPositionZ();
5169 const float old_r = GetOrientation();
5171 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5173 if (teleport || old_x != x || old_y != y || old_z != z)
5174 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5175 else
5176 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5178 // move and update visible state if need
5179 m->PlayerRelocation(this, x, y, z, orientation);
5181 // reread after Map::Relocation
5182 m = MapManager::Instance().GetMap(GetMapId(), this);
5183 x = GetPositionX();
5184 y = GetPositionY();
5185 z = GetPositionZ();
5188 // code block for underwater state update
5189 UpdateUnderwaterState(m, x, y, z);
5191 CheckExploreSystem();
5193 // group update
5194 if(GetGroup())
5195 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5197 return true;
5200 void Player::SaveRecallPosition()
5202 m_recallMap = GetMapId();
5203 m_recallX = GetPositionX();
5204 m_recallY = GetPositionY();
5205 m_recallZ = GetPositionZ();
5206 m_recallO = GetOrientation();
5209 void Player::SendMessageToSet(WorldPacket *data, bool self)
5211 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
5214 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5216 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self);
5219 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5221 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self,own_team_only);
5224 void Player::SendDirectMessage(WorldPacket *data)
5226 GetSession()->SendPacket(data);
5229 void Player::CheckExploreSystem()
5231 if (!isAlive())
5232 return;
5234 if (isInFlight())
5235 return;
5237 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5238 if(areaFlag==0xffff)
5239 return;
5240 int offset = areaFlag / 32;
5242 if(offset >= 128)
5244 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);
5245 return;
5248 uint32 val = (uint32)(1 << (areaFlag % 32));
5249 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5251 if( !(currFields & val) )
5253 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5255 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5256 if(!p)
5258 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5260 else if(p->area_level > 0)
5262 uint32 area = p->ID;
5263 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5265 SendExplorationExperience(area,0);
5267 else
5269 int32 diff = int32(getLevel()) - p->area_level;
5270 uint32 XP = 0;
5271 if (diff < -5)
5273 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5275 else if (diff > 5)
5277 int32 exploration_percent = (100-((diff-5)*5));
5278 if (exploration_percent > 100)
5279 exploration_percent = 100;
5280 else if (exploration_percent < 0)
5281 exploration_percent = 0;
5283 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5285 else
5287 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5290 GiveXP( XP, NULL );
5291 SendExplorationExperience(area,XP);
5293 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5298 uint32 Player::TeamForRace(uint8 race)
5300 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5301 if(!rEntry)
5303 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5304 return ALLIANCE;
5307 switch(rEntry->TeamID)
5309 case 7: return ALLIANCE;
5310 case 1: return HORDE;
5313 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5314 return ALLIANCE;
5317 uint32 Player::getFactionForRace(uint8 race)
5319 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5320 if(!rEntry)
5322 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5323 return 0;
5326 return rEntry->FactionID;
5329 void Player::setFactionForRace(uint8 race)
5331 m_team = TeamForRace(race);
5332 setFaction( getFactionForRace(race) );
5335 void Player::UpdateReputation() const
5337 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5339 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5341 SendFactionState(&(itr->second));
5345 void Player::SendFactionState(FactionState const* faction) const
5347 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5349 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5350 data << (float) 0; // unk 2.4.0
5351 data << (uint8) 0; // wotlk 8634
5352 data << (uint32) 1; // count
5353 // for
5354 data << (uint32) faction->ReputationListID;
5355 data << (uint32) faction->Standing;
5356 // end for
5357 GetSession()->SendPacket(&data);
5361 void Player::SendInitialReputations()
5363 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5364 data << uint32 (0x00000080);
5366 RepListID a = 0;
5368 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5370 // fill in absent fields
5371 for (; a != itr->first; a++)
5373 data << uint8 (0x00);
5374 data << uint32 (0x00000000);
5377 // fill in encountered data
5378 data << uint8 (itr->second.Flags);
5379 data << uint32 (itr->second.Standing);
5381 ++a;
5384 // fill in absent fields
5385 for (; a != 128; a++)
5387 data << uint8 (0x00);
5388 data << uint32 (0x00000000);
5391 GetSession()->SendPacket(&data);
5394 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5396 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5397 if (itr != m_factions.end())
5398 return &itr->second;
5400 return NULL;
5403 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5405 // not allow declare war to own faction
5406 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5407 return;
5409 // already set
5410 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5411 return;
5413 if( atWar )
5414 faction->Flags |= FACTION_FLAG_AT_WAR;
5415 else
5416 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5418 faction->Changed = true;
5421 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5423 // always invisible or hidden faction can't be inactive
5424 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5425 return;
5427 // already set
5428 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5429 return;
5431 if(inactive)
5432 faction->Flags |= FACTION_FLAG_INACTIVE;
5433 else
5434 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5436 faction->Changed = true;
5439 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5441 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5443 if(!factionTemplateEntry)
5444 return;
5446 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5449 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5451 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5452 if(!factionEntry)
5453 return;
5455 if(factionEntry->reputationListID < 0)
5456 return;
5458 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5459 if (itr == m_factions.end())
5460 return;
5462 SetFactionVisible(&itr->second);
5465 void Player::SetFactionVisible(FactionState* faction)
5467 // always invisible or hidden faction can't be make visible
5468 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5469 return;
5471 // already set
5472 if(faction->Flags & FACTION_FLAG_VISIBLE)
5473 return;
5475 faction->Flags |= FACTION_FLAG_VISIBLE;
5476 faction->Changed = true;
5478 if(!m_session->PlayerLoading())
5480 // make faction visible in reputation list at client
5481 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5482 data << faction->ReputationListID;
5483 GetSession()->SendPacket(&data);
5487 void Player::SetInitialFactions()
5489 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5491 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5493 if( factionEntry && (factionEntry->reputationListID >= 0))
5495 FactionState newFaction;
5496 newFaction.ID = factionEntry->ID;
5497 newFaction.ReputationListID = factionEntry->reputationListID;
5498 newFaction.Standing = 0;
5499 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5500 newFaction.Changed = true;
5502 m_factions[newFaction.ReputationListID] = newFaction;
5507 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5509 if (!factionEntry)
5510 return 0;
5512 uint32 raceMask = getRaceMask();
5513 uint32 classMask = getClassMask();
5514 for (int i=0; i < 4; i++)
5516 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5517 (factionEntry->BaseRepClassMask[i]==0 ||
5518 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5519 return factionEntry->ReputationFlags[i];
5521 return 0;
5524 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5526 if (!factionEntry)
5527 return 0;
5529 uint32 raceMask = getRaceMask();
5530 uint32 classMask = getClassMask();
5531 for (int i=0; i < 4; i++)
5533 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5534 (factionEntry->BaseRepClassMask[i]==0 ||
5535 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5536 return factionEntry->BaseRepValue[i];
5539 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5540 return 0;
5543 int32 Player::GetReputation(uint32 faction_id) const
5545 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5547 if (!factionEntry)
5549 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5550 return 0;
5553 return GetReputation(factionEntry);
5556 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5558 // Faction without recorded reputation. Just ignore.
5559 if(!factionEntry)
5560 return 0;
5562 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5563 if (itr != m_factions.end())
5564 return GetBaseReputation(factionEntry) + itr->second.Standing;
5566 return 0;
5569 ReputationRank Player::GetReputationRank(uint32 faction) const
5571 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5572 if(!factionEntry)
5573 return MIN_REPUTATION_RANK;
5575 return GetReputationRank(factionEntry);
5578 ReputationRank Player::ReputationToRank(int32 standing) const
5580 int32 Limit = Reputation_Cap + 1;
5581 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5583 Limit -= ReputationRank_Length[i];
5584 if (standing >= Limit )
5585 return ReputationRank(i);
5587 return MIN_REPUTATION_RANK;
5590 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5592 int32 Reputation = GetReputation(factionEntry);
5593 return ReputationToRank(Reputation);
5596 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5598 int32 Reputation = GetBaseReputation(factionEntry);
5599 return ReputationToRank(Reputation);
5602 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5604 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5606 if(!factionTemplateEntry)
5608 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5609 return false;
5612 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5614 // Faction without recorded reputation. Just ignore.
5615 if(!factionEntry)
5616 return false;
5618 return ModifyFactionReputation(factionEntry, DeltaReputation);
5621 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5623 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5624 if (flist)
5626 bool res = false;
5627 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5629 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5630 if(factionEntryCalc)
5631 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5633 return res;
5635 else
5636 return ModifyOneFactionReputation(factionEntry, standing);
5639 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5641 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5642 if (itr != m_factions.end())
5644 int32 BaseRep = GetBaseReputation(factionEntry);
5645 int32 new_rep = BaseRep + itr->second.Standing + standing;
5647 if (new_rep > Reputation_Cap)
5648 new_rep = Reputation_Cap;
5649 else
5650 if (new_rep < Reputation_Bottom)
5651 new_rep = Reputation_Bottom;
5653 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5654 SetFactionAtWar(&itr->second,true);
5656 itr->second.Standing = new_rep - BaseRep;
5657 itr->second.Changed = true;
5659 SetFactionVisible(&itr->second);
5661 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5663 if(uint32 questid = GetQuestSlotQuestId(i))
5665 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5666 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5668 QuestStatusData& q_status = mQuestStatus[questid];
5669 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5671 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5672 if ( CanCompleteQuest( questid ) )
5673 CompleteQuest( questid );
5675 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5677 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5678 IncompleteQuest( questid );
5684 SendFactionState(&(itr->second));
5686 return true;
5688 return false;
5691 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5693 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5695 if(!factionTemplateEntry)
5697 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5698 return false;
5701 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5703 // Faction without recorded reputation. Just ignore.
5704 if(!factionEntry)
5705 return false;
5707 return SetFactionReputation(factionEntry, standing);
5710 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5712 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5713 if (flist)
5715 bool res = false;
5716 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5718 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5719 if(factionEntryCalc)
5720 res = SetOneFactionReputation(factionEntryCalc, standing);
5722 return res;
5724 else
5725 return SetOneFactionReputation(factionEntry, standing);
5728 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5730 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5731 if (itr != m_factions.end())
5733 if (standing > Reputation_Cap)
5734 standing = Reputation_Cap;
5735 else
5736 if (standing < Reputation_Bottom)
5737 standing = Reputation_Bottom;
5739 int32 BaseRep = GetBaseReputation(factionEntry);
5740 itr->second.Standing = standing - BaseRep;
5741 itr->second.Changed = true;
5743 SetFactionVisible(&itr->second);
5745 if(ReputationToRank(standing) <= REP_HOSTILE)
5746 SetFactionAtWar(&itr->second,true);
5748 SendFactionState(&(itr->second));
5749 return true;
5751 return false;
5754 //Calculate total reputation percent player gain with quest/creature level
5755 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5757 // for grey creature kill received 20%, in other case 100.
5758 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5760 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5762 percent += rep > 0 ? repMod : -repMod;
5764 if(percent <=0)
5765 return 0;
5767 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5770 //Calculates how many reputation points player gains in victim's enemy factions
5771 void Player::RewardReputation(Unit *pVictim, float rate)
5773 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5774 return;
5776 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5778 if(!Rep)
5779 return;
5781 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5783 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5784 donerep1 = int32(donerep1*rate);
5785 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5786 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5787 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5788 ModifyFactionReputation(factionEntry1, donerep1);
5790 // Wiki: Team factions value divided by 2
5791 if(Rep->is_teamaward1)
5793 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5794 if(team1_factionEntry)
5795 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5799 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5801 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5802 donerep2 = int32(donerep2*rate);
5803 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5804 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5805 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5806 ModifyFactionReputation(factionEntry2, donerep2);
5808 // Wiki: Team factions value divided by 2
5809 if(Rep->is_teamaward2)
5811 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5812 if(team2_factionEntry)
5813 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5818 //Calculate how many reputation points player gain with the quest
5819 void Player::RewardReputation(Quest const *pQuest)
5821 // quest reputation reward/loss
5822 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5824 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5826 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5827 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5828 if(factionEntry)
5829 ModifyFactionReputation(factionEntry, rep);
5833 // TODO: implement reputation spillover
5836 void Player::UpdateArenaFields(void)
5838 /* arena calcs go here */
5841 void Player::UpdateHonorFields()
5843 /// called when rewarding honor and at each save
5844 uint64 now = time(NULL);
5845 uint64 today = uint64(time(NULL) / DAY) * DAY;
5847 if(m_lastHonorUpdateTime < today)
5849 uint64 yesterday = today - DAY;
5851 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5853 // update yesterday's contribution
5854 if(m_lastHonorUpdateTime >= yesterday )
5856 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5858 // this is the first update today, reset today's contribution
5859 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5860 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5862 else
5864 // no honor/kills yesterday or today, reset
5865 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5866 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5870 m_lastHonorUpdateTime = now;
5873 ///Calculate the amount of honor gained based on the victim
5874 ///and the size of the group for which the honor is divided
5875 ///An exact honor value can also be given (overriding the calcs)
5876 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5878 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5879 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5880 return false;
5882 uint64 victim_guid = 0;
5883 uint32 victim_rank = 0;
5884 time_t now = time(NULL);
5886 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5887 UpdateHonorFields();
5889 if(honor <= 0)
5891 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5892 return false;
5894 victim_guid = uVictim->GetGUID();
5896 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5898 Player *pVictim = (Player *)uVictim;
5900 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5901 return false;
5903 float f = 1; //need for total kills (?? need more info)
5904 uint32 k_grey = 0;
5905 uint32 k_level = getLevel();
5906 uint32 v_level = pVictim->getLevel();
5909 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5910 // [0] Just name
5911 // [1..14] Alliance honor titles and player name
5912 // [15..28] Horde honor titles and player name
5913 // [29..38] Other title and player name
5914 // [39+] Nothing
5915 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5916 // Get Killer titles, CharTitlesEntry::bit_index
5917 // Ranks:
5918 // title[1..14] -> rank[5..18]
5919 // title[15..28] -> rank[5..18]
5920 // title[other] -> 0
5921 if (victim_title == 0)
5922 victim_guid = 0; // Don't show HK: <rank> message, only log.
5923 else if (victim_title < 15)
5924 victim_rank = victim_title + 4;
5925 else if (victim_title < 29)
5926 victim_rank = victim_title - 14 + 4;
5927 else
5928 victim_guid = 0; // Don't show HK: <rank> message, only log.
5931 if(k_level <= 5)
5932 k_grey = 0;
5933 else if( k_level <= 39 )
5934 k_grey = k_level - 5 - k_level/10;
5935 else
5936 k_grey = k_level - 1 - k_level/5;
5938 if(v_level<=k_grey)
5939 return false;
5941 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5943 int32 v_rank =1; //need more info
5945 honor = ((f * diff_level * (190 + v_rank*10))/6);
5946 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5948 // count the number of playerkills in one day
5949 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5950 // and those in a lifetime
5951 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5953 else
5955 Creature *cVictim = (Creature *)uVictim;
5957 if (!cVictim->isRacialLeader())
5958 return false;
5960 honor = 100; // ??? need more info
5961 victim_rank = 19; // HK: Leader
5965 if (uVictim != NULL)
5967 honor *= sWorld.getRate(RATE_HONOR);
5969 if(groupsize > 1)
5970 honor /= groupsize;
5972 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5975 // honor - for show honor points in log
5976 // victim_guid - for show victim name in log
5977 // victim_rank [1..4] HK: <dishonored rank>
5978 // victim_rank [5..19] HK: <alliance\horde rank>
5979 // victim_rank [0,20+] HK: <>
5980 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5981 data << (uint32) honor;
5982 data << (uint64) victim_guid;
5983 data << (uint32) victim_rank;
5985 GetSession()->SendPacket(&data);
5987 // add honor points
5988 ModifyHonorPoints(int32(honor));
5990 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5991 return true;
5994 void Player::ModifyHonorPoints( int32 value )
5996 if(value < 0)
5998 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5999 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6000 else
6001 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6003 else
6004 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6007 void Player::ModifyArenaPoints( int32 value )
6009 if(value < 0)
6011 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6012 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6013 else
6014 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6016 else
6017 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6020 uint32 Player::GetGuildIdFromDB(uint64 guid)
6022 std::ostringstream ss;
6023 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
6024 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6025 if( result )
6027 uint32 v = result->Fetch()[0].GetUInt32();
6028 delete result;
6029 return v;
6031 else
6032 return 0;
6035 uint32 Player::GetRankFromDB(uint64 guid)
6037 std::ostringstream ss;
6038 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6039 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6040 if( result )
6042 uint32 v = result->Fetch()[0].GetUInt32();
6043 delete result;
6044 return v;
6046 else
6047 return 0;
6050 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6052 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);
6053 if(!result)
6054 return 0;
6056 uint32 id = (*result)[0].GetUInt32();
6057 delete result;
6058 return id;
6061 uint32 Player::GetZoneIdFromDB(uint64 guid)
6063 std::ostringstream ss;
6065 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6066 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6067 if (!result)
6068 return 0;
6069 Field* fields = result->Fetch();
6070 uint32 zone = fields[0].GetUInt32();
6071 delete result;
6073 if (!zone)
6075 // stored zone is zero, use generic and slow zone detection
6076 ss.str("");
6077 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6078 result = CharacterDatabase.Query(ss.str().c_str());
6079 if( !result )
6080 return 0;
6081 fields = result->Fetch();
6082 uint32 map = fields[0].GetUInt32();
6083 float posx = fields[1].GetFloat();
6084 float posy = fields[2].GetFloat();
6085 delete result;
6087 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6089 ss.str("");
6090 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6091 CharacterDatabase.Execute(ss.str().c_str());
6094 return zone;
6097 void Player::UpdateArea(uint32 newArea)
6099 // FFA_PVP flags are area and not zone id dependent
6100 // so apply them accordingly
6101 m_areaUpdateId = newArea;
6103 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6105 if(area && (area->flags & AREA_FLAG_ARENA))
6107 if(!isGameMaster())
6108 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6110 else
6112 // remove ffa flag only if not ffapvp realm
6113 // removal in sanctuaries and capitals is handled in zone update
6114 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6115 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6118 UpdateAreaDependentAuras(newArea);
6121 void Player::UpdateZone(uint32 newZone)
6123 m_zoneUpdateId = newZone;
6124 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6126 // zone changed, so area changed as well, update it
6127 UpdateArea(GetAreaId());
6129 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6130 if(!zone)
6131 return;
6133 if (sWorld.getConfig(CONFIG_WEATHER))
6135 Weather *wth = sWorld.FindWeather(zone->ID);
6136 if(wth)
6138 wth->SendWeatherUpdateToPlayer(this);
6140 else
6142 if(!sWorld.AddWeather(zone->ID))
6144 // send fine weather packet to remove old zone's weather
6145 Weather::SendFineWeatherUpdateToPlayer(this);
6150 pvpInfo.inHostileArea =
6151 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6152 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6153 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6154 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6156 if(pvpInfo.inHostileArea) // in hostile area
6158 if(!IsPvP() || pvpInfo.endTimer != 0)
6159 UpdatePvP(true, true);
6161 else // in friendly area
6163 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6164 pvpInfo.endTimer = time(0); // start toggle-off
6167 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6169 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6170 if(sWorld.IsFFAPvPRealm())
6171 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6173 else
6175 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6178 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6180 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6181 SetRestType(REST_TYPE_IN_CITY);
6182 InnEnter(time(0),GetMapId(),0,0,0);
6184 if(sWorld.IsFFAPvPRealm())
6185 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6187 else // anywhere else
6189 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6191 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6193 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6195 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6196 SetRestType(REST_TYPE_NO);
6198 if(sWorld.IsFFAPvPRealm())
6199 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6202 else // not in tavern (leave city then)
6204 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6205 SetRestType(REST_TYPE_NO);
6207 // Set player to FFA PVP when not in rested enviroment.
6208 if(sWorld.IsFFAPvPRealm())
6209 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6214 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6215 // if player resurrected at teleport this will be applied in resurrect code
6216 if(isAlive())
6217 DestroyZoneLimitedItem( true, newZone );
6219 // recent client version not send leave/join channel packets for built-in local channels
6220 UpdateLocalChannels( newZone );
6222 // group update
6223 if(GetGroup())
6224 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6226 UpdateZoneDependentAuras(newZone);
6229 //If players are too far way of duel flag... then player loose the duel
6230 void Player::CheckDuelDistance(time_t currTime)
6232 if(!duel)
6233 return;
6235 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6236 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6237 if(!obj)
6238 return;
6240 if(duel->outOfBound == 0)
6242 if(!IsWithinDistInMap(obj, 50))
6244 duel->outOfBound = currTime;
6246 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6247 GetSession()->SendPacket(&data);
6250 else
6252 if(IsWithinDistInMap(obj, 40))
6254 duel->outOfBound = 0;
6256 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6257 GetSession()->SendPacket(&data);
6259 else if(currTime >= (duel->outOfBound+10))
6261 DuelComplete(DUEL_FLED);
6266 void Player::DuelComplete(DuelCompleteType type)
6268 // duel not requested
6269 if(!duel)
6270 return;
6272 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6273 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6274 GetSession()->SendPacket(&data);
6275 duel->opponent->GetSession()->SendPacket(&data);
6277 if(type != DUEL_INTERUPTED)
6279 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6280 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6281 data << duel->opponent->GetName();
6282 data << GetName();
6283 SendMessageToSet(&data,true);
6286 // cool-down duel spell
6287 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6289 data<<GetGUID();
6290 data<<uint8(0x0);
6292 data<<(uint32)7266;
6293 data<<uint32(0x0);
6294 GetSession()->SendPacket(&data);
6295 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6296 data<<duel->opponent->GetGUID();
6297 data<<uint8(0x0);
6298 data<<(uint32)7266;
6299 data<<uint32(0x0);
6300 duel->opponent->GetSession()->SendPacket(&data);*/
6302 //Remove Duel Flag object
6303 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6304 if(obj)
6305 duel->initiator->RemoveGameObject(obj,true);
6307 /* remove auras */
6308 std::vector<uint32> auras2remove;
6309 AuraMap const& vAuras = duel->opponent->GetAuras();
6310 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6312 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6313 auras2remove.push_back(i->second->GetId());
6316 for(size_t i=0; i<auras2remove.size(); i++)
6317 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6319 auras2remove.clear();
6320 AuraMap const& auras = GetAuras();
6321 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6323 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6324 auras2remove.push_back(i->second->GetId());
6326 for(size_t i=0; i<auras2remove.size(); i++)
6327 RemoveAurasDueToSpell(auras2remove[i]);
6329 // cleanup combo points
6330 if(GetComboTarget()==duel->opponent->GetGUID())
6331 ClearComboPoints();
6332 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6333 ClearComboPoints();
6335 if(duel->opponent->GetComboTarget()==GetGUID())
6336 duel->opponent->ClearComboPoints();
6337 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6338 duel->opponent->ClearComboPoints();
6340 //cleanups
6341 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6342 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6343 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6344 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6346 delete duel->opponent->duel;
6347 duel->opponent->duel = NULL;
6348 delete duel;
6349 duel = NULL;
6352 //---------------------------------------------------------//
6354 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6356 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6357 return;
6359 // not apply/remove mods for broken item
6360 if(item->IsBroken())
6361 return;
6363 ItemPrototype const *proto = item->GetProto();
6365 if(!proto)
6366 return;
6368 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6370 uint32 attacktype = Player::GetAttackBySlot(slot);
6371 if(attacktype < MAX_ATTACK)
6372 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6374 _ApplyItemBonuses(proto,slot,apply);
6376 if( slot==EQUIPMENT_SLOT_RANGED )
6377 _ApplyAmmoBonuses();
6379 ApplyItemEquipSpell(item,apply);
6380 ApplyEnchantment(item, apply);
6382 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6383 CorrectMetaGemEnchants(slot, apply);
6385 sLog.outDebug("_ApplyItemMods complete.");
6388 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6390 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6391 return;
6393 for (int i = 0; i < 10; i++)
6395 uint32 statType = 0;
6396 int32 val = 0;
6398 if(proto->ScalingStatDistribution)
6400 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6402 statType = ssd->StatMod[i];
6404 if(uint32 modifier = ssd->Modifier[i])
6406 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6407 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6409 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6410 val = (multiplier * modifier) / 10000;
6415 else
6417 statType = proto->ItemStat[i].ItemStatType;
6418 val = float(proto->ItemStat[i].ItemStatValue);
6421 if(val == 0)
6422 continue;
6424 switch (statType)
6426 case ITEM_MOD_MANA:
6427 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6428 break;
6429 case ITEM_MOD_HEALTH: // modify HP
6430 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6431 break;
6432 case ITEM_MOD_AGILITY: // modify agility
6433 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6434 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6435 break;
6436 case ITEM_MOD_STRENGTH: //modify strength
6437 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6438 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6439 break;
6440 case ITEM_MOD_INTELLECT: //modify intellect
6441 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6442 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6443 break;
6444 case ITEM_MOD_SPIRIT: //modify spirit
6445 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6446 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6447 break;
6448 case ITEM_MOD_STAMINA: //modify stamina
6449 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6450 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6451 break;
6452 case ITEM_MOD_DEFENSE_SKILL_RATING:
6453 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6454 break;
6455 case ITEM_MOD_DODGE_RATING:
6456 ApplyRatingMod(CR_DODGE, int32(val), apply);
6457 break;
6458 case ITEM_MOD_PARRY_RATING:
6459 ApplyRatingMod(CR_PARRY, int32(val), apply);
6460 break;
6461 case ITEM_MOD_BLOCK_RATING:
6462 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6463 break;
6464 case ITEM_MOD_HIT_MELEE_RATING:
6465 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6466 break;
6467 case ITEM_MOD_HIT_RANGED_RATING:
6468 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6469 break;
6470 case ITEM_MOD_HIT_SPELL_RATING:
6471 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6472 break;
6473 case ITEM_MOD_CRIT_MELEE_RATING:
6474 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6475 break;
6476 case ITEM_MOD_CRIT_RANGED_RATING:
6477 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6478 break;
6479 case ITEM_MOD_CRIT_SPELL_RATING:
6480 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6481 break;
6482 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6483 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6484 break;
6485 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6486 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6487 break;
6488 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6489 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6490 break;
6491 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6492 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6493 break;
6494 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6495 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6496 break;
6497 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6498 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6499 break;
6500 case ITEM_MOD_HASTE_MELEE_RATING:
6501 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6502 break;
6503 case ITEM_MOD_HASTE_RANGED_RATING:
6504 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6505 break;
6506 case ITEM_MOD_HASTE_SPELL_RATING:
6507 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6508 break;
6509 case ITEM_MOD_HIT_RATING:
6510 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6511 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6512 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6513 break;
6514 case ITEM_MOD_CRIT_RATING:
6515 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6516 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6517 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6518 break;
6519 case ITEM_MOD_HIT_TAKEN_RATING:
6520 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6521 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6522 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6523 break;
6524 case ITEM_MOD_CRIT_TAKEN_RATING:
6525 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6526 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6527 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6528 break;
6529 case ITEM_MOD_RESILIENCE_RATING:
6530 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6531 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6532 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6533 break;
6534 case ITEM_MOD_HASTE_RATING:
6535 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6536 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6537 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6538 break;
6539 case ITEM_MOD_EXPERTISE_RATING:
6540 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6541 break;
6542 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6543 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6544 break;
6548 if (proto->Armor)
6549 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6551 if (proto->Block)
6552 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6554 if (proto->HolyRes)
6555 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6557 if (proto->FireRes)
6558 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6560 if (proto->NatureRes)
6561 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6563 if (proto->FrostRes)
6564 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6566 if (proto->ShadowRes)
6567 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6569 if (proto->ArcaneRes)
6570 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6572 WeaponAttackType attType = BASE_ATTACK;
6573 float damage = 0.0f;
6575 if( slot == EQUIPMENT_SLOT_RANGED && (
6576 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6577 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6579 attType = RANGED_ATTACK;
6581 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6583 attType = OFF_ATTACK;
6586 if (proto->Damage[0].DamageMin > 0 )
6588 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6589 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6590 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6593 if (proto->Damage[0].DamageMax > 0 )
6595 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6596 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6599 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6600 return;
6602 if (proto->Delay)
6604 if(slot == EQUIPMENT_SLOT_RANGED)
6605 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6606 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6607 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6608 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6609 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6612 if(CanModifyStats() && (damage || proto->Delay))
6613 UpdateDamagePhysical(attType);
6616 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6618 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6619 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6620 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6622 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6623 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6624 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6626 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6627 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6628 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6631 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6633 // generic not weapon specific case processes in aura code
6634 if(aura->GetSpellProto()->EquippedItemClass == -1)
6635 return;
6637 BaseModGroup mod = BASEMOD_END;
6638 switch(attackType)
6640 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6641 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6642 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6643 default: return;
6646 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6648 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6652 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6654 // ignore spell mods for not wands
6655 Modifier const* modifier = aura->GetModifier();
6656 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6657 return;
6659 // generic not weapon specific case processes in aura code
6660 if(aura->GetSpellProto()->EquippedItemClass == -1)
6661 return;
6663 UnitMods unitMod = UNIT_MOD_END;
6664 switch(attackType)
6666 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6667 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6668 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6669 default: return;
6672 UnitModifierType unitModType = TOTAL_VALUE;
6673 switch(modifier->m_auraname)
6675 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6676 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6677 default: return;
6680 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6682 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6686 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6688 if(!item)
6689 return;
6691 ItemPrototype const *proto = item->GetProto();
6692 if(!proto)
6693 return;
6695 for (int i = 0; i < 5; i++)
6697 _Spell const& spellData = proto->Spells[i];
6699 // no spell
6700 if(!spellData.SpellId )
6701 continue;
6703 // wrong triggering type
6704 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6705 continue;
6707 // check if it is valid spell
6708 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6709 if(!spellproto)
6710 continue;
6712 ApplyEquipSpell(spellproto,item,apply,form_change);
6716 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6718 if(apply)
6720 // Cannot be used in this stance/form
6721 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6722 return;
6724 if(form_change) // check aura active state from other form
6726 bool found = false;
6727 for (int k=0; k < 3; ++k)
6729 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6730 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6732 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6734 found = true;
6735 break;
6738 if(found)
6739 break;
6742 if(found) // and skip re-cast already active aura at form change
6743 return;
6746 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6748 CastSpell(this,spellInfo,true,item);
6750 else
6752 if(form_change) // check aura compatibility
6754 // Cannot be used in this stance/form
6755 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6756 return; // and remove only not compatible at form change
6759 if(item)
6760 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6761 else
6762 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6766 void Player::UpdateEquipSpellsAtFormChange()
6768 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6770 if(m_items[i] && !m_items[i]->IsBroken())
6772 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6773 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6777 // item set bonuses not dependent from item broken state
6778 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6780 ItemSetEffect* eff = ItemSetEff[setindex];
6781 if(!eff)
6782 continue;
6784 for(uint32 y=0;y<8; ++y)
6786 SpellEntry const* spellInfo = eff->spells[y];
6787 if(!spellInfo)
6788 continue;
6790 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6791 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6796 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6798 if(!item || item->IsBroken())
6799 return;
6801 ItemPrototype const *proto = item->GetProto();
6802 if(!proto)
6803 return;
6805 if (!Target || Target == this )
6806 return;
6808 for (int i = 0; i < 5; i++)
6810 _Spell const& spellData = proto->Spells[i];
6812 // no spell
6813 if(!spellData.SpellId )
6814 continue;
6816 // wrong triggering type
6817 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6818 continue;
6820 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6821 if(!spellInfo)
6823 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6824 continue;
6827 // not allow proc extra attack spell at extra attack
6828 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6829 return;
6831 float chance = spellInfo->procChance;
6833 if(spellData.SpellPPMRate)
6835 uint32 WeaponSpeed = GetAttackTime(attType);
6836 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6838 else if(chance > 100.0f)
6840 chance = GetWeaponProcChance();
6843 if (roll_chance_f(chance))
6844 this->CastSpell(Target, spellInfo->Id, true, item);
6847 // item combat enchantments
6848 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6850 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6851 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6852 if(!pEnchant) continue;
6853 for (int s=0;s<3;s++)
6855 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6856 continue;
6858 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6859 if (!spellInfo)
6861 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6862 continue;
6865 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6866 if (roll_chance_f(chance))
6868 if(IsPositiveSpell(pEnchant->spellid[s]))
6869 CastSpell(this, pEnchant->spellid[s], true, item);
6870 else
6871 CastSpell(Target, pEnchant->spellid[s], true, item);
6877 void Player::_RemoveAllItemMods()
6879 sLog.outDebug("_RemoveAllItemMods start.");
6881 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6883 if(m_items[i])
6885 ItemPrototype const *proto = m_items[i]->GetProto();
6886 if(!proto)
6887 continue;
6889 // item set bonuses not dependent from item broken state
6890 if(proto->ItemSet)
6891 RemoveItemsSetItem(this,proto);
6893 if(m_items[i]->IsBroken())
6894 continue;
6896 ApplyItemEquipSpell(m_items[i],false);
6897 ApplyEnchantment(m_items[i], false);
6901 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6903 if(m_items[i])
6905 if(m_items[i]->IsBroken())
6906 continue;
6907 ItemPrototype const *proto = m_items[i]->GetProto();
6908 if(!proto)
6909 continue;
6911 uint32 attacktype = Player::GetAttackBySlot(i);
6912 if(attacktype < MAX_ATTACK)
6913 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6915 _ApplyItemBonuses(proto,i, false);
6917 if( i == EQUIPMENT_SLOT_RANGED )
6918 _ApplyAmmoBonuses();
6922 sLog.outDebug("_RemoveAllItemMods complete.");
6925 void Player::_ApplyAllItemMods()
6927 sLog.outDebug("_ApplyAllItemMods start.");
6929 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6931 if(m_items[i])
6933 if(m_items[i]->IsBroken())
6934 continue;
6936 ItemPrototype const *proto = m_items[i]->GetProto();
6937 if(!proto)
6938 continue;
6940 uint32 attacktype = Player::GetAttackBySlot(i);
6941 if(attacktype < MAX_ATTACK)
6942 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6944 _ApplyItemBonuses(proto,i, true);
6946 if( i == EQUIPMENT_SLOT_RANGED )
6947 _ApplyAmmoBonuses();
6951 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6953 if(m_items[i])
6955 ItemPrototype const *proto = m_items[i]->GetProto();
6956 if(!proto)
6957 continue;
6959 // item set bonuses not dependent from item broken state
6960 if(proto->ItemSet)
6961 AddItemsSetItem(this,m_items[i]);
6963 if(m_items[i]->IsBroken())
6964 continue;
6966 ApplyItemEquipSpell(m_items[i],true);
6967 ApplyEnchantment(m_items[i], true);
6971 sLog.outDebug("_ApplyAllItemMods complete.");
6974 void Player::_ApplyAmmoBonuses()
6976 // check ammo
6977 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6978 if(!ammo_id)
6979 return;
6981 float currentAmmoDPS;
6983 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6984 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6985 currentAmmoDPS = 0.0f;
6986 else
6987 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6989 if(currentAmmoDPS == GetAmmoDPS())
6990 return;
6992 m_ammoDPS = currentAmmoDPS;
6994 if(CanModifyStats())
6995 UpdateDamagePhysical(RANGED_ATTACK);
6998 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7000 if(!ammo_proto)
7001 return false;
7003 // check ranged weapon
7004 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7005 if(!weapon || weapon->IsBroken() )
7006 return false;
7008 ItemPrototype const* weapon_proto = weapon->GetProto();
7009 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7010 return false;
7012 // check ammo ws. weapon compatibility
7013 switch(weapon_proto->SubClass)
7015 case ITEM_SUBCLASS_WEAPON_BOW:
7016 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7017 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7018 return false;
7019 break;
7020 case ITEM_SUBCLASS_WEAPON_GUN:
7021 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7022 return false;
7023 break;
7024 default:
7025 return false;
7028 return true;
7031 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7032 Called by remove insignia spell effect */
7033 void Player::RemovedInsignia(Player* looterPlr)
7035 if (!GetBattleGroundId())
7036 return;
7038 // If not released spirit, do it !
7039 if(m_deathTimer > 0)
7041 m_deathTimer = 0;
7042 BuildPlayerRepop();
7043 RepopAtGraveyard();
7046 Corpse *corpse = GetCorpse();
7047 if (!corpse)
7048 return;
7050 // We have to convert player corpse to bones, not to be able to resurrect there
7051 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7052 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7053 if (!bones)
7054 return;
7056 // Now we must make bones lootable, and send player loot
7057 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7059 // We store the level of our player in the gold field
7060 // We retrieve this information at Player::SendLoot()
7061 bones->loot.gold = getLevel();
7062 bones->lootRecipient = looterPlr;
7063 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7066 /*Loot type MUST be
7067 1-corpse, go
7068 2-skinning
7069 3-Fishing
7072 void Player::SendLootRelease( uint64 guid )
7074 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7075 data << uint64(guid) << uint8(1);
7076 SendDirectMessage( &data );
7079 void Player::SendLoot(uint64 guid, LootType loot_type)
7081 Loot *loot = 0;
7082 PermissionTypes permission = ALL_PERMISSION;
7084 sLog.outDebug("Player::SendLoot");
7085 if (IS_GAMEOBJECT_GUID(guid))
7087 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7088 GameObject *go =
7089 ObjectAccessor::GetGameObject(*this, guid);
7091 // not check distance for GO in case owned GO (fishing bobber case, for example)
7092 // And permit out of range GO with no owner in case fishing hole
7093 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7095 SendLootRelease(guid);
7096 return;
7099 loot = &go->loot;
7101 if(go->getLootState() == GO_READY)
7103 uint32 lootid = go->GetLootId();
7105 if(lootid)
7107 sLog.outDebug(" if(lootid)");
7108 loot->clear();
7109 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7112 if(loot_type == LOOT_FISHING)
7113 go->getFishLoot(loot);
7115 go->SetLootState(GO_ACTIVATED);
7118 else if (IS_ITEM_GUID(guid))
7120 Item *item = GetItemByGuid( guid );
7122 if (!item)
7124 SendLootRelease(guid);
7125 return;
7128 if(loot_type == LOOT_DISENCHANTING)
7130 loot = &item->loot;
7132 if(!item->m_lootGenerated)
7134 item->m_lootGenerated = true;
7135 loot->clear();
7136 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7139 else if(loot_type == LOOT_PROSPECTING)
7141 loot = &item->loot;
7143 if(!item->m_lootGenerated)
7145 item->m_lootGenerated = true;
7146 loot->clear();
7147 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7150 else
7152 loot = &item->loot;
7154 if(!item->m_lootGenerated)
7156 item->m_lootGenerated = true;
7157 loot->clear();
7158 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7160 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7164 else if (IS_CORPSE_GUID(guid)) // remove insignia
7166 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7168 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7170 SendLootRelease(guid);
7171 return;
7174 loot = &bones->loot;
7176 if (!bones->lootForBody)
7178 bones->lootForBody = true;
7179 uint32 pLevel = bones->loot.gold;
7180 bones->loot.clear();
7181 // It may need a better formula
7182 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7183 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7186 if (bones->lootRecipient != this)
7187 permission = NONE_PERMISSION;
7189 else
7191 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7193 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7194 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7196 SendLootRelease(guid);
7197 return;
7200 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7202 SendLootRelease(guid);
7203 return;
7206 loot = &creature->loot;
7208 if(loot_type == LOOT_PICKPOCKETING)
7210 if ( !creature->lootForPickPocketed )
7212 creature->lootForPickPocketed = true;
7213 loot->clear();
7215 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7216 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7218 // Generate extra money for pick pocket loot
7219 const uint32 a = urand(0, creature->getLevel()/2);
7220 const uint32 b = urand(0, getLevel()/2);
7221 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7224 else
7226 // the player whose group may loot the corpse
7227 Player *recipient = creature->GetLootRecipient();
7228 if (!recipient)
7230 creature->SetLootRecipient(this);
7231 recipient = this;
7234 if (creature->lootForPickPocketed)
7236 creature->lootForPickPocketed = false;
7237 loot->clear();
7240 if(!creature->lootForBody)
7242 creature->lootForBody = true;
7243 loot->clear();
7245 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7246 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7248 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7250 if(Group* group = recipient->GetGroup())
7252 group->UpdateLooterGuid(creature,true);
7254 switch (group->GetLootMethod())
7256 case GROUP_LOOT:
7257 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7258 group->GroupLoot(recipient->GetGUID(), loot, creature);
7259 break;
7260 case NEED_BEFORE_GREED:
7261 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7262 break;
7263 case MASTER_LOOT:
7264 group->MasterLoot(recipient->GetGUID(), loot, creature);
7265 break;
7266 default:
7267 break;
7272 // possible only if creature->lootForBody && loot->empty() at spell cast check
7273 if (loot_type == LOOT_SKINNING)
7275 loot->clear();
7276 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7278 // set group rights only for loot_type != LOOT_SKINNING
7279 else
7281 if(Group* group = GetGroup())
7283 if( group == recipient->GetGroup() )
7285 if(group->GetLootMethod() == FREE_FOR_ALL)
7286 permission = ALL_PERMISSION;
7287 else if(group->GetLooterGuid() == GetGUID())
7289 if(group->GetLootMethod() == MASTER_LOOT)
7290 permission = MASTER_PERMISSION;
7291 else
7292 permission = ALL_PERMISSION;
7294 else
7295 permission = GROUP_PERMISSION;
7297 else
7298 permission = NONE_PERMISSION;
7300 else if(recipient == this)
7301 permission = ALL_PERMISSION;
7302 else
7303 permission = NONE_PERMISSION;
7308 SetLootGUID(guid);
7310 QuestItemList *q_list = 0;
7311 if (permission != NONE_PERMISSION)
7313 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7314 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7315 if (itr == lootPlayerQuestItems.end())
7316 q_list = loot->FillQuestLoot(this);
7317 else
7318 q_list = itr->second;
7321 QuestItemList *ffa_list = 0;
7322 if (permission != NONE_PERMISSION)
7324 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7325 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7326 if (itr == lootPlayerFFAItems.end())
7327 ffa_list = loot->FillFFALoot(this);
7328 else
7329 ffa_list = itr->second;
7332 QuestItemList *conditional_list = 0;
7333 if (permission != NONE_PERMISSION)
7335 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7336 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7337 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7338 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7339 else
7340 conditional_list = itr->second;
7343 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7344 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7345 loot_type = LOOT_SKINNING;
7347 if(loot_type == LOOT_FISHINGHOLE)
7348 loot_type = LOOT_FISHING;
7350 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7352 data << uint64(guid);
7353 data << uint8(loot_type);
7354 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7356 SendDirectMessage(&data);
7358 // add 'this' player as one of the players that are looting 'loot'
7359 if (permission != NONE_PERMISSION)
7360 loot->AddLooter(GetGUID());
7362 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7363 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7366 void Player::SendNotifyLootMoneyRemoved()
7368 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7369 GetSession()->SendPacket( &data );
7372 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7374 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7375 data << uint8(lootSlot);
7376 GetSession()->SendPacket( &data );
7379 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7381 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7382 data << Field;
7383 data << Value;
7384 GetSession()->SendPacket(&data);
7387 void Player::SendInitWorldStates()
7389 // data depends on zoneid/mapid...
7390 BattleGround* bg = GetBattleGround();
7391 uint16 NumberOfFields = 0;
7392 uint32 mapid = GetMapId();
7393 uint32 zoneid = GetZoneId();
7394 uint32 areaid = GetAreaId();
7395 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7396 // may be exist better way to do this...
7397 switch(zoneid)
7399 case 0:
7400 case 1:
7401 case 4:
7402 case 8:
7403 case 10:
7404 case 11:
7405 case 12:
7406 case 36:
7407 case 38:
7408 case 40:
7409 case 41:
7410 case 51:
7411 case 267:
7412 case 1519:
7413 case 1537:
7414 case 2257:
7415 case 2918:
7416 NumberOfFields = 6;
7417 break;
7418 case 2597:
7419 NumberOfFields = 81;
7420 break;
7421 case 3277:
7422 NumberOfFields = 14;
7423 break;
7424 case 3358:
7425 case 3820:
7426 NumberOfFields = 38;
7427 break;
7428 case 3483:
7429 NumberOfFields = 22;
7430 break;
7431 case 3519:
7432 NumberOfFields = 36;
7433 break;
7434 case 3521:
7435 NumberOfFields = 35;
7436 break;
7437 case 3698:
7438 case 3702:
7439 case 3968:
7440 NumberOfFields = 9;
7441 break;
7442 case 3703:
7443 NumberOfFields = 9;
7444 break;
7445 default:
7446 NumberOfFields = 10;
7447 break;
7450 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7451 data << uint32(mapid); // mapid
7452 data << uint32(zoneid); // zone id
7453 data << uint32(areaid); // area id, new 2.1.0
7454 data << uint16(NumberOfFields); // count of uint64 blocks
7455 data << uint32(0x8d8) << uint32(0x0); // 1
7456 data << uint32(0x8d7) << uint32(0x0); // 2
7457 data << uint32(0x8d6) << uint32(0x0); // 3
7458 data << uint32(0x8d5) << uint32(0x0); // 4
7459 data << uint32(0x8d4) << uint32(0x0); // 5
7460 data << uint32(0x8d3) << uint32(0x0); // 6
7461 if(mapid == 530) // Outland
7463 data << uint32(0x9bf) << uint32(0x0); // 7
7464 data << uint32(0x9bd) << uint32(0xF); // 8
7465 data << uint32(0x9bb) << uint32(0xF); // 9
7467 switch(zoneid)
7469 case 1:
7470 case 11:
7471 case 12:
7472 case 38:
7473 case 40:
7474 case 51:
7475 case 1519:
7476 case 1537:
7477 case 2257:
7478 break;
7479 case 2597: // AV
7480 data << uint32(0x7ae) << uint32(0x1); // 7
7481 data << uint32(0x532) << uint32(0x1); // 8
7482 data << uint32(0x531) << uint32(0x0); // 9
7483 data << uint32(0x52e) << uint32(0x0); // 10
7484 data << uint32(0x571) << uint32(0x0); // 11
7485 data << uint32(0x570) << uint32(0x0); // 12
7486 data << uint32(0x567) << uint32(0x1); // 13
7487 data << uint32(0x566) << uint32(0x1); // 14
7488 data << uint32(0x550) << uint32(0x1); // 15
7489 data << uint32(0x544) << uint32(0x0); // 16
7490 data << uint32(0x536) << uint32(0x0); // 17
7491 data << uint32(0x535) << uint32(0x1); // 18
7492 data << uint32(0x518) << uint32(0x0); // 19
7493 data << uint32(0x517) << uint32(0x0); // 20
7494 data << uint32(0x574) << uint32(0x0); // 21
7495 data << uint32(0x573) << uint32(0x0); // 22
7496 data << uint32(0x572) << uint32(0x0); // 23
7497 data << uint32(0x56f) << uint32(0x0); // 24
7498 data << uint32(0x56e) << uint32(0x0); // 25
7499 data << uint32(0x56d) << uint32(0x0); // 26
7500 data << uint32(0x56c) << uint32(0x0); // 27
7501 data << uint32(0x56b) << uint32(0x0); // 28
7502 data << uint32(0x56a) << uint32(0x1); // 29
7503 data << uint32(0x569) << uint32(0x1); // 30
7504 data << uint32(0x568) << uint32(0x1); // 13
7505 data << uint32(0x565) << uint32(0x0); // 32
7506 data << uint32(0x564) << uint32(0x0); // 33
7507 data << uint32(0x563) << uint32(0x0); // 34
7508 data << uint32(0x562) << uint32(0x0); // 35
7509 data << uint32(0x561) << uint32(0x0); // 36
7510 data << uint32(0x560) << uint32(0x0); // 37
7511 data << uint32(0x55f) << uint32(0x0); // 38
7512 data << uint32(0x55e) << uint32(0x0); // 39
7513 data << uint32(0x55d) << uint32(0x0); // 40
7514 data << uint32(0x3c6) << uint32(0x4); // 41
7515 data << uint32(0x3c4) << uint32(0x6); // 42
7516 data << uint32(0x3c2) << uint32(0x4); // 43
7517 data << uint32(0x516) << uint32(0x1); // 44
7518 data << uint32(0x515) << uint32(0x0); // 45
7519 data << uint32(0x3b6) << uint32(0x6); // 46
7520 data << uint32(0x55c) << uint32(0x0); // 47
7521 data << uint32(0x55b) << uint32(0x0); // 48
7522 data << uint32(0x55a) << uint32(0x0); // 49
7523 data << uint32(0x559) << uint32(0x0); // 50
7524 data << uint32(0x558) << uint32(0x0); // 51
7525 data << uint32(0x557) << uint32(0x0); // 52
7526 data << uint32(0x556) << uint32(0x0); // 53
7527 data << uint32(0x555) << uint32(0x0); // 54
7528 data << uint32(0x554) << uint32(0x1); // 55
7529 data << uint32(0x553) << uint32(0x1); // 56
7530 data << uint32(0x552) << uint32(0x1); // 57
7531 data << uint32(0x551) << uint32(0x1); // 58
7532 data << uint32(0x54f) << uint32(0x0); // 59
7533 data << uint32(0x54e) << uint32(0x0); // 60
7534 data << uint32(0x54d) << uint32(0x1); // 61
7535 data << uint32(0x54c) << uint32(0x0); // 62
7536 data << uint32(0x54b) << uint32(0x0); // 63
7537 data << uint32(0x545) << uint32(0x0); // 64
7538 data << uint32(0x543) << uint32(0x1); // 65
7539 data << uint32(0x542) << uint32(0x0); // 66
7540 data << uint32(0x540) << uint32(0x0); // 67
7541 data << uint32(0x53f) << uint32(0x0); // 68
7542 data << uint32(0x53e) << uint32(0x0); // 69
7543 data << uint32(0x53d) << uint32(0x0); // 70
7544 data << uint32(0x53c) << uint32(0x0); // 71
7545 data << uint32(0x53b) << uint32(0x0); // 72
7546 data << uint32(0x53a) << uint32(0x1); // 73
7547 data << uint32(0x539) << uint32(0x0); // 74
7548 data << uint32(0x538) << uint32(0x0); // 75
7549 data << uint32(0x537) << uint32(0x0); // 76
7550 data << uint32(0x534) << uint32(0x0); // 77
7551 data << uint32(0x533) << uint32(0x0); // 78
7552 data << uint32(0x530) << uint32(0x0); // 79
7553 data << uint32(0x52f) << uint32(0x0); // 80
7554 data << uint32(0x52d) << uint32(0x1); // 81
7555 break;
7556 case 3277: // WS
7557 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7558 bg->FillInitialWorldStates(data);
7559 else
7561 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7562 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7563 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7564 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7565 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7566 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7567 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7568 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7570 break;
7571 case 3358: // AB
7572 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7573 bg->FillInitialWorldStates(data);
7574 else
7576 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7577 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7578 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7579 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7580 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7581 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7582 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7583 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7584 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7585 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7586 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7587 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7588 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7589 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7590 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7591 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7592 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7593 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7594 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7595 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7596 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7597 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7598 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7599 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7600 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7601 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7602 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7603 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7604 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7605 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7606 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7607 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7609 break;
7610 case 3820: // EY
7611 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7612 bg->FillInitialWorldStates(data);
7613 else
7615 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7616 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7617 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7618 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7619 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7620 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7621 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7622 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7623 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7624 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7625 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7626 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7627 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7628 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7629 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7630 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7631 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7632 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7633 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontroled (1 - yes, 0 - no)
7634 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7635 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7636 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7637 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7638 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7639 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7640 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7641 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7642 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7643 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7644 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7645 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7646 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7647 // and some more ... unknown
7649 break;
7650 case 3483: // Hellfire Peninsula
7651 data << uint32(0x9ba) << uint32(0x1); // 10
7652 data << uint32(0x9b9) << uint32(0x1); // 11
7653 data << uint32(0x9b5) << uint32(0x0); // 12
7654 data << uint32(0x9b4) << uint32(0x1); // 13
7655 data << uint32(0x9b3) << uint32(0x0); // 14
7656 data << uint32(0x9b2) << uint32(0x0); // 15
7657 data << uint32(0x9b1) << uint32(0x1); // 16
7658 data << uint32(0x9b0) << uint32(0x0); // 17
7659 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7660 data << uint32(0x9ac) << uint32(0x0); // 19
7661 data << uint32(0x9a8) << uint32(0x0); // 20
7662 data << uint32(0x9a7) << uint32(0x0); // 21
7663 data << uint32(0x9a6) << uint32(0x1); // 22
7664 break;
7665 case 3519: // Terokkar Forest
7666 data << uint32(0xa41) << uint32(0x0); // 10
7667 data << uint32(0xa40) << uint32(0x14); // 11
7668 data << uint32(0xa3f) << uint32(0x0); // 12
7669 data << uint32(0xa3e) << uint32(0x0); // 13
7670 data << uint32(0xa3d) << uint32(0x5); // 14
7671 data << uint32(0xa3c) << uint32(0x0); // 15
7672 data << uint32(0xa87) << uint32(0x0); // 16
7673 data << uint32(0xa86) << uint32(0x0); // 17
7674 data << uint32(0xa85) << uint32(0x0); // 18
7675 data << uint32(0xa84) << uint32(0x0); // 19
7676 data << uint32(0xa83) << uint32(0x0); // 20
7677 data << uint32(0xa82) << uint32(0x0); // 21
7678 data << uint32(0xa81) << uint32(0x0); // 22
7679 data << uint32(0xa80) << uint32(0x0); // 23
7680 data << uint32(0xa7e) << uint32(0x0); // 24
7681 data << uint32(0xa7d) << uint32(0x0); // 25
7682 data << uint32(0xa7c) << uint32(0x0); // 26
7683 data << uint32(0xa7b) << uint32(0x0); // 27
7684 data << uint32(0xa7a) << uint32(0x0); // 28
7685 data << uint32(0xa79) << uint32(0x0); // 29
7686 data << uint32(0x9d0) << uint32(0x5); // 30
7687 data << uint32(0x9ce) << uint32(0x0); // 31
7688 data << uint32(0x9cd) << uint32(0x0); // 32
7689 data << uint32(0x9cc) << uint32(0x0); // 33
7690 data << uint32(0xa88) << uint32(0x0); // 34
7691 data << uint32(0xad0) << uint32(0x0); // 35
7692 data << uint32(0xacf) << uint32(0x1); // 36
7693 break;
7694 case 3521: // Zangarmarsh
7695 data << uint32(0x9e1) << uint32(0x0); // 10
7696 data << uint32(0x9e0) << uint32(0x0); // 11
7697 data << uint32(0x9df) << uint32(0x0); // 12
7698 data << uint32(0xa5d) << uint32(0x1); // 13
7699 data << uint32(0xa5c) << uint32(0x0); // 14
7700 data << uint32(0xa5b) << uint32(0x1); // 15
7701 data << uint32(0xa5a) << uint32(0x0); // 16
7702 data << uint32(0xa59) << uint32(0x1); // 17
7703 data << uint32(0xa58) << uint32(0x0); // 18
7704 data << uint32(0xa57) << uint32(0x0); // 19
7705 data << uint32(0xa56) << uint32(0x0); // 20
7706 data << uint32(0xa55) << uint32(0x1); // 21
7707 data << uint32(0xa54) << uint32(0x0); // 22
7708 data << uint32(0x9e7) << uint32(0x0); // 23
7709 data << uint32(0x9e6) << uint32(0x0); // 24
7710 data << uint32(0x9e5) << uint32(0x0); // 25
7711 data << uint32(0xa00) << uint32(0x0); // 26
7712 data << uint32(0x9ff) << uint32(0x1); // 27
7713 data << uint32(0x9fe) << uint32(0x0); // 28
7714 data << uint32(0x9fd) << uint32(0x0); // 29
7715 data << uint32(0x9fc) << uint32(0x1); // 30
7716 data << uint32(0x9fb) << uint32(0x0); // 31
7717 data << uint32(0xa62) << uint32(0x0); // 32
7718 data << uint32(0xa61) << uint32(0x1); // 33
7719 data << uint32(0xa60) << uint32(0x1); // 34
7720 data << uint32(0xa5f) << uint32(0x0); // 35
7721 break;
7722 case 3698: // Nagrand Arena
7723 data << uint32(0xa0f) << uint32(0x0); // 7
7724 data << uint32(0xa10) << uint32(0x0); // 8
7725 data << uint32(0xa11) << uint32(0x0); // 9
7726 break;
7727 case 3702: // Blade's Edge Arena
7728 data << uint32(0x9f0) << uint32(0x0); // 7
7729 data << uint32(0x9f1) << uint32(0x0); // 8
7730 data << uint32(0x9f3) << uint32(0x0); // 9
7731 break;
7732 case 3968: // Ruins of Lordaeron
7733 data << uint32(0xbb8) << uint32(0x0); // 7
7734 data << uint32(0xbb9) << uint32(0x0); // 8
7735 data << uint32(0xbba) << uint32(0x0); // 9
7736 break;
7737 case 3703: // Shattrath City
7738 break;
7739 default:
7740 data << uint32(0x914) << uint32(0x0); // 7
7741 data << uint32(0x913) << uint32(0x0); // 8
7742 data << uint32(0x912) << uint32(0x0); // 9
7743 data << uint32(0x915) << uint32(0x0); // 10
7744 break;
7746 GetSession()->SendPacket(&data);
7749 uint32 Player::GetXPRestBonus(uint32 xp)
7751 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7753 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7754 rested_bonus = xp;
7756 SetRestBonus( GetRestBonus() - rested_bonus);
7758 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7759 return rested_bonus;
7762 void Player::SetBindPoint(uint64 guid)
7764 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7765 data << uint64(guid);
7766 GetSession()->SendPacket( &data );
7769 void Player::SendTalentWipeConfirm(uint64 guid)
7771 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7772 data << uint64(guid);
7773 data << uint32(resetTalentsCost());
7774 GetSession()->SendPacket( &data );
7777 void Player::SendPetSkillWipeConfirm()
7779 Pet* pet = GetPet();
7780 if(!pet)
7781 return;
7782 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7783 data << pet->GetGUID();
7784 data << uint32(pet->resetTalentsCost());
7785 GetSession()->SendPacket( &data );
7788 /*********************************************************/
7789 /*** STORAGE SYSTEM ***/
7790 /*********************************************************/
7792 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7794 assert(i < 3);
7795 if(i < 2 && item)
7797 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7798 return;
7799 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7800 if(charges == 0)
7801 return;
7802 if(charges > 1)
7803 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7804 else if(charges <= 1)
7806 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7807 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7812 void Player::SetSheath( uint32 sheathed )
7814 switch (sheathed)
7816 case SHEATH_STATE_UNARMED: // no prepared weapon
7817 SetVirtualItemSlot(0,NULL);
7818 SetVirtualItemSlot(1,NULL);
7819 SetVirtualItemSlot(2,NULL);
7820 break;
7821 case SHEATH_STATE_MELEE: // prepared melee weapon
7823 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7824 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7825 SetVirtualItemSlot(2,NULL);
7826 }; break;
7827 case SHEATH_STATE_RANGED: // prepared ranged weapon
7828 SetVirtualItemSlot(0,NULL);
7829 SetVirtualItemSlot(1,NULL);
7830 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7831 break;
7832 default:
7833 SetVirtualItemSlot(0,NULL);
7834 SetVirtualItemSlot(1,NULL);
7835 SetVirtualItemSlot(2,NULL);
7836 break;
7838 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7841 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7843 uint8 pClass = getClass();
7845 uint8 slots[4];
7846 slots[0] = NULL_SLOT;
7847 slots[1] = NULL_SLOT;
7848 slots[2] = NULL_SLOT;
7849 slots[3] = NULL_SLOT;
7850 switch( proto->InventoryType )
7852 case INVTYPE_HEAD:
7853 slots[0] = EQUIPMENT_SLOT_HEAD;
7854 break;
7855 case INVTYPE_NECK:
7856 slots[0] = EQUIPMENT_SLOT_NECK;
7857 break;
7858 case INVTYPE_SHOULDERS:
7859 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7860 break;
7861 case INVTYPE_BODY:
7862 slots[0] = EQUIPMENT_SLOT_BODY;
7863 break;
7864 case INVTYPE_CHEST:
7865 slots[0] = EQUIPMENT_SLOT_CHEST;
7866 break;
7867 case INVTYPE_ROBE:
7868 slots[0] = EQUIPMENT_SLOT_CHEST;
7869 break;
7870 case INVTYPE_WAIST:
7871 slots[0] = EQUIPMENT_SLOT_WAIST;
7872 break;
7873 case INVTYPE_LEGS:
7874 slots[0] = EQUIPMENT_SLOT_LEGS;
7875 break;
7876 case INVTYPE_FEET:
7877 slots[0] = EQUIPMENT_SLOT_FEET;
7878 break;
7879 case INVTYPE_WRISTS:
7880 slots[0] = EQUIPMENT_SLOT_WRISTS;
7881 break;
7882 case INVTYPE_HANDS:
7883 slots[0] = EQUIPMENT_SLOT_HANDS;
7884 break;
7885 case INVTYPE_FINGER:
7886 slots[0] = EQUIPMENT_SLOT_FINGER1;
7887 slots[1] = EQUIPMENT_SLOT_FINGER2;
7888 break;
7889 case INVTYPE_TRINKET:
7890 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7891 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7892 break;
7893 case INVTYPE_CLOAK:
7894 slots[0] = EQUIPMENT_SLOT_BACK;
7895 break;
7896 case INVTYPE_WEAPON:
7898 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7900 // suggest offhand slot only if know dual wielding
7901 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7902 if(CanDualWield())
7903 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7904 };break;
7905 case INVTYPE_SHIELD:
7906 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7907 break;
7908 case INVTYPE_RANGED:
7909 slots[0] = EQUIPMENT_SLOT_RANGED;
7910 break;
7911 case INVTYPE_2HWEAPON:
7912 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7913 break;
7914 case INVTYPE_TABARD:
7915 slots[0] = EQUIPMENT_SLOT_TABARD;
7916 break;
7917 case INVTYPE_WEAPONMAINHAND:
7918 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7919 break;
7920 case INVTYPE_WEAPONOFFHAND:
7921 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7922 break;
7923 case INVTYPE_HOLDABLE:
7924 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7925 break;
7926 case INVTYPE_THROWN:
7927 slots[0] = EQUIPMENT_SLOT_RANGED;
7928 break;
7929 case INVTYPE_RANGEDRIGHT:
7930 slots[0] = EQUIPMENT_SLOT_RANGED;
7931 break;
7932 case INVTYPE_BAG:
7933 slots[0] = INVENTORY_SLOT_BAG_1;
7934 slots[1] = INVENTORY_SLOT_BAG_2;
7935 slots[2] = INVENTORY_SLOT_BAG_3;
7936 slots[3] = INVENTORY_SLOT_BAG_4;
7937 break;
7938 case INVTYPE_RELIC:
7940 switch(proto->SubClass)
7942 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7943 if (pClass == CLASS_PALADIN)
7944 slots[0] = EQUIPMENT_SLOT_RANGED;
7945 break;
7946 case ITEM_SUBCLASS_ARMOR_IDOL:
7947 if (pClass == CLASS_DRUID)
7948 slots[0] = EQUIPMENT_SLOT_RANGED;
7949 break;
7950 case ITEM_SUBCLASS_ARMOR_TOTEM:
7951 if (pClass == CLASS_SHAMAN)
7952 slots[0] = EQUIPMENT_SLOT_RANGED;
7953 break;
7954 case ITEM_SUBCLASS_ARMOR_MISC:
7955 if (pClass == CLASS_WARLOCK)
7956 slots[0] = EQUIPMENT_SLOT_RANGED;
7957 break;
7959 break;
7961 default :
7962 return NULL_SLOT;
7965 if( slot != NULL_SLOT )
7967 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7969 for (int i = 0; i < 4; i++)
7971 if ( slots[i] == slot )
7972 return slot;
7976 else
7978 // search free slot at first
7979 for (int i = 0; i < 4; i++)
7981 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7983 // in case 2hand equipped weapon offhand slot empty but not free
7984 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7986 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7987 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7988 return slots[i];
7990 else
7991 return slots[i];
7995 // if not found free and can swap return first appropriate from used
7996 for (int i = 0; i < 4; i++)
7998 if ( slots[i] != NULL_SLOT && swap )
7999 return slots[i];
8003 // no free position
8004 return NULL_SLOT;
8007 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8009 Item *pItem;
8010 uint32 tempcount = 0;
8012 uint8 res = EQUIP_ERR_OK;
8014 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8016 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8017 if( pItem && pItem->GetEntry() == item )
8019 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8020 if(ires==EQUIP_ERR_OK)
8022 tempcount += pItem->GetCount();
8023 if( tempcount >= count )
8024 return EQUIP_ERR_OK;
8026 else
8027 res = ires;
8030 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8032 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8033 if( pItem && pItem->GetEntry() == item )
8035 tempcount += pItem->GetCount();
8036 if( tempcount >= count )
8037 return EQUIP_ERR_OK;
8040 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8042 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8043 if( pItem && pItem->GetEntry() == item )
8045 tempcount += pItem->GetCount();
8046 if( tempcount >= count )
8047 return EQUIP_ERR_OK;
8050 Bag *pBag;
8051 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8053 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8054 if( pBag )
8056 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8058 pItem = GetItemByPos( i, j );
8059 if( pItem && pItem->GetEntry() == item )
8061 tempcount += pItem->GetCount();
8062 if( tempcount >= count )
8063 return EQUIP_ERR_OK;
8069 // not found req. item count and have unequippable items
8070 return res;
8073 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8075 uint32 count = 0;
8076 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8078 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8079 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8080 count += pItem->GetCount();
8082 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8084 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8085 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8086 count += pItem->GetCount();
8088 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8090 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8091 if( pBag )
8092 count += pBag->GetItemCount(item,skipItem);
8095 if(skipItem && skipItem->GetProto()->GemProperties)
8097 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8099 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8100 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8101 count += pItem->GetGemCountWithID(item);
8105 if(inBankAlso)
8107 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8109 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8110 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8111 count += pItem->GetCount();
8113 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8115 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8116 if( pBag )
8117 count += pBag->GetItemCount(item,skipItem);
8120 if(skipItem && skipItem->GetProto()->GemProperties)
8122 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8124 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8125 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8126 count += pItem->GetGemCountWithID(item);
8131 return count;
8134 Item* Player::GetItemByGuid( uint64 guid ) const
8136 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8138 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8139 if( pItem && pItem->GetGUID() == guid )
8140 return pItem;
8142 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8144 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8145 if( pItem && pItem->GetGUID() == guid )
8146 return pItem;
8149 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8151 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8152 if( pBag )
8154 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8156 Item* pItem = pBag->GetItemByPos( j );
8157 if( pItem && pItem->GetGUID() == guid )
8158 return pItem;
8162 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8164 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8165 if( pBag )
8167 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8169 Item* pItem = pBag->GetItemByPos( j );
8170 if( pItem && pItem->GetGUID() == guid )
8171 return pItem;
8176 return NULL;
8179 Item* Player::GetItemByPos( uint16 pos ) const
8181 uint8 bag = pos >> 8;
8182 uint8 slot = pos & 255;
8183 return GetItemByPos( bag, slot );
8186 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8188 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8189 return m_items[slot];
8190 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8191 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8193 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8194 if ( pBag )
8195 return pBag->GetItemByPos(slot);
8197 return NULL;
8200 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8202 uint16 slot;
8203 switch (attackType)
8205 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8206 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8207 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8208 default: return NULL;
8211 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8212 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8213 return NULL;
8215 if(!useable)
8216 return item;
8218 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8219 return NULL;
8221 return item;
8224 Item* Player::GetShield(bool useable) const
8226 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8227 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8228 return NULL;
8230 if(!useable)
8231 return item;
8233 if( item->IsBroken())
8234 return NULL;
8236 return item;
8239 uint32 Player::GetAttackBySlot( uint8 slot )
8241 switch(slot)
8243 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8244 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8245 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8246 default: return MAX_ATTACK;
8250 bool Player::HasBankBagSlot( uint8 slot ) const
8252 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8253 if( slot < maxslot )
8254 return true;
8255 return false;
8258 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8260 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8261 return true;
8262 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8263 return true;
8264 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8265 return true;
8266 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8267 return true;
8268 return false;
8271 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8273 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8274 return true;
8275 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8276 return true;
8277 return false;
8280 bool Player::IsBankPos( uint8 bag, uint8 slot )
8282 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8283 return true;
8284 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8285 return true;
8286 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8287 return true;
8288 return false;
8291 bool Player::IsBagPos( uint16 pos )
8293 uint8 bag = pos >> 8;
8294 uint8 slot = pos & 255;
8295 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8296 return true;
8297 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8298 return true;
8299 return false;
8302 bool Player::IsValidPos( uint8 bag, uint8 slot )
8304 // post selected
8305 if(bag == NULL_BAG)
8306 return true;
8308 if (bag == INVENTORY_SLOT_BAG_0)
8310 // any post selected
8311 if (slot == NULL_SLOT)
8312 return true;
8314 // equipment
8315 if (slot < EQUIPMENT_SLOT_END)
8316 return true;
8318 // bag equip slots
8319 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8320 return true;
8322 // backpack slots
8323 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8324 return true;
8326 // keyring slots
8327 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8328 return true;
8330 // bank main slots
8331 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8332 return true;
8334 // bank bag slots
8335 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8336 return true;
8338 return false;
8341 // bag content slots
8342 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8344 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8345 if(!pBag)
8346 return false;
8348 // any post selected
8349 if (slot == NULL_SLOT)
8350 return true;
8352 return slot < pBag->GetBagSize();
8355 // bank bag content slots
8356 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8358 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8359 if(!pBag)
8360 return false;
8362 // any post selected
8363 if (slot == NULL_SLOT)
8364 return true;
8366 return slot < pBag->GetBagSize();
8369 // where this?
8370 return false;
8374 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8376 uint32 tempcount = 0;
8377 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8379 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8380 if( pItem && pItem->GetEntry() == item )
8382 tempcount += pItem->GetCount();
8383 if( tempcount >= count )
8384 return true;
8387 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8389 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8390 if( pItem && pItem->GetEntry() == item )
8392 tempcount += pItem->GetCount();
8393 if( tempcount >= count )
8394 return true;
8397 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8399 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8401 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8403 Item* pItem = GetItemByPos( i, j );
8404 if( pItem && pItem->GetEntry() == item )
8406 tempcount += pItem->GetCount();
8407 if( tempcount >= count )
8408 return true;
8414 if(inBankAlso)
8416 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8418 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8419 if( pItem && pItem->GetEntry() == item )
8421 tempcount += pItem->GetCount();
8422 if( tempcount >= count )
8423 return true;
8426 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8428 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8430 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8432 Item* pItem = GetItemByPos( i, j );
8433 if( pItem && pItem->GetEntry() == item )
8435 tempcount += pItem->GetCount();
8436 if( tempcount >= count )
8437 return true;
8444 return false;
8447 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8449 Item *pItem;
8450 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8452 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8453 if( pItem && pItem->GetEntry() == item )
8454 return pItem;
8457 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8458 if (pProto && pProto->GemProperties)
8460 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8462 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8463 if( pItem && pItem->GetProto()->Socket[0].Color )
8465 if (pItem->GetGemCountWithID(item) > 0 )
8466 return pItem;
8471 return NULL;
8474 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8476 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8477 if( !pProto )
8479 if(no_space_count)
8480 *no_space_count = count;
8481 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8484 // no maximum
8485 if(pProto->MaxCount == 0)
8486 return EQUIP_ERR_OK;
8488 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8490 if( curcount + count > pProto->MaxCount )
8492 if(no_space_count)
8493 *no_space_count = count +curcount - pProto->MaxCount;
8494 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8497 return EQUIP_ERR_OK;
8500 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8502 Item *pItem;
8503 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8505 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8506 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8507 return true;
8509 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8511 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8512 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8513 return true;
8515 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8517 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8519 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8521 pItem = GetItemByPos( i, j );
8522 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8523 return true;
8527 return false;
8530 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8532 Item* pItem2 = GetItemByPos( bag, slot );
8534 // ignore move item (this slot will be empty at move)
8535 if(pItem2==pSrcItem)
8536 pItem2 = NULL;
8538 uint32 need_space;
8540 // empty specific slot - check item fit to slot
8541 if( !pItem2 || swap )
8543 if( bag == INVENTORY_SLOT_BAG_0 )
8545 // keyring case
8546 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8547 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8549 // vanitypet case
8550 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS))
8551 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8553 // currencytoken case
8554 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8555 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8557 // guestbag case
8558 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS))
8559 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8561 // prevent cheating
8562 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8563 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8565 else
8567 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8568 if( !pBag )
8569 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8571 ItemPrototype const* pBagProto = pBag->GetProto();
8572 if( !pBagProto )
8573 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8575 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8576 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8579 // non empty stack with space
8580 need_space = pProto->Stackable;
8582 // non empty slot, check item type
8583 else
8585 // check item type
8586 if(pItem2->GetEntry() != pProto->ItemId)
8587 return EQUIP_ERR_ITEM_CANT_STACK;
8589 // check free space
8590 if(pItem2->GetCount() >= pProto->Stackable)
8591 return EQUIP_ERR_ITEM_CANT_STACK;
8593 need_space = pProto->Stackable - pItem2->GetCount();
8596 if(need_space > count)
8597 need_space = count;
8599 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8600 if(!newPosition.isContainedIn(dest))
8602 dest.push_back(newPosition);
8603 count -= need_space;
8605 return EQUIP_ERR_OK;
8608 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
8610 // skip specific bag already processed in first called _CanStoreItem_InBag
8611 if(bag==skip_bag)
8612 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8614 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8615 if( !pBag )
8616 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8618 ItemPrototype const* pBagProto = pBag->GetProto();
8619 if( !pBagProto )
8620 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8622 // specialized bag mode or non-specilized
8623 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8624 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8626 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8627 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8629 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8631 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8632 if(j==skip_slot)
8633 continue;
8635 Item* pItem2 = GetItemByPos( bag, j );
8637 // ignore move item (this slot will be empty at move)
8638 if(pItem2==pSrcItem)
8639 pItem2 = NULL;
8641 // if merge skip empty, if !merge skip non-empty
8642 if((pItem2!=NULL)!=merge)
8643 continue;
8645 if( pItem2 )
8647 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8649 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8650 if(need_space > count)
8651 need_space = count;
8653 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8654 if(!newPosition.isContainedIn(dest))
8656 dest.push_back(newPosition);
8657 count -= need_space;
8659 if(count==0)
8660 return EQUIP_ERR_OK;
8664 else
8666 uint32 need_space = pProto->Stackable;
8667 if(need_space > count)
8668 need_space = count;
8670 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8671 if(!newPosition.isContainedIn(dest))
8673 dest.push_back(newPosition);
8674 count -= need_space;
8676 if(count==0)
8677 return EQUIP_ERR_OK;
8681 return EQUIP_ERR_OK;
8684 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
8686 for(uint32 j = slot_begin; j < slot_end; j++)
8688 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8689 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8690 continue;
8692 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8694 // ignore move item (this slot will be empty at move)
8695 if(pItem2==pSrcItem)
8696 pItem2 = NULL;
8698 // if merge skip empty, if !merge skip non-empty
8699 if((pItem2!=NULL)!=merge)
8700 continue;
8702 if( pItem2 )
8704 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8706 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8707 if(need_space > count)
8708 need_space = count;
8709 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8710 if(!newPosition.isContainedIn(dest))
8712 dest.push_back(newPosition);
8713 count -= need_space;
8715 if(count==0)
8716 return EQUIP_ERR_OK;
8720 else
8722 uint32 need_space = pProto->Stackable;
8723 if(need_space > count)
8724 need_space = count;
8726 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8727 if(!newPosition.isContainedIn(dest))
8729 dest.push_back(newPosition);
8730 count -= need_space;
8732 if(count==0)
8733 return EQUIP_ERR_OK;
8737 return EQUIP_ERR_OK;
8740 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8742 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8744 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8745 if( !pProto )
8747 if(no_space_count)
8748 *no_space_count = count;
8749 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8752 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8754 if(no_space_count)
8755 *no_space_count = count;
8756 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8759 // check count of items (skip for auto move for same player from bank)
8760 uint32 no_similar_count = 0; // can't store this amount similar items
8761 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8762 if(res!=EQUIP_ERR_OK)
8764 if(count==no_similar_count)
8766 if(no_space_count)
8767 *no_space_count = no_similar_count;
8768 return res;
8770 count -= no_similar_count;
8773 // in specific slot
8774 if( bag != NULL_BAG && slot != NULL_SLOT )
8776 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8777 if(res!=EQUIP_ERR_OK)
8779 if(no_space_count)
8780 *no_space_count = count + no_similar_count;
8781 return res;
8784 if(count==0)
8786 if(no_similar_count==0)
8787 return EQUIP_ERR_OK;
8789 if(no_space_count)
8790 *no_space_count = count + no_similar_count;
8791 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8795 // not specific slot or have space for partly store only in specific slot
8797 // in specific bag
8798 if( bag != NULL_BAG )
8800 // search stack in bag for merge to
8801 if( pProto->Stackable > 1 )
8803 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8805 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8806 if(res!=EQUIP_ERR_OK)
8808 if(no_space_count)
8809 *no_space_count = count + no_similar_count;
8810 return res;
8813 if(count==0)
8815 if(no_similar_count==0)
8816 return EQUIP_ERR_OK;
8818 if(no_space_count)
8819 *no_space_count = count + no_similar_count;
8820 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8823 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8824 if(res!=EQUIP_ERR_OK)
8826 if(no_space_count)
8827 *no_space_count = count + no_similar_count;
8828 return res;
8831 if(count==0)
8833 if(no_similar_count==0)
8834 return EQUIP_ERR_OK;
8836 if(no_space_count)
8837 *no_space_count = count + no_similar_count;
8838 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8841 else // equipped bag
8843 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8844 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8845 if(res!=EQUIP_ERR_OK)
8846 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8848 if(res!=EQUIP_ERR_OK)
8850 if(no_space_count)
8851 *no_space_count = count + no_similar_count;
8852 return res;
8855 if(count==0)
8857 if(no_similar_count==0)
8858 return EQUIP_ERR_OK;
8860 if(no_space_count)
8861 *no_space_count = count + no_similar_count;
8862 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8867 // search free slot in bag for place to
8868 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8870 // search free slot - keyring case
8871 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8873 uint32 keyringSize = GetMaxKeyringSize();
8874 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8875 if(res!=EQUIP_ERR_OK)
8877 if(no_space_count)
8878 *no_space_count = count + no_similar_count;
8879 return res;
8882 if(count==0)
8884 if(no_similar_count==0)
8885 return EQUIP_ERR_OK;
8887 if(no_space_count)
8888 *no_space_count = count + no_similar_count;
8889 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8892 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
8894 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8895 if(res!=EQUIP_ERR_OK)
8897 if(no_space_count)
8898 *no_space_count = count + no_similar_count;
8899 return res;
8902 if(count==0)
8904 if(no_similar_count==0)
8905 return EQUIP_ERR_OK;
8907 if(no_space_count)
8908 *no_space_count = count + no_similar_count;
8909 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8912 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8914 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8915 if(res!=EQUIP_ERR_OK)
8917 if(no_space_count)
8918 *no_space_count = count + no_similar_count;
8919 return res;
8922 if(count==0)
8924 if(no_similar_count==0)
8925 return EQUIP_ERR_OK;
8927 if(no_space_count)
8928 *no_space_count = count + no_similar_count;
8929 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8932 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
8934 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8935 if(res!=EQUIP_ERR_OK)
8937 if(no_space_count)
8938 *no_space_count = count + no_similar_count;
8939 return res;
8942 if(count==0)
8944 if(no_similar_count==0)
8945 return EQUIP_ERR_OK;
8947 if(no_space_count)
8948 *no_space_count = count + no_similar_count;
8949 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8953 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8954 if(res!=EQUIP_ERR_OK)
8956 if(no_space_count)
8957 *no_space_count = count + no_similar_count;
8958 return res;
8961 if(count==0)
8963 if(no_similar_count==0)
8964 return EQUIP_ERR_OK;
8966 if(no_space_count)
8967 *no_space_count = count + no_similar_count;
8968 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8971 else // equipped bag
8973 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8974 if(res!=EQUIP_ERR_OK)
8975 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8977 if(res!=EQUIP_ERR_OK)
8979 if(no_space_count)
8980 *no_space_count = count + no_similar_count;
8981 return res;
8984 if(count==0)
8986 if(no_similar_count==0)
8987 return EQUIP_ERR_OK;
8989 if(no_space_count)
8990 *no_space_count = count + no_similar_count;
8991 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8996 // not specific bag or have space for partly store only in specific bag
8998 // search stack for merge to
8999 if( pProto->Stackable > 1 )
9001 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9002 if(res!=EQUIP_ERR_OK)
9004 if(no_space_count)
9005 *no_space_count = count + no_similar_count;
9006 return res;
9009 if(count==0)
9011 if(no_similar_count==0)
9012 return EQUIP_ERR_OK;
9014 if(no_space_count)
9015 *no_space_count = count + no_similar_count;
9016 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9019 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9020 if(res!=EQUIP_ERR_OK)
9022 if(no_space_count)
9023 *no_space_count = count + no_similar_count;
9024 return res;
9027 if(count==0)
9029 if(no_similar_count==0)
9030 return EQUIP_ERR_OK;
9032 if(no_space_count)
9033 *no_space_count = count + no_similar_count;
9034 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9037 if( pProto->BagFamily )
9039 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9041 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9042 if(res!=EQUIP_ERR_OK)
9043 continue;
9045 if(count==0)
9047 if(no_similar_count==0)
9048 return EQUIP_ERR_OK;
9050 if(no_space_count)
9051 *no_space_count = count + no_similar_count;
9052 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9057 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9059 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9060 if(res!=EQUIP_ERR_OK)
9061 continue;
9063 if(count==0)
9065 if(no_similar_count==0)
9066 return EQUIP_ERR_OK;
9068 if(no_space_count)
9069 *no_space_count = count + no_similar_count;
9070 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9075 // search free slot - special bag case
9076 if( pProto->BagFamily )
9078 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9080 uint32 keyringSize = GetMaxKeyringSize();
9081 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9082 if(res!=EQUIP_ERR_OK)
9084 if(no_space_count)
9085 *no_space_count = count + no_similar_count;
9086 return res;
9089 if(count==0)
9091 if(no_similar_count==0)
9092 return EQUIP_ERR_OK;
9094 if(no_space_count)
9095 *no_space_count = count + no_similar_count;
9096 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9099 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9101 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9102 if(res!=EQUIP_ERR_OK)
9104 if(no_space_count)
9105 *no_space_count = count + no_similar_count;
9106 return res;
9109 if(count==0)
9111 if(no_similar_count==0)
9112 return EQUIP_ERR_OK;
9114 if(no_space_count)
9115 *no_space_count = count + no_similar_count;
9116 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9119 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9121 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9122 if(res!=EQUIP_ERR_OK)
9124 if(no_space_count)
9125 *no_space_count = count + no_similar_count;
9126 return res;
9129 if(count==0)
9131 if(no_similar_count==0)
9132 return EQUIP_ERR_OK;
9134 if(no_space_count)
9135 *no_space_count = count + no_similar_count;
9136 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9139 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9141 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9142 if(res!=EQUIP_ERR_OK)
9144 if(no_space_count)
9145 *no_space_count = count + no_similar_count;
9146 return res;
9149 if(count==0)
9151 if(no_similar_count==0)
9152 return EQUIP_ERR_OK;
9154 if(no_space_count)
9155 *no_space_count = count + no_similar_count;
9156 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9160 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9162 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9163 if(res!=EQUIP_ERR_OK)
9164 continue;
9166 if(count==0)
9168 if(no_similar_count==0)
9169 return EQUIP_ERR_OK;
9171 if(no_space_count)
9172 *no_space_count = count + no_similar_count;
9173 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9178 // search free slot
9179 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9180 if(res!=EQUIP_ERR_OK)
9182 if(no_space_count)
9183 *no_space_count = count + no_similar_count;
9184 return res;
9187 if(count==0)
9189 if(no_similar_count==0)
9190 return EQUIP_ERR_OK;
9192 if(no_space_count)
9193 *no_space_count = count + no_similar_count;
9194 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9197 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9199 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9200 if(res!=EQUIP_ERR_OK)
9201 continue;
9203 if(count==0)
9205 if(no_similar_count==0)
9206 return EQUIP_ERR_OK;
9208 if(no_space_count)
9209 *no_space_count = count + no_similar_count;
9210 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9214 if(no_space_count)
9215 *no_space_count = count + no_similar_count;
9217 return EQUIP_ERR_INVENTORY_FULL;
9220 //////////////////////////////////////////////////////////////////////////
9221 uint8 Player::CanStoreItems( Item **pItems,int count) const
9223 Item *pItem2;
9225 // fill space table
9226 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9227 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9228 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9229 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9230 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9231 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9233 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9234 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9235 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9236 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9237 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9238 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9240 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9242 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9244 if (pItem2 && !pItem2->IsInTrade())
9246 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9250 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9252 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9254 if (pItem2 && !pItem2->IsInTrade())
9256 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9260 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9262 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9264 if (pItem2 && !pItem2->IsInTrade())
9266 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9270 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9272 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9274 if (pItem2 && !pItem2->IsInTrade())
9276 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9280 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9282 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9284 if (pItem2 && !pItem2->IsInTrade())
9286 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9290 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9292 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9294 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9296 pItem2 = GetItemByPos( i, j );
9297 if (pItem2 && !pItem2->IsInTrade())
9299 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9305 // check free space for all items
9306 for (int k=0;k<count;k++)
9308 Item *pItem = pItems[k];
9310 // no item
9311 if (!pItem) continue;
9313 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9314 ItemPrototype const *pProto = pItem->GetProto();
9316 // strange item
9317 if( !pProto )
9318 return EQUIP_ERR_ITEM_NOT_FOUND;
9320 // item it 'bind'
9321 if(pItem->IsBindedNotWith(GetGUID()))
9322 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9324 Bag *pBag;
9325 ItemPrototype const *pBagProto;
9327 // item is 'one item only'
9328 uint8 res = CanTakeMoreSimilarItems(pItem);
9329 if(res != EQUIP_ERR_OK)
9330 return res;
9332 // search stack for merge to
9333 if( pProto->Stackable > 1 )
9335 bool b_found = false;
9337 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9339 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9340 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9342 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9343 b_found = true;
9344 break;
9347 if (b_found) continue;
9349 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9351 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9352 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9354 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9355 b_found = true;
9356 break;
9359 if (b_found) continue;
9361 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9363 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9364 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9366 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9367 b_found = true;
9368 break;
9371 if (b_found) continue;
9373 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9375 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9376 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9378 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9379 b_found = true;
9380 break;
9383 if (b_found) continue;
9385 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9387 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9388 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9390 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9391 b_found = true;
9392 break;
9395 if (b_found) continue;
9397 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9399 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9400 if( pBag )
9402 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9404 pItem2 = GetItemByPos( t, j );
9405 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9407 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9408 b_found = true;
9409 break;
9414 if (b_found) continue;
9417 // special bag case
9418 if( pProto->BagFamily )
9420 bool b_found = false;
9421 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9423 uint32 keyringSize = GetMaxKeyringSize();
9424 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9426 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9428 inv_keys[t-KEYRING_SLOT_START] = 1;
9429 b_found = true;
9430 break;
9435 if (b_found) continue;
9437 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9439 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9441 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9443 inv_pets[t-VANITYPET_SLOT_START] = 1;
9444 b_found = true;
9445 break;
9450 if (b_found) continue;
9452 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9454 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9456 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9458 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9459 b_found = true;
9460 break;
9465 if (b_found) continue;
9467 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9469 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9471 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9473 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9474 b_found = true;
9475 break;
9480 if (b_found) continue;
9482 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9484 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9485 if( pBag )
9487 pBagProto = pBag->GetProto();
9489 // not plain container check
9490 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9491 ItemCanGoIntoBag(pProto,pBagProto) )
9493 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9495 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9497 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9498 b_found = true;
9499 break;
9505 if (b_found) continue;
9508 // search free slot
9509 bool b_found = false;
9510 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9512 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9514 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9515 b_found = true;
9516 break;
9519 if (b_found) continue;
9521 // search free slot in bags
9522 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9524 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9525 if( pBag )
9527 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9529 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9531 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9532 b_found = true;
9533 break;
9539 // no free slot found?
9540 if (!b_found)
9541 return EQUIP_ERR_INVENTORY_FULL;
9544 return EQUIP_ERR_OK;
9547 //////////////////////////////////////////////////////////////////////////
9548 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9550 dest = 0;
9551 Item *pItem = Item::CreateItem( item, count, this );
9552 if( pItem )
9554 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9555 delete pItem;
9556 return result;
9559 return EQUIP_ERR_ITEM_NOT_FOUND;
9562 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9564 dest = 0;
9565 if( pItem )
9567 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9568 ItemPrototype const *pProto = pItem->GetProto();
9569 if( pProto )
9571 // May be here should be more stronger checks; STUNNED checked
9572 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9573 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9574 return EQUIP_ERR_YOU_ARE_STUNNED;
9576 if(pItem->IsBindedNotWith(GetGUID()))
9577 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9579 // check count of items (skip for auto move for same player from bank)
9580 uint8 res = CanTakeMoreSimilarItems(pItem);
9581 if(res != EQUIP_ERR_OK)
9582 return res;
9584 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9585 // - combat
9586 // - in-progress arenas
9587 if( !pProto->CanChangeEquipStateInCombat() )
9589 if( isInCombat() )
9590 return EQUIP_ERR_NOT_IN_COMBAT;
9592 if(BattleGround* bg = GetBattleGround())
9593 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9594 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9597 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9598 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9600 if(IsNonMeleeSpellCasted(false))
9601 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9603 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9604 if( eslot == NULL_SLOT )
9605 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9607 uint8 msg = CanUseItem( pItem , not_loading );
9608 if( msg != EQUIP_ERR_OK )
9609 return msg;
9610 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9611 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9613 // check unique-equipped on item
9614 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9616 // there is an equip limit on this item
9617 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9618 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9619 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9622 // check unique-equipped on gems
9623 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9625 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9626 if(!enchant_id)
9627 continue;
9628 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9629 if(!enchantEntry)
9630 continue;
9632 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9633 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9635 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9636 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9637 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9641 // check unique-equipped special item classes
9642 if (pProto->Class == ITEM_CLASS_QUIVER)
9644 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9646 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9648 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9650 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9651 (!swap || pBag->GetSlot() != eslot ) )
9653 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9654 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9655 else
9656 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9663 uint32 type = pProto->InventoryType;
9665 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9667 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9669 if(!CanDualWield())
9670 return EQUIP_ERR_CANT_DUAL_WIELD;
9673 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9674 if(mainItem)
9676 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9677 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9681 // equip two-hand weapon case (with possible unequip 2 items)
9682 if( type == INVTYPE_2HWEAPON )
9684 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9685 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9687 // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
9688 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9689 ItemPosCountVec off_dest;
9690 if( offItem && (!not_loading ||
9691 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9692 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9693 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9695 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9696 return EQUIP_ERR_OK;
9699 if( !swap )
9700 return EQUIP_ERR_ITEM_NOT_FOUND;
9701 else
9702 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9705 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9707 // Applied only to equipped items and bank bags
9708 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9709 return EQUIP_ERR_OK;
9711 Item* pItem = GetItemByPos(pos);
9713 // Applied only to existed equipped item
9714 if( !pItem )
9715 return EQUIP_ERR_OK;
9717 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9719 ItemPrototype const *pProto = pItem->GetProto();
9720 if( !pProto )
9721 return EQUIP_ERR_ITEM_NOT_FOUND;
9723 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9724 // - combat
9725 // - in-progress arenas
9726 if( !pProto->CanChangeEquipStateInCombat() )
9728 if( isInCombat() )
9729 return EQUIP_ERR_NOT_IN_COMBAT;
9731 if(BattleGround* bg = GetBattleGround())
9732 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9733 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9736 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9737 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9739 return EQUIP_ERR_OK;
9742 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9744 if( !pItem )
9745 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9747 uint32 count = pItem->GetCount();
9749 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9750 ItemPrototype const *pProto = pItem->GetProto();
9751 if( !pProto )
9752 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9754 if( pItem->IsBindedNotWith(GetGUID()) )
9755 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9757 // check count of items (skip for auto move for same player from bank)
9758 uint8 res = CanTakeMoreSimilarItems(pItem);
9759 if(res != EQUIP_ERR_OK)
9760 return res;
9762 // in specific slot
9763 if( bag != NULL_BAG && slot != NULL_SLOT )
9765 if( pProto->InventoryType == INVTYPE_BAG )
9767 Bag *pBag = (Bag*)pItem;
9768 if( pBag )
9770 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9772 if( !HasBankBagSlot( slot ) )
9773 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9774 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9775 return cantuse;
9777 else
9779 if( !pBag->IsEmpty() )
9780 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9784 else
9786 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9787 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9790 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9791 if(res!=EQUIP_ERR_OK)
9792 return res;
9794 if(count==0)
9795 return EQUIP_ERR_OK;
9798 // not specific slot or have spece for partly store only in specific slot
9800 // in specific bag
9801 if( bag != NULL_BAG )
9803 if( pProto->InventoryType == INVTYPE_BAG )
9805 Bag *pBag = (Bag*)pItem;
9806 if( pBag && !pBag->IsEmpty() )
9807 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9810 // search stack in bag for merge to
9811 if( pProto->Stackable > 1 )
9813 if( bag == INVENTORY_SLOT_BAG_0 )
9815 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9816 if(res!=EQUIP_ERR_OK)
9817 return res;
9819 if(count==0)
9820 return EQUIP_ERR_OK;
9822 else
9824 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9825 if(res!=EQUIP_ERR_OK)
9826 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9828 if(res!=EQUIP_ERR_OK)
9829 return res;
9831 if(count==0)
9832 return EQUIP_ERR_OK;
9836 // search free slot in bag
9837 if( bag == INVENTORY_SLOT_BAG_0 )
9839 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9840 if(res!=EQUIP_ERR_OK)
9841 return res;
9843 if(count==0)
9844 return EQUIP_ERR_OK;
9846 else
9848 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9849 if(res!=EQUIP_ERR_OK)
9850 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9852 if(res!=EQUIP_ERR_OK)
9853 return res;
9855 if(count==0)
9856 return EQUIP_ERR_OK;
9860 // not specific bag or have spece for partly store only in specific bag
9862 // search stack for merge to
9863 if( pProto->Stackable > 1 )
9865 // in slots
9866 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9867 if(res!=EQUIP_ERR_OK)
9868 return res;
9870 if(count==0)
9871 return EQUIP_ERR_OK;
9873 // in special bags
9874 if( pProto->BagFamily )
9876 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9878 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9879 if(res!=EQUIP_ERR_OK)
9880 continue;
9882 if(count==0)
9883 return EQUIP_ERR_OK;
9887 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9889 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9890 if(res!=EQUIP_ERR_OK)
9891 continue;
9893 if(count==0)
9894 return EQUIP_ERR_OK;
9898 // search free place in special bag
9899 if( pProto->BagFamily )
9901 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9903 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9904 if(res!=EQUIP_ERR_OK)
9905 continue;
9907 if(count==0)
9908 return EQUIP_ERR_OK;
9912 // search free space
9913 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9914 if(res!=EQUIP_ERR_OK)
9915 return res;
9917 if(count==0)
9918 return EQUIP_ERR_OK;
9920 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9922 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9923 if(res!=EQUIP_ERR_OK)
9924 continue;
9926 if(count==0)
9927 return EQUIP_ERR_OK;
9929 return EQUIP_ERR_BANK_FULL;
9932 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9934 if( pItem )
9936 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9937 if( !isAlive() && not_loading )
9938 return EQUIP_ERR_YOU_ARE_DEAD;
9939 //if( isStunned() )
9940 // return EQUIP_ERR_YOU_ARE_STUNNED;
9941 ItemPrototype const *pProto = pItem->GetProto();
9942 if( pProto )
9944 if( pItem->IsBindedNotWith(GetGUID()) )
9945 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9946 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9947 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9948 if( pItem->GetSkill() != 0 )
9950 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9951 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9953 if( pProto->RequiredSkill != 0 )
9955 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9956 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9957 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9958 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9960 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9961 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9962 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9963 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9964 if( getLevel() < pProto->RequiredLevel )
9965 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9966 return EQUIP_ERR_OK;
9969 return EQUIP_ERR_ITEM_NOT_FOUND;
9972 bool Player::CanUseItem( ItemPrototype const *pProto )
9974 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9976 if( pProto )
9978 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9979 return false;
9980 if( pProto->RequiredSkill != 0 )
9982 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9983 return false;
9984 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9985 return false;
9987 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9988 return false;
9989 if( getLevel() < pProto->RequiredLevel )
9990 return false;
9991 return true;
9993 return false;
9996 uint8 Player::CanUseAmmo( uint32 item ) const
9998 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9999 if( !isAlive() )
10000 return EQUIP_ERR_YOU_ARE_DEAD;
10001 //if( isStunned() )
10002 // return EQUIP_ERR_YOU_ARE_STUNNED;
10003 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10004 if( pProto )
10006 if( pProto->InventoryType!= INVTYPE_AMMO )
10007 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10008 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10009 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10010 if( pProto->RequiredSkill != 0 )
10012 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10013 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10014 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10015 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10017 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10018 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10019 /*if( GetReputation() < pProto->RequiredReputation )
10020 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10022 if( getLevel() < pProto->RequiredLevel )
10023 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10025 // Requires No Ammo
10026 if(GetDummyAura(46699))
10027 return EQUIP_ERR_BAG_FULL6;
10029 return EQUIP_ERR_OK;
10031 return EQUIP_ERR_ITEM_NOT_FOUND;
10034 void Player::SetAmmo( uint32 item )
10036 if(!item)
10037 return;
10039 // already set
10040 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10041 return;
10043 // check ammo
10044 if(item)
10046 uint8 msg = CanUseAmmo( item );
10047 if( msg != EQUIP_ERR_OK )
10049 SendEquipError( msg, NULL, NULL );
10050 return;
10054 SetUInt32Value(PLAYER_AMMO_ID, item);
10056 _ApplyAmmoBonuses();
10059 void Player::RemoveAmmo()
10061 SetUInt32Value(PLAYER_AMMO_ID, 0);
10063 m_ammoDPS = 0.0f;
10065 if(CanModifyStats())
10066 UpdateDamagePhysical(RANGED_ATTACK);
10069 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10070 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10072 uint32 count = 0;
10073 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10074 count += itr->count;
10076 Item *pItem = Item::CreateItem( item, count, this );
10077 if( pItem )
10079 ItemAddedQuestCheck( item, count );
10080 if(randomPropertyId)
10081 pItem->SetItemRandomProperties(randomPropertyId);
10082 pItem = StoreItem( dest, pItem, update );
10084 return pItem;
10087 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10089 if( !pItem )
10090 return NULL;
10092 Item* lastItem = pItem;
10094 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10096 uint16 pos = itr->pos;
10097 uint32 count = itr->count;
10099 ++itr;
10101 if(itr == dest.end())
10103 lastItem = _StoreItem(pos,pItem,count,false,update);
10104 break;
10107 lastItem = _StoreItem(pos,pItem,count,true,update);
10110 return lastItem;
10113 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10114 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10116 if( !pItem )
10117 return NULL;
10119 uint8 bag = pos >> 8;
10120 uint8 slot = pos & 255;
10122 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10124 Item *pItem2 = GetItemByPos( bag, slot );
10126 if( !pItem2 )
10128 if(clone)
10129 pItem = pItem->CloneItem(count,this);
10130 else
10131 pItem->SetCount(count);
10133 if(!pItem)
10134 return NULL;
10136 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10137 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10138 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10139 pItem->SetBinding( true );
10141 if( bag == INVENTORY_SLOT_BAG_0 )
10143 m_items[slot] = pItem;
10144 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10145 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10146 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10148 pItem->SetSlot( slot );
10149 pItem->SetContainer( NULL );
10151 if( IsInWorld() && update )
10153 pItem->AddToWorld();
10154 pItem->SendUpdateToPlayer( this );
10157 pItem->SetState(ITEM_CHANGED, this);
10159 else
10161 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10162 if( pBag )
10164 pBag->StoreItem( slot, pItem, update );
10165 if( IsInWorld() && update )
10167 pItem->AddToWorld();
10168 pItem->SendUpdateToPlayer( this );
10170 pItem->SetState(ITEM_CHANGED, this);
10171 pBag->SetState(ITEM_CHANGED, this);
10175 AddEnchantmentDurations(pItem);
10176 AddItemDurations(pItem);
10178 return pItem;
10180 else
10182 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10183 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10184 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10185 pItem2->SetBinding( true );
10187 pItem2->SetCount( pItem2->GetCount() + count );
10188 if( IsInWorld() && update )
10189 pItem2->SendUpdateToPlayer( this );
10191 if(!clone)
10193 // delete item (it not in any slot currently)
10194 if( IsInWorld() && update )
10196 pItem->RemoveFromWorld();
10197 pItem->DestroyForPlayer( this );
10200 RemoveEnchantmentDurations(pItem);
10201 RemoveItemDurations(pItem);
10203 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10204 pItem->SetState(ITEM_REMOVED, this);
10206 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10207 AddEnchantmentDurations(pItem2);
10209 pItem2->SetState(ITEM_CHANGED, this);
10211 return pItem2;
10215 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
10217 Item *pItem = Item::CreateItem( item, count, this );
10218 if( pItem )
10220 ItemAddedQuestCheck( item, count );
10221 Item * retItem = EquipItem( pos, pItem, update );
10223 return retItem;
10225 return NULL;
10228 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10230 if( pItem )
10232 AddEnchantmentDurations(pItem);
10233 AddItemDurations(pItem);
10235 uint8 bag = pos >> 8;
10236 uint8 slot = pos & 255;
10238 Item *pItem2 = GetItemByPos( bag, slot );
10240 if( !pItem2 )
10242 VisualizeItem( slot, pItem);
10244 if(isAlive())
10246 ItemPrototype const *pProto = pItem->GetProto();
10248 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10249 if(pProto && pProto->ItemSet)
10250 AddItemsSetItem(this,pItem);
10252 _ApplyItemMods(pItem, slot, true);
10254 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10256 m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
10257 if (getClass() == CLASS_ROGUE)
10258 m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
10262 if( IsInWorld() && update )
10264 pItem->AddToWorld();
10265 pItem->SendUpdateToPlayer( this );
10268 ApplyEquipCooldown(pItem);
10270 if( slot == EQUIPMENT_SLOT_MAINHAND )
10271 UpdateExpertise(BASE_ATTACK);
10272 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10273 UpdateExpertise(OFF_ATTACK);
10275 else
10277 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10278 if( IsInWorld() && update )
10279 pItem2->SendUpdateToPlayer( this );
10281 // delete item (it not in any slot currently)
10282 //pItem->DeleteFromDB();
10283 if( IsInWorld() && update )
10285 pItem->RemoveFromWorld();
10286 pItem->DestroyForPlayer( this );
10289 RemoveEnchantmentDurations(pItem);
10290 RemoveItemDurations(pItem);
10292 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10293 pItem->SetState(ITEM_REMOVED, this);
10294 pItem2->SetState(ITEM_CHANGED, this);
10296 ApplyEquipCooldown(pItem2);
10298 return pItem2;
10302 return pItem;
10305 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10307 if( pItem )
10309 AddEnchantmentDurations(pItem);
10310 AddItemDurations(pItem);
10312 uint8 slot = pos & 255;
10313 VisualizeItem( slot, pItem);
10315 if( IsInWorld() )
10317 pItem->AddToWorld();
10318 pItem->SendUpdateToPlayer( this );
10323 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10325 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10326 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10327 // entry // Size: 1
10328 // inspected enchantments // Size: 6
10329 // ? // Size: 5
10330 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10331 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10332 // // = 16
10334 if(pItem)
10336 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10338 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10339 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10341 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10342 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10344 // Use SetInt16Value to prevent set high part to FFFF for negative value
10345 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10346 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10348 else
10350 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10352 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10353 SetUInt32Value(VisibleBase + 0, 0);
10355 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10356 SetUInt32Value(VisibleBase + 1 + i, 0);
10358 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10359 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10363 void Player::VisualizeItem( uint8 slot, Item *pItem)
10365 if(!pItem)
10366 return;
10368 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10369 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10370 pItem->SetBinding( true );
10372 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10374 m_items[slot] = pItem;
10375 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10376 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10377 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10378 pItem->SetSlot( slot );
10379 pItem->SetContainer( NULL );
10381 if( slot < EQUIPMENT_SLOT_END )
10382 SetVisibleItemSlot(slot,pItem);
10384 pItem->SetState(ITEM_CHANGED, this);
10387 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10389 // note: removeitem does not actually change the item
10390 // it only takes the item out of storage temporarily
10391 // note2: if removeitem is to be used for delinking
10392 // the item must be removed from the player's updatequeue
10394 Item *pItem = GetItemByPos( bag, slot );
10395 if( pItem )
10397 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10399 RemoveEnchantmentDurations(pItem);
10400 RemoveItemDurations(pItem);
10402 if( bag == INVENTORY_SLOT_BAG_0 )
10404 if ( slot < INVENTORY_SLOT_BAG_END )
10406 ItemPrototype const *pProto = pItem->GetProto();
10407 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10409 if(pProto && pProto->ItemSet)
10410 RemoveItemsSetItem(this,pProto);
10412 _ApplyItemMods(pItem, slot, false);
10414 // remove item dependent auras and casts (only weapon and armor slots)
10415 if(slot < EQUIPMENT_SLOT_END)
10416 RemoveItemDependentAurasAndCasts(pItem);
10418 // remove held enchantments
10419 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10421 if (pItem->GetItemSuffixFactor())
10423 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10424 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10426 else
10428 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10429 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10434 m_items[slot] = NULL;
10435 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10437 if ( slot < EQUIPMENT_SLOT_END )
10438 SetVisibleItemSlot(slot,NULL);
10440 else
10442 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10443 if( pBag )
10444 pBag->RemoveItem(slot, update);
10446 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10447 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10448 pItem->SetSlot( NULL_SLOT );
10449 if( IsInWorld() && update )
10450 pItem->SendUpdateToPlayer( this );
10452 if( slot == EQUIPMENT_SLOT_MAINHAND )
10453 UpdateExpertise(BASE_ATTACK);
10454 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10455 UpdateExpertise(OFF_ATTACK);
10459 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10460 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10462 if(Item* it = GetItemByPos(bag,slot))
10464 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10465 RemoveItem( bag,slot,update);
10466 it->RemoveFromUpdateQueueOf(this);
10467 if(it->IsInWorld())
10469 it->RemoveFromWorld();
10470 it->DestroyForPlayer( this );
10475 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10476 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10478 // update quest counters
10479 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10481 // store item
10482 Item* pLastItem = StoreItem( dest, pItem, update);
10484 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10485 if(pLastItem==pItem)
10487 // update owner for last item (this can be original item with wrong owner
10488 if(pLastItem->GetOwnerGUID() != GetGUID())
10489 pLastItem->SetOwnerGUID(GetGUID());
10491 // if this original item then it need create record in inventory
10492 // in case trade we laready have item in other player inventory
10493 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10497 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10499 Item *pItem = GetItemByPos( bag, slot );
10500 if( pItem )
10502 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10504 // start from destroy contained items (only equipped bag can have its)
10505 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10507 for (int i = 0; i < MAX_BAG_SIZE; i++)
10508 DestroyItem(slot,i,update);
10511 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10512 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10514 ItemPrototype const *pProto = pItem->GetProto();
10516 RemoveEnchantmentDurations(pItem);
10517 RemoveItemDurations(pItem);
10519 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10521 if( bag == INVENTORY_SLOT_BAG_0 )
10523 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10525 // equipment and equipped bags can have applied bonuses
10526 if ( slot < INVENTORY_SLOT_BAG_END )
10528 ItemPrototype const *pProto = pItem->GetProto();
10530 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10531 if(pProto && pProto->ItemSet)
10532 RemoveItemsSetItem(this,pProto);
10534 _ApplyItemMods(pItem, slot, false);
10537 if ( slot < EQUIPMENT_SLOT_END )
10539 // remove item dependent auras and casts (only weapon and armor slots)
10540 RemoveItemDependentAurasAndCasts(pItem);
10542 // equipment visual show
10543 SetVisibleItemSlot(slot,NULL);
10546 m_items[slot] = NULL;
10548 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10549 pBag->RemoveItem(slot, update);
10551 if( IsInWorld() && update )
10553 pItem->RemoveFromWorld();
10554 pItem->DestroyForPlayer(this);
10557 //pItem->SetOwnerGUID(0);
10558 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10559 pItem->SetSlot( NULL_SLOT );
10560 pItem->SetState(ITEM_REMOVED, this);
10564 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10566 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10567 Item *pItem;
10568 ItemPrototype const *pProto;
10569 uint32 remcount = 0;
10571 // in inventory
10572 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10574 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10575 if( pItem && pItem->GetEntry() == item )
10577 if( pItem->GetCount() + remcount <= count )
10579 // all items in inventory can unequipped
10580 remcount += pItem->GetCount();
10581 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10583 if(remcount >=count)
10584 return;
10586 else
10588 pProto = pItem->GetProto();
10589 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10590 pItem->SetCount( pItem->GetCount() - count + remcount );
10591 if( IsInWorld() & update )
10592 pItem->SendUpdateToPlayer( this );
10593 pItem->SetState(ITEM_CHANGED, this);
10594 return;
10598 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10600 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10601 if( pItem && pItem->GetEntry() == item )
10603 if( pItem->GetCount() + remcount <= count )
10605 // all keys can be unequipped
10606 remcount += pItem->GetCount();
10607 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10609 if(remcount >=count)
10610 return;
10612 else
10614 pProto = pItem->GetProto();
10615 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10616 pItem->SetCount( pItem->GetCount() - count + remcount );
10617 if( IsInWorld() & update )
10618 pItem->SendUpdateToPlayer( this );
10619 pItem->SetState(ITEM_CHANGED, this);
10620 return;
10625 // in inventory bags
10626 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10628 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10630 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10632 pItem = pBag->GetItemByPos(j);
10633 if( pItem && pItem->GetEntry() == item )
10635 // all items in bags can be unequipped
10636 if( pItem->GetCount() + remcount <= count )
10638 remcount += pItem->GetCount();
10639 DestroyItem( i, j, update );
10641 if(remcount >=count)
10642 return;
10644 else
10646 pProto = pItem->GetProto();
10647 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10648 pItem->SetCount( pItem->GetCount() - count + remcount );
10649 if( IsInWorld() && update )
10650 pItem->SendUpdateToPlayer( this );
10651 pItem->SetState(ITEM_CHANGED, this);
10652 return;
10659 // in equipment and bag list
10660 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10662 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10663 if( pItem && pItem->GetEntry() == item )
10665 if( pItem->GetCount() + remcount <= count )
10667 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10669 remcount += pItem->GetCount();
10670 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10672 if(remcount >=count)
10673 return;
10676 else
10678 pProto = pItem->GetProto();
10679 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10680 pItem->SetCount( pItem->GetCount() - count + remcount );
10681 if( IsInWorld() & update )
10682 pItem->SendUpdateToPlayer( this );
10683 pItem->SetState(ITEM_CHANGED, this);
10684 return;
10690 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10692 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10694 // in inventory
10695 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10697 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10698 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10699 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10701 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10703 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10704 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10705 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10708 // in inventory bags
10709 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10711 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10712 if( pBag )
10714 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10716 Item* pItem = pBag->GetItemByPos(j);
10717 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10718 DestroyItem( i, j, update);
10723 // in equipment and bag list
10724 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10726 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10727 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10728 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10732 void Player::DestroyConjuredItems( bool update )
10734 // used when entering arena
10735 // destroys all conjured items
10736 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10738 // in inventory
10739 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10741 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10742 if( pItem && pItem->GetProto() &&
10743 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10744 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10745 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10748 // in inventory bags
10749 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10751 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10752 if( pBag )
10754 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10756 Item* pItem = pBag->GetItemByPos(j);
10757 if( pItem && pItem->GetProto() &&
10758 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10759 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10760 DestroyItem( i, j, update);
10765 // in equipment and bag list
10766 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10768 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10769 if( pItem && pItem->GetProto() &&
10770 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10771 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10772 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10776 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10778 if(!pItem)
10779 return;
10781 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10783 if( pItem->GetCount() <= count )
10785 count-= pItem->GetCount();
10787 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10789 else
10791 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10792 pItem->SetCount( pItem->GetCount() - count );
10793 count = 0;
10794 if( IsInWorld() & update )
10795 pItem->SendUpdateToPlayer( this );
10796 pItem->SetState(ITEM_CHANGED, this);
10800 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10802 uint8 srcbag = src >> 8;
10803 uint8 srcslot = src & 255;
10805 uint8 dstbag = dst >> 8;
10806 uint8 dstslot = dst & 255;
10808 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10809 if( !pSrcItem )
10811 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10812 return;
10815 // not let split all items (can be only at cheating)
10816 if(pSrcItem->GetCount() == count)
10818 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10819 return;
10822 // not let split more existed items (can be only at cheating)
10823 if(pSrcItem->GetCount() < count)
10825 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10826 return;
10829 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10831 //best error message found for attempting to split while looting
10832 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10833 return;
10836 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10837 Item *pNewItem = pSrcItem->CloneItem( count, this );
10838 if( !pNewItem )
10840 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10841 return;
10844 if( IsInventoryPos( dst ) )
10846 // change item amount before check (for unique max count check)
10847 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10849 ItemPosCountVec dest;
10850 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10851 if( msg != EQUIP_ERR_OK )
10853 delete pNewItem;
10854 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10855 SendEquipError( msg, pSrcItem, NULL );
10856 return;
10859 if( IsInWorld() )
10860 pSrcItem->SendUpdateToPlayer( this );
10861 pSrcItem->SetState(ITEM_CHANGED, this);
10862 StoreItem( dest, pNewItem, true);
10864 else if( IsBankPos ( dst ) )
10866 // change item amount before check (for unique max count check)
10867 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10869 ItemPosCountVec dest;
10870 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10871 if( msg != EQUIP_ERR_OK )
10873 delete pNewItem;
10874 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10875 SendEquipError( msg, pSrcItem, NULL );
10876 return;
10879 if( IsInWorld() )
10880 pSrcItem->SendUpdateToPlayer( this );
10881 pSrcItem->SetState(ITEM_CHANGED, this);
10882 BankItem( dest, pNewItem, true);
10884 else if( IsEquipmentPos ( dst ) )
10886 // change item amount before check (for unique max count check), provide space for splitted items
10887 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10889 uint16 dest;
10890 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10891 if( msg != EQUIP_ERR_OK )
10893 delete pNewItem;
10894 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10895 SendEquipError( msg, pSrcItem, NULL );
10896 return;
10899 if( IsInWorld() )
10900 pSrcItem->SendUpdateToPlayer( this );
10901 pSrcItem->SetState(ITEM_CHANGED, this);
10902 EquipItem( dest, pNewItem, true);
10903 AutoUnequipOffhandIfNeed();
10907 void Player::SwapItem( uint16 src, uint16 dst )
10909 uint8 srcbag = src >> 8;
10910 uint8 srcslot = src & 255;
10912 uint8 dstbag = dst >> 8;
10913 uint8 dstslot = dst & 255;
10915 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10916 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10918 if( !pSrcItem )
10919 return;
10921 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10923 if(!isAlive() )
10925 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10926 return;
10929 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10931 //best error message found for attempting to swap while looting
10932 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10933 return;
10936 // check unequip potability for equipped items and bank bags
10937 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10939 // bags can be swapped with empty bag slots
10940 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10941 if(msg != EQUIP_ERR_OK)
10943 SendEquipError( msg, pSrcItem, pDstItem );
10944 return;
10948 // prevent put equipped/bank bag in self
10949 if( IsBagPos ( src ) && srcslot == dstbag)
10951 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10952 return;
10955 if( !pDstItem )
10957 if( IsInventoryPos( dst ) )
10959 ItemPosCountVec dest;
10960 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10961 if( msg != EQUIP_ERR_OK )
10963 SendEquipError( msg, pSrcItem, NULL );
10964 return;
10967 RemoveItem(srcbag, srcslot, true);
10968 StoreItem( dest, pSrcItem, true);
10970 else if( IsBankPos ( dst ) )
10972 ItemPosCountVec dest;
10973 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10974 if( msg != EQUIP_ERR_OK )
10976 SendEquipError( msg, pSrcItem, NULL );
10977 return;
10980 RemoveItem(srcbag, srcslot, true);
10981 BankItem( dest, pSrcItem, true);
10983 else if( IsEquipmentPos ( dst ) )
10985 uint16 dest;
10986 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10987 if( msg != EQUIP_ERR_OK )
10989 SendEquipError( msg, pSrcItem, NULL );
10990 return;
10993 RemoveItem(srcbag, srcslot, true);
10994 EquipItem( dest, pSrcItem, true);
10995 AutoUnequipOffhandIfNeed();
10998 else // if (!pDstItem)
11000 if(pDstItem->m_lootGenerated) // prevent swap looting item
11002 //best error message found for attempting to swap while looting
11003 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11004 return;
11007 // check unequip potability for equipped items and bank bags
11008 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11010 // bags can be swapped with empty bag slots
11011 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11012 if(msg != EQUIP_ERR_OK)
11014 SendEquipError( msg, pSrcItem, pDstItem );
11015 return;
11019 // attempt merge to / fill target item
11021 uint8 msg;
11022 ItemPosCountVec sDest;
11023 uint16 eDest;
11024 if( IsInventoryPos( dst ) )
11025 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11026 else if( IsBankPos ( dst ) )
11027 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11028 else if( IsEquipmentPos ( dst ) )
11029 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11030 else
11031 return;
11033 // can be merge/fill
11034 if(msg == EQUIP_ERR_OK)
11036 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
11038 RemoveItem(srcbag, srcslot, true);
11040 if( IsInventoryPos( dst ) )
11041 StoreItem( sDest, pSrcItem, true);
11042 else if( IsBankPos ( dst ) )
11043 BankItem( sDest, pSrcItem, true);
11044 else if( IsEquipmentPos ( dst ) )
11046 EquipItem( eDest, pSrcItem, true);
11047 AutoUnequipOffhandIfNeed();
11050 else
11052 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
11053 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
11054 pSrcItem->SetState(ITEM_CHANGED, this);
11055 pDstItem->SetState(ITEM_CHANGED, this);
11056 if( IsInWorld() )
11058 pSrcItem->SendUpdateToPlayer( this );
11059 pDstItem->SendUpdateToPlayer( this );
11062 return;
11066 // impossible merge/fill, do real swap
11067 uint8 msg;
11069 // check src->dest move possibility
11070 ItemPosCountVec sDest;
11071 uint16 eDest;
11072 if( IsInventoryPos( dst ) )
11073 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11074 else if( IsBankPos( dst ) )
11075 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11076 else if( IsEquipmentPos( dst ) )
11078 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11079 if( msg == EQUIP_ERR_OK )
11080 msg = CanUnequipItem( eDest, true );
11083 if( msg != EQUIP_ERR_OK )
11085 SendEquipError( msg, pSrcItem, pDstItem );
11086 return;
11089 // check dest->src move possibility
11090 ItemPosCountVec sDest2;
11091 uint16 eDest2;
11092 if( IsInventoryPos( src ) )
11093 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11094 else if( IsBankPos( src ) )
11095 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11096 else if( IsEquipmentPos( src ) )
11098 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11099 if( msg == EQUIP_ERR_OK )
11100 msg = CanUnequipItem( eDest2, true);
11103 if( msg != EQUIP_ERR_OK )
11105 SendEquipError( msg, pDstItem, pSrcItem );
11106 return;
11109 // now do moves, remove...
11110 RemoveItem(dstbag, dstslot, false);
11111 RemoveItem(srcbag, srcslot, false);
11113 // add to dest
11114 if( IsInventoryPos( dst ) )
11115 StoreItem(sDest, pSrcItem, true);
11116 else if( IsBankPos( dst ) )
11117 BankItem(sDest, pSrcItem, true);
11118 else if( IsEquipmentPos( dst ) )
11119 EquipItem(eDest, pSrcItem, true);
11121 // add to src
11122 if( IsInventoryPos( src ) )
11123 StoreItem(sDest2, pDstItem, true);
11124 else if( IsBankPos( src ) )
11125 BankItem(sDest2, pDstItem, true);
11126 else if( IsEquipmentPos( src ) )
11127 EquipItem(eDest2, pDstItem, true);
11129 AutoUnequipOffhandIfNeed();
11133 void Player::AddItemToBuyBackSlot( Item *pItem )
11135 if( pItem )
11137 uint32 slot = m_currentBuybackSlot;
11138 // if current back slot non-empty search oldest or free
11139 if(m_items[slot])
11141 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11142 uint32 oldest_slot = BUYBACK_SLOT_START;
11144 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11146 // found empty
11147 if(!m_items[i])
11149 slot = i;
11150 break;
11153 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11155 if(oldest_time > i_time)
11157 oldest_time = i_time;
11158 oldest_slot = i;
11162 // find oldest
11163 slot = oldest_slot;
11166 RemoveItemFromBuyBackSlot( slot, true );
11167 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11169 m_items[slot] = pItem;
11170 time_t base = time(NULL);
11171 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11172 uint32 eslot = slot - BUYBACK_SLOT_START;
11174 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11175 ItemPrototype const *pProto = pItem->GetProto();
11176 if( pProto )
11177 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11178 else
11179 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11180 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11182 // move to next (for non filled list is move most optimized choice)
11183 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11184 ++m_currentBuybackSlot;
11188 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11190 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11191 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11192 return m_items[slot];
11193 return NULL;
11196 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11198 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11199 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11201 Item *pItem = m_items[slot];
11202 if( pItem )
11204 pItem->RemoveFromWorld();
11205 if(del) pItem->SetState(ITEM_REMOVED, this);
11208 m_items[slot] = NULL;
11210 uint32 eslot = slot - BUYBACK_SLOT_START;
11211 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11212 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11213 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11215 // if current backslot is filled set to now free slot
11216 if(m_items[m_currentBuybackSlot])
11217 m_currentBuybackSlot = slot;
11221 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11223 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11224 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11225 data << uint8(msg);
11227 if(msg)
11229 data << uint64(pItem ? pItem->GetGUID() : 0);
11230 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11231 data << uint8(0); // not 0 there...
11233 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11235 uint32 level = 0;
11237 if(pItem)
11238 if(ItemPrototype const* proto = pItem->GetProto())
11239 level = proto->RequiredLevel;
11241 data << uint32(level); // new 2.4.0
11244 GetSession()->SendPacket(&data);
11247 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11249 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11250 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11251 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11252 data << uint32(item);
11253 if( param > 0 )
11254 data << uint32(param);
11255 data << uint8(msg);
11256 GetSession()->SendPacket(&data);
11259 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11261 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11262 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11263 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11264 data << uint64(guid);
11265 if( param > 0 )
11266 data << uint32(param);
11267 data << uint8(msg);
11268 GetSession()->SendPacket(&data);
11271 void Player::ClearTrade()
11273 tradeGold = 0;
11274 acceptTrade = false;
11275 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11276 tradeItems[i] = NULL_SLOT;
11279 void Player::TradeCancel(bool sendback)
11281 if(pTrader)
11283 // send yellow "Trade cancelled" message to both traders
11284 WorldSession* ws;
11285 ws = GetSession();
11286 if(sendback)
11287 ws->SendCancelTrade();
11288 ws = pTrader->GetSession();
11289 if(!ws->PlayerLogout())
11290 ws->SendCancelTrade();
11292 // cleanup
11293 ClearTrade();
11294 pTrader->ClearTrade();
11295 // prevent loss of reference
11296 pTrader->pTrader = NULL;
11297 pTrader = NULL;
11301 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11303 if(m_itemDuration.empty())
11304 return;
11306 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11308 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11310 Item* item = *itr;
11311 ++itr; // current element can be erased in UpdateDuration
11313 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11314 item->UpdateDuration(this,time);
11318 void Player::UpdateEnchantTime(uint32 time)
11320 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11322 assert(itr->item);
11323 next=itr;
11324 if(!itr->item->GetEnchantmentId(itr->slot))
11326 next = m_enchantDuration.erase(itr);
11328 else if(itr->leftduration <= time)
11330 ApplyEnchantment(itr->item,itr->slot,false,false);
11331 itr->item->ClearEnchantment(itr->slot);
11332 next = m_enchantDuration.erase(itr);
11334 else if(itr->leftduration > time)
11336 itr->leftduration -= time;
11337 ++next;
11342 void Player::AddEnchantmentDurations(Item *item)
11344 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11346 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11347 continue;
11349 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11350 if( duration > 0 )
11351 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11355 void Player::RemoveEnchantmentDurations(Item *item)
11357 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11359 if(itr->item == item)
11361 // save duration in item
11362 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11363 itr = m_enchantDuration.erase(itr);
11365 else
11366 ++itr;
11370 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11372 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11373 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11375 next = itr;
11376 if(itr->slot==slot)
11378 if(itr->item && itr->item->GetEnchantmentId(slot))
11380 // remove from stats
11381 ApplyEnchantment(itr->item,slot,false,false);
11382 // remove visual
11383 itr->item->ClearEnchantment(slot);
11385 // remove from update list
11386 next = m_enchantDuration.erase(itr);
11388 else
11389 ++next;
11392 // remove enchants from inventory items
11393 // NOTE: no need to remove these from stats, since these aren't equipped
11394 // in inventory
11395 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11397 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11398 if( pItem && pItem->GetEnchantmentId(slot) )
11399 pItem->ClearEnchantment(slot);
11402 // in inventory bags
11403 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11405 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11406 if( pBag )
11408 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11410 Item* pItem = pBag->GetItemByPos(j);
11411 if( pItem && pItem->GetEnchantmentId(slot) )
11412 pItem->ClearEnchantment(slot);
11418 // duration == 0 will remove item enchant
11419 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11421 if(!item)
11422 return;
11424 if(slot >= MAX_ENCHANTMENT_SLOT)
11425 return;
11427 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11429 if(itr->item == item && itr->slot == slot)
11431 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11432 m_enchantDuration.erase(itr);
11433 break;
11436 if(item && duration > 0 )
11438 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11439 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11443 void Player::ApplyEnchantment(Item *item,bool apply)
11445 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11446 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11449 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11451 if(!item)
11452 return;
11454 if(!item->IsEquipped())
11455 return;
11457 if(slot >= MAX_ENCHANTMENT_SLOT)
11458 return;
11460 uint32 enchant_id = item->GetEnchantmentId(slot);
11461 if(!enchant_id)
11462 return;
11464 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11465 if(!pEnchant)
11466 return;
11468 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11469 return;
11471 for (int s=0; s<3; s++)
11473 uint32 enchant_display_type = pEnchant->type[s];
11474 uint32 enchant_amount = pEnchant->amount[s];
11475 uint32 enchant_spell_id = pEnchant->spellid[s];
11477 switch(enchant_display_type)
11479 case ITEM_ENCHANTMENT_TYPE_NONE:
11480 break;
11481 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11482 // processed in Player::CastItemCombatSpell
11483 break;
11484 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11485 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11486 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11487 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11488 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11489 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11490 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11491 break;
11492 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11493 if(enchant_spell_id)
11495 if(apply)
11497 int32 basepoints = int32(enchant_amount);
11498 // Random Property Exist - try found basepoints for spell (basepoints depencs from item suffix factor)
11499 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11501 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11502 if (item_rand)
11504 // Search enchant_amount
11505 for (int k=0; k<3; k++)
11507 if(item_rand->enchant_id[k] == enchant_id)
11509 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11510 break;
11515 // Cast custom spell vs all equal basepoints getted from enchant_amount
11516 if (basepoints)
11517 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11518 else
11519 CastSpell(this,enchant_spell_id,true,item);
11521 else
11522 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11524 break;
11525 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11526 if (!enchant_amount)
11528 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11529 if(item_rand)
11531 for (int k=0; k<3; k++)
11533 if(item_rand->enchant_id[k] == enchant_id)
11535 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11536 break;
11542 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11543 break;
11544 case ITEM_ENCHANTMENT_TYPE_STAT:
11546 if (!enchant_amount)
11548 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11549 if(item_rand_suffix)
11551 for (int k=0; k<3; k++)
11553 if(item_rand_suffix->enchant_id[k] == enchant_id)
11555 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11556 break;
11562 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11563 switch (enchant_spell_id)
11565 case ITEM_MOD_AGILITY:
11566 sLog.outDebug("+ %u AGILITY",enchant_amount);
11567 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11568 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11569 break;
11570 case ITEM_MOD_STRENGTH:
11571 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11572 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11573 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11574 break;
11575 case ITEM_MOD_INTELLECT:
11576 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11577 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11578 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11579 break;
11580 case ITEM_MOD_SPIRIT:
11581 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11582 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11583 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11584 break;
11585 case ITEM_MOD_STAMINA:
11586 sLog.outDebug("+ %u STAMINA",enchant_amount);
11587 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11588 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11589 break;
11590 case ITEM_MOD_DEFENSE_SKILL_RATING:
11591 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11592 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11593 break;
11594 case ITEM_MOD_DODGE_RATING:
11595 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11596 sLog.outDebug("+ %u DODGE", enchant_amount);
11597 break;
11598 case ITEM_MOD_PARRY_RATING:
11599 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11600 sLog.outDebug("+ %u PARRY", enchant_amount);
11601 break;
11602 case ITEM_MOD_BLOCK_RATING:
11603 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11604 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11605 break;
11606 case ITEM_MOD_HIT_MELEE_RATING:
11607 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11608 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11609 break;
11610 case ITEM_MOD_HIT_RANGED_RATING:
11611 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11612 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11613 break;
11614 case ITEM_MOD_HIT_SPELL_RATING:
11615 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11616 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11617 break;
11618 case ITEM_MOD_CRIT_MELEE_RATING:
11619 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11620 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11621 break;
11622 case ITEM_MOD_CRIT_RANGED_RATING:
11623 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11624 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11625 break;
11626 case ITEM_MOD_CRIT_SPELL_RATING:
11627 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11628 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11629 break;
11630 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11631 // in Enchantments
11632 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11633 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11634 // break;
11635 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11636 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11637 // break;
11638 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11639 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11640 // break;
11641 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11642 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11643 // break;
11644 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11645 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11646 // break;
11647 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11648 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11649 // break;
11650 // case ITEM_MOD_HASTE_MELEE_RATING:
11651 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11652 // break;
11653 // case ITEM_MOD_HASTE_RANGED_RATING:
11654 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11655 // break;
11656 case ITEM_MOD_HASTE_SPELL_RATING:
11657 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11658 break;
11659 case ITEM_MOD_HIT_RATING:
11660 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11661 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11662 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11663 sLog.outDebug("+ %u HIT", enchant_amount);
11664 break;
11665 case ITEM_MOD_CRIT_RATING:
11666 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11667 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11668 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11669 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11670 break;
11671 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11672 // case ITEM_MOD_HIT_TAKEN_RATING:
11673 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11674 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11675 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11676 // break;
11677 // case ITEM_MOD_CRIT_TAKEN_RATING:
11678 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11679 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11680 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11681 // break;
11682 case ITEM_MOD_RESILIENCE_RATING:
11683 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11684 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11685 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11686 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11687 break;
11688 case ITEM_MOD_HASTE_RATING:
11689 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11690 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11691 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11692 sLog.outDebug("+ %u HASTE", enchant_amount);
11693 break;
11694 case ITEM_MOD_EXPERTISE_RATING:
11695 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11696 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11697 break;
11698 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11699 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11700 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11701 break;
11702 default:
11703 break;
11705 break;
11707 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11709 if(getClass() == CLASS_SHAMAN)
11711 float addValue = 0.0f;
11712 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11714 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11715 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11717 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11719 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11720 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11723 break;
11725 default:
11726 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11727 break;
11728 } /*switch(enchant_display_type)*/
11729 } /*for*/
11731 // visualize enchantment at player and equipped items
11732 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11734 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11735 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11738 if(apply_dur)
11740 if(apply)
11742 // set duration
11743 uint32 duration = item->GetEnchantmentDuration(slot);
11744 if(duration > 0)
11745 AddEnchantmentDuration(item,slot,duration);
11747 else
11749 // duration == 0 will remove EnchantDuration
11750 AddEnchantmentDuration(item,slot,0);
11755 void Player::SendEnchantmentDurations()
11757 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11759 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11763 void Player::SendItemDurations()
11765 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11767 (*itr)->SendTimeUpdate(this);
11771 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11773 if(!item) // prevent crash
11774 return;
11776 // last check 2.0.10
11777 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11778 data << GetGUID(); // player GUID
11779 data << uint32(received); // 0=looted, 1=from npc
11780 data << uint32(created); // 0=received, 1=created
11781 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11782 data << (uint8)item->GetBagSlot(); // bagslot
11783 // item slot, but when added to stack: 0xFFFFFFFF
11784 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11785 data << uint32(item->GetEntry()); // item id
11786 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11787 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11788 data << uint32(count); // count of items
11789 data << GetItemCount(item->GetEntry()); // count of items in inventory
11791 if (broadcast && GetGroup())
11792 GetGroup()->BroadcastPacket(&data);
11793 else
11794 GetSession()->SendPacket(&data);
11797 /*********************************************************/
11798 /*** QUEST SYSTEM ***/
11799 /*********************************************************/
11801 void Player::PrepareQuestMenu( uint64 guid )
11803 Object *pObject;
11804 QuestRelations* pObjectQR;
11805 QuestRelations* pObjectQIR;
11806 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11807 if( pCreature )
11809 pObject = (Object*)pCreature;
11810 pObjectQR = &objmgr.mCreatureQuestRelations;
11811 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11813 else
11815 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11816 if( pGameObject )
11818 pObject = (Object*)pGameObject;
11819 pObjectQR = &objmgr.mGOQuestRelations;
11820 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11822 else
11823 return;
11826 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11827 qm.ClearMenu();
11829 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11831 uint32 quest_id = i->second;
11832 QuestStatus status = GetQuestStatus( quest_id );
11833 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11834 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11835 else if ( status == QUEST_STATUS_INCOMPLETE )
11836 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11837 else if (status == QUEST_STATUS_AVAILABLE )
11838 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11841 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11843 uint32 quest_id = i->second;
11844 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11845 if(!pQuest) continue;
11847 QuestStatus status = GetQuestStatus( quest_id );
11849 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11850 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11851 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11852 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11856 void Player::SendPreparedQuest( uint64 guid )
11858 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11859 if( questMenu.Empty() )
11860 return;
11862 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11864 uint32 status = qmi0.m_qIcon;
11866 // single element case
11867 if ( questMenu.MenuItemCount() == 1 )
11869 // Auto open -- maybe also should verify there is no greeting
11870 uint32 quest_id = qmi0.m_qId;
11871 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11872 if ( pQuest )
11874 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11875 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11876 else if( status == DIALOG_STATUS_INCOMPLETE )
11877 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11878 // Send completable on repeatable quest if player don't have quest
11879 else if( pQuest->IsRepeatable() )
11880 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11881 else
11882 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11885 // multiply entries
11886 else
11888 QEmote qe;
11889 qe._Delay = 0;
11890 qe._Emote = 0;
11891 std::string title = "";
11892 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11893 if( pCreature )
11895 uint32 textid = pCreature->GetNpcTextId();
11896 GossipText * gossiptext = objmgr.GetGossipText(textid);
11897 if( !gossiptext )
11899 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11900 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11901 title = "";
11903 else
11905 qe = gossiptext->Options[0].Emotes[0];
11907 if(!gossiptext->Options[0].Text_0.empty())
11909 title = gossiptext->Options[0].Text_0;
11911 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11912 if (loc_idx >= 0)
11914 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11915 if (nl)
11917 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11918 title = nl->Text_0[0][loc_idx];
11922 else
11924 title = gossiptext->Options[0].Text_1;
11926 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11927 if (loc_idx >= 0)
11929 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11930 if (nl)
11932 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11933 title = nl->Text_1[0][loc_idx];
11939 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11943 bool Player::IsActiveQuest( uint32 quest_id ) const
11945 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11947 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11950 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11952 Object *pObject;
11953 QuestRelations* pObjectQR;
11954 QuestRelations* pObjectQIR;
11956 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11957 if( pCreature )
11959 pObject = (Object*)pCreature;
11960 pObjectQR = &objmgr.mCreatureQuestRelations;
11961 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11963 else
11965 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11966 if( pGameObject )
11968 pObject = (Object*)pGameObject;
11969 pObjectQR = &objmgr.mGOQuestRelations;
11970 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11972 else
11973 return NULL;
11976 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11977 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11979 if (itr->second == nextQuestID)
11980 return objmgr.GetQuestTemplate(nextQuestID);
11983 return NULL;
11986 bool Player::CanSeeStartQuest( Quest const *pQuest )
11988 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11989 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11990 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11991 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11993 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11996 return false;
11999 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12001 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12002 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12003 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12004 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12005 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12006 && SatisfyQuestDay( pQuest, msg );
12009 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12011 if( !SatisfyQuestLog( msg ) )
12012 return false;
12014 uint32 srcitem = pQuest->GetSrcItemId();
12015 if( srcitem > 0 )
12017 uint32 count = pQuest->GetSrcItemCount();
12018 ItemPosCountVec dest;
12019 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12021 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12022 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12023 return true;
12024 else if( msg != EQUIP_ERR_OK )
12026 SendEquipError( msg, NULL, NULL );
12027 return false;
12030 return true;
12033 bool Player::CanCompleteQuest( uint32 quest_id )
12035 if( quest_id )
12037 QuestStatusData& q_status = mQuestStatus[quest_id];
12038 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12039 return false; // not allow re-complete quest
12041 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12043 if(!qInfo)
12044 return false;
12046 // auto complete quest
12047 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12048 return true;
12050 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12053 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12055 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12057 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12058 return false;
12062 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12064 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12066 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12067 continue;
12069 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12070 return false;
12074 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12075 return false;
12077 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12078 return false;
12080 if ( qInfo->GetRewOrReqMoney() < 0 )
12082 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12083 return false;
12086 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12087 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12088 return false;
12090 return true;
12093 return false;
12096 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12098 // Solve problem that player don't have the quest and try complete it.
12099 // if repeatable she must be able to complete event if player don't have it.
12100 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12101 if( !CanTakeQuest(pQuest, false) )
12102 return false;
12104 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12105 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12106 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12107 return false;
12109 if( !CanRewardQuest(pQuest, false) )
12110 return false;
12112 return true;
12115 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12117 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12118 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12119 return false;
12121 // daily quest can't be rewarded (10 daily quest already completed)
12122 if(!SatisfyQuestDay(pQuest,true))
12123 return false;
12125 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12126 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12127 return false;
12129 // prevent receive reward with quest items in bank
12130 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12132 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12134 if( pQuest->ReqItemCount[i]!= 0 &&
12135 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12137 if(msg)
12138 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12139 return false;
12144 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12145 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12146 return false;
12148 return true;
12151 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12153 // prevent receive reward with quest items in bank or for not completed quest
12154 if(!CanRewardQuest(pQuest,msg))
12155 return false;
12157 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12159 if( pQuest->RewChoiceItemId[reward] )
12161 ItemPosCountVec dest;
12162 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12163 if( res != EQUIP_ERR_OK )
12165 SendEquipError( res, NULL, NULL );
12166 return false;
12171 if ( pQuest->GetRewItemsCount() > 0 )
12173 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12175 if( pQuest->RewItemId[i] )
12177 ItemPosCountVec dest;
12178 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12179 if( res != EQUIP_ERR_OK )
12181 SendEquipError( res, NULL, NULL );
12182 return false;
12188 return true;
12191 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12193 uint16 log_slot = FindQuestSlot( 0 );
12194 assert(log_slot < MAX_QUEST_LOG_SIZE);
12196 uint32 quest_id = pQuest->GetQuestId();
12198 // if not exist then created with set uState==NEW and rewarded=false
12199 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12200 if (questStatusData.uState != QUEST_NEW)
12201 questStatusData.uState = QUEST_CHANGED;
12203 // check for repeatable quests status reset
12204 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12205 questStatusData.m_explored = false;
12207 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12209 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12210 questStatusData.m_itemcount[i] = 0;
12213 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12215 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12216 questStatusData.m_creatureOrGOcount[i] = 0;
12219 GiveQuestSourceItem( pQuest );
12220 AdjustQuestReqItemCount( pQuest );
12222 if( pQuest->GetRepObjectiveFaction() )
12223 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12225 uint32 qtime = 0;
12226 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12228 uint32 limittime = pQuest->GetLimitTime();
12230 // shared timed quest
12231 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12232 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12234 AddTimedQuest( quest_id );
12235 questStatusData.m_timer = limittime * 1000;
12236 qtime = static_cast<uint32>(time(NULL)) + limittime;
12238 else
12239 questStatusData.m_timer = 0;
12241 SetQuestSlot(log_slot, quest_id, qtime);
12243 //starting initial quest script
12244 if(questGiver && pQuest->GetQuestStartScript()!=0)
12245 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12247 UpdateForQuestsGO();
12250 void Player::CompleteQuest( uint32 quest_id )
12252 if( quest_id )
12254 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12256 uint16 log_slot = FindQuestSlot( quest_id );
12257 if( log_slot < MAX_QUEST_LOG_SIZE)
12258 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12260 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12262 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12263 RewardQuest(qInfo,0,this,false);
12264 else
12265 SendQuestComplete( quest_id );
12270 void Player::IncompleteQuest( uint32 quest_id )
12272 if( quest_id )
12274 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12276 uint16 log_slot = FindQuestSlot( quest_id );
12277 if( log_slot < MAX_QUEST_LOG_SIZE)
12278 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12282 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12284 uint32 quest_id = pQuest->GetQuestId();
12286 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12288 if ( pQuest->ReqItemId[i] )
12289 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12292 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12293 // SetTimedQuest( 0 );
12294 m_timedquests.erase(pQuest->GetQuestId());
12296 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12298 if( pQuest->RewChoiceItemId[reward] )
12300 ItemPosCountVec dest;
12301 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12303 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12304 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12309 if ( pQuest->GetRewItemsCount() > 0 )
12311 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12313 if( pQuest->RewItemId[i] )
12315 ItemPosCountVec dest;
12316 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12318 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12319 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12325 RewardReputation( pQuest );
12327 if( pQuest->GetRewSpellCast() > 0 )
12328 CastSpell( this, pQuest->GetRewSpellCast(), true);
12329 else if( pQuest->GetRewSpell() > 0)
12330 CastSpell( this, pQuest->GetRewSpell(), true);
12332 uint16 log_slot = FindQuestSlot( quest_id );
12333 if( log_slot < MAX_QUEST_LOG_SIZE)
12334 SetQuestSlot(log_slot,0);
12336 QuestStatusData& q_status = mQuestStatus[quest_id];
12338 // Not give XP in case already completed once repeatable quest
12339 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12341 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12342 GiveXP( XP , NULL );
12343 else
12344 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12346 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12347 ModifyMoney( pQuest->GetRewOrReqMoney() );
12349 // honor reward
12350 if(pQuest->GetRewHonorableKills())
12351 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12353 // title reward
12354 if(pQuest->GetCharTitleId())
12356 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12357 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12360 // Send reward mail
12361 if(pQuest->GetRewMailTemplateId())
12363 MailMessageType mailType;
12364 uint32 senderGuidOrEntry;
12365 switch(questGiver->GetTypeId())
12367 case TYPEID_UNIT:
12368 mailType = MAIL_CREATURE;
12369 senderGuidOrEntry = questGiver->GetEntry();
12370 break;
12371 case TYPEID_GAMEOBJECT:
12372 mailType = MAIL_GAMEOBJECT;
12373 senderGuidOrEntry = questGiver->GetEntry();
12374 break;
12375 case TYPEID_ITEM:
12376 mailType = MAIL_ITEM;
12377 senderGuidOrEntry = questGiver->GetEntry();
12378 break;
12379 case TYPEID_PLAYER:
12380 mailType = MAIL_NORMAL;
12381 senderGuidOrEntry = questGiver->GetGUIDLow();
12382 break;
12383 default:
12384 mailType = MAIL_NORMAL;
12385 senderGuidOrEntry = GetGUIDLow();
12386 break;
12389 Loot questMailLoot;
12391 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12393 // fill mail
12394 MailItemsInfo mi; // item list preparing
12396 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12398 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12400 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12402 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12403 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12408 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12410 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12412 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12414 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12415 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12420 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12423 if(pQuest->IsDaily())
12425 SetDailyQuestStatus(quest_id);
12426 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12429 if ( !pQuest->IsRepeatable() )
12430 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12431 else
12432 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12434 q_status.m_rewarded = true;
12436 if(announce)
12437 SendQuestReward( pQuest, XP, questGiver );
12439 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12440 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12441 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12444 void Player::FailQuest( uint32 quest_id )
12446 if( quest_id )
12448 IncompleteQuest( quest_id );
12450 uint16 log_slot = FindQuestSlot( quest_id );
12451 if( log_slot < MAX_QUEST_LOG_SIZE)
12453 SetQuestSlotTimer(log_slot, 1 );
12454 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12456 SendQuestFailed( quest_id );
12460 void Player::FailTimedQuest( uint32 quest_id )
12462 if( quest_id )
12464 QuestStatusData& q_status = mQuestStatus[quest_id];
12466 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12467 q_status.m_timer = 0;
12469 IncompleteQuest( quest_id );
12471 uint16 log_slot = FindQuestSlot( quest_id );
12472 if( log_slot < MAX_QUEST_LOG_SIZE)
12474 SetQuestSlotTimer(log_slot, 1 );
12475 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12477 SendQuestTimerFailed( quest_id );
12481 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12483 int32 zoneOrSort = qInfo->GetZoneOrSort();
12484 int32 skillOrClass = qInfo->GetSkillOrClass();
12486 // skip zone zoneOrSort and 0 case skillOrClass
12487 if( zoneOrSort >= 0 && skillOrClass == 0 )
12488 return true;
12490 int32 questSort = -zoneOrSort;
12491 uint8 reqSortClass = ClassByQuestSort(questSort);
12493 // check class sort cases in zoneOrSort
12494 if( reqSortClass != 0 && getClass() != reqSortClass)
12496 if( msg )
12497 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12498 return false;
12501 // check class
12502 if( skillOrClass < 0 )
12504 uint8 reqClass = -int32(skillOrClass);
12505 if(getClass() != reqClass)
12507 if( msg )
12508 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12509 return false;
12512 // check skill
12513 else if( skillOrClass > 0 )
12515 uint32 reqSkill = skillOrClass;
12516 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12518 if( msg )
12519 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12520 return false;
12524 return true;
12527 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12529 if( getLevel() < qInfo->GetMinLevel() )
12531 if( msg )
12532 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12533 return false;
12535 return true;
12538 bool Player::SatisfyQuestLog( bool msg )
12540 // exist free slot
12541 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12542 return true;
12544 if( msg )
12546 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12547 GetSession()->SendPacket( &data );
12548 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12550 return false;
12553 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12555 // No previous quest (might be first quest in a series)
12556 if( qInfo->prevQuests.empty())
12557 return true;
12559 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12561 uint32 prevId = abs(*iter);
12563 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12564 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12566 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12568 // If any of the positive previous quests completed, return true
12569 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12571 // skip one-from-all exclusive group
12572 if(qPrevInfo->GetExclusiveGroup() >= 0)
12573 return true;
12575 // each-from-all exclusive group ( < 0)
12576 // can be start if only all quests in prev quest exclusive group complited and rewarded
12577 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12578 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12580 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12582 for(; iter != end; ++iter)
12584 uint32 exclude_Id = iter->second;
12586 // skip checked quest id, only state of other quests in group is interesting
12587 if(exclude_Id == prevId)
12588 continue;
12590 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12592 // alternative quest from group also must be completed and rewarded(reported)
12593 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12595 if( msg )
12596 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12597 return false;
12600 return true;
12602 // If any of the negative previous quests active, return true
12603 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12604 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12606 // skip one-from-all exclusive group
12607 if(qPrevInfo->GetExclusiveGroup() >= 0)
12608 return true;
12610 // each-from-all exclusive group ( < 0)
12611 // can be start if only all quests in prev quest exclusive group active
12612 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12613 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12615 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12617 for(; iter != end; ++iter)
12619 uint32 exclude_Id = iter->second;
12621 // skip checked quest id, only state of other quests in group is interesting
12622 if(exclude_Id == prevId)
12623 continue;
12625 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12627 // alternative quest from group also must be active
12628 if( i_exstatus == mQuestStatus.end() ||
12629 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12630 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12632 if( msg )
12633 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12634 return false;
12637 return true;
12642 // Has only positive prev. quests in non-rewarded state
12643 // and negative prev. quests in non-active state
12644 if( msg )
12645 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12647 return false;
12650 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12652 uint32 reqraces = qInfo->GetRequiredRaces();
12653 if ( reqraces == 0 )
12654 return true;
12655 if( (reqraces & getRaceMask()) == 0 )
12657 if( msg )
12658 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12659 return false;
12661 return true;
12664 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12666 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12667 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12669 if( msg )
12670 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12671 return false;
12674 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12675 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12677 if( msg )
12678 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12679 return false;
12682 return true;
12685 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12687 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12688 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12690 if( msg )
12691 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12692 return false;
12694 return true;
12697 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12699 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12701 if( msg )
12702 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12703 return false;
12705 return true;
12708 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12710 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12711 if(qInfo->GetExclusiveGroup() <= 0)
12712 return true;
12714 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12715 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12717 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12719 for(; iter != end; ++iter)
12721 uint32 exclude_Id = iter->second;
12723 // skip checked quest id, only state of other quests in group is interesting
12724 if(exclude_Id == qInfo->GetQuestId())
12725 continue;
12727 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12729 // alternative quest already started or completed
12730 if( i_exstatus != mQuestStatus.end()
12731 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12733 if( msg )
12734 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12735 return false;
12738 return true;
12741 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12743 if(!qInfo->GetNextQuestInChain())
12744 return true;
12746 // next quest in chain already started or completed
12747 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12748 if( itr != mQuestStatus.end()
12749 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12751 if( msg )
12752 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12753 return false;
12756 // check for all quests further up the chain
12757 // only necessary if there are quest chains with more than one quest that can be skipped
12758 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12759 return true;
12762 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12764 // No previous quest in chain
12765 if( qInfo->prevChainQuests.empty())
12766 return true;
12768 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12770 uint32 prevId = *iter;
12772 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12774 if( i_prevstatus != mQuestStatus.end() )
12776 // If any of the previous quests in chain active, return false
12777 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12778 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12780 if( msg )
12781 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12782 return false;
12786 // check for all quests further down the chain
12787 // only necessary if there are quest chains with more than one quest that can be skipped
12788 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12789 // return false;
12792 // No previous quest in chain active
12793 return true;
12796 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12798 if(!qInfo->IsDaily())
12799 return true;
12801 bool have_slot = false;
12802 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12804 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12805 if(qInfo->GetQuestId()==id)
12806 return false;
12808 if(!id)
12809 have_slot = true;
12812 if(!have_slot)
12814 if( msg )
12815 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12816 return false;
12819 return true;
12822 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12824 uint32 srcitem = pQuest->GetSrcItemId();
12825 if( srcitem > 0 )
12827 uint32 count = pQuest->GetSrcItemCount();
12828 if( count <= 0 )
12829 count = 1;
12831 ItemPosCountVec dest;
12832 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12833 if( msg == EQUIP_ERR_OK )
12835 Item * item = StoreNewItem(dest, srcitem, true);
12836 SendNewItem(item, count, true, false);
12837 return true;
12839 // player already have max amount required item, just report success
12840 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12841 return true;
12842 else
12843 SendEquipError( msg, NULL, NULL );
12844 return false;
12847 return true;
12850 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12852 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12853 if( qInfo )
12855 uint32 srcitem = qInfo->GetSrcItemId();
12856 if( srcitem > 0 )
12858 uint32 count = qInfo->GetSrcItemCount();
12859 if( count <= 0 )
12860 count = 1;
12862 // exist one case when destroy source quest item not possible:
12863 // non un-equippable item (equipped non-empty bag, for example)
12864 uint8 res = CanUnequipItems(srcitem,count);
12865 if(res != EQUIP_ERR_OK)
12867 if(msg)
12868 SendEquipError( res, NULL, NULL );
12869 return false;
12872 DestroyItemCount(srcitem, count, true, true);
12875 return true;
12878 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12880 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12881 if( qInfo )
12883 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12884 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12885 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12886 && !qInfo->IsRepeatable() )
12887 return itr->second.m_rewarded;
12889 return false;
12891 return false;
12894 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12896 if( quest_id )
12898 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12899 if( itr != mQuestStatus.end() )
12900 return itr->second.m_status;
12902 return QUEST_STATUS_NONE;
12905 bool Player::CanShareQuest(uint32 quest_id) const
12907 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12908 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12910 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12911 if( itr != mQuestStatus.end() )
12912 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12914 return false;
12917 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12919 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12920 if( qInfo )
12922 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12924 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12925 m_timedquests.erase(qInfo->GetQuestId());
12928 QuestStatusData& q_status = mQuestStatus[quest_id];
12930 q_status.m_status = status;
12931 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12934 UpdateForQuestsGO();
12937 // not used in MaNGOS, but used in scripting code
12938 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12940 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12941 if( !qInfo )
12942 return 0;
12944 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12945 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12946 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12948 return 0;
12951 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12953 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12955 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12957 uint32 reqitemcount = pQuest->ReqItemCount[i];
12958 if( reqitemcount != 0 )
12960 uint32 quest_id = pQuest->GetQuestId();
12961 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12963 QuestStatusData& q_status = mQuestStatus[quest_id];
12964 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12965 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12971 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12973 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12974 if ( GetQuestSlotQuestId(i) == quest_id )
12975 return i;
12977 return MAX_QUEST_LOG_SIZE;
12980 void Player::AreaExploredOrEventHappens( uint32 questId )
12982 if( questId )
12984 uint16 log_slot = FindQuestSlot( questId );
12985 if( log_slot < MAX_QUEST_LOG_SIZE)
12987 QuestStatusData& q_status = mQuestStatus[questId];
12989 if(!q_status.m_explored)
12991 q_status.m_explored = true;
12992 if (q_status.uState != QUEST_NEW)
12993 q_status.uState = QUEST_CHANGED;
12996 if( CanCompleteQuest( questId ) )
12997 CompleteQuest( questId );
13001 //not used in mangosd, function for external script library
13002 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13004 if( Group *pGroup = GetGroup() )
13006 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13008 Player *pGroupGuy = itr->getSource();
13010 // for any leave or dead (with not released body) group member at appropriate distance
13011 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13012 pGroupGuy->AreaExploredOrEventHappens(questId);
13015 else
13016 AreaExploredOrEventHappens(questId);
13019 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13021 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13023 uint32 questid = GetQuestSlotQuestId(i);
13024 if ( questid == 0 )
13025 continue;
13027 QuestStatusData& q_status = mQuestStatus[questid];
13029 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13030 continue;
13032 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13033 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13034 continue;
13036 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13038 uint32 reqitem = qInfo->ReqItemId[j];
13039 if ( reqitem == entry )
13041 uint32 reqitemcount = qInfo->ReqItemCount[j];
13042 uint32 curitemcount = q_status.m_itemcount[j];
13043 if ( curitemcount < reqitemcount )
13045 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13046 q_status.m_itemcount[j] += additemcount;
13047 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13049 SendQuestUpdateAddItem( qInfo, j, additemcount );
13051 if ( CanCompleteQuest( questid ) )
13052 CompleteQuest( questid );
13053 return;
13057 UpdateForQuestsGO();
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 becaue 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 prepering
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 flase 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)
16007 uint8 addlist = 0;
16009 sLog.outDebug("Pet Spells Groups");
16011 CreatureInfo const *cinfo = pet->GetCreatureInfo();
16013 if(pet->isControlled() && (pet->getPetType() == HUNTER_PET || cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK))
16015 for(PetSpellMap::iterator itr = pet->m_spells.begin();itr != pet->m_spells.end();itr++)
16017 if(itr->second->state == PETSPELL_REMOVED)
16018 continue;
16019 ++addlist;
16023 // first line + actionbar + spellcount + spells + last adds
16024 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);
16026 CharmInfo *charmInfo = pet->GetCharmInfo();
16028 //16
16029 data << uint64(pet->GetGUID());
16030 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16031 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16032 data << uint32(0);
16034 for(uint32 i = 0; i < 10; i++) //40
16036 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16039 data << uint8(addlist); //1
16041 if(addlist && pet->isControlled())
16043 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16045 if(itr->second->state == PETSPELL_REMOVED)
16046 continue;
16048 data << uint16(itr->first);
16049 data << uint16(itr->second->active); // pet spell active state isn't boolean
16053 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
16054 uint8 count = 3; //1+8+8+8=25
16056 // if count = 0, then end of packet...
16057 data << count;
16058 // uint32 value is spell id...
16059 // uint64 value is constant 0, unknown...
16060 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
16061 //data << uint32(0x5fd1) << uint64(0); // if count = 2
16062 data << uint32(0x8e8c) << uint64(0); // if count = 3
16063 data << uint32(0x8e8b) << uint64(0); // if count = 3
16065 GetSession()->SendPacket(&data);
16069 void Player::PossessSpellInitialize()
16071 Unit* charm = GetCharm();
16073 if(!charm)
16074 return;
16076 CharmInfo *charmInfo = charm->GetCharmInfo();
16078 if(!charmInfo)
16080 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16081 return;
16084 uint8 addlist = 0;
16085 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16087 //16
16088 data << uint64(charm->GetGUID());
16089 data << uint32(0x00000000);
16090 data << uint8(0) << uint8(0) << uint16(0);
16091 data << uint32(0);
16093 for(uint32 i = 0; i < 10; i++) //40
16095 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16098 data << uint8(addlist); //1
16100 uint8 count = 3;
16101 data << count;
16102 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
16103 data << uint32(0x8e8c) << uint64(0); // if count = 3
16104 data << uint32(0x8e8b) << uint64(0); // if count = 3
16106 GetSession()->SendPacket(&data);
16109 void Player::CharmSpellInitialize()
16111 Unit* charm = GetCharm();
16113 if(!charm)
16114 return;
16116 CharmInfo *charmInfo = charm->GetCharmInfo();
16117 if(!charmInfo)
16119 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16120 return;
16123 uint8 addlist = 0;
16125 if(charm->GetTypeId() != TYPEID_PLAYER)
16127 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16129 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16131 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16133 if(charmInfo->GetCharmSpell(i)->spellId)
16134 ++addlist;
16139 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16141 data << (uint64)charm->GetGUID() << uint32(0x00000000);
16143 if(charm->GetTypeId() != TYPEID_PLAYER)
16144 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16145 else
16146 data << uint8(0) << uint8(0);
16148 data << uint16(0);
16149 data << uint32(0);
16151 for(uint32 i = 0; i < 10; i++) //40
16153 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16156 data << uint8(addlist); //1
16158 if(addlist)
16160 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16162 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16163 if(cspell->spellId)
16165 data << uint16(cspell->spellId);
16166 data << uint16(cspell->active);
16171 uint8 count = 3;
16172 data << count;
16173 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
16174 data << uint32(0x8e8c) << uint64(0); // if count = 3
16175 data << uint32(0x8e8b) << uint64(0); // if count = 3
16177 GetSession()->SendPacket(&data);
16180 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
16182 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16183 if (!spellInfo) return 0;
16184 int32 total = 0;
16185 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16187 SpellModifier *mod = *itr;
16189 if(!IsAffectedBySpellmod(spellInfo,mod))
16190 continue;
16192 if (mod->type == SPELLMOD_FLAT)
16193 total += mod->value;
16195 return total;
16198 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
16200 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16201 if (!spellInfo) return 0;
16202 int32 total = 0;
16203 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16205 SpellModifier *mod = *itr;
16207 if(!IsAffectedBySpellmod(spellInfo,mod))
16208 continue;
16210 if (mod->type == SPELLMOD_PCT)
16211 total += mod->value;
16213 return total;
16216 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16218 if (!mod || !spellInfo)
16219 return false;
16221 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16223 // prevent apply to any spell except spell that trigger expire
16224 if(spell)
16226 if(mod->lastAffected != spell)
16227 return false;
16229 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16230 return false;
16233 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
16236 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16238 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16240 for(int eff=0;eff<64;++eff)
16242 uint64 _mask = uint64(1) << eff;
16243 if ( mod->mask & _mask)
16245 int32 val = 0;
16246 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16248 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
16249 val += (*itr)->value;
16251 val += apply ? mod->value : -(mod->value);
16252 WorldPacket data(Opcode, (1+1+4));
16253 data << uint8(eff);
16254 data << uint8(mod->op);
16255 data << int32(val);
16256 SendDirectMessage(&data);
16260 if (apply)
16261 m_spellMods[mod->op].push_back(mod);
16262 else
16264 if (mod->charges == -1)
16265 --m_SpellModRemoveCount;
16266 m_spellMods[mod->op].remove(mod);
16267 delete mod;
16271 void Player::RemoveSpellMods(Spell const* spell)
16273 if(!spell || (m_SpellModRemoveCount == 0))
16274 return;
16276 for(int i=0;i<MAX_SPELLMOD;++i)
16278 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16280 SpellModifier *mod = *itr;
16281 ++itr;
16283 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16285 RemoveAurasDueToSpell(mod->spellId);
16286 if (m_spellMods[i].empty())
16287 break;
16288 else
16289 itr = m_spellMods[i].begin();
16295 // send Proficiency
16296 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16298 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16299 data << pr1 << pr2;
16300 GetSession()->SendPacket (&data);
16303 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16305 QueryResult *result = NULL;
16306 if(type==10)
16307 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16308 else
16309 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16310 if(result)
16312 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.
16313 { // and SendPetitionQueryOpcode reads data from the DB
16314 Field *fields = result->Fetch();
16315 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16316 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16318 // send update if charter owner in game
16319 Player* owner = objmgr.GetPlayer(ownerguid);
16320 if(owner)
16321 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16323 } while ( result->NextRow() );
16325 delete result;
16327 if(type==10)
16328 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16329 else
16330 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16333 CharacterDatabase.BeginTransaction();
16334 if(type == 10)
16336 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16337 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16339 else
16341 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16342 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16344 CharacterDatabase.CommitTransaction();
16347 void Player::SetRestBonus (float rest_bonus_new)
16349 // Prevent resting on max level
16350 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16351 rest_bonus_new = 0;
16353 if(rest_bonus_new < 0)
16354 rest_bonus_new = 0;
16356 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16358 if(rest_bonus_new > rest_bonus_max)
16359 m_rest_bonus = rest_bonus_max;
16360 else
16361 m_rest_bonus = rest_bonus_new;
16363 // update data for client
16364 if(m_rest_bonus>10)
16365 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16366 else if(m_rest_bonus<=1)
16367 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16369 //RestTickUpdate
16370 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16373 void Player::HandleStealthedUnitsDetection()
16375 std::list<Unit*> stealthedUnits;
16377 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16378 Cell cell(p);
16379 cell.data.Part.reserved = ALL_DISTRICT;
16380 cell.SetNoCreate();
16382 MaNGOS::AnyStealthedCheck u_check;
16383 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16385 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16386 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16388 CellLock<GridReadGuard> cell_lock(cell, p);
16389 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16390 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16392 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16394 if((*i)==this)
16396 i = stealthedUnits.erase(i);
16397 continue;
16400 if ((*i)->isVisibleForOrDetect(this,true))
16403 (*i)->SendUpdateToPlayer(this);
16404 m_clientGUIDs.insert((*i)->GetGUID());
16406 #ifdef MANGOS_DEBUG
16407 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16408 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16409 #endif
16411 // target aura duration for caster show only if target exist at caster client
16412 // send data at target visibility change (adding to client)
16413 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16414 SendAurasForTarget(*i);
16416 i = stealthedUnits.erase(i);
16417 continue;
16420 ++i;
16424 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16426 if(nodes.size() < 2)
16427 return false;
16429 // not let cheating with start flight mounted
16430 if(IsMounted())
16432 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16433 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16434 GetSession()->SendPacket(&data);
16435 return false;
16438 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16440 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16441 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16442 GetSession()->SendPacket(&data);
16443 return false;
16446 // 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
16447 if(GetSession()->isLogingOut() ||
16448 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16449 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16450 IsNonMeleeSpellCasted(false) ||
16451 isInCombat())
16453 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16454 data << uint32(ERR_TAXIPLAYERBUSY);
16455 GetSession()->SendPacket(&data);
16456 return false;
16459 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16460 return false;
16462 uint32 sourcenode = nodes[0];
16464 // starting node too far away (cheat?)
16465 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16466 if( !node || node->map_id != GetMapId() ||
16467 (node->x - GetPositionX())*(node->x - GetPositionX())+
16468 (node->y - GetPositionY())*(node->y - GetPositionY())+
16469 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16470 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16472 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16473 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16474 GetSession()->SendPacket(&data);
16475 return false;
16478 // Prepare to flight start now
16480 // stop combat at start taxi flight if any
16481 CombatStop();
16483 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16484 TradeCancel(true);
16486 // clean not finished taxi path if any
16487 m_taxi.ClearTaxiDestinations();
16489 // 0 element current node
16490 m_taxi.AddTaxiDestination(sourcenode);
16492 // fill destinations path tail
16493 uint32 sourcepath = 0;
16494 uint32 totalcost = 0;
16496 uint32 prevnode = sourcenode;
16497 uint32 lastnode = 0;
16499 for(uint32 i = 1; i < nodes.size(); ++i)
16501 uint32 path, cost;
16503 lastnode = nodes[i];
16504 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16506 if(!path)
16508 m_taxi.ClearTaxiDestinations();
16509 return false;
16512 totalcost += cost;
16514 if(prevnode == sourcenode)
16515 sourcepath = path;
16517 m_taxi.AddTaxiDestination(lastnode);
16519 prevnode = lastnode;
16522 if(!mount_id) // if not provide then attempt use default.
16523 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16525 if (mount_id == 0 || sourcepath == 0)
16527 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16528 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16529 GetSession()->SendPacket(&data);
16530 m_taxi.ClearTaxiDestinations();
16531 return false;
16534 uint32 money = GetMoney();
16536 if(npc)
16538 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16541 if(money < totalcost)
16543 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16544 data << uint32(ERR_TAXINOTENOUGHMONEY);
16545 GetSession()->SendPacket(&data);
16546 m_taxi.ClearTaxiDestinations();
16547 return false;
16550 //Checks and preparations done, DO FLIGHT
16551 ModifyMoney(-(int32)totalcost);
16553 // prevent stealth flight
16554 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16556 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16557 data << uint32(ERR_TAXIOK);
16558 GetSession()->SendPacket(&data);
16560 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16562 GetSession()->SendDoFlight(mount_id, sourcepath);
16564 return true;
16567 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16569 // last check 2.0.10
16570 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16571 data << GetGUID();
16572 data << uint8(0x0); // flags (0x1, 0x2)
16573 time_t curTime = time(NULL);
16574 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16576 if (itr->second->state == PLAYERSPELL_REMOVED)
16577 continue;
16578 uint32 unSpellId = itr->first;
16579 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16580 if (!spellInfo)
16582 ASSERT(spellInfo);
16583 continue;
16586 // Not send cooldown for this spells
16587 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16588 continue;
16590 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16592 data << unSpellId;
16593 data << unTimeMs; // in m.secs
16594 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16597 GetSession()->SendPacket(&data);
16600 void Player::InitDataForForm(bool reapplyMods)
16602 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16603 if(ssEntry && ssEntry->attackSpeed)
16605 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16606 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16607 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16609 else
16610 SetRegularAttackTime();
16612 switch(m_form)
16614 case FORM_CAT:
16616 if(getPowerType()!=POWER_ENERGY)
16617 setPowerType(POWER_ENERGY);
16618 break;
16620 case FORM_BEAR:
16621 case FORM_DIREBEAR:
16623 if(getPowerType()!=POWER_RAGE)
16624 setPowerType(POWER_RAGE);
16625 break;
16627 default: // 0, for example
16629 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16630 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16631 setPowerType(Powers(cEntry->powerType));
16632 break;
16636 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16637 if (!reapplyMods)
16638 UpdateEquipSpellsAtFormChange();
16640 UpdateAttackPowerAndDamage();
16641 UpdateAttackPowerAndDamage(true);
16644 // Return true is the bought item has a max count to force refresh of window by caller
16645 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16647 // cheating attempt
16648 if(count < 1) count = 1;
16650 if(!isAlive())
16651 return false;
16653 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16654 if( !pProto )
16656 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16657 return false;
16660 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16661 if (!pCreature)
16663 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16664 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16665 return false;
16668 VendorItemData const* vItems = pCreature->GetVendorItems();
16669 if(!vItems || vItems->Empty())
16671 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16672 return false;
16675 size_t vendor_slot = vItems->FindItemSlot(item);
16676 if(vendor_slot >= vItems->GetItemCount())
16678 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16679 return false;
16682 VendorItem const* crItem = vItems->m_items[vendor_slot];
16684 // check current item amount if it limited
16685 if( crItem->maxcount != 0 )
16687 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16689 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16690 return false;
16694 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16696 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16697 return false;
16700 if(crItem->ExtendedCost)
16702 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16703 if(!iece)
16705 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16706 return false;
16709 // honor points price
16710 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16712 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16713 return false;
16716 // arena points price
16717 if(GetArenaPoints() < (iece->reqarenapoints * count))
16719 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16720 return false;
16723 // item base price
16724 for (uint8 i = 0; i < 5; ++i)
16726 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16728 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16729 return false;
16733 // check for personal arena rating requirement
16734 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16736 // probably not the proper equip err
16737 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16738 return false;
16742 uint32 price = pProto->BuyPrice * count;
16744 // reputation discount
16745 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16747 if( GetMoney() < price )
16749 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16750 return false;
16753 uint8 bag = 0; // init for case invalid bagGUID
16755 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16757 Bag *pBag;
16758 if( bagguid == GetGUID() )
16760 bag = INVENTORY_SLOT_BAG_0;
16762 else
16764 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16766 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16767 if( pBag )
16769 if( bagguid == pBag->GetGUID() )
16771 bag = i;
16772 break;
16779 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16781 ItemPosCountVec dest;
16782 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16783 if( msg != EQUIP_ERR_OK )
16785 SendEquipError( msg, NULL, NULL );
16786 return false;
16789 ModifyMoney( -(int32)price );
16790 if(crItem->ExtendedCost) // case for new honor system
16792 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16793 if(iece->reqhonorpoints)
16794 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16795 if(iece->reqarenapoints)
16796 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16797 for (uint8 i = 0; i < 5; ++i)
16799 if(iece->reqitem[i])
16800 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16804 if(Item *it = StoreNewItem( dest, item, true ))
16806 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16808 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16809 data << pCreature->GetGUID();
16810 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16811 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16812 data << (uint32)count;
16813 GetSession()->SendPacket(&data);
16815 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16818 else if( IsEquipmentPos( bag, slot ) )
16820 uint16 dest;
16821 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16822 if( msg != EQUIP_ERR_OK )
16824 SendEquipError( msg, NULL, NULL );
16825 return false;
16828 ModifyMoney( -(int32)price );
16829 if(crItem->ExtendedCost) // case for new honor system
16831 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16832 if(iece->reqhonorpoints)
16833 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16834 if(iece->reqarenapoints)
16835 ModifyArenaPoints( - int32(iece->reqarenapoints));
16836 for (uint8 i = 0; i < 5; ++i)
16838 if(iece->reqitem[i])
16839 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16843 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16845 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16847 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16848 data << pCreature->GetGUID();
16849 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16850 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16851 data << (uint32)count;
16852 GetSession()->SendPacket(&data);
16854 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16856 AutoUnequipOffhandIfNeed();
16859 else
16861 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16862 return false;
16865 return crItem->maxcount!=0;
16868 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16870 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16871 // the personal rating of the arena team must match the required limit as well
16872 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16873 uint32 max_personal_rating = 0;
16874 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16876 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16878 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16879 uint32 t_rating = at->GetRating();
16880 p_rating = p_rating<t_rating? p_rating : t_rating;
16881 if(max_personal_rating < p_rating)
16882 max_personal_rating = p_rating;
16885 return max_personal_rating;
16888 void Player::UpdateHomebindTime(uint32 time)
16890 // GMs never get homebind timer online
16891 if (m_InstanceValid || isGameMaster())
16893 if(m_HomebindTimer) // instance valid, but timer not reset
16895 // hide reminder
16896 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16897 data << uint32(0);
16898 data << uint32(0);
16899 GetSession()->SendPacket(&data);
16901 // instance is valid, reset homebind timer
16902 m_HomebindTimer = 0;
16904 else if (m_HomebindTimer > 0)
16906 if (time >= m_HomebindTimer)
16908 // teleport to homebind location
16909 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16911 else
16912 m_HomebindTimer -= time;
16914 else
16916 // instance is invalid, start homebind timer
16917 m_HomebindTimer = 60000;
16918 // send message to player
16919 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16920 data << m_HomebindTimer;
16921 data << uint32(1);
16922 GetSession()->SendPacket(&data);
16923 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16927 void Player::UpdatePvP(bool state, bool ovrride)
16929 if(!state || ovrride)
16931 SetPvP(state);
16932 if(Pet* pet = GetPet())
16933 pet->SetPvP(state);
16934 if(Unit* charmed = GetCharm())
16935 charmed->SetPvP(state);
16937 pvpInfo.endTimer = 0;
16939 else
16941 if(pvpInfo.endTimer != 0)
16942 pvpInfo.endTimer = time(NULL);
16943 else
16945 SetPvP(state);
16947 if(Pet* pet = GetPet())
16948 pet->SetPvP(state);
16949 if(Unit* charmed = GetCharm())
16950 charmed->SetPvP(state);
16955 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16957 SpellCooldown sc;
16958 sc.end = end_time;
16959 sc.itemid = itemid;
16960 m_spellCooldowns[spellid] = sc;
16963 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16965 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16966 return;
16968 // Get spell cooldwn
16969 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16970 // Apply spellmods
16971 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16972 if (cooldown < 0)
16973 cooldown = 0;
16974 // Add cooldown
16975 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16976 // Send activate
16977 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16978 data << spellInfo->Id;
16979 data << GetGUID();
16980 SendDirectMessage(&data);
16982 //slot to be excluded while counting
16983 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16985 if(!enchantmentcondition)
16986 return true;
16988 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16990 if(!Condition)
16991 return true;
16993 uint8 curcount[4] = {0, 0, 0, 0};
16995 //counting current equipped gem colors
16996 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
16998 if(i == slot)
16999 continue;
17000 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17001 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17003 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17005 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17006 if(!enchant_id)
17007 continue;
17009 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17010 if(!enchantEntry)
17011 continue;
17013 uint32 gemid = enchantEntry->GemID;
17014 if(!gemid)
17015 continue;
17017 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17018 if(!gemProto)
17019 continue;
17021 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17022 if(!gemProperty)
17023 continue;
17025 uint8 GemColor = gemProperty->color;
17027 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17029 if(tmpcolormask & GemColor)
17030 ++curcount[b];
17036 bool activate = true;
17038 for(int i = 0; i < 5; i++)
17040 if(!Condition->Color[i])
17041 continue;
17043 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17045 // if have <CompareColor> use them as count, else use <value> from Condition
17046 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17048 switch(Condition->Comparator[i])
17050 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17051 activate &= (_cur_gem < _cmp_gem) ? true : false;
17052 break;
17053 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17054 activate &= (_cur_gem > _cmp_gem) ? true : false;
17055 break;
17056 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17057 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17058 break;
17062 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");
17064 return activate;
17067 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17069 //cycle all equipped items
17070 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17072 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17073 if(slot == exceptslot)
17074 continue;
17076 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17078 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17079 continue;
17081 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17083 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17084 if(!enchant_id)
17085 continue;
17087 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17088 if(!enchantEntry)
17089 continue;
17091 uint32 condition = enchantEntry->EnchantmentCondition;
17092 if(condition)
17094 //was enchant active with/without item?
17095 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17096 //should it now be?
17097 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17099 // ignore item gem conditions
17100 //if state changed, (dis)apply enchant
17101 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17108 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17109 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17111 //cycle all equipped items
17112 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17114 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17115 if(slot == exceptslot)
17116 continue;
17118 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17120 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17121 continue;
17123 //cycle all (gem)enchants
17124 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17126 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17127 if(!enchant_id) //if no enchant go to next enchant(slot)
17128 continue;
17130 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17131 if(!enchantEntry)
17132 continue;
17134 //only metagems to be (de)activated, so only enchants with condition
17135 uint32 condition = enchantEntry->EnchantmentCondition;
17136 if(condition)
17137 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17142 void Player::LeaveBattleground(bool teleportToEntryPoint)
17144 if(BattleGround *bg = GetBattleGround())
17146 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17148 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17150 // call after remove to be sure that player resurrected for correct cast
17151 if(need_debuf)
17152 CastSpell(this, 26013, true); // Deserter
17156 bool Player::CanJoinToBattleground() const
17158 // check Deserter debuff
17159 if(GetDummyAura(26013))
17160 return false;
17162 return true;
17165 bool Player::CanReportAfkDueToLimit()
17167 // a player can complain about 15 people per 5 minutes
17168 if(m_bgAfkReportedCount >= 15)
17169 return false;
17170 ++m_bgAfkReportedCount;
17171 return true;
17174 ///This player has been blamed to be inactive in a battleground
17175 void Player::ReportedAfkBy(Player* reporter)
17177 BattleGround *bg = GetBattleGround();
17178 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17179 return;
17181 // check if player has 'Idle' or 'Inactive' debuff
17182 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17184 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17185 // 3 players have to complain to apply debuff
17186 if(m_bgAfkReporter.size() >= 3)
17188 // cast 'Idle' spell
17189 CastSpell(this, 43680, true);
17190 m_bgAfkReporter.clear();
17195 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17197 // gamemaster in GM mode see all, including ghosts
17198 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17199 return true;
17201 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17202 if (InBattleGround())
17204 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17205 return false;
17206 return true;
17209 // Live player see live player or dead player with not realized corpse
17210 if(pl->isAlive() || pl->m_deathTimer > 0)
17212 return isAlive() || m_deathTimer > 0;
17215 // Ghost see other friendly ghosts, that's for sure
17216 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17217 return true;
17219 // Dead player see live players near own corpse
17220 if(isAlive())
17222 Corpse *corpse = pl->GetCorpse();
17223 if(corpse)
17225 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17226 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17227 return true;
17231 // and not see any other
17232 return false;
17235 bool Player::IsVisibleGloballyFor( Player* u ) const
17237 if(!u)
17238 return false;
17240 // Always can see self
17241 if (u==this)
17242 return true;
17244 // Visible units, always are visible for all players
17245 if (GetVisibility() == VISIBILITY_ON)
17246 return true;
17248 // GMs are visible for higher gms (or players are visible for gms)
17249 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17250 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17252 // non faction visibility non-breakable for non-GMs
17253 if (GetVisibility() == VISIBILITY_OFF)
17254 return false;
17256 // non-gm stealth/invisibility not hide from global player lists
17257 return true;
17260 void Player::UpdateVisibilityOf(WorldObject* target)
17262 if(HaveAtClient(target))
17264 if(!target->isVisibleForInState(this,true))
17266 target->DestroyForPlayer(this);
17267 m_clientGUIDs.erase(target->GetGUID());
17269 #ifdef MANGOS_DEBUG
17270 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17271 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17272 #endif
17275 else
17277 if(target->isVisibleForInState(this,false))
17279 target->SendUpdateToPlayer(this);
17280 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17281 m_clientGUIDs.insert(target->GetGUID());
17283 #ifdef MANGOS_DEBUG
17284 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17285 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17286 #endif
17288 // target aura duration for caster show only if target exist at caster client
17289 // send data at target visibility change (adding to client)
17290 if(target!=this && target->isType(TYPEMASK_UNIT))
17291 SendAurasForTarget((Unit*)target);
17293 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17294 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17299 template<class T>
17300 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17302 s64.insert(target->GetGUID());
17305 template<>
17306 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17308 if(!target->IsTransport())
17309 s64.insert(target->GetGUID());
17312 template<class T>
17313 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17315 if(HaveAtClient(target))
17317 if(!target->isVisibleForInState(this,true))
17319 target->BuildOutOfRangeUpdateBlock(&data);
17320 m_clientGUIDs.erase(target->GetGUID());
17322 #ifdef MANGOS_DEBUG
17323 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17324 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));
17325 #endif
17328 else
17330 if(target->isVisibleForInState(this,false))
17332 visibleNow.insert(target);
17333 target->BuildUpdate(data_updates);
17334 target->BuildCreateUpdateBlockForPlayer(&data, this);
17335 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17337 #ifdef MANGOS_DEBUG
17338 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17339 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));
17340 #endif
17345 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17346 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17347 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17348 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17349 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17351 void Player::InitPrimaryProffesions()
17353 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17356 void Player::SendComboPoints()
17358 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17359 if (combotarget)
17361 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17362 data.append(combotarget->GetPackGUID());
17363 data << uint8(m_comboPoints);
17364 GetSession()->SendPacket(&data);
17368 void Player::AddComboPoints(Unit* target, int8 count)
17370 if(!count)
17371 return;
17373 // without combo points lost (duration checked in aura)
17374 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17376 if(target->GetGUID() == m_comboTarget)
17378 m_comboPoints += count;
17380 else
17382 if(m_comboTarget)
17383 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17384 target->RemoveComboPointHolder(GetGUIDLow());
17386 m_comboTarget = target->GetGUID();
17387 m_comboPoints = count;
17389 target->AddComboPointHolder(GetGUIDLow());
17392 if (m_comboPoints > 5) m_comboPoints = 5;
17393 if (m_comboPoints < 0) m_comboPoints = 0;
17395 SendComboPoints();
17398 void Player::ClearComboPoints()
17400 if(!m_comboTarget)
17401 return;
17403 // without combopoints lost (duration checked in aura)
17404 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17406 m_comboPoints = 0;
17408 SendComboPoints();
17410 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17411 target->RemoveComboPointHolder(GetGUIDLow());
17413 m_comboTarget = 0;
17416 void Player::SetGroup(Group *group, int8 subgroup)
17418 if(group == NULL) m_group.unlink();
17419 else
17421 // never use SetGroup without a subgroup unless you specify NULL for group
17422 assert(subgroup >= 0);
17423 m_group.link(group, this);
17424 m_group.setSubGroup((uint8)subgroup);
17428 void Player::SendInitialPacketsBeforeAddToMap()
17430 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17431 data << uint32(0); // unknown, may be rest state time or expirience
17432 GetSession()->SendPacket(&data);
17434 // Homebind
17435 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17436 data << m_homebindX << m_homebindY << m_homebindZ;
17437 data << (uint32) m_homebindMapId;
17438 data << (uint32) m_homebindZoneId;
17439 GetSession()->SendPacket(&data);
17441 // SMSG_SET_PROFICIENCY
17442 // SMSG_UPDATE_AURA_DURATION
17444 // tutorial stuff
17445 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17446 for (int i = 0; i < 8; ++i)
17447 data << uint32( GetTutorialInt(i) );
17448 GetSession()->SendPacket(&data);
17450 SendInitialSpells();
17452 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17453 data << uint32(0); // count, for(count) uint32;
17454 GetSession()->SendPacket(&data);
17456 SendInitialActionButtons();
17457 SendInitialReputations();
17458 m_achievementMgr.SendAllAchievementData();
17459 UpdateZone(GetZoneId());
17460 SendInitWorldStates();
17462 // SMSG_SET_AURA_SINGLE
17464 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17465 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17466 data << (float)0.01666667f; // game speed
17467 GetSession()->SendPacket( &data );
17469 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17470 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17471 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17474 void Player::SendInitialPacketsAfterAddToMap()
17476 CastSpell(this, 836, true); // LOGINEFFECT
17478 // set some aura effects that send packet to player client after add player to map
17479 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17480 // same auras state lost at far teleport, send it one more time in this case also
17481 static const AuraType auratypes[] =
17483 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17484 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17485 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17487 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17489 Unit::AuraList const& auraList = GetAurasByType(*itr);
17490 if(!auraList.empty())
17491 auraList.front()->ApplyModifier(true,true);
17494 if(HasAuraType(SPELL_AURA_MOD_STUN))
17495 SetMovement(MOVE_ROOT);
17497 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17498 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17500 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17501 data.append(GetPackGUID());
17502 data << (uint32)2;
17503 SendMessageToSet(&data,true);
17506 SendAurasForTarget(this);
17507 SendEnchantmentDurations(); // must be after add to map
17508 SendItemDurations(); // must be after add to map
17511 void Player::SendUpdateToOutOfRangeGroupMembers()
17513 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17514 return;
17515 if(Group* group = GetGroup())
17516 group->UpdatePlayerOutOfRange(this);
17518 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17519 m_auraUpdateMask = 0;
17520 if(Pet *pet = GetPet())
17521 pet->ResetAuraUpdateMask();
17524 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17526 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17527 data << uint32(mapid);
17528 data << uint8(reason); // transfer abort reason
17529 switch(reason)
17531 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17532 case TRANSFER_ABORT_DIFFICULTY:
17533 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17534 data << uint8(arg);
17535 break;
17537 GetSession()->SendPacket(&data);
17540 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17542 // type of warning, based on the time remaining until reset
17543 uint32 type;
17544 if(time > 3600)
17545 type = RAID_INSTANCE_WELCOME;
17546 else if(time > 900 && time <= 3600)
17547 type = RAID_INSTANCE_WARNING_HOURS;
17548 else if(time > 300 && time <= 900)
17549 type = RAID_INSTANCE_WARNING_MIN;
17550 else
17551 type = RAID_INSTANCE_WARNING_MIN_SOON;
17552 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17553 data << uint32(type);
17554 data << uint32(mapid);
17555 data << uint32(time);
17556 GetSession()->SendPacket(&data);
17559 void Player::ApplyEquipCooldown( Item * pItem )
17561 for(int i = 0; i <5; ++i)
17563 _Spell const& spellData = pItem->GetProto()->Spells[i];
17565 // no spell
17566 if( !spellData.SpellId )
17567 continue;
17569 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17570 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17571 continue;
17573 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17575 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17576 data << pItem->GetGUID();
17577 data << uint32(spellData.SpellId);
17578 GetSession()->SendPacket(&data);
17582 void Player::resetSpells()
17584 // not need after this call
17585 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17587 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17588 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17591 // make full copy of map (spells removed and marked as deleted at another spell remove
17592 // and we can't use original map for safe iterative with visit each spell at loop end
17593 PlayerSpellMap smap = GetSpellMap();
17595 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17596 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17598 learnDefaultSpells();
17599 learnQuestRewardedSpells();
17602 void Player::learnDefaultSpells(bool loading)
17604 // learn default race/class spells
17605 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17606 std::list<CreateSpellPair>::const_iterator spell_itr;
17607 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17609 uint16 tspell = spell_itr->first;
17610 if (tspell)
17612 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17613 if(loading || !spell_itr->second) // not care about passive spells or loading case
17614 addSpell(tspell,spell_itr->second);
17615 else // but send in normal spell in game learn case
17616 learnSpell(tspell);
17621 void Player::learnQuestRewardedSpells(Quest const* quest)
17623 uint32 spell_id = quest->GetRewSpellCast();
17625 // skip quests without rewarded spell
17626 if( !spell_id )
17627 return;
17629 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17630 if(!spellInfo)
17631 return;
17633 // check learned spells state
17634 bool found = false;
17635 for(int i=0; i < 3; ++i)
17637 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17639 found = true;
17640 break;
17644 // skip quests with not teaching spell or already known spell
17645 if(!found)
17646 return;
17648 // prevent learn non first rank unknown profession and second specialization for same profession)
17649 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17650 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17652 // not have first rank learned (unlearned prof?)
17653 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17654 if( !HasSpell(first_spell) )
17655 return;
17657 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17658 if(!learnedInfo)
17659 return;
17661 // specialization
17662 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17664 // search other specialization for same prof
17665 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17667 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17668 continue;
17670 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17671 if(!itrInfo)
17672 return;
17674 // compare only specializations
17675 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17676 continue;
17678 // compare same chain spells
17679 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17680 continue;
17682 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17683 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17684 return;
17689 CastSpell( this, spell_id, true);
17692 void Player::learnQuestRewardedSpells()
17694 // learn spells received from quest completing
17695 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17697 // skip no rewarded quests
17698 if(!itr->second.m_rewarded)
17699 continue;
17701 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17702 if( !quest )
17703 continue;
17705 learnQuestRewardedSpells(quest);
17709 void Player::learnSkillRewardedSpells(uint32 skill_id )
17711 uint32 raceMask = getRaceMask();
17712 uint32 classMask = getClassMask();
17713 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17715 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17716 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17717 continue;
17718 // Check race if set
17719 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17720 continue;
17721 // Check class if set
17722 if (pAbility->classmask && !(pAbility->classmask & classMask))
17723 continue;
17725 if (SpellEntry const* spellentry = sSpellStore.LookupEntry(pAbility->spellId))
17727 // Ok need learn spell
17728 learnSpell(pAbility->spellId);
17733 void Player::learnSkillRewardedSpells()
17735 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17737 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17738 continue;
17740 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17742 learnSkillRewardedSpells(pskill);
17746 void Player::SendAurasForTarget(Unit *target)
17748 WorldPacket data(SMSG_AURA_UPDATE_ALL);
17749 data.append(target->GetPackGUID());
17751 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17753 Aura* aura = itr->second;
17754 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17755 continue;
17757 data << uint8(aura->GetAuraSlot());
17758 data << uint32(aura->GetId());
17760 if(aura->GetId())
17762 uint8 auraFlags = aura->GetAuraFlags();
17763 data << uint8(auraFlags); // flags
17764 data << uint8(aura->GetAuraLevel()); // level
17765 data << uint8(aura->m_procCharges); // charges
17767 /*if(!(auraFlags & AFLAG_NOT_GUID))
17769 data << uint8(0) // packed GUID of someone (caster?)
17772 if(auraFlags & AFLAG_DURATION) // include aura duration
17774 data << uint32(aura->GetAuraMaxDuration());
17775 data << uint32(aura->GetAuraDuration());
17780 GetSession()->SendPacket(&data);
17783 void Player::SetDailyQuestStatus( uint32 quest_id )
17785 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17787 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17789 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17790 m_lastDailyQuestTime = time(NULL); // last daily quest time
17791 m_DailyQuestChanged = true;
17792 break;
17797 void Player::ResetDailyQuestStatus()
17799 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17800 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17802 // DB data deleted in caller
17803 m_DailyQuestChanged = false;
17804 m_lastDailyQuestTime = 0;
17807 BattleGround* Player::GetBattleGround() const
17809 if(GetBattleGroundId()==0)
17810 return NULL;
17812 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17815 bool Player::InArena() const
17817 BattleGround *bg = GetBattleGround();
17818 if(!bg || !bg->isArena())
17819 return false;
17821 return true;
17824 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17826 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17827 if(!bg)
17828 return false;
17830 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17831 return false;
17833 return true;
17836 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17838 if(queue_id < 1)
17839 return 0;
17841 if(queue_id >=6)
17842 queue_id = 6;
17844 return 10*(queue_id+1);
17847 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17849 if(queue_id >=6)
17850 return 255; // hardcoded max level
17852 return 10*(queue_id+2)-1;
17855 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17857 uint32 level = getLevel();
17858 if(level <= 19)
17859 return 0;
17860 else if (level > 69)
17861 return 6;
17862 else
17863 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17866 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17868 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17869 if(!vendor_faction)
17870 return 1.0f;
17872 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17873 if(rank <= REP_NEUTRAL)
17874 return 1.0f;
17876 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17879 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17881 uint32 racemask = getRaceMask();
17882 uint32 classmask = getClassMask();
17884 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17885 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17887 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17889 // skip wrong race skills
17890 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17891 return false;
17893 // skip wrong class skills
17894 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17895 return false;
17897 return true;
17900 bool Player::HasQuestForGO(int32 GOId)
17902 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17904 QuestStatusData qs=i->second;
17905 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17907 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17908 if(!qinfo)
17909 continue;
17911 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17912 continue;
17914 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17916 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17917 continue;
17919 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17920 return true;
17924 return false;
17927 void Player::UpdateForQuestsGO()
17929 if(m_clientGUIDs.empty())
17930 return;
17932 UpdateData udata;
17933 WorldPacket packet;
17934 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17936 if(IS_GAMEOBJECT_GUID(*itr))
17938 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17939 if(obj)
17940 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17943 udata.BuildPacket(&packet);
17944 GetSession()->SendPacket(&packet);
17947 void Player::SummonIfPossible(bool agree)
17949 if(!agree)
17951 m_summon_expire = 0;
17952 return;
17955 // expire and auto declined
17956 if(m_summon_expire < time(NULL))
17957 return;
17959 // stop taxi flight at summon
17960 if(isInFlight())
17962 GetMotionMaster()->MovementExpired();
17963 m_taxi.ClearTaxiDestinations();
17966 // drop flag at summon
17967 if(BattleGround *bg = GetBattleGround())
17968 bg->EventPlayerDroppedFlag(this);
17970 m_summon_expire = 0;
17972 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17975 void Player::RemoveItemDurations( Item *item )
17977 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17979 if(*itr==item)
17981 m_itemDuration.erase(itr);
17982 break;
17987 void Player::AddItemDurations( Item *item )
17989 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17991 m_itemDuration.push_back(item);
17992 item->SendTimeUpdate(this);
17996 void Player::AutoUnequipOffhandIfNeed()
17998 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
17999 if(!offItem)
18000 return;
18002 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
18004 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
18005 return;
18007 ItemPosCountVec off_dest;
18008 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18009 if( off_msg == EQUIP_ERR_OK )
18011 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18012 StoreItem( off_dest, offItem, true );
18014 else
18016 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18020 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18022 if(spellInfo->EquippedItemClass < 0)
18023 return true;
18025 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18026 // for optimize check 2 used cases only
18027 switch(spellInfo->EquippedItemClass)
18029 case ITEM_CLASS_WEAPON:
18031 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18032 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18033 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18034 return true;
18035 break;
18037 case ITEM_CLASS_ARMOR:
18039 // tabard not have dependent spells
18040 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18041 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18042 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18043 return true;
18045 // shields can be equipped to offhand slot
18046 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18047 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18048 return true;
18050 // ranged slot can have some armor subclasses
18051 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18052 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18053 return true;
18055 break;
18057 default:
18058 sLog.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo->EquippedItemClass);
18059 break;
18062 return false;
18065 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18067 AuraMap& auras = GetAuras();
18068 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18070 Aura* aura = itr->second;
18072 // skip passive (passive item dependent spells work in another way) and not self applied auras
18073 SpellEntry const* spellInfo = aura->GetSpellProto();
18074 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18076 ++itr;
18077 continue;
18080 // skip if not item dependent or have alternative item
18081 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18083 ++itr;
18084 continue;
18087 // no alt item, remove aura, restart check
18088 RemoveAurasDueToSpell(aura->GetId());
18089 itr = auras.begin();
18092 // currently casted spells can be dependent from item
18093 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18095 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18096 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18097 InterruptSpell(i);
18101 uint32 Player::GetResurrectionSpellId()
18103 // search priceless resurrection possabilities
18104 uint32 prio = 0;
18105 uint32 spell_id = 0;
18106 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18107 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18109 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18110 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18112 switch((*itr)->GetId())
18114 case 20707: spell_id = 3026; break; // rank 1
18115 case 20762: spell_id = 20758; break; // rank 2
18116 case 20763: spell_id = 20759; break; // rank 3
18117 case 20764: spell_id = 20760; break; // rank 4
18118 case 20765: spell_id = 20761; break; // rank 5
18119 case 27239: spell_id = 27240; break; // rank 6
18120 default:
18121 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18122 continue;
18125 prio = 3;
18127 // Twisting Nether // prio: 2 (max)
18128 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18130 prio = 2;
18131 spell_id = 23700;
18135 // Reincarnation (passive spell) // prio: 1
18136 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18137 spell_id = 21169;
18139 return spell_id;
18142 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18144 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18146 // prepare data for near group iteration (PvP and !PvP cases)
18147 uint32 xp = 0;
18148 bool honored_kill = false;
18150 if(Group *pGroup = GetGroup())
18152 uint32 count = 0;
18153 uint32 sum_level = 0;
18154 Player* member_with_max_level = NULL;
18155 Player* not_gray_member_with_max_level = NULL;
18157 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18159 if(member_with_max_level)
18161 /// not get Xp in PvP or no not gray players in group
18162 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18164 /// skip in check PvP case (for speed, not used)
18165 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18166 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18167 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18169 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18171 Player* pGroupGuy = itr->getSource();
18172 if(!pGroupGuy)
18173 continue;
18175 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18176 continue; // member (alive or dead) or his corpse at req. distance
18178 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18179 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18180 honored_kill = true;
18182 // xp and reputation only in !PvP case
18183 if(!PvP)
18185 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18187 // if is in dungeon then all receive full reputation at kill
18188 // rewarded any alive/dead/near_corpse group member
18189 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18191 // XP updated only for alive group member
18192 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18193 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18195 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18197 pGroupGuy->GiveXP(itr_xp, pVictim);
18198 if(Pet* pet = pGroupGuy->GetPet())
18199 pet->GivePetXP(itr_xp/2);
18202 // quest objectives updated only for alive group member or dead but with not released body
18203 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18205 // normal creature (not pet/etc) can be only in !PvP case
18206 if(pVictim->GetTypeId()==TYPEID_UNIT)
18207 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18213 else // if (!pGroup)
18215 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18217 // honor can be in PvP and !PvP (racial leader) cases
18218 if(RewardHonor(pVictim,1))
18219 honored_kill = true;
18221 // xp and reputation only in !PvP case
18222 if(!PvP)
18224 RewardReputation(pVictim,1);
18225 GiveXP(xp, pVictim);
18227 if(Pet* pet = GetPet())
18228 pet->GivePetXP(xp);
18230 // normal creature (not pet/etc) can be only in !PvP case
18231 if(pVictim->GetTypeId()==TYPEID_UNIT)
18232 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18235 return xp || honored_kill;
18238 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18240 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18241 return true;
18243 if(isAlive())
18244 return false;
18246 Corpse* corpse = GetCorpse();
18247 if(!corpse)
18248 return false;
18250 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18253 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18255 Item* item = GetWeaponForAttack(attType,true);
18257 // unarmmed only with base attack
18258 if(attType != BASE_ATTACK && !item)
18259 return 0;
18261 // weapon skill or (unarmed for base attack)
18262 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18263 return GetBaseSkillValue(skill);
18266 void Player::ResurectUsingRequestData()
18268 ResurrectPlayer(0.0f,false);
18270 if(GetMaxHealth() > m_resurrectHealth)
18271 SetHealth( m_resurrectHealth );
18272 else
18273 SetHealth( GetMaxHealth() );
18275 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18276 SetPower(POWER_MANA, m_resurrectMana );
18277 else
18278 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18280 SetPower(POWER_RAGE, 0 );
18282 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18284 SpawnCorpseBones();
18286 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18289 void Player::SetClientControl(Unit* target, uint8 allowMove)
18291 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18292 data.append(target->GetPackGUID());
18293 data << uint8(allowMove);
18294 GetSession()->SendPacket(&data);
18297 void Player::UpdateZoneDependentAuras( uint32 newZone )
18299 // remove new continent flight forms
18300 if( !isGameMaster() &&
18301 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
18303 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18304 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18307 // Some spells applied at enter into zone (with subzones)
18308 // Human Illusion
18309 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18310 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18312 uint32 spellid = 0;
18313 // all horde races
18314 if( GetTeam() == HORDE )
18315 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18316 // and some alliance races
18317 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18318 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18320 if(spellid && !HasAura(spellid,0) )
18321 CastSpell(this,spellid,true);
18325 void Player::UpdateAreaDependentAuras( uint32 newArea )
18327 // remove auras from spells with area limitations
18328 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18330 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18331 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
18332 RemoveAura(iter);
18333 else
18334 ++iter;
18337 // unmount if enter in this subzone
18338 if( newArea == 35)
18339 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18340 // Dragonmaw Illusion
18341 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18343 if( GetDummyAura(40214) )
18345 if( !HasAura(40216,0) )
18346 CastSpell(this,40216,true);
18347 if( !HasAura(42016,0) )
18348 CastSpell(this,42016,true);
18353 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18355 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18356 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18358 return copseReclaimDelay[0];
18361 time_t now = time(NULL);
18362 // 0..2 full period
18363 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18364 return copseReclaimDelay[count];
18367 void Player::UpdateCorpseReclaimDelay()
18369 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18371 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18372 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18373 return;
18375 time_t now = time(NULL);
18376 if(now < m_deathExpireTime)
18378 // full and partly periods 1..3
18379 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18380 if(count < MAX_DEATH_COUNT)
18381 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18382 else
18383 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18385 else
18386 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18389 void Player::SendCorpseReclaimDelay(bool load)
18391 Corpse* corpse = GetCorpse();
18392 if(!corpse)
18393 return;
18395 uint32 delay;
18396 if(load)
18398 if(corpse->GetGhostTime() > m_deathExpireTime)
18399 return;
18401 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18403 uint32 count;
18404 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18405 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18407 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18408 if(count>=MAX_DEATH_COUNT)
18409 count = MAX_DEATH_COUNT-1;
18411 else
18412 count=0;
18414 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18416 time_t now = time(NULL);
18417 if(now >= expected_time)
18418 return;
18420 delay = expected_time-now;
18422 else
18423 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18425 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18426 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18427 data << uint32(delay*1000);
18428 GetSession()->SendPacket( &data );
18431 Player* Player::GetNextRandomRaidMember(float radius)
18433 Group *pGroup = GetGroup();
18434 if(!pGroup)
18435 return NULL;
18437 std::vector<Player*> nearMembers;
18438 nearMembers.reserve(pGroup->GetMembersCount());
18440 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18442 Player* Target = itr->getSource();
18444 // IsHostileTo check duel and controlled by enemy
18445 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18446 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18447 nearMembers.push_back(Target);
18450 if (nearMembers.empty())
18451 return NULL;
18453 uint32 randTarget = urand(0,nearMembers.size()-1);
18454 return nearMembers[randTarget];
18457 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18459 float water_z = m->GetWaterLevel(x,y);
18460 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18461 uint8 flag1 = m->GetTerrainType(x,y);
18463 //!Underwater check, not in water if underground or above water level
18464 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18465 m_isunderwater &= 0x7A;
18466 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18467 m_isunderwater |= 0x01;
18469 //!in lava check, anywhere under lava level
18470 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18471 m_isunderwater |= 0x80;
18474 void Player::SetCanParry( bool value )
18476 if(m_canParry==value)
18477 return;
18479 m_canParry = value;
18480 UpdateParryPercentage();
18483 void Player::SetCanBlock( bool value )
18485 if(m_canBlock==value)
18486 return;
18488 m_canBlock = value;
18489 UpdateBlockPercentage();
18492 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18494 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18495 if(itr->pos == this->pos)
18496 return true;
18498 return false;
18501 bool Player::isAllowUseBattleGroundObject()
18503 return ( //InBattleGround() && // in battleground - not need, check in other cases
18504 !IsMounted() && // not mounted
18505 !HasStealthAura() && // not stealthed
18506 !HasInvisibilityAura() && // not invisible
18507 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18508 isAlive() // live player
18512 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18514 uint32 level = getLevel();
18516 if(level > sGtBarberShopCostBaseStore.GetNumRows())
18517 level = GT_MAX_LEVEL; // max level in this dbc
18519 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18520 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18521 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18523 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18524 return 0;
18526 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18528 if(!bsc) // shouldn't happen
18529 return 0xFFFFFFFF;
18531 float cost = 0;
18533 if(hairstyle != newhairstyle)
18534 cost += bsc->cost; // full price
18536 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18537 cost += bsc->cost * 0.5f; // +1/2 of price
18539 if(facialhair != newfacialhair)
18540 cost += bsc->cost * 0.75f; // +3/4 of price
18542 return uint32(cost);
18545 void Player::InitGlyphsForLevel()
18547 uint32 level = getLevel();
18548 uint32 value = 0;
18550 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18551 if(level >= 15)
18552 value |= (0x01 | 0x02);
18553 if(level >= 30)
18554 value |= 0x04;
18555 if(level >= 50)
18556 value |= 0x08;
18557 if(level >= 70)
18558 value |= 0x10;
18559 if(level >= 80)
18560 value |= 0x20;
18562 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);