Advertisement
FridayGeek

Untitled

Oct 17th, 2020
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 146.64 KB | None | 0 0
  1. ////////////////////////////////////////////////////////////////////////
  2. // OpenTibia - an opensource roleplaying game
  3. ////////////////////////////////////////////////////////////////////////
  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 3 of the License, or
  7. // (at your option) any later version.
  8. //
  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.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program.  If not, see <http://www.gnu.org/licenses/>.
  16. ////////////////////////////////////////////////////////////////////////
  17. #include "otpch.h"
  18. #include <iostream>
  19.  
  20. #include "player.h"
  21. #include "manager.h"
  22.  
  23. #include "iologindata.h"
  24. #include "ioban.h"
  25.  
  26. #include "town.h"
  27. #include "house.h"
  28. #include "beds.h"
  29.  
  30. #include "combat.h"
  31. #include "movement.h"
  32. #include "weapons.h"
  33. #include "creatureevent.h"
  34.  
  35. #include "configmanager.h"
  36. #include "game.h"
  37. #include "chat.h"
  38.  
  39. extern ConfigManager g_config;
  40. extern Game g_game;
  41. extern Chat g_chat;
  42. extern MoveEvents* g_moveEvents;
  43. extern Weapons* g_weapons;
  44. extern CreatureEvents* g_creatureEvents;
  45.  
  46. AutoList<Player> Player::castAutoList;
  47. AutoList<Player> Player::autoList;
  48. AutoList<ProtocolGame> Player::cSpectators;
  49. uint32_t Player::nextSpectator = 0;
  50.  
  51. #ifdef __ENABLE_SERVER_DIAGNOSTIC__
  52. uint32_t Player::playerCount = 0;
  53. #endif
  54. MuteCountMap Player::muteCountMap;
  55.  
  56. Player::Player(const std::string& _name, ProtocolGame* p):
  57.     Creature(), transferContainer(ITEM_LOCKER), name(_name), nameDescription(_name), client(p)
  58. {
  59.     if(client)
  60.         client->setPlayer(this);
  61.  
  62.     pzLocked = isConnecting = addAttackSkillPoint = requestedOutfit = false;
  63.     saving = true;
  64.  
  65.     lastAttackBlockType = BLOCK_NONE;
  66.     chaseMode = CHASEMODE_STANDSTILL;
  67.     fightMode = FIGHTMODE_ATTACK;
  68.     tradeState = TRADE_NONE;
  69.     accountManager = MANAGER_NONE;
  70.     guildLevel = GUILDLEVEL_NONE;
  71.  
  72.     promotionLevel = walkTaskEvent = actionTaskEvent = nextStepEvent = bloodHitCount = shieldBlockCount = 0;
  73.     lastAttack = idleTime = marriage = blessings = balance = premiumDays = mana = manaMax = manaSpent = 0;
  74.     soul = guildId = levelPercent = magLevelPercent = magLevel = experience = damageImmunities = 0;
  75.     conditionImmunities = conditionSuppressions = groupId = vocationId = managerNumber2 = town = skullEnd = 0;
  76.     lastLogin = lastLogout = lastIP = messageTicks = messageBuffer = nextAction = 0;
  77.     editListId = maxWriteLen = windowTextId = rankId = 0;
  78.     managerNumber3 = g_config.getNumber(ConfigManager::DEFAULT_TOWN_ID);
  79.  
  80.     purchaseCallback = saleCallback = -1;
  81.     level = shootRange = 1;
  82.     rates[SKILL__MAGLEVEL] = rates[SKILL__LEVEL] = 1.0f;
  83.     soulMax = 100;
  84.     capacity = 400.00;
  85.     stamina = STAMINA_MAX;
  86.     lastLoad = lastPing = lastPong = OTSYS_TIME();
  87.  
  88.     writeItem = NULL;
  89.     group = NULL;
  90.     editHouse = NULL;
  91.     shopOwner = NULL;
  92.     tradeItem = NULL;
  93.     tradePartner = NULL;
  94.     walkTask = NULL;
  95.     weapon = NULL;
  96.  
  97.     setVocation(0);
  98.     setParty(NULL);
  99.  
  100.     transferContainer.setParent(NULL);
  101.     for(int32_t i = 0; i < 11; i++)
  102.     {
  103.         inventory[i] = NULL;
  104.         inventoryAbilities[i] = false;
  105.     }
  106.  
  107.     for(int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i)
  108.     {
  109.         skills[i][SKILL_LEVEL] = 10;
  110.         skills[i][SKILL_TRIES] = skills[i][SKILL_PERCENT] = 0;
  111.         rates[i] = 1.0f;
  112.     }
  113.  
  114.     for(int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i)
  115.         varSkills[i] = 0;
  116.  
  117.     for(int32_t i = STAT_FIRST; i <= STAT_LAST; ++i)
  118.         varStats[i] = 0;
  119.  
  120.     for(int32_t i = LOSS_FIRST; i <= LOSS_LAST; ++i)
  121.         lossPercent[i] = 100;
  122.  
  123.     for(int32_t i = 0; i <= 12; i++)
  124.         talkState[i] = false;
  125. #ifdef __ENABLE_SERVER_DIAGNOSTIC__
  126.  
  127.     playerCount++;
  128. #endif
  129. }
  130.  
  131. Player::~Player()
  132. {
  133. #ifdef __ENABLE_SERVER_DIAGNOSTIC__
  134.     playerCount--;
  135. #endif
  136.     setWriteItem(NULL);
  137.     for(int32_t i = 0; i < 11; i++)
  138.     {
  139.         if(inventory[i])
  140.         {
  141.             inventory[i]->setParent(NULL);
  142.             inventory[i]->unRef();
  143.  
  144.             inventory[i] = NULL;
  145.             inventoryAbilities[i] = false;
  146.         }
  147.     }
  148.  
  149.     setNextWalkActionTask(NULL);
  150.     transferContainer.setParent(NULL);
  151.     for(DepotMap::iterator it = depots.begin(); it != depots.end(); it++)
  152.         it->second.first->unRef();
  153. }
  154.  
  155. void Player::setCasting(bool c)
  156. {
  157.     if(cast.isCasting == c)
  158.         return;
  159.  
  160.     if(cast.isCasting && !c)
  161.     {
  162.         castAutoList.erase(id);            
  163.         kickCastViewers();
  164.     }
  165.     else
  166.     {
  167.         castAutoList[id] = this;
  168.            
  169.         ChatChannel* channel = g_chat.createChannel(this, CHANNEL_PRIVATE);
  170.         if(channel && channel->addUser(this))
  171.             sendCreatePrivateChannel(channel->getId(), channel->getName());
  172.     }
  173.  
  174.     cast.isCasting = c;
  175. }
  176.  
  177. void Player::setVocation(uint32_t id)
  178. {
  179.     vocationId = id;
  180.     vocation = Vocations::getInstance()->getVocation(id);
  181.  
  182.     soulMax = vocation->getGain(GAIN_SOUL);
  183.     if(Condition* condition = getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT))
  184.     {
  185.         condition->setParam(CONDITIONPARAM_HEALTHGAIN, vocation->getGainAmount(GAIN_HEALTH));
  186.         condition->setParam(CONDITIONPARAM_HEALTHTICKS, (vocation->getGainTicks(GAIN_HEALTH) * 1000));
  187.         condition->setParam(CONDITIONPARAM_MANAGAIN, vocation->getGainAmount(GAIN_MANA));
  188.         condition->setParam(CONDITIONPARAM_MANATICKS, (vocation->getGainTicks(GAIN_MANA) * 1000));
  189.     }
  190. }
  191.  
  192. bool Player::isPushable() const
  193. {
  194.     return accountManager == MANAGER_NONE && !hasFlag(PlayerFlag_CannotBePushed) && Creature::isPushable();
  195. }
  196.  
  197. std::string Player::getDescription(int32_t lookDistance) const
  198. {
  199.     std::stringstream s;
  200.     if(lookDistance == -1)
  201.     {
  202.         s << "yourself.";
  203.         if(hasFlag(PlayerFlag_ShowGroupNameInsteadOfVocation))
  204.             s << " You are " << group->getName();
  205.         else if(vocationId != 0)
  206.             s << " You are " << vocation->getDescription();
  207.         else
  208.             s << " You have no vocation";
  209.     }
  210.     else
  211.     {
  212.         s << nameDescription;
  213.         if(!hasCustomFlag(PlayerCustomFlag_HideLevel))
  214.             s << " (Level " << level << ")";
  215.  
  216.         s << ". " << (sex % 2 ? "He" : "She");
  217.         if(hasFlag(PlayerFlag_ShowGroupNameInsteadOfVocation))
  218.             s << " is " << group->getName();
  219.         else if(vocationId != 0)
  220.             s << " is " << vocation->getDescription();
  221.         else
  222.             s << " has no vocation";
  223.  
  224.         s << getSpecialDescription();
  225.     }
  226.  
  227.     std::string tmp;
  228.     if(marriage && IOLoginData::getInstance()->getNameByGuid(marriage, tmp))
  229.     {
  230.         s << ", ";
  231.         if(vocationId == 0)
  232.         {
  233.             if(lookDistance == -1)
  234.                 s << "and you are";
  235.             else
  236.                 s << "and is";
  237.  
  238.             s << " ";
  239.         }
  240.  
  241.         s << (sex % 2 ? "husband" : "wife") << " of " << tmp;
  242.     }
  243.  
  244.     s << ".";
  245.     if(guildId)
  246.     {
  247.         if(lookDistance == -1)
  248.             s << " You are ";
  249.         else
  250.             s << " " << (sex % 2 ? "He" : "She") << " is ";
  251.  
  252.         s << (rankName.empty() ? "a member" : rankName)<< " of the " << guildName;
  253.         if(!guildNick.empty())
  254.             s << " (" << guildNick << ")";
  255.  
  256.         s << ".";
  257.     }
  258.  
  259.     return s.str();
  260. }
  261.  
  262. Item* Player::getInventoryItem(slots_t slot) const
  263. {
  264.     if(slot > SLOT_PRE_FIRST && slot < SLOT_LAST)
  265.         return inventory[slot];
  266.  
  267.     if(slot == SLOT_HAND)
  268.         return inventory[SLOT_LEFT] ? inventory[SLOT_LEFT] : inventory[SLOT_RIGHT];
  269.  
  270.     return NULL;
  271. }
  272.  
  273. Item* Player::getEquippedItem(slots_t slot) const
  274. {
  275.     Item* item = getInventoryItem(slot);
  276.     if(!item)
  277.         return NULL;
  278.  
  279.     switch(slot)
  280.     {
  281.         case SLOT_LEFT:
  282.         case SLOT_RIGHT:
  283.             return item->getWieldPosition() == SLOT_HAND ? item : NULL;
  284.  
  285.         default:
  286.             break;
  287.     }
  288.  
  289.     return item->getWieldPosition() == slot ? item : NULL;
  290. }
  291.  
  292. void Player::setConditionSuppressions(uint32_t conditions, bool remove)
  293. {
  294.     if(remove)
  295.         conditionSuppressions &= ~conditions;
  296.     else
  297.         conditionSuppressions |= conditions;
  298. }
  299.  
  300. Item* Player::getWeapon(bool ignoreAmmo)
  301. {
  302.     if(weapon)
  303.         return weapon;
  304.  
  305.     Item* item = NULL;
  306.     for(int32_t slot = SLOT_RIGHT; slot <= SLOT_LEFT; ++slot)
  307.     {
  308.         if(!(item = getEquippedItem((slots_t)slot)) || item->getWeaponType() != WEAPON_DIST)
  309.             continue;
  310.  
  311.         if(!ignoreAmmo && item->getAmmoType() != AMMO_NONE)
  312.         {
  313.             Item* ammoItem = getInventoryItem(SLOT_AMMO);
  314.             if(ammoItem && ammoItem->getAmmoType() == item->getAmmoType())
  315.             {
  316.                 if(g_weapons->getWeapon(ammoItem))
  317.                 {
  318.                     shootRange = item->getShootRange();
  319.                     return ammoItem;
  320.                 }
  321.             }
  322.         }
  323.         else if(g_weapons->getWeapon(item))
  324.         {
  325.             shootRange = item->getShootRange();
  326.             return item;
  327.         }
  328.     }
  329.  
  330.     return NULL;
  331. }
  332.  
  333. ItemVector Player::getWeapons() const
  334. {
  335.     Item* item = NULL;
  336.     ItemVector weapons;
  337.     for(int32_t slot = SLOT_RIGHT; slot <= SLOT_LEFT; ++slot)
  338.     {
  339.         if(!(item = getEquippedItem((slots_t)slot)))
  340.             continue;
  341.  
  342.         switch(item->getWeaponType())
  343.         {
  344.             case WEAPON_DIST:
  345.                 if(item->getAmmoType() != AMMO_NONE)
  346.                     break;
  347.  
  348.             case WEAPON_SWORD:
  349.             case WEAPON_CLUB:
  350.             case WEAPON_AXE:
  351.             case WEAPON_FIST:
  352.             case WEAPON_WAND:
  353.             {
  354.                 if(g_weapons->getWeapon(item))
  355.                     weapons.push_back(item);
  356.  
  357.                 break;
  358.             }
  359.  
  360.             default:
  361.                 break;
  362.         }
  363.     }
  364.  
  365.     return weapons;
  366. }
  367.  
  368. void Player::updateWeapon()
  369. {
  370.     ItemVector weapons = getWeapons();
  371.     if(weapons.empty())
  372.         weapon = NULL;
  373.     else if(!weapon || weapons.size() == 1 || weapons[1] == weapon)
  374.         weapon = weapons[0];
  375.     else if(weapons[0] == weapon)
  376.         weapon = weapons[1];
  377.     else
  378.         weapon = NULL;
  379.  
  380.     if(weapon)
  381.         shootRange = weapon->getShootRange();
  382. }
  383.  
  384. WeaponType_t Player::getWeaponType()
  385. {
  386.     if(Item* item = getWeapon(false))
  387.         return item->getWeaponType();
  388.  
  389.     return WEAPON_NONE;
  390. }
  391.  
  392. int32_t Player::getWeaponSkill(const Item* item) const
  393. {
  394.     if(!item)
  395.         return getSkill(SKILL_FIST, SKILL_LEVEL);
  396.  
  397.     switch(item->getWeaponType())
  398.     {
  399.         case WEAPON_SWORD:
  400.             return getSkill(SKILL_SWORD, SKILL_LEVEL);
  401.  
  402.         case WEAPON_CLUB:
  403.             return getSkill(SKILL_CLUB, SKILL_LEVEL);
  404.  
  405.         case WEAPON_AXE:
  406.             return getSkill(SKILL_AXE, SKILL_LEVEL);
  407.  
  408.         case WEAPON_FIST:
  409.             return getSkill(SKILL_FIST, SKILL_LEVEL);
  410.  
  411.         case WEAPON_DIST:
  412.             return getSkill(SKILL_DIST, SKILL_LEVEL);
  413.  
  414.         default:
  415.             break;
  416.     }
  417.  
  418.     return 0;
  419. }
  420.  
  421. int32_t Player::getArmor() const
  422. {
  423.     int32_t i = SLOT_FIRST, armor = 0;
  424.     for(; i < SLOT_LAST; ++i)
  425.     {
  426.         if(Item* item = getInventoryItem((slots_t)i))
  427.             armor += item->getArmor();
  428.     }
  429.  
  430.     if(vocation->getMultiplier(MULTIPLIER_ARMOR) != 1.0)
  431.         return int32_t(armor * vocation->getMultiplier(MULTIPLIER_ARMOR));
  432.  
  433.     return armor;
  434. }
  435.  
  436. void Player::getShieldAndWeapon(const Item* &_shield, const Item* &_weapon) const
  437. {
  438.     _shield = NULL;
  439.     Item* item = NULL;
  440.     for(uint32_t slot = SLOT_RIGHT; slot <= SLOT_LEFT; ++slot)
  441.     {
  442.         if(!(item = getInventoryItem((slots_t)slot)) || item->getWeaponType() != WEAPON_SHIELD)
  443.             continue;
  444.  
  445.         if(!_shield || (_shield && item->getDefense() > _shield->getDefense()))
  446.             _shield = item;
  447.     }
  448.  
  449.     _weapon = weapon;
  450. }
  451.  
  452. int32_t Player::getDefense() const
  453. {
  454.     int32_t baseDefense = 5, defenseValue = 0, defenseSkill = 0, extraDefense = 0;
  455.     float defenseFactor = getDefenseFactor();
  456.  
  457.     const Item *_weapon = NULL, *_shield = NULL;
  458.     getShieldAndWeapon(_shield, _weapon);
  459.     if(_weapon)
  460.     {
  461.         extraDefense = _weapon->getExtraDefense();
  462.         defenseValue = baseDefense + _weapon->getDefense();
  463.         defenseSkill = getWeaponSkill(_weapon);
  464.     }
  465.  
  466.     if(_shield && _shield->getDefense() > defenseValue)
  467.     {
  468.         if(_shield->getExtraDefense() > extraDefense)
  469.             extraDefense = _shield->getExtraDefense();
  470.  
  471.         defenseValue = baseDefense + _shield->getDefense();
  472.         defenseSkill = getSkill(SKILL_SHIELD, SKILL_LEVEL);
  473.     }
  474.  
  475.     if(!defenseSkill)
  476.         return 0;
  477.  
  478.     defenseValue += extraDefense;
  479.     if(vocation->getMultiplier(MULTIPLIER_DEFENSE) != 1.0)
  480.         defenseValue = int32_t(defenseValue * vocation->getMultiplier(MULTIPLIER_DEFENSE));
  481.  
  482.     return ((int32_t)std::ceil(((float)(defenseSkill * (defenseValue * 0.015)) + (defenseValue * 0.1)) * defenseFactor));
  483. }
  484.  
  485. float Player::getAttackFactor() const
  486. {
  487.     switch(fightMode)
  488.     {
  489.         case FIGHTMODE_BALANCED:
  490.             return 1.2f;
  491.  
  492.         case FIGHTMODE_DEFENSE:
  493.             return 2.0f;
  494.  
  495.         case FIGHTMODE_ATTACK:
  496.         default:
  497.             break;
  498.     }
  499.  
  500.     return 1.0f;
  501. }
  502.  
  503. float Player::getDefenseFactor() const
  504. {
  505.     switch(fightMode)
  506.     {
  507.         case FIGHTMODE_BALANCED:
  508.             return 1.2f;
  509.  
  510.         case FIGHTMODE_DEFENSE:
  511.         {
  512.             if((OTSYS_TIME() - lastAttack) < getAttackSpeed()) //attacking will cause us to get into normal defense
  513.                 return 1.0f;
  514.  
  515.             return 2.0f;
  516.         }
  517.  
  518.         case FIGHTMODE_ATTACK:
  519.         default:
  520.             break;
  521.     }
  522.  
  523.     return 1.0f;
  524. }
  525.  
  526. void Player::sendIcons() const
  527. {
  528.     if(!client)
  529.         return;
  530.  
  531.     uint32_t icons = 0;
  532.     for(ConditionList::const_iterator it = conditions.begin(); it != conditions.end(); ++it)
  533.     {
  534.         if(!isSuppress((*it)->getType()))
  535.             icons |= (*it)->getIcons();
  536.     }
  537.  
  538.     if(getZone() == ZONE_PROTECTION)
  539.         icons |= ICON_PROTECTIONZONE;
  540.  
  541.     if(pzLocked)
  542.         icons |= ICON_PZ;
  543.  
  544.     client->sendIcons(icons);
  545.    
  546.     for(AutoList<ProtocolGame>::const_iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  547.         if(it->second->getPlayer() == this)
  548.             it->second->sendIcons(icons);
  549. }
  550.  
  551. void Player::updateInventoryWeight()
  552. {
  553.     inventoryWeight = 0.00;
  554.     if(hasFlag(PlayerFlag_HasInfiniteCapacity))
  555.         return;
  556.  
  557.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  558.     {
  559.         if(Item* item = getInventoryItem((slots_t)i))
  560.             inventoryWeight += item->getWeight();
  561.     }
  562. }
  563.  
  564. void Player::updateInventoryGoods(uint32_t itemId)
  565. {
  566.     if(Item::items[itemId].worth)
  567.     {
  568.         sendGoods();
  569.         return;
  570.     }
  571.  
  572.     for(ShopInfoList::iterator it = shopOffer.begin(); it != shopOffer.end(); ++it)
  573.     {
  574.         if(it->itemId != itemId)
  575.             continue;
  576.  
  577.         sendGoods();
  578.         break;
  579.     }
  580. }
  581.  
  582. int32_t Player::getPlayerInfo(playerinfo_t playerinfo) const
  583. {
  584.     switch(playerinfo)
  585.     {
  586.         case PLAYERINFO_LEVEL:
  587.             return level;
  588.         case PLAYERINFO_LEVELPERCENT:
  589.             return levelPercent;
  590.         case PLAYERINFO_MAGICLEVEL:
  591.             return std::max((int32_t)0, ((int32_t)magLevel + varStats[STAT_MAGICLEVEL]));
  592.         case PLAYERINFO_MAGICLEVELPERCENT:
  593.             return magLevelPercent;
  594.         case PLAYERINFO_HEALTH:
  595.             return health;
  596.         case PLAYERINFO_MAXHEALTH:
  597.             return std::max((int32_t)1, ((int32_t)healthMax + varStats[STAT_MAXHEALTH]));
  598.         case PLAYERINFO_MANA:
  599.             return mana;
  600.         case PLAYERINFO_MAXMANA:
  601.             return std::max((int32_t)0, ((int32_t)manaMax + varStats[STAT_MAXMANA]));
  602.         case PLAYERINFO_SOUL:
  603.             return std::max((int32_t)0, ((int32_t)soul + varStats[STAT_SOUL]));
  604.         default:
  605.             break;
  606.     }
  607.  
  608.     return 0;
  609. }
  610.  
  611. int32_t Player::getSkill(skills_t skilltype, skillsid_t skillinfo) const
  612. {
  613.     int32_t ret = skills[skilltype][skillinfo];
  614.     if(skillinfo == SKILL_LEVEL)
  615.         ret += varSkills[skilltype];
  616.  
  617.     return std::max((int32_t)0, ret);
  618. }
  619.  
  620. void Player::addSkillAdvance(skills_t skill, uint32_t count, bool useMultiplier/* = true*/)
  621. {
  622.     if(!count)
  623.         return;
  624.  
  625.     //player has reached max skill
  626.     uint32_t currReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL]),
  627.         nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  628.     if(currReqTries > nextReqTries)
  629.         return;
  630.  
  631.     if(useMultiplier)
  632.         count = uint32_t((double)count * rates[skill] * g_config.getDouble(ConfigManager::RATE_SKILL));
  633.  
  634.     std::stringstream s;
  635.     while(skills[skill][SKILL_TRIES] + count >= nextReqTries)
  636.     {
  637.         count -= nextReqTries - skills[skill][SKILL_TRIES];
  638.         skills[skill][SKILL_TRIES] = skills[skill][SKILL_PERCENT] = 0;
  639.         skills[skill][SKILL_LEVEL]++;
  640.  
  641.         s.str("");
  642.         s << "You advanced in " << getSkillName(skill);
  643.         if(g_config.getBool(ConfigManager::ADVANCING_SKILL_LEVEL))
  644.             s << " [" << skills[skill][SKILL_LEVEL] << "]";
  645.  
  646.         s << ".";
  647.         sendTextMessage(MSG_EVENT_ADVANCE, s.str().c_str());
  648.  
  649.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  650.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  651.             (*it)->executeAdvance(this, skill, (skills[skill][SKILL_LEVEL] - 1), skills[skill][SKILL_LEVEL]);
  652.  
  653.         currReqTries = nextReqTries;
  654.         nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  655.         if(currReqTries > nextReqTries)
  656.         {
  657.             count = 0;
  658.             break;
  659.         }
  660.     }
  661.  
  662.     if(count)
  663.         skills[skill][SKILL_TRIES] += count;
  664.  
  665.     //update percent
  666.     uint32_t newPercent = Player::getPercentLevel(skills[skill][SKILL_TRIES], nextReqTries);
  667.     if(skills[skill][SKILL_PERCENT] != newPercent)
  668.     {
  669.         skills[skill][SKILL_PERCENT] = newPercent;
  670.         sendSkills();
  671.     }
  672.     else if(!s.str().empty())
  673.         sendSkills();
  674. }
  675.  
  676. void Player::setVarStats(stats_t stat, int32_t modifier)
  677. {
  678.     varStats[stat] += modifier;
  679.     switch(stat)
  680.     {
  681.         case STAT_MAXHEALTH:
  682.         {
  683.             if(getHealth() > getMaxHealth())
  684.                 Creature::changeHealth(getMaxHealth() - getHealth());
  685.             else
  686.                 g_game.addCreatureHealth(this);
  687.  
  688.             break;
  689.         }
  690.  
  691.         case STAT_MAXMANA:
  692.         {
  693.             if(getMana() > getMaxMana())
  694.                 Creature::changeMana(getMaxMana() - getMana());
  695.  
  696.             break;
  697.         }
  698.  
  699.         default:
  700.             break;
  701.     }
  702. }
  703.  
  704. int32_t Player::getDefaultStats(stats_t stat)
  705. {
  706.     switch(stat)
  707.     {
  708.         case STAT_MAGICLEVEL:
  709.             return getMagicLevel() - getVarStats(STAT_MAGICLEVEL);
  710.         case STAT_MAXHEALTH:
  711.             return getMaxHealth() - getVarStats(STAT_MAXHEALTH);
  712.         case STAT_MAXMANA:
  713.             return getMaxMana() - getVarStats(STAT_MAXMANA);
  714.         case STAT_SOUL:
  715.             return getSoul() - getVarStats(STAT_SOUL);
  716.         default:
  717.             break;
  718.     }
  719.  
  720.     return 0;
  721. }
  722.  
  723. Container* Player::getContainer(uint32_t cid)
  724. {
  725.     for(ContainerVector::iterator it = containerVec.begin(); it != containerVec.end(); ++it)
  726.     {
  727.         if(it->first == cid)
  728.             return it->second;
  729.     }
  730.  
  731.     return NULL;
  732. }
  733.  
  734. int32_t Player::getContainerID(const Container* container) const
  735. {
  736.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  737.     {
  738.         if(cl->second == container)
  739.             return cl->first;
  740.     }
  741.  
  742.     return -1;
  743. }
  744.  
  745. void Player::addContainer(uint32_t cid, Container* container)
  746. {
  747. #ifdef __DEBUG__
  748.     std::clog << getName() << ", addContainer: " << (int32_t)cid << std::endl;
  749. #endif
  750.     if(cid > 0xF)
  751.         return;
  752.  
  753.     for(ContainerVector::iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  754.     {
  755.         if(cl->first == cid)
  756.         {
  757.             cl->second = container;
  758.             return;
  759.         }
  760.     }
  761.  
  762.     containerVec.push_back(std::make_pair(cid, container));
  763. }
  764.  
  765. void Player::closeContainer(uint32_t cid)
  766. {
  767.     for(ContainerVector::iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  768.     {
  769.         if(cl->first == cid)
  770.         {
  771.             containerVec.erase(cl);
  772.             break;
  773.         }
  774.     }
  775. #ifdef __DEBUG__
  776.  
  777.     std::clog << getName() << ", closeContainer: " << (int32_t)cid << std::endl;
  778. #endif
  779. }
  780.  
  781. bool Player::canOpenCorpse(uint32_t ownerId)
  782. {
  783.     return guid == ownerId || (party && party->canOpenCorpse(ownerId)) || hasCustomFlag(PlayerCustomFlag_GamemasterPrivileges);
  784. }
  785.  
  786. uint16_t Player::getLookCorpse() const
  787. {
  788.     if(sex % 2)
  789.         return ITEM_MALE_CORPSE;
  790.  
  791.     return ITEM_FEMALE_CORPSE;
  792. }
  793.  
  794. void Player::dropLoot(Container* corpse)
  795. {
  796.     if(!corpse || lootDrop != LOOT_DROP_FULL)
  797.         return;
  798.  
  799.     uint32_t loss = lossPercent[LOSS_CONTAINERS];
  800.     if(g_config.getBool(ConfigManager::BLESSINGS))
  801.     {
  802.         uint32_t start = g_config.getNumber(ConfigManager::BLESS_REDUCTION_BASE), bless = getBlessings();
  803.         while(bless > 0 && loss > 0)
  804.         {
  805.             loss -= start;
  806.             start -= g_config.getNumber(ConfigManager::BLESS_REDUCTION_DECREMENT);
  807.             bless--;
  808.         }
  809.     }
  810.  
  811.     uint32_t itemLoss = (uint32_t)std::floor((5. + loss) * lossPercent[LOSS_ITEMS] / 1000.);
  812.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  813.     {
  814.         Item* item = inventory[i];
  815.         if(!item)
  816.             continue;
  817.  
  818.         uint32_t tmp = random_range(1, 100);
  819.         if(skull > SKULL_WHITE || (item->getContainer() && tmp < loss) || (!item->getContainer() && tmp < itemLoss))
  820.         {
  821.             g_game.internalMoveItem(NULL, this, corpse, INDEX_WHEREEVER, item, item->getItemCount(), 0);
  822.             sendRemoveInventoryItem((slots_t)i, inventory[(slots_t)i]);
  823.         }
  824.     }
  825. }
  826.  
  827. bool Player::setStorage(const uint32_t key, const std::string& value)
  828. {
  829.     if(!IS_IN_KEYRANGE(key, RESERVED_RANGE))
  830.         return Creature::setStorage(key, value);
  831.  
  832.     if(IS_IN_KEYRANGE(key, OUTFITS_RANGE))
  833.     {
  834.         uint32_t lookType = atoi(value.c_str()) >> 16, addons = atoi(value.c_str()) & 0xFF;
  835.         if(addons < 4)
  836.         {
  837.             Outfit outfit;
  838.             if(Outfits::getInstance()->getOutfit(lookType, outfit))
  839.                 return addOutfit(outfit.outfitId, addons);
  840.         }
  841.         else
  842.             std::clog << "[Warning - Player::setStorage] Invalid addons value key: " << key
  843.                 << ", value: " << value << " for player: " << getName() << std::endl;
  844.     }
  845.     else if(IS_IN_KEYRANGE(key, OUTFITSID_RANGE))
  846.     {
  847.         uint32_t outfitId = atoi(value.c_str()) >> 16, addons = atoi(value.c_str()) & 0xFF;
  848.         if(addons < 4)
  849.             return addOutfit(outfitId, addons);
  850.         else
  851.             std::clog << "[Warning - Player::setStorage] Invalid addons value key: " << key
  852.                 << ", value: " << value << " for player: " << getName() << std::endl;
  853.     }
  854.     else
  855.         std::clog << "[Warning - Player::setStorage] Unknown reserved key: " << key << " for player: " << getName() << std::endl;
  856.  
  857.     return false;
  858. }
  859.  
  860. void Player::eraseStorage(const uint32_t key)
  861. {
  862.     Creature::eraseStorage(key);
  863.     if(IS_IN_KEYRANGE(key, RESERVED_RANGE))
  864.         std::clog << "[Warning - Player::eraseStorage] Unknown reserved key: " << key << " for player: " << name << std::endl;
  865. }
  866.  
  867. bool Player::canSee(const Position& pos) const
  868. {
  869.     if(client)
  870.         return client->canSee(pos);
  871.  
  872.     return false;
  873. }
  874.  
  875. bool Player::canSeeCreature(const Creature* creature) const
  876. {
  877.     if(creature == this)
  878.         return true;
  879.  
  880.     if(const Player* player = creature->getPlayer())
  881.         return !player->isGhost() || getGhostAccess() >= player->getGhostAccess();
  882.  
  883.     return !creature->isInvisible() || canSeeInvisibility();
  884. }
  885.  
  886. bool Player::canWalkthrough(const Creature* creature) const
  887. {
  888.     if(creature == this || hasCustomFlag(PlayerCustomFlag_CanWalkthrough) || creature->isWalkable() ||
  889.         (creature->getMaster() && creature->getMaster() != this && canWalkthrough(creature->getMaster())))
  890.         return true;
  891.  
  892.     const Player* player = creature->getPlayer();
  893.     if(!player)
  894.         return false;
  895.  
  896.     if((((g_game.getWorldType() == WORLDTYPE_OPTIONAL && !player->isEnemy(this, true) &&
  897.         player->getVocation()->isAttackable()) || player->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) || (player->getVocation()->isAttackable() &&
  898.         player->getLevel() < (uint32_t)g_config.getNumber(ConfigManager::PROTECTION_LEVEL))) && player->getTile()->ground &&
  899.         Item::items[player->getTile()->ground->getID()].walkStack) && (!player->hasCustomFlag(PlayerCustomFlag_GamemasterPrivileges)
  900.         || player->getAccess() <= getAccess()))
  901.         return true;
  902.  
  903.     return (player->isGhost() && getGhostAccess() < player->getGhostAccess())
  904.         || (isGhost() && getGhostAccess() > player->getGhostAccess());
  905. }
  906.  
  907. Depot* Player::getDepot(uint32_t depotId, bool autoCreateDepot)
  908. {
  909.     DepotMap::iterator it = depots.find(depotId);
  910.     if(it != depots.end())
  911.         return it->second.first;
  912.  
  913.     //create a new depot?
  914.     if(autoCreateDepot)
  915.     {
  916.         Item* locker = Item::CreateItem(ITEM_LOCKER);
  917.         if(Container* container = locker->getContainer())
  918.         {
  919.             if(Depot* depot = container->getDepot())
  920.             {
  921.                 container->__internalAddThing(Item::CreateItem(ITEM_DEPOT));
  922.                 addDepot(depot, depotId);
  923.                 return depot;
  924.             }
  925.         }
  926.  
  927.         g_game.freeThing(locker);
  928.         std::clog << "Failure: Creating a new depot with id: " << depotId <<
  929.             ", for player: " << getName() << std::endl;
  930.     }
  931.  
  932.     return NULL;
  933. }
  934.  
  935. bool Player::addDepot(Depot* depot, uint32_t depotId)
  936. {
  937.     if(getDepot(depotId, false))
  938.         return false;
  939.  
  940.     depots[depotId] = std::make_pair(depot, false);
  941.     depot->setMaxDepotLimit((group != NULL ? group->getDepotLimit(isPremium()) : 1000));
  942.     return true;
  943. }
  944.  
  945. void Player::useDepot(uint32_t depotId, bool value)
  946. {
  947.     DepotMap::iterator it = depots.find(depotId);
  948.     if(it != depots.end())
  949.         depots[depotId] = std::make_pair(it->second.first, value);
  950. }
  951.  
  952. void Player::sendCancelMessage(ReturnValue message) const
  953. {
  954.     switch(message)
  955.     {
  956.         case RET_DESTINATIONOUTOFREACH:
  957.             sendCancel("Destination is out of reach.");
  958.             break;
  959.  
  960.         case RET_NOTMOVEABLE:
  961.             sendCancel("You cannot move this object.");
  962.             break;
  963.  
  964.         case RET_DROPTWOHANDEDITEM:
  965.             sendCancel("Drop the double-handed object first.");
  966.             break;
  967.  
  968.         case RET_BOTHHANDSNEEDTOBEFREE:
  969.             sendCancel("Both hands need to be free.");
  970.             break;
  971.  
  972.         case RET_CANNOTBEDRESSED:
  973.             sendCancel("You cannot dress this object there.");
  974.             break;
  975.  
  976.         case RET_PUTTHISOBJECTINYOURHAND:
  977.             sendCancel("Put this object in your hand.");
  978.             break;
  979.  
  980.         case RET_PUTTHISOBJECTINBOTHHANDS:
  981.             sendCancel("Put this object in both hands.");
  982.             break;
  983.  
  984.         case RET_CANONLYUSEONEWEAPON:
  985.             sendCancel("You may use only one weapon.");
  986.             break;
  987.  
  988.         case RET_TOOFARAWAY:
  989.             sendCancel("Too far away.");
  990.             break;
  991.  
  992.         case RET_FIRSTGODOWNSTAIRS:
  993.             sendCancel("First go downstairs.");
  994.             break;
  995.  
  996.         case RET_FIRSTGOUPSTAIRS:
  997.             sendCancel("First go upstairs.");
  998.             break;
  999.  
  1000.         case RET_NOTENOUGHCAPACITY:
  1001.             sendCancel("This object is too heavy for you to carry.");
  1002.             break;
  1003.  
  1004.         case RET_CONTAINERNOTENOUGHROOM:
  1005.             sendCancel("You cannot put more objects in this container.");
  1006.             break;
  1007.  
  1008.         case RET_NEEDEXCHANGE:
  1009.         case RET_NOTENOUGHROOM:
  1010.             sendCancel("There is not enough room.");
  1011.             break;
  1012.  
  1013.         case RET_CANNOTPICKUP:
  1014.             sendCancel("You cannot take this object.");
  1015.             break;
  1016.  
  1017.         case RET_CANNOTTHROW:
  1018.             sendCancel("You cannot throw there.");
  1019.             break;
  1020.  
  1021.         case RET_THEREISNOWAY:
  1022.             sendCancel("There is no way.");
  1023.             break;
  1024.  
  1025.         case RET_THISISIMPOSSIBLE:
  1026.             sendCancel("This is impossible.");
  1027.             break;
  1028.  
  1029.         case RET_PLAYERISPZLOCKED:
  1030.             sendCancel("You cannot enter a protection zone after attacking another player.");
  1031.             break;
  1032.  
  1033.         case RET_PLAYERISNOTINVITED:
  1034.             sendCancel("You are not invited.");
  1035.             break;
  1036.  
  1037.         case RET_CREATUREDOESNOTEXIST:
  1038.             sendCancel("Creature does not exist.");
  1039.             break;
  1040.  
  1041.         case RET_DEPOTISFULL:
  1042.             sendCancel("You cannot put more items in this depot.");
  1043.             break;
  1044.  
  1045.         case RET_CANNOTUSETHISOBJECT:
  1046.             sendCancel("You cannot use this object.");
  1047.             break;
  1048.  
  1049.         case RET_PLAYERWITHTHISNAMEISNOTONLINE:
  1050.             sendCancel("A player with this name is not online.");
  1051.             break;
  1052.  
  1053.         case RET_NOTREQUIREDLEVELTOUSERUNE:
  1054.             sendCancel("You do not have the required magic level to use this rune.");
  1055.             break;
  1056.  
  1057.         case RET_YOUAREALREADYTRADING:
  1058.             sendCancel("You are already trading.");
  1059.             break;
  1060.  
  1061.         case RET_THISPLAYERISALREADYTRADING:
  1062.             sendCancel("This player is already trading.");
  1063.             break;
  1064.  
  1065.         case RET_YOUMAYNOTLOGOUTDURINGAFIGHT:
  1066.             sendCancel("You may not logout during or immediately after a fight!");
  1067.             break;
  1068.  
  1069.         case RET_DIRECTPLAYERSHOOT:
  1070.             sendCancel("You are not allowed to shoot directly on players.");
  1071.             break;
  1072.  
  1073.         case RET_NOTENOUGHLEVEL:
  1074.             sendCancel("You do not have enough level.");
  1075.             break;
  1076.  
  1077.         case RET_NOTENOUGHMAGICLEVEL:
  1078.             sendCancel("You do not have enough magic level.");
  1079.             break;
  1080.  
  1081.         case RET_NOTENOUGHMANA:
  1082.             sendCancel("You do not have enough mana.");
  1083.             break;
  1084.  
  1085.         case RET_NOTENOUGHSOUL:
  1086.             sendCancel("You do not have enough soul.");
  1087.             break;
  1088.  
  1089.         case RET_YOUAREEXHAUSTED:
  1090.             sendCancel("You are exhausted.");
  1091.             break;
  1092.  
  1093.         case RET_CANONLYUSETHISRUNEONCREATURES:
  1094.             sendCancel("You can only use this rune on creatures.");
  1095.             break;
  1096.  
  1097.         case RET_PLAYERISNOTREACHABLE:
  1098.             sendCancel("Player is not reachable.");
  1099.             break;
  1100.  
  1101.         case RET_CREATUREISNOTREACHABLE:
  1102.             sendCancel("Creature is not reachable.");
  1103.             break;
  1104.  
  1105.         case RET_ACTIONNOTPERMITTEDINPROTECTIONZONE:
  1106.             sendCancel("This action is not permitted in a protection zone.");
  1107.             break;
  1108.  
  1109.         case RET_YOUMAYNOTATTACKTHISPLAYER:
  1110.             sendCancel("You may not attack this player.");
  1111.             break;
  1112.  
  1113.         case RET_YOUMAYNOTATTACKTHISCREATURE:
  1114.             sendCancel("You may not attack this creature.");
  1115.             break;
  1116.  
  1117.         case RET_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE:
  1118.             sendCancel("You may not attack a person in a protection zone.");
  1119.             break;
  1120.  
  1121.         case RET_YOUMAYNOTATTACKAPERSONWHILEINPROTECTIONZONE:
  1122.             sendCancel("You may not attack a person while you are in a protection zone.");
  1123.             break;
  1124.  
  1125.         case RET_YOUCANONLYUSEITONCREATURES:
  1126.             sendCancel("You can only use it on creatures.");
  1127.             break;
  1128.  
  1129.         case RET_TURNSECUREMODETOATTACKUNMARKEDPLAYERS:
  1130.             sendCancel("Turn secure mode off if you really want to attack unmarked players.");
  1131.             break;
  1132.  
  1133.         case RET_YOUNEEDPREMIUMACCOUNT:
  1134.             sendCancel("You need a premium account.");
  1135.             break;
  1136.  
  1137.         case RET_YOUNEEDTOLEARNTHISSPELL:
  1138.             sendCancel("You need to learn this spell first.");
  1139.             break;
  1140.  
  1141.         case RET_YOURVOCATIONCANNOTUSETHISSPELL:
  1142.             sendCancel("Your vocation cannot use this spell.");
  1143.             break;
  1144.  
  1145.         case RET_YOUNEEDAWEAPONTOUSETHISSPELL:
  1146.             sendCancel("You need to equip a weapon to use this spell.");
  1147.             break;
  1148.  
  1149.         case RET_PLAYERISPZLOCKEDLEAVEPVPZONE:
  1150.             sendCancel("You cannot leave a pvp zone after attacking another player.");
  1151.             break;
  1152.  
  1153.         case RET_PLAYERISPZLOCKEDENTERPVPZONE:
  1154.             sendCancel("You cannot enter a pvp zone after attacking another player.");
  1155.             break;
  1156.  
  1157.         case RET_ACTIONNOTPERMITTEDINANOPVPZONE:
  1158.             sendCancel("This action is not permitted in a safe zone.");
  1159.             break;
  1160.  
  1161.         case RET_YOUCANNOTLOGOUTHERE:
  1162.             sendCancel("You cannot logout here.");
  1163.             break;
  1164.  
  1165.         case RET_YOUNEEDAMAGICITEMTOCASTSPELL:
  1166.             sendCancel("You need a magic item to cast this spell.");
  1167.             break;
  1168.  
  1169.         case RET_CANNOTCONJUREITEMHERE:
  1170.             sendCancel("You cannot conjure items here.");
  1171.             break;
  1172.  
  1173.         case RET_YOUNEEDTOSPLITYOURSPEARS:
  1174.             sendCancel("You need to split your spears first.");
  1175.             break;
  1176.  
  1177.         case RET_NAMEISTOOAMBIGUOUS:
  1178.             sendCancel("Name is too ambiguous.");
  1179.             break;
  1180.  
  1181.         case RET_CANONLYUSEONESHIELD:
  1182.             sendCancel("You may use only one shield.");
  1183.             break;
  1184.  
  1185.         case RET_YOUARENOTTHEOWNER:
  1186.             sendCancel("You are not the owner.");
  1187.             break;
  1188.  
  1189.         case RET_YOUMAYNOTCASTAREAONBLACKSKULL:
  1190.             sendCancel("You may not cast area spells while you have a black skull.");
  1191.             break;
  1192.  
  1193.         case RET_TILEISFULL:
  1194.             sendCancel("You cannot add more items on this tile.");
  1195.             break;
  1196.  
  1197.         case RET_YOUHAVETOWAIT:
  1198.             sendCancel("Sorry, you have to wait.");
  1199.             break;
  1200.  
  1201.         case RET_DONTSHOWMESSAGE:
  1202.             break;
  1203.  
  1204.         case RET_NOTPOSSIBLE:
  1205.         default:
  1206.             sendCancel("Sorry, not possible.");
  1207.             break;
  1208.     }
  1209. }
  1210.  
  1211. Item* Player::getWriteItem(uint32_t& _windowTextId, uint16_t& _maxWriteLen)
  1212. {
  1213.     _windowTextId = windowTextId;
  1214.     _maxWriteLen = maxWriteLen;
  1215.     return writeItem;
  1216. }
  1217.  
  1218. void Player::setWriteItem(Item* item, uint16_t _maxWriteLen/* = 0*/)
  1219. {
  1220.     windowTextId++;
  1221.     if(writeItem)
  1222.         writeItem->unRef();
  1223.  
  1224.     if(item)
  1225.     {
  1226.         writeItem = item;
  1227.         maxWriteLen = _maxWriteLen;
  1228.         writeItem->addRef();
  1229.     }
  1230.     else
  1231.     {
  1232.         writeItem = NULL;
  1233.         maxWriteLen = 0;
  1234.     }
  1235. }
  1236.  
  1237. House* Player::getEditHouse(uint32_t& _windowTextId, uint32_t& _listId)
  1238. {
  1239.     _windowTextId = windowTextId;
  1240.     _listId = editListId;
  1241.     return editHouse;
  1242. }
  1243.  
  1244. void Player::setEditHouse(House* house, uint32_t listId/* = 0*/)
  1245. {
  1246.     windowTextId++;
  1247.     editHouse = house;
  1248.     editListId = listId;
  1249. }
  1250.  
  1251. void Player::sendHouseWindow(House* house, uint32_t listId) const
  1252. {
  1253.     if(!client)
  1254.         return;
  1255.  
  1256.     std::string text;
  1257.     if(house->getAccessList(listId, text))
  1258.         client->sendHouseWindow(windowTextId, house, listId, text);
  1259. }
  1260.  
  1261. void Player::sendCreatureChangeVisible(const Creature* creature, Visible_t visible)
  1262. {
  1263.     if(!client)
  1264.         return;
  1265.  
  1266.     const Player* player = creature->getPlayer();
  1267.     if(player == this || (player && (visible < VISIBLE_GHOST_APPEAR || getGhostAccess() >= player->getGhostAccess()))
  1268.         || (!player && canSeeInvisibility()))
  1269.         sendCreatureChangeOutfit(creature, creature->getCurrentOutfit());
  1270.     else if(visible == VISIBLE_DISAPPEAR || visible == VISIBLE_GHOST_DISAPPEAR)
  1271.         sendCreatureDisappear(creature, creature->getTile()->getClientIndexOfThing(this, creature));
  1272.     else
  1273.         sendCreatureAppear(creature);
  1274. }
  1275.  
  1276. void Player::sendAddContainerItem(const Container* container, const Item* item)
  1277. {
  1278.     if(!client)
  1279.         return;
  1280.  
  1281.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1282.     {
  1283.         if(cl->second == container)
  1284.         {
  1285.             client->sendAddContainerItem(cl->first, item);
  1286.             for(AutoList<ProtocolGame>::iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  1287.                 if(it->second->getPlayer() == this)
  1288.                     it->second->sendAddContainerItem(cl->first, item);
  1289.         }
  1290.     }
  1291. }
  1292.  
  1293. void Player::sendUpdateContainerItem(const Container* container, uint8_t slot, const Item*, const Item* newItem)
  1294. {
  1295.     if(!client)
  1296.         return;
  1297.  
  1298.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1299.     {
  1300.         if(cl->second == container)
  1301.         {
  1302.             client->sendUpdateContainerItem(cl->first, slot, newItem);
  1303.             for(AutoList<ProtocolGame>::iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  1304.                 if(it->second->getPlayer() == this)
  1305.                     it->second->sendUpdateContainerItem(cl->first, slot, newItem);
  1306.         }
  1307.     }
  1308. }
  1309.  
  1310. void Player::sendRemoveContainerItem(const Container* container, uint8_t slot, const Item*)
  1311. {
  1312.     if(!client)
  1313.         return;
  1314.  
  1315.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1316.     {
  1317.         if(cl->second == container)
  1318.         {
  1319.             client->sendRemoveContainerItem(cl->first, slot);
  1320.             for(AutoList<ProtocolGame>::iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  1321.                 if(it->second->getPlayer() == this)
  1322.                     it->second->sendRemoveContainerItem(cl->first, slot);
  1323.         }
  1324.     }
  1325. }
  1326.  
  1327. void Player::onUpdateTileItem(const Tile* tile, const Position& pos, const Item* oldItem,
  1328.     const ItemType& oldType, const Item* newItem, const ItemType& newType)
  1329. {
  1330.     Creature::onUpdateTileItem(tile, pos, oldItem, oldType, newItem, newType);
  1331.     if(oldItem != newItem)
  1332.         onRemoveTileItem(tile, pos, oldType, oldItem);
  1333.  
  1334.     if(tradeState != TRADE_TRANSFER && tradeItem && oldItem == tradeItem)
  1335.         g_game.internalCloseTrade(this);
  1336. }
  1337.  
  1338. void Player::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, const Item* item)
  1339. {
  1340.     Creature::onRemoveTileItem(tile, pos, iType, item);
  1341.     if(tradeState == TRADE_TRANSFER)
  1342.         return;
  1343.  
  1344.     checkTradeState(item);
  1345.     if(tradeItem)
  1346.     {
  1347.         const Container* container = item->getContainer();
  1348.         if(container && container->isHoldingItem(tradeItem))
  1349.             g_game.internalCloseTrade(this);
  1350.     }
  1351. }
  1352.  
  1353. void Player::onCreatureAppear(const Creature* creature)
  1354. {
  1355.     Creature::onCreatureAppear(creature);
  1356.     if(creature != this)
  1357.         return;
  1358.  
  1359.     Item* item = NULL;
  1360.     for(int32_t slot = SLOT_FIRST; slot < SLOT_LAST; ++slot)
  1361.     {
  1362.         if(!(item = getInventoryItem((slots_t)slot)))
  1363.             continue;
  1364.  
  1365.         item->__startDecaying();
  1366.         g_moveEvents->onPlayerEquip(this, item, (slots_t)slot, false);
  1367.     }
  1368.  
  1369.     updateWeapon();
  1370.     if(BedItem* bed = Beds::getInstance()->getBedBySleeper(guid))
  1371.         bed->wakeUp();
  1372.  
  1373.     Outfit outfit;
  1374.     if(Outfits::getInstance()->getOutfit(defaultOutfit.lookType, outfit))
  1375.         outfitAttributes = Outfits::getInstance()->addAttributes(getID(), outfit.outfitId, sex, defaultOutfit.lookAddons);
  1376.  
  1377.     if(lastLogout && stamina < STAMINA_MAX)
  1378.     {
  1379.         int64_t ticks = (int64_t)time(NULL) - lastLogout - 600;
  1380.         if(ticks > 0)
  1381.         {
  1382.             ticks = (int64_t)((double)(ticks * 1000) / g_config.getDouble(ConfigManager::RATE_STAMINA_GAIN));
  1383.             int64_t premium = g_config.getNumber(ConfigManager::STAMINA_LIMIT_TOP) * STAMINA_MULTIPLIER, period = ticks;
  1384.             if((int64_t)stamina <= premium)
  1385.             {
  1386.                 period += stamina;
  1387.                 if(period > premium)
  1388.                     period -= premium;
  1389.                 else
  1390.                     period = 0;
  1391.  
  1392.                 useStamina(ticks - period);
  1393.             }
  1394.  
  1395.             if(period > 0)
  1396.             {
  1397.                 ticks = (int64_t)((g_config.getDouble(ConfigManager::RATE_STAMINA_GAIN) * period)
  1398.                     / g_config.getDouble(ConfigManager::RATE_STAMINA_THRESHOLD));
  1399.                 if(stamina + ticks > STAMINA_MAX)
  1400.                     ticks = STAMINA_MAX - stamina;
  1401.  
  1402.                 useStamina(ticks);
  1403.             }
  1404.  
  1405.             sendStats();
  1406.         }
  1407.     }
  1408.  
  1409.     g_game.checkPlayersRecord(this);
  1410.     if(!isGhost())
  1411.         IOLoginData::getInstance()->updateOnlineStatus(guid, true);
  1412.  
  1413.     if(g_config.getBool(ConfigManager::DISPLAY_LOGGING))
  1414.         std::clog << name << " has logged in." << std::endl;
  1415. }
  1416.  
  1417. void Player::onAttackedCreatureDisappear(bool isLogout)
  1418. {
  1419.     sendCancelTarget();
  1420.     if(!isLogout)
  1421.         sendTextMessage(MSG_STATUS_SMALL, "Target lost.");
  1422. }
  1423.  
  1424. void Player::onFollowCreatureDisappear(bool isLogout)
  1425. {
  1426.     sendCancelTarget();
  1427.     if(!isLogout)
  1428.         sendTextMessage(MSG_STATUS_SMALL, "Target lost.");
  1429. }
  1430.  
  1431. void Player::onChangeZone(ZoneType_t zone)
  1432. {
  1433.     if(attackedCreature && zone == ZONE_PROTECTION && !hasFlag(PlayerFlag_IgnoreProtectionZone))
  1434.     {
  1435.         setAttackedCreature(NULL);
  1436.         onAttackedCreatureDisappear(false);
  1437.     }
  1438.     sendIcons();
  1439. }
  1440.  
  1441. void Player::onAttackedCreatureChangeZone(ZoneType_t zone)
  1442. {
  1443.     if(zone == ZONE_PROTECTION && !hasFlag(PlayerFlag_IgnoreProtectionZone))
  1444.     {
  1445.         setAttackedCreature(NULL);
  1446.         onAttackedCreatureDisappear(false);
  1447.     }
  1448.     else if(zone == ZONE_OPTIONAL && attackedCreature->getPlayer() && !hasFlag(PlayerFlag_IgnoreProtectionZone))
  1449.     {
  1450.         setAttackedCreature(NULL);
  1451.         onAttackedCreatureDisappear(false);
  1452.     }
  1453.     else if(zone == ZONE_OPEN && g_game.getWorldType() == WORLDTYPE_OPTIONAL && attackedCreature->getPlayer()
  1454.         && !attackedCreature->getPlayer()->isEnemy(this, true)
  1455.         )
  1456.     {
  1457.         //attackedCreature can leave a pvp zone if not pzlocked
  1458.         setAttackedCreature(NULL);
  1459.         onAttackedCreatureDisappear(false);
  1460.     }
  1461. }
  1462.  
  1463. void Player::onCreatureDisappear(const Creature* creature, bool isLogout)
  1464. {
  1465.     Creature::onCreatureDisappear(creature, isLogout);
  1466.     if(creature != this)
  1467.         return;
  1468.  
  1469.     if(isLogout)
  1470.     {
  1471.         loginPosition = getPosition();
  1472.         lastLogout = time(NULL);
  1473.     }
  1474.  
  1475.     if(eventWalk)
  1476.         setFollowCreature(NULL);
  1477.  
  1478.     closeShopWindow();
  1479.     if(tradePartner)
  1480.         g_game.internalCloseTrade(this);
  1481.  
  1482.     clearPartyInvitations();
  1483.     if(party)
  1484.         party->leave(this);
  1485.  
  1486.     g_game.cancelRuleViolation(this);
  1487.     if(hasFlag(PlayerFlag_CanAnswerRuleViolations))
  1488.     {
  1489.         PlayerVector closeReportList;
  1490.         for(RuleViolationsMap::const_iterator it = g_game.getRuleViolations().begin(); it != g_game.getRuleViolations().end(); ++it)
  1491.         {
  1492.             if(it->second->gamemaster == this)
  1493.                 closeReportList.push_back(it->second->reporter);
  1494.         }
  1495.  
  1496.         for(PlayerVector::iterator it = closeReportList.begin(); it != closeReportList.end(); ++it)
  1497.             g_game.closeRuleViolation(*it);
  1498.     }
  1499.  
  1500.     g_chat.removeUserFromAllChannels(this);
  1501.     if(!isGhost())
  1502.         IOLoginData::getInstance()->updateOnlineStatus(guid, false);
  1503.  
  1504.     if(g_config.getBool(ConfigManager::DISPLAY_LOGGING))
  1505.         std::clog << getName() << " has logged out." << std::endl;
  1506.  
  1507.     bool saved = false;
  1508.     for(uint32_t tries = 0; !saved && tries < 3; ++tries)
  1509.     {
  1510.         if(IOLoginData::getInstance()->savePlayer(this))
  1511.             saved = true;
  1512. #ifdef __DEBUG__
  1513.         else
  1514.             std::clog << "Error while saving player: " << getName() << ", strike " << tries << "." << std::endl;
  1515. #endif
  1516.     }
  1517.  
  1518.     if(!saved)
  1519. #ifndef __DEBUG__
  1520.         std::clog << "Error while saving player: " << getName() << "." << std::endl;
  1521. #else
  1522.         std::clog << "Player " << getName() << " couldn't be saved." << std::endl;
  1523. #endif
  1524. }
  1525.  
  1526. void Player::openShopWindow()
  1527. {
  1528.     sendShop();
  1529.     sendGoods();
  1530. }
  1531.  
  1532. void Player::closeShopWindow(bool send/* = true*/, Npc* npc/* = NULL*/, int32_t onBuy/* = -1*/, int32_t onSell/* = -1*/)
  1533. {
  1534.     if(npc || (npc = getShopOwner(onBuy, onSell)))
  1535.         npc->onPlayerEndTrade(this, onBuy, onSell);
  1536.  
  1537.     if(shopOwner)
  1538.     {
  1539.         shopOwner = NULL;
  1540.         if(send)
  1541.             sendCloseShop();
  1542.     }
  1543.  
  1544.     purchaseCallback = saleCallback = -1;
  1545.     shopOffer.clear();
  1546. }
  1547.  
  1548. bool Player::canShopItem(uint16_t itemId, uint8_t subType, ShopEvent_t event)
  1549. {
  1550.     for(ShopInfoList::iterator sit = shopOffer.begin(); sit != shopOffer.end(); ++sit)
  1551.     {
  1552.         if(sit->itemId != itemId || ((event != SHOPEVENT_BUY || sit->buyPrice < 0)
  1553.             && (event != SHOPEVENT_SELL || sit->sellPrice < 0)))
  1554.             continue;
  1555.  
  1556.         if(event == SHOPEVENT_SELL)
  1557.             return true;
  1558.  
  1559.         const ItemType& it = Item::items[id];
  1560.         if(it.isFluidContainer() || it.isSplash())
  1561.             return sit->subType == subType;
  1562.  
  1563.         return true;
  1564.     }
  1565.  
  1566.     return false;
  1567. }
  1568.  
  1569. void Player::onWalk(Direction& dir)
  1570. {
  1571.     Creature::onWalk(dir);
  1572.     setNextActionTask(NULL);
  1573. }
  1574.  
  1575. void Player::onCreatureMove(const Creature* creature, const Tile* newTile, const Position& newPos,
  1576.     const Tile* oldTile, const Position& oldPos, bool teleport)
  1577. {
  1578.     Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport);
  1579.     if(creature != this)
  1580.         return;
  1581.  
  1582.     if(getParty())
  1583.         getParty()->updateSharedExperience();
  1584.  
  1585.     //check if we should close trade
  1586.     if(tradeState != TRADE_TRANSFER && ((tradeItem && !Position::areInRange<1,1,0>(tradeItem->getPosition(), getPosition()))
  1587.         || (tradePartner && !Position::areInRange<2,2,0>(tradePartner->getPosition(), getPosition()))))
  1588.         g_game.internalCloseTrade(this);
  1589.  
  1590.     if((teleport || oldPos.z != newPos.z) && !hasCustomFlag(PlayerCustomFlag_CanStairhop))
  1591.     {
  1592.         int32_t ticks = g_config.getNumber(ConfigManager::STAIRHOP_DELAY);
  1593.         if(ticks > 0)
  1594.         {
  1595.             addExhaust(ticks, EXHAUST_COMBAT);
  1596.             if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks))
  1597.                 addCondition(condition);
  1598.         }
  1599.     }
  1600.  
  1601.     // unset editing house
  1602.     if (editHouse && !newTile->hasFlag(TILESTATE_HOUSE))
  1603.         editHouse = NULL;
  1604. }
  1605.  
  1606. void Player::onAddContainerItem(const Container*, const Item* item)
  1607. {
  1608.     checkTradeState(item);
  1609. }
  1610.  
  1611. void Player::onUpdateContainerItem(const Container* container, uint8_t slot,
  1612.     const Item* oldItem, const ItemType&, const Item* newItem, const ItemType&)
  1613. {
  1614.     if(oldItem != newItem)
  1615.         onRemoveContainerItem(container, slot, oldItem);
  1616.  
  1617.     if(tradeState != TRADE_TRANSFER)
  1618.         checkTradeState(oldItem);
  1619. }
  1620.  
  1621. void Player::onRemoveContainerItem(const Container* container, uint8_t, const Item* item)
  1622. {
  1623.     if(tradeState == TRADE_TRANSFER)
  1624.         return;
  1625.  
  1626.     checkTradeState(item);
  1627.     if(tradeItem)
  1628.     {
  1629.         if(tradeItem->getParent() != container && container->isHoldingItem(tradeItem))
  1630.             g_game.internalCloseTrade(this);
  1631.     }
  1632. }
  1633.  
  1634. void Player::onCloseContainer(const Container* container)
  1635. {
  1636.     if(!client)
  1637.         return;
  1638.  
  1639.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1640.     {
  1641.         if(cl->second == container)
  1642.         {
  1643.             client->sendCloseContainer(cl->first);
  1644.             for(AutoList<ProtocolGame>::iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  1645.                 if(it->second->getPlayer() == this)
  1646.                     it->second->sendCloseContainer(cl->first);
  1647.         }
  1648.     }
  1649. }
  1650.  
  1651. void Player::onSendContainer(const Container* container)
  1652. {
  1653.     if(!client)
  1654.         return;
  1655.  
  1656.     bool hasParent = dynamic_cast<const Container*>(container->getParent()) != NULL;
  1657.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1658.     {
  1659.         if(cl->second == container)
  1660.         {
  1661.             client->sendContainer(cl->first, container, hasParent);
  1662.             for(AutoList<ProtocolGame>::iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  1663.                 if(it->second->getPlayer() == this)
  1664.                     it->second->sendContainer(cl->first, container, hasParent);
  1665.         }
  1666.     }
  1667. }
  1668.  
  1669. void Player::onUpdateInventoryItem(slots_t slot, Item* oldItem, const ItemType& ,
  1670.     Item* newItem, const ItemType&)
  1671. {
  1672.     if(oldItem != newItem)
  1673.         onRemoveInventoryItem(slot, oldItem);
  1674.  
  1675.     if(tradeState != TRADE_TRANSFER)
  1676.         checkTradeState(oldItem);
  1677. }
  1678.  
  1679. void Player::onRemoveInventoryItem(slots_t, Item* item)
  1680. {
  1681.     if(tradeState == TRADE_TRANSFER)
  1682.         return;
  1683.  
  1684.     checkTradeState(item);
  1685.     if(tradeItem)
  1686.     {
  1687.         const Container* container = item->getContainer();
  1688.         if(container && container->isHoldingItem(tradeItem))
  1689.             g_game.internalCloseTrade(this);
  1690.     }
  1691. }
  1692.  
  1693. void Player::checkTradeState(const Item* item)
  1694. {
  1695.     if(!tradeItem || tradeState == TRADE_TRANSFER)
  1696.         return;
  1697.  
  1698.     if(tradeItem != item)
  1699.     {
  1700.         const Container* container = dynamic_cast<const Container*>(item->getParent());
  1701.         while(container != NULL)
  1702.         {
  1703.             if(container == tradeItem)
  1704.             {
  1705.                 g_game.internalCloseTrade(this);
  1706.                 break;
  1707.             }
  1708.  
  1709.             container = dynamic_cast<const Container*>(container->getParent());
  1710.         }
  1711.     }
  1712.     else
  1713.         g_game.internalCloseTrade(this);
  1714. }
  1715.  
  1716. void Player::setNextWalkActionTask(SchedulerTask* task)
  1717. {
  1718.     if(walkTaskEvent)
  1719.     {
  1720.         Scheduler::getInstance().stopEvent(walkTaskEvent);
  1721.         walkTaskEvent = 0;
  1722.     }
  1723.  
  1724.     delete walkTask;
  1725.     walkTask = task;
  1726.     setIdleTime(0);
  1727. }
  1728.  
  1729. void Player::setNextWalkTask(SchedulerTask* task)
  1730. {
  1731.     if(nextStepEvent)
  1732.     {
  1733.         Scheduler::getInstance().stopEvent(nextStepEvent);
  1734.         nextStepEvent = 0;
  1735.     }
  1736.  
  1737.     if(task)
  1738.     {
  1739.         nextStepEvent = Scheduler::getInstance().addEvent(task);
  1740.         setIdleTime(0);
  1741.     }
  1742. }
  1743.  
  1744. void Player::setNextActionTask(SchedulerTask* task)
  1745. {
  1746.     if(actionTaskEvent)
  1747.     {
  1748.         Scheduler::getInstance().stopEvent(actionTaskEvent);
  1749.         actionTaskEvent = 0;
  1750.     }
  1751.  
  1752.     if(task)
  1753.     {
  1754.         actionTaskEvent = Scheduler::getInstance().addEvent(task);
  1755.         setIdleTime(0);
  1756.     }
  1757. }
  1758.  
  1759. uint32_t Player::getNextActionTime() const
  1760. {
  1761.     return (uint32_t)std::max((int64_t)SCHEDULER_MINTICKS, ((int64_t)nextAction - OTSYS_TIME()));
  1762. }
  1763.  
  1764. void Player::onThink(uint32_t interval)
  1765. {
  1766.     Creature::onThink(interval);
  1767.     int64_t timeNow = OTSYS_TIME();
  1768.     if(timeNow - lastPing >= 5000)
  1769.     {
  1770.         lastPing = timeNow;
  1771.         if(client)
  1772.         {
  1773.             for(AutoList<ProtocolGame>::iterator it = Player::cSpectators.begin(); it != Player::cSpectators.end(); ++it)
  1774.                 if(it->second->getPlayer() == this)
  1775.                     it->second->sendPing();
  1776.  
  1777.             client->sendPing();
  1778.         }
  1779.         else if(g_config.getBool(ConfigManager::STOP_ATTACK_AT_EXIT))
  1780.             setAttackedCreature(NULL);
  1781.     }
  1782.  
  1783.     if((timeNow - lastPong) >= 60000 && !getTile()->hasFlag(TILESTATE_NOLOGOUT)
  1784.         && !isConnecting && !pzLocked && !hasCondition(CONDITION_INFIGHT))
  1785.     {
  1786.         if(client)
  1787.             client->logout(true, true);
  1788.         else if(g_creatureEvents->playerLogout(this, false))
  1789.             g_game.removeCreature(this, true);
  1790.     }
  1791.  
  1792.     messageTicks += interval;
  1793.     if(messageTicks >= 1500)
  1794.     {
  1795.         messageTicks = 0;
  1796.         addMessageBuffer();
  1797.     }
  1798. }
  1799.  
  1800. bool Player::isMuted(uint16_t channelId, SpeakClasses type, uint32_t& time)
  1801. {
  1802.     time = 0;
  1803.     if(hasFlag(PlayerFlag_CannotBeMuted))
  1804.         return false;
  1805.  
  1806.     int32_t muteTicks = 0;
  1807.     for(ConditionList::iterator it = conditions.begin(); it != conditions.end(); ++it)
  1808.     {
  1809.         if((*it)->getType() == CONDITION_MUTED && (*it)->getSubId() == 0 && (*it)->getTicks() > muteTicks)
  1810.             muteTicks = (*it)->getTicks();
  1811.     }
  1812.  
  1813.     time = (uint32_t)muteTicks / 1000;
  1814.     return type != SPEAK_PRIVATE_PN && (type != SPEAK_CHANNEL_Y || (channelId != CHANNEL_GUILD && !g_chat.isPrivateChannel(channelId)));
  1815. }
  1816.  
  1817. void Player::addMessageBuffer()
  1818. {
  1819.     if(!hasFlag(PlayerFlag_CannotBeMuted) && g_config.getNumber(ConfigManager::MAX_MESSAGEBUFFER) && messageBuffer)
  1820.         messageBuffer--;
  1821. }
  1822.  
  1823. void Player::removeMessageBuffer()
  1824. {
  1825.     if(isAccountManager())
  1826.         return;
  1827.  
  1828.     if(hasFlag(PlayerFlag_CannotBeMuted))
  1829.         return;
  1830.  
  1831.     int32_t maxBuffer = g_config.getNumber(ConfigManager::MAX_MESSAGEBUFFER);
  1832.     if(!maxBuffer || messageBuffer > maxBuffer + 1 || ++messageBuffer <= maxBuffer)
  1833.         return;
  1834.  
  1835.     uint32_t muteCount = 1;
  1836.     MuteCountMap::iterator it = muteCountMap.find(guid);
  1837.     if(it != muteCountMap.end())
  1838.         muteCount = it->second;
  1839.  
  1840.     uint32_t muteTime = 5 * muteCount * muteCount;
  1841.     muteCountMap[guid] = muteCount + 1;
  1842.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000))
  1843.         addCondition(condition);
  1844.  
  1845.     char buffer[50];
  1846.     sprintf(buffer, "You are muted for %d seconds.", muteTime);
  1847.     sendTextMessage(MSG_STATUS_SMALL, buffer);
  1848. }
  1849.  
  1850. void Player::drainHealth(Creature* attacker, CombatType_t combatType, int32_t damage)
  1851. {
  1852.     Creature::drainHealth(attacker, combatType, damage);
  1853.     char buffer[150];
  1854.     if(attacker)
  1855.         sprintf(buffer, "You lose %d hitpoint%s due to an attack by %s.", damage, (damage != 1 ? "s" : ""), attacker->getNameDescription().c_str());
  1856.     else
  1857.         sprintf(buffer, "You lose %d hitpoint%s.", damage, (damage != 1 ? "s" : ""));
  1858.  
  1859.     sendStats();
  1860.     sendTextMessage(MSG_EVENT_DEFAULT, buffer);
  1861. }
  1862.  
  1863. void Player::drainMana(Creature* attacker, CombatType_t combatType, int32_t damage)
  1864. {
  1865.     Creature::drainMana(attacker, combatType, damage);
  1866.     char buffer[150];
  1867.     if(attacker)
  1868.         sprintf(buffer, "You lose %d mana blocking an attack by %s.", damage, attacker->getNameDescription().c_str());
  1869.     else
  1870.         sprintf(buffer, "You lose %d mana.", damage);
  1871.  
  1872.     sendStats();
  1873.     sendTextMessage(MSG_EVENT_DEFAULT, buffer);
  1874. }
  1875.  
  1876. void Player::addManaSpent(uint64_t amount, bool useMultiplier/* = true*/)
  1877. {
  1878.     if(!amount)
  1879.         return;
  1880.  
  1881.     uint64_t currReqMana = vocation->getReqMana(magLevel), nextReqMana = vocation->getReqMana(magLevel + 1);
  1882.     if(currReqMana > nextReqMana) //player has reached max magic level
  1883.         return;
  1884.  
  1885.     if(useMultiplier)
  1886.         amount = uint64_t((double)amount * rates[SKILL__MAGLEVEL] * g_config.getDouble(ConfigManager::RATE_MAGIC));
  1887.  
  1888.     bool advance = false;
  1889.     while(manaSpent + amount >= nextReqMana)
  1890.     {
  1891.         amount -= nextReqMana - manaSpent;
  1892.         manaSpent = 0;
  1893.         magLevel++;
  1894.  
  1895.         char advMsg[50];
  1896.         sprintf(advMsg, "You advanced to magic level %d.", magLevel);
  1897.         sendTextMessage(MSG_EVENT_ADVANCE, advMsg);
  1898.  
  1899.         advance = true;
  1900.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  1901.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  1902.             (*it)->executeAdvance(this, SKILL__MAGLEVEL, (magLevel - 1), magLevel);
  1903.  
  1904.         currReqMana = nextReqMana;
  1905.         nextReqMana = vocation->getReqMana(magLevel + 1);
  1906.         if(currReqMana > nextReqMana)
  1907.         {
  1908.             amount = 0;
  1909.             break;
  1910.         }
  1911.     }
  1912.  
  1913.     if(amount)
  1914.         manaSpent += amount;
  1915.  
  1916.     uint32_t newPercent = Player::getPercentLevel(manaSpent, nextReqMana);
  1917.     if(magLevelPercent != newPercent)
  1918.     {
  1919.         magLevelPercent = newPercent;
  1920.         sendStats();
  1921.     }
  1922.     else if(advance)
  1923.         sendStats();
  1924. }
  1925.  
  1926. void Player::setSkillLevel(skills_t skill, uint32_t value)
  1927. {
  1928.     uint32_t old_level = skills[skill][SKILL_LEVEL];
  1929.     std::stringstream s;
  1930.  
  1931.     skills[skill][SKILL_LEVEL] = value;
  1932.     skills[skill][SKILL_TRIES] = 0;
  1933.     skills[skill][SKILL_PERCENT] = 0;
  1934.  
  1935.     s.str("");
  1936.     s << "You advanced in " << getSkillName(skill);
  1937.     if(g_config.getBool(ConfigManager::ADVANCING_SKILL_LEVEL))
  1938.         s << " [" << skills[skill][SKILL_LEVEL] << "]";
  1939.  
  1940.     s << ".";
  1941.     sendTextMessage(MSG_EVENT_ADVANCE, s.str().c_str());
  1942.  
  1943.     CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  1944.     for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  1945.         (*it)->executeAdvance(this, skill, old_level, skills[skill][SKILL_LEVEL]);
  1946.  
  1947.     sendSkills();
  1948. }
  1949.  
  1950. void Player::setMagicLevel(uint64_t value)
  1951. {
  1952.     uint64_t old_level = magLevel;
  1953.  
  1954.     magLevel = value;
  1955.     manaSpent = 0;
  1956.     magLevelPercent = 0;
  1957.    
  1958.     char advMsg[50];
  1959.     sprintf(advMsg, "You advanced to magic level %d.", magLevel);
  1960.     sendTextMessage(MSG_EVENT_ADVANCE, advMsg);
  1961.  
  1962.     CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  1963.     for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  1964.         (*it)->executeAdvance(this, SKILL__MAGLEVEL, old_level, magLevel);
  1965.  
  1966.     sendStats();
  1967. }
  1968.  
  1969. void Player::addExperience(uint64_t exp)
  1970. {
  1971.     uint32_t prevLevel = level;
  1972.     uint64_t nextLevelExp = Player::getExpForLevel(level + 1);
  1973.     if(Player::getExpForLevel(level) > nextLevelExp)
  1974.     {
  1975.         //player has reached max level
  1976.         levelPercent = 0;
  1977.         sendStats();
  1978.         return;
  1979.     }
  1980.  
  1981.     experience += exp;
  1982.     while(experience >= nextLevelExp)
  1983.     {
  1984.         healthMax += vocation->getGain(GAIN_HEALTH);
  1985.         health += vocation->getGain(GAIN_HEALTH);
  1986.         manaMax += vocation->getGain(GAIN_MANA);
  1987.         mana += vocation->getGain(GAIN_MANA);
  1988.         capacity += vocation->getGainCap();
  1989.  
  1990.         ++level;
  1991.         nextLevelExp = Player::getExpForLevel(level + 1);
  1992.         if(Player::getExpForLevel(level) > nextLevelExp) //player has reached max level
  1993.             break;
  1994.     }
  1995.  
  1996.     if(prevLevel != level)
  1997.     {
  1998.         updateBaseSpeed();
  1999.         g_game.changeSpeed(this, 0);
  2000.  
  2001.         g_game.addCreatureHealth(this);
  2002.         if(party)
  2003.             party->updateSharedExperience();
  2004.  
  2005.         char advMsg[60];
  2006.         sprintf(advMsg, "You advanced from Level %d to Level %d.", prevLevel, level);
  2007.         sendTextMessage(MSG_EVENT_ADVANCE, advMsg);
  2008.  
  2009.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  2010.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  2011.             (*it)->executeAdvance(this, SKILL__LEVEL, prevLevel, level);
  2012.     }
  2013.  
  2014.     uint64_t currLevelExp = Player::getExpForLevel(level);
  2015.     nextLevelExp = Player::getExpForLevel(level + 1);
  2016.     levelPercent = 0;
  2017.     if(nextLevelExp > currLevelExp)
  2018.         levelPercent = Player::getPercentLevel(experience - currLevelExp, nextLevelExp - currLevelExp);
  2019.  
  2020.     sendStats();
  2021. }
  2022.  
  2023. void Player::removeExperience(uint64_t exp, bool updateStats/* = true*/)
  2024. {
  2025.     uint32_t prevLevel = level;
  2026.     experience -= std::min(exp, experience);
  2027.     while(level > 1 && experience < Player::getExpForLevel(level))
  2028.     {
  2029.         level--;
  2030.         healthMax = std::max((int32_t)0, (healthMax - (int32_t)vocation->getGain(GAIN_HEALTH)));
  2031.         manaMax = std::max((int32_t)0, (manaMax - (int32_t)vocation->getGain(GAIN_MANA)));
  2032.         capacity = std::max((double)0, (capacity - (double)vocation->getGainCap()));
  2033.     }
  2034.  
  2035.     if(prevLevel != level)
  2036.     {
  2037.         if(updateStats)
  2038.         {
  2039.             updateBaseSpeed();
  2040.             g_game.changeSpeed(this, 0);
  2041.             g_game.addCreatureHealth(this);
  2042.         }
  2043.  
  2044.         char advMsg[90];
  2045.         sprintf(advMsg, "You were downgraded from Level %d to Level %d.", prevLevel, level);
  2046.         sendTextMessage(MSG_EVENT_ADVANCE, advMsg);
  2047.     }
  2048.  
  2049.     uint64_t currLevelExp = Player::getExpForLevel(level);
  2050.     uint64_t nextLevelExp = Player::getExpForLevel(level + 1);
  2051.     if(nextLevelExp > currLevelExp)
  2052.         levelPercent = Player::getPercentLevel(experience - currLevelExp, nextLevelExp - currLevelExp);
  2053.     else
  2054.         levelPercent = 0;
  2055.  
  2056.     if(updateStats)
  2057.         sendStats();
  2058. }
  2059.  
  2060. uint32_t Player::getPercentLevel(uint64_t count, uint64_t nextLevelCount)
  2061. {
  2062.     if(nextLevelCount > 0)
  2063.         return std::min((uint32_t)100, std::max((uint32_t)0, uint32_t(count * 100 / nextLevelCount)));
  2064.  
  2065.     return 0;
  2066. }
  2067.  
  2068. void Player::onBlockHit(BlockType_t)
  2069. {
  2070.     if(shieldBlockCount > 0)
  2071.     {
  2072.         --shieldBlockCount;
  2073.         if(hasShield())
  2074.             addSkillAdvance(SKILL_SHIELD, 1);
  2075.     }
  2076. }
  2077.  
  2078. void Player::onAttackedCreatureBlockHit(Creature* target, BlockType_t blockType)
  2079. {
  2080.     Creature::onAttackedCreatureBlockHit(target, blockType);
  2081.     lastAttackBlockType = blockType;
  2082.     switch(blockType)
  2083.     {
  2084.         case BLOCK_NONE:
  2085.         {
  2086.             addAttackSkillPoint = true;
  2087.             bloodHitCount = 30;
  2088.             shieldBlockCount = 30;
  2089.             break;
  2090.         }
  2091.  
  2092.         case BLOCK_DEFENSE:
  2093.         case BLOCK_ARMOR:
  2094.         {
  2095.             //need to draw blood every 30 hits
  2096.             if(bloodHitCount > 0)
  2097.             {
  2098.                 addAttackSkillPoint = true;
  2099.                 --bloodHitCount;
  2100.             }
  2101.             else
  2102.                 addAttackSkillPoint = false;
  2103.  
  2104.             break;
  2105.         }
  2106.  
  2107.         default:
  2108.         {
  2109.             addAttackSkillPoint = false;
  2110.             break;
  2111.         }
  2112.     }
  2113. }
  2114.  
  2115. bool Player::hasShield() const
  2116. {
  2117.     Item* item = getInventoryItem(SLOT_LEFT);
  2118.     return (item && item->getWeaponType() == WEAPON_SHIELD) || ((item = getInventoryItem(SLOT_RIGHT)) && item->getWeaponType() == WEAPON_SHIELD);
  2119. }
  2120.  
  2121. BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage,
  2122.     bool checkDefense/* = false*/, bool checkArmor/* = false*/, bool reflect/* = true*/)
  2123. {
  2124.     BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor);
  2125.     if(attacker)
  2126.     {
  2127.         int16_t color = g_config.getNumber(ConfigManager::SQUARE_COLOR);
  2128.         if(color < 0)
  2129.             color = random_range(0, 254);
  2130.  
  2131.         sendCreatureSquare(attacker, color);
  2132.     }
  2133.  
  2134.     if(blockType != BLOCK_NONE)
  2135.         return blockType;
  2136.  
  2137.     if(vocation->getMultiplier(MULTIPLIER_MAGICDEFENSE) != 1.0 && combatType != COMBAT_NONE &&
  2138.         combatType != COMBAT_PHYSICALDAMAGE && combatType != COMBAT_UNDEFINEDDAMAGE &&
  2139.         combatType != COMBAT_DROWNDAMAGE)
  2140.         damage -= (int32_t)std::ceil((double)(damage * vocation->getMultiplier(MULTIPLIER_MAGICDEFENSE)) / 100.);
  2141.  
  2142.     if(damage <= 0)
  2143.         return blockType;
  2144.  
  2145.     int32_t blocked = 0, reflected = 0;
  2146.     if(reflect)
  2147.         reflect = attacker && !attacker->isRemoved() && attacker->getHealth() > 0;
  2148.  
  2149.     Item* item = NULL;
  2150.     for(int32_t slot = SLOT_FIRST; slot < SLOT_LAST; ++slot)
  2151.     {
  2152.         if(!(item = getInventoryItem((slots_t)slot)) || item->isRemoved() ||
  2153.             (g_moveEvents->hasEquipEvent(item) && !isItemAbilityEnabled((slots_t)slot)))
  2154.             continue;
  2155.  
  2156.         const ItemType& it = Item::items[item->getID()];
  2157.         if(it.abilities.absorb[combatType])
  2158.         {
  2159.             blocked += (int32_t)std::ceil((double)(damage * it.abilities.absorb[combatType]) / 100.);
  2160.             if(item->hasCharges())
  2161.                 g_game.transformItem(item, item->getID(), std::max((int32_t)0, (int32_t)item->getCharges() - 1));
  2162.         }
  2163.  
  2164.         if(!reflect)
  2165.             continue;
  2166.  
  2167.         if(it.abilities.reflect[REFLECT_PERCENT][combatType] && random_range(1, 100) < it.abilities.reflect[REFLECT_CHANCE][combatType])
  2168.         {
  2169.             reflected += (int32_t)std::ceil((double)(damage * it.abilities.reflect[REFLECT_PERCENT][combatType]) / 100.);
  2170.             if(item->hasCharges() && !it.abilities.absorb[combatType])
  2171.                 g_game.transformItem(item, item->getID(), std::max((int32_t)0, (int32_t)item->getCharges() - 1));
  2172.         }
  2173.     }
  2174.  
  2175.     if(outfitAttributes)
  2176.     {
  2177.         uint32_t tmp = Outfits::getInstance()->getOutfitAbsorb(defaultOutfit.lookType, sex, combatType);
  2178.         if(tmp)
  2179.             blocked += (int32_t)std::ceil((double)(damage * tmp) / 100.);
  2180.  
  2181.         if(reflect)
  2182.         {
  2183.             tmp = Outfits::getInstance()->getOutfitReflect(defaultOutfit.lookType, sex, combatType);
  2184.             if(tmp)
  2185.                 reflected += (int32_t)std::ceil((double)(damage * tmp) / 100.);
  2186.         }
  2187.     }
  2188.  
  2189.     if(vocation->getAbsorb(combatType))
  2190.         blocked += (int32_t)std::ceil((double)(damage * vocation->getAbsorb(combatType)) / 100.);
  2191.  
  2192.     if(reflect && vocation->getReflect(combatType))
  2193.         reflected += (int32_t)std::ceil((double)(damage * vocation->getReflect(combatType)) / 100.);
  2194.  
  2195.     damage -= blocked;
  2196.     if(damage <= 0)
  2197.     {
  2198.         damage = 0;
  2199.         blockType = BLOCK_DEFENSE;
  2200.     }
  2201.  
  2202.     if(reflected)
  2203.     {
  2204.         if(combatType != COMBAT_HEALING)
  2205.             reflected = -reflected;
  2206.  
  2207.         if(attacker->blockHit(this, combatType, reflected, false, false, false) == BLOCK_NONE)
  2208.             g_game.combatChangeHealth(combatType, NULL, attacker, reflected);
  2209.     }
  2210.  
  2211.     return blockType;
  2212. }
  2213.  
  2214. uint32_t Player::getIP() const
  2215. {
  2216.     if(client)
  2217.         return client->getIP();
  2218.  
  2219.     return lastIP;
  2220. }
  2221.  
  2222. bool Player::onDeath()
  2223. {
  2224.     kickCastViewers();
  2225.  
  2226.     Item* preventLoss = NULL;
  2227.     Item* preventDrop = NULL;
  2228.     if(getZone() == ZONE_HARDCORE)
  2229.     {
  2230.         setDropLoot(LOOT_DROP_NONE);
  2231.         setLossSkill(false);
  2232.     }
  2233.     else if(skull < SKULL_RED)
  2234.     {
  2235.         Item* item = NULL;
  2236.         for(int32_t i = SLOT_FIRST; ((skillLoss || lootDrop == LOOT_DROP_FULL) && i < SLOT_LAST); ++i)
  2237.         {
  2238.             if(!(item = getInventoryItem((slots_t)i)) || item->isRemoved() ||
  2239.                 (g_moveEvents->hasEquipEvent(item) && !isItemAbilityEnabled((slots_t)i)))
  2240.                 continue;
  2241.  
  2242.             const ItemType& it = Item::items[item->getID()];
  2243.             if(lootDrop == LOOT_DROP_FULL && it.abilities.preventDrop)
  2244.             {
  2245.                 setDropLoot(LOOT_DROP_PREVENT);
  2246.                 preventDrop = item;
  2247.             }
  2248.  
  2249.             if(skillLoss && !preventLoss && it.abilities.preventLoss)
  2250.                 preventLoss = item;
  2251.         }
  2252.     }
  2253.  
  2254.     if(!Creature::onDeath())
  2255.     {
  2256.         if(preventDrop)
  2257.             setDropLoot(LOOT_DROP_FULL);
  2258.  
  2259.         return false;
  2260.     }
  2261.  
  2262.     if(preventLoss)
  2263.     {
  2264.         setLossSkill(false);
  2265.         if(preventLoss->getCharges() > 1) //weird, but transform failed to remove for some hosters
  2266.             g_game.transformItem(preventLoss, preventLoss->getID(), std::max(0, ((int32_t)preventLoss->getCharges() - 1)));
  2267.         else
  2268.             g_game.internalRemoveItem(NULL, preventDrop);
  2269.     }
  2270.  
  2271.     if(preventDrop && preventDrop != preventLoss)
  2272.     {
  2273.         if(preventDrop->getCharges() > 1) //weird, but transform failed to remove for some hosters
  2274.             g_game.transformItem(preventDrop, preventDrop->getID(), std::max(0, ((int32_t)preventDrop->getCharges() - 1)));
  2275.         else
  2276.             g_game.internalRemoveItem(NULL, preventDrop);
  2277.     }
  2278.  
  2279.     removeConditions(CONDITIONEND_DEATH);
  2280.     if(skillLoss)
  2281.     {
  2282.         uint64_t lossExperience = getLostExperience();
  2283.         removeExperience(lossExperience, false);
  2284.         double percent = 1. - ((double)(experience - lossExperience) / experience);
  2285.  
  2286.         //Magic level loss
  2287.         uint32_t sumMana = 0;
  2288.         uint64_t lostMana = 0;
  2289.         for(uint32_t i = 1; i <= magLevel; ++i)
  2290.             sumMana += vocation->getReqMana(i);
  2291.  
  2292.         sumMana += manaSpent;
  2293.         lostMana = (uint64_t)std::ceil(sumMana * ((double)(percent * lossPercent[LOSS_MANA]) / 100.));
  2294.         while(lostMana > manaSpent && magLevel > 0)
  2295.         {
  2296.             lostMana -= manaSpent;
  2297.             manaSpent = vocation->getReqMana(magLevel);
  2298.             magLevel--;
  2299.         }
  2300.  
  2301.         manaSpent -= std::max((int32_t)0, (int32_t)lostMana);
  2302.         uint64_t nextReqMana = vocation->getReqMana(magLevel + 1);
  2303.         if(nextReqMana > vocation->getReqMana(magLevel))
  2304.             magLevelPercent = Player::getPercentLevel(manaSpent, nextReqMana);
  2305.         else
  2306.             magLevelPercent = 0;
  2307.  
  2308.         //Skill loss
  2309.         uint32_t lostSkillTries, sumSkillTries;
  2310.         for(int16_t i = 0; i < 7; ++i) //for each skill
  2311.         {
  2312.             lostSkillTries = sumSkillTries = 0;
  2313.             for(uint32_t c = 11; c <= skills[i][SKILL_LEVEL]; ++c) //sum up all required tries for all skill levels
  2314.                 sumSkillTries += vocation->getReqSkillTries(i, c);
  2315.  
  2316.             sumSkillTries += skills[i][SKILL_TRIES];
  2317.             lostSkillTries = (uint32_t)std::ceil(sumSkillTries * ((double)(percent * lossPercent[LOSS_SKILLS]) / 100.));
  2318.             while(lostSkillTries > skills[i][SKILL_TRIES])
  2319.             {
  2320.                 lostSkillTries -= skills[i][SKILL_TRIES];
  2321.                 skills[i][SKILL_TRIES] = vocation->getReqSkillTries(i, skills[i][SKILL_LEVEL]);
  2322.                 if(skills[i][SKILL_LEVEL] < 11)
  2323.                 {
  2324.                     skills[i][SKILL_LEVEL] = 10;
  2325.                     skills[i][SKILL_TRIES] = lostSkillTries = 0;
  2326.                     break;
  2327.                 }
  2328.                 else
  2329.                     skills[i][SKILL_LEVEL]--;
  2330.             }
  2331.  
  2332.             skills[i][SKILL_TRIES] = std::max((int32_t)0, (int32_t)(skills[i][SKILL_TRIES] - lostSkillTries));
  2333.         }
  2334.  
  2335.         blessings = 0;
  2336.         loginPosition = masterPosition;
  2337.         if(!inventory[SLOT_BACKPACK])
  2338.             __internalAddThing(SLOT_BACKPACK, Item::CreateItem(g_config.getNumber(ConfigManager::DEATH_CONTAINER)));
  2339.  
  2340.         sendIcons();
  2341.         sendStats();
  2342.         sendSkills();
  2343.  
  2344.         g_creatureEvents->playerLogout(this, true);
  2345.         g_game.removeCreature(this, false);
  2346.         sendReLoginWindow();
  2347.     }
  2348.     else
  2349.     {
  2350.         setLossSkill(true);
  2351.         if(preventLoss)
  2352.         {
  2353.             loginPosition = masterPosition;
  2354.             g_creatureEvents->playerLogout(this, true);
  2355.             g_game.removeCreature(this, false);
  2356.             sendReLoginWindow();
  2357.         }
  2358.     }
  2359.  
  2360.     return true;
  2361. }
  2362.  
  2363. void Player::dropCorpse(DeathList deathList)
  2364. {
  2365.     if(lootDrop == LOOT_DROP_NONE)
  2366.     {
  2367.         pzLocked = false;
  2368.         if(health <= 0)
  2369.         {
  2370.             health = healthMax;
  2371.             mana = manaMax;
  2372.         }
  2373.  
  2374.         setDropLoot(LOOT_DROP_FULL);
  2375.         sendStats();
  2376.         sendIcons();
  2377.  
  2378.         onIdleStatus();
  2379.         g_game.addCreatureHealth(this);
  2380.         g_game.internalTeleport(this, masterPosition, false);
  2381.     }
  2382.     else
  2383.     {
  2384.         Creature::dropCorpse(deathList);
  2385.         if(g_config.getBool(ConfigManager::DEATH_LIST))
  2386.             IOLoginData::getInstance()->playerDeath(this, deathList);
  2387.     }
  2388. }
  2389.  
  2390. Item* Player::createCorpse(DeathList deathList)
  2391. {
  2392.     Item* corpse = Creature::createCorpse(deathList);
  2393.     if(!corpse)
  2394.         return NULL;
  2395.  
  2396.     std::stringstream ss;
  2397.     ss << "You recognize " << getNameDescription() << ". " << (sex % 2 ? "He" : "She") << " was killed by ";
  2398.     if(deathList[0].isCreatureKill())
  2399.     {
  2400.         ss << deathList[0].getKillerCreature()->getNameDescription();
  2401.         if(deathList[0].getKillerCreature()->getMaster())
  2402.             ss << " summoned by " << deathList[0].getKillerCreature()->getMaster()->getNameDescription();
  2403.     }
  2404.     else
  2405.         ss << deathList[0].getKillerName();
  2406.  
  2407.     if(deathList.size() > 1)
  2408.     {
  2409.         if(deathList[0].getKillerType() != deathList[1].getKillerType())
  2410.         {
  2411.             if(deathList[1].isCreatureKill())
  2412.             {
  2413.                 ss << " and by " << deathList[1].getKillerCreature()->getNameDescription();
  2414.                 if(deathList[1].getKillerCreature()->getMaster())
  2415.                     ss << " summoned by " << deathList[1].getKillerCreature()->getMaster()->getNameDescription();
  2416.             }
  2417.             else
  2418.                 ss << " and by " << deathList[1].getKillerName();
  2419.         }
  2420.         else if(deathList[1].isCreatureKill())
  2421.         {
  2422.             if(deathList[0].getKillerCreature()->getName() != deathList[1].getKillerCreature()->getName())
  2423.             {
  2424.                 ss << " and by " << deathList[1].getKillerCreature()->getNameDescription();
  2425.                 if(deathList[1].getKillerCreature()->getMaster())
  2426.                     ss << " summoned by " << deathList[1].getKillerCreature()->getMaster()->getNameDescription();
  2427.             }
  2428.         }
  2429.         else if(asLowerCaseString(deathList[0].getKillerName()) != asLowerCaseString(deathList[1].getKillerName()))
  2430.             ss << " and by " << deathList[1].getKillerName();
  2431.     }
  2432.  
  2433.     ss << ".";
  2434.     corpse->setSpecialDescription(ss.str().c_str());
  2435.     return corpse;
  2436. }
  2437.  
  2438. void Player::addExhaust(uint32_t ticks, Exhaust_t type)
  2439. {
  2440.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT,
  2441.         CONDITION_EXHAUST, ticks, 0, false, (uint32_t)type))
  2442.         addCondition(condition);
  2443. }
  2444.  
  2445. void Player::addInFightTicks(bool pzLock, int32_t ticks/* = 0*/)
  2446. {
  2447.     if(hasFlag(PlayerFlag_NotGainInFight))
  2448.         return;
  2449.  
  2450.     if(!ticks)
  2451.         ticks = g_config.getNumber(ConfigManager::PZ_LOCKED);
  2452.     else
  2453.         ticks = std::max(-1, ticks);
  2454.  
  2455.     if(pzLock)
  2456.         pzLocked = true;
  2457.  
  2458.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT,
  2459.         CONDITION_INFIGHT, ticks))
  2460.         addCondition(condition);
  2461. }
  2462.  
  2463. void Player::addDefaultRegeneration(uint32_t addTicks)
  2464. {
  2465.     Condition* condition = getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT);
  2466.     if(condition)
  2467.         condition->setTicks(condition->getTicks() + addTicks);
  2468.     else if((condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_REGENERATION, addTicks)))
  2469.     {
  2470.         condition->setParam(CONDITIONPARAM_HEALTHGAIN, vocation->getGainAmount(GAIN_HEALTH));
  2471.         condition->setParam(CONDITIONPARAM_HEALTHTICKS, vocation->getGainTicks(GAIN_HEALTH) * 1000);
  2472.         condition->setParam(CONDITIONPARAM_MANAGAIN, vocation->getGainAmount(GAIN_MANA));
  2473.         condition->setParam(CONDITIONPARAM_MANATICKS, vocation->getGainTicks(GAIN_MANA) * 1000);
  2474.         addCondition(condition);
  2475.     }
  2476. }
  2477.  
  2478. void Player::removeList()
  2479. {
  2480.     Manager::getInstance()->removeUser(id);
  2481.     autoList.erase(id);
  2482.     castAutoList.erase(id);
  2483.    
  2484.     if(!isGhost())
  2485.     {
  2486.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  2487.             it->second->notifyLogOut(this);
  2488.     }
  2489.     else
  2490.     {
  2491.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  2492.         {
  2493.             if(it->second->canSeeCreature(this))
  2494.                 it->second->notifyLogOut(this);
  2495.         }
  2496.     }
  2497. }
  2498.  
  2499. void Player::addList()
  2500. {
  2501.     if(!isGhost())
  2502.     {
  2503.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  2504.             it->second->notifyLogIn(this);
  2505.     }
  2506.     else
  2507.     {
  2508.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  2509.         {
  2510.             if(it->second->canSeeCreature(this))
  2511.                 it->second->notifyLogIn(this);
  2512.         }
  2513.     }
  2514.  
  2515.     autoList[id] = this;
  2516.     Manager::getInstance()->addUser(this);
  2517. }
  2518.  
  2519. void Player::kickPlayer(bool displayEffect, bool forceLogout)
  2520. {
  2521.     if(!client)
  2522.     {
  2523.         if(g_creatureEvents->playerLogout(this, forceLogout))
  2524.             g_game.removeCreature(this);
  2525.     }
  2526.     else
  2527.         client->logout(displayEffect, forceLogout);
  2528. }
  2529.  
  2530. void Player::notifyLogIn(Player* loginPlayer)
  2531. {
  2532.     if(!client)
  2533.         return;
  2534.  
  2535.     VIPSet::iterator it = VIPList.find(loginPlayer->getGUID());
  2536.     if(it != VIPList.end())
  2537.         client->sendVIPLogIn(loginPlayer->getGUID());
  2538. }
  2539.  
  2540. void Player::notifyLogOut(Player* logoutPlayer)
  2541. {
  2542.     if(!client)
  2543.         return;
  2544.  
  2545.     VIPSet::iterator it = VIPList.find(logoutPlayer->getGUID());
  2546.     if(it != VIPList.end())
  2547.         client->sendVIPLogOut(logoutPlayer->getGUID());
  2548. }
  2549.  
  2550. bool Player::removeVIP(uint32_t _guid)
  2551. {
  2552.     VIPSet::iterator it = VIPList.find(_guid);
  2553.     if(it == VIPList.end())
  2554.         return false;
  2555.  
  2556.     VIPList.erase(it);
  2557.     return true;
  2558. }
  2559.  
  2560. bool Player::addVIP(uint32_t _guid, std::string& name, bool isOnline, bool internal/* = false*/)
  2561. {
  2562.     if(guid == _guid)
  2563.     {
  2564.         if(!internal)
  2565.             sendTextMessage(MSG_STATUS_SMALL, "You cannot add yourself.");
  2566.  
  2567.         return false;
  2568.     }
  2569.  
  2570.     if(VIPList.size() > (group ? group->getMaxVips(isPremium()) : g_config.getNumber(ConfigManager::VIPLIST_DEFAULT_LIMIT)))
  2571.     {
  2572.         if(!internal)
  2573.             sendTextMessage(MSG_STATUS_SMALL, "You cannot add more buddies.");
  2574.  
  2575.         return false;
  2576.     }
  2577.  
  2578.     VIPSet::iterator it = VIPList.find(_guid);
  2579.     if(it != VIPList.end())
  2580.     {
  2581.         if(!internal)
  2582.             sendTextMessage(MSG_STATUS_SMALL, "This player is already in your list.");
  2583.  
  2584.         return false;
  2585.     }
  2586.  
  2587.     VIPList.insert(_guid);
  2588.     if(client && !internal)
  2589.         client->sendVIP(_guid, name, isOnline);
  2590.  
  2591.     return true;
  2592. }
  2593.  
  2594. //close container and its child containers
  2595. void Player::autoCloseContainers(const Container* container)
  2596. {
  2597.     typedef std::vector<uint32_t> CloseList;
  2598.     CloseList closeList;
  2599.     for(ContainerVector::iterator it = containerVec.begin(); it != containerVec.end(); ++it)
  2600.     {
  2601.         Container* tmp = it->second;
  2602.         while(tmp != NULL)
  2603.         {
  2604.             if(tmp->isRemoved() || tmp == container)
  2605.             {
  2606.                 closeList.push_back(it->first);
  2607.                 break;
  2608.             }
  2609.  
  2610.             tmp = dynamic_cast<Container*>(tmp->getParent());
  2611.         }
  2612.     }
  2613.  
  2614.     for(CloseList::iterator it = closeList.begin(); it != closeList.end(); ++it)
  2615.     {
  2616.         closeContainer(*it);
  2617.         if(client)
  2618.         {
  2619.             client->sendCloseContainer(*it);
  2620.             for(AutoList<ProtocolGame>::iterator it2 = Player::cSpectators.begin(); it2 != Player::cSpectators.end(); ++it2)
  2621.                 if(it2->second->getPlayer() == this)
  2622.                     it2->second->sendCloseContainer(*it);
  2623.         }
  2624.     }
  2625. }
  2626.  
  2627. bool Player::hasCapacity(const Item* item, uint32_t count) const
  2628. {
  2629.     if(hasFlag(PlayerFlag_CannotPickupItem))
  2630.         return false;
  2631.  
  2632.     if(hasFlag(PlayerFlag_HasInfiniteCapacity) || item->getTopParent() == this)
  2633.         return true;
  2634.  
  2635.     double itemWeight = 0;
  2636.     if(item->isStackable())
  2637.         itemWeight = Item::items[item->getID()].weight * count;
  2638.     else
  2639.         itemWeight = item->getWeight();
  2640.  
  2641.     return (itemWeight < getFreeCapacity());
  2642. }
  2643.  
  2644. ReturnValue Player::__queryAdd(int32_t index, const Thing* thing, uint32_t count, uint32_t flags) const
  2645. {
  2646.     const Item* item = thing->getItem();
  2647.     if(!item)
  2648.         return RET_NOTPOSSIBLE;
  2649.  
  2650.     bool childOwner = ((flags & FLAG_CHILDISOWNER) == FLAG_CHILDISOWNER), skipLimit = ((flags & FLAG_NOLIMIT) == FLAG_NOLIMIT);
  2651.     if(childOwner)
  2652.     {
  2653.         //a child container is querying the player, just check if enough capacity
  2654.         if(skipLimit || hasCapacity(item, count))
  2655.             return RET_NOERROR;
  2656.  
  2657.         return RET_NOTENOUGHCAPACITY;
  2658.     }
  2659.  
  2660.     if(!item->isPickupable())
  2661.         return RET_CANNOTPICKUP;
  2662.  
  2663.     ReturnValue ret = RET_NOERROR;
  2664.     if((item->getSlotPosition() & SLOTP_HEAD) || (item->getSlotPosition() & SLOTP_NECKLACE) ||
  2665.         (item->getSlotPosition() & SLOTP_BACKPACK) || (item->getSlotPosition() & SLOTP_ARMOR) ||
  2666.         (item->getSlotPosition() & SLOTP_LEGS) || (item->getSlotPosition() & SLOTP_FEET) ||
  2667.         (item->getSlotPosition() & SLOTP_RING))
  2668.         ret = RET_CANNOTBEDRESSED;
  2669.     else if(item->getSlotPosition() & SLOTP_TWO_HAND)
  2670.         ret = RET_PUTTHISOBJECTINBOTHHANDS;
  2671.     else if((item->getSlotPosition() & SLOTP_RIGHT) || (item->getSlotPosition() & SLOTP_LEFT))
  2672.         ret = RET_PUTTHISOBJECTINYOURHAND;
  2673.  
  2674.     switch(index)
  2675.     {
  2676.         case SLOT_HEAD:
  2677.             if(item->getSlotPosition() & SLOTP_HEAD)
  2678.                 ret = RET_NOERROR;
  2679.             break;
  2680.         case SLOT_NECKLACE:
  2681.             if(item->getSlotPosition() & SLOTP_NECKLACE)
  2682.                 ret = RET_NOERROR;
  2683.             break;
  2684.         case SLOT_BACKPACK:
  2685.             if(item->getSlotPosition() & SLOTP_BACKPACK)
  2686.                 ret = RET_NOERROR;
  2687.             break;
  2688.         case SLOT_ARMOR:
  2689.             if(item->getSlotPosition() & SLOTP_ARMOR)
  2690.                 ret = RET_NOERROR;
  2691.             break;
  2692.         case SLOT_RIGHT:
  2693.             if(item->getSlotPosition() & SLOTP_RIGHT)
  2694.             {
  2695.                 //check if we already carry an item in the other hand
  2696.                 if(item->getSlotPosition() & SLOTP_TWO_HAND)
  2697.                 {
  2698.                     if(inventory[SLOT_LEFT] && inventory[SLOT_LEFT] != item)
  2699.                         ret = RET_BOTHHANDSNEEDTOBEFREE;
  2700.                     else
  2701.                         ret = RET_NOERROR;
  2702.                 }
  2703.                 else if(inventory[SLOT_LEFT])
  2704.                 {
  2705.                     const Item* leftItem = inventory[SLOT_LEFT];
  2706.                     WeaponType_t type = item->getWeaponType(), leftType = leftItem->getWeaponType();
  2707.                     if(leftItem->getSlotPosition() & SLOTP_TWO_HAND)
  2708.                         ret = RET_DROPTWOHANDEDITEM;
  2709.                     else if(item == leftItem && item->getItemCount() == count)
  2710.                         ret = RET_NOERROR;
  2711.                     else if(leftType == WEAPON_SHIELD && type == WEAPON_SHIELD)
  2712.                         ret = RET_CANONLYUSEONESHIELD;
  2713.                     else if(!leftItem->isWeapon() || !item->isWeapon() ||
  2714.                         leftType == WEAPON_AMMO || type == WEAPON_AMMO ||
  2715.                         leftType == WEAPON_SHIELD || type == WEAPON_SHIELD ||
  2716.                         (leftItem->isDualWield() && item->isDualWield()))
  2717.                         ret = RET_NOERROR;
  2718.                     else
  2719.                         ret = RET_CANONLYUSEONEWEAPON;
  2720.                 }
  2721.                 else
  2722.                     ret = RET_NOERROR;
  2723.             }
  2724.             break;
  2725.         case SLOT_LEFT:
  2726.             if(item->getSlotPosition() & SLOTP_LEFT)
  2727.             {
  2728.                 //check if we already carry an item in the other hand
  2729.                 if(item->getSlotPosition() & SLOTP_TWO_HAND)
  2730.                 {
  2731.                     if(inventory[SLOT_RIGHT] && inventory[SLOT_RIGHT] != item)
  2732.                         ret = RET_BOTHHANDSNEEDTOBEFREE;
  2733.                     else
  2734.                         ret = RET_NOERROR;
  2735.                 }
  2736.                 else if(inventory[SLOT_RIGHT])
  2737.                 {
  2738.                     const Item* rightItem = inventory[SLOT_RIGHT];
  2739.                     WeaponType_t type = item->getWeaponType(), rightType = rightItem->getWeaponType();
  2740.                     if(rightItem->getSlotPosition() & SLOTP_TWO_HAND)
  2741.                         ret = RET_DROPTWOHANDEDITEM;
  2742.                     else if(item == rightItem && item->getItemCount() == count)
  2743.                         ret = RET_NOERROR;
  2744.                     else if(rightType == WEAPON_SHIELD && type == WEAPON_SHIELD)
  2745.                         ret = RET_CANONLYUSEONESHIELD;
  2746.                     else if(!rightItem->isWeapon() || !item->isWeapon() ||
  2747.                         rightType == WEAPON_AMMO || type == WEAPON_AMMO ||
  2748.                         rightType == WEAPON_SHIELD || type == WEAPON_SHIELD ||
  2749.                         (rightItem->isDualWield() && item->isDualWield()))
  2750.                         ret = RET_NOERROR;
  2751.                     else
  2752.                         ret = RET_CANONLYUSEONEWEAPON;
  2753.                 }
  2754.                 else
  2755.                     ret = RET_NOERROR;
  2756.             }
  2757.             break;
  2758.         case SLOT_LEGS:
  2759.             if(item->getSlotPosition() & SLOTP_LEGS)
  2760.                 ret = RET_NOERROR;
  2761.             break;
  2762.         case SLOT_FEET:
  2763.             if(item->getSlotPosition() & SLOTP_FEET)
  2764.                 ret = RET_NOERROR;
  2765.             break;
  2766.         case SLOT_RING:
  2767.             if(item->getSlotPosition() & SLOTP_RING)
  2768.                 ret = RET_NOERROR;
  2769.             break;
  2770.         case SLOT_AMMO:
  2771.             if(item->getSlotPosition() & SLOTP_AMMO)
  2772.                 ret = RET_NOERROR;
  2773.             break;
  2774.         case SLOT_WHEREEVER:
  2775.         case -1:
  2776.             ret = RET_NOTENOUGHROOM;
  2777.             break;
  2778.         default:
  2779.             ret = RET_NOTPOSSIBLE;
  2780.             break;
  2781.     }
  2782.  
  2783.     if(ret == RET_NOERROR || ret == RET_NOTENOUGHROOM)
  2784.     {
  2785.         //need an exchange with source?
  2786.         if(getInventoryItem((slots_t)index) != NULL && (!getInventoryItem((slots_t)index)->isStackable()
  2787.             || getInventoryItem((slots_t)index)->getID() != item->getID()))
  2788.             return RET_NEEDEXCHANGE;
  2789.  
  2790.         if(!g_moveEvents->onPlayerEquip(const_cast<Player*>(this), const_cast<Item*>(item), (slots_t)index, true))
  2791.             return RET_CANNOTBEDRESSED;
  2792.  
  2793.         //check if enough capacity
  2794.         if(!hasCapacity(item, count))
  2795.             return RET_NOTENOUGHCAPACITY;
  2796.     }
  2797.  
  2798.     return ret;
  2799. }
  2800.  
  2801. ReturnValue Player::__queryMaxCount(int32_t index, const Thing* thing, uint32_t count, uint32_t& maxQueryCount,
  2802.     uint32_t flags) const
  2803. {
  2804.     const Item* item = thing->getItem();
  2805.     if(!item)
  2806.     {
  2807.         maxQueryCount = 0;
  2808.         return RET_NOTPOSSIBLE;
  2809.     }
  2810.  
  2811.     if(index == INDEX_WHEREEVER)
  2812.     {
  2813.         uint32_t n = 0;
  2814.         for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  2815.         {
  2816.             if(Item* inventoryItem = inventory[i])
  2817.             {
  2818.                 if(Container* subContainer = inventoryItem->getContainer())
  2819.                 {
  2820.                     uint32_t queryCount = 0;
  2821.                     subContainer->__queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags);
  2822.  
  2823.                     //iterate through all items, including sub-containers (deep search)
  2824.                     n += queryCount;
  2825.                     for(ContainerIterator cit = subContainer->begin(); cit != subContainer->end(); ++cit)
  2826.                     {
  2827.                         if(Container* tmpContainer  = (*cit)->getContainer())
  2828.                         {
  2829.                             queryCount = 0;
  2830.                             tmpContainer->__queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags);
  2831.                             n += queryCount;
  2832.                         }
  2833.                     }
  2834.                 }
  2835.                 else if(inventoryItem->isStackable() && item->getID() == inventoryItem->getID() && inventoryItem->getItemCount() < 100)
  2836.                 {
  2837.                     uint32_t remainder = (100 - inventoryItem->getItemCount());
  2838.                     if(__queryAdd(i, item, remainder, flags) == RET_NOERROR)
  2839.                         n += remainder;
  2840.                 }
  2841.             }
  2842.             else if(__queryAdd(i, item, item->getItemCount(), flags) == RET_NOERROR)
  2843.             {
  2844.                 if(item->isStackable())
  2845.                     n += 100;
  2846.                 else
  2847.                     n += 1;
  2848.             }
  2849.         }
  2850.  
  2851.         maxQueryCount = n;
  2852.     }
  2853.     else
  2854.     {
  2855.         const Thing* destThing = __getThing(index);
  2856.         const Item* destItem = NULL;
  2857.         if(destThing)
  2858.             destItem = destThing->getItem();
  2859.  
  2860.         if(destItem)
  2861.         {
  2862.             if(destItem->isStackable() && item->getID() == destItem->getID() && destItem->getItemCount() < 100)
  2863.                 maxQueryCount = 100 - destItem->getItemCount();
  2864.             else
  2865.                 maxQueryCount = 0;
  2866.         }
  2867.         else if(__queryAdd(index, item, item->getItemCount(), flags) == RET_NOERROR)
  2868.         {
  2869.             if(item->isStackable())
  2870.                 maxQueryCount = 100;
  2871.             else
  2872.                 maxQueryCount = 1;
  2873.  
  2874.             return RET_NOERROR;
  2875.         }
  2876.     }
  2877.  
  2878.     if(maxQueryCount < count)
  2879.         return RET_NOTENOUGHROOM;
  2880.  
  2881.     return RET_NOERROR;
  2882. }
  2883.  
  2884. ReturnValue Player::__queryRemove(const Thing* thing, uint32_t count, uint32_t flags) const
  2885. {
  2886.     int32_t index = __getIndexOfThing(thing);
  2887.     if(index == -1)
  2888.         return RET_NOTPOSSIBLE;
  2889.  
  2890.     const Item* item = thing->getItem();
  2891.     if(!item)
  2892.         return RET_NOTPOSSIBLE;
  2893.  
  2894.     if(!count || (item->isStackable() && count > item->getItemCount()))
  2895.         return RET_NOTPOSSIBLE;
  2896.  
  2897.      if(!item->isMoveable() && !hasBitSet(FLAG_IGNORENOTMOVEABLE, flags))
  2898.         return RET_NOTMOVEABLE;
  2899.  
  2900.     return RET_NOERROR;
  2901. }
  2902.  
  2903. Cylinder* Player::__queryDestination(int32_t& index, const Thing* thing, Item** destItem,
  2904.     uint32_t& flags)
  2905. {
  2906.     if(!index /*drop to capacity window*/ || index == INDEX_WHEREEVER)
  2907.     {
  2908.         *destItem = NULL;
  2909.         const Item* item = thing->getItem();
  2910.         if(!item)
  2911.             return this;
  2912.  
  2913.         std::list<std::pair<Container*, int32_t> > containers;
  2914.         std::list<std::pair<Cylinder*, int32_t> > freeSlots;
  2915.  
  2916.         bool autoStack = !((flags & FLAG_IGNOREAUTOSTACK) == FLAG_IGNOREAUTOSTACK);
  2917.         for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  2918.         {
  2919.             if(Item* invItem = inventory[i])
  2920.             {
  2921.                 if(invItem == item || invItem == tradeItem)
  2922.                     continue;
  2923.  
  2924.                 if(autoStack && item->isStackable() && __queryAdd(i, item, item->getItemCount(), 0)
  2925.                     == RET_NOERROR && invItem->getID() == item->getID() && invItem->getItemCount() < 100)
  2926.                 {
  2927.                     *destItem = invItem;
  2928.                     index = i;
  2929.                     return this;
  2930.                 }
  2931.  
  2932.                 if(Container* container = invItem->getContainer())
  2933.                 {
  2934.                     if(!autoStack && container->__queryAdd(INDEX_WHEREEVER,
  2935.                         item, item->getItemCount(), flags) == RET_NOERROR)
  2936.                     {
  2937.                         index = INDEX_WHEREEVER;
  2938.                         return container;
  2939.                     }
  2940.  
  2941.                     containers.push_back(std::make_pair(container, 0));
  2942.                 }
  2943.             }
  2944.             else if(!autoStack)
  2945.             {
  2946.                 if(__queryAdd(i, item, item->getItemCount(), 0) == RET_NOERROR)
  2947.                 {
  2948.                     index = i;
  2949.                     return this;
  2950.                 }
  2951.             }
  2952.             else
  2953.                 freeSlots.push_back(std::make_pair(this, i));
  2954.         }
  2955.  
  2956.         int32_t deepness = g_config.getNumber(ConfigManager::PLAYER_DEEPNESS);
  2957.         while(!containers.empty())
  2958.         {
  2959.             Container* tmpContainer = containers.front().first;
  2960.             int32_t level = containers.front().second;
  2961.  
  2962.             containers.pop_front();
  2963.             if(!tmpContainer)
  2964.                 continue;
  2965.  
  2966.             for(uint32_t n = 0; n < tmpContainer->capacity(); ++n)
  2967.             {
  2968.                 if(Item* tmpItem = tmpContainer->getItem(n))
  2969.                 {
  2970.                     if(tmpItem == item || tmpItem == tradeItem)
  2971.                         continue;
  2972.  
  2973.                     if(autoStack && item->isStackable() && tmpContainer->__queryAdd(n, item, item->getItemCount(),
  2974.                         0) == RET_NOERROR && tmpItem->getID() == item->getID() && tmpItem->getItemCount() < 100)
  2975.                     {
  2976.                         index = n;
  2977.                         *destItem = tmpItem;
  2978.                         return tmpContainer;
  2979.                     }
  2980.  
  2981.                     if(Container* container = tmpItem->getContainer())
  2982.                     {
  2983.                         if(!autoStack && container->__queryAdd(INDEX_WHEREEVER,
  2984.                             item, item->getItemCount(), flags) == RET_NOERROR)
  2985.                         {
  2986.                             index = INDEX_WHEREEVER;
  2987.                             return container;
  2988.                         }
  2989.  
  2990.                         if(deepness < 0 || level < deepness)
  2991.                             containers.push_back(std::make_pair(container, level + 1));
  2992.                     }
  2993.                 }
  2994.                 else
  2995.                 {
  2996.                     if(!autoStack)
  2997.                     {
  2998.                         if(tmpContainer->__queryAdd(n, item, item->getItemCount(), 0) == RET_NOERROR)
  2999.                         {
  3000.                             index = n;
  3001.                             return tmpContainer;
  3002.                         }
  3003.                     }
  3004.                     else
  3005.                         freeSlots.push_back(std::make_pair(tmpContainer, n));
  3006.  
  3007.                     break; // one slot to check is definitely enough.
  3008.                 }
  3009.             }
  3010.         }
  3011.  
  3012.         if(autoStack)
  3013.         {
  3014.             while(!freeSlots.empty())
  3015.             {
  3016.                 Cylinder* tmpCylinder = freeSlots.front().first;
  3017.                 int32_t i = freeSlots.front().second;
  3018.  
  3019.                 freeSlots.pop_front();
  3020.                 if(!tmpCylinder)
  3021.                     continue;
  3022.  
  3023.                 if(tmpCylinder->__queryAdd(i, item, item->getItemCount(), flags) == RET_NOERROR)
  3024.                 {
  3025.                     index = i;
  3026.                     return tmpCylinder;
  3027.                 }
  3028.             }
  3029.         }
  3030.  
  3031.         return this;
  3032.     }
  3033.  
  3034.     Thing* destThing = __getThing(index);
  3035.     if(destThing)
  3036.         *destItem = destThing->getItem();
  3037.  
  3038.     if(Cylinder* subCylinder = dynamic_cast<Cylinder*>(destThing))
  3039.     {
  3040.         index = INDEX_WHEREEVER;
  3041.         *destItem = NULL;
  3042.         return subCylinder;
  3043.     }
  3044.  
  3045.     return this;
  3046. }
  3047.  
  3048. void Player::__addThing(Creature* actor, Thing* thing)
  3049. {
  3050.     __addThing(actor, 0, thing);
  3051. }
  3052.  
  3053. void Player::__addThing(Creature*, int32_t index, Thing* thing)
  3054. {
  3055.     if(index < 0 || index > 11)
  3056.     {
  3057. #ifdef __DEBUG_MOVESYS__
  3058.         std::clog << "Failure: [Player::__addThing], " << "player: " << getName() << ", index: " << index << ", index < 0 || index > 11" << std::endl;
  3059. #endif
  3060.         return /*RET_NOTPOSSIBLE*/;
  3061.     }
  3062.  
  3063.     if(!index)
  3064.     {
  3065. #ifdef __DEBUG_MOVESYS__
  3066.         std::clog << "Failure: [Player::__addThing], " << "player: " << getName() << ", index == 0" << std::endl;
  3067. #endif
  3068.         return /*RET_NOTENOUGHROOM*/;
  3069.     }
  3070.  
  3071.     Item* item = thing->getItem();
  3072.     if(!item)
  3073.     {
  3074. #ifdef __DEBUG_MOVESYS__
  3075.         std::clog << "Failure: [Player::__addThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3076. #endif
  3077.         return /*RET_NOTPOSSIBLE*/;
  3078.     }
  3079.  
  3080.     item->setParent(this);
  3081.     inventory[index] = item;
  3082.  
  3083.     //send to client
  3084.     sendAddInventoryItem((slots_t)index, item);
  3085.     //event methods
  3086.     onAddInventoryItem((slots_t)index, item);
  3087. }
  3088.  
  3089. void Player::__updateThing(Thing* thing, uint16_t itemId, uint32_t count)
  3090. {
  3091.     int32_t index = __getIndexOfThing(thing);
  3092.     if(index == -1)
  3093.     {
  3094. #ifdef __DEBUG_MOVESYS__
  3095.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", index == -1" << std::endl;
  3096. #endif
  3097.         return /*RET_NOTPOSSIBLE*/;
  3098.     }
  3099.  
  3100.     Item* item = thing->getItem();
  3101.     if(!item)
  3102.     {
  3103. #ifdef __DEBUG_MOVESYS__
  3104.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3105. #endif
  3106.         return /*RET_NOTPOSSIBLE*/;
  3107.     }
  3108.  
  3109.     const ItemType& oldType = Item::items[item->getID()];
  3110.     const ItemType& newType = Item::items[itemId];
  3111.  
  3112.     item->setID(itemId);
  3113.     item->setSubType(count);
  3114.  
  3115.     //send to client
  3116.     sendUpdateInventoryItem((slots_t)index, item, item);
  3117.     //event methods
  3118.     onUpdateInventoryItem((slots_t)index, item, oldType, item, newType);
  3119. }
  3120.  
  3121. void Player::__replaceThing(uint32_t index, Thing* thing)
  3122. {
  3123.     if(index > 11)
  3124.     {
  3125. #ifdef __DEBUG_MOVESYS__
  3126.         std::clog << "Failure: [Player::__replaceThing], " << "player: " << getName() << ", index: " << index << ", index < 0 || index > 11" << std::endl;
  3127. #endif
  3128.         return /*RET_NOTPOSSIBLE*/;
  3129.     }
  3130.  
  3131.     Item* oldItem = getInventoryItem((slots_t)index);
  3132.     if(!oldItem)
  3133.     {
  3134. #ifdef __DEBUG_MOVESYS__
  3135.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", oldItem == NULL" << std::endl;
  3136. #endif
  3137.         return /*RET_NOTPOSSIBLE*/;
  3138.     }
  3139.  
  3140.     Item* item = thing->getItem();
  3141.     if(!item)
  3142.     {
  3143. #ifdef __DEBUG_MOVESYS__
  3144.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3145. #endif
  3146.         return /*RET_NOTPOSSIBLE*/;
  3147.     }
  3148.  
  3149.     const ItemType& oldType = Item::items[oldItem->getID()];
  3150.     const ItemType& newType = Item::items[item->getID()];
  3151.  
  3152.     //send to client
  3153.     sendUpdateInventoryItem((slots_t)index, oldItem, item);
  3154.     //event methods
  3155.     onUpdateInventoryItem((slots_t)index, oldItem, oldType, item, newType);
  3156.  
  3157.     item->setParent(this);
  3158.     inventory[index] = item;
  3159. }
  3160.  
  3161. void Player::__removeThing(Thing* thing, uint32_t count)
  3162. {
  3163.     Item* item = thing->getItem();
  3164.     if(!item)
  3165.     {
  3166. #ifdef __DEBUG_MOVESYS__
  3167.         std::clog << "Failure: [Player::__removeThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3168. #endif
  3169.         return /*RET_NOTPOSSIBLE*/;
  3170.     }
  3171.  
  3172.     int32_t index = __getIndexOfThing(thing);
  3173.     if(index == -1)
  3174.     {
  3175. #ifdef __DEBUG_MOVESYS__
  3176.         std::clog << "Failure: [Player::__removeThing], " << "player: " << getName() << ", index == -1" << std::endl;
  3177. #endif
  3178.         return /*RET_NOTPOSSIBLE*/;
  3179.     }
  3180.  
  3181.     if(item->isStackable())
  3182.     {
  3183.         if(count == item->getItemCount())
  3184.         {
  3185.             //send change to client
  3186.             sendRemoveInventoryItem((slots_t)index, item);
  3187.             //event methods
  3188.             onRemoveInventoryItem((slots_t)index, item);
  3189.  
  3190.             item->setParent(NULL);
  3191.             inventory[index] = NULL;
  3192.         }
  3193.         else
  3194.         {
  3195.             item->setItemCount(std::max(0, (int32_t)(item->getItemCount() - count)));
  3196.             const ItemType& it = Item::items[item->getID()];
  3197.  
  3198.             //send change to client
  3199.             sendUpdateInventoryItem((slots_t)index, item, item);
  3200.             //event methods
  3201.             onUpdateInventoryItem((slots_t)index, item, it, item, it);
  3202.         }
  3203.     }
  3204.     else
  3205.     {
  3206.         //send change to client
  3207.         sendRemoveInventoryItem((slots_t)index, item);
  3208.         //event methods
  3209.         onRemoveInventoryItem((slots_t)index, item);
  3210.  
  3211.         item->setParent(NULL);
  3212.         inventory[index] = NULL;
  3213.     }
  3214. }
  3215.  
  3216. Thing* Player::__getThing(uint32_t index) const
  3217. {
  3218.     if(index > SLOT_PRE_FIRST && index < SLOT_LAST)
  3219.         return inventory[index];
  3220.  
  3221.     return NULL;
  3222. }
  3223.  
  3224. int32_t Player::__getIndexOfThing(const Thing* thing) const
  3225. {
  3226.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3227.     {
  3228.         if(inventory[i] == thing)
  3229.             return i;
  3230.     }
  3231.  
  3232.     return -1;
  3233. }
  3234.  
  3235. int32_t Player::__getFirstIndex() const
  3236. {
  3237.     return SLOT_FIRST;
  3238. }
  3239.  
  3240. int32_t Player::__getLastIndex() const
  3241. {
  3242.     return SLOT_LAST;
  3243. }
  3244.  
  3245. uint32_t Player::__getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const
  3246. {
  3247.     Item* item = NULL;
  3248.     Container* container = NULL;
  3249.  
  3250.     uint32_t count = 0;
  3251.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3252.     {
  3253.         if(!(item = inventory[i]))
  3254.             continue;
  3255.  
  3256.         if(item->getID() != itemId)
  3257.         {
  3258.             if(!(container = item->getContainer()))
  3259.                 continue;
  3260.  
  3261.             for(ContainerIterator it = container->begin(), end = container->end(); it != end; ++it)
  3262.             {
  3263.                 if((*it)->getID() == itemId)
  3264.                     count += Item::countByType(*it, subType);
  3265.             }
  3266.         }
  3267.         else
  3268.             count += Item::countByType(item, subType);
  3269.     }
  3270.  
  3271.     return count;
  3272.  
  3273. }
  3274.  
  3275. std::map<uint32_t, uint32_t>& Player::__getAllItemTypeCount(std::map<uint32_t, uint32_t>& countMap) const
  3276. {
  3277.     Item* item = NULL;
  3278.     Container* container = NULL;
  3279.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3280.     {
  3281.         if(!(item = inventory[i]))
  3282.             continue;
  3283.  
  3284.         countMap[item->getID()] += Item::countByType(item, -1);
  3285.         if(!(container = item->getContainer()))
  3286.             continue;
  3287.  
  3288.         for(ContainerIterator it = container->begin(), end = container->end(); it != end; ++it)
  3289.             countMap[(*it)->getID()] += Item::countByType(*it, -1);
  3290.     }
  3291.  
  3292.     return countMap;
  3293. }
  3294.  
  3295. void Player::postAddNotification(Creature*, Thing* thing, const Cylinder* oldParent,
  3296.     int32_t index, cylinderlink_t link /*= LINK_OWNER*/)
  3297. {
  3298.     if(link == LINK_OWNER) //calling movement scripts
  3299.         g_moveEvents->onPlayerEquip(this, thing->getItem(), (slots_t)index, false);
  3300.  
  3301.     bool requireListUpdate = true;
  3302.     if(link == LINK_OWNER || link == LINK_TOPPARENT)
  3303.     {
  3304.         if(const Item* item = (oldParent ? oldParent->getItem() : NULL))
  3305.         {
  3306.             assert(item->getContainer() != NULL);
  3307.             requireListUpdate = item->getContainer()->getHoldingPlayer() != this;
  3308.         }
  3309.         else
  3310.             requireListUpdate = oldParent != this;
  3311.  
  3312.         updateInventoryWeight();
  3313.         updateItemsLight();
  3314.         updateWeapon();
  3315.         sendStats();
  3316.     }
  3317.  
  3318.     if(const Item* item = thing->getItem())
  3319.     {
  3320.         if(const Container* container = item->getContainer())
  3321.             onSendContainer(container);
  3322.  
  3323.         if(shopOwner && requireListUpdate)
  3324.             updateInventoryGoods(item->getID());
  3325.     }
  3326.     else if(const Creature* creature = thing->getCreature())
  3327.     {
  3328.         if(creature != this)
  3329.             return;
  3330.  
  3331.         std::vector<Container*> containers;
  3332.         for(ContainerVector::iterator it = containerVec.begin(); it != containerVec.end(); ++it)
  3333.         {
  3334.             if(!Position::areInRange<1,1,0>(it->second->getPosition(), getPosition()))
  3335.                 containers.push_back(it->second);
  3336.         }
  3337.  
  3338.         for(std::vector<Container*>::const_iterator it = containers.begin(); it != containers.end(); ++it)
  3339.             autoCloseContainers(*it);
  3340.     }
  3341. }
  3342.  
  3343. void Player::postRemoveNotification(Creature*, Thing* thing, const Cylinder* newParent,
  3344.     int32_t index, bool isCompleteRemoval, cylinderlink_t link /*= LINK_OWNER*/)
  3345. {
  3346.     if(link == LINK_OWNER) //calling movement scripts
  3347.         g_moveEvents->onPlayerDeEquip(this, thing->getItem(), (slots_t)index, isCompleteRemoval);
  3348.  
  3349.     bool requireListUpdate = true;
  3350.     if(link == LINK_OWNER || link == LINK_TOPPARENT)
  3351.     {
  3352.         if(const Item* item = (newParent ? newParent->getItem() : NULL))
  3353.         {
  3354.             assert(item->getContainer() != NULL);
  3355.             requireListUpdate = item->getContainer()->getHoldingPlayer() != this;
  3356.         }
  3357.         else
  3358.             requireListUpdate = newParent != this;
  3359.  
  3360.         updateInventoryWeight();
  3361.         updateItemsLight();
  3362.         updateWeapon();
  3363.         sendStats();
  3364.     }
  3365.  
  3366.     if(const Item* item = thing->getItem())
  3367.     {
  3368.         if(const Container* container = item->getContainer())
  3369.         {
  3370.             if(container->isRemoved() || !Position::areInRange<1,1,0>(getPosition(), container->getPosition()))
  3371.                 autoCloseContainers(container);
  3372.             else if(container->getTopParent() == this)
  3373.                 onSendContainer(container);
  3374.             else if(const Container* topContainer = dynamic_cast<const Container*>(container->getTopParent()))
  3375.             {
  3376.                 if(const Depot* depot = dynamic_cast<const Depot*>(topContainer))
  3377.                 {
  3378.                     bool isOwner = false;
  3379.                     for(DepotMap::iterator it = depots.begin(); it != depots.end(); ++it)
  3380.                     {
  3381.                         if(it->second.first != depot)
  3382.                             continue;
  3383.  
  3384.                         isOwner = true;
  3385.                         onSendContainer(container);
  3386.                     }
  3387.  
  3388.                     if(!isOwner)
  3389.                         autoCloseContainers(container);
  3390.                 }
  3391.                 else
  3392.                     onSendContainer(container);
  3393.             }
  3394.             else
  3395.                 autoCloseContainers(container);
  3396.         }
  3397.  
  3398.         if(shopOwner && requireListUpdate)
  3399.             updateInventoryGoods(item->getID());
  3400.     }
  3401. }
  3402.  
  3403. void Player::__internalAddThing(Thing* thing)
  3404. {
  3405.     __internalAddThing(0, thing);
  3406. }
  3407.  
  3408. void Player::__internalAddThing(uint32_t index, Thing* thing)
  3409. {
  3410. #ifdef __DEBUG_MOVESYS__
  3411.     std::clog << "[Player::__internalAddThing] index: " << index << std::endl;
  3412.  
  3413. #endif
  3414.     if(!index || index > 11)
  3415.     {
  3416. #ifdef __DEBUG_MOVESYS__
  3417.         std::clog << "Failure: [Player::__internalAddThing] index == 0 || index > 11" << std::endl;
  3418. #endif
  3419.         return;
  3420.     }
  3421.  
  3422.     if(inventory[index])
  3423.     {
  3424. #ifdef __DEBUG_MOVESYS__
  3425.         std::clog << "Warning: [Player::__internalAddThing], player: " << getName() << ", items[index] is not empty." << std::endl;
  3426. #endif
  3427.         return;
  3428.     }
  3429.  
  3430.     Item* item = thing->getItem();
  3431.     if(!item)
  3432.     {
  3433. #ifdef __DEBUG_MOVESYS__
  3434.         std::clog << "Failure: [Player::__internalAddThing] item == NULL" << std::endl;
  3435. #endif
  3436.         return;
  3437.     }
  3438.  
  3439.     inventory[index] = item;
  3440.     item->setParent(this);
  3441. }
  3442.  
  3443. bool Player::setFollowCreature(Creature* creature, bool fullPathSearch /*= false*/)
  3444. {
  3445.     bool deny = false;
  3446.     CreatureEventList followEvents = getCreatureEvents(CREATURE_EVENT_FOLLOW);
  3447.     for(CreatureEventList::iterator it = followEvents.begin(); it != followEvents.end(); ++it)
  3448.     {
  3449.         if(creature && !(*it)->executeFollow(this, creature))
  3450.             deny = true;
  3451.     }
  3452.  
  3453.     if(!deny && Creature::setFollowCreature(creature, fullPathSearch))
  3454.         return true;
  3455.  
  3456.     setFollowCreature(NULL);
  3457.     setAttackedCreature(NULL);
  3458.     if(!deny)
  3459.         sendCancelMessage(RET_THEREISNOWAY);
  3460.  
  3461.     sendCancelTarget();
  3462.     cancelNextWalk = true;
  3463.     return false;
  3464. }
  3465.  
  3466. bool Player::setAttackedCreature(Creature* creature)
  3467. {
  3468.     if(!Creature::setAttackedCreature(creature))
  3469.     {
  3470.         sendCancelTarget();
  3471.         return false;
  3472.     }
  3473.  
  3474.     if(chaseMode == CHASEMODE_FOLLOW && creature)
  3475.     {
  3476.         if(followCreature != creature) //chase opponent
  3477.             setFollowCreature(creature);
  3478.     }
  3479.     else
  3480.         setFollowCreature(NULL);
  3481.  
  3482.     if(creature)
  3483.         Dispatcher::getInstance().addTask(createTask(boost::bind(&Game::checkCreatureAttack, &g_game, getID())));
  3484.  
  3485.     return true;
  3486. }
  3487.  
  3488. void Player::goToFollowCreature()
  3489. {
  3490.     if(!walkTask)
  3491.         Creature::goToFollowCreature();
  3492. }
  3493.  
  3494. void Player::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const
  3495. {
  3496.     Creature::getPathSearchParams(creature, fpp);
  3497.     fpp.fullPathSearch = true;
  3498. }
  3499.  
  3500. void Player::doAttacking(uint32_t)
  3501. {
  3502.     if(!lastAttack)
  3503.         lastAttack = OTSYS_TIME() - getAttackSpeed() - 1;
  3504.     else if((OTSYS_TIME() - lastAttack) < getAttackSpeed())
  3505.         return;
  3506.  
  3507.     if(hasCondition(CONDITION_PACIFIED) && !hasCustomFlag(PlayerCustomFlag_IgnorePacification))
  3508.     {
  3509.         lastAttack = OTSYS_TIME();
  3510.         return;
  3511.     }
  3512.  
  3513.     Item* item = getWeapon(false);
  3514.     if(const Weapon* _weapon = g_weapons->getWeapon(item))
  3515.     {
  3516.         if(_weapon->interruptSwing() && !canDoAction())
  3517.         {
  3518.             SchedulerTask* task = createSchedulerTask(getNextActionTime(),
  3519.                 boost::bind(&Game::checkCreatureAttack, &g_game, getID()));
  3520.             setNextActionTask(task);
  3521.         }
  3522.         else
  3523.         {
  3524.             if((!_weapon->hasExhaustion() || !hasCondition(CONDITION_EXHAUST, EXHAUST_COMBAT)) && _weapon->useWeapon(this, item, attackedCreature))
  3525.                 lastAttack = OTSYS_TIME();
  3526.  
  3527.             updateWeapon();
  3528.         }
  3529.     }
  3530.     else if(Weapon::useFist(this, attackedCreature))
  3531.         lastAttack = OTSYS_TIME();
  3532. }
  3533.  
  3534. double Player::getGainedExperience(Creature* attacker) const
  3535. {
  3536.     if(!skillLoss)
  3537.         return 0;
  3538.  
  3539.     double rate = g_config.getDouble(ConfigManager::RATE_PVP_EXPERIENCE);
  3540.     if(rate <= 0)
  3541.         return 0;
  3542.  
  3543.     Player* attackerPlayer = attacker->getPlayer();
  3544.     if(!attackerPlayer || attackerPlayer == this)
  3545.         return 0;
  3546.  
  3547.     double attackerLevel = (double)attackerPlayer->getLevel(), min = g_config.getDouble(
  3548.         ConfigManager::EFP_MIN_THRESHOLD), max = g_config.getDouble(ConfigManager::EFP_MAX_THRESHOLD);
  3549.     if((min > 0 && level < (uint32_t)std::floor(attackerLevel * min)) || (max > 0 &&
  3550.         level > (uint32_t)std::floor(attackerLevel * max)))
  3551.         return 0;
  3552.  
  3553.     /*
  3554.         Formula
  3555.         a = attackers level * 0.9
  3556.         b = victims level
  3557.         c = victims experience
  3558.         result = (1 - (a / b)) * 0.05 * c
  3559.         Not affected by special multipliers(!)
  3560.     */
  3561.     uint32_t a = (uint32_t)std::floor(attackerLevel * 0.9), b = level;
  3562.     uint64_t c = getExperience();
  3563.     return (double)std::max((uint64_t)0, (uint64_t)std::floor(getDamageRatio(attacker)
  3564.         * std::max((double)0, ((double)(1 - (((double)a / b))))) * 0.05 * c)) * rate;
  3565. }
  3566.  
  3567. void Player::onFollowCreature(const Creature* creature)
  3568. {
  3569.     if(!creature)
  3570.         cancelNextWalk = true;
  3571. }
  3572.  
  3573. void Player::setChaseMode(chaseMode_t mode)
  3574. {
  3575.     chaseMode_t prevChaseMode = chaseMode;
  3576.     chaseMode = mode;
  3577.  
  3578.     if(prevChaseMode == chaseMode)
  3579.         return;
  3580.  
  3581.     if(chaseMode == CHASEMODE_FOLLOW)
  3582.     {
  3583.         if(!followCreature && attackedCreature) //chase opponent
  3584.             setFollowCreature(attackedCreature);
  3585.     }
  3586.     else if(attackedCreature)
  3587.     {
  3588.         setFollowCreature(NULL);
  3589.         cancelNextWalk = true;
  3590.     }
  3591. }
  3592.  
  3593. void Player::onWalkAborted()
  3594. {
  3595.     setNextWalkActionTask(NULL);
  3596.     sendCancelWalk();
  3597. }
  3598.  
  3599. void Player::onWalkComplete()
  3600. {
  3601.     if(!walkTask)
  3602.         return;
  3603.  
  3604.     walkTaskEvent = Scheduler::getInstance().addEvent(walkTask);
  3605.     walkTask = NULL;
  3606. }
  3607.  
  3608. void Player::getCreatureLight(LightInfo& light) const
  3609. {
  3610.     if(internalLight.level > itemsLight.level)
  3611.         light = internalLight;
  3612.     else
  3613.         light = itemsLight;
  3614. }
  3615.  
  3616. void Player::updateItemsLight(bool internal/* = false*/)
  3617. {
  3618.     LightInfo maxLight, curLight;
  3619.     Item* item = NULL;
  3620.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3621.     {
  3622.         if(!(item = getInventoryItem((slots_t)i)))
  3623.             continue;
  3624.  
  3625.         item->getLight(curLight);
  3626.         if(curLight.level > maxLight.level)
  3627.             maxLight = curLight;
  3628.     }
  3629.  
  3630.     if(itemsLight.level != maxLight.level || itemsLight.color != maxLight.color)
  3631.     {
  3632.         itemsLight = maxLight;
  3633.         if(!internal)
  3634.             g_game.changeLight(this);
  3635.     }
  3636. }
  3637.  
  3638. void Player::onAddCondition(ConditionType_t type, bool hadCondition)
  3639. {
  3640.     Creature::onAddCondition(type, hadCondition);
  3641.     if(getLastPosition().x && type != CONDITION_GAMEMASTER) // don't send if player have just logged in (its already done in protocolgame), or condition have no icons
  3642.         sendIcons();
  3643. }
  3644.  
  3645. void Player::onAddCombatCondition(ConditionType_t type, bool)
  3646. {
  3647.     std::string tmp;
  3648.     switch(type)
  3649.     {
  3650.         //client hardcoded
  3651.         case CONDITION_FIRE:
  3652.             tmp = "burning";
  3653.             break;
  3654.         case CONDITION_POISON:
  3655.             tmp = "poisoned";
  3656.             break;
  3657.         case CONDITION_ENERGY:
  3658.             tmp = "electrified";
  3659.             break;
  3660.         case CONDITION_FREEZING:
  3661.             tmp = "freezing";
  3662.             break;
  3663.         case CONDITION_DAZZLED:
  3664.             tmp = "dazzled";
  3665.             break;
  3666.         case CONDITION_CURSED:
  3667.             tmp = "cursed";
  3668.             break;
  3669.         case CONDITION_DROWN:
  3670.             tmp = "drowning";
  3671.             break;
  3672.         case CONDITION_DRUNK:
  3673.             tmp = "drunk";
  3674.             break;
  3675.         case CONDITION_PARALYZE:
  3676.             tmp = "paralyzed";
  3677.             break;
  3678.         /*case CONDITION_MANASHIELD:
  3679.             tmp = "protected by a magic shield";
  3680.             break;
  3681.         case CONDITION_HASTE:
  3682.             tmp = "hasted";
  3683.             break;
  3684.         case CONDITION_ATTRIBUTES:
  3685.             tmp = "strengthened";
  3686.             break;*/
  3687.         default:
  3688.             break;
  3689.     }
  3690.  
  3691.     if(!tmp.empty())
  3692.         sendTextMessage(MSG_STATUS_DEFAULT, "You are " + tmp + ".");
  3693. }
  3694.  
  3695. void Player::onEndCondition(ConditionType_t type)
  3696. {
  3697.     Creature::onEndCondition(type);
  3698.     if(type == CONDITION_INFIGHT)
  3699.     {
  3700.         onIdleStatus();
  3701.         clearAttacked();
  3702.  
  3703.         pzLocked = false;
  3704.         if(skull < SKULL_RED)
  3705.             setSkull(SKULL_NONE);
  3706.  
  3707.         g_game.updateCreatureSkull(this);
  3708.     }
  3709.  
  3710.     sendIcons();
  3711. }
  3712.  
  3713. void Player::onCombatRemoveCondition(const Creature*, Condition* condition)
  3714. {
  3715.     //Creature::onCombatRemoveCondition(attacker, condition);
  3716.     bool remove = true;
  3717.     if(condition->getId() > 0)
  3718.     {
  3719.         remove = false;
  3720.         //Means the condition is from an item, id == slot
  3721.         if(g_game.getWorldType() == WORLDTYPE_HARDCORE)
  3722.         {
  3723.             if(Item* item = getInventoryItem((slots_t)condition->getId()))
  3724.             {
  3725.                 //25% chance to destroy the item
  3726.                 if(random_range(1, 100) < 26)
  3727.                     g_game.internalRemoveItem(NULL, item);
  3728.             }
  3729.         }
  3730.     }
  3731.  
  3732.     if(remove)
  3733.     {
  3734.         if(!canDoAction())
  3735.         {
  3736.             int32_t delay = getNextActionTime();
  3737.             delay -= (delay % EVENT_CREATURE_THINK_INTERVAL);
  3738.             if(delay < 0)
  3739.                 removeCondition(condition);
  3740.             else
  3741.                 condition->setTicks(delay);
  3742.         }
  3743.         else
  3744.             removeCondition(condition);
  3745.     }
  3746. }
  3747.  
  3748. void Player::onTickCondition(ConditionType_t type, int32_t interval, bool& _remove)
  3749. {
  3750.     Creature::onTickCondition(type, interval, _remove);
  3751.     if(type == CONDITION_HUNTING)
  3752.         useStamina(-(interval * g_config.getNumber(ConfigManager::RATE_STAMINA_LOSS)));
  3753. }
  3754.  
  3755. void Player::onAttackedCreature(Creature* target)
  3756. {
  3757.     Creature::onAttackedCreature(target);
  3758.     if(hasFlag(PlayerFlag_NotGainInFight))
  3759.         return;
  3760.  
  3761.     addInFightTicks(false);
  3762.     Player* targetPlayer = target->getPlayer();
  3763.     if(!targetPlayer)
  3764.         return;
  3765.  
  3766.     addAttacked(targetPlayer);
  3767.     if(targetPlayer == this && targetPlayer->getZone() != ZONE_HARDCORE)
  3768.     {
  3769.         targetPlayer->sendCreatureSkull(this);
  3770.         return;
  3771.     }
  3772.  
  3773.     if(Combat::isInPvpZone(this, targetPlayer) || isPartner(targetPlayer) ||
  3774.         isAlly(targetPlayer) ||
  3775.         (g_config.getBool(ConfigManager::ALLOW_FIGHTBACK) && targetPlayer->hasAttacked(this)
  3776.         && !targetPlayer->isEnemy(this, false)
  3777.         ))
  3778.         return;
  3779.  
  3780.     if(!pzLocked)
  3781.     {
  3782.         pzLocked = true;
  3783.         sendIcons();
  3784.     }
  3785.  
  3786.     if(getZone() != target->getZone() || skull != SKULL_NONE
  3787.         || targetPlayer->isEnemy(this, true)
  3788.         )
  3789.         return;
  3790.  
  3791.     if(targetPlayer->getSkull() != SKULL_NONE)
  3792.         targetPlayer->sendCreatureSkull(this);
  3793.     else if(!hasCustomFlag(PlayerCustomFlag_NotGainSkull))
  3794.     {
  3795.         setSkull(SKULL_WHITE);
  3796.         g_game.updateCreatureSkull(this);
  3797.     }
  3798. }
  3799.  
  3800. void Player::onSummonAttackedCreature(Creature* summon, Creature* target)
  3801. {
  3802.     Creature::onSummonAttackedCreature(summon, target);
  3803.     onAttackedCreature(target);
  3804. }
  3805.  
  3806. void Player::onAttacked()
  3807. {
  3808.     Creature::onAttacked();
  3809.     addInFightTicks(false);
  3810. }
  3811.  
  3812. bool Player::checkLoginDelay(uint32_t playerId) const
  3813. {
  3814.     return (!hasCustomFlag(PlayerCustomFlag_IgnoreLoginDelay) && OTSYS_TIME() <= (lastLoad + g_config.getNumber(
  3815.         ConfigManager::LOGIN_PROTECTION)) && !hasBeenAttacked(playerId));
  3816. }
  3817.  
  3818. void Player::onIdleStatus()
  3819. {
  3820.     Creature::onIdleStatus();
  3821.     if(getParty())
  3822.         getParty()->clearPlayerPoints(this);
  3823. }
  3824.  
  3825. void Player::onPlacedCreature()
  3826. {
  3827.     //scripting event - onLogin
  3828.     if(!g_creatureEvents->playerLogin(this))
  3829.         kickPlayer(true, true);
  3830. }
  3831.  
  3832. void Player::onAttackedCreatureDrain(Creature* target, int32_t points)
  3833. {
  3834.     Creature::onAttackedCreatureDrain(target, points);
  3835.     if(party && target && (!target->getMaster() || !target->getMaster()->getPlayer())
  3836.         && target->getMonster() && target->getMonster()->isHostile()) //we have fulfilled a requirement for shared experience
  3837.         getParty()->addPlayerDamageMonster(this, points);
  3838.  
  3839.     char buffer[100];
  3840.     sprintf(buffer, "You deal %d damage to %s.", points, target->getNameDescription().c_str());
  3841.     sendTextMessage(MSG_STATUS_DEFAULT, buffer);
  3842. }
  3843.  
  3844. void Player::onSummonAttackedCreatureDrain(Creature* summon, Creature* target, int32_t points)
  3845. {
  3846.     Creature::onSummonAttackedCreatureDrain(summon, target, points);
  3847.  
  3848.     char buffer[100];
  3849.     sprintf(buffer, "Your %s deals %d damage to %s.", summon->getName().c_str(), points, target->getNameDescription().c_str());
  3850.     sendTextMessage(MSG_EVENT_DEFAULT, buffer);
  3851. }
  3852.  
  3853. void Player::onTargetCreatureGainHealth(Creature* target, int32_t points)
  3854. {
  3855.     Creature::onTargetCreatureGainHealth(target, points);
  3856.     if(target && getParty())
  3857.     {
  3858.         Player* tmpPlayer = NULL;
  3859.         if(target->getPlayer())
  3860.             tmpPlayer = target->getPlayer();
  3861.         else if(target->getMaster() && target->getMaster()->getPlayer())
  3862.             tmpPlayer = target->getMaster()->getPlayer();
  3863.  
  3864.         if(isPartner(tmpPlayer))
  3865.             party->addPlayerHealedMember(this, points);
  3866.     }
  3867. }
  3868.  
  3869. GuildEmblems_t Player::getGuildEmblem(const Creature* creature) const
  3870. {
  3871.     const Player* player = creature->getPlayer();
  3872.     if(!player || !player->hasEnemy())
  3873.         return Creature::getGuildEmblem(creature);
  3874.  
  3875.     if(player->isEnemy(this, false))
  3876.         return EMBLEM_RED;
  3877.  
  3878.     return player->getGuildId() == guildId ? EMBLEM_GREEN : EMBLEM_BLUE;
  3879. }
  3880.  
  3881. bool Player::getEnemy(const Player* player, War_t& data) const
  3882. {
  3883.     if(!guildId || !player || player->isRemoved())
  3884.         return false;
  3885.  
  3886.     uint32_t guild = player->getGuildId();
  3887.     if(!guild)
  3888.         return false;
  3889.  
  3890.     WarMap::const_iterator it = warMap.find(guild);
  3891.     if(it == warMap.end())
  3892.         return false;
  3893.  
  3894.     data = it->second;
  3895.     return true;
  3896. }
  3897.  
  3898. bool Player::isEnemy(const Player* player, bool allies) const
  3899. {
  3900.     if(!guildId || !player || player->isRemoved())
  3901.         return false;
  3902.  
  3903.     uint32_t guild = player->getGuildId();
  3904.     if(!guild)
  3905.         return false;
  3906.  
  3907.     return !warMap.empty() && (((g_game.getWorldType() != WORLDTYPE_OPTIONAL || g_config.getBool(
  3908.         ConfigManager::OPTIONAL_WAR_ATTACK_ALLY)) && allies && guildId == guild) ||
  3909.         warMap.find(guild) != warMap.end());
  3910. }
  3911.  
  3912. bool Player::isAlly(const Player* player) const
  3913. {
  3914.     return !warMap.empty() && player && player->getGuildId() == guildId;
  3915. }
  3916.  
  3917. bool Player::onKilledCreature(Creature* target, DeathEntry& entry)
  3918. {
  3919.     if(!Creature::onKilledCreature(target, entry))
  3920.         return false;
  3921.  
  3922.     if(hasFlag(PlayerFlag_NotGenerateLoot))
  3923.         target->setDropLoot(LOOT_DROP_NONE);
  3924.  
  3925.     Condition* condition = NULL;
  3926.     if(target->getMonster() && !target->isPlayerSummon() && !hasFlag(PlayerFlag_HasInfiniteStamina)
  3927.         && (condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_HUNTING,
  3928.         g_config.getNumber(ConfigManager::HUNTING_DURATION))))
  3929.         addCondition(condition);
  3930.  
  3931.     if(hasFlag(PlayerFlag_NotGainInFight) || getZone() != target->getZone())
  3932.         return true;
  3933.  
  3934.     Player* targetPlayer = target->getPlayer();
  3935.     if(!targetPlayer || Combat::isInPvpZone(this, targetPlayer) || isPartner(targetPlayer) || isAlly(targetPlayer))
  3936.         return true;
  3937.  
  3938.     War_t enemy;
  3939.     if(targetPlayer->getEnemy(this, enemy) && (!entry.isLast() || IOGuild::getInstance()->war(enemy)))
  3940.         entry.setWar(enemy);
  3941.  
  3942.     if(!entry.isJustify() || !hasCondition(CONDITION_INFIGHT))
  3943.         return true;
  3944.  
  3945.     if(!targetPlayer->hasAttacked(this) && target->getSkull() == SKULL_NONE && targetPlayer != this
  3946.         && (addUnjustifiedKill(targetPlayer, !enemy.war) || entry.isLast()))
  3947.         entry.setUnjustified();
  3948.  
  3949.     addInFightTicks(true, g_config.getNumber(ConfigManager::WHITE_SKULL_TIME));
  3950.     return true;
  3951. }
  3952.  
  3953. bool Player::gainExperience(double& gainExp, bool fromMonster)
  3954. {
  3955.     if(!rateExperience(gainExp, fromMonster))
  3956.         return false;
  3957.  
  3958.     //soul regeneration
  3959.     if(gainExp >= level)
  3960.     {
  3961.         if(Condition* condition = Condition::createCondition(
  3962.             CONDITIONID_DEFAULT, CONDITION_SOUL, 4 * 60 * 1000))
  3963.         {
  3964.             condition->setParam(CONDITIONPARAM_SOULGAIN,
  3965.                 vocation->getGainAmount(GAIN_SOUL));
  3966.             condition->setParam(CONDITIONPARAM_SOULTICKS,
  3967.                 (vocation->getGainTicks(GAIN_SOUL) * 1000));
  3968.             addCondition(condition);
  3969.         }
  3970.     }
  3971.  
  3972.     addExperience((uint64_t)gainExp);
  3973.     return true;
  3974. }
  3975.  
  3976. bool Player::rateExperience(double& gainExp, bool fromMonster)
  3977. {
  3978.     if(hasFlag(PlayerFlag_NotGainExperience) || gainExp <= 0)
  3979.         return false;
  3980.  
  3981.     if(!fromMonster)
  3982.         return true;
  3983.  
  3984.     gainExp *= rates[SKILL__LEVEL] * g_game.getExperienceStage(level,
  3985.         vocation->getExperienceMultiplier());
  3986.     if(!hasFlag(PlayerFlag_HasInfiniteStamina))
  3987.     {
  3988.         int32_t minutes = getStaminaMinutes();
  3989.         if(minutes >= g_config.getNumber(ConfigManager::STAMINA_LIMIT_TOP))
  3990.         {
  3991.             if(isPremium() || !g_config.getNumber(ConfigManager::STAMINA_BONUS_PREMIUM))
  3992.                 gainExp *= g_config.getDouble(ConfigManager::RATE_STAMINA_ABOVE);
  3993.         }
  3994.         else if(minutes < (g_config.getNumber(ConfigManager::STAMINA_LIMIT_BOTTOM)) && minutes > 0)
  3995.             gainExp *= g_config.getDouble(ConfigManager::RATE_STAMINA_UNDER);
  3996.         else if(minutes <= 0)
  3997.             gainExp = 0;
  3998.     }
  3999.     else if(isPremium() || !g_config.getNumber(ConfigManager::STAMINA_BONUS_PREMIUM))
  4000.         gainExp *= g_config.getDouble(ConfigManager::RATE_STAMINA_ABOVE);
  4001.  
  4002.     return true;
  4003. }
  4004.  
  4005. void Player::onGainExperience(double& gainExp, bool fromMonster, bool multiplied)
  4006. {
  4007.     if(party && party->isSharedExperienceEnabled() && party->isSharedExperienceActive())
  4008.     {
  4009.         party->shareExperience(gainExp, fromMonster, multiplied);
  4010.         rateExperience(gainExp, fromMonster);
  4011.         return; //we will get a share of the experience through the sharing mechanism
  4012.     }
  4013.  
  4014.     if(gainExperience(gainExp, fromMonster))
  4015.         Creature::onGainExperience(gainExp, fromMonster, true);
  4016. }
  4017.  
  4018. void Player::onGainSharedExperience(double& gainExp, bool fromMonster, bool)
  4019. {
  4020.     if(gainExperience(gainExp, fromMonster))
  4021.         Creature::onGainSharedExperience(gainExp, fromMonster, true);
  4022. }
  4023.  
  4024. bool Player::isImmune(CombatType_t type) const
  4025. {
  4026.     return hasCustomFlag(PlayerCustomFlag_IsImmune) || Creature::isImmune(type);
  4027. }
  4028.  
  4029. bool Player::isImmune(ConditionType_t type) const
  4030. {
  4031.     return hasCustomFlag(PlayerCustomFlag_IsImmune) || Creature::isImmune(type);
  4032. }
  4033.  
  4034. bool Player::isAttackable() const
  4035. {
  4036.     return (!hasFlag(PlayerFlag_CannotBeAttacked) && !isAccountManager());
  4037. }
  4038.  
  4039. void Player::changeHealth(int32_t healthChange)
  4040. {
  4041.     Creature::changeHealth(healthChange);
  4042.     sendStats();
  4043. }
  4044.  
  4045. void Player::changeMana(int32_t manaChange)
  4046. {
  4047.     if(!hasFlag(PlayerFlag_HasInfiniteMana))
  4048.         Creature::changeMana(manaChange);
  4049.  
  4050.     sendStats();
  4051. }
  4052.  
  4053. void Player::changeSoul(int32_t soulChange)
  4054. {
  4055.     if(!hasFlag(PlayerFlag_HasInfiniteSoul))
  4056.         soul = std::min((int32_t)soulMax, (int32_t)soul + soulChange);
  4057.  
  4058.     sendStats();
  4059. }
  4060.  
  4061. bool Player::changeOutfit(Outfit_t outfit, bool checkList)
  4062. {
  4063.     uint32_t outfitId = Outfits::getInstance()->getOutfitId(outfit.lookType);
  4064.     if(checkList && (!canWearOutfit(outfitId, outfit.lookAddons) || !requestedOutfit))
  4065.         return false;
  4066.  
  4067.     requestedOutfit = false;
  4068.     if(outfitAttributes)
  4069.     {
  4070.         uint32_t oldId = Outfits::getInstance()->getOutfitId(defaultOutfit.lookType);
  4071.         outfitAttributes = !Outfits::getInstance()->removeAttributes(getID(), oldId, sex);
  4072.     }
  4073.  
  4074.     defaultOutfit = outfit;
  4075.     outfitAttributes = Outfits::getInstance()->addAttributes(getID(), outfitId, sex, defaultOutfit.lookAddons);
  4076.     return true;
  4077. }
  4078.  
  4079. bool Player::canWearOutfit(uint32_t outfitId, uint32_t addons)
  4080. {
  4081.     OutfitMap::iterator it = outfits.find(outfitId);
  4082.     if(it == outfits.end() || (it->second.isPremium && !isPremium()) || getAccess() < it->second.accessLevel
  4083.         || ((it->second.addons & addons) != addons && !hasCustomFlag(PlayerCustomFlag_CanWearAllAddons)))
  4084.         return false;
  4085.  
  4086.     if(!it->second.storageId)
  4087.         return true;
  4088.  
  4089.     std::string value;
  4090.     getStorage(it->second.storageId, value);
  4091.  
  4092.     bool ret = value == it->second.storageValue;
  4093.     if(ret)
  4094.         return ret;
  4095.  
  4096.     int32_t tmp = atoi(value.c_str());
  4097.     if(!tmp && value != "0")
  4098.         return ret;
  4099.  
  4100.     tmp = atoi(it->second.storageValue.c_str());
  4101.     if(!tmp && it->second.storageValue != "0")
  4102.         return ret;
  4103.  
  4104.     return atoi(value.c_str()) >= tmp;
  4105. }
  4106.  
  4107. bool Player::addOutfit(uint32_t outfitId, uint32_t addons)
  4108. {
  4109.     Outfit outfit;
  4110.     if(!Outfits::getInstance()->getOutfit(outfitId, sex, outfit))
  4111.         return false;
  4112.  
  4113.     OutfitMap::iterator it = outfits.find(outfitId);
  4114.     if(it != outfits.end())
  4115.         outfit.addons |= it->second.addons;
  4116.  
  4117.     outfit.addons |= addons;
  4118.     outfits[outfitId] = outfit;
  4119.     return true;
  4120. }
  4121.  
  4122. bool Player::removeOutfit(uint32_t outfitId, uint32_t addons)
  4123. {
  4124.     OutfitMap::iterator it = outfits.find(outfitId);
  4125.     if(it == outfits.end())
  4126.         return false;
  4127.  
  4128.     if(addons == 0xFF) //remove outfit
  4129.         outfits.erase(it);
  4130.     else //remove addons
  4131.         outfits[outfitId].addons = it->second.addons & (~addons);
  4132.  
  4133.     return true;
  4134. }
  4135.  
  4136. void Player::generateReservedStorage()
  4137. {
  4138.     uint32_t baseKey = PSTRG_OUTFITSID_RANGE_START + 1;
  4139.     const OutfitMap& defaultOutfits = Outfits::getInstance()->getOutfits(sex);
  4140.     for(OutfitMap::const_iterator it = outfits.begin(); it != outfits.end(); ++it)
  4141.     {
  4142.         OutfitMap::const_iterator dit = defaultOutfits.find(it->first);
  4143.         if(dit == defaultOutfits.end() || (dit->second.isDefault && (dit->second.addons
  4144.             & it->second.addons) == it->second.addons))
  4145.             continue;
  4146.  
  4147.         std::stringstream ss;
  4148.         ss << ((it->first << 16) | (it->second.addons & 0xFF));
  4149.         storageMap[baseKey] = ss.str();
  4150.  
  4151.         baseKey++;
  4152.         if(baseKey <= PSTRG_OUTFITSID_RANGE_START + PSTRG_OUTFITSID_RANGE_SIZE)
  4153.             continue;
  4154.  
  4155.         std::clog << "[Warning - Player::genReservedStorageRange] Player " << getName() << " with more than 500 outfits!" << std::endl;
  4156.         break;
  4157.     }
  4158. }
  4159.  
  4160. void Player::setSex(uint16_t newSex)
  4161. {
  4162.     sex = newSex;
  4163.     const OutfitMap& defaultOutfits = Outfits::getInstance()->getOutfits(sex);
  4164.     for(OutfitMap::const_iterator it = defaultOutfits.begin(); it != defaultOutfits.end(); ++it)
  4165.     {
  4166.         if(it->second.isDefault)
  4167.             addOutfit(it->first, it->second.addons);
  4168.     }
  4169. }
  4170.  
  4171. Skulls_t Player::getSkull() const
  4172. {
  4173.     if(hasFlag(PlayerFlag_NotGainInFight) || hasCustomFlag(PlayerCustomFlag_NotGainSkull))
  4174.         return SKULL_NONE;
  4175.  
  4176.     return skull;
  4177. }
  4178.  
  4179. Skulls_t Player::getSkullType(const Creature* creature) const
  4180. {
  4181.     if(const Player* player = creature->getPlayer())
  4182.     {
  4183.         if(g_game.getWorldType() != WORLDTYPE_OPEN)
  4184.             return SKULL_NONE;
  4185.  
  4186.         if((player == this || (skull != SKULL_NONE && player->getSkull() < SKULL_RED)) && player->hasAttacked(this) && !player->isEnemy(this, false))
  4187.             return SKULL_YELLOW;
  4188.  
  4189.         if(player->getSkull() == SKULL_NONE && (isPartner(player) || isAlly(player)) && g_game.getWorldType() != WORLDTYPE_OPTIONAL)
  4190.             return SKULL_GREEN;
  4191.     }
  4192.  
  4193.     return Creature::getSkullType(creature);
  4194. }
  4195.  
  4196. bool Player::hasAttacked(const Player* attacked) const
  4197. {
  4198.     if (hasFlag(PlayerFlag_NotGainInFight) || !attacked)
  4199.         return false;
  4200.  
  4201.     return attackedSet.find(attacked->guid) != attackedSet.end();
  4202. }
  4203.  
  4204. void Player::addAttacked(const Player* attacked)
  4205. {
  4206.     if(hasFlag(PlayerFlag_NotGainInFight) || !attacked)
  4207.         return;
  4208.  
  4209.     uint32_t attackedId = attacked->getID();
  4210.     if(attackedSet.find(attackedId) == attackedSet.end())
  4211.         attackedSet.insert(attackedId);
  4212. }
  4213.  
  4214. void Player::setSkullEnd(time_t _time, bool login, Skulls_t _skull)
  4215. {
  4216.     if(g_game.getWorldType() != WORLDTYPE_OPEN
  4217.         || hasFlag(PlayerFlag_NotGainInFight) ||
  4218.         hasCustomFlag(PlayerCustomFlag_NotGainSkull))
  4219.         return;
  4220.  
  4221.     bool requireUpdate = false;
  4222.     if(_time > time(NULL))
  4223.     {
  4224.         requireUpdate = true;
  4225.         setSkull(_skull);
  4226.     }
  4227.     else if(skull == _skull)
  4228.     {
  4229.         requireUpdate = true;
  4230.         setSkull(SKULL_NONE);
  4231.         _time = 0;
  4232.     }
  4233.  
  4234.     if(requireUpdate)
  4235.     {
  4236.         skullEnd = _time;
  4237.         if(!login)
  4238.             g_game.updateCreatureSkull(this);
  4239.     }
  4240. }
  4241.  
  4242. bool Player::addUnjustifiedKill(const Player* attacked, bool countNow)
  4243. {
  4244.     if(!g_config.getBool(ConfigManager::USE_FRAG_HANDLER) || hasFlag(
  4245.         PlayerFlag_NotGainInFight) || g_game.getWorldType() != WORLDTYPE_OPEN
  4246.         || hasCustomFlag(PlayerCustomFlag_NotGainUnjustified) || hasCustomFlag(
  4247.         PlayerCustomFlag_NotGainSkull) || attacked == this)
  4248.         return false;
  4249.  
  4250.     if(client && countNow)
  4251.     {
  4252.         char buffer[90];
  4253.         sprintf(buffer, "Warning! The murder of %s was not justified.",
  4254.             attacked->getName().c_str());
  4255.         client->sendTextMessage(MSG_STATUS_WARNING, buffer);
  4256.     }
  4257.  
  4258.     time_t now = time(NULL), today = (now - 84600), week = (now - (7 * 84600));
  4259.     std::vector<time_t> dateList;
  4260.  
  4261.     IOLoginData::getInstance()->getUnjustifiedDates(guid, dateList, now);
  4262.     if(countNow)
  4263.         dateList.push_back(now);
  4264.  
  4265.     uint32_t tc = 0, wc = 0, mc = dateList.size();
  4266.     for(std::vector<time_t>::iterator it = dateList.begin(); it != dateList.end(); ++it)
  4267.     {
  4268.         if((*it) > week)
  4269.             wc++;
  4270.  
  4271.         if((*it) > today)
  4272.             tc++;
  4273.     }
  4274.  
  4275.     uint32_t d = g_config.getNumber(ConfigManager::RED_DAILY_LIMIT), w = g_config.getNumber(
  4276.         ConfigManager::RED_WEEKLY_LIMIT), m = g_config.getNumber(ConfigManager::RED_MONTHLY_LIMIT);
  4277.     if(skull < SKULL_RED && ((d > 0 && tc >= d) || (w > 0 && wc >= w) || (m > 0 && mc >= m)))
  4278.         setSkullEnd(now + g_config.getNumber(ConfigManager::RED_SKULL_LENGTH), false, SKULL_RED);
  4279.  
  4280.     if(!g_config.getBool(ConfigManager::USE_BLACK_SKULL))
  4281.     {
  4282.         d += g_config.getNumber(ConfigManager::BAN_DAILY_LIMIT);
  4283.         w += g_config.getNumber(ConfigManager::BAN_WEEKLY_LIMIT);
  4284.         m += g_config.getNumber(ConfigManager::BAN_MONTHLY_LIMIT);
  4285.         if((d <= 0 || tc < d) && (w <= 0 || wc < w) && (m <= 0 || mc < m))
  4286.             return true;
  4287.  
  4288.         if(!IOBan::getInstance()->addAccountBanishment(accountId, (now + g_config.getNumber(
  4289.             ConfigManager::KILLS_BAN_LENGTH)), 20, ACTION_BANISHMENT, "Unjustified player killing.", 0, guid))
  4290.             return true;
  4291.  
  4292.         sendTextMessage(MSG_INFO_DESCR, "You have been banished.");
  4293.         g_game.addMagicEffect(getPosition(), MAGIC_EFFECT_WRAPS_GREEN);
  4294.         Scheduler::getInstance().addEvent(createSchedulerTask(1000, boost::bind(
  4295.             &Game::kickPlayer, &g_game, getID(), false)));
  4296.     }
  4297.     else
  4298.     {
  4299.         d += g_config.getNumber(ConfigManager::BLACK_DAILY_LIMIT);
  4300.         w += g_config.getNumber(ConfigManager::BLACK_WEEKLY_LIMIT);
  4301.         m += g_config.getNumber(ConfigManager::BLACK_MONTHLY_LIMIT);
  4302.         if(skull < SKULL_BLACK && ((d > 0 && tc >= d) || (w > 0 && wc >= w) || (m > 0 && mc >= m)))
  4303.         {
  4304.             setSkullEnd(now + g_config.getNumber(ConfigManager::BLACK_SKULL_LENGTH), false, SKULL_BLACK);
  4305.             setAttackedCreature(NULL);
  4306.             destroySummons();
  4307.         }
  4308.     }
  4309.  
  4310.     return true;
  4311. }
  4312.  
  4313. void Player::setPromotionLevel(uint32_t pLevel)
  4314. {
  4315.     if(pLevel > promotionLevel)
  4316.     {
  4317.         uint32_t tmpLevel = 0, currentVoc = vocationId;
  4318.         for(uint32_t i = promotionLevel; i < pLevel; ++i)
  4319.         {
  4320.             currentVoc = Vocations::getInstance()->getPromotedVocation(currentVoc);
  4321.             if(!currentVoc)
  4322.                 break;
  4323.  
  4324.             tmpLevel++;
  4325.             Vocation* voc = Vocations::getInstance()->getVocation(currentVoc);
  4326.             if(voc->isPremiumNeeded() && !isPremium() && g_config.getBool(ConfigManager::PREMIUM_FOR_PROMOTION))
  4327.                 continue;
  4328.  
  4329.             vocationId = currentVoc;
  4330.         }
  4331.  
  4332.         promotionLevel += tmpLevel;
  4333.     }
  4334.     else if(pLevel < promotionLevel)
  4335.     {
  4336.         uint32_t tmpLevel = 0, currentVoc = vocationId;
  4337.         for(uint32_t i = pLevel; i < promotionLevel; ++i)
  4338.         {
  4339.             Vocation* voc = Vocations::getInstance()->getVocation(currentVoc);
  4340.             if(voc->getFromVocation() == currentVoc)
  4341.                 break;
  4342.  
  4343.             tmpLevel++;
  4344.             currentVoc = voc->getFromVocation();
  4345.             if(voc->isPremiumNeeded() && !isPremium() && g_config.getBool(ConfigManager::PREMIUM_FOR_PROMOTION))
  4346.                 continue;
  4347.  
  4348.             vocationId = currentVoc;
  4349.         }
  4350.  
  4351.         promotionLevel -= tmpLevel;
  4352.     }
  4353.  
  4354.     setVocation(vocationId);
  4355. }
  4356.  
  4357. uint16_t Player::getBlessings() const
  4358. {
  4359.     if(!g_config.getBool(ConfigManager::BLESSINGS) || (!isPremium() &&
  4360.         g_config.getBool(ConfigManager::BLESSING_ONLY_PREMIUM)))
  4361.         return 0;
  4362.  
  4363.     uint16_t count = 0;
  4364.     for(int16_t i = 0; i < 16; ++i)
  4365.     {
  4366.         if(hasBlessing(i))
  4367.             count++;
  4368.     }
  4369.  
  4370.     return count;
  4371. }
  4372.  
  4373. uint64_t Player::getLostExperience() const
  4374. {
  4375.     if(!skillLoss)
  4376.         return 0;
  4377.  
  4378.     double percent = (double)(lossPercent[LOSS_EXPERIENCE] - vocation->getLessLoss() - (getBlessings() * g_config.getNumber(
  4379.         ConfigManager::BLESS_REDUCTION))) / 100.;
  4380.     if(level <= 25)
  4381.         return (uint64_t)std::floor((double)(experience * percent) / 10.);
  4382.  
  4383.     int32_t base = level;
  4384.     double levels = (double)(base + 50) / 100.;
  4385.  
  4386.     uint64_t lost = 0;
  4387.     while(levels > 1.0f)
  4388.     {
  4389.         lost += (getExpForLevel(base) - getExpForLevel(base - 1));
  4390.         base--;
  4391.         levels -= 1.;
  4392.     }
  4393.  
  4394.     if(levels > 0.)
  4395.         lost += (uint64_t)std::floor((double)(getExpForLevel(base) - getExpForLevel(base - 1)) * levels);
  4396.  
  4397.     return (uint64_t)std::floor((double)(lost * percent));
  4398. }
  4399.  
  4400. uint32_t Player::getAttackSpeed() const
  4401. {
  4402.     return ((weapon && weapon->getAttackSpeed() != 0) ? weapon->getAttackSpeed() : (vocation->getAttackSpeed() / std::max((size_t)1, getWeapons().size())));
  4403. }
  4404.  
  4405. void Player::learnInstantSpell(const std::string& name)
  4406. {
  4407.     if(!hasLearnedInstantSpell(name))
  4408.         learnedInstantSpellList.push_back(name);
  4409. }
  4410.  
  4411. void Player::unlearnInstantSpell(const std::string& name)
  4412. {
  4413.     if(!hasLearnedInstantSpell(name))
  4414.         return;
  4415.  
  4416.     LearnedInstantSpellList::iterator it = std::find(learnedInstantSpellList.begin(), learnedInstantSpellList.end(), name);
  4417.     if(it != learnedInstantSpellList.end())
  4418.         learnedInstantSpellList.erase(it);
  4419. }
  4420.  
  4421. bool Player::hasLearnedInstantSpell(const std::string& name) const
  4422. {
  4423.     if(hasFlag(PlayerFlag_CannotUseSpells))
  4424.         return false;
  4425.  
  4426.     if(hasFlag(PlayerFlag_IgnoreSpellCheck))
  4427.         return true;
  4428.  
  4429.     for(LearnedInstantSpellList::const_iterator it = learnedInstantSpellList.begin(); it != learnedInstantSpellList.end(); ++it)
  4430.     {
  4431.         if(!strcasecmp((*it).c_str(), name.c_str()))
  4432.             return true;
  4433.     }
  4434.  
  4435.     return false;
  4436. }
  4437.  
  4438. void Player::manageAccount(const std::string &text)
  4439. {
  4440.     std::stringstream msg;
  4441.     msg << "Account Manager: ";
  4442.  
  4443.     bool noSwap = true;
  4444.     switch(accountManager)
  4445.     {
  4446.         case MANAGER_NAMELOCK:
  4447.         {
  4448.             if(!talkState[1])
  4449.             {
  4450.                 managerString = text;
  4451.                 trimString(managerString);
  4452.                 if(managerString.length() < 4)
  4453.                     msg << "Your name you want is too short, please select a longer name.";
  4454.                 else if(managerString.length() > 20)
  4455.                     msg << "The name you want is too long, please select a shorter name.";
  4456.                 else if(!isValidName(managerString))
  4457.                     msg << "That name seems to contain invalid symbols, please choose another name.";
  4458.                 else if(IOLoginData::getInstance()->playerExists(managerString, true))
  4459.                     msg << "A player with that name already exists, please choose another name.";
  4460.                 else
  4461.                 {
  4462.                     std::string tmp = asLowerCaseString(managerString);
  4463.                     if(tmp.substr(0, 4) != "god " && tmp.substr(0, 3) != "cm " && tmp.substr(0, 3) != "gm ")
  4464.                     {
  4465.                         talkState[1] = true;
  4466.                         talkState[2] = true;
  4467.                         msg << managerString << ", are you sure?";
  4468.                     }
  4469.                     else
  4470.                         msg << "Your character is not a staff member, please tell me another name!";
  4471.                 }
  4472.             }
  4473.             else if(checkText(text, "no") && talkState[2])
  4474.             {
  4475.                 talkState[1] = talkState[2] = false;
  4476.                 msg << "What else would you like to name your character?";
  4477.             }
  4478.             else if(checkText(text, "yes") && talkState[2])
  4479.             {
  4480.                 if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4481.                 {
  4482.                     uint32_t tmp;
  4483.                     if(IOLoginData::getInstance()->getGuidByName(tmp, managerString2) &&
  4484.                         IOLoginData::getInstance()->changeName(tmp, managerString, managerString2) &&
  4485.                         IOBan::getInstance()->removePlayerBanishment(tmp, PLAYERBAN_LOCK))
  4486.                     {
  4487.                         if(House* house = Houses::getInstance()->getHouseByPlayerId(tmp))
  4488.                             house->updateDoorDescription(managerString);
  4489.  
  4490.                         talkState[1] = true;
  4491.                         talkState[2] = false;
  4492.                         msg << "Your character has been successfully renamed, you should now be able to login at it without any problems.";
  4493.                     }
  4494.                     else
  4495.                     {
  4496.                         talkState[1] = talkState[2] = false;
  4497.                         msg << "Failed to change your name, please try again.";
  4498.                     }
  4499.                 }
  4500.                 else
  4501.                 {
  4502.                     talkState[1] = talkState[2] = false;
  4503.                     msg << "A player with that name already exists, please choose another name.";
  4504.                 }
  4505.             }
  4506.             else
  4507.                 msg << "Sorry, but I can't understand you, please try to repeat that!";
  4508.  
  4509.             break;
  4510.         }
  4511.         case MANAGER_ACCOUNT:
  4512.         {
  4513.             Account account = IOLoginData::getInstance()->loadAccount(managerNumber);
  4514.             if(checkText(text, "cancel") || (checkText(text, "account") && !talkState[1]))
  4515.             {
  4516.                 talkState[1] = true;
  4517.                 for(int8_t i = 2; i <= 12; i++)
  4518.                     talkState[i] = false;
  4519.  
  4520.                 msg << "Do you want to change your 'password', request a 'recovery key', add a 'character', or 'delete' a character?";
  4521.             }
  4522.             else if(checkText(text, "delete") && talkState[1])
  4523.             {
  4524.                 talkState[1] = false;
  4525.                 talkState[2] = true;
  4526.                 msg << "Which character would you like to delete?";
  4527.             }
  4528.             else if(talkState[2])
  4529.             {
  4530.                 std::string tmp = text;
  4531.                 trimString(tmp);
  4532.                 if(!isValidName(tmp, false))
  4533.                     msg << "That name contains invalid characters, try to say your name again, you might have typed it wrong.";
  4534.                 else
  4535.                 {
  4536.                     talkState[2] = false;
  4537.                     talkState[3] = true;
  4538.                     managerString = tmp;
  4539.                     msg << "Do you really want to delete the character named " << managerString << "?";
  4540.                 }
  4541.             }
  4542.             else if(checkText(text, "yes") && talkState[3])
  4543.             {
  4544.                 switch(IOLoginData::getInstance()->deleteCharacter(managerNumber, managerString))
  4545.                 {
  4546.                     case DELETE_INTERNAL:
  4547.                         msg << "An error occured while deleting your character. Either the character does not belong to you or it doesn't exist.";
  4548.                         break;
  4549.  
  4550.                     case DELETE_SUCCESS:
  4551.                         msg << "Your character has been deleted.";
  4552.                         break;
  4553.  
  4554.                     case DELETE_HOUSE:
  4555.                         msg << "Your character owns a house. To make sure you really want to lose your house by deleting your character, you have to login and leave the house or pass it to someone else first.";
  4556.                         break;
  4557.  
  4558.                     case DELETE_LEADER:
  4559.                         msg << "Your character is the leader of a guild. You need to disband or pass the leadership someone else to delete your character.";
  4560.                         break;
  4561.  
  4562.                     case DELETE_ONLINE:
  4563.                         msg << "A character with that name is currently online, to delete a character it has to be offline.";
  4564.                         break;
  4565.                 }
  4566.  
  4567.                 talkState[1] = true;
  4568.                 for(int8_t i = 2; i <= 12; i++)
  4569.                     talkState[i] = false;
  4570.             }
  4571.             else if(checkText(text, "no") && talkState[3])
  4572.             {
  4573.                 talkState[1] = true;
  4574.                 talkState[3] = false;
  4575.                 msg << "Tell me what character you want to delete.";
  4576.             }
  4577.             else if(checkText(text, "password") && talkState[1])
  4578.             {
  4579.                 talkState[1] = false;
  4580.                 talkState[4] = true;
  4581.                 msg << "Tell me your new password please.";
  4582.             }
  4583.             else if(talkState[4])
  4584.             {
  4585.                 std::string tmp = text;
  4586.                 trimString(tmp);
  4587.                 if(tmp.length() < 6)
  4588.                     msg << "That password is too short, at least 6 digits are required. Please select a longer password.";
  4589.                 else if(!isValidPassword(tmp))
  4590.                     msg << "Your password contains invalid characters... please tell me another one.";
  4591.                 else
  4592.                 {
  4593.                     talkState[4] = false;
  4594.                     talkState[5] = true;
  4595.                     managerString = tmp;
  4596.                     msg << "Should '" << managerString << "' be your new password?";
  4597.                 }
  4598.             }
  4599.             else if(checkText(text, "yes") && talkState[5])
  4600.             {
  4601.                 talkState[1] = true;
  4602.                 for(int8_t i = 2; i <= 12; i++)
  4603.                     talkState[i] = false;
  4604.  
  4605.                 IOLoginData::getInstance()->setPassword(managerNumber, managerString);
  4606.                 msg << "Your password has been changed.";
  4607.             }
  4608.             else if(checkText(text, "no") && talkState[5])
  4609.             {
  4610.                 talkState[1] = true;
  4611.                 for(int8_t i = 2; i <= 12; i++)
  4612.                     talkState[i] = false;
  4613.  
  4614.                 msg << "Then not.";
  4615.             }
  4616.             else if(checkText(text, "character") && talkState[1])
  4617.             {
  4618.                 if(account.charList.size() <= 15)
  4619.                 {
  4620.                     talkState[1] = false;
  4621.                     talkState[6] = true;
  4622.                     msg << "What would you like as your character name?";
  4623.                 }
  4624.                 else
  4625.                 {
  4626.                     talkState[1] = true;
  4627.                     for(int8_t i = 2; i <= 12; i++)
  4628.                         talkState[i] = false;
  4629.  
  4630.                     msg << "Your account reach the limit of 15 players, you can 'delete' a character if you want to create a new one.";
  4631.                 }
  4632.             }
  4633.             else if(talkState[6])
  4634.             {
  4635.                 managerString = text;
  4636.                 trimString(managerString);
  4637.                 if(managerString.length() < 4)
  4638.                     msg << "Your name you want is too short, please select a longer name.";
  4639.                 else if(managerString.length() > 20)
  4640.                     msg << "The name you want is too long, please select a shorter name.";
  4641.                 else if(!isValidName(managerString))
  4642.                     msg << "That name seems to contain invalid symbols, please choose another name.";
  4643.                 else if(IOLoginData::getInstance()->playerExists(managerString, true))
  4644.                     msg << "A player with that name already exists, please choose another name.";
  4645.                 else
  4646.                 {
  4647.                     std::string tmp = asLowerCaseString(managerString);
  4648.                     if(tmp.substr(0, 4) != "god " && tmp.substr(0, 3) != "cm " && tmp.substr(0, 3) != "gm ")
  4649.                     {
  4650.                         talkState[6] = false;
  4651.                         talkState[7] = true;
  4652.                         msg << managerString << ", are you sure?";
  4653.                     }
  4654.                     else
  4655.                         msg << "Your character is not a staff member, please tell me another name!";
  4656.                 }
  4657.             }
  4658.             else if(checkText(text, "no") && talkState[7])
  4659.             {
  4660.                 talkState[6] = true;
  4661.                 talkState[7] = false;
  4662.                 msg << "What else would you like to name your character?";
  4663.             }
  4664.             else if(checkText(text, "yes") && talkState[7])
  4665.             {
  4666.                 talkState[7] = false;
  4667.                 talkState[8] = true;
  4668.                 msg << "Should your character be a 'male' or a 'female'.";
  4669.             }
  4670.             else if(talkState[8] && (checkText(text, "female") || checkText(text, "male")))
  4671.             {
  4672.                 talkState[8] = false;
  4673.                 talkState[9] = true;
  4674.                 if(checkText(text, "female"))
  4675.                 {
  4676.                     msg << "A female, are you sure?";
  4677.                     managerSex = PLAYERSEX_FEMALE;
  4678.                 }
  4679.                 else
  4680.                 {
  4681.                     msg << "A male, are you sure?";
  4682.                     managerSex = PLAYERSEX_MALE;
  4683.                 }
  4684.             }
  4685.             else if(checkText(text, "no") && talkState[9])
  4686.             {
  4687.                 talkState[8] = true;
  4688.                 talkState[9] = false;
  4689.                 msg << "Tell me... would you like to be a 'male' or a 'female'?";
  4690.             }
  4691.             else if(checkText(text, "yes") && talkState[9])
  4692.             {
  4693.                 if(g_config.getBool(ConfigManager::START_CHOOSEVOC))
  4694.                 {
  4695.                     talkState[9] = false;
  4696.                     talkState[11] = true;
  4697.  
  4698.                     bool firstPart = true;
  4699.                     for(VocationsMap::iterator it = Vocations::getInstance()->getFirstVocation(); it != Vocations::getInstance()->getLastVocation(); ++it)
  4700.                     {
  4701.                         if(it->first == it->second->getFromVocation() && it->first != 0)
  4702.                         {
  4703.                             if(firstPart)
  4704.                             {
  4705.                                 msg << "What do you want to be... " << it->second->getDescription();
  4706.                                 firstPart = false;
  4707.                             }
  4708.                             else if(it->first - 1 != 0)
  4709.                                 msg << ", " << it->second->getDescription();
  4710.                             else
  4711.                                 msg << " or " << it->second->getDescription() << ".";
  4712.                         }
  4713.                     }
  4714.                 }
  4715.                 else if(g_config.getBool(ConfigManager::START_CHOOSETOWN))
  4716.                 {
  4717.                     talkState[9] = false;
  4718.                     talkState[13] = true;
  4719.                    
  4720.                     bool firstPart = true;
  4721.                     for(TownMap::const_iterator it = Towns::getInstance()->getFirstTown(); it != Towns::getInstance()->getLastTown(); ++it)
  4722.                     {
  4723.                         if(it->second->getID() < 100)
  4724.                         {
  4725.                             if(firstPart)
  4726.                             {
  4727.                                 msg << "Where do you want to live... " << it->second->getName();
  4728.                                 firstPart = false;
  4729.                             }
  4730.                             else if(it->first - 1 != 0)
  4731.                                 msg << ", " << it->second->getName();
  4732.                             else
  4733.                                 msg << " or " << it->second->getName() << ".";
  4734.                         }
  4735.                     }
  4736.                 }
  4737.                 else if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4738.                 {
  4739.                     talkState[1] = true;
  4740.                     for(int8_t i = 2; i <= 12; i++)
  4741.                         talkState[i] = false;
  4742.  
  4743.                     if(IOLoginData::getInstance()->createCharacter(managerNumber, managerString, managerNumber2, (uint16_t)managerSex, managerNumber3))
  4744.                         msg << "Your character has been created.";
  4745.                     else
  4746.                         msg << "Your character couldn't be created, please try again.";
  4747.                 }
  4748.                 else
  4749.                 {
  4750.                     talkState[6] = true;
  4751.                     talkState[9] = false;
  4752.                     msg << "A player with that name already exists, please choose another name.";
  4753.                 }
  4754.             }
  4755.             else if(talkState[11])
  4756.             {
  4757.                 for(VocationsMap::iterator it = Vocations::getInstance()->getFirstVocation(); it != Vocations::getInstance()->getLastVocation(); ++it)
  4758.                 {
  4759.                     std::string tmp = asLowerCaseString(it->second->getName());
  4760.                     if(checkText(text, tmp) && it != Vocations::getInstance()->getLastVocation() && it->first == it->second->getFromVocation() && it->first != 0)
  4761.                     {
  4762.                         msg << "So you would like to be " << it->second->getDescription() << "... are you sure?";
  4763.                         managerNumber2 = it->first;
  4764.                         talkState[11] = false;
  4765.                         talkState[12] = true;
  4766.                     }
  4767.                 }
  4768.  
  4769.                 if(msg.str().length() == 17)
  4770.                     msg << "I don't understand what vocation you would like to be... could you please repeat it?";
  4771.             }
  4772.             else if(checkText(text, "yes") && talkState[12])
  4773.             {
  4774.                 if(g_config.getBool(ConfigManager::START_CHOOSETOWN))
  4775.                 {
  4776.                     talkState[12] = false;
  4777.                     talkState[13] = true;
  4778.  
  4779.                     bool firstPart = true;
  4780.                     for(TownMap::const_iterator it = Towns::getInstance()->getFirstTown(); it != Towns::getInstance()->getLastTown(); ++it)
  4781.                     {
  4782.                         if(it->second->getID() < 100)
  4783.                         {
  4784.                             if(firstPart)
  4785.                             {
  4786.                                 msg << "Where do you want to live... " << it->second->getName();
  4787.                                 firstPart = false;
  4788.                             }
  4789.                             else if(it->first - 1 != 0)
  4790.                                 msg << ", " << it->second->getName();
  4791.                             else
  4792.                                 msg << " or " << it->second->getName() << ".";
  4793.                         }
  4794.                     }
  4795.                 }
  4796.                 else if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4797.                 {
  4798.                     talkState[1] = true;
  4799.                     for(int8_t i = 2; i <= 12; i++)
  4800.                         talkState[i] = false;
  4801.  
  4802.                     if(IOLoginData::getInstance()->createCharacter(managerNumber, managerString, managerNumber2, (uint16_t)managerSex, managerNumber3))
  4803.                         msg << "Your character has been created.";
  4804.                     else
  4805.                         msg << "Your character couldn't be created, please try again.";
  4806.                 }
  4807.                 else
  4808.                 {
  4809.                     talkState[6] = true;
  4810.                     talkState[9] = false;
  4811.                     msg << "A player with that name already exists, please choose another name.";
  4812.                 }
  4813.             }
  4814.             else if(checkText(text, "no") && talkState[12])
  4815.             {
  4816.                 talkState[11] = true;
  4817.                 talkState[12] = false;
  4818.                 msg << "No? Then what would you like to be?";
  4819.             }
  4820.             else if(talkState[13])
  4821.             {
  4822.                 for(TownMap::const_iterator it = Towns::getInstance()->getFirstTown(); it != Towns::getInstance()->getLastTown(); it++)
  4823.                 {
  4824.                     std::string tmp = asLowerCaseString(it->second->getName());
  4825.                     if(checkText(text, tmp) && it != Towns::getInstance()->getLastTown() && it->second->getID() < 100)
  4826.                     {
  4827.                         msg << "So do you want to live in " << it->second->getName() << ".. are you sure?";
  4828.                         managerNumber3 = it->first;
  4829.                         talkState[13] = false;
  4830.                         talkState[14] = true;
  4831.                     }
  4832.                 }
  4833.  
  4834.                 if(msg.str().length() == 17)
  4835.                     msg << "I don't understand where you would like to live... could you please repeat it?";
  4836.             }
  4837.             else if(checkText(text, "yes") && talkState[14])
  4838.             {
  4839.                 if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4840.                 {
  4841.                     talkState[1] = true;
  4842.                     for(int8_t i = 2; i <= 14; i++)
  4843.                         talkState[i] = false;
  4844.  
  4845.                     if(IOLoginData::getInstance()->createCharacter(managerNumber, managerString, managerNumber2, (uint16_t)managerSex, managerNumber3))
  4846.                         msg << "Your character has been created.";
  4847.                     else
  4848.                         msg << "Your character couldn't be created, please try again.";
  4849.                 }
  4850.                 else
  4851.                 {
  4852.                     talkState[6] = true;
  4853.                     talkState[9] = false;
  4854.                     msg << "A player with that name already exists, please choose another name.";
  4855.                 }
  4856.             }
  4857.             else if(checkText(text, "no") && talkState[14])
  4858.             {
  4859.                 talkState[13] = true;
  4860.                 talkState[14] = false;
  4861.                 msg << "So where do you want to live?";
  4862.             }
  4863.             else if(checkText(text, "recovery key") && talkState[1])
  4864.             {
  4865.                 talkState[1] = false;
  4866.                 talkState[10] = true;
  4867.                 msg << "Would you like a recovery key?";
  4868.             }
  4869.             else if(checkText(text, "yes") && talkState[10])
  4870.             {
  4871.                 if(account.recoveryKey != "0")
  4872.                     msg << "Sorry, you already have a recovery key, for security reasons I may not give you a new one.";
  4873.                 else
  4874.                 {
  4875.                     managerString = generateRecoveryKey(4, 4);
  4876.                     IOLoginData::getInstance()->setRecoveryKey(managerNumber, managerString);
  4877.                     msg << "Your recovery key is: " << managerString << ".";
  4878.                 }
  4879.  
  4880.                 talkState[1] = true;
  4881.                 for(int8_t i = 2; i <= 12; i++)
  4882.                     talkState[i] = false;
  4883.             }
  4884.             else if(checkText(text, "no") && talkState[10])
  4885.             {
  4886.                 msg << "Then not.";
  4887.                 talkState[1] = true;
  4888.                 for(int8_t i = 2; i <= 12; i++)
  4889.                     talkState[i] = false;
  4890.             }
  4891.             else
  4892.                 msg << "Please read the latest message that I have specified, I don't understand the current requested action.";
  4893.  
  4894.             break;
  4895.         }
  4896.         case MANAGER_NEW:
  4897.         {
  4898.             if(checkText(text, "account") && !talkState[1])
  4899.             {
  4900.                 msg << "What would you like your password to be?";
  4901.                 talkState[1] = true;
  4902.                 talkState[2] = true;
  4903.             }
  4904.             else if(talkState[2])
  4905.             {
  4906.                 std::string tmp = text;
  4907.                 trimString(tmp);
  4908.                 if(tmp.length() < 6)
  4909.                     msg << "That password is too short, at least 6 digits are required. Please select a longer password.";
  4910.                 else if(!isValidPassword(tmp))
  4911.                     msg << "Your password contains invalid characters... please tell me another one.";
  4912.                 else
  4913.                 {
  4914.                     talkState[3] = true;
  4915.                     talkState[2] = false;
  4916.                     managerString = tmp;
  4917.                     msg << managerString << " is it? 'yes' or 'no'?";
  4918.                 }
  4919.             }
  4920.             else if(checkText(text, "yes") && talkState[3])
  4921.             {
  4922.                 if(g_config.getBool(ConfigManager::GENERATE_ACCOUNT_NUMBER))
  4923.                 {
  4924.                     do
  4925.                         sprintf(managerChar, "%d%d%d%d%d%d%d", random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9));
  4926.                     while(IOLoginData::getInstance()->accountNameExists(managerChar));
  4927.  
  4928.                     uint32_t id = (uint32_t)IOLoginData::getInstance()->createAccount(managerChar, managerString);
  4929.                     if(id)
  4930.                     {
  4931.                         accountManager = MANAGER_ACCOUNT;
  4932.                         managerNumber = id;
  4933.  
  4934.                         noSwap = talkState[1] = false;
  4935.                         msg << "Your account has been created, you may manage it now, but remember your account name: '"
  4936.                             << managerChar << "' and password: '" << managerString
  4937.                             << "'! If the account name is too hard to remember, please note it somewhere.";
  4938.                     }
  4939.                     else
  4940.                         msg << "Your account could not be created, please try again.";
  4941.  
  4942.                     for(int8_t i = 2; i <= 5; i++)
  4943.                         talkState[i] = false;
  4944.                 }
  4945.                 else
  4946.                 {
  4947.                     msg << "What would you like your account name to be?";
  4948.                     talkState[3] = false;
  4949.                     talkState[4] = true;
  4950.                 }
  4951.             }
  4952.             else if(checkText(text, "no") && talkState[3])
  4953.             {
  4954.                 talkState[2] = true;
  4955.                 talkState[3] = false;
  4956.                 msg << "What would you like your password to be then?";
  4957.             }
  4958.             else if(talkState[4])
  4959.             {
  4960.                 std::string tmp = text;
  4961.                 trimString(tmp);
  4962.                 if(tmp.length() < 3)
  4963.                     msg << "That account name is too short, at least 3 digits are required. Please select a longer account name.";
  4964.                 else if(tmp.length() > 25)
  4965.                     msg << "That account name is too long, not more than 25 digits are required. Please select a shorter account name.";
  4966.                 else if(!isValidAccountName(tmp))
  4967.                     msg << "Your account name contains invalid characters, please choose another one.";
  4968.                 else if(asLowerCaseString(tmp) == asLowerCaseString(managerString))
  4969.                     msg << "Your account name cannot be same as password, please choose another one.";
  4970.                 else
  4971.                 {
  4972.                     sprintf(managerChar, "%s", tmp.c_str());
  4973.                     msg << managerChar << ", are you sure?";
  4974.                     talkState[4] = false;
  4975.                     talkState[5] = true;
  4976.                 }
  4977.             }
  4978.             else if(checkText(text, "yes") && talkState[5])
  4979.             {
  4980.                 if(!IOLoginData::getInstance()->accountNameExists(managerChar))
  4981.                 {
  4982.                     uint32_t id = (uint32_t)IOLoginData::getInstance()->createAccount(managerChar, managerString);
  4983.                     if(id)
  4984.                     {
  4985.                         accountManager = MANAGER_ACCOUNT;
  4986.                         managerNumber = id;
  4987.  
  4988.                         noSwap = talkState[1] = false;
  4989.                         msg << "Your account has been created, you may manage it now, but remember your account name: '"
  4990.                             << managerChar << "' and password: '" << managerString << "'!";
  4991.                     }
  4992.                     else
  4993.                         msg << "Your account could not be created, please try again.";
  4994.  
  4995.                     for(int8_t i = 2; i <= 5; i++)
  4996.                         talkState[i] = false;
  4997.                 }
  4998.                 else
  4999.                 {
  5000.                     msg << "An account with that name already exists, please try another account name.";
  5001.                     talkState[4] = true;
  5002.                     talkState[5] = false;
  5003.                 }
  5004.             }
  5005.             else if(checkText(text, "no") && talkState[5])
  5006.             {
  5007.                 talkState[5] = false;
  5008.                 talkState[4] = true;
  5009.                 msg << "What else would you like as your account name?";
  5010.             }
  5011.             else if(checkText(text, "recover") && !talkState[6])
  5012.             {
  5013.                 talkState[6] = true;
  5014.                 talkState[7] = true;
  5015.                 msg << "What was your account name?";
  5016.             }
  5017.             else if(talkState[7])
  5018.             {
  5019.                 managerString = text;
  5020.                 if(IOLoginData::getInstance()->getAccountId(managerString, (uint32_t&)managerNumber))
  5021.                 {
  5022.                     talkState[7] = false;
  5023.                     talkState[8] = true;
  5024.                     msg << "What was your recovery key?";
  5025.                 }
  5026.                 else
  5027.                 {
  5028.                     msg << "Sorry, but account with such name doesn't exists.";
  5029.                     talkState[6] = talkState[7] = false;
  5030.                 }
  5031.             }
  5032.             else if(talkState[8])
  5033.             {
  5034.                 managerString2 = text;
  5035.                 if(IOLoginData::getInstance()->validRecoveryKey(managerNumber, managerString2) && managerString2 != "0")
  5036.                 {
  5037.                     sprintf(managerChar, "%s%d", g_config.getString(ConfigManager::SERVER_NAME).c_str(), random_range(100, 999));
  5038.                     IOLoginData::getInstance()->setPassword(managerNumber, managerChar);
  5039.                     msg << "Correct! Your new password is: " << managerChar << ".";
  5040.                 }
  5041.                 else
  5042.                     msg << "Sorry, but this key doesn't match to account you gave me.";
  5043.  
  5044.                 talkState[7] = talkState[8] = false;
  5045.             }
  5046.             else
  5047.                 msg << "Sorry, but I can't understand you, please try to repeat that.";
  5048.  
  5049.             break;
  5050.         }
  5051.         default:
  5052.             return;
  5053.             break;
  5054.     }
  5055.  
  5056.     sendTextMessage(MSG_STATUS_CONSOLE_BLUE, msg.str().c_str());
  5057.     if(!noSwap)
  5058.         sendTextMessage(MSG_STATUS_CONSOLE_ORANGE, "Hint: Type 'account' to manage your account and if you want to start over then type 'cancel'.");
  5059. }
  5060.  
  5061. bool Player::isGuildInvited(uint32_t guildId) const
  5062. {
  5063.     for(InvitedToGuildsList::const_iterator it = invitedToGuildsList.begin(); it != invitedToGuildsList.end(); ++it)
  5064.     {
  5065.         if((*it) == guildId)
  5066.             return true;
  5067.     }
  5068.  
  5069.     return false;
  5070. }
  5071.  
  5072. void Player::leaveGuild()
  5073. {
  5074.     sendClosePrivate(CHANNEL_GUILD);
  5075.     warMap.clear();
  5076.     g_game.updateCreatureEmblem(this);
  5077.  
  5078.     guildLevel = GUILDLEVEL_NONE;
  5079.     guildId = rankId = 0;
  5080.     guildName = rankName = guildNick = std::string();
  5081. }
  5082.  
  5083. bool Player::isPremium() const
  5084. {
  5085.     if(g_config.getBool(ConfigManager::FREE_PREMIUM) || hasFlag(PlayerFlag_IsAlwaysPremium))
  5086.         return true;
  5087.  
  5088.     return premiumDays;
  5089. }
  5090.  
  5091. bool Player::setGuildLevel(GuildLevel_t newLevel, uint32_t rank/* = 0*/)
  5092. {
  5093.     std::string name;
  5094.     if(!IOGuild::getInstance()->getRankEx(rank, name, guildId, newLevel))
  5095.         return false;
  5096.  
  5097.     guildLevel = newLevel;
  5098.     rankName = name;
  5099.     rankId = rank;
  5100.     return true;
  5101. }
  5102.  
  5103. void Player::setGroupId(int32_t newId)
  5104. {
  5105.     if(Group* tmp = Groups::getInstance()->getGroup(newId))
  5106.     {
  5107.         groupId = newId;
  5108.         group = tmp;
  5109.     }
  5110. }
  5111.  
  5112. void Player::setGroup(Group* newGroup)
  5113. {
  5114.     if(!newGroup)
  5115.         return;
  5116.  
  5117.     group = newGroup;
  5118.     groupId = group->getId();
  5119. }
  5120.  
  5121. PartyShields_t Player::getPartyShield(const Creature* creature) const
  5122. {
  5123.     const Player* player = creature->getPlayer();
  5124.     if(!player)
  5125.         return Creature::getPartyShield(creature);
  5126.  
  5127.     if(Party* party = getParty())
  5128.     {
  5129.         if(party->getLeader() == player)
  5130.         {
  5131.             if(!party->isSharedExperienceActive())
  5132.                 return SHIELD_YELLOW;
  5133.  
  5134.             if(party->isSharedExperienceEnabled())
  5135.                 return SHIELD_YELLOW_SHAREDEXP;
  5136.  
  5137.             if(party->canUseSharedExperience(player))
  5138.                 return SHIELD_YELLOW_NOSHAREDEXP;
  5139.  
  5140.             return SHIELD_YELLOW_NOSHAREDEXP_BLINK;
  5141.         }
  5142.  
  5143.         if(party->isPlayerMember(player))
  5144.         {
  5145.             if(!party->isSharedExperienceActive())
  5146.                 return SHIELD_BLUE;
  5147.  
  5148.             if(party->isSharedExperienceEnabled())
  5149.                 return SHIELD_BLUE_SHAREDEXP;
  5150.  
  5151.             if(party->canUseSharedExperience(player))
  5152.                 return SHIELD_BLUE_NOSHAREDEXP;
  5153.  
  5154.             return SHIELD_BLUE_NOSHAREDEXP_BLINK;
  5155.         }
  5156.  
  5157.         if(isInviting(player))
  5158.             return SHIELD_WHITEBLUE;
  5159.     }
  5160.  
  5161.     if(player->isInviting(this))
  5162.         return SHIELD_WHITEYELLOW;
  5163.  
  5164.     return SHIELD_NONE;
  5165. }
  5166.  
  5167. bool Player::isInviting(const Player* player) const
  5168. {
  5169.     if(!player || player->isRemoved() || !party || party->getLeader() != this)
  5170.         return false;
  5171.  
  5172.     return party->isPlayerInvited(player);
  5173. }
  5174.  
  5175. bool Player::isPartner(const Player* player) const
  5176. {
  5177.     return player && player->getParty() && player->getParty() == party;
  5178. }
  5179.  
  5180. bool Player::getHideHealth() const
  5181. {
  5182.     if(hasFlag(PlayerFlag_HideHealth))
  5183.         return true;
  5184.  
  5185.     return hideHealth;
  5186. }
  5187.  
  5188. void Player::sendPlayerIcons(Player* player)
  5189. {
  5190.     sendCreatureShield(player);
  5191.     sendCreatureSkull(player);
  5192. }
  5193.  
  5194. bool Player::addPartyInvitation(Party* party)
  5195. {
  5196.     if(!party)
  5197.         return false;
  5198.  
  5199.     PartyList::iterator it = std::find(invitePartyList.begin(), invitePartyList.end(), party);
  5200.     if(it != invitePartyList.end())
  5201.         return false;
  5202.  
  5203.     invitePartyList.push_back(party);
  5204.     return true;
  5205. }
  5206.  
  5207. bool Player::removePartyInvitation(Party* party)
  5208. {
  5209.     if(!party)
  5210.         return false;
  5211.  
  5212.     PartyList::iterator it = std::find(invitePartyList.begin(), invitePartyList.end(), party);
  5213.     if(it != invitePartyList.end())
  5214.     {
  5215.         invitePartyList.erase(it);
  5216.         return true;
  5217.     }
  5218.     return false;
  5219. }
  5220.  
  5221. void Player::clearPartyInvitations()
  5222. {
  5223.     if(invitePartyList.empty())
  5224.         return;
  5225.  
  5226.     PartyList list;
  5227.     for(PartyList::iterator it = invitePartyList.begin(); it != invitePartyList.end(); ++it)
  5228.         list.push_back(*it);
  5229.  
  5230.     invitePartyList.clear();
  5231.     for(PartyList::iterator it = list.begin(); it != list.end(); ++it)
  5232.         (*it)->removeInvite(this);
  5233. }
  5234.  
  5235. void Player::increaseCombatValues(int32_t& min, int32_t& max, bool useCharges, bool countWeapon)
  5236. {
  5237.     if(min > 0)
  5238.         min = (int32_t)(min * vocation->getMultiplier(MULTIPLIER_HEALING));
  5239.     else
  5240.         min = (int32_t)(min * vocation->getMultiplier(MULTIPLIER_MAGIC));
  5241.  
  5242.     if(max > 0)
  5243.         max = (int32_t)(max * vocation->getMultiplier(MULTIPLIER_HEALING));
  5244.     else
  5245.         max = (int32_t)(max * vocation->getMultiplier(MULTIPLIER_MAGIC));
  5246.  
  5247.     Item* item = NULL;
  5248.     int32_t minValue = 0, maxValue = 0, i = SLOT_FIRST;
  5249.     for(; i < SLOT_LAST; ++i)
  5250.     {
  5251.         if(!(item = getInventoryItem((slots_t)i)) || item->isRemoved() ||
  5252.             (g_moveEvents->hasEquipEvent(item) && !isItemAbilityEnabled((slots_t)i)))
  5253.             continue;
  5254.  
  5255.         const ItemType& it = Item::items[item->getID()];
  5256.         if(min > 0)
  5257.         {
  5258.             minValue += it.abilities.increment[HEALING_VALUE];
  5259.             if(it.abilities.increment[HEALING_PERCENT])
  5260.                 min = (int32_t)std::ceil((double)(min * it.abilities.increment[HEALING_PERCENT]) / 100.);
  5261.         }
  5262.         else
  5263.         {
  5264.             minValue -= it.abilities.increment[MAGIC_VALUE];
  5265.             if(it.abilities.increment[MAGIC_PERCENT])
  5266.                 min = (int32_t)std::ceil((double)(min * it.abilities.increment[MAGIC_PERCENT]) / 100.);
  5267.         }
  5268.  
  5269.         if(max > 0)
  5270.         {
  5271.             maxValue += it.abilities.increment[HEALING_VALUE];
  5272.             if(it.abilities.increment[HEALING_PERCENT])
  5273.                 max = (int32_t)std::ceil((double)(max * it.abilities.increment[HEALING_PERCENT]) / 100.);
  5274.         }
  5275.         else
  5276.         {
  5277.             maxValue -= it.abilities.increment[MAGIC_VALUE];
  5278.             if(it.abilities.increment[MAGIC_PERCENT])
  5279.                 max = (int32_t)std::ceil((double)(max * it.abilities.increment[MAGIC_PERCENT]) / 100.);
  5280.         }
  5281.  
  5282.         bool removeCharges = false;
  5283.         for(int32_t j = INCREMENT_FIRST; j <= INCREMENT_LAST; ++j)
  5284.         {
  5285.             if(!it.abilities.increment[(Increment_t)j])
  5286.                 continue;
  5287.  
  5288.             removeCharges = true;
  5289.             break;
  5290.         }
  5291.  
  5292.         if(useCharges && removeCharges && (countWeapon || item != weapon) && item->hasCharges())
  5293.             g_game.transformItem(item, item->getID(), std::max((int32_t)0, (int32_t)item->getCharges() - 1));
  5294.     }
  5295.  
  5296.     min += minValue;
  5297.     max += maxValue;
  5298. }
  5299.  
  5300. bool Player::transferMoneyTo(const std::string& name, uint64_t amount)
  5301. {
  5302.     if(!g_config.getBool(ConfigManager::BANK_SYSTEM) || amount > balance)
  5303.         return false;
  5304.  
  5305.     Player* target = g_game.getPlayerByNameEx(name);
  5306.     if(!target)
  5307.         return false;
  5308.  
  5309.     balance -= amount;
  5310.     target->balance += amount;
  5311.     if(target->isVirtual())
  5312.     {
  5313.         IOLoginData::getInstance()->savePlayer(target);
  5314.         delete target;
  5315.     }
  5316.  
  5317.     return true;
  5318. }
  5319.  
  5320. void Player::sendCritical() const
  5321. {
  5322.     if(g_config.getBool(ConfigManager::DISPLAY_CRITICAL_HIT))
  5323.         g_game.addAnimatedText(getPosition(), COLOR_DARKRED, "CRITICAL!");
  5324. }
  5325.  
  5326. bool Player::addOfflineTrainingTries(skills_t skill, int32_t tries)
  5327. {
  5328.     if(tries <= 0 || skill == SKILL__LEVEL || skill == SKILL__EXPERIENCE)
  5329.         return false;
  5330.  
  5331.     uint32_t oldSkillValue, newSkillValue;
  5332.     long double oldPercentToNextLevel, newPercentToNextLevel;
  5333.  
  5334.     std::ostringstream ss;
  5335.     if(skill == SKILL__MAGLEVEL)
  5336.     {
  5337.         uint64_t currReqMana = vocation->getReqMana(magLevel), nextReqMana = vocation->getReqMana(magLevel + 1);
  5338.         if(currReqMana >= nextReqMana)
  5339.             return false;
  5340.  
  5341.         oldSkillValue = magLevel;
  5342.         oldPercentToNextLevel = (long double)(manaSpent * 100) / nextReqMana;
  5343.  
  5344.         tries *= g_config.getDouble(ConfigManager::RATE_MAGIC_OFFLINE);
  5345.         while((manaSpent + tries) >= nextReqMana)
  5346.         {
  5347.             tries -= nextReqMana - manaSpent;
  5348.             manaSpent = 0;
  5349.             magLevel++;
  5350.  
  5351.             CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  5352.             for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  5353.                 (*it)->executeAdvance(this, SKILL__MAGLEVEL, (magLevel - 1), magLevel);
  5354.  
  5355.             currReqMana = nextReqMana;
  5356.             nextReqMana = vocation->getReqMana(magLevel + 1);
  5357.             if(currReqMana >= nextReqMana)
  5358.             {
  5359.                 tries = 0;
  5360.                 break;
  5361.             }
  5362.         }
  5363.  
  5364.         if(tries)
  5365.             manaSpent += tries;
  5366.  
  5367.         uint32_t newPercent;
  5368.         if(nextReqMana > currReqMana)
  5369.         {
  5370.             newPercent = Player::getPercentLevel(manaSpent, nextReqMana);
  5371.             newPercentToNextLevel = (long double)(manaSpent * 100) / nextReqMana;
  5372.         }
  5373.         else
  5374.             newPercent = newPercentToNextLevel = 0;
  5375.  
  5376.         if(newPercent != magLevelPercent)
  5377.         {
  5378.             magLevelPercent = newPercent;
  5379.             sendStats();
  5380.         }
  5381.  
  5382.         newSkillValue = magLevel;
  5383.         ss << "You advanced to magic level " << magLevel << ".";
  5384.         sendTextMessage(MSG_EVENT_ADVANCE, ss.str().c_str());
  5385.         ss.str("");
  5386.     }
  5387.     else
  5388.     {
  5389.         uint64_t currReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL]),
  5390.             nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  5391.         if(currReqTries >= nextReqTries)
  5392.             return false;
  5393.  
  5394.         oldSkillValue = skills[skill][SKILL_LEVEL];
  5395.         oldPercentToNextLevel = (long double)(skills[skill][SKILL_TRIES] * 100) / nextReqTries;
  5396.  
  5397.         tries *= g_config.getDouble(ConfigManager::RATE_SKILL_OFFLINE);
  5398.         while((skills[skill][SKILL_TRIES] + tries) >= nextReqTries)
  5399.         {
  5400.             tries -= nextReqTries - skills[skill][SKILL_TRIES];
  5401.             skills[skill][SKILL_LEVEL]++;
  5402.             skills[skill][SKILL_TRIES] = skills[skill][SKILL_PERCENT] = 0;         
  5403.  
  5404.             CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  5405.             for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  5406.                 (*it)->executeAdvance(this, skill, (skills[skill][SKILL_LEVEL] - 1), skills[skill][SKILL_LEVEL]);
  5407.  
  5408.             currReqTries = nextReqTries;
  5409.             nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  5410.             if(currReqTries >= nextReqTries)
  5411.             {
  5412.                 tries = 0;
  5413.                 break;
  5414.             }
  5415.         }
  5416.  
  5417.         if(tries)
  5418.             skills[skill][SKILL_TRIES] += tries;
  5419.  
  5420.         uint32_t newPercent;
  5421.         if(nextReqTries > currReqTries)
  5422.         {
  5423.             newPercent = Player::getPercentLevel(skills[skill][SKILL_TRIES], nextReqTries);
  5424.             newPercentToNextLevel = (long double)(skills[skill][SKILL_TRIES] * 100) / nextReqTries;
  5425.         }
  5426.         else
  5427.             newPercent = newPercentToNextLevel = 0;
  5428.  
  5429.         if(skills[skill][SKILL_PERCENT] != newPercent)
  5430.         {
  5431.             skills[skill][SKILL_PERCENT] = newPercent;
  5432.             sendStats();
  5433.         }
  5434.  
  5435.         newSkillValue = skills[skill][SKILL_LEVEL];
  5436.         ss << "You advanced to " << getSkillName(skill) << " level " << skills[skill][SKILL_LEVEL] << ".";
  5437.         sendTextMessage(MSG_EVENT_ADVANCE, ss.str().c_str());
  5438.         ss.str("");
  5439.     }
  5440.  
  5441.     ss << std::fixed << std::setprecision(2) << "Your " << ucwords(getSkillName(skill)) << " skill changed from level " << oldSkillValue << " (with " << oldPercentToNextLevel << "% progress towards level " << (oldSkillValue + 1) << ") to level " << newSkillValue << " (with " << newPercentToNextLevel << "% progress towards level " << (newSkillValue + 1) << ")";
  5442.     sendTextMessage(MSG_EVENT_ADVANCE, ss.str().c_str());
  5443.     return true;
  5444. }
  5445.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement