Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Common operation need to add item from inventory without delete in trade, guild bank, mail....
- void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
- {
- // update quest counters
- ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
- // store item
- Item* pLastItem = StoreItem(dest, pItem, update);
- // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
- if (pLastItem == pItem)
- {
- // update owner for last item (this can be original item with wrong owner
- if (pLastItem->GetOwnerGUID() != GetGUID())
- pLastItem->SetOwnerGUID(GetGUID());
- // if this original item then it need create record in inventory
- // in case trade we already have item in other player inventory
- pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
- }
- if (pLastItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE))
- AddTradeableItem(pLastItem);
- }
- void Player::DestroyItem(uint8 bag, uint8 slot, bool update)
- {
- Item* pItem = GetItemByPos(bag, slot);
- if (pItem)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
- // Also remove all contained items if the item is a bag.
- // This if () prevents item saving crashes if the condition for a bag to be empty before being destroyed was bypassed somehow.
- if (pItem->IsNotEmptyBag())
- for (uint8 i = 0; i < MAX_BAG_SIZE; ++i)
- DestroyItem(slot, i, update);
- if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED))
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT);
- stmt->setUInt32(0, pItem->GetGUIDLow());
- CharacterDatabase.Execute(stmt);
- }
- RemoveEnchantmentDurations(pItem);
- RemoveItemDurations(pItem);
- pItem->SetNotRefundable(this);
- pItem->ClearSoulboundTradeable(this);
- RemoveTradeableItem(pItem);
- const ItemTemplate* proto = pItem->GetTemplate();
- for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
- if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
- RemoveAurasDueToSpell(proto->Spells[i].SpellId);
- ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount());
- if (bag == INVENTORY_SLOT_BAG_0)
- {
- SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
- // equipment and equipped bags can have applied bonuses
- if (slot < INVENTORY_SLOT_BAG_END)
- {
- ItemTemplate const* pProto = pItem->GetTemplate();
- // item set bonuses applied only at equip and removed at unequip, and still active for broken items
- if (pProto && pProto->ItemSet)
- RemoveItemsSetItem(this, pProto);
- _ApplyItemMods(pItem, slot, false);
- }
- if (slot < EQUIPMENT_SLOT_END)
- {
- // remove item dependent auras and casts (only weapon and armor slots)
- RemoveItemDependentAurasAndCasts(pItem);
- // update expertise and armor penetration - passive auras may need it
- switch (slot)
- {
- case EQUIPMENT_SLOT_MAINHAND:
- case EQUIPMENT_SLOT_OFFHAND:
- case EQUIPMENT_SLOT_RANGED:
- RecalculateRating(CR_ARMOR_PENETRATION);
- default:
- break;
- }
- if (slot == EQUIPMENT_SLOT_MAINHAND)
- UpdateExpertise(BASE_ATTACK);
- else if (slot == EQUIPMENT_SLOT_OFFHAND)
- UpdateExpertise(OFF_ATTACK);
- // equipment visual show
- SetVisibleItemSlot(slot, NULL);
- }
- m_items[slot] = NULL;
- }
- else if (Bag* pBag = GetBagByPos(bag))
- pBag->RemoveItem(slot, update);
- if (IsInWorld() && update)
- {
- pItem->RemoveFromWorld();
- pItem->DestroyForPlayer(this);
- }
- //pItem->SetOwnerGUID(0);
- pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
- pItem->SetSlot(NULL_SLOT);
- pItem->SetState(ITEM_REMOVED, this);
- }
- }
- void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
- uint32 remcount = 0;
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- {
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- {
- if (pItem->GetEntry() == item && !pItem->IsInTrade())
- {
- if (pItem->GetCount() + remcount <= count)
- {
- // all items in inventory can unequipped
- remcount += pItem->GetCount();
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- if (remcount >= count)
- return;
- }
- else
- {
- ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
- pItem->SetCount(pItem->GetCount() - count + remcount);
- if (IsInWorld() && update)
- pItem->SendUpdateToPlayer(this);
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- {
- if (pItem->GetEntry() == item && !pItem->IsInTrade())
- {
- if (pItem->GetCount() + remcount <= count)
- {
- // all keys can be unequipped
- remcount += pItem->GetCount();
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- if (remcount >= count)
- return;
- }
- else
- {
- ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
- pItem->SetCount(pItem->GetCount() - count + remcount);
- if (IsInWorld() && update)
- pItem->SendUpdateToPlayer(this);
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- if (Bag* pBag = GetBagByPos(i))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- if (Item* pItem = pBag->GetItemByPos(j))
- {
- if (pItem->GetEntry() == item && !pItem->IsInTrade())
- {
- // all items in bags can be unequipped
- if (pItem->GetCount() + remcount <= count)
- {
- remcount += pItem->GetCount();
- DestroyItem(i, j, update);
- if (remcount >= count)
- return;
- }
- else
- {
- ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
- pItem->SetCount(pItem->GetCount() - count + remcount);
- if (IsInWorld() && update)
- pItem->SendUpdateToPlayer(this);
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
- }
- }
- // in equipment and bag list
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- {
- if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
- {
- if (pItem->GetCount() + remcount <= count)
- {
- if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK)
- {
- remcount += pItem->GetCount();
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- if (remcount >= count)
- return;
- }
- }
- else
- {
- ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
- pItem->SetCount(pItem->GetCount() - count + remcount);
- if (IsInWorld() && update)
- pItem->SendUpdateToPlayer(this);
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
- }
- void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone);
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Bag* pBag = GetBagByPos(i))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem(i, j, update);
- // in equipment and bag list
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- }
- void Player::DestroyConjuredItems(bool update)
- {
- // used when entering arena
- // destroys all conjured items
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyConjuredItems");
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->IsConjuredConsumable())
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Bag* pBag = GetBagByPos(i))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->IsConjuredConsumable())
- DestroyItem(i, j, update);
- // in equipment and bag list
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->IsConjuredConsumable())
- DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
- }
- Item* Player::GetItemByEntry(uint32 entry) const
- {
- // in inventory
- for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEntry() == entry)
- return pItem;
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEntry() == entry)
- return pItem;
- for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Bag* pBag = GetBagByPos(i))
- for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->GetEntry() == entry)
- return pItem;
- for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEntry() == entry)
- return pItem;
- return NULL;
- }
- void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update)
- {
- if (!pItem)
- return;
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(), pItem->GetEntry(), count);
- if (pItem->GetCount() <= count)
- {
- count -= pItem->GetCount();
- DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), update);
- }
- else
- {
- ItemRemovedQuestCheck(pItem->GetEntry(), count);
- pItem->SetCount(pItem->GetCount() - count);
- count = 0;
- if (IsInWorld() && update)
- pItem->SendUpdateToPlayer(this);
- pItem->SetState(ITEM_CHANGED, this);
- }
- }
- void Player::SplitItem(uint16 src, uint16 dst, uint32 count)
- {
- uint8 srcbag = src >> 8;
- uint8 srcslot = src & 255;
- uint8 dstbag = dst >> 8;
- uint8 dstslot = dst & 255;
- Item* pSrcItem = GetItemByPos(srcbag, srcslot);
- if (!pSrcItem)
- {
- SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL);
- return;
- }
- if (pSrcItem->m_lootGenerated) // prevent split looting item (item
- {
- //best error message found for attempting to split while looting
- SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL);
- return;
- }
- // not let split all items (can be only at cheating)
- if (pSrcItem->GetCount() == count)
- {
- SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL);
- return;
- }
- // not let split more existed items (can be only at cheating)
- if (pSrcItem->GetCount() < count)
- {
- SendEquipError(EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL);
- return;
- }
- //! If trading
- if (TradeData* tradeData = GetTradeData())
- {
- //! If current item is in trade window (only possible with packet spoofing - silent return)
- if (tradeData->GetTradeSlotForItem(pSrcItem->GetGUID()) != TRADE_SLOT_INVALID)
- return;
- }
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
- Item* pNewItem = pSrcItem->CloneItem(count, this);
- if (!pNewItem)
- {
- SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL);
- return;
- }
- if (IsInventoryPos(dst))
- {
- // change item amount before check (for unique max count check)
- pSrcItem->SetCount(pSrcItem->GetCount() - count);
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pNewItem, false);
- if (msg != EQUIP_ERR_OK)
- {
- delete pNewItem;
- pSrcItem->SetCount(pSrcItem->GetCount() + count);
- SendEquipError(msg, pSrcItem, NULL);
- return;
- }
- if (IsInWorld())
- pSrcItem->SendUpdateToPlayer(this);
- pSrcItem->SetState(ITEM_CHANGED, this);
- StoreItem(dest, pNewItem, true);
- }
- else if (IsBankPos(dst))
- {
- // change item amount before check (for unique max count check)
- pSrcItem->SetCount(pSrcItem->GetCount() - count);
- ItemPosCountVec dest;
- InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pNewItem, false);
- if (msg != EQUIP_ERR_OK)
- {
- delete pNewItem;
- pSrcItem->SetCount(pSrcItem->GetCount() + count);
- SendEquipError(msg, pSrcItem, NULL);
- return;
- }
- if (IsInWorld())
- pSrcItem->SendUpdateToPlayer(this);
- pSrcItem->SetState(ITEM_CHANGED, this);
- BankItem(dest, pNewItem, true);
- }
- else if (IsEquipmentPos(dst))
- {
- // change item amount before check (for unique max count check), provide space for splitted items
- pSrcItem->SetCount(pSrcItem->GetCount() - count);
- uint16 dest;
- InventoryResult msg = CanEquipItem(dstslot, dest, pNewItem, false);
- if (msg != EQUIP_ERR_OK)
- {
- delete pNewItem;
- pSrcItem->SetCount(pSrcItem->GetCount() + count);
- SendEquipError(msg, pSrcItem, NULL);
- return;
- }
- if (IsInWorld())
- pSrcItem->SendUpdateToPlayer(this);
- pSrcItem->SetState(ITEM_CHANGED, this);
- EquipItem(dest, pNewItem, true);
- AutoUnequipOffhandIfNeed();
- }
- }
- void Player::SwapItem(uint16 src, uint16 dst)
- {
- uint8 srcbag = src >> 8;
- uint8 srcslot = src & 255;
- uint8 dstbag = dst >> 8;
- uint8 dstslot = dst & 255;
- Item* pSrcItem = GetItemByPos(srcbag, srcslot);
- Item* pDstItem = GetItemByPos(dstbag, dstslot);
- if (!pSrcItem)
- return;
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
- if (!isAlive())
- {
- SendEquipError(EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem);
- return;
- }
- // SRC checks
- if (pSrcItem->m_lootGenerated) // prevent swap looting item
- {
- //best error message found for attempting to swap while looting
- SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL);
- return;
- }
- // check unequip potability for equipped items and bank bags
- if (IsEquipmentPos(src) || IsBagPos(src))
- {
- // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
- InventoryResult msg = CanUnequipItem(src, !IsBagPos(src) || IsBagPos(dst) || (pDstItem && pDstItem->ToBag() && pDstItem->ToBag()->IsEmpty()));
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pSrcItem, pDstItem);
- return;
- }
- }
- // prevent put equipped/bank bag in self
- if (IsBagPos(src) && srcslot == dstbag)
- {
- SendEquipError(EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem);
- return;
- }
- // prevent equipping bag in the same slot from its inside
- if (IsBagPos(dst) && srcbag == dstslot)
- {
- SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem);
- return;
- }
- // DST checks
- if (pDstItem)
- {
- if (pDstItem->m_lootGenerated) // prevent swap looting item
- {
- //best error message found for attempting to swap while looting
- SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL);
- return;
- }
- // check unequip potability for equipped items and bank bags
- if (IsEquipmentPos(dst) || IsBagPos(dst))
- {
- // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
- InventoryResult msg = CanUnequipItem(dst, !IsBagPos(dst) || IsBagPos(src) || (pSrcItem->ToBag() && pSrcItem->ToBag()->IsEmpty()));
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pSrcItem, pDstItem);
- return;
- }
- }
- }
- // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
- // or swap empty bag with another empty or not empty bag (with items exchange)
- // Move case
- if (!pDstItem)
- {
- if (IsInventoryPos(dst))
- {
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pSrcItem, false);
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pSrcItem, NULL);
- return;
- }
- RemoveItem(srcbag, srcslot, true);
- StoreItem(dest, pSrcItem, true);
- if (IsBankPos(src))
- ItemAddedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
- }
- else if (IsBankPos(dst))
- {
- ItemPosCountVec dest;
- InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pSrcItem, false);
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pSrcItem, NULL);
- return;
- }
- RemoveItem(srcbag, srcslot, true);
- BankItem(dest, pSrcItem, true);
- ItemRemovedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
- }
- else if (IsEquipmentPos(dst))
- {
- uint16 dest;
- InventoryResult msg = CanEquipItem(dstslot, dest, pSrcItem, false);
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pSrcItem, NULL);
- return;
- }
- RemoveItem(srcbag, srcslot, true);
- EquipItem(dest, pSrcItem, true);
- AutoUnequipOffhandIfNeed();
- }
- return;
- }
- // attempt merge to / fill target item
- if (!pSrcItem->IsBag() && !pDstItem->IsBag())
- {
- InventoryResult msg;
- ItemPosCountVec sDest;
- uint16 eDest = 0;
- if (IsInventoryPos(dst))
- msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, false);
- else if (IsBankPos(dst))
- msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, false);
- else if (IsEquipmentPos(dst))
- msg = CanEquipItem(dstslot, eDest, pSrcItem, false);
- else
- return;
- // can be merge/fill
- if (msg == EQUIP_ERR_OK)
- {
- if (pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetTemplate()->GetMaxStackSize())
- {
- RemoveItem(srcbag, srcslot, true);
- if (IsInventoryPos(dst))
- StoreItem(sDest, pSrcItem, true);
- else if (IsBankPos(dst))
- BankItem(sDest, pSrcItem, true);
- else if (IsEquipmentPos(dst))
- {
- EquipItem(eDest, pSrcItem, true);
- AutoUnequipOffhandIfNeed();
- }
- }
- else
- {
- pSrcItem->SetCount(pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetTemplate()->GetMaxStackSize());
- pDstItem->SetCount(pSrcItem->GetTemplate()->GetMaxStackSize());
- pSrcItem->SetState(ITEM_CHANGED, this);
- pDstItem->SetState(ITEM_CHANGED, this);
- if (IsInWorld())
- {
- pSrcItem->SendUpdateToPlayer(this);
- pDstItem->SendUpdateToPlayer(this);
- }
- }
- SendRefundInfo(pDstItem);
- return;
- }
- }
- // impossible merge/fill, do real swap
- InventoryResult msg = EQUIP_ERR_OK;
- // check src->dest move possibility
- ItemPosCountVec sDest;
- uint16 eDest = 0;
- if (IsInventoryPos(dst))
- msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, true);
- else if (IsBankPos(dst))
- msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, true);
- else if (IsEquipmentPos(dst))
- {
- msg = CanEquipItem(dstslot, eDest, pSrcItem, true);
- if (msg == EQUIP_ERR_OK)
- msg = CanUnequipItem(eDest, true);
- }
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pSrcItem, pDstItem);
- return;
- }
- // check dest->src move possibility
- ItemPosCountVec sDest2;
- uint16 eDest2 = 0;
- if (IsInventoryPos(src))
- msg = CanStoreItem(srcbag, srcslot, sDest2, pDstItem, true);
- else if (IsBankPos(src))
- msg = CanBankItem(srcbag, srcslot, sDest2, pDstItem, true);
- else if (IsEquipmentPos(src))
- {
- msg = CanEquipItem(srcslot, eDest2, pDstItem, true);
- if (msg == EQUIP_ERR_OK)
- msg = CanUnequipItem(eDest2, true);
- }
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, pDstItem, pSrcItem);
- return;
- }
- // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
- if (Bag* srcBag = pSrcItem->ToBag())
- {
- if (Bag* dstBag = pDstItem->ToBag())
- {
- Bag* emptyBag = NULL;
- Bag* fullBag = NULL;
- if (srcBag->IsEmpty() && !IsBagPos(src))
- {
- emptyBag = srcBag;
- fullBag = dstBag;
- }
- else if (dstBag->IsEmpty() && !IsBagPos(dst))
- {
- emptyBag = dstBag;
- fullBag = srcBag;
- }
- // bag swap (with items exchange) case
- if (emptyBag && fullBag)
- {
- ItemTemplate const* emptyProto = emptyBag->GetTemplate();
- uint32 count = 0;
- for (uint32 i=0; i < fullBag->GetBagSize(); ++i)
- {
- Item* bagItem = fullBag->GetItemByPos(i);
- if (!bagItem)
- continue;
- ItemTemplate const* bagItemProto = bagItem->GetTemplate();
- if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emptyProto))
- {
- // one from items not go to empty target bag
- SendEquipError(EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem);
- return;
- }
- ++count;
- }
- if (count > emptyBag->GetBagSize())
- {
- // too small targeted bag
- SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem);
- return;
- }
- // Items swap
- count = 0; // will pos in new bag
- for (uint32 i = 0; i< fullBag->GetBagSize(); ++i)
- {
- Item* bagItem = fullBag->GetItemByPos(i);
- if (!bagItem)
- continue;
- fullBag->RemoveItem(i, true);
- emptyBag->StoreItem(count, bagItem, true);
- bagItem->SetState(ITEM_CHANGED, this);
- ++count;
- }
- }
- }
- }
- // now do moves, remove...
- RemoveItem(dstbag, dstslot, false);
- RemoveItem(srcbag, srcslot, false);
- // add to dest
- if (IsInventoryPos(dst))
- StoreItem(sDest, pSrcItem, true);
- else if (IsBankPos(dst))
- BankItem(sDest, pSrcItem, true);
- else if (IsEquipmentPos(dst))
- EquipItem(eDest, pSrcItem, true);
- // add to src
- if (IsInventoryPos(src))
- StoreItem(sDest2, pDstItem, true);
- else if (IsBankPos(src))
- BankItem(sDest2, pDstItem, true);
- else if (IsEquipmentPos(src))
- EquipItem(eDest2, pDstItem, true);
- // if player is moving bags and is looting an item inside this bag
- // release the loot
- if (GetLootGUID())
- {
- bool released = false;
- if (IsBagPos(src))
- {
- Bag* bag = pSrcItem->ToBag();
- for (uint32 i = 0; i < bag->GetBagSize(); ++i)
- {
- if (Item* bagItem = bag->GetItemByPos(i))
- {
- if (bagItem->m_lootGenerated)
- {
- m_session->DoLootRelease(GetLootGUID());
- released = true; // so we don't need to look at dstBag
- break;
- }
- }
- }
- }
- if (!released && IsBagPos(dst) && pDstItem)
- {
- Bag* bag = pDstItem->ToBag();
- for (uint32 i = 0; i < bag->GetBagSize(); ++i)
- {
- if (Item* bagItem = bag->GetItemByPos(i))
- {
- if (bagItem->m_lootGenerated)
- {
- m_session->DoLootRelease(GetLootGUID());
- released = true; // not realy needed here
- break;
- }
- }
- }
- }
- }
- AutoUnequipOffhandIfNeed();
- }
- void Player::AddItemToBuyBackSlot(Item* pItem)
- {
- if (pItem)
- {
- uint32 slot = m_currentBuybackSlot;
- // if current back slot non-empty search oldest or free
- if (m_items[slot])
- {
- uint32 oldest_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1);
- uint32 oldest_slot = BUYBACK_SLOT_START;
- for (uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i)
- {
- // found empty
- if (!m_items[i])
- {
- slot = i;
- break;
- }
- uint32 i_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
- if (oldest_time > i_time)
- {
- oldest_time = i_time;
- oldest_slot = i;
- }
- }
- // find oldest
- slot = oldest_slot;
- }
- RemoveItemFromBuyBackSlot(slot, true);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
- m_items[slot] = pItem;
- time_t base = time(NULL);
- uint32 etime = uint32(base - m_logintime + (30 * 3600));
- uint32 eslot = slot - BUYBACK_SLOT_START;
- SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID());
- if (ItemTemplate const* proto = pItem->GetTemplate())
- SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, proto->SellPrice * pItem->GetCount());
- else
- SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
- SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime);
- // move to next (for non filled list is move most optimized choice)
- if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
- ++m_currentBuybackSlot;
- }
- }
- Item* Player::GetItemFromBuyBackSlot(uint32 slot)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
- if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
- return m_items[slot];
- return NULL;
- }
- void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
- if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
- {
- Item* pItem = m_items[slot];
- if (pItem)
- {
- pItem->RemoveFromWorld();
- if (del)
- pItem->SetState(ITEM_REMOVED, this);
- }
- m_items[slot] = NULL;
- uint32 eslot = slot - BUYBACK_SLOT_START;
- SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
- SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
- SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
- // if current backslot is filled set to now free slot
- if (m_items[m_currentBuybackSlot])
- m_currentBuybackSlot = slot;
- }
- }
- void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint32 itemid)
- {
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
- WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18));
- data << uint8(msg);
- if (msg != EQUIP_ERR_OK)
- {
- data << uint64(pItem ? pItem->GetGUID() : 0);
- data << uint64(pItem2 ? pItem2->GetGUID() : 0);
- data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
- switch (msg)
- {
- case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
- case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
- {
- ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
- data << uint32(proto ? proto->RequiredLevel : 0);
- break;
- }
- case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
- {
- data << uint64(0); // item guid
- data << uint32(0); // slot
- data << uint64(0); // container
- break;
- }
- case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED:
- case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED:
- case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED:
- {
- ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
- data << uint32(proto ? proto->ItemLimitCategory : 0);
- break;
- }
- default:
- break;
- }
- }
- GetSession()->SendPacket(&data);
- }
- void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param)
- {
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_BUY_FAILED");
- WorldPacket data(SMSG_BUY_FAILED, (8+4+4+1));
- data << uint64(creature ? creature->GetGUID() : 0);
- data << uint32(item);
- if (param > 0)
- data << uint32(param);
- data << uint8(msg);
- GetSession()->SendPacket(&data);
- }
- void Player::SendSellError(SellResult msg, Creature* creature, uint64 guid, uint32 param)
- {
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_SELL_ITEM");
- WorldPacket data(SMSG_SELL_ITEM, (8+8+(param?4:0)+1)); // last check 2.0.10
- data << uint64(creature ? creature->GetGUID() : 0);
- data << uint64(guid);
- if (param > 0)
- data << uint32(param);
- data << uint8(msg);
- GetSession()->SendPacket(&data);
- }
- void Player::TradeCancel(bool sendback)
- {
- if (m_trade)
- {
- Player* trader = m_trade->GetTrader();
- // send yellow "Trade canceled" message to both traders
- if (sendback)
- GetSession()->SendCancelTrade();
- trader->GetSession()->SendCancelTrade();
- // cleanup
- delete m_trade;
- m_trade = NULL;
- delete trader->m_trade;
- trader->m_trade = NULL;
- }
- }
- void Player::UpdateSoulboundTradeItems()
- {
- if (m_itemSoulboundTradeable.empty())
- return;
- // also checks for garbage data
- for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();)
- {
- ASSERT(*itr);
- if ((*itr)->GetOwnerGUID() != GetGUID())
- {
- m_itemSoulboundTradeable.erase(itr++);
- continue;
- }
- if ((*itr)->CheckSoulboundTradeExpire())
- {
- m_itemSoulboundTradeable.erase(itr++);
- continue;
- }
- ++itr;
- }
- }
- void Player::AddTradeableItem(Item* item)
- {
- m_itemSoulboundTradeable.push_back(item);
- }
- //TODO: should never allow an item to be added to m_itemSoulboundTradeable twice
- void Player::RemoveTradeableItem(Item* item)
- {
- m_itemSoulboundTradeable.remove(item);
- }
- void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
- {
- if (m_itemDuration.empty())
- return;
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Player::UpdateItemDuration(%u, %u)", time, realtimeonly);
- for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end();)
- {
- Item* item = *itr;
- ++itr; // current element can be erased in UpdateDuration
- if (!realtimeonly || item->GetTemplate()->FlagsCu & ITEM_FLAGS_CU_DURATION_REAL_TIME)
- item->UpdateDuration(this, time);
- }
- }
- void Player::UpdateEnchantTime(uint32 time)
- {
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr=next)
- {
- ASSERT(itr->item);
- next = itr;
- if (!itr->item->GetEnchantmentId(itr->slot))
- {
- next = m_enchantDuration.erase(itr);
- }
- else if (itr->leftduration <= time)
- {
- ApplyEnchantment(itr->item, itr->slot, false, false);
- itr->item->ClearEnchantment(itr->slot);
- next = m_enchantDuration.erase(itr);
- }
- else if (itr->leftduration > time)
- {
- itr->leftduration -= time;
- ++next;
- }
- }
- }
- void Player::AddEnchantmentDurations(Item* item)
- {
- for (int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
- {
- if (!item->GetEnchantmentId(EnchantmentSlot(x)))
- continue;
- uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
- if (duration > 0)
- AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
- }
- }
- void Player::RemoveEnchantmentDurations(Item* item)
- {
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
- {
- if (itr->item == item)
- {
- // save duration in item
- item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration, this);
- itr = m_enchantDuration.erase(itr);
- }
- else
- ++itr;
- }
- }
- void Player::RemoveArenaEnchantments(EnchantmentSlot slot)
- {
- // remove enchantments from equipped items first to clean up the m_enchantDuration list
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
- {
- next = itr;
- if (itr->slot == slot)
- {
- if (itr->item && itr->item->GetEnchantmentId(slot))
- {
- // Poisons and DK runes are enchants which are allowed on arenas
- if (sSpellMgr->IsArenaAllowedEnchancment(itr->item->GetEnchantmentId(slot)))
- {
- ++next;
- continue;
- }
- // remove from stats
- ApplyEnchantment(itr->item, slot, false, false);
- // remove visual
- itr->item->ClearEnchantment(slot);
- }
- // remove from update list
- next = m_enchantDuration.erase(itr);
- }
- else
- ++next;
- }
- // remove enchants from inventory items
- // NOTE: no need to remove these from stats, since these aren't equipped
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEnchantmentId(slot))
- pItem->ClearEnchantment(slot);
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Bag* pBag = GetBagByPos(i))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->GetEnchantmentId(slot))
- pItem->ClearEnchantment(slot);
- }
- // duration == 0 will remove item enchant
- void Player::AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration)
- {
- if (!item)
- return;
- if (slot >= MAX_ENCHANTMENT_SLOT)
- return;
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
- {
- if (itr->item == item && itr->slot == slot)
- {
- itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration, this);
- m_enchantDuration.erase(itr);
- break;
- }
- }
- if (item && duration > 0)
- {
- GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
- m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
- }
- }
- void Player::ApplyEnchantment(Item* item, bool apply)
- {
- for (uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
- ApplyEnchantment(item, EnchantmentSlot(slot), apply);
- }
- void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
- {
- if (!item || !item->IsEquipped())
- return;
- if (slot >= MAX_ENCHANTMENT_SLOT)
- return;
- uint32 enchant_id = item->GetEnchantmentId(slot);
- if (!enchant_id)
- return;
- SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!pEnchant)
- return;
- if (!ignore_condition && pEnchant->EnchantmentCondition && !EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
- return;
- if (pEnchant->requiredLevel > getLevel())
- return;
- if (pEnchant->requiredSkill > 0 && pEnchant->requiredSkillValue > GetSkillValue(pEnchant->requiredSkill))
- return;
- // If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements
- // rather than the gem requirements itself. If the socket has no color it is a prismatic socket.
- if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3)
- && !item->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color)
- {
- // Check if the requirements for the prismatic socket are met before applying the gem stats
- SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(item->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT));
- if (!pPrismaticEnchant || (pPrismaticEnchant->requiredSkill > 0 && pPrismaticEnchant->requiredSkillValue > GetSkillValue(pPrismaticEnchant->requiredSkill)))
- return;
- }
- if (!item->IsBroken())
- {
- for (int s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
- {
- uint32 enchant_display_type = pEnchant->type[s];
- uint32 enchant_amount = pEnchant->amount[s];
- uint32 enchant_spell_id = pEnchant->spellid[s];
- switch (enchant_display_type)
- {
- case ITEM_ENCHANTMENT_TYPE_NONE:
- break;
- case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
- // processed in Player::CastItemCombatSpell
- break;
- case ITEM_ENCHANTMENT_TYPE_DAMAGE:
- if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
- HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
- else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
- HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
- else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
- HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
- if (enchant_spell_id)
- {
- if (apply)
- {
- int32 basepoints = 0;
- // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
- if (item->GetItemRandomPropertyId())
- {
- ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
- if (item_rand)
- {
- // Search enchant_amount
- for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
- {
- if (item_rand->enchant_id[k] == enchant_id)
- {
- basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000);
- break;
- }
- }
- }
- }
- // Cast custom spell vs all equal basepoints got from enchant_amount
- if (basepoints)
- CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
- else
- CastSpell(this, enchant_spell_id, true, item);
- }
- else
- RemoveAurasDueToItemSpell(item, enchant_spell_id);
- }
- break;
- case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
- if (!enchant_amount)
- {
- ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
- if (item_rand)
- {
- for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
- {
- if (item_rand->enchant_id[k] == enchant_id)
- {
- enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000);
- break;
- }
- }
- }
- }
- HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_ENCHANTMENT_TYPE_STAT:
- {
- if (!enchant_amount)
- {
- ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
- if (item_rand_suffix)
- {
- for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
- {
- if (item_rand_suffix->enchant_id[k] == enchant_id)
- {
- enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000);
- break;
- }
- }
- }
- }
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Adding %u to stat nb %u", enchant_amount, enchant_spell_id);
- switch (enchant_spell_id)
- {
- case ITEM_MOD_MANA:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA", enchant_amount);
- HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_MOD_HEALTH:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH", enchant_amount);
- HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_MOD_AGILITY:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u AGILITY", enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_AGILITY, (float)enchant_amount, apply);
- break;
- case ITEM_MOD_STRENGTH:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STRENGTH", enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_STRENGTH, (float)enchant_amount, apply);
- break;
- case ITEM_MOD_INTELLECT:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u INTELLECT", enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_INTELLECT, (float)enchant_amount, apply);
- break;
- case ITEM_MOD_SPIRIT:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPIRIT", enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_SPIRIT, (float)enchant_amount, apply);
- break;
- case ITEM_MOD_STAMINA:
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STAMINA", enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_STAMINA, (float)enchant_amount, apply);
- break;
- case ITEM_MOD_DEFENSE_SKILL_RATING:
- ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DEFENCE", enchant_amount);
- break;
- case ITEM_MOD_DODGE_RATING:
- ApplyRatingMod(CR_DODGE, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DODGE", enchant_amount);
- break;
- case ITEM_MOD_PARRY_RATING:
- ApplyRatingMod(CR_PARRY, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u PARRY", enchant_amount);
- break;
- case ITEM_MOD_BLOCK_RATING:
- ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SHIELD_BLOCK", enchant_amount);
- break;
- case ITEM_MOD_HIT_MELEE_RATING:
- ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_HIT", enchant_amount);
- break;
- case ITEM_MOD_HIT_RANGED_RATING:
- ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_HIT", enchant_amount);
- break;
- case ITEM_MOD_HIT_SPELL_RATING:
- ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_HIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_MELEE_RATING:
- ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_CRIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_RANGED_RATING:
- ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_CRIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_SPELL_RATING:
- ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_CRIT", enchant_amount);
- break;
- // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
- // in Enchantments
- // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
- // ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
- // break;
- // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
- // ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
- // break;
- // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
- // ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
- // break;
- // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
- // ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
- // break;
- // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
- // ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
- // break;
- // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
- // ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
- // break;
- // case ITEM_MOD_HASTE_MELEE_RATING:
- // ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
- // break;
- // case ITEM_MOD_HASTE_RANGED_RATING:
- // ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
- // break;
- case ITEM_MOD_HASTE_SPELL_RATING:
- ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
- break;
- case ITEM_MOD_HIT_RATING:
- ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
- ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
- ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_RATING:
- ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
- ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
- ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u CRITICAL", enchant_amount);
- break;
- // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
- // case ITEM_MOD_HIT_TAKEN_RATING:
- // ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
- // ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
- // ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
- // break;
- // case ITEM_MOD_CRIT_TAKEN_RATING:
- // ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
- // ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
- // ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
- // break;
- case ITEM_MOD_RESILIENCE_RATING:
- ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
- ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
- ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RESILIENCE", enchant_amount);
- break;
- case ITEM_MOD_HASTE_RATING:
- ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
- ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
- ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HASTE", enchant_amount);
- break;
- case ITEM_MOD_EXPERTISE_RATING:
- ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u EXPERTISE", enchant_amount);
- break;
- case ITEM_MOD_ATTACK_POWER:
- HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
- HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ATTACK_POWER", enchant_amount);
- break;
- case ITEM_MOD_RANGED_ATTACK_POWER:
- HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_ATTACK_POWER", enchant_amount);
- break;
- // case ITEM_MOD_FERAL_ATTACK_POWER:
- // ApplyFeralAPBonus(enchant_amount, apply);
- // sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u FERAL_ATTACK_POWER", enchant_amount);
- // break;
- case ITEM_MOD_MANA_REGENERATION:
- ApplyManaRegenBonus(enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA_REGENERATION", enchant_amount);
- break;
- case ITEM_MOD_ARMOR_PENETRATION_RATING:
- ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ARMOR PENETRATION", enchant_amount);
- break;
- case ITEM_MOD_SPELL_POWER:
- ApplySpellPowerBonus(enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_POWER", enchant_amount);
- break;
- case ITEM_MOD_HEALTH_REGEN:
- ApplyHealthRegenBonus(enchant_amount, apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH_REGENERATION", enchant_amount);
- break;
- case ITEM_MOD_SPELL_PENETRATION:
- ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, enchant_amount, apply);
- m_spellPenetrationItemMod += apply ? int32(enchant_amount) : -int32(enchant_amount);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_PENETRATION", enchant_amount);
- break;
- case ITEM_MOD_BLOCK_VALUE:
- HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply);
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u BLOCK_VALUE", enchant_amount);
- break;
- case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
- case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
- default:
- break;
- }
- break;
- }
- case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
- {
- if (getClass() == CLASS_SHAMAN)
- {
- float addValue = 0.0f;
- if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
- {
- addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f);
- HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
- }
- else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
- {
- addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f);
- HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
- }
- }
- break;
- }
- case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
- // processed in Player::CastItemUseSpell
- break;
- case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
- // nothing do..
- break;
- default:
- sLog->outError(LOG_FILTER_PLAYER, "Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
- break;
- } /*switch (enchant_display_type)*/
- } /*for*/
- }
- // visualize enchantment at player and equipped items
- if (slot == PERM_ENCHANTMENT_SLOT)
- SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
- if (slot == TEMP_ENCHANTMENT_SLOT)
- SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
- if (apply_dur)
- {
- if (apply)
- {
- // set duration
- uint32 duration = item->GetEnchantmentDuration(slot);
- if (duration > 0)
- AddEnchantmentDuration(item, slot, duration);
- }
- else
- {
- // duration == 0 will remove EnchantDuration
- AddEnchantmentDuration(item, slot, 0);
- }
- }
- }
- void Player::UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 new_value)
- {
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (m_items[i])
- {
- for (uint8 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
- {
- uint32 ench_id = m_items[i]->GetEnchantmentId(EnchantmentSlot(slot));
- if (!ench_id)
- continue;
- SpellItemEnchantmentEntry const* Enchant = sSpellItemEnchantmentStore.LookupEntry(ench_id);
- if (!Enchant)
- return;
- if (Enchant->requiredSkill == skill_id)
- {
- // Checks if the enchantment needs to be applied or removed
- if (curr_value < Enchant->requiredSkillValue && new_value >= Enchant->requiredSkillValue)
- ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
- else if (new_value < Enchant->requiredSkillValue && curr_value >= Enchant->requiredSkillValue)
- ApplyEnchantment(m_items[i], EnchantmentSlot(slot), false);
- }
- // If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements
- // rather than the gem requirements itself. If the socket has no color it is a prismatic socket.
- if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3)
- && !m_items[i]->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color)
- {
- SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(m_items[i]->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT));
- if (pPrismaticEnchant && pPrismaticEnchant->requiredSkill == skill_id)
- {
- if (curr_value < pPrismaticEnchant->requiredSkillValue && new_value >= pPrismaticEnchant->requiredSkillValue)
- ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
- else if (new_value < pPrismaticEnchant->requiredSkillValue && curr_value >= pPrismaticEnchant->requiredSkillValue)
- ApplyEnchantment(m_items[i], EnchantmentSlot(slot), false);
- }
- }
- }
- }
- }
- }
- void Player::SendEnchantmentDurations()
- {
- for (EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
- {
- GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
- }
- }
- void Player::SendItemDurations()
- {
- for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
- {
- (*itr)->SendTimeUpdate(this);
- }
- }
- void Player::SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast)
- {
- if (!item) // prevent crash
- return;
- // last check 2.0.10
- WorldPacket data(SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4));
- data << uint64(GetGUID()); // player GUID
- data << uint32(received); // 0=looted, 1=from npc
- data << uint32(created); // 0=received, 1=created
- data << uint32(1); // bool print error to chat
- data << uint8(item->GetBagSlot()); // bagslot
- // item slot, but when added to stack: 0xFFFFFFFF
- data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
- data << uint32(item->GetEntry()); // item id
- data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
- data << int32(item->GetItemRandomPropertyId()); // random item property id
- data << uint32(count); // count of items
- data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
- if (broadcast && GetGroup())
- GetGroup()->BroadcastPacket(&data, true);
- else
- GetSession()->SendPacket(&data);
- }
- /*********************************************************/
- /*** GOSSIP SYSTEM ***/
- /*********************************************************/
- void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool showQuests /*= false*/)
- {
- PlayerMenu* menu = PlayerTalkClass;
- menu->ClearMenus();
- menu->GetGossipMenu().SetMenuId(menuId);
- GossipMenuItemsMapBounds menuItemBounds = sObjectMgr->GetGossipMenuItemsMapBounds(menuId);
- // if default menuId and no menu options exist for this, use options from default options
- if (menuItemBounds.first == menuItemBounds.second && menuId == GetDefaultGossipMenuForSource(source))
- menuItemBounds = sObjectMgr->GetGossipMenuItemsMapBounds(0);
- uint32 npcflags = 0;
- if (source->GetTypeId() == TYPEID_UNIT)
- {
- npcflags = source->GetUInt32Value(UNIT_NPC_FLAGS);
- if (npcflags & UNIT_NPC_FLAG_QUESTGIVER && showQuests)
- PrepareQuestMenu(source->GetGUID());
- }
- if (source->GetTypeId() == TYPEID_GAMEOBJECT)
- if (source->ToGameObject()->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
- PrepareQuestMenu(source->GetGUID());
- for (GossipMenuItemsContainer::const_iterator itr = menuItemBounds.first; itr != menuItemBounds.second; ++itr)
- {
- bool canTalk = true;
- if (!sConditionMgr->IsObjectMeetToConditions(this, source, itr->second.Conditions))
- continue;
- if (Creature* creature = source->ToCreature())
- {
- if (!(itr->second.OptionNpcflag & npcflags))
- continue;
- switch (itr->second.OptionType)
- {
- case GOSSIP_OPTION_ARMORER:
- canTalk = false; // added in special mode
- break;
- case GOSSIP_OPTION_SPIRITHEALER:
- if (!isDead())
- canTalk = false;
- break;
- case GOSSIP_OPTION_VENDOR:
- {
- VendorItemData const* vendorItems = creature->GetVendorItems();
- if (!vendorItems || vendorItems->Empty())
- {
- sLog->outError(LOG_FILTER_SQL, "Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", creature->GetGUIDLow(), creature->GetEntry());
- canTalk = false;
- }
- break;
- }
- case GOSSIP_OPTION_TRAINER:
- if (!creature->isCanTrainingOf(this, false))
- canTalk = false;
- break;
- case GOSSIP_OPTION_LEARNDUALSPEC:
- if (!(GetSpecsCount() == 1 && creature->isCanTrainingAndResetTalentsOf(this) && !(getLevel() < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))))
- canTalk = false;
- break;
- case GOSSIP_OPTION_UNLEARNTALENTS:
- if (!creature->isCanTrainingAndResetTalentsOf(this))
- canTalk = false;
- break;
- case GOSSIP_OPTION_UNLEARNPETTALENTS:
- if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || creature->GetCreatureTemplate()->trainer_type != TRAINER_TYPE_PETS || creature->GetCreatureTemplate()->trainer_class != CLASS_HUNTER)
- canTalk = false;
- break;
- case GOSSIP_OPTION_TAXIVENDOR:
- if (GetSession()->SendLearnNewTaxiNode(creature))
- return;
- break;
- case GOSSIP_OPTION_BATTLEFIELD:
- if (!creature->isCanInteractWithBattleMaster(this, false))
- canTalk = false;
- break;
- case GOSSIP_OPTION_STABLEPET:
- if (getClass() != CLASS_HUNTER)
- canTalk = false;
- break;
- case GOSSIP_OPTION_QUESTGIVER:
- canTalk = false;
- break;
- case GOSSIP_OPTION_GOSSIP:
- case GOSSIP_OPTION_SPIRITGUIDE:
- case GOSSIP_OPTION_INNKEEPER:
- case GOSSIP_OPTION_BANKER:
- case GOSSIP_OPTION_PETITIONER:
- case GOSSIP_OPTION_TABARDDESIGNER:
- case GOSSIP_OPTION_AUCTIONEER:
- break; // no checks
- case GOSSIP_OPTION_OUTDOORPVP:
- if (!sOutdoorPvPMgr->CanTalkTo(this, creature, itr->second))
- canTalk = false;
- break;
- default:
- sLog->outError(LOG_FILTER_SQL, "Creature entry %u have unknown gossip option %u for menu %u", creature->GetEntry(), itr->second.OptionType, itr->second.MenuId);
- canTalk = false;
- break;
- }
- }
- else if (GameObject* go = source->ToGameObject())
- {
- switch (itr->second.OptionType)
- {
- case GOSSIP_OPTION_GOSSIP:
- if (go->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && go->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
- canTalk = false;
- break;
- default:
- canTalk = false;
- break;
- }
- }
- if (canTalk)
- {
- std::string strOptionText = itr->second.OptionText;
- std::string strBoxText = itr->second.BoxText;
- int32 locale = GetSession()->GetSessionDbLocaleIndex();
- if (locale >= 0)
- {
- uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.OptionIndex);
- if (GossipMenuItemsLocale const* no = sObjectMgr->GetGossipMenuItemsLocale(idxEntry))
- {
- ObjectMgr::GetLocaleString(no->OptionText, locale, strOptionText);
- ObjectMgr::GetLocaleString(no->BoxText, locale, strBoxText);
- }
- }
- menu->GetGossipMenu().AddMenuItem(itr->second.OptionIndex, itr->second.OptionIcon, strOptionText, 0, itr->second.OptionType, strBoxText, itr->second.BoxMoney, itr->second.BoxCoded);
- menu->GetGossipMenu().AddGossipMenuItemData(itr->second.OptionIndex, itr->second.ActionMenuId, itr->second.ActionPoiId);
- }
- }
- }
- void Player::SendPreparedGossip(WorldObject* source)
- {
- if (!source)
- return;
- if (source->GetTypeId() == TYPEID_UNIT)
- {
- // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
- if (!source->ToCreature()->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
- {
- SendPreparedQuest(source->GetGUID());
- return;
- }
- }
- else if (source->GetTypeId() == TYPEID_GAMEOBJECT)
- {
- // probably need to find a better way here
- if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
- {
- SendPreparedQuest(source->GetGUID());
- return;
- }
- }
- // in case non empty gossip menu (that not included quests list size) show it
- // (quest entries from quest menu will be included in list)
- uint32 textId = GetGossipTextId(source);
- if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
- textId = GetGossipTextId(menuId, source);
- PlayerTalkClass->SendGossipMenu(textId, source->GetGUID());
- }
- void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId)
- {
- GossipMenu& gossipMenu = PlayerTalkClass->GetGossipMenu();
- // if not same, then something funky is going on
- if (menuId != gossipMenu.GetMenuId())
- return;
- GossipMenuItem const* item = gossipMenu.GetItem(gossipListId);
- if (!item)
- return;
- uint32 gossipOptionId = item->OptionType;
- uint64 guid = source->GetGUID();
- if (source->GetTypeId() == TYPEID_GAMEOBJECT)
- {
- if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), source->GetEntry());
- return;
- }
- }
- GossipMenuItemData const* menuItemData = gossipMenu.GetItemData(gossipListId);
- if (!menuItemData)
- return;
- int32 cost = int32(item->BoxMoney);
- if (!HasEnoughMoney(cost))
- {
- SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
- PlayerTalkClass->SendCloseGossip();
- return;
- }
- switch (gossipOptionId)
- {
- case GOSSIP_OPTION_GOSSIP:
- {
- if (menuItemData->GossipActionPoi)
- PlayerTalkClass->SendPointOfInterest(menuItemData->GossipActionPoi);
- if (menuItemData->GossipActionMenuId)
- {
- PrepareGossipMenu(source, menuItemData->GossipActionMenuId);
- SendPreparedGossip(source);
- }
- break;
- }
- case GOSSIP_OPTION_OUTDOORPVP:
- sOutdoorPvPMgr->HandleGossipOption(this, source->GetGUID(), gossipListId);
- break;
- case GOSSIP_OPTION_SPIRITHEALER:
- if (isDead())
- source->ToCreature()->CastSpell(source->ToCreature(), 17251, true, NULL, NULL, GetGUID());
- break;
- case GOSSIP_OPTION_QUESTGIVER:
- PrepareQuestMenu(guid);
- SendPreparedQuest(guid);
- break;
- case GOSSIP_OPTION_VENDOR:
- case GOSSIP_OPTION_ARMORER:
- GetSession()->SendListInventory(guid);
- break;
- case GOSSIP_OPTION_STABLEPET:
- GetSession()->SendStablePet(guid);
- break;
- case GOSSIP_OPTION_TRAINER:
- GetSession()->SendTrainerList(guid);
- break;
- case GOSSIP_OPTION_LEARNDUALSPEC:
- if (GetSpecsCount() == 1 && getLevel() >= sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))
- {
- // Cast spells that teach dual spec
- // Both are also ImplicitTarget self and must be cast by player
- CastSpell(this, 63680, true, NULL, NULL, GetGUID());
- CastSpell(this, 63624, true, NULL, NULL, GetGUID());
- // Should show another Gossip text with "Congratulations..."
- PlayerTalkClass->SendCloseGossip();
- }
- break;
- case GOSSIP_OPTION_UNLEARNTALENTS:
- PlayerTalkClass->SendCloseGossip();
- SendTalentWipeConfirm(guid);
- break;
- case GOSSIP_OPTION_UNLEARNPETTALENTS:
- PlayerTalkClass->SendCloseGossip();
- ResetPetTalents();
- break;
- case GOSSIP_OPTION_TAXIVENDOR:
- GetSession()->SendTaxiMenu(source->ToCreature());
- break;
- case GOSSIP_OPTION_INNKEEPER:
- PlayerTalkClass->SendCloseGossip();
- SetBindPoint(guid);
- break;
- case GOSSIP_OPTION_BANKER:
- GetSession()->SendShowBank(guid);
- break;
- case GOSSIP_OPTION_PETITIONER:
- PlayerTalkClass->SendCloseGossip();
- GetSession()->SendPetitionShowList(guid);
- break;
- case GOSSIP_OPTION_TABARDDESIGNER:
- PlayerTalkClass->SendCloseGossip();
- GetSession()->SendTabardVendorActivate(guid);
- break;
- case GOSSIP_OPTION_AUCTIONEER:
- GetSession()->SendAuctionHello(guid, source->ToCreature());
- break;
- case GOSSIP_OPTION_SPIRITGUIDE:
- PrepareGossipMenu(source);
- SendPreparedGossip(source);
- break;
- case GOSSIP_OPTION_BATTLEFIELD:
- {
- BattlegroundTypeId bgTypeId = sBattlegroundMgr->GetBattleMasterBG(source->GetEntry());
- if (bgTypeId == BATTLEGROUND_TYPE_NONE)
- {
- sLog->outError(LOG_FILTER_PLAYER, "a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
- return;
- }
- GetSession()->SendBattleGroundList(guid, bgTypeId);
- break;
- }
- }
- ModifyMoney(-cost);
- }
- uint32 Player::GetGossipTextId(WorldObject* source)
- {
- if (!source)
- return DEFAULT_GOSSIP_MESSAGE;
- return GetGossipTextId(GetDefaultGossipMenuForSource(source), source);
- }
- uint32 Player::GetGossipTextId(uint32 menuId, WorldObject* source)
- {
- uint32 textId = DEFAULT_GOSSIP_MESSAGE;
- if (!menuId)
- return textId;
- GossipMenusMapBounds menuBounds = sObjectMgr->GetGossipMenusMapBounds(menuId);
- for (GossipMenusContainer::const_iterator itr = menuBounds.first; itr != menuBounds.second; ++itr)
- {
- if (sConditionMgr->IsObjectMeetToConditions(this, source, itr->second.conditions))
- textId = itr->second.text_id;
- }
- return textId;
- }
- uint32 Player::GetDefaultGossipMenuForSource(WorldObject* source)
- {
- switch (source->GetTypeId())
- {
- case TYPEID_UNIT:
- return source->ToCreature()->GetCreatureTemplate()->GossipMenuId;
- case TYPEID_GAMEOBJECT:
- return source->ToGameObject()->GetGOInfo()->GetGossipMenuId();
- default:
- break;
- }
- return 0;
- }
- /*********************************************************/
- /*** QUEST SYSTEM ***/
- /*********************************************************/
- void Player::PrepareQuestMenu(uint64 guid)
- {
- QuestRelationBounds objectQR;
- QuestRelationBounds objectQIR;
- // pets also can have quests
- Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
- if (creature)
- {
- objectQR = sObjectMgr->GetCreatureQuestRelationBounds(creature->GetEntry());
- objectQIR = sObjectMgr->GetCreatureQuestInvolvedRelationBounds(creature->GetEntry());
- }
- else
- {
- //we should obtain map pointer from GetMap() in 99% of cases. Special case
- //only for quests which cast teleport spells on player
- Map* _map = IsInWorld() ? GetMap() : sMapMgr->FindMap(GetMapId(), GetInstanceId());
- ASSERT(_map);
- GameObject* pGameObject = _map->GetGameObject(guid);
- if (pGameObject)
- {
- objectQR = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry());
- objectQIR = sObjectMgr->GetGOQuestInvolvedRelationBounds(pGameObject->GetEntry());
- }
- else
- return;
- }
- QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
- qm.ClearMenu();
- for (QuestRelations::const_iterator i = objectQIR.first; i != objectQIR.second; ++i)
- {
- uint32 quest_id = i->second;
- QuestStatus status = GetQuestStatus(quest_id);
- if (status == QUEST_STATUS_COMPLETE)
- qm.AddMenuItem(quest_id, 4);
- else if (status == QUEST_STATUS_INCOMPLETE)
- qm.AddMenuItem(quest_id, 4);
- //else if (status == QUEST_STATUS_AVAILABLE)
- // qm.AddMenuItem(quest_id, 2);
- }
- for (QuestRelations::const_iterator i = objectQR.first; i != objectQR.second; ++i)
- {
- uint32 quest_id = i->second;
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (!quest)
- continue;
- if (!CanTakeQuest(quest, false))
- continue;
- if (quest->IsAutoComplete())
- qm.AddMenuItem(quest_id, 4);
- else if (GetQuestStatus(quest_id) == QUEST_STATUS_NONE)
- qm.AddMenuItem(quest_id, 2);
- }
- }
- void Player::SendPreparedQuest(uint64 guid)
- {
- QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
- if (questMenu.Empty())
- return;
- QuestMenuItem const& qmi0 = questMenu.GetItem(0);
- uint32 icon = qmi0.QuestIcon;
- // single element case
- if (questMenu.GetMenuItemCount() == 1)
- {
- // Auto open -- maybe also should verify there is no greeting
- uint32 questId = qmi0.QuestId;
- Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
- if (quest)
- {
- if (icon == 4 && !GetQuestRewardStatus(questId))
- PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanRewardQuest(quest, false), true);
- else if (icon == 4)
- PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanRewardQuest(quest, false), true);
- // Send completable on repeatable and autoCompletable quest if player don't have quest
- // TODO: verify if check for !quest->IsDaily() is really correct (possibly not)
- else
- {
- Object* object = ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM);
- if (!object || (!object->hasQuest(questId) && !object->hasInvolvedQuest(questId)))
- {
- PlayerTalkClass->SendCloseGossip();
- return;
- }
- if (quest->IsAutoAccept() && CanAddQuest(quest, true) && CanTakeQuest(quest, true))
- {
- AddQuest(quest, object);
- if (CanCompleteQuest(questId))
- CompleteQuest(questId);
- }
- if ((quest->IsAutoComplete() && quest->IsRepeatable() && !quest->IsDailyOrWeekly()) || quest->HasFlag(QUEST_FLAGS_AUTOCOMPLETE))
- PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanCompleteRepeatableQuest(quest), true);
- else
- PlayerTalkClass->SendQuestGiverQuestDetails(quest, guid, true);
- }
- }
- }
- // multiple entries
- else
- {
- QEmote qe;
- qe._Delay = 0;
- qe._Emote = 0;
- std::string title = "";
- // need pet case for some quests
- Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
- if (creature)
- {
- uint32 textid = GetGossipTextId(creature);
- GossipText const* gossiptext = sObjectMgr->GetGossipText(textid);
- if (!gossiptext)
- {
- qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
- qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
- title = "";
- }
- else
- {
- qe = gossiptext->Options[0].Emotes[0];
- if (!gossiptext->Options[0].Text_0.empty())
- {
- title = gossiptext->Options[0].Text_0;
- int loc_idx = GetSession()->GetSessionDbLocaleIndex();
- if (loc_idx >= 0)
- if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
- ObjectMgr::GetLocaleString(nl->Text_0[0], loc_idx, title);
- }
- else
- {
- title = gossiptext->Options[0].Text_1;
- int loc_idx = GetSession()->GetSessionDbLocaleIndex();
- if (loc_idx >= 0)
- if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
- ObjectMgr::GetLocaleString(nl->Text_1[0], loc_idx, title);
- }
- }
- }
- PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
- }
- }
- bool Player::IsActiveQuest(uint32 quest_id) const
- {
- return m_QuestStatus.find(quest_id) != m_QuestStatus.end();
- }
- Quest const* Player::GetNextQuest(uint64 guid, Quest const* quest)
- {
- QuestRelationBounds objectQR;
- Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
- if (creature)
- objectQR = sObjectMgr->GetCreatureQuestRelationBounds(creature->GetEntry());
- else
- {
- //we should obtain map pointer from GetMap() in 99% of cases. Special case
- //only for quests which cast teleport spells on player
- Map* _map = IsInWorld() ? GetMap() : sMapMgr->FindMap(GetMapId(), GetInstanceId());
- ASSERT(_map);
- GameObject* pGameObject = _map->GetGameObject(guid);
- if (pGameObject)
- objectQR = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry());
- else
- return NULL;
- }
- uint32 nextQuestID = quest->GetNextQuestInChain();
- for (QuestRelations::const_iterator itr = objectQR.first; itr != objectQR.second; ++itr)
- {
- if (itr->second == nextQuestID)
- return sObjectMgr->GetQuestTemplate(nextQuestID);
- }
- return NULL;
- }
- bool Player::CanSeeStartQuest(Quest const* quest)
- {
- if (SatisfyQuestClass(quest, false) && SatisfyQuestRace(quest, false) && SatisfyQuestSkill(quest, false) &&
- SatisfyQuestExclusiveGroup(quest, false) && SatisfyQuestReputation(quest, false) &&
- SatisfyQuestPreviousQuest(quest, false) && SatisfyQuestNextChain(quest, false) &&
- SatisfyQuestPrevChain(quest, false) && SatisfyQuestDay(quest, false) && SatisfyQuestWeek(quest, false) &&
- SatisfyQuestSeasonal(quest, false) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this))
- {
- return getLevel() + sWorld->getIntConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= quest->GetMinLevel();
- }
- return false;
- }
- bool Player::CanTakeQuest(Quest const* quest, bool msg)
- {
- return SatisfyQuestStatus(quest, msg) && SatisfyQuestExclusiveGroup(quest, msg)
- && SatisfyQuestClass(quest, msg) && SatisfyQuestRace(quest, msg) && SatisfyQuestLevel(quest, msg)
- && SatisfyQuestSkill(quest, msg) && SatisfyQuestReputation(quest, msg)
- && SatisfyQuestPreviousQuest(quest, msg) && SatisfyQuestTimed(quest, msg)
- && SatisfyQuestNextChain(quest, msg) && SatisfyQuestPrevChain(quest, msg)
- && SatisfyQuestDay(quest, msg) && SatisfyQuestWeek(quest, msg)
- && SatisfyQuestSeasonal(quest,msg) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this)
- && SatisfyQuestConditions(quest, msg);
- }
- bool Player::CanAddQuest(Quest const* quest, bool msg)
- {
- if (!SatisfyQuestLog(msg))
- return false;
- uint32 srcitem = quest->GetSrcItemId();
- if (srcitem > 0)
- {
- uint32 count = quest->GetSrcItemCount();
- ItemPosCountVec dest;
- InventoryResult msg2 = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, srcitem, count);
- // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
- if (msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS)
- return true;
- else if (msg2 != EQUIP_ERR_OK)
- {
- SendEquipError(msg2, NULL, NULL, srcitem);
- return false;
- }
- }
- return true;
- }
- bool Player::CanCompleteQuest(uint32 quest_id)
- {
- if (quest_id)
- {
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
- if (!qInfo)
- return false;
- if (!qInfo->IsRepeatable() && m_RewardedQuests.find(quest_id) != m_RewardedQuests.end())
- return false; // not allow re-complete quest
- // auto complete quest
- if ((qInfo->IsAutoComplete() || qInfo->GetFlags() & QUEST_FLAGS_AUTOCOMPLETE) && CanTakeQuest(qInfo, false))
- return true;
- QuestStatusMap::iterator itr = m_QuestStatus.find(quest_id);
- if (itr == m_QuestStatus.end())
- return false;
- QuestStatusData &q_status = itr->second;
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
- {
- if (qInfo->RequiredItemCount[i]!= 0 && q_status.ItemCount[i] < qInfo->RequiredItemCount[i])
- return false;
- }
- }
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
- {
- for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
- {
- if (qInfo->RequiredNpcOrGo[i] == 0)
- continue;
- if (qInfo->RequiredNpcOrGoCount[i] != 0 && q_status.CreatureOrGOCount[i] < qInfo->RequiredNpcOrGoCount[i])
- return false;
- }
- }
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_PLAYER_KILL))
- if (qInfo->GetPlayersSlain() != 0 && q_status.PlayerCount < qInfo->GetPlayersSlain())
- return false;
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_EXPLORATION_OR_EVENT) && !q_status.Explored)
- return false;
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_TIMED) && q_status.Timer == 0)
- return false;
- if (qInfo->GetRewOrReqMoney() < 0)
- {
- if (!HasEnoughMoney(-qInfo->GetRewOrReqMoney()))
- return false;
- }
- uint32 repFacId = qInfo->GetRepObjectiveFaction();
- if (repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue())
- return false;
- return true;
- }
- }
- return false;
- }
- bool Player::CanCompleteRepeatableQuest(Quest const* quest)
- {
- // Solve problem that player don't have the quest and try complete it.
- // if repeatable she must be able to complete event if player don't have it.
- // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
- if (!CanTakeQuest(quest, false))
- return false;
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
- if (quest->RequiredItemId[i] && quest->RequiredItemCount[i] && !HasItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i]))
- return false;
- if (!CanRewardQuest(quest, false))
- return false;
- return true;
- }
- bool Player::CanRewardQuest(Quest const* quest, bool msg)
- {
- // not auto complete quest and not completed quest (only cheating case, then ignore without message)
- if (!quest->IsDFQuest() && !quest->IsAutoComplete() && !(quest->GetFlags() & QUEST_FLAGS_AUTOCOMPLETE) && GetQuestStatus(quest->GetQuestId()) != QUEST_STATUS_COMPLETE)
- return false;
- // daily quest can't be rewarded (25 daily quest already completed)
- if (!SatisfyQuestDay(quest, true) || !SatisfyQuestWeek(quest, true) || !SatisfyQuestSeasonal(quest,true))
- return false;
- // rewarded and not repeatable quest (only cheating case, then ignore without message)
- if (GetQuestRewardStatus(quest->GetQuestId()))
- return false;
- // prevent receive reward with quest items in bank
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
- {
- if (quest->RequiredItemCount[i]!= 0 &&
- GetItemCount(quest->RequiredItemId[i]) < quest->RequiredItemCount[i])
- {
- if (msg)
- SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, quest->RequiredItemId[i]);
- return false;
- }
- }
- }
- // prevent receive reward with low money and GetRewOrReqMoney() < 0
- if (quest->GetRewOrReqMoney() < 0 && !HasEnoughMoney(-quest->GetRewOrReqMoney()))
- return false;
- return true;
- }
- bool Player::CanRewardQuest(Quest const* quest, uint32 reward, bool msg)
- {
- // prevent receive reward with quest items in bank or for not completed quest
- if (!CanRewardQuest(quest, msg))
- return false;
- if (quest->GetRewChoiceItemsCount() > 0)
- {
- if (quest->RewardChoiceItemId[reward])
- {
- ItemPosCountVec dest;
- InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardChoiceItemId[reward], quest->RewardChoiceItemCount[reward]);
- if (res != EQUIP_ERR_OK)
- {
- SendEquipError(res, NULL, NULL, quest->RewardChoiceItemId[reward]);
- return false;
- }
- }
- }
- if (quest->GetRewItemsCount() > 0)
- {
- for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
- {
- if (quest->RewardItemId[i])
- {
- ItemPosCountVec dest;
- InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardItemId[i], quest->RewardItemIdCount[i]);
- if (res != EQUIP_ERR_OK)
- {
- SendEquipError(res, NULL, NULL, quest->RewardItemId[i]);
- return false;
- }
- }
- }
- }
- return true;
- }
- void Player::AddQuest(Quest const* quest, Object* questGiver)
- {
- uint16 log_slot = FindQuestSlot(0);
- if (log_slot >= MAX_QUEST_LOG_SIZE) // Player does not have any free slot in the quest log
- return;
- uint32 quest_id = quest->GetQuestId();
- // if not exist then created with set uState == NEW and rewarded=false
- QuestStatusData& questStatusData = m_QuestStatus[quest_id];
- // check for repeatable quests status reset
- questStatusData.Status = QUEST_STATUS_INCOMPLETE;
- questStatusData.Explored = false;
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
- questStatusData.ItemCount[i] = 0;
- }
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
- {
- for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
- questStatusData.CreatureOrGOCount[i] = 0;
- }
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_PLAYER_KILL))
- questStatusData.PlayerCount = 0;
- GiveQuestSourceItem(quest);
- AdjustQuestReqItemCount(quest, questStatusData);
- if (quest->GetRepObjectiveFaction())
- if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(quest->GetRepObjectiveFaction()))
- GetReputationMgr().SetVisible(factionEntry);
- if (quest->GetRepObjectiveFaction2())
- if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(quest->GetRepObjectiveFaction2()))
- GetReputationMgr().SetVisible(factionEntry);
- uint32 qtime = 0;
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
- {
- uint32 limittime = quest->GetLimitTime();
- // shared timed quest
- if (questGiver && questGiver->GetTypeId() == TYPEID_PLAYER)
- limittime = questGiver->ToPlayer()->getQuestStatusMap()[quest_id].Timer / IN_MILLISECONDS;
- AddTimedQuest(quest_id);
- questStatusData.Timer = limittime * IN_MILLISECONDS;
- qtime = static_cast<uint32>(time(NULL)) + limittime;
- }
- else
- questStatusData.Timer = 0;
- SetQuestSlot(log_slot, quest_id, qtime);
- m_QuestStatusSave[quest_id] = true;
- GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_QUEST, quest_id);
- //starting initial quest script
- if (questGiver && quest->GetQuestStartScript() != 0)
- GetMap()->ScriptsStart(sQuestStartScripts, quest->GetQuestStartScript(), questGiver, this);
- // Some spells applied at quest activation
- SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForQuestMapBounds(quest_id, true);
- if (saBounds.first != saBounds.second)
- {
- uint32 zone, area;
- GetZoneAndAreaId(zone, area);
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area))
- if (!HasAura(itr->second->spellId))
- CastSpell(this, itr->second->spellId, true);
- }
- UpdateForQuestWorldObjects();
- }
- void Player::CompleteQuest(uint32 quest_id)
- {
- if (quest_id)
- {
- SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
- uint16 log_slot = FindQuestSlot(quest_id);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
- if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id))
- {
- if (qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED))
- RewardQuest(qInfo, 0, this, false);
- else
- SendQuestComplete(quest_id);
- }
- }
- }
- void Player::IncompleteQuest(uint32 quest_id)
- {
- if (quest_id)
- {
- SetQuestStatus(quest_id, QUEST_STATUS_INCOMPLETE);
- uint16 log_slot = FindQuestSlot(quest_id);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
- }
- }
- void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool announce)
- {
- //this THING should be here to protect code from quest, which cast on player far teleport as a reward
- //should work fine, cause far teleport will be executed in Player::Update()
- SetCanDelayTeleport(true);
- uint32 quest_id = quest->GetQuestId();
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
- if (quest->RequiredItemId[i])
- DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true);
- for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
- {
- if (quest->RequiredSourceItemId[i])
- {
- uint32 count = quest->RequiredSourceItemCount[i];
- DestroyItemCount(quest->RequiredSourceItemId[i], count ? count : 9999, true);
- }
- }
- RemoveTimedQuest(quest_id);
- if (quest->GetRewChoiceItemsCount() > 0)
- {
- if (uint32 itemId = quest->RewardChoiceItemId[reward])
- {
- ItemPosCountVec dest;
- if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardChoiceItemCount[reward]) == EQUIP_ERR_OK)
- {
- Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
- SendNewItem(item, quest->RewardChoiceItemCount[reward], true, false);
- }
- }
- }
- if (quest->GetRewItemsCount() > 0)
- {
- for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
- {
- if (uint32 itemId = quest->RewardItemId[i])
- {
- ItemPosCountVec dest;
- if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardItemIdCount[i]) == EQUIP_ERR_OK)
- {
- Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
- SendNewItem(item, quest->RewardItemIdCount[i], true, false);
- }
- }
- }
- }
- RewardReputation(quest);
- uint16 log_slot = FindQuestSlot(quest_id);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlot(log_slot, 0);
- bool rewarded = (m_RewardedQuests.find(quest_id) != m_RewardedQuests.end());
- // Not give XP in case already completed once repeatable quest
- uint32 XP = rewarded ? 0 : uint32(quest->XPValue(this)*sWorld->getRate(RATE_XP_QUEST));
- // handle SPELL_AURA_MOD_XP_QUEST_PCT auras
- Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT);
- for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
- AddPctN(XP, (*i)->GetAmount());
- int32 moneyRew = 0;
- if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
- GiveXP(XP, NULL);
- else
- moneyRew = int32(quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY));
- // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
- if (quest->GetRewOrReqMoney())
- moneyRew += quest->GetRewOrReqMoney();
- if (moneyRew)
- {
- ModifyMoney(moneyRew);
- if (moneyRew > 0)
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, uint32(moneyRew));
- }
- // honor reward
- if (uint32 honor = quest->CalculateHonorGain(getLevel()))
- RewardHonor(NULL, 0, honor);
- // title reward
- if (quest->GetCharTitleId())
- {
- if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(quest->GetCharTitleId()))
- SetTitle(titleEntry);
- }
- if (quest->GetBonusTalents())
- {
- m_questRewardTalentCount+=quest->GetBonusTalents();
- InitTalentForLevel();
- }
- if (quest->GetRewArenaPoints())
- ModifyArenaPoints(quest->GetRewArenaPoints());
- // Send reward mail
- if (uint32 mail_template_id = quest->GetRewMailTemplateId())
- {
- //- TODO: Poor design of mail system
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- MailDraft(mail_template_id).SendMailTo(trans, this, questGiver, MAIL_CHECK_MASK_HAS_BODY, quest->GetRewMailDelaySecs());
- CharacterDatabase.CommitTransaction(trans);
- }
- if (quest->IsDaily() || quest->IsDFQuest())
- {
- SetDailyQuestStatus(quest_id);
- if (quest->IsDaily())
- {
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, quest_id);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY, quest_id);
- }
- }
- else if (quest->IsWeekly())
- SetWeeklyQuestStatus(quest_id);
- else if (quest->IsSeasonal())
- SetSeasonalQuestStatus(quest_id);
- RemoveActiveQuest(quest_id);
- m_RewardedQuests.insert(quest_id);
- m_RewardedQuestsSave[quest_id] = true;
- // StoreNewItem, mail reward, etc. save data directly to the database
- // to prevent exploitable data desynchronisation we save the quest status to the database too
- // (to prevent rewarding this quest another time while rewards were already given out)
- SQLTransaction trans = SQLTransaction(NULL);
- _SaveQuestStatus(trans);
- if (announce)
- SendQuestReward(quest, XP, questGiver);
- // cast spells after mark quest complete (some spells have quest completed state requirements in spell_area data)
- if (quest->GetRewSpellCast() > 0)
- CastSpell(this, quest->GetRewSpellCast(), true);
- else if (quest->GetRewSpell() > 0)
- CastSpell(this, quest->GetRewSpell(), true);
- if (quest->GetZoneOrSort() > 0)
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, quest->GetZoneOrSort());
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, quest->GetQuestId());
- uint32 zone = 0;
- uint32 area = 0;
- // remove auras from spells with quest reward state limitations
- SpellAreaForQuestMapBounds saEndBounds = sSpellMgr->GetSpellAreaForQuestEndMapBounds(quest_id);
- if (saEndBounds.first != saEndBounds.second)
- {
- GetZoneAndAreaId(zone, area);
- for (SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
- if (!itr->second->IsFitToRequirements(this, zone, area))
- RemoveAurasDueToSpell(itr->second->spellId);
- }
- // Some spells applied at quest reward
- SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForQuestMapBounds(quest_id, false);
- if (saBounds.first != saBounds.second)
- {
- if (!zone || !area)
- GetZoneAndAreaId(zone, area);
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area))
- if (!HasAura(itr->second->spellId))
- CastSpell(this, itr->second->spellId, true);
- }
- //lets remove flag for delayed teleports
- SetCanDelayTeleport(false);
- }
- void Player::FailQuest(uint32 questId)
- {
- if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
- {
- SetQuestStatus(questId, QUEST_STATUS_FAILED);
- uint16 log_slot = FindQuestSlot(questId);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- {
- SetQuestSlotTimer(log_slot, 1);
- SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
- }
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
- {
- QuestStatusData& q_status = m_QuestStatus[questId];
- RemoveTimedQuest(questId);
- q_status.Timer = 0;
- SendQuestTimerFailed(questId);
- }
- else
- SendQuestFailed(questId);
- // Destroy quest items on quest failure.
- for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
- if (quest->RequiredItemId[i] > 0 && quest->RequiredItemCount[i] > 0)
- // Destroy items received on starting the quest.
- DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true, true);
- for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
- if (quest->RequiredSourceItemId[i] > 0 && quest->RequiredSourceItemCount[i] > 0)
- // Destroy items received during the quest.
- DestroyItemCount(quest->RequiredSourceItemId[i], quest->RequiredSourceItemCount[i], true, true);
- }
- }
- bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const
- {
- uint32 skill = qInfo->GetRequiredSkill();
- // skip 0 case RequiredSkill
- if (skill == 0)
- return true;
- // check skill value
- if (GetSkillValue(skill) < qInfo->GetRequiredSkillValue())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg)
- {
- if (getLevel() < qInfo->GetMinLevel())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_LOW_LEVEL);
- return false;
- }
- else if (qInfo->GetMaxLevel() > 0 && getLevel() > qInfo->GetMaxLevel())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); // There doesn't seem to be a specific response for too high player level
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestLog(bool msg)
- {
- // exist free slot
- if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
- return true;
- if (msg)
- {
- WorldPacket data(SMSG_QUESTLOG_FULL, 0);
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTLOG_FULL");
- }
- return false;
- }
- bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg)
- {
- // No previous quest (might be first quest in a series)
- if (qInfo->prevQuests.empty())
- return true;
- for (Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
- {
- uint32 prevId = abs(*iter);
- Quest const* qPrevInfo = sObjectMgr->GetQuestTemplate(prevId);
- if (qPrevInfo)
- {
- // If any of the positive previous quests completed, return true
- if (*iter > 0 && m_RewardedQuests.find(prevId) != m_RewardedQuests.end())
- {
- // skip one-from-all exclusive group
- if (qPrevInfo->GetExclusiveGroup() >= 0)
- return true;
- // each-from-all exclusive group (< 0)
- // can be start if only all quests in prev quest exclusive group completed and rewarded
- ObjectMgr::ExclusiveQuestGroups::iterator iter2 = sObjectMgr->mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
- ObjectMgr::ExclusiveQuestGroups::iterator end = sObjectMgr->mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
- ASSERT(iter2 != end); // always must be found if qPrevInfo->ExclusiveGroup != 0
- for (; iter2 != end; ++iter2)
- {
- uint32 exclude_Id = iter2->second;
- // skip checked quest id, only state of other quests in group is interesting
- if (exclude_Id == prevId)
- continue;
- // alternative quest from group also must be completed and rewarded(reported)
- if (m_RewardedQuests.find(exclude_Id) == m_RewardedQuests.end())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- }
- return true;
- }
- // If any of the negative previous quests active, return true
- if (*iter < 0 && GetQuestStatus(prevId) != QUEST_STATUS_NONE)
- {
- // skip one-from-all exclusive group
- if (qPrevInfo->GetExclusiveGroup() >= 0)
- return true;
- // each-from-all exclusive group (< 0)
- // can be start if only all quests in prev quest exclusive group active
- ObjectMgr::ExclusiveQuestGroups::iterator iter2 = sObjectMgr->mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
- ObjectMgr::ExclusiveQuestGroups::iterator end = sObjectMgr->mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
- ASSERT(iter2 != end); // always must be found if qPrevInfo->ExclusiveGroup != 0
- for (; iter2 != end; ++iter2)
- {
- uint32 exclude_Id = iter2->second;
- // skip checked quest id, only state of other quests in group is interesting
- if (exclude_Id == prevId)
- continue;
- // alternative quest from group also must be active
- if (GetQuestStatus(exclude_Id) != QUEST_STATUS_NONE)
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- }
- return true;
- }
- }
- }
- // Has only positive prev. quests in non-rewarded state
- // and negative prev. quests in non-active state
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const
- {
- uint32 reqClass = qInfo->GetRequiredClasses();
- if (reqClass == 0)
- return true;
- if ((reqClass & getClassMask()) == 0)
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg)
- {
- uint32 reqraces = qInfo->GetRequiredRaces();
- if (reqraces == 0)
- return true;
- if ((reqraces & getRaceMask()) == 0)
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg)
- {
- uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
- if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
- if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- // ReputationObjective2 does not seem to be an objective requirement but a requirement
- // to be able to accept the quest
- uint32 fIdObj = qInfo->GetRepObjectiveFaction2();
- if (fIdObj && GetReputationMgr().GetReputation(fIdObj) >= qInfo->GetRepObjectiveValue2())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg)
- {
- if (GetQuestStatus(qInfo->GetQuestId()) != QUEST_STATUS_NONE)
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestConditions(Quest const* qInfo, bool msg)
- {
- ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_QUEST_ACCEPT, qInfo->GetQuestId());
- if (!sConditionMgr->IsObjectMeetToConditions(this, conditions))
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- sLog->outDebug(LOG_FILTER_CONDITIONSYS, "Player::SatisfyQuestConditions: conditions not met for quest %u", qInfo->GetQuestId());
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
- {
- if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg)
- {
- // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
- if (qInfo->GetExclusiveGroup() <= 0)
- return true;
- ObjectMgr::ExclusiveQuestGroups::iterator iter = sObjectMgr->mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
- ObjectMgr::ExclusiveQuestGroups::iterator end = sObjectMgr->mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
- ASSERT(iter != end); // always must be found if qInfo->ExclusiveGroup != 0
- for (; iter != end; ++iter)
- {
- uint32 exclude_Id = iter->second;
- // skip checked quest id, only state of other quests in group is interesting
- if (exclude_Id == qInfo->GetQuestId())
- continue;
- // not allow have daily quest if daily quest from exclusive group already recently completed
- Quest const* Nquest = sObjectMgr->GetQuestTemplate(exclude_Id);
- if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false) || !SatisfyQuestSeasonal(Nquest,false))
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- // alternative quest already started or completed - but don't check rewarded states if both are repeatable
- if (GetQuestStatus(exclude_Id) != QUEST_STATUS_NONE || (!(qInfo->IsRepeatable() && Nquest->IsRepeatable()) && (m_RewardedQuests.find(exclude_Id) != m_RewardedQuests.end())))
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- }
- return true;
- }
- bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg)
- {
- uint32 nextQuest = qInfo->GetNextQuestInChain();
- if (!nextQuest)
- return true;
- // next quest in chain already started or completed
- if (GetQuestStatus(nextQuest) != QUEST_STATUS_NONE) // GetQuestStatus returns QUEST_STATUS_COMPLETED for rewarded quests
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- // check for all quests further up the chain
- // only necessary if there are quest chains with more than one quest that can be skipped
- //return SatisfyQuestNextChain(qInfo->GetNextQuestInChain(), msg);
- return true;
- }
- bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg)
- {
- // No previous quest in chain
- if (qInfo->prevChainQuests.empty())
- return true;
- for (Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter)
- {
- QuestStatusMap::const_iterator itr = m_QuestStatus.find(*iter);
- // If any of the previous quests in chain active, return false
- if (itr != m_QuestStatus.end() && itr->second.Status != QUEST_STATUS_NONE)
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- // check for all quests further down the chain
- // only necessary if there are quest chains with more than one quest that can be skipped
- //if (!SatisfyQuestPrevChain(prevId, msg))
- // return false;
- }
- // No previous quest in chain active
- return true;
- }
- bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg)
- {
- if (!qInfo->IsDaily() && !qInfo->IsDFQuest())
- return true;
- if (qInfo->IsDFQuest())
- {
- if (!m_DFQuests.empty())
- return false;
- return true;
- }
- bool have_slot = false;
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- {
- uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
- if (qInfo->GetQuestId() == id)
- return false;
- if (!id)
- have_slot = true;
- }
- if (!have_slot)
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DAILY_QUESTS_REMAINING);
- return false;
- }
- return true;
- }
- bool Player::SatisfyQuestWeek(Quest const* qInfo, bool /*msg*/)
- {
- if (!qInfo->IsWeekly() || m_weeklyquests.empty())
- return true;
- // if not found in cooldown list
- return m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end();
- }
- bool Player::SatisfyQuestSeasonal(Quest const* qInfo, bool /*msg*/)
- {
- if (!qInfo->IsSeasonal() || m_seasonalquests.empty())
- return true;
- uint16 eventId = sGameEventMgr->GetEventIdForQuest(qInfo);
- if (m_seasonalquests.find(eventId) == m_seasonalquests.end() || m_seasonalquests[eventId].empty())
- return true;
- // if not found in cooldown list
- return m_seasonalquests[eventId].find(qInfo->GetQuestId()) == m_seasonalquests[eventId].end();
- }
- bool Player::GiveQuestSourceItem(Quest const* quest)
- {
- uint32 srcitem = quest->GetSrcItemId();
- if (srcitem > 0)
- {
- uint32 count = quest->GetSrcItemCount();
- if (count <= 0)
- count = 1;
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, srcitem, count);
- if (msg == EQUIP_ERR_OK)
- {
- Item* item = StoreNewItem(dest, srcitem, true);
- SendNewItem(item, count, true, false);
- return true;
- }
- // player already have max amount required item, just report success
- else if (msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS)
- return true;
- else
- SendEquipError(msg, NULL, NULL, srcitem);
- return false;
- }
- return true;
- }
- bool Player::TakeQuestSourceItem(uint32 questId, bool msg)
- {
- Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
- if (quest)
- {
- uint32 srcItemId = quest->GetSrcItemId();
- ItemTemplate const* item = sObjectMgr->GetItemTemplate(srcItemId);
- bool destroyItem = true;
- if (srcItemId > 0)
- {
- uint32 count = quest->GetSrcItemCount();
- if (count <= 0)
- count = 1;
- // exist two cases when destroy source quest item not possible:
- // a) non un-equippable item (equipped non-empty bag, for example)
- // b) when quest is started from an item and item also is needed in
- // the end as RequiredItemId
- InventoryResult res = CanUnequipItems(srcItemId, count);
- if (res != EQUIP_ERR_OK)
- {
- if (msg)
- SendEquipError(res, NULL, NULL, srcItemId);
- return false;
- }
- for (uint8 n = 0; n < QUEST_ITEM_OBJECTIVES_COUNT; ++n)
- if (item->StartQuest == questId && srcItemId == quest->RequiredItemId[n])
- destroyItem = false;
- if (destroyItem)
- DestroyItemCount(srcItemId, count, true, true);
- }
- }
- return true;
- }
- bool Player::GetQuestRewardStatus(uint32 quest_id) const
- {
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
- if (qInfo)
- {
- // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
- if (!qInfo->IsRepeatable())
- return m_RewardedQuests.find(quest_id) != m_RewardedQuests.end();
- return false;
- }
- return false;
- }
- QuestStatus Player::GetQuestStatus(uint32 quest_id) const
- {
- if (quest_id)
- {
- QuestStatusMap::const_iterator itr = m_QuestStatus.find(quest_id);
- if (itr != m_QuestStatus.end())
- return itr->second.Status;
- if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id))
- if (!qInfo->IsRepeatable() && m_RewardedQuests.find(quest_id) != m_RewardedQuests.end())
- return QUEST_STATUS_REWARDED;
- }
- return QUEST_STATUS_NONE;
- }
- bool Player::CanShareQuest(uint32 quest_id) const
- {
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
- if (qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE))
- {
- QuestStatusMap::const_iterator itr = m_QuestStatus.find(quest_id);
- if (itr != m_QuestStatus.end())
- return itr->second.Status == QUEST_STATUS_INCOMPLETE;
- }
- return false;
- }
- void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
- {
- if (sObjectMgr->GetQuestTemplate(quest_id))
- {
- m_QuestStatus[quest_id].Status = status;
- m_QuestStatusSave[quest_id] = true;
- }
- UpdateForQuestWorldObjects();
- }
- void Player::RemoveActiveQuest(uint32 quest_id)
- {
- QuestStatusMap::iterator itr = m_QuestStatus.find(quest_id);
- if (itr != m_QuestStatus.end())
- {
- m_QuestStatus.erase(itr);
- m_QuestStatusSave[quest_id] = false;
- return;
- }
- }
- void Player::RemoveRewardedQuest(uint32 quest_id)
- {
- RewardedQuestSet::iterator rewItr = m_RewardedQuests.find(quest_id);
- if (rewItr != m_RewardedQuests.end())
- {
- m_RewardedQuests.erase(rewItr);
- m_RewardedQuestsSave[quest_id] = false;
- }
- }
- // not used in Trinity, but used in scripting code
- uint16 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
- {
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
- if (!qInfo)
- return 0;
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- if (qInfo->RequiredNpcOrGo[j] == entry)
- return m_QuestStatus[quest_id].CreatureOrGOCount[j];
- return 0;
- }
- void Player::AdjustQuestReqItemCount(Quest const* quest, QuestStatusData& questStatusData)
- {
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
- {
- uint32 reqitemcount = quest->RequiredItemCount[i];
- if (reqitemcount != 0)
- {
- uint32 curitemcount = GetItemCount(quest->RequiredItemId[i], true);
- questStatusData.ItemCount[i] = std::min(curitemcount, reqitemcount);
- m_QuestStatusSave[quest->GetQuestId()] = true;
- }
- }
- }
- }
- uint16 Player::FindQuestSlot(uint32 quest_id) const
- {
- for (uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- if (GetQuestSlotQuestId(i) == quest_id)
- return i;
- return MAX_QUEST_LOG_SIZE;
- }
- void Player::AreaExploredOrEventHappens(uint32 questId)
- {
- if (questId)
- {
- uint16 log_slot = FindQuestSlot(questId);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- {
- QuestStatusData& q_status = m_QuestStatus[questId];
- if (!q_status.Explored)
- {
- q_status.Explored = true;
- m_QuestStatusSave[questId] = true;
- }
- }
- if (CanCompleteQuest(questId))
- CompleteQuest(questId);
- }
- }
- //not used in Trinityd, function for external script library
- void Player::GroupEventHappens(uint32 questId, WorldObject const* pEventObject)
- {
- if (Group* group = GetGroup())
- {
- for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* player = itr->getSource();
- // for any leave or dead (with not released body) group member at appropriate distance
- if (player && player->IsAtGroupRewardDistance(pEventObject) && !player->GetCorpse())
- player->AreaExploredOrEventHappens(questId);
- }
- }
- else
- AreaExploredOrEventHappens(questId);
- }
- void Player::ItemAddedQuestCheck(uint32 entry, uint32 count)
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (questid == 0)
- continue;
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status != QUEST_STATUS_INCOMPLETE)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qInfo || !qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- continue;
- for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
- {
- uint32 reqitem = qInfo->RequiredItemId[j];
- if (reqitem == entry)
- {
- uint32 reqitemcount = qInfo->RequiredItemCount[j];
- uint16 curitemcount = q_status.ItemCount[j];
- if (curitemcount < reqitemcount)
- {
- uint16 additemcount = curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount;
- q_status.ItemCount[j] += additemcount;
- m_QuestStatusSave[questid] = true;
- SendQuestUpdateAddItem(qInfo, j, additemcount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- return;
- }
- }
- }
- UpdateForQuestWorldObjects();
- }
- void Player::ItemRemovedQuestCheck(uint32 entry, uint32 count)
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- if (!qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- continue;
- for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
- {
- uint32 reqitem = qInfo->RequiredItemId[j];
- if (reqitem == entry)
- {
- QuestStatusData& q_status = m_QuestStatus[questid];
- uint32 reqitemcount = qInfo->RequiredItemCount[j];
- uint16 curitemcount;
- if (q_status.Status != QUEST_STATUS_COMPLETE)
- curitemcount = q_status.ItemCount[j];
- else
- curitemcount = GetItemCount(entry, true);
- if (curitemcount < reqitemcount + count)
- {
- uint16 remitemcount = curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount;
- q_status.ItemCount[j] = (curitemcount <= remitemcount) ? 0 : curitemcount - remitemcount;
- m_QuestStatusSave[questid] = true;
- IncompleteQuest(questid);
- }
- return;
- }
- }
- }
- UpdateForQuestWorldObjects();
- }
- void Player::KilledMonster(CreatureTemplate const* cInfo, uint64 guid)
- {
- if (cInfo->Entry)
- KilledMonsterCredit(cInfo->Entry, guid);
- for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
- if (cInfo->KillCredit[i])
- KilledMonsterCredit(cInfo->KillCredit[i], 0);
- }
- void Player::KilledMonsterCredit(uint32 entry, uint64 guid)
- {
- uint16 addkillcount = 1;
- uint32 real_entry = entry;
- if (guid)
- {
- Creature* killed = GetMap()->GetCreature(guid);
- if (killed && killed->GetEntry())
- real_entry = killed->GetEntry();
- }
- GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_CREATURE, real_entry); // MUST BE CALLED FIRST
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, real_entry, addkillcount, guid ? GetMap()->GetCreature(guid) : NULL);
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- // just if !ingroup || !noraidgroup || raidgroup
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid()))
- {
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST))
- {
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- // skip GO activate objective or none
- if (qInfo->RequiredNpcOrGo[j] <= 0)
- continue;
- // skip Cast at creature objective
- if (qInfo->RequiredSpellCast[j] != 0)
- continue;
- uint32 reqkill = qInfo->RequiredNpcOrGo[j];
- if (reqkill == real_entry)
- {
- uint32 reqkillcount = qInfo->RequiredNpcOrGoCount[j];
- uint16 curkillcount = q_status.CreatureOrGOCount[j];
- if (curkillcount < reqkillcount)
- {
- q_status.CreatureOrGOCount[j] = curkillcount + addkillcount;
- m_QuestStatusSave[questid] = true;
- SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curkillcount, addkillcount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
- break;
- }
- }
- }
- }
- }
- }
- void Player::KilledPlayerCredit()
- {
- uint16 addkillcount = 1;
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- // just if !ingroup || !noraidgroup || raidgroup
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid()))
- {
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_PLAYER_KILL))
- {
- uint32 reqkill = qInfo->GetPlayersSlain();
- uint16 curkill = q_status.PlayerCount;
- if (curkill < reqkill)
- {
- q_status.PlayerCount = curkill + addkillcount;
- m_QuestStatusSave[questid] = true;
- SendQuestUpdateAddPlayer(qInfo, curkill, addkillcount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- break;
- }
- }
- }
- }
- void Player::CastedCreatureOrGO(uint32 entry, uint64 guid, uint32 spell_id)
- {
- bool isCreature = IS_CRE_OR_VEH_GUID(guid);
- uint16 addCastCount = 1;
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST))
- {
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- // skip kill creature objective (0) or wrong spell casts
- if (qInfo->RequiredSpellCast[j] != spell_id)
- continue;
- uint32 reqTarget = 0;
- if (isCreature)
- {
- // creature activate objectives
- if (qInfo->RequiredNpcOrGo[j] > 0)
- {
- // checked at quest_template loading
- reqTarget = qInfo->RequiredNpcOrGo[j];
- if (reqTarget != entry) // if entry doesn't match, check for killcredits referenced in template
- {
- CreatureTemplate const* cinfo = sObjectMgr->GetCreatureTemplate(entry);
- for (uint8 k = 0; k < MAX_KILL_CREDIT; ++k)
- if (cinfo->KillCredit[k] == reqTarget)
- entry = cinfo->KillCredit[k];
- }
- }
- }
- else
- {
- // GO activate objective
- if (qInfo->RequiredNpcOrGo[j] < 0)
- // checked at quest_template loading
- reqTarget = - qInfo->RequiredNpcOrGo[j];
- }
- // other not this creature/GO related objectives
- if (reqTarget != entry)
- continue;
- uint32 reqCastCount = qInfo->RequiredNpcOrGoCount[j];
- uint16 curCastCount = q_status.CreatureOrGOCount[j];
- if (curCastCount < reqCastCount)
- {
- q_status.CreatureOrGOCount[j] = curCastCount + addCastCount;
- m_QuestStatusSave[questid] = true;
- SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curCastCount, addCastCount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
- break;
- }
- }
- }
- }
- }
- void Player::TalkedToCreature(uint32 entry, uint64 guid)
- {
- uint16 addTalkCount = 1;
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
- {
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- // skip spell casts and Gameobject objectives
- if (qInfo->RequiredSpellCast[j] > 0 || qInfo->RequiredNpcOrGo[j] < 0)
- continue;
- uint32 reqTarget = 0;
- if (qInfo->RequiredNpcOrGo[j] > 0) // creature activate objectives
- // checked at quest_template loading
- reqTarget = qInfo->RequiredNpcOrGo[j];
- else
- continue;
- if (reqTarget == entry)
- {
- uint32 reqTalkCount = qInfo->RequiredNpcOrGoCount[j];
- uint16 curTalkCount = q_status.CreatureOrGOCount[j];
- if (curTalkCount < reqTalkCount)
- {
- q_status.CreatureOrGOCount[j] = curTalkCount + addTalkCount;
- m_QuestStatusSave[questid] = true;
- SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curTalkCount, addTalkCount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
- continue;
- }
- }
- }
- }
- }
- }
- void Player::MoneyChanged(uint32 count)
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
- Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
- if (qInfo && qInfo->GetRewOrReqMoney() < 0)
- {
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- if (int32(count) >= -qInfo->GetRewOrReqMoney())
- {
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- }
- }
- else if (q_status.Status == QUEST_STATUS_COMPLETE)
- {
- if (int32(count) < -qInfo->GetRewOrReqMoney())
- IncompleteQuest(questid);
- }
- }
- }
- }
- void Player::ReputationChanged(FactionEntry const* factionEntry)
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- if (uint32 questid = GetQuestSlotQuestId(i))
- {
- if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid))
- {
- if (qInfo->GetRepObjectiveFaction() == factionEntry->ID)
- {
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- }
- else if (q_status.Status == QUEST_STATUS_COMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
- IncompleteQuest(questid);
- }
- }
- }
- }
- }
- }
- void Player::ReputationChanged2(FactionEntry const* factionEntry)
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- if (uint32 questid = GetQuestSlotQuestId(i))
- {
- if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid))
- {
- if (qInfo->GetRepObjectiveFaction2() == factionEntry->ID)
- {
- QuestStatusData& q_status = m_QuestStatus[questid];
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue2())
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- }
- else if (q_status.Status == QUEST_STATUS_COMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue2())
- IncompleteQuest(questid);
- }
- }
- }
- }
- }
- }
- bool Player::HasQuestForItem(uint32 itemid) const
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (questid == 0)
- continue;
- QuestStatusMap::const_iterator qs_itr = m_QuestStatus.find(questid);
- if (qs_itr == m_QuestStatus.end())
- continue;
- QuestStatusData const& q_status = qs_itr->second;
- if (q_status.Status == QUEST_STATUS_INCOMPLETE)
- {
- Quest const* qinfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qinfo)
- continue;
- // hide quest if player is in raid-group and quest is no raid quest
- if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid())
- if (!InBattleground()) //there are two ways.. we can make every bg-quest a raidquest, or add this code here.. i don't know if this can be exploited by other quests, but i think all other quests depend on a specific area.. but keep this in mind, if something strange happens later
- continue;
- // There should be no mixed ReqItem/ReqSource drop
- // This part for ReqItem drop
- for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
- {
- if (itemid == qinfo->RequiredItemId[j] && q_status.ItemCount[j] < qinfo->RequiredItemCount[j])
- return true;
- }
- // This part - for ReqSource
- for (uint8 j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
- {
- // examined item is a source item
- if (qinfo->RequiredSourceItemId[j] == itemid)
- {
- ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid);
- // 'unique' item
- if (pProto->MaxCount && int32(GetItemCount(itemid, true)) < pProto->MaxCount)
- return true;
- // allows custom amount drop when not 0
- if (qinfo->RequiredSourceItemCount[j])
- {
- if (GetItemCount(itemid, true) < qinfo->RequiredSourceItemCount[j])
- return true;
- } else if (GetItemCount(itemid, true) < pProto->GetMaxStackSize())
- return true;
- }
- }
- }
- }
- return false;
- }
- void Player::SendQuestComplete(uint32 quest_id)
- {
- if (quest_id)
- {
- WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
- data << uint32(quest_id);
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id);
- }
- }
- void Player::SendQuestReward(Quest const* quest, uint32 XP, Object* questGiver)
- {
- uint32 questid = quest->GetQuestId();
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid);
- sGameEventMgr->HandleQuestComplete(questid);
- WorldPacket data(SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4));
- data << uint32(questid);
- if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
- {
- data << uint32(XP);
- data << uint32(quest->GetRewOrReqMoney());
- }
- else
- {
- data << uint32(0);
- data << uint32(quest->GetRewOrReqMoney() + int32(quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY)));
- }
- data << 10 * Trinity::Honor::hk_honor_at_level(getLevel(), quest->GetRewHonorMultiplier());
- data << uint32(quest->GetBonusTalents()); // bonus talents
- data << uint32(quest->GetRewArenaPoints());
- GetSession()->SendPacket(&data);
- if (quest->GetQuestCompleteScript() != 0)
- GetMap()->ScriptsStart(sQuestEndScripts, quest->GetQuestCompleteScript(), questGiver, this);
- }
- void Player::SendQuestFailed(uint32 questId, InventoryResult reason)
- {
- if (questId)
- {
- WorldPacket data(SMSG_QUESTGIVER_QUEST_FAILED, 4 + 4);
- data << uint32(questId);
- data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message)
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
- }
- }
- void Player::SendQuestTimerFailed(uint32 quest_id)
- {
- if (quest_id)
- {
- WorldPacket data(SMSG_QUESTUPDATE_FAILEDTIMER, 4);
- data << uint32(quest_id);
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
- }
- }
- void Player::SendCanTakeQuestResponse(uint32 msg) const
- {
- WorldPacket data(SMSG_QUESTGIVER_QUEST_INVALID, 4);
- data << uint32(msg);
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
- }
- void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver)
- {
- if (pReceiver)
- {
- std::string strTitle = quest->GetTitle();
- int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
- if (loc_idx >= 0)
- if (const QuestLocale* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
- ObjectMgr::GetLocaleString(pLocale->Title, loc_idx, strTitle);
- WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
- data << uint32(quest->GetQuestId());
- data << strTitle;
- data << uint64(GetGUID());
- pReceiver->GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
- }
- }
- void Player::SendPushToPartyResponse(Player* player, uint32 msg)
- {
- if (player)
- {
- WorldPacket data(MSG_QUEST_PUSH_RESULT, (8+1));
- data << uint64(player->GetGUID());
- data << uint8(msg); // valid values: 0-8
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent MSG_QUEST_PUSH_RESULT");
- }
- }
- void Player::SendQuestUpdateAddItem(Quest const* /*quest*/, uint32 /*item_idx*/, uint16 /*count*/)
- {
- WorldPacket data(SMSG_QUESTUPDATE_ADD_ITEM, 0);
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM");
- //data << quest->RequiredItemId[item_idx];
- //data << count;
- GetSession()->SendPacket(&data);
- }
- void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, uint64 guid, uint32 creatureOrGO_idx, uint16 old_count, uint16 add_count)
- {
- ASSERT(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
- int32 entry = quest->RequiredNpcOrGo[ creatureOrGO_idx ];
- if (entry < 0)
- // client expected gameobject template id in form (id|0x80000000)
- entry = (-entry) | 0x80000000;
- WorldPacket data(SMSG_QUESTUPDATE_ADD_KILL, (4*4+8));
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL");
- data << uint32(quest->GetQuestId());
- data << uint32(entry);
- data << uint32(old_count + add_count);
- data << uint32(quest->RequiredNpcOrGoCount[ creatureOrGO_idx ]);
- data << uint64(guid);
- GetSession()->SendPacket(&data);
- uint16 log_slot = FindQuestSlot(quest->GetQuestId());
- if (log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlotCounter(log_slot, creatureOrGO_idx, GetQuestSlotCounter(log_slot, creatureOrGO_idx)+add_count);
- }
- void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint16 add_count)
- {
- ASSERT(old_count + add_count < 65536 && "player count store in 16 bits");
- WorldPacket data(SMSG_QUESTUPDATE_ADD_PVP_KILL, (3*4));
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_PVP_KILL");
- data << uint32(quest->GetQuestId());
- data << uint32(old_count + add_count);
- data << uint32(quest->GetPlayersSlain());
- GetSession()->SendPacket(&data);
- uint16 log_slot = FindQuestSlot(quest->GetQuestId());
- if (log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlotCounter(log_slot, QUEST_PVP_KILL_SLOT, GetQuestSlotCounter(log_slot, QUEST_PVP_KILL_SLOT) + add_count);
- }
- /*********************************************************/
- /*** LOAD SYSTEM ***/
- /*********************************************************/
- void Player::Initialize(uint32 guid)
- {
- Object::_Create(guid, 0, HIGHGUID_PLAYER);
- }
- void Player::_LoadDeclinedNames(PreparedQueryResult result)
- {
- if (!result)
- return;
- delete m_declinedname;
- m_declinedname = new DeclinedName;
- for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
- m_declinedname->name[i] = (*result)[i].GetString();
- }
- void Player::_LoadArenaTeamInfo(PreparedQueryResult result)
- {
- // arenateamid, played_week, played_season, personal_rating
- memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
- uint16 personalRatingCache[] = {0, 0, 0};
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint32 arenaTeamId = fields[0].GetUInt32();
- ArenaTeam* arenaTeam = sArenaTeamMgr->GetArenaTeamById(arenaTeamId);
- if (!arenaTeam)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenaTeamId);
- continue;
- }
- uint8 arenaSlot = arenaTeam->GetSlot();
- personalRatingCache[arenaSlot] = fields[4].GetUInt16();
- SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenaTeamId);
- SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, arenaTeam->GetType());
- SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (arenaTeam->GetCaptain() == GetGUID()) ? 0 : 1);
- SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, uint32(fields[1].GetUInt16()));
- SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, uint32(fields[2].GetUInt16()));
- SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, uint32(fields[3].GetUInt16()));
- }
- while (result->NextRow());
- }
- for (uint8 slot = 0; slot <= 2; ++slot)
- {
- SetArenaTeamInfoField(slot, ARENA_TEAM_PERSONAL_RATING, uint32(personalRatingCache[slot]));
- }
- }
- void Player::_LoadEquipmentSets(PreparedQueryResult result)
- {
- // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
- if (!result)
- return;
- uint32 count = 0;
- do
- {
- Field* fields = result->Fetch();
- EquipmentSet eqSet;
- eqSet.Guid = fields[0].GetUInt64();
- uint8 index = fields[1].GetUInt8();
- eqSet.Name = fields[2].GetString();
- eqSet.IconName = fields[3].GetString();
- eqSet.IgnoreMask = fields[4].GetUInt32();
- eqSet.state = EQUIPMENT_SET_UNCHANGED;
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- eqSet.Items[i] = fields[5+i].GetUInt32();
- m_EquipmentSets[index] = eqSet;
- ++count;
- if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit
- break;
- }
- while (result->NextRow());
- }
- void Player::_LoadBGData(PreparedQueryResult result)
- {
- if (!result)
- return;
- Field* fields = result->Fetch();
- // Expecting only one row
- // 0 1 2 3 4 5 6 7 8 9
- // SELECT instanceId, team, joinX, joinY, joinZ, joinO, joinMapId, taxiStart, taxiEnd, mountSpell FROM character_battleground_data WHERE guid = ?
- m_bgData.bgInstanceID = fields[0].GetUInt32();
- m_bgData.bgTeam = fields[1].GetUInt16();
- m_bgData.joinPos = WorldLocation(fields[6].GetUInt16(), // Map
- fields[2].GetFloat(), // X
- fields[3].GetFloat(), // Y
- fields[4].GetFloat(), // Z
- fields[5].GetFloat()); // Orientation
- m_bgData.taxiPath[0] = fields[7].GetUInt32();
- m_bgData.taxiPath[1] = fields[8].GetUInt32();
- m_bgData.mountSpell = fields[9].GetUInt32();
- }
- bool Player::LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, uint64 guid)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION);
- stmt->setUInt32(0, GUID_LOPART(guid));
- PreparedQueryResult result = CharacterDatabase.Query(stmt);
- if (!result)
- return false;
- Field* fields = result->Fetch();
- x = fields[0].GetFloat();
- y = fields[1].GetFloat();
- z = fields[2].GetFloat();
- o = fields[3].GetFloat();
- mapid = fields[4].GetUInt16();
- in_flight = !fields[5].GetString().empty();
- return true;
- }
- void Player::SetHomebind(WorldLocation const& /*loc*/, uint32 /*area_id*/)
- {
- m_homebindMapId = GetMapId();
- m_homebindAreaId = GetAreaId();
- m_homebindX = GetPositionX();
- m_homebindY = GetPositionY();
- m_homebindZ = GetPositionZ();
- // update sql homebind
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_HOMEBIND);
- stmt->setUInt16(0, m_homebindMapId);
- stmt->setUInt16(1, m_homebindAreaId);
- stmt->setFloat (2, m_homebindX);
- stmt->setFloat (3, m_homebindY);
- stmt->setFloat (4, m_homebindZ);
- stmt->setUInt32(5, GetGUIDLow());
- CharacterDatabase.Execute(stmt);
- }
- uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
- {
- if (index >= data.size())
- return 0;
- return (uint32)atoi(data[index]);
- }
- float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
- {
- float result;
- uint32 temp = Player::GetUInt32ValueFromArray(data, index);
- memcpy(&result, &temp, sizeof(result));
- return result;
- }
- bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder)
- {
- //// 0 1 2 3 4 5 6 7 8 9 10 11
- //QueryResult* result = CharacterDatabase.PQuery("SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, "
- // 12 13 14 15 16 17 18 19 20 21 22 23 24
- //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, "
- // 25 26 27 28 29 30 31 32 33 34 35 36 37 38
- //"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, "
- // 39 40 41 42 43 44 45 46 47 48 49
- //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, "
- // 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
- //"health, power1, power2, power3, power4, power5, power6, power7, instance_id, speccount, activespec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels FROM characters WHERE guid = '%u'", guid);
- PreparedQueryResult result = holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADFROM);
- if (!result)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) not found in table `characters`, can't load. ", guid);
- return false;
- }
- Field* fields = result->Fetch();
- uint32 dbAccountId = fields[1].GetUInt32();
- // check if the character's account in the db and the logged in account match.
- // player should be able to load/delete character only with correct account!
- if (dbAccountId != GetSession()->GetAccountId())
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) loading from wrong account (is: %u, should be: %u)", guid, GetSession()->GetAccountId(), dbAccountId);
- return false;
- }
- if (holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADBANNED))
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) is banned, can't load.", guid);
- return false;
- }
- Object::_Create(guid, 0, HIGHGUID_PLAYER);
- m_name = fields[2].GetString();
- // check name limitations
- if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
- (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()) && sObjectMgr->IsReservedName(m_name)))
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);
- stmt->setUInt16(0, uint16(AT_LOGIN_RENAME));
- stmt->setUInt32(1, guid);
- CharacterDatabase.Execute(stmt);
- return false;
- }
- // Cleanup old Wowarmory feeds
- InitWowarmoryFeeds();
- // overwrite possible wrong/corrupted guid
- SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
- uint8 Gender = fields[5].GetUInt8();
- if (!IsValidGender(Gender))
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) has wrong gender (%hu), can't be loaded.", guid, Gender);
- return false;
- }
- // overwrite some data fields
- uint32 bytes0 = 0;
- bytes0 |= fields[3].GetUInt8(); // race
- bytes0 |= fields[4].GetUInt8() << 8; // class
- bytes0 |= Gender << 16; // gender
- SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
- SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8());
- SetUInt32Value(PLAYER_XP, fields[7].GetUInt32());
- _LoadIntoDataField(fields[61].GetCString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE);
- _LoadIntoDataField(fields[64].GetCString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2);
- SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
- SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
- SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f);
- // load achievements before anything else to prevent multiple gains for the same achievement/criteria on every loading (as loading does call UpdateAchievementCriteria)
- m_achievementMgr.LoadFromDB(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
- uint32 money = fields[8].GetUInt32();
- if (money > MAX_MONEY_AMOUNT)
- money = MAX_MONEY_AMOUNT;
- SetMoney(money);
- SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32());
- SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32());
- SetByteValue(PLAYER_BYTES_3, 0, fields[5].GetUInt8());
- SetByteValue(PLAYER_BYTES_3, 1, fields[49].GetUInt8());
- SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32());
- SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetUInt32());
- SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64());
- SetUInt32Value(PLAYER_AMMO_ID, fields[63].GetUInt32());
- // set which actionbars the client has active - DO NOT REMOVE EVER AGAIN (can be changed though, if it does change fieldwise)
- SetByteValue(PLAYER_FIELD_BYTES, 2, fields[65].GetUInt8());
- InitDisplayIds();
- // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
- for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
- SetVisibleItemSlot(slot, NULL);
- delete m_items[slot];
- m_items[slot] = NULL;
- }
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Load Basic value of player %s is: ", m_name.c_str());
- outDebugValues();
- //Need to call it to initialize m_team (m_team can be calculated from race)
- //Other way is to saves m_team into characters table.
- setFactionForRace(getRace());
- // load home bind and check in same time class/race pair, it used later for restore broken positions
- if (!_LoadHomeBind(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
- return false;
- InitPrimaryProfessions(); // to max set before any spell loaded
- // init saved position, and fix it later if problematic
- uint32 transGUID = fields[30].GetUInt32();
- Relocate(fields[12].GetFloat(), fields[13].GetFloat(), fields[14].GetFloat(), fields[16].GetFloat());
- uint32 mapId = fields[15].GetUInt16();
- uint32 instanceId = fields[58].GetUInt32();
- uint32 dungeonDiff = fields[38].GetUInt8() & 0x0F;
- if (dungeonDiff >= MAX_DUNGEON_DIFFICULTY)
- dungeonDiff = DUNGEON_DIFFICULTY_NORMAL;
- uint32 raidDiff = (fields[38].GetUInt8() >> 4) & 0x0F;
- if (raidDiff >= MAX_RAID_DIFFICULTY)
- raidDiff = RAID_DIFFICULTY_10MAN_NORMAL;
- SetDungeonDifficulty(Difficulty(dungeonDiff)); // may be changed in _LoadGroup
- SetRaidDifficulty(Difficulty(raidDiff)); // may be changed in _LoadGroup
- std::string taxi_nodes = fields[37].GetString();
- #define RelocateToHomebind(){ mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); }
- _LoadGroup(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADGROUP));
- _LoadArenaTeamInfo(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
- SetArenaPoints(fields[39].GetUInt32());
- // check arena teams integrity
- for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
- {
- uint32 arena_team_id = GetArenaTeamId(arena_slot);
- if (!arena_team_id)
- continue;
- if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(arena_team_id))
- if (at->IsMember(GetGUID()))
- continue;
- // arena team not exist or not member, cleanup fields
- for (int j = 0; j < 6; ++j)
- SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
- }
- SetHonorPoints(fields[40].GetUInt32());
- SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32());
- SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32());
- SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, fields[43].GetUInt32());
- SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16());
- SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16());
- _LoadBoundInstances(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
- _LoadInstanceTimeRestrictions(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADINSTANCELOCKTIMES));
- _LoadBGData(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
- GetSession()->SetPlayer(this);
- MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
- if (!mapEntry || !IsPositionValid())
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- RelocateToHomebind();
- }
- // Player was saved in Arena or Bg
- else if (mapEntry && mapEntry->IsBattlegroundOrArena())
- {
- Battleground* currentBg = NULL;
- if (m_bgData.bgInstanceID) //saved in Battleground
- currentBg = sBattlegroundMgr->GetBattleground(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
- bool player_at_bg = currentBg && currentBg->IsPlayerInBattleground(GetGUID());
- if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
- {
- BattlegroundQueueTypeId bgQueueTypeId = sBattlegroundMgr->BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
- AddBattlegroundQueueId(bgQueueTypeId);
- m_bgData.bgTypeID = currentBg->GetTypeID();
- //join player to battleground group
- currentBg->EventPlayerLoggedIn(this);
- currentBg->AddOrSetPlayerToCorrectBgGroup(this, m_bgData.bgTeam);
- SetInviteForBattlegroundQueueType(bgQueueTypeId, currentBg->GetInstanceID());
- }
- // Bg was not found - go to Entry Point
- else
- {
- // leave bg
- if (player_at_bg)
- currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
- // Do not look for instance if bg not found
- const WorldLocation& _loc = GetBattlegroundEntryPoint();
- mapId = _loc.GetMapId(); instanceId = 0;
- if (mapId == MAPID_INVALID) // Battleground Entry Point not found (???)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.", guid);
- RelocateToHomebind();
- }
- else
- Relocate(&_loc);
- // We are not in BG anymore
- m_bgData.bgInstanceID = 0;
- }
- }
- // currently we do not support transport in bg
- else if (transGUID)
- {
- m_movementInfo.t_guid = MAKE_NEW_GUID(transGUID, 0, HIGHGUID_MO_TRANSPORT);
- m_movementInfo.t_pos.Relocate(fields[26].GetFloat(), fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat());
- if (!Trinity::IsValidMapCoord(
- GetPositionX()+m_movementInfo.t_pos.m_positionX, GetPositionY()+m_movementInfo.t_pos.m_positionY,
- GetPositionZ()+m_movementInfo.t_pos.m_positionZ, GetOrientation()+m_movementInfo.t_pos.m_orientation) ||
- // transport size limited
- m_movementInfo.t_pos.m_positionX > 250 || m_movementInfo.t_pos.m_positionY > 250 || m_movementInfo.t_pos.m_positionZ > 250)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to bind location.",
- guid, GetPositionX()+m_movementInfo.t_pos.m_positionX, GetPositionY()+m_movementInfo.t_pos.m_positionY,
- GetPositionZ()+m_movementInfo.t_pos.m_positionZ, GetOrientation()+m_movementInfo.t_pos.m_orientation);
- RelocateToHomebind();
- }
- else
- {
- for (MapManager::TransportSet::iterator iter = sMapMgr->m_Transports.begin(); iter != sMapMgr->m_Transports.end(); ++iter)
- {
- if ((*iter)->GetGUIDLow() == transGUID)
- {
- m_transport = *iter;
- m_transport->AddPassenger(this);
- mapId = (m_transport->GetMapId());
- break;
- }
- }
- if (!m_transport)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have problems with transport guid (%u). Teleport to bind location.",
- guid, transGUID);
- RelocateToHomebind();
- }
- }
- }
- // currently we do not support taxi in instance
- else if (!taxi_nodes.empty())
- {
- instanceId = 0;
- // Not finish taxi flight path
- if (m_bgData.HasTaxiPath())
- {
- for (int i = 0; i < 2; ++i)
- m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
- }
- else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam()))
- {
- // problems with taxi path loading
- TaxiNodesEntry const* nodeEntry = NULL;
- if (uint32 node_id = m_taxi.GetTaxiSource())
- nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
- if (!nodeEntry) // don't know taxi start node, to homebind
- {
- sLog->outError(LOG_FILTER_PLAYER, "Character %u have wrong data in taxi destination list, teleport to homebind.", GetGUIDLow());
- RelocateToHomebind();
- }
- else // have start node, to it
- {
- sLog->outError(LOG_FILTER_PLAYER, "Character %u have too short taxi destination list, teleport to original node.", GetGUIDLow());
- mapId = nodeEntry->map_id;
- Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z, 0.0f);
- }
- m_taxi.ClearTaxiDestinations();
- }
- if (uint32 node_id = m_taxi.GetTaxiSource())
- {
- // save source node as recall coord to prevent recall and fall from sky
- TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
- if (nodeEntry && nodeEntry->map_id == GetMapId())
- {
- ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
- mapId = nodeEntry->map_id;
- Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z, 0.0f);
- }
- // flight will started later
- }
- }
- // Map could be changed before
- mapEntry = sMapStore.LookupEntry(mapId);
- // client without expansion support
- if (mapEntry)
- {
- if (GetSession()->Expansion() < mapEntry->Expansion())
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player %s using client without required expansion tried login at non accessible map %u", GetName(), mapId);
- RelocateToHomebind();
- }
- // fix crash (because of if (Map* map = _FindMap(instanceId)) in MapInstanced::CreateInstance)
- if (instanceId)
- if (InstanceSave* save = GetInstanceSave(mapId, mapEntry->IsRaid()))
- if (save->GetInstanceId() != instanceId)
- instanceId = 0;
- }
- // NOW player must have valid map
- // load the player's map here if it's not already loaded
- Map* map = sMapMgr->CreateMap(mapId, this);
- if (!map)
- {
- instanceId = 0;
- AreaTrigger const* at = sObjectMgr->GetGoBackTrigger(mapId);
- if (at)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) is teleported to gobacktrigger (Map: %u X: %f Y: %f Z: %f O: %f).", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- Relocate(at->target_X, at->target_Y, at->target_Z, GetOrientation());
- mapId = at->target_mapId;
- }
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) is teleported to home (Map: %u X: %f Y: %f Z: %f O: %f).", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- RelocateToHomebind();
- }
- map = sMapMgr->CreateMap(mapId, this);
- if (!map)
- {
- PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
- mapId = info->mapId;
- Relocate(info->positionX, info->positionY, info->positionZ, 0.0f);
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- map = sMapMgr->CreateMap(mapId, this);
- if (!map)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) has invalid default map coordinates (X: %f Y: %f Z: %f O: %f). or instance couldn't be created", guid, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- return false;
- }
- }
- }
- // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
- if (instanceId && !sInstanceSaveMgr->GetInstanceSave(instanceId) && !map->IsBattlegroundOrArena())
- {
- AreaTrigger const* at = sObjectMgr->GetMapEntranceTrigger(mapId);
- if (at)
- Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), mapId);
- RelocateToHomebind();
- }
- }
- SetMap(map);
- StoreRaidMapDifficulty();
- // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
- // this must help in case next save after mass player load after server startup
- m_nextSave = urand(m_nextSave/2, m_nextSave*3/2);
- SaveRecallPosition();
- time_t now = time(NULL);
- time_t logoutTime = time_t(fields[22].GetUInt32());
- // since last logout (in seconds)
- uint32 time_diff = uint32(now - logoutTime); //uint64 is excessive for a time_diff in seconds.. uint32 allows for 136~ year difference.
- // set value, including drunk invisibility detection
- // calculate sobering. after 15 minutes logged out, the player will be sober again
- uint8 newDrunkValue = 0;
- if (time_diff < uint32(GetDrunkValue()) * 9)
- newDrunkValue = GetDrunkValue() - time_diff / 9;
- SetDrunkValue(newDrunkValue);
- m_cinematic = fields[18].GetUInt8();
- m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32();
- m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32();
- m_resetTalentsCost = fields[24].GetUInt32();
- m_resetTalentsTime = time_t(fields[25].GetUInt32());
- m_taxi.LoadTaxiMask(fields[17].GetCString()); // must be before InitTaxiNodesForLevel
- uint32 extraflags = fields[31].GetUInt16();
- m_stableSlots = fields[32].GetUInt8();
- if (m_stableSlots > MAX_PET_STABLES)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player can have not more %u stable slots, but have in DB %u", MAX_PET_STABLES, uint32(m_stableSlots));
- m_stableSlots = MAX_PET_STABLES;
- }
- m_atLoginFlags = fields[33].GetUInt16();
- // Honor system
- // Update Honor kills data
- m_lastHonorUpdateTime = logoutTime;
- UpdateHonorFields();
- m_deathExpireTime = time_t(fields[36].GetUInt32());
- if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
- m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
- // clear channel spell data (if saved at channel spell casting)
- SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
- SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
- // clear charm/summon related fields
- SetOwnerGUID(0);
- SetUInt64Value(UNIT_FIELD_CHARMEDBY, 0);
- SetUInt64Value(UNIT_FIELD_CHARM, 0);
- SetUInt64Value(UNIT_FIELD_SUMMON, 0);
- SetUInt64Value(PLAYER_FARSIGHT, 0);
- SetCreatorGUID(0);
- RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
- // reset some aura modifiers before aura apply
- SetUInt32Value(PLAYER_TRACK_CREATURES, 0);
- SetUInt32Value(PLAYER_TRACK_RESOURCES, 0);
- // make sure the unit is considered out of combat for proper loading
- ClearInCombat();
- // make sure the unit is considered not in duel for proper loading
- SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
- SetUInt32Value(PLAYER_DUEL_TEAM, 0);
- // reset stats before loading any modifiers
- InitStatsForLevel();
- InitGlyphsForLevel();
- InitTaxiNodesForLevel();
- InitRunes();
- // rest bonus can only be calculated after InitStatsForLevel()
- m_rest_bonus = fields[21].GetFloat();
- if (time_diff > 0)
- {
- //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
- float bubble0 = 0.031f;
- //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
- float bubble1 = 0.125f;
- float bubble = fields[23].GetUInt8() > 0
- ? bubble1*sWorld->getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
- : bubble0*sWorld->getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
- SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
- }
- // load skills after InitStatsForLevel because it triggering aura apply also
- _LoadSkills(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
- UpdateSkillsForLevel(); //update skills after load, to make sure they are correctly update at player load
- // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
- //mails are loaded only when needed ;-) - when player in game click on mailbox.
- //_LoadMail();
- m_specsCount = fields[59].GetUInt8();
- m_activeSpec = fields[60].GetUInt8();
- // sanity check
- if (m_specsCount > MAX_TALENT_SPECS || m_activeSpec > MAX_TALENT_SPEC || m_specsCount < MIN_TALENT_SPECS)
- {
- m_activeSpec = 0;
- sLog->outError(LOG_FILTER_PLAYER, "Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName(), GetGUIDLow(), m_specsCount, m_activeSpec);
- }
- _LoadTalents(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
- _LoadSpells(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
- _LoadGlyphs(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
- _LoadAuras(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
- _LoadGlyphAuras();
- // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
- if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
- m_deathState = DEAD;
- // after spell load, learn rewarded spell if need also
- _LoadQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
- _LoadQuestStatusRewarded(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUSREW));
- _LoadDailyQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
- _LoadWeeklyQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADWEEKLYQUESTSTATUS));
- _LoadSeasonalQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSEASONALQUESTSTATUS));
- _LoadRandomBGStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADRANDOMBG));
- // after spell and quest load
- InitTalentForLevel();
- learnDefaultSpells();
- // must be before inventory (some items required reputation check)
- m_reputationMgr.LoadFromDB(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
- _LoadInventory(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
- // update items with duration and realtime
- UpdateItemDuration(time_diff, true);
- _LoadActions(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
- // unread mails and next delivery time, actual mails not loaded
- _LoadMailInit(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
- m_social = sSocialMgr->LoadFromDB(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
- // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
- // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
- uint32 curTitle = fields[46].GetUInt32();
- if (curTitle && !HasTitle(curTitle))
- curTitle = 0;
- SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
- // has to be called after last Relocate() in Player::LoadFromDB
- SetFallInformation(0, GetPositionZ());
- _LoadSpellCooldowns(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
- // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
- // Do now before stats re-calculation cleanup for ghost state unexpected auras
- if (!isAlive())
- RemoveAllAurasOnDeath();
- else
- RemoveAllAurasRequiringDeadTarget();
- //apply all stat bonuses from items and auras
- SetCanModifyStats(true);
- UpdateAllStats();
- // restore remembered power/health values (but not more max values)
- uint32 savedHealth = fields[50].GetUInt32();
- SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
- for (uint8 i = 0; i < MAX_POWERS; ++i)
- {
- uint32 savedPower = fields[51+i].GetUInt32();
- SetPower(Powers(i), savedPower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower);
- }
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "The value of player %s after load item and aura is: ", m_name.c_str());
- outDebugValues();
- // GM state
- if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
- {
- switch (sWorld->getIntConfig(CONFIG_GM_LOGIN_STATE))
- {
- default:
- case 0: break; // disable
- case 1: SetGameMaster(true); break; // enable
- case 2: // save state
- if (extraflags & PLAYER_EXTRA_GM_ON)
- SetGameMaster(true);
- break;
- }
- switch (sWorld->getIntConfig(CONFIG_GM_VISIBLE_STATE))
- {
- default:
- case 0: SetGMVisible(false); break; // invisible
- case 1: break; // visible
- case 2: // save state
- if (extraflags & PLAYER_EXTRA_GM_INVISIBLE)
- SetGMVisible(false);
- break;
- }
- switch (sWorld->getIntConfig(CONFIG_GM_CHAT))
- {
- default:
- case 0: break; // disable
- case 1: SetGMChat(true); break; // enable
- case 2: // save state
- if (extraflags & PLAYER_EXTRA_GM_CHAT)
- SetGMChat(true);
- break;
- }
- switch (sWorld->getIntConfig(CONFIG_GM_WHISPERING_TO))
- {
- default:
- case 0: break; // disable
- case 1: SetAcceptWhispers(true); break; // enable
- case 2: // save state
- if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
- SetAcceptWhispers(true);
- break;
- }
- }
- // RaF stuff.
- m_grantableLevels = fields[66].GetUInt8();
- if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
- SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
- if (m_grantableLevels > 0)
- SetByteValue(PLAYER_FIELD_BYTES, 1, 0x01);
- _LoadDeclinedNames(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
- m_achievementMgr.CheckAllAchievementCriteria();
- _LoadEquipmentSets(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
- return true;
- }
- bool Player::isAllowedToLoot(const Creature* creature)
- {
- if (!creature->isDead() || !creature->IsDamageEnoughForLootingAndReward())
- return false;
- if (HasPendingBind())
- return false;
- const Loot* loot = &creature->loot;
- if (loot->isLooted()) // nothing to loot or everything looted.
- return false;
- Group* thisGroup = GetGroup();
- if (!thisGroup)
- return this == creature->GetLootRecipient();
- else if (thisGroup != creature->GetLootRecipientGroup())
- return false;
- switch (thisGroup->GetLootMethod())
- {
- case FREE_FOR_ALL:
- return true;
- case ROUND_ROBIN:
- case MASTER_LOOT:
- // may only loot if the player is the loot roundrobin player
- // or if there are free/quest/conditional item for the player
- if (loot->roundRobinPlayer == 0 || loot->roundRobinPlayer == GetGUID())
- return true;
- return loot->hasItemFor(this);
- case GROUP_LOOT:
- case NEED_BEFORE_GREED:
- // may only loot if the player is the loot roundrobin player
- // or item over threshold (so roll(s) can be launched)
- // or if there are free/quest/conditional item for the player
- if (loot->roundRobinPlayer == 0 || loot->roundRobinPlayer == GetGUID())
- return true;
- if (loot->hasOverThresholdItem())
- return true;
- return loot->hasItemFor(this);
- }
- return false;
- }
- void Player::_LoadActions(PreparedQueryResult result)
- {
- m_actionButtons.clear();
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint8 button = fields[0].GetUInt8();
- uint32 action = fields[1].GetUInt32();
- uint8 type = fields[2].GetUInt8();
- if (ActionButton* ab = addActionButton(button, action, type))
- ab->uState = ACTIONBUTTON_UNCHANGED;
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, " ...at loading, and will deleted in DB also");
- // Will deleted in DB at next save (it can create data until save but marked as deleted)
- m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
- }
- } while (result->NextRow());
- }
- }
- void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Loading auras for player %u", GetGUIDLow());
- /* 0 1 2 3 4 5 6 7 8 9 10
- QueryResult* result = CharacterDatabase.PQuery("SELECT caster_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2,
- 11 12 13
- maxduration, remaintime, remaincharges FROM character_aura WHERE guid = '%u'", GetGUIDLow());
- */
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- int32 damage[3];
- int32 baseDamage[3];
- uint64 caster_guid = fields[0].GetUInt64();
- uint32 spellid = fields[1].GetUInt32();
- uint8 effmask = fields[2].GetUInt8();
- uint8 recalculatemask = fields[3].GetUInt8();
- uint8 stackcount = fields[4].GetUInt8();
- damage[0] = fields[5].GetInt32();
- damage[1] = fields[6].GetInt32();
- damage[2] = fields[7].GetInt32();
- baseDamage[0] = fields[8].GetInt32();
- baseDamage[1] = fields[9].GetInt32();
- baseDamage[2] = fields[10].GetInt32();
- int32 maxduration = fields[11].GetInt32();
- int32 remaintime = fields[12].GetInt32();
- uint8 remaincharges = fields[13].GetUInt8();
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid);
- if (!spellInfo)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Unknown aura (spellid %u), ignore.", spellid);
- continue;
- }
- // negative effects should continue counting down after logout
- if (remaintime != -1 && !spellInfo->IsPositive())
- {
- if (remaintime/IN_MILLISECONDS <= int32(timediff))
- continue;
- remaintime -= timediff*IN_MILLISECONDS;
- }
- // prevent wrong values of remaincharges
- if (spellInfo->ProcCharges)
- {
- // we have no control over the order of applying auras and modifiers allow auras
- // to have more charges than value in SpellInfo
- if (remaincharges <= 0/* || remaincharges > spellproto->procCharges*/)
- remaincharges = spellInfo->ProcCharges;
- }
- else
- remaincharges = 0;
- if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, NULL, &baseDamage[0], NULL, caster_guid))
- {
- if (!aura->CanBeSaved())
- {
- aura->Remove();
- continue;
- }
- aura->SetLoadedState(maxduration, remaintime, remaincharges, stackcount, recalculatemask, &damage[0]);
- aura->ApplyForTargets();
- sLog->outInfo(LOG_FILTER_PLAYER, "Added aura spellid %u, effectmask %u", spellInfo->Id, effmask);
- }
- }
- while (result->NextRow());
- }
- }
- void Player::_LoadGlyphAuras()
- {
- for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
- {
- if (uint32 glyph = GetGlyph(i))
- {
- if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
- {
- if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
- {
- if (gp->TypeFlags == gs->TypeFlags)
- {
- CastSpell(this, gp->SpellId, true);
- continue;
- }
- else
- sLog->outError(LOG_FILTER_PLAYER, "Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
- }
- else
- sLog->outError(LOG_FILTER_PLAYER, "Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
- }
- else
- sLog->outError(LOG_FILTER_PLAYER, "Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
- // On any error remove glyph
- SetGlyph(i, 0);
- }
- }
- }
- void Player::LoadCorpse()
- {
- if (isAlive())
- sObjectAccessor->ConvertCorpseForPlayer(GetGUID());
- else
- {
- if (Corpse* corpse = GetCorpse())
- ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable());
- else
- //Prevent Dead Player login without corpse
- ResurrectPlayer(0.5f);
- }
- }
- void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff)
- {
- //QueryResult* result = CharacterDatabase.PQuery("SELECT data, text, bag, slot, item, item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag, slot", GetGUIDLow());
- //NOTE: the "order by `bag`" is important because it makes sure
- //the bagMap is filled before items in the bags are loaded
- //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
- //expected to be equipped before offhand items (TODO: fixme)
- if (result)
- {
- uint32 zoneId = GetZoneId();
- std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
- std::map<uint64, Item*> invalidBagMap; // fast guid lookup for bags
- std::list<Item*> problematicItems;
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- // Prevent items from being added to the queue while loading
- m_itemUpdateQueueBlocked = true;
- do
- {
- Field* fields = result->Fetch();
- if (Item* item = _LoadItem(trans, zoneId, timeDiff, fields))
- {
- uint32 bagGuid = fields[11].GetUInt32();
- uint8 slot = fields[12].GetUInt8();
- uint8 err = EQUIP_ERR_OK;
- // Item is not in bag
- if (!bagGuid)
- {
- item->SetContainer(NULL);
- item->SetSlot(slot);
- if (IsInventoryPos(INVENTORY_SLOT_BAG_0, slot))
- {
- ItemPosCountVec dest;
- err = CanStoreItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false);
- if (err == EQUIP_ERR_OK)
- item = StoreItem(dest, item, true);
- }
- else if (IsEquipmentPos(INVENTORY_SLOT_BAG_0, slot))
- {
- uint16 dest;
- err = CanEquipItem(slot, dest, item, false, false);
- if (err == EQUIP_ERR_OK)
- QuickEquipItem(dest, item);
- }
- else if (IsBankPos(INVENTORY_SLOT_BAG_0, slot))
- {
- ItemPosCountVec dest;
- err = CanBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false, false);
- if (err == EQUIP_ERR_OK)
- item = BankItem(dest, item, true);
- }
- // Remember bags that may contain items in them
- if (err == EQUIP_ERR_OK)
- {
- if (IsBagPos(item->GetPos()))
- if (Bag* pBag = item->ToBag())
- bagMap[item->GetGUIDLow()] = pBag;
- }
- else
- if (IsBagPos(item->GetPos()))
- if (item->IsBag())
- invalidBagMap[item->GetGUIDLow()] = item;
- }
- else
- {
- item->SetSlot(NULL_SLOT);
- // Item is in the bag, find the bag
- std::map<uint64, Bag*>::iterator itr = bagMap.find(bagGuid);
- if (itr != bagMap.end())
- {
- ItemPosCountVec dest;
- err = CanStoreItem(itr->second->GetSlot(), slot, dest, item);
- if (err == EQUIP_ERR_OK)
- item = StoreItem(dest, item, true);
- }
- else if (invalidBagMap.find(bagGuid) != invalidBagMap.end())
- {
- std::map<uint64, Item*>::iterator itr = invalidBagMap.find(bagGuid);
- if (std::find(problematicItems.begin(),problematicItems.end(),itr->second) != problematicItems.end())
- err = EQUIP_ERR_INT_BAG_ERROR;
- }
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which doesnt have a valid bag (Bag GUID: %u, slot: %u). Possible cheat?",
- GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot);
- item->DeleteFromInventoryDB(trans);
- delete item;
- continue;
- }
- }
- // Item's state may have changed after storing
- if (err == EQUIP_ERR_OK)
- item->SetState(ITEM_UNCHANGED, this);
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which can't be loaded into inventory (Bag GUID: %u, slot: %u) by reason %u. Item will be sent by mail.",
- GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot, err);
- item->DeleteFromInventoryDB(trans);
- problematicItems.push_back(item);
- }
- }
- } while (result->NextRow());
- m_itemUpdateQueueBlocked = false;
- // Send problematic items by mail
- while (!problematicItems.empty())
- {
- std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
- MailDraft draft(subject, "There were problems with equipping item(s).");
- for (uint8 i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
- {
- draft.AddItem(problematicItems.front());
- problematicItems.pop_front();
- }
- draft.SendMailTo(trans, this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
- }
- CharacterDatabase.CommitTransaction(trans);
- }
- //if (isAlive())
- _ApplyAllItemMods();
- }
- Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields)
- {
- PreparedStatement* stmt = NULL;
- Item* item = NULL;
- uint32 itemGuid = fields[13].GetUInt32();
- uint32 itemEntry = fields[14].GetUInt32();
- if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry))
- {
- bool remove = false;
- item = NewItemOrBag(proto);
- if (item->LoadFromDB(itemGuid, GetGUID(), fields, itemEntry))
- {
- // Do not allow to have item limited to another map/zone in alive state
- if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId))
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', map: %u) has item (GUID: %u, entry: %u) limited to another map (%u). Deleting item.",
- GetGUIDLow(), GetName(), GetMapId(), item->GetGUIDLow(), item->GetEntry(), zoneId);
- remove = true;
- }
- // "Conjured items disappear if you are logged out for more than 15 minutes"
- else if (timeDiff > 15 * MINUTE && proto->Flags & ITEM_PROTO_FLAG_CONJURED)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', diff: %u) has conjured item (GUID: %u, entry: %u) with expired lifetime (15 minutes). Deleting item.",
- GetGUIDLow(), GetName(), timeDiff, item->GetGUIDLow(), item->GetEntry());
- remove = true;
- }
- else if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
- {
- if (item->GetPlayedTime() > (2 * HOUR))
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with expired refund time (%u). Deleting refund data and removing refundable flag.",
- GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry(), item->GetPlayedTime());
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE);
- stmt->setUInt32(0, item->GetGUIDLow());
- trans->Append(stmt);
- item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
- }
- else
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_REFUNDS);
- stmt->setUInt32(0, item->GetGUIDLow());
- stmt->setUInt32(1, GetGUIDLow());
- if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
- {
- item->SetRefundRecipient((*result)[0].GetUInt32());
- item->SetPaidMoney((*result)[1].GetUInt32());
- item->SetPaidExtendedCost((*result)[2].GetUInt16());
- AddRefundReference(item->GetGUIDLow());
- }
- else
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with refundable flags, but without data in item_refund_instance. Removing flag.",
- GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry());
- item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
- }
- }
- }
- else if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE))
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_BOP_TRADE);
- stmt->setUInt32(0, item->GetGUIDLow());
- if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
- {
- std::string strGUID = (*result)[0].GetString();
- Tokens GUIDlist(strGUID, ' ');
- AllowedLooterSet looters;
- for (Tokens::iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr)
- looters.insert(atol(*itr));
- item->SetSoulboundTradeable(looters);
- AddTradeableItem(item);
- }
- else
- {
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with ITEM_FLAG_BOP_TRADEABLE flag, but without data in item_soulbound_trade_data. Removing flag.",
- GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry());
- item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE);
- }
- }
- else if (proto->HolidayId)
- {
- remove = true;
- GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap();
- GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr->GetActiveEventList();
- for (GameEventMgr::ActiveEvents::const_iterator itr = activeEventsList.begin(); itr != activeEventsList.end(); ++itr)
- {
- if (uint32(events[*itr].holiday_id) == proto->HolidayId)
- {
- remove = false;
- break;
- }
- }
- }
- }
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has broken item (GUID: %u, entry: %u) in inventory. Deleting item.",
- GetGUIDLow(), GetName(), itemGuid, itemEntry);
- remove = true;
- }
- // Remove item from inventory if necessary
- if (remove)
- {
- Item::DeleteFromInventoryDB(trans, itemGuid);
- item->FSetState(ITEM_REMOVED);
- item->SaveToDB(trans); // it also deletes item object!
- item = NULL;
- }
- }
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has unknown item (entry: %u) in inventory. Deleting item.",
- GetGUIDLow(), GetName(), itemEntry);
- Item::DeleteFromInventoryDB(trans, itemGuid);
- Item::DeleteFromDB(trans, itemGuid);
- }
- return item;
- }
- // load mailed item which should receive current player
- void Player::_LoadMailedItems(Mail* mail)
- {
- // data needs to be at first place for Item::LoadFromDB
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS);
- stmt->setUInt32(0, mail->messageID);
- PreparedQueryResult result = CharacterDatabase.Query(stmt);
- if (!result)
- return;
- do
- {
- Field* fields = result->Fetch();
- uint32 itemGuid = fields[11].GetUInt32();
- uint32 itemTemplate = fields[12].GetUInt32();
- mail->AddItem(itemGuid, itemTemplate);
- ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemTemplate);
- if (!proto)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), itemGuid, itemTemplate, mail->messageID);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM);
- stmt->setUInt32(0, itemGuid);
- CharacterDatabase.Execute(stmt);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
- stmt->setUInt32(0, itemGuid);
- CharacterDatabase.Execute(stmt);
- continue;
- }
- Item* item = NewItemOrBag(proto);
- if (!item->LoadFromDB(itemGuid, MAKE_NEW_GUID(fields[13].GetUInt32(), 0, HIGHGUID_PLAYER), fields, itemTemplate))
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, itemGuid);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
- stmt->setUInt32(0, itemGuid);
- CharacterDatabase.Execute(stmt);
- item->FSetState(ITEM_REMOVED);
- SQLTransaction temp = SQLTransaction(NULL);
- item->SaveToDB(temp); // it also deletes item object !
- continue;
- }
- AddMItem(item);
- }
- while (result->NextRow());
- }
- void Player::_LoadMailInit(PreparedQueryResult resultUnread, PreparedQueryResult resultDelivery)
- {
- //set a count of unread mails
- //QueryResult* resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid), (uint64)cTime);
- if (resultUnread)
- unReadMails = uint8((*resultUnread)[0].GetUInt64());
- // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
- //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
- if (resultDelivery)
- m_nextMailDelivereTime = time_t((*resultDelivery)[0].GetUInt32());
- }
- void Player::_LoadMail()
- {
- m_mail.clear();
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL);
- stmt->setUInt32(0, GetGUIDLow());
- PreparedQueryResult result = CharacterDatabase.Query(stmt);
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- Mail* m = new Mail;
- m->messageID = fields[0].GetUInt32();
- m->messageType = fields[1].GetUInt8();
- m->sender = fields[2].GetUInt32();
- m->receiver = fields[3].GetUInt32();
- m->subject = fields[4].GetString();
- m->body = fields[5].GetString();
- bool has_items = fields[6].GetBool();
- m->expire_time = time_t(fields[7].GetUInt32());
- m->deliver_time = time_t(fields[8].GetUInt32());
- m->money = fields[9].GetUInt32();
- m->COD = fields[10].GetUInt32();
- m->checked = fields[11].GetUInt8();
- m->stationery = fields[12].GetUInt8();
- m->mailTemplateId = fields[13].GetInt16();
- if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
- m->mailTemplateId = 0;
- }
- m->state = MAIL_STATE_UNCHANGED;
- if (has_items)
- _LoadMailedItems(m);
- m_mail.push_back(m);
- }
- while (result->NextRow());
- }
- m_mailsLoaded = true;
- }
- void Player::LoadPet()
- {
- //fixme: the pet should still be loaded if the player is not in world
- // just not added to the map
- if (IsInWorld())
- {
- Pet* pet = new Pet(this);
- if (!pet->LoadPetFromDB(this, 0, 0, true))
- delete pet;
- }
- }
- void Player::_LoadQuestStatus(PreparedQueryResult result)
- {
- uint16 slot = 0;
- //// 0 1 2 3 4 5 6 7 8 9 10
- //QueryResult* result = CharacterDatabase.PQuery("SELECT quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3,
- // 11 12
- // itemcount4, playercount FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint32 quest_id = fields[0].GetUInt32();
- // used to be new, no delete?
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (quest)
- {
- // find or create
- QuestStatusData& questStatusData = m_QuestStatus[quest_id];
- uint8 qstatus = fields[1].GetUInt8();
- if (qstatus < MAX_QUEST_STATUS)
- questStatusData.Status = QuestStatus(qstatus);
- else
- {
- questStatusData.Status = QUEST_STATUS_INCOMPLETE;
- sLog->outError(LOG_FILTER_PLAYER, "Player %s (GUID: %u) has invalid quest %d status (%u), replaced by QUEST_STATUS_INCOMPLETE(3).",
- GetName(), GetGUIDLow(), quest_id, qstatus);
- }
- questStatusData.Explored = (fields[2].GetUInt8() > 0);
- time_t quest_time = time_t(fields[3].GetUInt32());
- if (quest->HasFlag(QUEST_TRINITY_FLAGS_TIMED) && !GetQuestRewardStatus(quest_id))
- {
- AddTimedQuest(quest_id);
- if (quest_time <= sWorld->GetGameTime())
- questStatusData.Timer = 1;
- else
- questStatusData.Timer = uint32((quest_time - sWorld->GetGameTime()) * IN_MILLISECONDS);
- }
- else
- quest_time = 0;
- questStatusData.CreatureOrGOCount[0] = fields[4].GetUInt16();
- questStatusData.CreatureOrGOCount[1] = fields[5].GetUInt16();
- questStatusData.CreatureOrGOCount[2] = fields[6].GetUInt16();
- questStatusData.CreatureOrGOCount[3] = fields[7].GetUInt16();
- questStatusData.ItemCount[0] = fields[8].GetUInt16();
- questStatusData.ItemCount[1] = fields[9].GetUInt16();
- questStatusData.ItemCount[2] = fields[10].GetUInt16();
- questStatusData.ItemCount[3] = fields[11].GetUInt16();
- questStatusData.PlayerCount = fields[12].GetUInt16();
- // add to quest log
- if (slot < MAX_QUEST_LOG_SIZE && questStatusData.Status != QUEST_STATUS_NONE)
- {
- SetQuestSlot(slot, quest_id, uint32(quest_time)); // cast can't be helped
- if (questStatusData.Status == QUEST_STATUS_COMPLETE)
- SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
- else if (questStatusData.Status == QUEST_STATUS_FAILED)
- SetQuestSlotState(slot, QUEST_STATE_FAIL);
- for (uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
- if (questStatusData.CreatureOrGOCount[idx])
- SetQuestSlotCounter(slot, idx, questStatusData.CreatureOrGOCount[idx]);
- if (questStatusData.PlayerCount)
- SetQuestSlotCounter(slot, QUEST_PVP_KILL_SLOT, questStatusData.PlayerCount);
- ++slot;
- }
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.Status, quest_id, GetGUIDLow());
- }
- }
- while (result->NextRow());
- }
- // clear quest log tail
- for (uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i)
- SetQuestSlot(i, 0);
- }
- void Player::_LoadQuestStatusRewarded(PreparedQueryResult result)
- {
- // SELECT quest FROM character_queststatus_rewarded WHERE guid = ?
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint32 quest_id = fields[0].GetUInt32();
- // used to be new, no delete?
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (quest)
- {
- // learn rewarded spell if unknown
- learnQuestRewardedSpells(quest);
- // set rewarded title if any
- if (quest->GetCharTitleId())
- {
- if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(quest->GetCharTitleId()))
- SetTitle(titleEntry);
- }
- if (quest->GetBonusTalents())
- m_questRewardTalentCount += quest->GetBonusTalents();
- }
- m_RewardedQuests.insert(quest_id);
- }
- while (result->NextRow());
- }
- }
- void Player::_LoadDailyQuestStatus(PreparedQueryResult result)
- {
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, 0);
- m_DFQuests.clear();
- //QueryResult* result = CharacterDatabase.PQuery("SELECT quest, time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
- if (result)
- {
- uint32 quest_daily_idx = 0;
- do
- {
- Field* fields = result->Fetch();
- if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(fields[0].GetUInt32()))
- {
- if (qQuest->IsDFQuest())
- {
- m_DFQuests.insert(qQuest->GetQuestId());
- m_lastDailyQuestTime = time_t(fields[1].GetUInt32());
- continue;
- }
- }
- if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`", GetGUIDLow());
- break;
- }
- uint32 quest_id = fields[0].GetUInt32();
- // save _any_ from daily quest times (it must be after last reset anyway)
- m_lastDailyQuestTime = time_t(fields[1].GetUInt32());
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (!quest)
- continue;
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id);
- ++quest_daily_idx;
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Daily quest (%u) cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
- }
- while (result->NextRow());
- }
- m_DailyQuestChanged = false;
- }
- void Player::_LoadWeeklyQuestStatus(PreparedQueryResult result)
- {
- m_weeklyquests.clear();
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint32 quest_id = fields[0].GetUInt32();
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (!quest)
- continue;
- m_weeklyquests.insert(quest_id);
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
- }
- while (result->NextRow());
- }
- m_WeeklyQuestChanged = false;
- }
- void Player::_LoadSeasonalQuestStatus(PreparedQueryResult result)
- {
- m_seasonalquests.clear();
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint32 quest_id = fields[0].GetUInt32();
- uint32 event_id = fields[1].GetUInt32();
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (!quest)
- continue;
- m_seasonalquests[event_id].insert(quest_id);
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Seasonal quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
- }
- while (result->NextRow());
- }
- m_SeasonalQuestChanged = false;
- }
- void Player::_LoadSpells(PreparedQueryResult result)
- {
- //QueryResult* result = CharacterDatabase.PQuery("SELECT spell, active, disabled FROM character_spell WHERE guid = '%u'", GetGUIDLow());
- if (result)
- {
- do
- addSpell((*result)[0].GetUInt32(), (*result)[1].GetBool(), false, false, (*result)[2].GetBool(), true);
- while (result->NextRow());
- }
- }
- void Player::_LoadGroup(PreparedQueryResult result)
- {
- //QueryResult* result = CharacterDatabase.PQuery("SELECT guid FROM group_member WHERE memberGuid=%u", GetGUIDLow());
- if (result)
- {
- if (Group* group = sGroupMgr->GetGroupByDbStoreId((*result)[0].GetUInt32()))
- {
- uint8 subgroup = group->GetMemberGroup(GetGUID());
- SetGroup(group, subgroup);
- if (getLevel() >= LEVELREQUIREMENT_HEROIC)
- {
- // the group leader may change the instance difficulty while the player is offline
- SetDungeonDifficulty(group->GetDungeonDifficulty());
- SetRaidDifficulty(group->GetRaidDifficulty());
- }
- }
- }
- }
- void Player::_LoadBoundInstances(PreparedQueryResult result)
- {
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- m_boundInstances[i].clear();
- Group* group = GetGroup();
- //QueryResult* result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- bool perm = fields[1].GetBool();
- uint32 mapId = fields[2].GetUInt16();
- uint32 instanceId = fields[0].GetUInt32();
- uint8 difficulty = fields[3].GetUInt8();
- time_t resetTime = time_t(fields[4].GetUInt32());
- // the resettime for normal instances is only saved when the InstanceSave is unloaded
- // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
- // and in that case it is not used
- bool deleteInstance = false;
- MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
- if (!mapEntry || !mapEntry->IsDungeon())
- {
- sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
- deleteInstance = true;
- }
- else if (difficulty >= MAX_DIFFICULTY)
- {
- sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
- deleteInstance = true;
- }
- else
- {
- MapDifficulty const* mapDiff = GetMapDifficultyData(mapId, Difficulty(difficulty));
- if (!mapDiff)
- {
- sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
- deleteInstance = true;
- }
- else if (!perm && group)
- {
- sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d, %d, %d", GetName(), GetGUIDLow(), GUID_LOPART(group->GetGUID()), mapId, instanceId, difficulty);
- deleteInstance = true;
- }
- }
- if (deleteInstance)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, instanceId);
- CharacterDatabase.Execute(stmt);
- continue;
- }
- // since non permanent binds are always solo bind, they can always be reset
- if (InstanceSave* save = sInstanceSaveMgr->AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true))
- BindToInstance(save, perm, true);
- }
- while (result->NextRow());
- }
- }
- InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
- {
- // some instances only have one difficulty
- MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(mapid, difficulty);
- if (!mapDiff)
- return NULL;
- BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
- if (itr != m_boundInstances[difficulty].end())
- return &itr->second;
- else
- return NULL;
- }
- InstanceSave* Player::GetInstanceSave(uint32 mapid, bool raid)
- {
- InstancePlayerBind* pBind = GetBoundInstance(mapid, GetDifficulty(raid));
- InstanceSave* pSave = pBind ? pBind->save : NULL;
- if (!pBind || !pBind->perm)
- if (Group* group = GetGroup())
- if (InstanceGroupBind* groupBind = group->GetBoundInstance(this))
- pSave = groupBind->save;
- return pSave;
- }
- void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
- {
- BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
- UnbindInstance(itr, difficulty, unload);
- }
- void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
- {
- if (itr != m_boundInstances[difficulty].end())
- {
- if (!unload)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, itr->second.save->GetInstanceId());
- CharacterDatabase.Execute(stmt);
- }
- if (itr->second.perm)
- GetSession()->SendCalendarRaidLockout(itr->second.save, false);
- itr->second.save->RemovePlayer(this); // save can become invalid
- m_boundInstances[difficulty].erase(itr++);
- }
- }
- InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, bool load)
- {
- if (save)
- {
- InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
- if (bind.save)
- {
- // update the save when the group kills a boss
- if (permanent != bind.perm || save != bind.save)
- if (!load)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE);
- stmt->setUInt32(0, save->GetInstanceId());
- stmt->setBool(1, permanent);
- stmt->setUInt32(2, GetGUIDLow());
- stmt->setUInt32(3, bind.save->GetInstanceId());
- CharacterDatabase.Execute(stmt);
- }
- }
- else
- if (!load)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, save->GetInstanceId());
- stmt->setBool(2, permanent);
- CharacterDatabase.Execute(stmt);
- }
- if (bind.save != save)
- {
- if (bind.save)
- bind.save->RemovePlayer(this);
- save->AddPlayer(this);
- }
- if (permanent)
- save->SetCanReset(false);
- bind.save = save;
- bind.perm = permanent;
- if (!load)
- sLog->outDebug(LOG_FILTER_MAPS, "Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty());
- sScriptMgr->OnPlayerBindToInstance(this, save->GetDifficulty(), save->GetMapId(), permanent);
- return &bind;
- }
- else
- return NULL;
- }
- void Player::BindToInstance()
- {
- InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(_pendingBindId);
- if (!mapSave) //it seems sometimes mapSave is NULL, but I did not check why
- return;
- WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
- data << uint32(0);
- GetSession()->SendPacket(&data);
- BindToInstance(mapSave, true);
- GetSession()->SendCalendarRaidLockout(mapSave, true);
- }
- void Player::SendRaidInfo()
- {
- uint32 counter = 0;
- WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
- size_t p_counter = data.wpos();
- data << uint32(counter); // placeholder
- time_t now = time(NULL);
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- {
- if (itr->second.perm)
- {
- InstanceSave* save = itr->second.save;
- data << uint32(save->GetMapId()); // map id
- data << uint32(save->GetDifficulty()); // difficulty
- data << uint64(save->GetInstanceId()); // instance id
- data << uint8(1); // expired = 0
- data << uint8(0); // extended = 1
- data << uint32(save->GetResetTime() - now); // reset time
- ++counter;
- }
- }
- }
- data.put<uint32>(p_counter, counter);
- GetSession()->SendPacket(&data);
- }
- /*
- - called on every successful teleportation to a map
- */
- void Player::SendSavedInstances()
- {
- bool hasBeenSaved = false;
- WorldPacket data;
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- {
- if (itr->second.perm) // only permanent binds are sent
- {
- hasBeenSaved = true;
- break;
- }
- }
- }
- //Send opcode 811. true or false means, whether you have current raid/heroic instances
- data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
- data << uint32(hasBeenSaved);
- GetSession()->SendPacket(&data);
- if (!hasBeenSaved)
- return;
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- {
- if (itr->second.perm)
- {
- data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
- data << uint32(itr->second.save->GetMapId());
- GetSession()->SendPacket(&data);
- }
- }
- }
- }
- /// convert the player's binds to the group
- void Player::ConvertInstancesToGroup(Player* player, Group* group, bool switchLeader)
- {
- // copy all binds to the group, when changing leader it's assumed the character
- // will not have any solo binds
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
- {
- group->BindToInstance(itr->second.save, itr->second.perm, false);
- // permanent binds are not removed
- if (switchLeader && !itr->second.perm)
- {
- // increments itr in call
- player->UnbindInstance(itr, Difficulty(i), false);
- }
- else
- ++itr;
- }
- }
- }
- bool Player::Satisfy(AccessRequirement const* ar, uint32 target_map, bool report)
- {
- if (!isGameMaster() && ar)
- {
- uint8 LevelMin = 0;
- uint8 LevelMax = 0;
- MapEntry const* mapEntry = sMapStore.LookupEntry(target_map);
- if (!mapEntry)
- return false;
- if (!sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_LEVEL))
- {
- if (ar->levelMin && getLevel() < ar->levelMin)
- LevelMin = ar->levelMin;
- if (ar->levelMax && getLevel() > ar->levelMax)
- LevelMax = ar->levelMax;
- }
- uint32 missingItem = 0;
- if (ar->item)
- {
- if (!HasItemCount(ar->item, 1) &&
- (!ar->item2 || !HasItemCount(ar->item2, 1)))
- missingItem = ar->item;
- }
- else if (ar->item2 && !HasItemCount(ar->item2, 1))
- missingItem = ar->item2;
- if (DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, target_map, this))
- {
- GetSession()->SendAreaTriggerMessage("%s", GetSession()->GetTrinityString(LANG_INSTANCE_CLOSED));
- return false;
- }
- uint32 missingQuest = 0;
- if (GetTeam() == ALLIANCE && ar->quest_A && !GetQuestRewardStatus(ar->quest_A))
- missingQuest = ar->quest_A;
- else if (GetTeam() == HORDE && ar->quest_H && !GetQuestRewardStatus(ar->quest_H))
- missingQuest = ar->quest_H;
- uint32 missingAchievement = 0;
- Player* leader = this;
- uint64 leaderGuid = GetGroup() ? GetGroup()->GetLeaderGUID() : GetGUID();
- if (leaderGuid != GetGUID())
- leader = ObjectAccessor::FindPlayer(leaderGuid);
- if (ar->achievement)
- if (!leader || !leader->GetAchievementMgr().HasAchieved(ar->achievement))
- missingAchievement = ar->achievement;
- Difficulty target_difficulty = GetDifficulty(mapEntry->IsRaid());
- MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(target_map, target_difficulty);
- if (LevelMin || LevelMax || missingItem || missingQuest || missingAchievement)
- {
- if (report)
- {
- if (missingQuest && !ar->questFailedText.empty())
- ChatHandler(GetSession()).PSendSysMessage("%s", ar->questFailedText.c_str());
- else if (mapDiff->hasErrorMessage) // if (missingAchievement) covered by this case
- SendTransferAborted(target_map, TRANSFER_ABORT_DIFFICULTY, target_difficulty);
- else if (missingItem)
- GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED_AND_ITEM), LevelMin, sObjectMgr->GetItemTemplate(missingItem)->Name1.c_str());
- else if (LevelMin)
- GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED), LevelMin);
- }
- return false;
- }
- }
- return true;
- }
- bool Player::CheckInstanceLoginValid()
- {
- if (!GetMap())
- return false;
- if (!GetMap()->IsDungeon() || isGameMaster())
- return true;
- if (GetMap()->IsRaid())
- {
- // cannot be in raid instance without a group
- if (!GetGroup())
- return false;
- }
- else
- {
- // cannot be in normal instance without a group and more players than 1 in instance
- if (!GetGroup() && GetMap()->GetPlayersCountExceptGMs() > 1)
- return false;
- }
- // do checks for satisfy accessreqs, instance full, encounter in progress (raid), perm bind group != perm bind player
- return sMapMgr->CanPlayerEnter(GetMap()->GetId(), this, true);
- }
- bool Player::_LoadHomeBind(PreparedQueryResult result)
- {
- PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
- if (!info)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player (Name %s) has incorrect race/class pair. Can't be loaded.", GetName());
- return false;
- }
- bool ok = false;
- // SELECT mapId, zoneId, posX, posY, posZ FROM character_homebind WHERE guid = ?
- if (result)
- {
- Field* fields = result->Fetch();
- m_homebindMapId = fields[0].GetUInt16();
- m_homebindAreaId = fields[1].GetUInt16();
- m_homebindX = fields[2].GetFloat();
- m_homebindY = fields[3].GetFloat();
- m_homebindZ = fields[4].GetFloat();
- MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
- // accept saved data only for valid position (and non instanceable), and accessable
- if (MapManager::IsValidMapCoord(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ) &&
- !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
- ok = true;
- else
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
- stmt->setUInt32(0, GetGUIDLow());
- CharacterDatabase.Execute(stmt);
- }
- }
- if (!ok)
- {
- m_homebindMapId = info->mapId;
- m_homebindAreaId = info->areaId;
- m_homebindX = info->positionX;
- m_homebindY = info->positionY;
- m_homebindZ = info->positionZ;
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt16(1, m_homebindMapId);
- stmt->setUInt16(2, m_homebindAreaId);
- stmt->setFloat (3, m_homebindX);
- stmt->setFloat (4, m_homebindY);
- stmt->setFloat (5, m_homebindZ);
- CharacterDatabase.Execute(stmt);
- }
- sLog->outDebug(LOG_FILTER_PLAYER, "Setting player home position - mapid: %u, areaid: %u, X: %f, Y: %f, Z: %f",
- m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
- return true;
- }
- /*********************************************************/
- /*** SAVE SYSTEM ***/
- /*********************************************************/
- void Player::SaveToDB(bool create /*=false*/)
- {
- // delay auto save at any saves (manual, in code, or autosave)
- m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE);
- //lets allow only players in world to be saved
- if (IsBeingTeleportedFar())
- {
- ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
- return;
- }
- // first save/honor gain after midnight will also update the player's honor fields
- UpdateHonorFields();
- sLog->outDebug(LOG_FILTER_UNITS, "The value of player %s at save: ", m_name.c_str());
- outDebugValues();
- PreparedStatement* stmt = NULL;
- uint8 index = 0;
- if (create)
- {
- //! Insert query
- //! TO DO: Filter out more redundant fields that can take their default value at player create
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER);
- stmt->setUInt32(index++, GetGUIDLow());
- stmt->setUInt32(index++, GetSession()->GetAccountId());
- stmt->setString(index++, GetName());
- stmt->setUInt8(index++, getRace());
- stmt->setUInt8(index++, getClass());
- stmt->setUInt8(index++, getGender());
- stmt->setUInt8(index++, getLevel());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_XP));
- stmt->setUInt32(index++, GetMoney());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES_2));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FLAGS));
- stmt->setUInt16(index++, (uint16)GetMapId());
- stmt->setUInt32(index++, (uint32)GetInstanceId());
- stmt->setUInt8(index++, (uint8(GetDungeonDifficulty()) | uint8(GetRaidDifficulty()) << 4));
- stmt->setFloat(index++, finiteAlways(GetPositionX()));
- stmt->setFloat(index++, finiteAlways(GetPositionY()));
- stmt->setFloat(index++, finiteAlways(GetPositionZ()));
- stmt->setFloat(index++, finiteAlways(GetOrientation()));
- std::ostringstream ss;
- ss << m_taxi;
- stmt->setString(index++, ss.str());
- stmt->setUInt8(index++, m_cinematic);
- stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]);
- stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]);
- stmt->setFloat(index++, finiteAlways(m_rest_bonus));
- stmt->setUInt32(index++, uint32(time(NULL)));
- stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
- //save, far from tavern/city
- //save, but in tavern/city
- stmt->setUInt32(index++, m_resetTalentsCost);
- stmt->setUInt32(index++, uint32(m_resetTalentsTime));
- stmt->setUInt16(index++, (uint16)m_ExtraFlags);
- stmt->setUInt8(index++, m_stableSlots);
- stmt->setUInt16(index++, (uint16)m_atLoginFlags);
- stmt->setUInt16(index++, GetZoneId());
- stmt->setUInt32(index++, uint32(m_deathExpireTime));
- ss.str("");
- ss << m_taxi.SaveTaxiDestinationsToString();
- stmt->setString(index++, ss.str());
- stmt->setUInt32(index++, GetArenaPoints());
- stmt->setUInt32(index++, GetHonorPoints());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));
- stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 0));
- stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 1));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_CHOSEN_TITLE));
- stmt->setUInt64(index++, GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
- stmt->setUInt8(index++, GetDrunkValue());
- stmt->setUInt32(index++, GetHealth());
- for (uint32 i = 0; i < MAX_POWERS; ++i)
- stmt->setUInt32(index++, GetPower(Powers(i)));
- stmt->setUInt32(index++, GetSession()->GetLatency());
- stmt->setUInt8(index++, m_specsCount);
- stmt->setUInt8(index++, m_activeSpec);
- ss.str("");
- for (uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i)
- ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << ' ';
- stmt->setString(index++, ss.str());
- ss.str("");
- // cache equipment...
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i)
- ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << ' ';
- // ...and bags for enum opcode
- for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- ss << item->GetEntry();
- else
- ss << '0';
- ss << " 0 ";
- }
- stmt->setString(index++, ss.str());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_AMMO_ID));
- ss.str("");
- for (uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i)
- ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' ';
- stmt->setString(index++, ss.str());
- stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, 2));
- stmt->setUInt32(index++, m_grantableLevels);
- }
- else
- {
- // Update query
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER);
- stmt->setString(index++, GetName());
- stmt->setUInt8(index++, getRace());
- stmt->setUInt8(index++, getClass());
- stmt->setUInt8(index++, getGender());
- stmt->setUInt8(index++, getLevel());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_XP));
- stmt->setUInt32(index++, GetMoney());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES_2));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FLAGS));
- if (!IsBeingTeleported())
- {
- stmt->setUInt16(index++, (uint16)GetMapId());
- stmt->setUInt32(index++, (uint32)GetInstanceId());
- stmt->setUInt8(index++, (uint8(GetDungeonDifficulty()) | uint8(GetRaidDifficulty()) << 4));
- stmt->setFloat(index++, finiteAlways(GetPositionX()));
- stmt->setFloat(index++, finiteAlways(GetPositionY()));
- stmt->setFloat(index++, finiteAlways(GetPositionZ()));
- stmt->setFloat(index++, finiteAlways(GetOrientation()));
- }
- else
- {
- stmt->setUInt16(index++, (uint16)GetTeleportDest().GetMapId());
- stmt->setUInt32(index++, (uint32)0);
- stmt->setUInt8(index++, (uint8(GetDungeonDifficulty()) | uint8(GetRaidDifficulty()) << 4));
- stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionX()));
- stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionY()));
- stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionZ()));
- stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetOrientation()));
- }
- std::ostringstream ss;
- ss << m_taxi;
- stmt->setString(index++, ss.str());
- stmt->setUInt8(index++, m_cinematic);
- stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]);
- stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]);
- stmt->setFloat(index++, finiteAlways(m_rest_bonus));
- stmt->setUInt32(index++, uint32(time(NULL)));
- stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
- //save, far from tavern/city
- //save, but in tavern/city
- stmt->setUInt32(index++, m_resetTalentsCost);
- stmt->setUInt32(index++, uint32(m_resetTalentsTime));
- stmt->setUInt16(index++, (uint16)m_ExtraFlags);
- stmt->setUInt8(index++, m_stableSlots);
- stmt->setUInt16(index++, (uint16)m_atLoginFlags);
- stmt->setUInt16(index++, GetZoneId());
- stmt->setUInt32(index++, uint32(m_deathExpireTime));
- ss.str("");
- ss << m_taxi.SaveTaxiDestinationsToString();
- stmt->setString(index++, ss.str());
- stmt->setUInt32(index++, GetArenaPoints());
- stmt->setUInt32(index++, GetHonorPoints());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));
- stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 0));
- stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 1));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_CHOSEN_TITLE));
- stmt->setUInt64(index++, GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES));
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
- stmt->setUInt8(index++, GetDrunkValue());
- stmt->setUInt32(index++, GetHealth());
- for (uint32 i = 0; i < MAX_POWERS; ++i)
- stmt->setUInt32(index++, GetPower(Powers(i)));
- stmt->setUInt32(index++, GetSession()->GetLatency());
- stmt->setUInt8(index++, m_specsCount);
- stmt->setUInt8(index++, m_activeSpec);
- ss.str("");
- for (uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i)
- ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << ' ';
- stmt->setString(index++, ss.str());
- ss.str("");
- // cache equipment...
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i)
- ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << ' ';
- // ...and bags for enum opcode
- for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- ss << item->GetEntry();
- else
- ss << '0';
- ss << " 0 ";
- }
- stmt->setString(index++, ss.str());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_AMMO_ID));
- ss.str("");
- for (uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i)
- ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' ';
- stmt->setString(index++, ss.str());
- stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, 2));
- stmt->setUInt32(index++, m_grantableLevels);
- stmt->setUInt8(index++, IsInWorld() ? 1 : 0);
- // Index
- stmt->setUInt32(index++, GetGUIDLow());
- }
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- trans->Append(stmt);
- if (m_mailsUpdated) //save mails only when needed
- _SaveMail(trans);
- _SaveBGData(trans);
- _SaveInventory(trans);
- _SaveQuestStatus(trans);
- _SaveDailyQuestStatus(trans);
- _SaveWeeklyQuestStatus(trans);
- _SaveSeasonalQuestStatus(trans);
- _SaveTalents(trans);
- _SaveSpells(trans);
- _SaveSpellCooldowns(trans);
- _SaveActions(trans);
- _SaveAuras(trans);
- _SaveSkills(trans);
- m_achievementMgr.SaveToDB(trans);
- m_reputationMgr.SaveToDB(trans);
- _SaveEquipmentSets(trans);
- GetSession()->SaveTutorialsData(trans); // changed only while character in game
- _SaveGlyphs(trans);
- _SaveInstanceTimeRestrictions(trans);
- // check if stats should only be saved on logout
- // save stats can be out of transaction
- if (m_session->isLogingOut() || !sWorld->getBoolConfig(CONFIG_STATS_SAVE_ONLY_ON_LOGOUT))
- _SaveStats(trans);
- CharacterDatabase.CommitTransaction(trans);
- /* World of Warcraft Armory */
- // Place this code AFTER CharacterDatabase.CommitTransaction(); to avoid some character saving errors.
- // Wowarmory feeds
- if (sWorld->getBoolConfig(CONFIG_ARMORY_ENABLE))
- {
- std::ostringstream sWowarmory;
- for (WowarmoryFeeds::iterator iter = m_wowarmory_feeds.begin(); iter < m_wowarmory_feeds.end(); ++iter) {
- sWowarmory << "INSERT IGNORE INTO character_feed_log (guid,type,data,date,counter,difficulty,item_guid,item_quality) VALUES ";
- // guid type data date counter difficulty item_guid item_quality
- sWowarmory << "(" << (*iter).guid << ", " << (*iter).type << ", " << (*iter).data << ", " << uint64((*iter).date) << ", " << (*iter).counter << ", " << uint32((*iter).difficulty) << ", " << (*iter).item_guid << ", " << (*iter).item_quality << ");";
- CharacterDatabase.PExecute(sWowarmory.str().c_str());
- sWowarmory.str("");
- }
- // Clear old saved feeds from storage - they are not required for server core.
- InitWowarmoryFeeds();
- // Character stats
- std::ostringstream ps;
- time_t t = time(NULL);
- CharacterDatabase.PExecute("DELETE FROM armory_character_stats WHERE guid = %u", GetGUIDLow());
- ps << "INSERT INTO armory_character_stats (guid, data, save_date) VALUES (" << GetGUIDLow() << ", '";
- for (uint16 i = 0; i < m_valuesCount; ++i)
- ps << GetUInt32Value(i) << " ";
- ps << "', " << uint64(t) << ");";
- CharacterDatabase.PExecute(ps.str().c_str());
- }
- /* World of Warcraft Armory */
- // save pet (hunter pet level and experience and all type pets health/mana).
- if (Pet* pet = GetPet())
- pet->SavePetToDB(PET_SAVE_AS_CURRENT);
- }
- // fast save function for item/money cheating preventing - save only inventory and money state
- void Player::SaveInventoryAndGoldToDB(SQLTransaction& trans)
- {
- _SaveInventory(trans);
- SaveGoldToDB(trans);
- }
- void Player::SaveGoldToDB(SQLTransaction& trans)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY);
- stmt->setUInt32(0, GetMoney());
- stmt->setUInt32(1, GetGUIDLow());
- trans->Append(stmt);
- }
- void Player::_SaveActions(SQLTransaction& trans)
- {
- PreparedStatement* stmt = NULL;
- for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();)
- {
- switch (itr->second.uState)
- {
- case ACTIONBUTTON_NEW:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt8(1, m_activeSpec);
- stmt->setUInt8(2, itr->first);
- stmt->setUInt32(3, itr->second.GetAction());
- stmt->setUInt8(4, uint8(itr->second.GetType()));
- trans->Append(stmt);
- itr->second.uState = ACTIONBUTTON_UNCHANGED;
- ++itr;
- break;
- case ACTIONBUTTON_CHANGED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ACTION);
- stmt->setUInt32(0, itr->second.GetAction());
- stmt->setUInt8(1, uint8(itr->second.GetType()));
- stmt->setUInt32(2, GetGUIDLow());
- stmt->setUInt8(3, itr->first);
- stmt->setUInt8(4, m_activeSpec);
- trans->Append(stmt);
- itr->second.uState = ACTIONBUTTON_UNCHANGED;
- ++itr;
- break;
- case ACTIONBUTTON_DELETED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt8(1, itr->first);
- stmt->setUInt8(2, m_activeSpec);
- trans->Append(stmt);
- m_actionButtons.erase(itr++);
- break;
- default:
- ++itr;
- break;
- }
- }
- }
- void Player::_SaveAuras(SQLTransaction& trans)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- for (AuraMap::const_iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end(); ++itr)
- {
- if (!itr->second->CanBeSaved())
- continue;
- Aura* aura = itr->second;
- int32 damage[MAX_SPELL_EFFECTS];
- int32 baseDamage[MAX_SPELL_EFFECTS];
- uint8 effMask = 0;
- uint8 recalculateMask = 0;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (AuraEffect const* effect = aura->GetEffect(i))
- {
- baseDamage[i] = effect->GetBaseAmount();
- damage[i] = effect->GetAmount();
- effMask |= 1 << i;
- if (effect->CanBeRecalculated())
- recalculateMask |= 1 << i;
- }
- else
- {
- baseDamage[i] = 0;
- damage[i] = 0;
- }
- }
- uint8 index = 0;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA);
- stmt->setUInt32(index++, GetGUIDLow());
- stmt->setUInt64(index++, itr->second->GetCasterGUID());
- stmt->setUInt64(index++, itr->second->GetCastItemGUID());
- stmt->setUInt32(index++, itr->second->GetId());
- stmt->setUInt8(index++, effMask);
- stmt->setUInt8(index++, recalculateMask);
- stmt->setUInt8(index++, itr->second->GetStackAmount());
- stmt->setInt32(index++, damage[0]);
- stmt->setInt32(index++, damage[1]);
- stmt->setInt32(index++, damage[2]);
- stmt->setInt32(index++, baseDamage[0]);
- stmt->setInt32(index++, baseDamage[1]);
- stmt->setInt32(index++, baseDamage[2]);
- stmt->setInt32(index++, itr->second->GetMaxDuration());
- stmt->setInt32(index++, itr->second->GetDuration());
- stmt->setUInt8(index, itr->second->GetCharges());
- trans->Append(stmt);
- }
- }
- void Player::_SaveInventory(SQLTransaction& trans)
- {
- PreparedStatement* stmt = NULL;
- // force items in buyback slots to new state
- // and remove those that aren't already
- for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
- {
- Item* item = m_items[i];
- if (!item || item->GetState() == ITEM_NEW)
- continue;
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM);
- stmt->setUInt32(0, item->GetGUIDLow());
- trans->Append(stmt);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
- stmt->setUInt32(0, item->GetGUIDLow());
- trans->Append(stmt);
- m_items[i]->FSetState(ITEM_NEW);
- }
- // Updated played time for refundable items. We don't do this in Player::Update because there's simply no need for it,
- // the client auto counts down in real time after having received the initial played time on the first
- // SMSG_ITEM_REFUND_INFO_RESPONSE packet.
- // Item::UpdatePlayedTime is only called when needed, which is in DB saves, and item refund info requests.
- std::set<uint32>::iterator i_next;
- for (std::set<uint32>::iterator itr = m_refundableItems.begin(); itr!= m_refundableItems.end(); itr = i_next)
- {
- // use copy iterator because itr may be invalid after operations in this loop
- i_next = itr;
- ++i_next;
- Item* iPtr = GetItemByGuid(MAKE_NEW_GUID(*itr, 0, HIGHGUID_ITEM));
- if (iPtr)
- {
- iPtr->UpdatePlayedTime(this);
- continue;
- }
- else
- {
- sLog->outError(LOG_FILTER_PLAYER, "Can't find item guid %u but is in refundable storage for player %u ! Removing.", *itr, GetGUIDLow());
- m_refundableItems.erase(itr);
- }
- }
- // update enchantment durations
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
- itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration, this);
- // if no changes
- if (m_itemUpdateQueue.empty())
- return;
- uint32 lowGuid = GetGUIDLow();
- for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
- {
- Item* item = m_itemUpdateQueue[i];
- if (!item)
- continue;
- Bag* container = item->GetContainer();
- uint32 bag_guid = container ? container->GetGUIDLow() : 0;
- if (item->GetState() != ITEM_REMOVED)
- {
- Item* test = GetItemByPos(item->GetBagSlot(), item->GetSlot());
- if (test == NULL)
- {
- uint32 bagTestGUID = 0;
- if (Item* test2 = GetItemByPos(INVENTORY_SLOT_BAG_0, item->GetBagSlot()))
- bagTestGUID = test2->GetGUIDLow();
- sLog->outError(LOG_FILTER_PLAYER, "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u (state %d) are incorrect, the player doesn't have an item at that position!", lowGuid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), (int32)item->GetState());
- // according to the test that was just performed nothing should be in this slot, delete
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT);
- stmt->setUInt32(0, bagTestGUID);
- stmt->setUInt8(1, item->GetSlot());
- stmt->setUInt32(2, lowGuid);
- trans->Append(stmt);
- // also THIS item should be somewhere else, cheat attempt
- item->FSetState(ITEM_REMOVED); // we are IN updateQueue right now, can't use SetState which modifies the queue
- DeleteRefundReference(item->GetGUIDLow());
- // don't skip, let the switch delete it
- //continue;
- }
- else if (test != item)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u are incorrect, the item with guid %u is there instead!", lowGuid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
- // save all changes to the item...
- if (item->GetState() != ITEM_NEW) // only for existing items, no dupes
- item->SaveToDB(trans);
- // ...but do not save position in invntory
- continue;
- }
- }
- PreparedStatement* stmt = NULL;
- switch (item->GetState())
- {
- case ITEM_NEW:
- case ITEM_CHANGED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_INVENTORY_ITEM);
- stmt->setUInt32(0, lowGuid);
- stmt->setUInt32(1, bag_guid);
- stmt->setUInt8 (2, item->GetSlot());
- stmt->setUInt32(3, item->GetGUIDLow());
- trans->Append(stmt);
- break;
- case ITEM_REMOVED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM);
- stmt->setUInt32(0, item->GetGUIDLow());
- trans->Append(stmt);
- case ITEM_UNCHANGED:
- break;
- }
- item->SaveToDB(trans); // item have unchanged inventory record and can be save standalone
- }
- m_itemUpdateQueue.clear();
- }
- void Player::_SaveMail(SQLTransaction& trans)
- {
- if (!m_mailsLoaded)
- return;
- PreparedStatement* stmt = NULL;
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
- {
- Mail* m = (*itr);
- if (m->state == MAIL_STATE_CHANGED)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_MAIL);
- stmt->setUInt8(0, uint8(m->HasItems() ? 1 : 0));
- stmt->setUInt32(1, uint32(m->expire_time));
- stmt->setUInt32(2, uint32(m->deliver_time));
- stmt->setUInt32(3, m->money);
- stmt->setUInt32(4, m->COD);
- stmt->setUInt8(5, uint8(m->checked));
- stmt->setUInt32(6, m->messageID);
- trans->Append(stmt);
- if (!m->removedItems.empty())
- {
- for (std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
- stmt->setUInt32(0, *itr2);
- trans->Append(stmt);
- }
- m->removedItems.clear();
- }
- m->state = MAIL_STATE_UNCHANGED;
- }
- else if (m->state == MAIL_STATE_DELETED)
- {
- if (m->HasItems())
- {
- PreparedStatement* stmt = NULL;
- for (MailItemInfoVec::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
- stmt->setUInt32(0, itr2->item_guid);
- trans->Append(stmt);
- }
- }
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID);
- stmt->setUInt32(0, m->messageID);
- trans->Append(stmt);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
- stmt->setUInt32(0, m->messageID);
- trans->Append(stmt);
- }
- }
- //deallocate deleted mails...
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();)
- {
- if ((*itr)->state == MAIL_STATE_DELETED)
- {
- Mail* m = *itr;
- m_mail.erase(itr);
- delete m;
- itr = m_mail.begin();
- }
- else
- ++itr;
- }
- m_mailsUpdated = false;
- }
- void Player::_SaveQuestStatus(SQLTransaction& trans)
- {
- bool isTransaction = !trans.null();
- if (!isTransaction)
- trans = CharacterDatabase.BeginTransaction();
- QuestStatusSaveMap::iterator saveItr;
- QuestStatusMap::iterator statusItr;
- PreparedStatement* stmt = NULL;
- bool keepAbandoned = !(sWorld->GetCleaningFlags() & CharacterDatabaseCleaner::CLEANING_FLAG_QUESTSTATUS);
- for (saveItr = m_QuestStatusSave.begin(); saveItr != m_QuestStatusSave.end(); ++saveItr)
- {
- if (saveItr->second)
- {
- statusItr = m_QuestStatus.find(saveItr->first);
- if (statusItr != m_QuestStatus.end() && (keepAbandoned || statusItr->second.Status != QUEST_STATUS_NONE))
- {
- uint8 index = 0;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS);
- stmt->setUInt32(index++, GetGUIDLow());
- stmt->setUInt32(index++, statusItr->first);
- stmt->setUInt8(index++, uint8(statusItr->second.Status));
- stmt->setBool(index++, statusItr->second.Explored);
- stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS+ sWorld->GetGameTime()));
- for (uint8 i = 0; i < 4; i++)
- stmt->setUInt16(index++, statusItr->second.CreatureOrGOCount[i]);
- for (uint8 i = 0; i < 4; i++)
- stmt->setUInt16(index++, statusItr->second.ItemCount[i]);
- stmt->setUInt16(index, statusItr->second.PlayerCount);
- trans->Append(stmt);
- }
- }
- else
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, saveItr->first);
- trans->Append(stmt);
- }
- }
- m_QuestStatusSave.clear();
- for (saveItr = m_RewardedQuestsSave.begin(); saveItr != m_RewardedQuestsSave.end(); ++saveItr)
- {
- if (saveItr->second)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_QUESTSTATUS);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, saveItr->first);
- trans->Append(stmt);
- }
- else if (!keepAbandoned)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, saveItr->first);
- trans->Append(stmt);
- }
- }
- m_RewardedQuestsSave.clear();
- if (!isTransaction)
- CharacterDatabase.CommitTransaction(trans);
- }
- void Player::_SaveDailyQuestStatus(SQLTransaction& trans)
- {
- if (!m_DailyQuestChanged)
- return;
- m_DailyQuestChanged = false;
- // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
- // we don't need transactions here.
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- {
- if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx));
- stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
- trans->Append(stmt);
- }
- }
- if (!m_DFQuests.empty())
- {
- for (DFQuestsDoneList::iterator itr = m_DFQuests.begin(); itr != m_DFQuests.end(); ++itr)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, (*itr));
- stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
- trans->Append(stmt);
- }
- }
- }
- void Player::_SaveWeeklyQuestStatus(SQLTransaction& trans)
- {
- if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
- return;
- // we don't need transactions here.
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
- {
- uint32 quest_id = *iter;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, quest_id);
- trans->Append(stmt);
- }
- m_WeeklyQuestChanged = false;
- }
- void Player::_SaveSeasonalQuestStatus(SQLTransaction& trans)
- {
- if (!m_SeasonalQuestChanged || m_seasonalquests.empty())
- return;
- // we don't need transactions here.
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- for (SeasonalEventQuestMap::const_iterator iter = m_seasonalquests.begin(); iter != m_seasonalquests.end(); ++iter)
- {
- uint16 event_id = iter->first;
- for (SeasonalQuestSet::const_iterator itr = iter->second.begin(); itr != iter->second.end(); ++itr)
- {
- uint32 quest_id = (*itr);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, quest_id);
- stmt->setUInt32(2, event_id);
- trans->Append(stmt);
- }
- }
- m_SeasonalQuestChanged = false;
- }
- void Player::_SaveSkills(SQLTransaction& trans)
- {
- PreparedStatement* stmt = NULL;
- // we don't need transactions here.
- for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end();)
- {
- if (itr->second.uState == SKILL_UNCHANGED)
- {
- ++itr;
- continue;
- }
- if (itr->second.uState == SKILL_DELETED)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, itr->first);
- trans->Append(stmt);
- mSkillStatus.erase(itr++);
- continue;
- }
- uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
- uint16 value = SKILL_VALUE(valueData);
- uint16 max = SKILL_MAX(valueData);
- switch (itr->second.uState)
- {
- case SKILL_NEW:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILLS);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt16(1, uint16(itr->first));
- stmt->setUInt16(2, value);
- stmt->setUInt16(3, max);
- trans->Append(stmt);
- break;
- case SKILL_CHANGED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_SKILLS);
- stmt->setUInt16(0, value);
- stmt->setUInt16(1, max);
- stmt->setUInt32(2, GetGUIDLow());
- stmt->setUInt16(3, uint16(itr->first));
- trans->Append(stmt);
- break;
- default:
- break;
- }
- itr->second.uState = SKILL_UNCHANGED;
- ++itr;
- }
- }
- void Player::_SaveSpells(SQLTransaction& trans)
- {
- PreparedStatement* stmt = NULL;
- for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end();)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL);
- stmt->setUInt32(0, itr->first);
- stmt->setUInt32(1, GetGUIDLow());
- trans->Append(stmt);
- }
- // add only changed/new not dependent spells
- if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SPELL);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, itr->first);
- stmt->setBool(2, itr->second->active);
- stmt->setBool(3, itr->second->disabled);
- trans->Append(stmt);
- }
- if (itr->second->state == PLAYERSPELL_REMOVED)
- {
- delete itr->second;
- m_spells.erase(itr++);
- }
- else
- {
- itr->second->state = PLAYERSPELL_UNCHANGED;
- ++itr;
- }
- }
- }
- // save player stats -- only for external usage
- // real stats will be recalculated on player login
- void Player::_SaveStats(SQLTransaction& trans)
- {
- // check if stat saving is enabled and if char level is high enough
- if (!sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE))
- return;
- PreparedStatement* stmt = NULL;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- uint8 index = 0;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_STATS);
- stmt->setUInt32(index++, GetGUIDLow());
- stmt->setUInt32(index++, GetMaxHealth());
- for (uint8 i = 0; i < MAX_POWERS; ++i)
- stmt->setUInt32(index++, GetMaxPower(Powers(i)));
- for (uint8 i = 0; i < MAX_STATS; ++i)
- stmt->setUInt32(index++, GetStat(Stats(i)));
- for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
- stmt->setUInt32(index++, GetResistance(SpellSchools(i)));
- stmt->setFloat(index++, GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
- stmt->setFloat(index++, GetFloatValue(PLAYER_DODGE_PERCENTAGE));
- stmt->setFloat(index++, GetFloatValue(PLAYER_PARRY_PERCENTAGE));
- stmt->setFloat(index++, GetFloatValue(PLAYER_CRIT_PERCENTAGE));
- stmt->setFloat(index++, GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE));
- stmt->setFloat(index++, GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1));
- stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_ATTACK_POWER));
- stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER));
- stmt->setUInt32(index++, GetBaseSpellPowerBonus());
- stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_TAKEN_SPELL));
- trans->Append(stmt);
- }
- void Player::outDebugValues() const
- {
- if (!sLog->ShouldLog(LOG_FILTER_UNITS, LOG_LEVEL_DEBUG))
- return;
- sLog->outDebug(LOG_FILTER_UNITS, "HP is: \t\t\t%u\t\tMP is: \t\t\t%u", GetMaxHealth(), GetMaxPower(POWER_MANA));
- sLog->outDebug(LOG_FILTER_UNITS, "AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f", GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
- sLog->outDebug(LOG_FILTER_UNITS, "INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f", GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
- sLog->outDebug(LOG_FILTER_UNITS, "STAMINA is: \t\t%f", GetStat(STAT_STAMINA));
- sLog->outDebug(LOG_FILTER_UNITS, "Armor is: \t\t%u\t\tBlock is: \t\t%f", GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
- sLog->outDebug(LOG_FILTER_UNITS, "HolyRes is: \t\t%u\t\tFireRes is: \t\t%u", GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
- sLog->outDebug(LOG_FILTER_UNITS, "NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u", GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
- sLog->outDebug(LOG_FILTER_UNITS, "ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u", GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
- sLog->outDebug(LOG_FILTER_UNITS, "MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f", GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
- sLog->outDebug(LOG_FILTER_UNITS, "MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f", GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
- sLog->outDebug(LOG_FILTER_UNITS, "MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f", GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
- sLog->outDebug(LOG_FILTER_UNITS, "ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u", GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
- }
- /*********************************************************/
- /*** FLOOD FILTER SYSTEM ***/
- /*********************************************************/
- void Player::UpdateSpeakTime()
- {
- // ignore chat spam protection for GMs in any mode
- if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
- return;
- time_t current = time (NULL);
- if (m_speakTime > current)
- {
- uint32 max_count = sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
- if (!max_count)
- return;
- ++m_speakCount;
- if (m_speakCount >= max_count)
- {
- // prevent overwrite mute time, if message send just before mutes set, for example.
- time_t new_mute = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_MUTE_TIME);
- if (GetSession()->m_muteTime < new_mute)
- GetSession()->m_muteTime = new_mute;
- m_speakCount = 0;
- }
- }
- else
- m_speakCount = 0;
- m_speakTime = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
- }
- bool Player::CanSpeak() const
- {
- return GetSession()->m_muteTime <= time (NULL);
- }
- /*********************************************************/
- /*** LOW LEVEL FUNCTIONS:Notifiers ***/
- /*********************************************************/
- void Player::SendAttackSwingNotInRange()
- {
- WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
- GetSession()->SendPacket(&data);
- }
- void Player::SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, uint64 guid)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION);
- stmt->setFloat(0, x);
- stmt->setFloat(1, y);
- stmt->setFloat(2, z);
- stmt->setFloat(3, o);
- stmt->setUInt16(4, uint16(mapid));
- stmt->setUInt16(5, uint16(zone));
- stmt->setUInt32(6, GUID_LOPART(guid));
- CharacterDatabase.Execute(stmt);
- }
- void Player::SetUInt32ValueInArray(Tokens& tokens, uint16 index, uint32 value)
- {
- char buf[11];
- snprintf(buf, 11, "%u", value);
- if (index >= tokens.size())
- return;
- tokens[index] = buf;
- }
- void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PLAYERBYTES2);
- stmt->setUInt32(0, GUID_LOPART(guid));
- PreparedQueryResult result = CharacterDatabase.Query(stmt);
- if (!result)
- return;
- Field* fields = result->Fetch();
- uint32 playerBytes2 = fields[0].GetUInt32();
- playerBytes2 &= ~0xFF;
- playerBytes2 |= facialHair;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_PLAYERBYTES);
- stmt->setUInt8(0, gender);
- stmt->setUInt32(1, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24));
- stmt->setUInt32(2, playerBytes2);
- stmt->setUInt32(3, GUID_LOPART(guid));
- CharacterDatabase.Execute(stmt);
- }
- void Player::SendAttackSwingDeadTarget()
- {
- WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
- GetSession()->SendPacket(&data);
- }
- void Player::SendAttackSwingCantAttack()
- {
- WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
- GetSession()->SendPacket(&data);
- }
- void Player::SendAttackSwingCancelAttack()
- {
- WorldPacket data(SMSG_CANCEL_COMBAT, 0);
- GetSession()->SendPacket(&data);
- }
- void Player::SendAttackSwingBadFacingAttack()
- {
- WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
- GetSession()->SendPacket(&data);
- }
- void Player::SendAutoRepeatCancel(Unit* target)
- {
- WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
- data.append(target->GetPackGUID()); // may be it's target guid
- GetSession()->SendPacket(&data);
- }
- void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
- {
- WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8);
- data << uint32(Area);
- data << uint32(Experience);
- GetSession()->SendPacket(&data);
- }
- void Player::SendDungeonDifficulty(bool IsInGroup)
- {
- uint8 val = 0x00000001;
- WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
- data << (uint32)GetDungeonDifficulty();
- data << uint32(val);
- data << uint32(IsInGroup);
- GetSession()->SendPacket(&data);
- }
- void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty)
- {
- uint8 val = 0x00000001;
- WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
- data << uint32(forcedDifficulty == -1 ? GetRaidDifficulty() : forcedDifficulty);
- data << uint32(val);
- data << uint32(IsInGroup);
- GetSession()->SendPacket(&data);
- }
- void Player::SendResetFailedNotify(uint32 mapid)
- {
- WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
- data << uint32(mapid);
- GetSession()->SendPacket(&data);
- }
- /// Reset all solo instances and optionally send a message on success for each
- void Player::ResetInstances(uint8 method, bool isRaid)
- {
- // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
- // we assume that when the difficulty changes, all instances that can be reset will be
- Difficulty diff = GetDifficulty(isRaid);
- for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
- {
- InstanceSave* p = itr->second.save;
- const MapEntry* entry = sMapStore.LookupEntry(itr->first);
- if (!entry || entry->IsRaid() != isRaid || !p->CanReset())
- {
- ++itr;
- continue;
- }
- if (method == INSTANCE_RESET_ALL)
- {
- // the "reset all instances" method can only reset normal maps
- if (entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
- {
- ++itr;
- continue;
- }
- }
- // if the map is loaded, reset it
- Map* map = sMapMgr->FindMap(p->GetMapId(), p->GetInstanceId());
- if (map && map->IsDungeon())
- if (!((InstanceMap*)map)->Reset(method))
- {
- ++itr;
- continue;
- }
- // since this is a solo instance there should not be any players inside
- if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
- SendResetInstanceSuccess(p->GetMapId());
- p->DeleteFromDB();
- m_boundInstances[diff].erase(itr++);
- // the following should remove the instance save from the manager and delete it as well
- p->RemovePlayer(this);
- }
- }
- void Player::SendResetInstanceSuccess(uint32 MapId)
- {
- WorldPacket data(SMSG_INSTANCE_RESET, 4);
- data << uint32(MapId);
- GetSession()->SendPacket(&data);
- }
- void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
- {
- /*reasons for instance reset failure:
- // 0: There are players inside the instance.
- // 1: There are players offline in your party.
- // 2>: There are players in your party attempting to zone into an instance.
- */
- WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
- data << uint32(reason);
- data << uint32(MapId);
- GetSession()->SendPacket(&data);
- }
- /*********************************************************/
- /*** Update timers ***/
- /*********************************************************/
- ///checks the 15 afk reports per 5 minutes limit
- void Player::UpdateAfkReport(time_t currTime)
- {
- if (m_bgData.bgAfkReportedTimer <= currTime)
- {
- m_bgData.bgAfkReportedCount = 0;
- m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
- }
- }
- void Player::UpdateContestedPvP(uint32 diff)
- {
- if (!m_contestedPvPTimer||isInCombat())
- return;
- if (m_contestedPvPTimer <= diff)
- {
- ResetContestedPvP();
- }
- else
- m_contestedPvPTimer -= diff;
- }
- void Player::UpdatePvPFlag(time_t currTime)
- {
- if (!IsPvP())
- return;
- if (pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300) || pvpInfo.inHostileArea)
- return;
- UpdatePvP(false);
- }
- void Player::UpdateDuelFlag(time_t currTime)
- {
- if (!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
- return;
- sScriptMgr->OnPlayerDuelStart(this, duel->opponent);
- SetUInt32Value(PLAYER_DUEL_TEAM, 1);
- duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
- duel->startTimer = 0;
- duel->startTime = currTime;
- duel->opponent->duel->startTimer = 0;
- duel->opponent->duel->startTime = currTime;
- }
- Pet* Player::GetPet() const
- {
- if (uint64 pet_guid = GetPetGUID())
- {
- if (!IS_PET_GUID(pet_guid))
- return NULL;
- Pet* pet = ObjectAccessor::GetPet(*this, pet_guid);
- if (!pet)
- return NULL;
- if (IsInWorld() && pet)
- return pet;
- //there may be a guardian in slot
- //sLog->outError(LOG_FILTER_PLAYER, "Player::GetPet: Pet %u not exist.", GUID_LOPART(pet_guid));
- //const_cast<Player*>(this)->SetPetGUID(0);
- }
- return NULL;
- }
- void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
- {
- if (!pet)
- pet = GetPet();
- if (pet)
- {
- sLog->outDebug(LOG_FILTER_PETS, "RemovePet %u, %u, %u", pet->GetEntry(), mode, returnreagent);
- if (pet->m_removed)
- return;
- }
- if (returnreagent && (pet || m_temporaryUnsummonedPetNumber) && !InBattleground())
- {
- //returning of reagents only for players, so best done here
- uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
- if (spellInfo)
- {
- for (uint32 i = 0; i < MAX_SPELL_REAGENTS; ++i)
- {
- if (spellInfo->Reagent[i] > 0)
- {
- ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
- InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i]);
- if (msg == EQUIP_ERR_OK)
- {
- Item* item = StoreNewItem(dest, spellInfo->Reagent[i], true);
- if (IsInWorld())
- SendNewItem(item, spellInfo->ReagentCount[i], true, false);
- }
- }
- }
- }
- m_temporaryUnsummonedPetNumber = 0;
- }
- if (!pet || pet->GetOwnerGUID() != GetGUID())
- return;
- pet->CombatStop();
- if (returnreagent)
- {
- switch (pet->GetEntry())
- {
- //warlock pets except imp are removed(?) when logging out
- case 1860:
- case 1863:
- case 417:
- case 17252:
- mode = PET_SAVE_NOT_IN_SLOT;
- break;
- }
- }
- // only if current pet in slot
- pet->SavePetToDB(mode);
- SetMinion(pet, false);
- pet->AddObjectToRemoveList();
- pet->m_removed = true;
- if (pet->isControlled())
- {
- WorldPacket data(SMSG_PET_SPELLS, 8);
- data << uint64(0);
- GetSession()->SendPacket(&data);
- if (GetGroup())
- SetGroupUpdateFlag(GROUP_UPDATE_PET);
- }
- }
- void Player::StopCastingCharm()
- {
- Unit* charm = GetCharm();
- if (!charm)
- return;
- if (charm->GetTypeId() == TYPEID_UNIT)
- {
- if (charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET))
- ((Puppet*)charm)->UnSummon();
- else if (charm->IsVehicle())
- ExitVehicle();
- }
- if (GetCharmGUID())
- charm->RemoveCharmAuras();
- if (GetCharmGUID())
- {
- sLog->outFatal(LOG_FILTER_PLAYER, "Player %s (GUID: " UI64FMTD " is not able to uncharm unit (GUID: " UI64FMTD " Entry: %u, Type: %u)", GetName(), GetGUID(), GetCharmGUID(), charm->GetEntry(), charm->GetTypeId());
- if (charm->GetCharmerGUID())
- {
- sLog->outFatal(LOG_FILTER_PLAYER, "Charmed unit has charmer guid " UI64FMTD, charm->GetCharmerGUID());
- ASSERT(false);
- }
- else
- SetCharm(charm, false);
- }
- }
- inline void Player::BuildPlayerChat(WorldPacket* data, uint8 msgtype, const std::string& text, uint32 language) const
- {
- *data << uint8(msgtype);
- *data << uint32(language);
- *data << uint64(GetGUID());
- *data << uint32(0); // constant unknown time
- *data << uint64(GetGUID());
- *data << uint32(text.length() + 1);
- *data << text;
- *data << uint8(GetChatTag());
- }
- void Player::Say(const std::string& text, const uint32 language)
- {
- std::string _text(text);
- sScriptMgr->OnPlayerChat(this, CHAT_MSG_SAY, language, _text);
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_SAY, _text, language);
- SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);
- }
- void Player::Yell(const std::string& text, const uint32 language)
- {
- std::string _text(text);
- sScriptMgr->OnPlayerChat(this, CHAT_MSG_YELL, language, _text);
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_YELL, _text, language);
- SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), true);
- }
- void Player::TextEmote(const std::string& text)
- {
- std::string _text(text);
- sScriptMgr->OnPlayerChat(this, CHAT_MSG_EMOTE, LANG_UNIVERSAL, _text);
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_EMOTE, _text, LANG_UNIVERSAL);
- SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), true, !sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT));
- }
- void Player::Whisper(const std::string& text, uint32 language, uint64 receiver)
- {
- bool isAddonMessage = language == LANG_ADDON;
- if (!isAddonMessage) // if not addon data
- language = LANG_UNIVERSAL; // whispers should always be readable
- Player* rPlayer = ObjectAccessor::FindPlayer(receiver);
- std::string _text(text);
- sScriptMgr->OnPlayerChat(this, CHAT_MSG_WHISPER, language, _text, rPlayer);
- // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
- if (!rPlayer->isDND() || isGameMaster())
- {
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_WHISPER, _text, language);
- rPlayer->GetSession()->SendPacket(&data);
- // not send confirmation for addon messages
- if (!isAddonMessage)
- {
- data.Initialize(SMSG_MESSAGECHAT, 200);
- rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, _text, language);
- GetSession()->SendPacket(&data);
- }
- }
- else if (!isAddonMessage)
- // announce to player that player he is whispering to is dnd and cannot receive his message
- ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
- // rest stuff shouldn't happen in case of addon message
- if (isAddonMessage)
- return;
- if (!isAcceptWhispers() && !isGameMaster() && !rPlayer->isGameMaster())
- {
- SetAcceptWhispers(true);
- ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
- }
- // announce to player that player he is whispering to is afk
- if (rPlayer->isAFK())
- ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
- // if player whisper someone, auto turn of dnd to be able to receive an answer
- if (isDND() && !rPlayer->isGameMaster())
- ToggleDND();
- }
- void Player::PetSpellInitialize()
- {
- Pet* pet = GetPet();
- if (!pet)
- return;
- sLog->outDebug(LOG_FILTER_PETS, "Pet Spells Groups");
- CharmInfo* charmInfo = pet->GetCharmInfo();
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
- data << uint64(pet->GetGUID());
- data << uint16(pet->GetCreatureTemplate()->family); // creature family (required for pet talents)
- data << uint32(pet->GetDuration());
- data << uint8(pet->GetReactState());
- data << uint8(charmInfo->GetCommandState());
- data << uint16(0); // Flags, mostly unknown
- // action bar loop
- charmInfo->BuildActionBar(&data);
- size_t spellsCountPos = data.wpos();
- // spells count
- uint8 addlist = 0;
- data << uint8(addlist); // placeholder
- if (pet->IsPermanentPetFor(this))
- {
- // spells loop
- for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
- {
- if (itr->second.state == PETSPELL_REMOVED)
- continue;
- data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first, itr->second.active));
- ++addlist;
- }
- }
- data.put<uint8>(spellsCountPos, addlist);
- uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
- data << uint8(cooldownsCount);
- time_t curTime = time(NULL);
- for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
- {
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
- if (!spellInfo)
- {
- data << uint32(0);
- data << uint16(0);
- data << uint32(0);
- data << uint32(0);
- continue;
- }
- time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
- data << uint32(itr->first); // spell ID
- CreatureSpellCooldowns::const_iterator categoryitr = pet->m_CreatureCategoryCooldowns.find(spellInfo->Category);
- if (categoryitr != pet->m_CreatureCategoryCooldowns.end())
- {
- time_t categoryCooldown = (categoryitr->second > curTime) ? (categoryitr->second - curTime) * IN_MILLISECONDS : 0;
- data << uint16(spellInfo->Category); // spell category
- data << uint32(cooldown); // spell cooldown
- data << uint32(categoryCooldown); // category cooldown
- }
- else
- {
- data << uint16(0);
- data << uint32(cooldown);
- data << uint32(0);
- }
- }
- GetSession()->SendPacket(&data);
- }
- void Player::PossessSpellInitialize()
- {
- Unit* charm = GetCharm();
- if (!charm)
- return;
- CharmInfo* charmInfo = charm->GetCharmInfo();
- if (!charmInfo)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::PossessSpellInitialize(): charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
- return;
- }
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
- data << uint64(charm->GetGUID());
- data << uint16(0);
- data << uint32(0);
- data << uint32(0);
- charmInfo->BuildActionBar(&data);
- data << uint8(0); // spells count
- data << uint8(0); // cooldowns count
- GetSession()->SendPacket(&data);
- }
- void Player::VehicleSpellInitialize()
- {
- Creature* vehicle = GetVehicleCreatureBase();
- if (!vehicle)
- return;
- uint8 cooldownCount = vehicle->m_CreatureSpellCooldowns.size();
- WorldPacket data(SMSG_PET_SPELLS, 8 + 2 + 4 + 4 + 4 * 10 + 1 + 1 + cooldownCount * (4 + 2 + 4 + 4));
- data << uint64(vehicle->GetGUID()); // Guid
- data << uint16(0); // Pet Family (0 for all vehicles)
- data << uint32(vehicle->isSummon() ? vehicle->ToTempSummon()->GetTimer() : 0); // Duration
- // The following three segments are read by the client as one uint32
- data << uint8(vehicle->GetReactState()); // React State
- data << uint8(0); // Command State
- data << uint16(0x800); // DisableActions (set for all vehicles)
- for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
- {
- uint32 spellId = vehicle->m_spells[i];
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
- if (!spellInfo)
- {
- data << uint16(0) << uint8(0) << uint8(i+8);
- continue;
- }
- ConditionList conditions = sConditionMgr->GetConditionsForVehicleSpell(vehicle->GetEntry(), spellId);
- if (!sConditionMgr->IsObjectMeetToConditions(this, vehicle, conditions))
- {
- sLog->outDebug(LOG_FILTER_CONDITIONSYS, "VehicleSpellInitialize: conditions not met for Vehicle entry %u spell %u", vehicle->ToCreature()->GetEntry(), spellId);
- data << uint16(0) << uint8(0) << uint8(i+8);
- continue;
- }
- if (spellInfo->IsPassive())
- vehicle->CastSpell(vehicle, spellId, true);
- data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId, i+8));
- }
- for (uint32 i = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i)
- data << uint32(0);
- data << uint8(0); // Auras?
- // Cooldowns
- data << uint8(cooldownCount);
- time_t now = sWorld->GetGameTime();
- for (CreatureSpellCooldowns::const_iterator itr = vehicle->m_CreatureSpellCooldowns.begin(); itr != vehicle->m_CreatureSpellCooldowns.end(); ++itr)
- {
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
- if (!spellInfo)
- {
- data << uint32(0);
- data << uint16(0);
- data << uint32(0);
- data << uint32(0);
- continue;
- }
- time_t cooldown = (itr->second > now) ? (itr->second - now) * IN_MILLISECONDS : 0;
- data << uint32(itr->first); // spell ID
- CreatureSpellCooldowns::const_iterator categoryitr = vehicle->m_CreatureCategoryCooldowns.find(spellInfo->Category);
- if (categoryitr != vehicle->m_CreatureCategoryCooldowns.end())
- {
- time_t categoryCooldown = (categoryitr->second > now) ? (categoryitr->second - now) * IN_MILLISECONDS : 0;
- data << uint16(spellInfo->Category); // spell category
- data << uint32(cooldown); // spell cooldown
- data << uint32(categoryCooldown); // category cooldown
- }
- else
- {
- data << uint16(0);
- data << uint32(cooldown);
- data << uint32(0);
- }
- }
- GetSession()->SendPacket(&data);
- }
- void Player::CharmSpellInitialize()
- {
- Unit* charm = GetFirstControlled();
- if (!charm)
- return;
- CharmInfo* charmInfo = charm->GetCharmInfo();
- if (!charmInfo)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player::CharmSpellInitialize(): the player's charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
- return;
- }
- uint8 addlist = 0;
- if (charm->GetTypeId() != TYPEID_PLAYER)
- {
- //CreatureInfo const* cinfo = charm->ToCreature()->GetCreatureTemplate();
- //if (cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
- {
- for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
- if (charmInfo->GetCharmSpell(i)->GetAction())
- ++addlist;
- }
- }
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
- data << uint64(charm->GetGUID());
- data << uint16(0);
- data << uint32(0);
- if (charm->GetTypeId() != TYPEID_PLAYER)
- data << uint8(charm->ToCreature()->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
- else
- data << uint32(0);
- charmInfo->BuildActionBar(&data);
- data << uint8(addlist);
- if (addlist)
- {
- for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
- {
- CharmSpellInfo* cspell = charmInfo->GetCharmSpell(i);
- if (cspell->GetAction())
- data << uint32(cspell->packedData);
- }
- }
- data << uint8(0); // cooldowns count
- GetSession()->SendPacket(&data);
- }
- void Player::SendRemoveControlBar()
- {
- WorldPacket data(SMSG_PET_SPELLS, 8);
- data << uint64(0);
- GetSession()->SendPacket(&data);
- }
- bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell)
- {
- if (!mod || !spellInfo)
- return false;
- // Mod out of charges
- if (spell && mod->charges == -1 && spell->m_appliedMods.find(mod->ownerAura) == spell->m_appliedMods.end())
- return false;
- // +duration to infinite duration spells making them limited
- if (mod->op == SPELLMOD_DURATION && spellInfo->GetDuration() == -1)
- return false;
- return spellInfo->IsAffectedBySpellMod(mod);
- }
- void Player::AddSpellMod(SpellModifier* mod, bool apply)
- {
- sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Player::AddSpellMod %d", mod->spellId);
- uint16 Opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
- int i = 0;
- flag96 _mask = 0;
- for (int eff = 0; eff < 96; ++eff)
- {
- if (eff != 0 && eff%32 == 0)
- _mask[i++] = 0;
- _mask[i] = uint32(1) << (eff-(32*i));
- if (mod->mask & _mask)
- {
- int32 val = 0;
- for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
- {
- if ((*itr)->type == mod->type && (*itr)->mask & _mask)
- val += (*itr)->value;
- }
- val += apply ? mod->value : -(mod->value);
- WorldPacket data(Opcode, (1+1+4));
- data << uint8(eff);
- data << uint8(mod->op);
- data << int32(val);
- SendDirectMessage(&data);
- }
- }
- if (apply)
- m_spellMods[mod->op].push_back(mod);
- else
- {
- m_spellMods[mod->op].remove(mod);
- // mods bound to aura will be removed in AuraEffect::~AuraEffect
- if (!mod->ownerAura)
- delete mod;
- }
- }
- // Restore spellmods in case of failed cast
- void Player::RestoreSpellMods(Spell* spell, uint32 ownerAuraId, Aura* aura)
- {
- if (!spell || spell->m_appliedMods.empty())
- return;
- for (uint8 i=0; i<MAX_SPELLMOD; ++i)
- {
- for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end(); ++itr)
- {
- SpellModifier* mod = *itr;
- // spellmods without aura set cannot be charged
- if (!mod->ownerAura || !mod->ownerAura->IsUsingCharges())
- continue;
- // Restore only specific owner aura mods
- if (ownerAuraId && (ownerAuraId != mod->ownerAura->GetSpellInfo()->Id))
- continue;
- if (aura && mod->ownerAura != aura)
- continue;
- // check if mod affected this spell
- // first, check if the mod aura applied at least one spellmod to this spell
- Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
- if (iterMod == spell->m_appliedMods.end())
- continue;
- // secondly, check if the current mod is one of the spellmods applied by the mod aura
- if (!(mod->mask & spell->m_spellInfo->SpellFamilyFlags))
- continue;
- // remove from list
- spell->m_appliedMods.erase(iterMod);
- // add mod charges back to mod
- if (mod->charges == -1)
- mod->charges = 1;
- else
- mod->charges++;
- // Do not set more spellmods than avalible
- if (mod->ownerAura->GetCharges() < mod->charges)
- mod->charges = mod->ownerAura->GetCharges();
- // Skip this check for now - aura charges may change due to various reason
- // TODO: trac these changes correctly
- //ASSERT (mod->ownerAura->GetCharges() <= mod->charges);
- }
- }
- }
- void Player::RestoreAllSpellMods(uint32 ownerAuraId, Aura* aura)
- {
- for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
- if (m_currentSpells[i])
- RestoreSpellMods(m_currentSpells[i], ownerAuraId, aura);
- }
- void Player::RemoveSpellMods(Spell* spell)
- {
- if (!spell)
- return;
- if (spell->m_appliedMods.empty())
- return;
- for (uint8 i=0; i<MAX_SPELLMOD; ++i)
- {
- for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
- {
- SpellModifier* mod = *itr;
- ++itr;
- // spellmods without aura set cannot be charged
- if (!mod->ownerAura || !mod->ownerAura->IsUsingCharges())
- continue;
- // check if mod affected this spell
- Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
- if (iterMod == spell->m_appliedMods.end())
- continue;
- // remove from list
- spell->m_appliedMods.erase(iterMod);
- if (mod->ownerAura->DropCharge(AURA_REMOVE_BY_EXPIRE))
- itr = m_spellMods[i].begin();
- }
- }
- }
- void Player::DropModCharge(SpellModifier* mod, Spell* spell)
- {
- // don't handle spells with proc_event entry defined
- // this is a temporary workaround, because all spellmods should be handled like that
- if (sSpellMgr->GetSpellProcEvent(mod->spellId))
- return;
- if (spell && mod->ownerAura && mod->charges > 0)
- {
- if (--mod->charges == 0)
- mod->charges = -1;
- spell->m_appliedMods.insert(mod->ownerAura);
- }
- }
- void Player::SetSpellModTakingSpell(Spell* spell, bool apply)
- {
- if (!spell || (m_spellModTakingSpell && m_spellModTakingSpell != spell))
- return;
- if (apply && spell->getState() == SPELL_STATE_FINISHED)
- return;
- m_spellModTakingSpell = apply ? spell : NULL;
- }
- // send Proficiency
- void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask)
- {
- WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4);
- data << uint8(itemClass) << uint32(itemSubclassMask);
- GetSession()->SendPacket(&data);
- }
- void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
- {
- PreparedStatement* stmt;
- if (type == 10)
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PETITION_SIG_BY_GUID);
- else
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PETITION_SIG_BY_GUID_TYPE);
- stmt->setUInt8(1, uint8(type));
- }
- stmt->setUInt32(0, GUID_LOPART(guid));
- PreparedQueryResult result = CharacterDatabase.Query(stmt);
- if (result)
- {
- do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
- { // and SendPetitionQueryOpcode reads data from the DB
- Field* fields = result->Fetch();
- uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
- uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
- // send update if charter owner in game
- Player* owner = ObjectAccessor::FindPlayer(ownerguid);
- if (owner)
- owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
- } while (result->NextRow());
- if (type == 10)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_PETITION_SIGNATURES);
- stmt->setUInt32(0, GUID_LOPART(guid));
- CharacterDatabase.Execute(stmt);
- }
- else
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE);
- stmt->setUInt32(0, GUID_LOPART(guid));
- stmt->setUInt8(1, uint8(type));
- CharacterDatabase.Execute(stmt);
- }
- }
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- if (type == 10)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER);
- stmt->setUInt32(0, GUID_LOPART(guid));
- trans->Append(stmt);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER);
- stmt->setUInt32(0, GUID_LOPART(guid));
- trans->Append(stmt);
- }
- else
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE);
- stmt->setUInt32(0, GUID_LOPART(guid));
- stmt->setUInt8(1, uint8(type));
- trans->Append(stmt);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER_AND_TYPE);
- stmt->setUInt32(0, GUID_LOPART(guid));
- stmt->setUInt8(1, uint8(type));
- trans->Append(stmt);
- }
- CharacterDatabase.CommitTransaction(trans);
- }
- void Player::LeaveAllArenaTeams(uint64 guid)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ARENA_TEAMS);
- stmt->setUInt32(0, GUID_LOPART(guid));
- PreparedQueryResult result = CharacterDatabase.Query(stmt);
- if (!result)
- return;
- do
- {
- Field* fields = result->Fetch();
- uint32 arenaTeamId = fields[0].GetUInt32();
- if (arenaTeamId != 0)
- {
- ArenaTeam* arenaTeam = sArenaTeamMgr->GetArenaTeamById(arenaTeamId);
- if (arenaTeam)
- arenaTeam->DelMember(guid, true);
- }
- }
- while (result->NextRow());
- }
- void Player::SetRestBonus (float rest_bonus_new)
- {
- // Prevent resting on max level
- if (getLevel() >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
- rest_bonus_new = 0;
- if (rest_bonus_new < 0)
- rest_bonus_new = 0;
- float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2;
- if (rest_bonus_new > rest_bonus_max)
- m_rest_bonus = rest_bonus_max;
- else
- m_rest_bonus = rest_bonus_new;
- // update data for client
- if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
- SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RAF_LINKED);
- else if (m_rest_bonus > 10)
- SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RESTED); // Set Reststate = Rested
- else if (m_rest_bonus <= 1)
- SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_NOT_RAF_LINKED); // Set Reststate = Normal
- //RestTickUpdate
- SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
- }
- bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
- {
- if (nodes.size() < 2)
- return false;
- // not let cheating with start flight in time of logout process || while in combat || has type state: stunned || has type state: root
- if (GetSession()->isLogingOut() || isInCombat() || HasUnitState(UNIT_STATE_STUNNED) || HasUnitState(UNIT_STATE_ROOT))
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERBUSY);
- return false;
- }
- if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
- return false;
- // taximaster case
- if (npc)
- {
- // not let cheating with start flight mounted
- if (IsMounted())
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERALREADYMOUNTED);
- return false;
- }
- if (IsInDisallowedMountForm())
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERSHAPESHIFTED);
- return false;
- }
- // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
- if (IsNonMeleeSpellCasted(false))
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERBUSY);
- return false;
- }
- }
- // cast case or scripted call case
- else
- {
- RemoveAurasByType(SPELL_AURA_MOUNTED);
- if (IsInDisallowedMountForm())
- RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);
- if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
- if (spell->m_spellInfo->Id != spellid)
- InterruptSpell(CURRENT_GENERIC_SPELL, false);
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false);
- if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
- if (spell->m_spellInfo->Id != spellid)
- InterruptSpell(CURRENT_CHANNELED_SPELL, true);
- }
- uint32 sourcenode = nodes[0];
- // starting node too far away (cheat?)
- TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
- if (!node)
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXINOSUCHPATH);
- return false;
- }
- // check node starting pos data set case if provided
- if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
- {
- if (node->map_id != GetMapId() ||
- (node->x - GetPositionX())*(node->x - GetPositionX())+
- (node->y - GetPositionY())*(node->y - GetPositionY())+
- (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
- (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXITOOFARAWAY);
- return false;
- }
- }
- // node must have pos if taxi master case (npc != NULL)
- else if (npc)
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIUNSPECIFIEDSERVERERROR);
- return false;
- }
- // Prepare to flight start now
- // stop combat at start taxi flight if any
- CombatStop();
- StopCastingCharm();
- StopCastingBindSight();
- ExitVehicle();
- // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
- TradeCancel(true);
- // clean not finished taxi path if any
- m_taxi.ClearTaxiDestinations();
- // 0 element current node
- m_taxi.AddTaxiDestination(sourcenode);
- // fill destinations path tail
- uint32 sourcepath = 0;
- uint32 totalcost = 0;
- uint32 prevnode = sourcenode;
- uint32 lastnode = 0;
- for (uint32 i = 1; i < nodes.size(); ++i)
- {
- uint32 path, cost;
- lastnode = nodes[i];
- sObjectMgr->GetTaxiPath(prevnode, lastnode, path, cost);
- if (!path)
- {
- m_taxi.ClearTaxiDestinations();
- return false;
- }
- totalcost += cost;
- if (prevnode == sourcenode)
- sourcepath = path;
- m_taxi.AddTaxiDestination(lastnode);
- prevnode = lastnode;
- }
- // get mount model (in case non taximaster (npc == NULL) allow more wide lookup)
- //
- // Hack-Fix for Alliance not being able to use Acherus taxi. There is
- // only one mount ID for both sides. Probably not good to use 315 in case DBC nodes
- // change but I couldn't find a suitable alternative. OK to use class because only DK
- // can use this taxi.
- uint32 mount_display_id = sObjectMgr->GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT));
- // in spell case allow 0 model
- if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIUNSPECIFIEDSERVERERROR);
- m_taxi.ClearTaxiDestinations();
- return false;
- }
- uint32 money = GetMoney();
- if (npc)
- totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
- if (money < totalcost)
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXINOTENOUGHMONEY);
- m_taxi.ClearTaxiDestinations();
- return false;
- }
- //Checks and preparations done, DO FLIGHT
- ModifyMoney(-(int32)totalcost);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
- // prevent stealth flight
- //RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
- if (sWorld->getBoolConfig(CONFIG_INSTANT_TAXI))
- {
- TaxiNodesEntry const* lastPathNode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]);
- m_taxi.ClearTaxiDestinations();
- TeleportTo(lastPathNode->map_id, lastPathNode->x, lastPathNode->y, lastPathNode->z, GetOrientation());
- return false;
- }
- else
- {
- GetSession()->SendActivateTaxiReply(ERR_TAXIOK);
- GetSession()->SendDoFlight(mount_display_id, sourcepath);
- }
- return true;
- }
- bool Player::ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid /*= 0*/)
- {
- TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
- if (!entry)
- return false;
- std::vector<uint32> nodes;
- nodes.resize(2);
- nodes[0] = entry->from;
- nodes[1] = entry->to;
- return ActivateTaxiPathTo(nodes, NULL, spellid);
- }
- void Player::CleanupAfterTaxiFlight()
- {
- m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
- Dismount();
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT);
- getHostileRefManager().setOnlineOfflineState(true);
- }
- void Player::ContinueTaxiFlight()
- {
- uint32 sourceNode = m_taxi.GetTaxiSource();
- if (!sourceNode)
- return;
- sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Restart character %u taxi flight", GetGUIDLow());
- uint32 mountDisplayId = sObjectMgr->GetTaxiMountDisplayId(sourceNode, GetTeam(), true);
- uint32 path = m_taxi.GetCurrentTaxiPath();
- // search appropriate start path node
- uint32 startNode = 0;
- TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
- float distPrev = MAP_SIZE*MAP_SIZE;
- float distNext =
- (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
- (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
- (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
- for (uint32 i = 1; i < nodeList.size(); ++i)
- {
- TaxiPathNodeEntry const& node = nodeList[i];
- TaxiPathNodeEntry const& prevNode = nodeList[i-1];
- // skip nodes at another map
- if (node.mapid != GetMapId())
- continue;
- distPrev = distNext;
- distNext =
- (node.x-GetPositionX())*(node.x-GetPositionX())+
- (node.y-GetPositionY())*(node.y-GetPositionY())+
- (node.z-GetPositionZ())*(node.z-GetPositionZ());
- float distNodes =
- (node.x-prevNode.x)*(node.x-prevNode.x)+
- (node.y-prevNode.y)*(node.y-prevNode.y)+
- (node.z-prevNode.z)*(node.z-prevNode.z);
- if (distNext + distPrev < distNodes)
- {
- startNode = i;
- break;
- }
- }
- GetSession()->SendDoFlight(mountDisplayId, path, startNode);
- }
- void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs)
- {
- // last check 2.0.10
- WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
- data << uint64(GetGUID());
- data << uint8(0x0); // flags (0x1, 0x2)
- time_t curTime = time(NULL);
- for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED)
- continue;
- uint32 unSpellId = itr->first;
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(unSpellId);
- if (!spellInfo)
- {
- ASSERT(spellInfo);
- continue;
- }
- // Not send cooldown for this spells
- if (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)
- continue;
- if (spellInfo->PreventionType != SPELL_PREVENTION_TYPE_SILENCE)
- continue;
- if ((idSchoolMask & spellInfo->GetSchoolMask()) && GetSpellCooldownDelay(unSpellId) < unTimeMs)
- {
- data << uint32(unSpellId);
- data << uint32(unTimeMs); // in m.secs
- AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILLISECONDS);
- }
- }
- GetSession()->SendPacket(&data);
- }
- void Player::InitDataForForm(bool reapplyMods)
- {
- ShapeshiftForm form = GetShapeshiftForm();
- SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(form);
- if (ssEntry && ssEntry->attackSpeed)
- {
- SetAttackTime(BASE_ATTACK, ssEntry->attackSpeed);
- SetAttackTime(OFF_ATTACK, ssEntry->attackSpeed);
- SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
- }
- else
- SetRegularAttackTime();
- switch (form)
- {
- case FORM_GHOUL:
- case FORM_CAT:
- {
- if (getPowerType() != POWER_ENERGY)
- setPowerType(POWER_ENERGY);
- break;
- }
- case FORM_BEAR:
- case FORM_DIREBEAR:
- {
- if (getPowerType() != POWER_RAGE)
- setPowerType(POWER_RAGE);
- break;
- }
- default: // 0, for example
- {
- ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
- if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
- setPowerType(Powers(cEntry->powerType));
- break;
- }
- }
- // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
- if (!reapplyMods)
- UpdateEquipSpellsAtFormChange();
- UpdateAttackPowerAndDamage();
- UpdateAttackPowerAndDamage(true);
- }
- void Player::InitDisplayIds()
- {
- PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
- if (!info)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
- return;
- }
- uint8 gender = getGender();
- switch (gender)
- {
- case GENDER_FEMALE:
- SetDisplayId(info->displayId_f);
- SetNativeDisplayId(info->displayId_f);
- break;
- case GENDER_MALE:
- SetDisplayId(info->displayId_m);
- SetNativeDisplayId(info->displayId_m);
- break;
- default:
- sLog->outError(LOG_FILTER_PLAYER, "Invalid gender %u for player", gender);
- return;
- }
- }
- inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot, int32 price, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore)
- {
- ItemPosCountVec vDest;
- uint16 uiDest = 0;
- InventoryResult msg = bStore ?
- CanStoreNewItem(bag, slot, vDest, item, pProto->BuyCount * count) :
- CanEquipNewItem(slot, uiDest, item, false);
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, NULL, NULL, item);
- return false;
- }
- ModifyMoney(-price);
- if (crItem->ExtendedCost) // case for new honor system
- {
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
- if (iece->reqhonorpoints)
- ModifyHonorPoints(- int32(iece->reqhonorpoints * count));
- if (iece->reqarenapoints)
- ModifyArenaPoints(- int32(iece->reqarenapoints * count));
- for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
- {
- if (iece->reqitem[i])
- DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
- }
- }
- Item* it = bStore ?
- StoreNewItem(vDest, item, true) :
- EquipNewItem(uiDest, item, true);
- if (it)
- {
- uint32 new_count = pVendor->UpdateVendorItemCurrentCount(crItem, pProto->BuyCount * count);
- WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
- data << uint64(pVendor->GetGUID());
- data << uint32(vendorslot + 1); // numbered from 1 at client
- data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
- data << uint32(count);
- GetSession()->SendPacket(&data);
- SendNewItem(it, pProto->BuyCount * count, true, false, false);
- if (!bStore)
- AutoUnequipOffhandIfNeed();
- if (pProto->Flags & ITEM_PROTO_FLAG_REFUNDABLE && crItem->ExtendedCost && pProto->GetMaxStackSize() == 1)
- {
- it->SetFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
- it->SetRefundRecipient(GetGUIDLow());
- it->SetPaidMoney(price);
- it->SetPaidExtendedCost(crItem->ExtendedCost);
- it->SaveRefundDataToDB();
- AddRefundReference(it->GetGUIDLow());
- }
- }
- return true;
- }
- // Return true is the bought item has a max count to force refresh of window by caller
- bool Player::BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot)
- {
- // cheating attempt
- if (count < 1) count = 1;
- // cheating attempt
- if (slot > MAX_BAG_SIZE && slot !=NULL_SLOT)
- return false;
- if (!isAlive())
- return false;
- ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
- if (!pProto)
- {
- SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
- return false;
- }
- Creature* creature = GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
- if (!creature)
- {
- sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)));
- SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
- return false;
- }
- VendorItemData const* vItems = creature->GetVendorItems();
- if (!vItems || vItems->Empty())
- {
- SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
- return false;
- }
- if (vendorslot >= vItems->GetItemCount())
- {
- SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
- return false;
- }
- VendorItem const* crItem = vItems->GetItem(vendorslot);
- // store diff item (cheating)
- if (!crItem || crItem->item != item)
- {
- SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
- return false;
- }
- // check current item amount if it limited
- if (crItem->maxcount != 0)
- {
- if (creature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count)
- {
- SendBuyError(BUY_ERR_ITEM_ALREADY_SOLD, creature, item, 0);
- return false;
- }
- }
- if (pProto->RequiredReputationFaction && (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank))
- {
- SendBuyError(BUY_ERR_REPUTATION_REQUIRE, creature, item, 0);
- return false;
- }
- if (crItem->ExtendedCost)
- {
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
- if (!iece)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
- return false;
- }
- // honor points price
- if (GetHonorPoints() < (iece->reqhonorpoints * count))
- {
- SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
- return false;
- }
- // arena points price
- if (GetArenaPoints() < (iece->reqarenapoints * count))
- {
- SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
- return false;
- }
- // item base price
- for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
- {
- if (iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
- {
- SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
- return false;
- }
- }
- // check for personal arena rating requirement
- if (GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating)
- {
- // probably not the proper equip err
- SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL);
- return false;
- }
- }
- uint32 price = 0;
- if (crItem->IsGoldRequired(pProto) && pProto->BuyPrice > 0) //Assume price cannot be negative (do not know why it is int32)
- {
- uint32 maxCount = MAX_MONEY_AMOUNT / pProto->BuyPrice;
- if ((uint32)count > maxCount)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player %s tried to buy %u item id %u, causing overflow", GetName(), (uint32)count, pProto->ItemId);
- count = (uint8)maxCount;
- }
- price = pProto->BuyPrice * count; //it should not exceed MAX_MONEY_AMOUNT
- // reputation discount
- price = uint32(floor(price * GetReputationPriceDiscount(creature)));
- if (!HasEnoughMoney(price))
- {
- SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, item, 0);
- return false;
- }
- }
- if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
- {
- if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, true))
- return false;
- }
- else if (IsEquipmentPos(bag, slot))
- {
- if (pProto->BuyCount * count != 1)
- {
- SendEquipError(EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL);
- return false;
- }
- if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, false))
- return false;
- }
- else
- {
- SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL);
- return false;
- }
- return crItem->maxcount != 0;
- }
- uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) const
- {
- // returns the maximal personal arena rating that can be used to purchase items requiring this condition
- // the personal rating of the arena team must match the required limit as well
- // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
- uint32 max_personal_rating = 0;
- for (uint8 i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
- {
- if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(GetArenaTeamId(i)))
- {
- uint32 p_rating = GetArenaPersonalRating(i);
- uint32 t_rating = at->GetRating();
- p_rating = p_rating < t_rating ? p_rating : t_rating;
- if (max_personal_rating < p_rating)
- max_personal_rating = p_rating;
- }
- }
- return max_personal_rating;
- }
- void Player::UpdateHomebindTime(uint32 time)
- {
- // GMs never get homebind timer online
- if (m_InstanceValid || isGameMaster())
- {
- if (m_HomebindTimer) // instance valid, but timer not reset
- {
- // hide reminder
- WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
- data << uint32(0);
- data << uint32(0);
- GetSession()->SendPacket(&data);
- }
- // instance is valid, reset homebind timer
- m_HomebindTimer = 0;
- }
- else if (m_HomebindTimer > 0)
- {
- if (time >= m_HomebindTimer)
- {
- // teleport to nearest graveyard
- RepopAtGraveyard();
- }
- else
- m_HomebindTimer -= time;
- }
- else
- {
- // instance is invalid, start homebind timer
- m_HomebindTimer = 60000;
- // send message to player
- WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
- data << uint32(m_HomebindTimer);
- data << uint32(1);
- GetSession()->SendPacket(&data);
- sLog->outDebug(LOG_FILTER_MAPS, "PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(), GetGUIDLow());
- }
- }
- void Player::UpdatePvPState(bool onlyFFA)
- {
- // TODO: should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled?
- // no, we shouldn't, those are checked for affecting player by client
- if (!pvpInfo.inNoPvPArea && !isGameMaster()
- && (pvpInfo.inFFAPvPArea || sWorld->IsFFAPvPRealm()))
- {
- if (!HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- {
- SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- }
- }
- else if (HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- {
- RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- }
- if (onlyFFA)
- return;
- if (pvpInfo.inHostileArea) // in hostile area
- {
- if (!IsPvP() || pvpInfo.endTimer != 0)
- UpdatePvP(true, true);
- }
- else // in friendly area
- {
- if (IsPvP() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
- pvpInfo.endTimer = time(0); // start toggle-off
- }
- }
- void Player::UpdatePvP(bool state, bool override)
- {
- if (!state || override)
- {
- SetPvP(state);
- pvpInfo.endTimer = 0;
- }
- else
- {
- pvpInfo.endTimer = time(NULL);
- SetPvP(state);
- }
- }
- void Player::AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
- {
- // init cooldown values
- uint32 cat = 0;
- int32 rec = -1;
- int32 catrec = -1;
- // some special item spells without correct cooldown in SpellInfo
- // cooldown information stored in item prototype
- // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
- if (itemId)
- {
- if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId))
- {
- for (uint8 idx = 0; idx < MAX_ITEM_SPELLS; ++idx)
- {
- if (uint32(proto->Spells[idx].SpellId) == spellInfo->Id)
- {
- cat = proto->Spells[idx].SpellCategory;
- rec = proto->Spells[idx].SpellCooldown;
- catrec = proto->Spells[idx].SpellCategoryCooldown;
- break;
- }
- }
- }
- }
- // if no cooldown found above then base at DBC data
- if (rec < 0 && catrec < 0)
- {
- cat = spellInfo->Category;
- rec = spellInfo->RecoveryTime;
- catrec = spellInfo->CategoryRecoveryTime;
- }
- time_t curTime = time(NULL);
- time_t catrecTime;
- time_t recTime;
- // overwrite time for selected category
- if (infinityCooldown)
- {
- // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
- // but not allow ignore until reset or re-login
- catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
- recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
- }
- else
- {
- // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
- // prevent 0 cooldowns set by another way
- if (rec <= 0 && catrec <= 0 && (cat == 76 || (spellInfo->IsAutoRepeatRangedSpell() && spellInfo->Id != 75)))
- rec = GetAttackTime(RANGED_ATTACK);
- // Now we have cooldown data (if found any), time to apply mods
- if (rec > 0)
- ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
- if (catrec > 0)
- ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
- // replace negative cooldowns by 0
- if (rec < 0) rec = 0;
- if (catrec < 0) catrec = 0;
- // no cooldown after applying spell mods
- if (rec == 0 && catrec == 0)
- return;
- catrecTime = catrec ? curTime+catrec/IN_MILLISECONDS : 0;
- recTime = rec ? curTime+rec/IN_MILLISECONDS : catrecTime;
- }
- // self spell cooldown
- if (recTime > 0)
- AddSpellCooldown(spellInfo->Id, itemId, recTime);
- // category spells
- if (cat && catrec > 0)
- {
- SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
- if (i_scstore != sSpellCategoryStore.end())
- {
- for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
- {
- if (*i_scset == spellInfo->Id) // skip main spell, already handled above
- continue;
- AddSpellCooldown(*i_scset, itemId, catrecTime);
- }
- }
- }
- }
- void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
- {
- SpellCooldown sc;
- sc.end = end_time;
- sc.itemid = itemid;
- m_spellCooldowns[spellid] = sc;
- }
- void Player::SendCooldownEvent(SpellInfo const* spellInfo, uint32 itemId /*= 0*/, Spell* spell /*= NULL*/, bool setCooldown /*= true*/)
- {
- // start cooldowns at server side, if any
- if (setCooldown)
- AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
- // Send activate cooldown timer (possible 0) at client side
- WorldPacket data(SMSG_COOLDOWN_EVENT, 4 + 8);
- data << uint32(spellInfo->Id);
- data << uint64(GetGUID());
- SendDirectMessage(&data);
- }
- void Player::UpdatePotionCooldown(Spell* spell)
- {
- // no potion used i combat or still in combat
- if (!m_lastPotionId || isInCombat())
- return;
- // Call not from spell cast, send cooldown event for item spells if no in combat
- if (!spell)
- {
- // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
- if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(m_lastPotionId))
- for (uint8 idx = 0; idx < MAX_ITEM_SPELLS; ++idx)
- if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
- if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(proto->Spells[idx].SpellId))
- SendCooldownEvent(spellInfo, m_lastPotionId);
- }
- // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
- else
- SendCooldownEvent(spell->m_spellInfo, m_lastPotionId, spell);
- m_lastPotionId = 0;
- }
- //slot to be excluded while counting
- bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
- {
- if (!enchantmentcondition)
- return true;
- SpellItemEnchantmentConditionEntry const* Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
- if (!Condition)
- return true;
- uint8 curcount[4] = {0, 0, 0, 0};
- //counting current equipped gem colors
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- if (i == slot)
- continue;
- Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
- if (pItem2 && !pItem2->IsBroken() && pItem2->GetTemplate()->Socket[0].Color)
- {
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if (!enchant_id)
- continue;
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!enchantEntry)
- continue;
- uint32 gemid = enchantEntry->GemID;
- if (!gemid)
- continue;
- ItemTemplate const* gemProto = sObjectMgr->GetItemTemplate(gemid);
- if (!gemProto)
- continue;
- GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
- if (!gemProperty)
- continue;
- uint8 GemColor = gemProperty->color;
- for (uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
- {
- if (tmpcolormask & GemColor)
- ++curcount[b];
- }
- }
- }
- }
- bool activate = true;
- for (uint8 i = 0; i < 5; i++)
- {
- if (!Condition->Color[i])
- continue;
- uint32 _cur_gem = curcount[Condition->Color[i] - 1];
- // if have <CompareColor> use them as count, else use <value> from Condition
- uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
- switch (Condition->Comparator[i])
- {
- case 2: // requires less <color> than (<value> || <comparecolor>) gems
- activate &= (_cur_gem < _cmp_gem) ? true : false;
- break;
- case 3: // requires more <color> than (<value> || <comparecolor>) gems
- activate &= (_cur_gem > _cmp_gem) ? true : false;
- break;
- case 5: // requires at least <color> than (<value> || <comparecolor>) gems
- activate &= (_cur_gem >= _cmp_gem) ? true : false;
- break;
- }
- }
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
- return activate;
- }
- void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
- {
- //cycle all equipped items
- for (uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- //enchants for the slot being socketed are handled by Player::ApplyItemMods
- if (slot == exceptslot)
- continue;
- Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
- if (!pItem || !pItem->GetTemplate()->Socket[0].Color)
- continue;
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if (!enchant_id)
- continue;
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!enchantEntry)
- continue;
- uint32 condition = enchantEntry->EnchantmentCondition;
- if (condition)
- {
- //was enchant active with/without item?
- bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
- //should it now be?
- if (wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
- {
- // ignore item gem conditions
- //if state changed, (dis)apply enchant
- ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
- }
- }
- }
- }
- }
- //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
- void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
- {
- //cycle all equipped items
- for (int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
- if (slot == exceptslot)
- continue;
- Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
- if (!pItem || !pItem->GetTemplate()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
- continue;
- //cycle all (gem)enchants
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if (!enchant_id) //if no enchant go to next enchant(slot)
- continue;
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!enchantEntry)
- continue;
- //only metagems to be (de)activated, so only enchants with condition
- uint32 condition = enchantEntry->EnchantmentCondition;
- if (condition)
- ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), apply);
- }
- }
- }
- void Player::SetBattlegroundEntryPoint()
- {
- // Taxi path store
- if (!m_taxi.empty())
- {
- m_bgData.mountSpell = 0;
- m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
- m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
- // On taxi we don't need check for dungeon
- m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- }
- else
- {
- m_bgData.ClearTaxiPath();
- // Mount spell id storing
- if (IsMounted())
- {
- AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOUNTED);
- if (!auras.empty())
- m_bgData.mountSpell = (*auras.begin())->GetId();
- }
- else
- m_bgData.mountSpell = 0;
- // If map is dungeon find linked graveyard
- if (GetMap()->IsDungeon())
- {
- if (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
- m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
- else
- sLog->outError(LOG_FILTER_PLAYER, "SetBattlegroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
- }
- // If new entry point is not BG or arena set it
- else if (!GetMap()->IsBattlegroundOrArena())
- m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- }
- if (m_bgData.joinPos.m_mapId == MAPID_INVALID) // In error cases use homebind position
- m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
- }
- void Player::LeaveBattleground(bool teleportToEntryPoint)
- {
- if (Battleground* bg = GetBattleground())
- {
- bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
- // call after remove to be sure that player resurrected for correct cast
- if (bg->isBattleground() && !isGameMaster() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_CAST_DESERTER))
- {
- if (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)
- {
- //lets check if player was teleported from BG and schedule delayed Deserter spell cast
- if (IsBeingTeleportedFar())
- {
- ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
- return;
- }
- CastSpell(this, 26013, true); // Deserter
- }
- }
- }
- }
- bool Player::CanJoinToBattleground() const
- {
- // check Deserter debuff
- if (HasAura(26013))
- return false;
- return true;
- }
- bool Player::CanReportAfkDueToLimit()
- {
- // a player can complain about 15 people per 5 minutes
- if (m_bgData.bgAfkReportedCount++ >= 15)
- return false;
- return true;
- }
- ///This player has been blamed to be inactive in a battleground
- void Player::ReportedAfkBy(Player* reporter)
- {
- Battleground* bg = GetBattleground();
- // Battleground also must be in progress!
- if (!bg || bg != reporter->GetBattleground() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS)
- return;
- // check if player has 'Idle' or 'Inactive' debuff
- if (m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit())
- {
- m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
- // 3 players have to complain to apply debuff
- if (m_bgData.bgAfkReporter.size() >= 3)
- {
- // cast 'Idle' spell
- CastSpell(this, 43680, true);
- m_bgData.bgAfkReporter.clear();
- }
- }
- }
- WorldLocation Player::GetStartPosition() const
- {
- PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
- uint32 mapId = info->mapId;
- if (getClass() == CLASS_DEATH_KNIGHT && HasSpell(50977))
- mapId = 0;
- return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0);
- }
- bool Player::IsNeverVisible() const
- {
- if (Unit::IsNeverVisible())
- return true;
- if (GetSession()->PlayerLogout() || GetSession()->PlayerLoading())
- return true;
- return false;
- }
- bool Player::CanAlwaysSee(WorldObject const* obj) const
- {
- // Always can see self
- if (m_mover == obj)
- return true;
- if (uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
- if (obj->GetGUID() == guid)
- return true;
- return false;
- }
- bool Player::IsAlwaysDetectableFor(WorldObject const* seer) const
- {
- if (Unit::IsAlwaysDetectableFor(seer))
- return true;
- if (const Player* seerPlayer = seer->ToPlayer())
- if (IsGroupVisibleFor(seerPlayer))
- return true;
- return false;
- }
- bool Player::IsVisibleGloballyFor(Player* u) const
- {
- if (!u)
- return false;
- // Always can see self
- if (u == this)
- return true;
- // Visible units, always are visible for all players
- if (IsVisible())
- return true;
- // GMs are visible for higher gms (or players are visible for gms)
- if (!AccountMgr::IsPlayerAccount(u->GetSession()->GetSecurity()))
- return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
- // non faction visibility non-breakable for non-GMs
- if (!IsVisible())
- return false;
- // non-gm stealth/invisibility not hide from global player lists
- return true;
- }
- template<class T>
- inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target, std::set<Unit*>& /*v*/)
- {
- s64.insert(target->GetGUID());
- }
- template<>
- inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Creature* target, std::set<Unit*>& v)
- {
- s64.insert(target->GetGUID());
- v.insert(target);
- }
- template<>
- inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Player* target, std::set<Unit*>& v)
- {
- s64.insert(target->GetGUID());
- v.insert(target);
- }
- template<class T>
- inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
- {
- }
- template<>
- inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
- {
- if (p->GetPetGUID() == t->GetGUID() && t->ToCreature()->isPet())
- ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
- }
- void Player::UpdateVisibilityOf(WorldObject* target)
- {
- if (HaveAtClient(target))
- {
- if (!canSeeOrDetect(target, false, true))
- {
- if (target->GetTypeId() == TYPEID_UNIT)
- BeforeVisibilityDestroy<Creature>(target->ToCreature(), this);
- target->DestroyForPlayer(this);
- m_clientGUIDs.erase(target->GetGUID());
- #ifdef TRINITY_DEBUG
- sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u) out of range for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), GetGUIDLow(), GetDistance(target));
- #endif
- }
- }
- else
- {
- if (canSeeOrDetect(target, false, true))
- {
- //if (target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
- // UpdateVisibilityOf(((Unit*)target)->m_Vehicle);
- target->SendUpdateToPlayer(this);
- m_clientGUIDs.insert(target->GetGUID());
- #ifdef TRINITY_DEBUG
- sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u) is visible now for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), GetGUIDLow(), GetDistance(target));
- #endif
- // target aura duration for caster show only if target exist at caster client
- // send data at target visibility change (adding to client)
- if (target->isType(TYPEMASK_UNIT))
- SendInitialVisiblePackets((Unit*)target);
- }
- }
- }
- void Player::UpdateTriggerVisibility()
- {
- if (m_clientGUIDs.empty())
- return;
- if (!IsInWorld())
- return;
- UpdateData udata;
- WorldPacket packet;
- for (ClientGUIDs::iterator itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
- {
- if (IS_CREATURE_GUID(*itr))
- {
- Creature* obj = GetMap()->GetCreature(*itr);
- if (!obj || !(obj->isTrigger() || obj->HasAuraType(SPELL_AURA_TRANSFORM))) // can transform into triggers
- continue;
- obj->BuildCreateUpdateBlockForPlayer(&udata, this);
- }
- }
- udata.BuildPacket(&packet);
- GetSession()->SendPacket(&packet);
- }
- void Player::SendInitialVisiblePackets(Unit* target)
- {
- SendAurasForTarget(target);
- if (target->isAlive())
- {
- if (target->HasUnitState(UNIT_STATE_MELEE_ATTACKING) && target->getVictim())
- target->SendMeleeAttackStart(target->getVictim());
- }
- }
- template<class T>
- void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow)
- {
- if (HaveAtClient(target))
- {
- if (!canSeeOrDetect(target, false, true))
- {
- BeforeVisibilityDestroy<T>(target, this);
- target->BuildOutOfRangeUpdateBlock(&data);
- m_clientGUIDs.erase(target->GetGUID());
- #ifdef TRINITY_DEBUG
- sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), target->GetEntry(), GetGUIDLow(), GetDistance(target));
- #endif
- }
- }
- else //if (visibleNow.size() < 30 || target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle())
- {
- if (canSeeOrDetect(target, false, true))
- {
- //if (target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
- // UpdateVisibilityOf(((Unit*)target)->m_Vehicle, data, visibleNow);
- target->BuildCreateUpdateBlockForPlayer(&data, this);
- UpdateVisibilityOf_helper(m_clientGUIDs, target, visibleNow);
- #ifdef TRINITY_DEBUG
- sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), target->GetEntry(), GetGUIDLow(), GetDistance(target));
- #endif
- }
- }
- }
- template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, std::set<Unit*>& visibleNow);
- template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, std::set<Unit*>& visibleNow);
- template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, std::set<Unit*>& visibleNow);
- template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
- template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
- void Player::UpdateObjectVisibility(bool forced)
- {
- if (!forced)
- AddToNotify(NOTIFY_VISIBILITY_CHANGED);
- else
- {
- Unit::UpdateObjectVisibility(true);
- UpdateVisibilityForPlayer();
- }
- }
- void Player::UpdateVisibilityForPlayer()
- {
- // updates visibility of all objects around point of view for current player
- Trinity::VisibleNotifier notifier(*this);
- m_seer->VisitNearbyObject(GetSightRange(), notifier);
- notifier.SendToSelf(); // send gathered data
- }
- void Player::InitPrimaryProfessions()
- {
- SetFreePrimaryProfessions(sWorld->getIntConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
- }
- void Player::ModifyMoney(int32 d)
- {
- sScriptMgr->OnPlayerMoneyChanged(this, d);
- if (d < 0)
- SetMoney (GetMoney() > uint32(-d) ? GetMoney() + d : 0);
- else
- {
- uint32 newAmount = 0;
- if (GetMoney() < uint32(MAX_MONEY_AMOUNT - d))
- newAmount = GetMoney() + d;
- else
- {
- // "At Gold Limit"
- newAmount = MAX_MONEY_AMOUNT;
- if (d)
- SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, NULL, NULL);
- }
- SetMoney (newAmount);
- }
- }
- Unit* Player::GetSelectedUnit() const
- {
- if (m_curSelection)
- return ObjectAccessor::GetUnit(*this, m_curSelection);
- return NULL;
- }
- Player* Player::GetSelectedPlayer() const
- {
- if (m_curSelection)
- return ObjectAccessor::GetPlayer(*this, m_curSelection);
- return NULL;
- }
- void Player::SendComboPoints()
- {
- Unit* combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
- if (combotarget)
- {
- WorldPacket data;
- if (m_mover != this)
- {
- data.Initialize(SMSG_PET_UPDATE_COMBO_POINTS, m_mover->GetPackGUID().size()+combotarget->GetPackGUID().size()+1);
- data.append(m_mover->GetPackGUID());
- }
- else
- data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
- data.append(combotarget->GetPackGUID());
- data << uint8(m_comboPoints);
- GetSession()->SendPacket(&data);
- }
- }
- void Player::AddComboPoints(Unit* target, int8 count, Spell* spell)
- {
- if (!count)
- return;
- int8 * comboPoints = spell ? &spell->m_comboPointGain : &m_comboPoints;
- // without combo points lost (duration checked in aura)
- RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
- if (target->GetGUID() == m_comboTarget)
- *comboPoints += count;
- else
- {
- if (m_comboTarget)
- if (Unit* target2 = ObjectAccessor::GetUnit(*this, m_comboTarget))
- target2->RemoveComboPointHolder(GetGUIDLow());
- // Spells will always add value to m_comboPoints eventualy, so it must be cleared first
- if (spell)
- m_comboPoints = 0;
- m_comboTarget = target->GetGUID();
- *comboPoints = count;
- target->AddComboPointHolder(GetGUIDLow());
- }
- if (*comboPoints > 5)
- *comboPoints = 5;
- else if (*comboPoints < 0)
- *comboPoints = 0;
- if (!spell)
- SendComboPoints();
- }
- void Player::GainSpellComboPoints(int8 count)
- {
- if (!count)
- return;
- m_comboPoints += count;
- if (m_comboPoints > 5) m_comboPoints = 5;
- else if (m_comboPoints < 0) m_comboPoints = 0;
- SendComboPoints();
- }
- void Player::ClearComboPoints()
- {
- if (!m_comboTarget)
- return;
- // without combopoints lost (duration checked in aura)
- RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
- m_comboPoints = 0;
- SendComboPoints();
- if (Unit* target = ObjectAccessor::GetUnit(*this, m_comboTarget))
- target->RemoveComboPointHolder(GetGUIDLow());
- m_comboTarget = 0;
- }
- void Player::SetGroup(Group* group, int8 subgroup)
- {
- if (group == NULL)
- m_group.unlink();
- else
- {
- // never use SetGroup without a subgroup unless you specify NULL for group
- ASSERT(subgroup >= 0);
- m_group.link(group, this);
- m_group.setSubGroup((uint8)subgroup);
- }
- UpdateObjectVisibility(false);
- }
- void Player::SendInitialPacketsBeforeAddToMap()
- {
- /// Pass 'this' as argument because we're not stored in ObjectAccessor yet
- GetSocial()->SendSocialList(this);
- // guild bank list wtf?
- // Homebind
- WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
- data << m_homebindX << m_homebindY << m_homebindZ;
- data << (uint32) m_homebindMapId;
- data << (uint32) m_homebindAreaId;
- GetSession()->SendPacket(&data);
- // SMSG_SET_PROFICIENCY
- // SMSG_SET_PCT_SPELL_MODIFIER
- // SMSG_SET_FLAT_SPELL_MODIFIER
- // SMSG_UPDATE_AURA_DURATION
- SendTalentsInfoData(false);
- // SMSG_INSTANCE_DIFFICULTY
- data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
- data << uint32(GetMap()->GetDifficulty());
- data << uint32(0);
- GetSession()->SendPacket(&data);
- SendInitialSpells();
- data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
- data << uint32(0); // count, for (count) uint32;
- GetSession()->SendPacket(&data);
- SendInitialActionButtons();
- m_reputationMgr.SendInitialReputations();
- m_achievementMgr.SendAllAchievementData();
- SendEquipmentSetList();
- data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
- data << uint32(secsToTimeBitFields(sWorld->GetGameTime()));
- data << float(0.01666667f); // game speed
- data << uint32(0); // added in 3.1.2
- GetSession()->SendPacket(&data);
- GetReputationMgr().SendForceReactions(); // SMSG_SET_FORCED_REACTIONS
- // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
- // SMSG_PET_GUIDS
- // SMSG_UPDATE_WORLD_STATE
- // SMSG_POWER_UPDATE
- SetMover(this);
- }
- void Player::SendInitialPacketsAfterAddToMap()
- {
- UpdateVisibilityForPlayer();
- // update zone
- uint32 newzone, newarea;
- GetZoneAndAreaId(newzone, newarea);
- UpdateZone(newzone, newarea); // also call SendInitWorldStates();
- ResetTimeSync();
- SendTimeSync();
- CastSpell(this, 836, true); // LOGINEFFECT
- // set some aura effects that send packet to player client after add player to map
- // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
- // same auras state lost at far teleport, send it one more time in this case also
- static const AuraType auratypes[] =
- {
- SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
- SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
- SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED, SPELL_AURA_NONE
- };
- for (AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
- {
- Unit::AuraEffectList const& auraList = GetAuraEffectsByType(*itr);
- if (!auraList.empty())
- auraList.front()->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
- }
- if (HasAuraType(SPELL_AURA_MOD_STUN))
- SetMovement(MOVE_ROOT);
- // manual send package (have code in HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true); that must not be re-applied.
- if (HasAuraType(SPELL_AURA_MOD_ROOT))
- {
- WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
- data2.append(GetPackGUID());
- data2 << (uint32)2;
- SendMessageToSet(&data2, true);
- }
- SendAurasForTarget(this);
- SendEnchantmentDurations(); // must be after add to map
- SendItemDurations(); // must be after add to map
- // raid downscaling - send difficulty to player
- if (GetMap()->IsRaid())
- {
- if (GetMap()->GetDifficulty() != GetRaidDifficulty())
- {
- StoreRaidMapDifficulty();
- SendRaidDifficulty(GetGroup() != NULL, GetStoredRaidDifficulty());
- }
- }
- else if (GetRaidDifficulty() != GetStoredRaidDifficulty())
- SendRaidDifficulty(GetGroup() != NULL);
- }
- void Player::SendUpdateToOutOfRangeGroupMembers()
- {
- if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
- return;
- if (Group* group = GetGroup())
- group->UpdatePlayerOutOfRange(this);
- m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
- m_auraRaidUpdateMask = 0;
- if (Pet* pet = GetPet())
- pet->ResetAuraUpdateMaskForRaid();
- }
- void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg)
- {
- WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
- data << uint32(mapid);
- data << uint8(reason); // transfer abort reason
- switch (reason)
- {
- case TRANSFER_ABORT_INSUF_EXPAN_LVL:
- case TRANSFER_ABORT_DIFFICULTY:
- case TRANSFER_ABORT_UNIQUE_MESSAGE:
- // these are the ONLY cases that have an extra argument in the packet!!!
- data << uint8(arg);
- break;
- default:
- break;
- }
- GetSession()->SendPacket(&data);
- }
- void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time)
- {
- // type of warning, based on the time remaining until reset
- uint32 type;
- if (time > 3600)
- type = RAID_INSTANCE_WELCOME;
- else if (time > 900 && time <= 3600)
- type = RAID_INSTANCE_WARNING_HOURS;
- else if (time > 300 && time <= 900)
- type = RAID_INSTANCE_WARNING_MIN;
- else
- type = RAID_INSTANCE_WARNING_MIN_SOON;
- WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
- data << uint32(type);
- data << uint32(mapid);
- data << uint32(difficulty); // difficulty
- data << uint32(time);
- if (type == RAID_INSTANCE_WELCOME)
- {
- data << uint8(0); // is locked
- data << uint8(0); // is extended, ignored if prev field is 0
- }
- GetSession()->SendPacket(&data);
- }
- void Player::ApplyEquipCooldown(Item* pItem)
- {
- if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_PROTO_FLAG_NO_EQUIP_COOLDOWN))
- return;
- for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
- {
- _Spell const& spellData = pItem->GetTemplate()->Spells[i];
- // no spell
- if (!spellData.SpellId)
- continue;
- // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
- if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
- continue;
- AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
- WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
- data << pItem->GetGUID();
- data << uint32(spellData.SpellId);
- GetSession()->SendPacket(&data);
- }
- }
- void Player::resetSpells(bool myClassOnly)
- {
- // not need after this call
- if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
- RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS, true);
- // make full copy of map (spells removed and marked as deleted at another spell remove
- // and we can't use original map for safe iterative with visit each spell at loop end
- PlayerSpellMap smap = GetSpellMap();
- uint32 family;
- if (myClassOnly)
- {
- ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(getClass());
- if (!clsEntry)
- return;
- family = clsEntry->spellfamily;
- for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
- {
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(iter->first);
- if (!spellInfo)
- continue;
- // skip server-side/triggered spells
- if (spellInfo->SpellLevel == 0)
- continue;
- // skip wrong class/race skills
- if (!IsSpellFitByClassAndRace(spellInfo->Id))
- continue;
- // skip other spell families
- if (spellInfo->SpellFamilyName != family)
- continue;
- // skip spells with first rank learned as talent (and all talents then also)
- uint32 first_rank = sSpellMgr->GetFirstSpellInChain(spellInfo->Id);
- if (GetTalentSpellCost(first_rank) > 0)
- continue;
- // skip broken spells
- if (!SpellMgr::IsSpellValid(spellInfo, this, false))
- continue;
- }
- }
- else
- for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
- removeSpell(iter->first, false, false); // only iter->first can be accessed, object by iter->second can be deleted already
- learnDefaultSpells();
- learnQuestRewardedSpells();
- }
- void Player::learnDefaultSpells()
- {
- // learn default race/class spells
- PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
- for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr != info->spell.end(); ++itr)
- {
- uint32 tspell = *itr;
- sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "PLAYER (Class: %u Race: %u): Adding initial spell, id = %u", uint32(getClass()), uint32(getRace()), tspell);
- if (!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
- addSpell(tspell, true, true, true, false);
- else // but send in normal spell in game learn case
- learnSpell(tspell, true);
- }
- }
- void Player::learnQuestRewardedSpells(Quest const* quest)
- {
- int32 spell_id = quest->GetRewSpellCast();
- uint32 src_spell_id = quest->GetSrcSpell();
- // skip quests without rewarded spell
- if (!spell_id)
- return;
- // if RewSpellCast = -1 we remove aura do to SrcSpell from player.
- if (spell_id == -1 && src_spell_id)
- {
- RemoveAurasDueToSpell(src_spell_id);
- return;
- }
- SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
- if (!spellInfo)
- return;
- // check learned spells state
- bool found = false;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (spellInfo->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->Effects[i].TriggerSpell))
- {
- found = true;
- break;
- }
- }
- // skip quests with not teaching spell or already known spell
- if (!found)
- return;
- // prevent learn non first rank unknown profession and second specialization for same profession)
- uint32 learned_0 = spellInfo->Effects[0].TriggerSpell;
- if (sSpellMgr->GetSpellRank(learned_0) > 1 && !HasSpell(learned_0))
- {
- // not have first rank learned (unlearned prof?)
- uint32 first_spell = sSpellMgr->GetFirstSpellInChain(learned_0);
- if (!HasSpell(first_spell))
- return;
- SpellInfo const* learnedInfo = sSpellMgr->GetSpellInfo(learned_0);
- if (!learnedInfo)
- return;
- SpellsRequiringSpellMapBounds spellsRequired = sSpellMgr->GetSpellsRequiredForSpellBounds(learned_0);
- for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequired.first; itr2 != spellsRequired.second; ++itr2)
- {
- uint32 profSpell = itr2->second;
- // specialization
- if (learnedInfo->Effects[0].Effect == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effects[1].Effect == 0 && profSpell)
- {
- // search other specialization for same prof
- for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->first == learned_0)
- continue;
- SpellInfo const* itrInfo = sSpellMgr->GetSpellInfo(itr->first);
- if (!itrInfo)
- return;
- // compare only specializations
- if (itrInfo->Effects[0].Effect != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effects[1].Effect != 0)
- continue;
- // compare same chain spells
- if (sSpellMgr->IsSpellRequiringSpell(itr->first, profSpell))
- return;
- }
- }
- }
- }
- CastSpell(this, spell_id, true);
- }
- void Player::learnQuestRewardedSpells()
- {
- // learn spells received from quest completing
- for (RewardedQuestSet::const_iterator itr = m_RewardedQuests.begin(); itr != m_RewardedQuests.end(); ++itr)
- {
- Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
- if (!quest)
- continue;
- learnQuestRewardedSpells(quest);
- }
- }
- void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value)
- {
- uint32 raceMask = getRaceMask();
- uint32 classMask = getClassMask();
- for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
- {
- SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j);
- if (!pAbility || pAbility->skillId != skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
- continue;
- // Check race if set
- if (pAbility->racemask && !(pAbility->racemask & raceMask))
- continue;
- // Check class if set
- if (pAbility->classmask && !(pAbility->classmask & classMask))
- continue;
- if (sSpellMgr->GetSpellInfo(pAbility->spellId))
- {
- // need unlearn spell
- if (skill_value < pAbility->req_skill_value)
- removeSpell(pAbility->spellId);
- // need learn
- else if (!IsInWorld())
- addSpell(pAbility->spellId, true, true, true, false);
- else
- learnSpell(pAbility->spellId, true);
- }
- }
- }
- void Player::SendAurasForTarget(Unit* target)
- {
- if (!target || target->GetVisibleAuras()->empty()) // speedup things
- return;
- /*! Blizz sends certain movement packets sometimes even before CreateObject
- These movement packets are usually found in SMSG_COMPRESSED_MOVES
- */
- if (target->HasAuraType(SPELL_AURA_FEATHER_FALL))
- target->SendMovementFeatherFall();
- if (target->HasAuraType(SPELL_AURA_WATER_WALK))
- target->SendMovementWaterWalking();
- if (target->HasAuraType(SPELL_AURA_HOVER))
- target->SendMovementHover();
- WorldPacket data(SMSG_AURA_UPDATE_ALL);
- data.append(target->GetPackGUID());
- Unit::VisibleAuraMap const* visibleAuras = target->GetVisibleAuras();
- for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
- {
- AuraApplication * auraApp = itr->second;
- auraApp->BuildUpdatePacket(data, false);
- }
- GetSession()->SendPacket(&data);
- }
- void Player::SetDailyQuestStatus(uint32 quest_id)
- {
- if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(quest_id))
- {
- if (!qQuest->IsDFQuest())
- {
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- {
- if (!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
- {
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id);
- m_lastDailyQuestTime = time(NULL); // last daily quest time
- m_DailyQuestChanged = true;
- break;
- }
- }
- } else
- {
- m_DFQuests.insert(quest_id);
- m_lastDailyQuestTime = time(NULL);
- m_DailyQuestChanged = true;
- }
- }
- }
- void Player::SetWeeklyQuestStatus(uint32 quest_id)
- {
- m_weeklyquests.insert(quest_id);
- m_WeeklyQuestChanged = true;
- }
- void Player::SetSeasonalQuestStatus(uint32 quest_id)
- {
- Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
- if (!quest)
- return;
- m_seasonalquests[sGameEventMgr->GetEventIdForQuest(quest)].insert(quest_id);
- m_SeasonalQuestChanged = true;
- }
- void Player::ResetDailyQuestStatus()
- {
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, 0);
- m_DFQuests.clear(); // Dungeon Finder Quests.
- // DB data deleted in caller
- m_DailyQuestChanged = false;
- m_lastDailyQuestTime = 0;
- }
- void Player::ResetWeeklyQuestStatus()
- {
- if (m_weeklyquests.empty())
- return;
- m_weeklyquests.clear();
- // DB data deleted in caller
- m_WeeklyQuestChanged = false;
- }
- void Player::ResetSeasonalQuestStatus(uint16 event_id)
- {
- if (m_seasonalquests.empty() || m_seasonalquests[event_id].empty())
- return;
- m_seasonalquests.erase(event_id);
- // DB data deleted in caller
- m_SeasonalQuestChanged = false;
- }
- Battleground* Player::GetBattleground() const
- {
- if (GetBattlegroundId() == 0)
- return NULL;
- return sBattlegroundMgr->GetBattleground(GetBattlegroundId(), m_bgData.bgTypeID);
- }
- bool Player::InArena() const
- {
- Battleground* bg = GetBattleground();
- if (!bg || !bg->isArena())
- return false;
- return true;
- }
- bool Player::GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const
- {
- // get a template bg instead of running one
- Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(bgTypeId);
- if (!bg)
- return false;
- // limit check leel to dbc compatible level range
- uint32 level = getLevel();
- if (level > DEFAULT_MAX_LEVEL)
- level = DEFAULT_MAX_LEVEL;
- if (level < bg->GetMinLevel() || level > bg->GetMaxLevel())
- return false;
- return true;
- }
- float Player::GetReputationPriceDiscount(Creature const* creature) const
- {
- FactionTemplateEntry const* vendor_faction = creature->getFactionTemplateEntry();
- if (!vendor_faction || !vendor_faction->faction)
- return 1.0f;
- ReputationRank rank = GetReputationRank(vendor_faction->faction);
- if (rank <= REP_NEUTRAL)
- return 1.0f;
- return 1.0f - 0.05f* (rank - REP_NEUTRAL);
- }
- bool Player::IsSpellFitByClassAndRace(uint32 spell_id) const
- {
- uint32 racemask = getRaceMask();
- uint32 classmask = getClassMask();
- SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spell_id);
- if (bounds.first == bounds.second)
- return true;
- for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
- {
- // skip wrong race skills
- if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
- continue;
- // skip wrong class skills
- if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
- continue;
- return true;
- }
- return false;
- }
- bool Player::HasQuestForGO(int32 GOId) const
- {
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (questid == 0)
- continue;
- QuestStatusMap::const_iterator qs_itr = m_QuestStatus.find(questid);
- if (qs_itr == m_QuestStatus.end())
- continue;
- QuestStatusData const& qs = qs_itr->second;
- if (qs.Status == QUEST_STATUS_INCOMPLETE)
- {
- Quest const* qinfo = sObjectMgr->GetQuestTemplate(questid);
- if (!qinfo)
- continue;
- if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid())
- continue;
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- if (qinfo->RequiredNpcOrGo[j] >= 0) //skip non GO case
- continue;
- if ((-1)*GOId == qinfo->RequiredNpcOrGo[j] && qs.CreatureOrGOCount[j] < qinfo->RequiredNpcOrGoCount[j])
- return true;
- }
- }
- }
- return false;
- }
- void Player::UpdateForQuestWorldObjects()
- {
- if (m_clientGUIDs.empty())
- return;
- UpdateData udata;
- WorldPacket packet;
- for (ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
- {
- if (IS_GAMEOBJECT_GUID(*itr))
- {
- if (GameObject* obj = HashMapHolder<GameObject>::Find(*itr))
- obj->BuildValuesUpdateBlockForPlayer(&udata, this);
- }
- else if (IS_CRE_OR_VEH_GUID(*itr))
- {
- Creature* obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
- if (!obj)
- continue;
- // check if this unit requires quest specific flags
- if (!obj->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK))
- continue;
- SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(obj->GetEntry());
- for (SpellClickInfoContainer::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
- {
- //! This code doesn't look right, but it was logically converted to condition system to do the exact
- //! same thing it did before. It definitely needs to be overlooked for intended functionality.
- ConditionList conds = sConditionMgr->GetConditionsForSpellClickEvent(obj->GetEntry(), _itr->second.spellId);
- bool buildUpdateBlock = false;
- for (ConditionList::const_iterator jtr = conds.begin(); jtr != conds.end() && !buildUpdateBlock; ++jtr)
- if ((*jtr)->ConditionType == CONDITION_QUESTREWARDED || (*jtr)->ConditionType == CONDITION_QUESTTAKEN)
- buildUpdateBlock = true;
- if (buildUpdateBlock)
- {
- obj->BuildCreateUpdateBlockForPlayer(&udata, this);
- break;
- }
- }
- }
- }
- udata.BuildPacket(&packet);
- GetSession()->SendPacket(&packet);
- }
- void Player::SummonIfPossible(bool agree)
- {
- if (!agree)
- {
- m_summon_expire = 0;
- return;
- }
- // expire and auto declined
- if (m_summon_expire < time(NULL))
- return;
- // stop taxi flight at summon
- if (isInFlight())
- {
- GetMotionMaster()->MovementExpired();
- CleanupAfterTaxiFlight();
- }
- // drop flag at summon
- // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
- if (Battleground* bg = GetBattleground())
- bg->EventPlayerDroppedFlag(this);
- m_summon_expire = 0;
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
- TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z, GetOrientation());
- }
- void Player::RemoveItemDurations(Item* item)
- {
- for (ItemDurationList::iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
- {
- if (*itr == item)
- {
- m_itemDuration.erase(itr);
- break;
- }
- }
- }
- void Player::AddItemDurations(Item* item)
- {
- if (item->GetUInt32Value(ITEM_FIELD_DURATION))
- {
- m_itemDuration.push_back(item);
- item->SendTimeUpdate(this);
- }
- }
- void Player::AutoUnequipOffhandIfNeed(bool force /*= false*/)
- {
- Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
- if (!offItem)
- return;
- // unequip offhand weapon if player doesn't have dual wield anymore
- if (!CanDualWield() && (offItem->GetTemplate()->InventoryType == INVTYPE_WEAPONOFFHAND || offItem->GetTemplate()->InventoryType == INVTYPE_WEAPON))
- force = true;
- // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
- if (!force && (CanTitanGrip() || (offItem->GetTemplate()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
- return;
- ItemPosCountVec off_dest;
- uint8 off_msg = CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false);
- if (off_msg == EQUIP_ERR_OK)
- {
- RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
- StoreItem(off_dest, offItem, true);
- }
- else
- {
- MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- offItem->DeleteFromInventoryDB(trans); // deletes item from character's inventory
- offItem->SaveToDB(trans); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
- std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
- MailDraft(subject, "There were problems with equipping one or several items").AddItem(offItem).SendMailTo(trans, this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
- CharacterDatabase.CommitTransaction(trans);
- }
- }
- OutdoorPvP* Player::GetOutdoorPvP() const
- {
- return sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId());
- }
- bool Player::HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem)
- {
- if (spellInfo->EquippedItemClass < 0)
- return true;
- // scan other equipped items for same requirements (mostly 2 daggers/etc)
- // for optimize check 2 used cases only
- switch (spellInfo->EquippedItemClass)
- {
- case ITEM_CLASS_WEAPON:
- {
- for (uint8 i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
- if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
- break;
- }
- case ITEM_CLASS_ARMOR:
- {
- // tabard not have dependent spells
- for (uint8 i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
- if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
- // shields can be equipped to offhand slot
- if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
- if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
- // ranged slot can have some armor subclasses
- if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
- if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
- break;
- }
- default:
- sLog->outError(LOG_FILTER_PLAYER, "HasItemFitToSpellRequirements: Not handled spell requirement for item class %u", spellInfo->EquippedItemClass);
- break;
- }
- return false;
- }
- bool Player::CanNoReagentCast(SpellInfo const* spellInfo) const
- {
- // don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP
- if (spellInfo->AttributesEx5 & SPELL_ATTR5_NO_REAGENT_WHILE_PREP &&
- HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
- return true;
- // Check no reagent use mask
- flag96 noReagentMask;
- noReagentMask[0] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1);
- noReagentMask[1] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+1);
- noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
- if (spellInfo->SpellFamilyFlags & noReagentMask)
- return true;
- return false;
- }
- void Player::RemoveItemDependentAurasAndCasts(Item* pItem)
- {
- for (AuraMap::iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end();)
- {
- Aura* aura = itr->second;
- // skip passive (passive item dependent spells work in another way) and not self applied auras
- SpellInfo const* spellInfo = aura->GetSpellInfo();
- if (aura->IsPassive() || aura->GetCasterGUID() != GetGUID())
- {
- ++itr;
- continue;
- }
- // skip if not item dependent or have alternative item
- if (HasItemFitToSpellRequirements(spellInfo, pItem))
- {
- ++itr;
- continue;
- }
- // no alt item, remove aura, restart check
- RemoveOwnedAura(itr);
- }
- // currently casted spells can be dependent from item
- for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
- if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
- if (spell->getState() != SPELL_STATE_DELAYED && !HasItemFitToSpellRequirements(spell->m_spellInfo, pItem))
- InterruptSpell(CurrentSpellTypes(i));
- }
- uint32 Player::GetResurrectionSpellId()
- {
- // search priceless resurrection possibilities
- uint32 prio = 0;
- uint32 spell_id = 0;
- AuraEffectList const& dummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
- {
- // Soulstone Resurrection // prio: 3 (max, non death persistent)
- if (prio < 2 && (*itr)->GetSpellInfo()->SpellVisual[0] == 99 && (*itr)->GetSpellInfo()->SpellIconID == 92)
- {
- switch ((*itr)->GetId())
- {
- case 20707: spell_id = 3026; break; // rank 1
- case 20762: spell_id = 20758; break; // rank 2
- case 20763: spell_id = 20759; break; // rank 3
- case 20764: spell_id = 20760; break; // rank 4
- case 20765: spell_id = 20761; break; // rank 5
- case 27239: spell_id = 27240; break; // rank 6
- case 47883: spell_id = 47882; break; // rank 7
- default:
- sLog->outError(LOG_FILTER_PLAYER, "Unhandled spell %u: S.Resurrection", (*itr)->GetId());
- continue;
- }
- prio = 3;
- }
- // Twisting Nether // prio: 2 (max)
- else if ((*itr)->GetId() == 23701 && roll_chance_i(10))
- {
- prio = 2;
- spell_id = 23700;
- }
- }
- // Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life
- if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasAura(58059) || HasItemCount(17030, 1)))
- spell_id = 21169;
- return spell_id;
- }
- // Used in triggers for check "Only to targets that grant experience or honor" req
- bool Player::isHonorOrXPTarget(Unit* victim)
- {
- uint8 v_level = victim->getLevel();
- uint8 k_grey = Trinity::XP::GetGrayLevel(getLevel());
- // Victim level less gray level
- if (v_level <= k_grey)
- return false;
- if (victim->GetTypeId() == TYPEID_UNIT)
- {
- if (victim->ToCreature()->isTotem() ||
- victim->ToCreature()->isPet() ||
- victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
- return false;
- }
- return true;
- }
- bool Player::GetsRecruitAFriendBonus(bool forXP)
- {
- bool recruitAFriend = false;
- if (getLevel() <= sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL) || !forXP)
- {
- if (Group* group = this->GetGroup())
- {
- for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* player = itr->getSource();
- if (!player)
- continue;
- if (!player->IsAtRecruitAFriendDistance(this))
- continue; // member (alive or dead) or his corpse at req. distance
- if (forXP)
- {
- // level must be allowed to get RaF bonus
- if (player->getLevel() > sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL))
- continue;
- // level difference must be small enough to get RaF bonus, UNLESS we are lower level
- if (player->getLevel() < getLevel())
- if (uint8(getLevel() - player->getLevel()) > sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL_DIFFERENCE))
- continue;
- }
- bool ARecruitedB = (player->GetSession()->GetRecruiterId() == GetSession()->GetAccountId());
- bool BRecruitedA = (GetSession()->GetRecruiterId() == player->GetSession()->GetAccountId());
- if (ARecruitedB || BRecruitedA)
- {
- recruitAFriend = true;
- break;
- }
- }
- }
- }
- return recruitAFriend;
- }
- void Player::RewardPlayerAndGroupAtKill(Unit* victim, bool isBattleGround)
- {
- KillRewarder(this, victim, isBattleGround).Reward();
- }
- void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
- {
- if (!pRewardSource)
- return;
- uint64 creature_guid = (pRewardSource->GetTypeId() == TYPEID_UNIT) ? pRewardSource->GetGUID() : uint64(0);
- // prepare data for near group iteration
- if (Group* group = GetGroup())
- {
- for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* player = itr->getSource();
- if (!player)
- continue;
- if (!player->IsAtGroupRewardDistance(pRewardSource))
- continue; // member (alive or dead) or his corpse at req. distance
- // quest objectives updated only for alive group member or dead but with not released body
- if (player->isAlive()|| !player->GetCorpse())
- player->KilledMonsterCredit(creature_id, creature_guid);
- }
- }
- else // if (!group)
- KilledMonsterCredit(creature_id, creature_guid);
- }
- bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
- {
- if (!pRewardSource)
- return false;
- const WorldObject* player = GetCorpse();
- if (!player || isAlive())
- player = this;
- if (player->GetMapId() != pRewardSource->GetMapId() || player->GetInstanceId() != pRewardSource->GetInstanceId())
- return false;
- return pRewardSource->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_GROUP_XP_DISTANCE);
- }
- bool Player::IsAtRecruitAFriendDistance(WorldObject const* pOther) const
- {
- if (!pOther)
- return false;
- const WorldObject* player = GetCorpse();
- if (!player || isAlive())
- player = this;
- if (player->GetMapId() != pOther->GetMapId() || player->GetInstanceId() != pOther->GetInstanceId())
- return false;
- return pOther->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_MAX_RECRUIT_A_FRIEND_DISTANCE);
- }
- uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
- {
- Item* item = GetWeaponForAttack(attType, true);
- // unarmed only with base attack
- if (attType != BASE_ATTACK && !item)
- return 0;
- // weapon skill or (unarmed for base attack and for fist weapons)
- uint32 skill = (item && item->GetSkill() != SKILL_FIST_WEAPONS) ? item->GetSkill() : uint32(SKILL_UNARMED);
- return GetBaseSkillValue(skill);
- }
- void Player::ResurectUsingRequestData()
- {
- /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
- TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
- if (IsBeingTeleported())
- {
- ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
- return;
- }
- ResurrectPlayer(0.0f, false);
- if (GetMaxHealth() > m_resurrectHealth)
- SetHealth(m_resurrectHealth);
- else
- SetFullHealth();
- if (GetMaxPower(POWER_MANA) > m_resurrectMana)
- SetPower(POWER_MANA, m_resurrectMana);
- else
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
- SetPower(POWER_RAGE, 0);
- SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
- SpawnCorpseBones();
- }
- void Player::SetClientControl(Unit* target, uint8 allowMove)
- {
- WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
- data.append(target->GetPackGUID());
- data << uint8(allowMove);
- GetSession()->SendPacket(&data);
- if (target == this)
- SetMover(this);
- }
- void Player::UpdateZoneDependentAuras(uint32 newZone)
- {
- // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
- SpellAreaForAreaMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(newZone);
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if (itr->second->autocast && itr->second->IsFitToRequirements(this, newZone, 0))
- if (!HasAura(itr->second->spellId))
- CastSpell(this, itr->second->spellId, true);
- }
- void Player::UpdateAreaDependentAuras(uint32 newArea)
- {
- // remove auras from spells with area limitations
- for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
- {
- // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
- if (iter->second->GetSpellInfo()->CheckLocation(GetMapId(), m_zoneUpdateId, newArea, this) != SPELL_CAST_OK)
- RemoveOwnedAura(iter);
- else
- ++iter;
- }
- // some auras applied at subzone enter
- SpellAreaForAreaMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(newArea);
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, newArea))
- if (!HasAura(itr->second->spellId))
- CastSpell(this, itr->second->spellId, true);
- if (newArea == 4273 && GetVehicle() && GetPositionX() > 400) // Ulduar
- {
- switch (GetVehicleBase()->GetEntry())
- {
- case 33062:
- case 33109:
- case 33060:
- GetVehicle()->Dismiss();
- break;
- }
- }
- }
- uint32 Player::GetCorpseReclaimDelay(bool pvp) const
- {
- if (pvp)
- {
- if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP))
- return copseReclaimDelay[0];
- }
- else if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))
- return 0;
- time_t now = time(NULL);
- // 0..2 full period
- // should be ceil(x)-1 but not floor(x)
- uint64 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now)/DEATH_EXPIRE_STEP : 0;
- return copseReclaimDelay[count];
- }
- void Player::UpdateCorpseReclaimDelay()
- {
- bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
- if ((pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
- (!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
- return;
- time_t now = time(NULL);
- if (now < m_deathExpireTime)
- {
- // full and partly periods 1..3
- uint64 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
- if (count < MAX_DEATH_COUNT)
- m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
- else
- m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
- }
- else
- m_deathExpireTime = now+DEATH_EXPIRE_STEP;
- }
- void Player::SendCorpseReclaimDelay(bool load)
- {
- Corpse* corpse = GetCorpse();
- if (load && !corpse)
- return;
- bool pvp;
- if (corpse)
- pvp = (corpse->GetType() == CORPSE_RESURRECTABLE_PVP);
- else
- pvp = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH);
- time_t delay;
- if (load)
- {
- if (corpse->GetGhostTime() > m_deathExpireTime)
- return;
- uint64 count;
- if ((pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
- (!pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
- {
- count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
- if (count >= MAX_DEATH_COUNT)
- count = MAX_DEATH_COUNT-1;
- }
- else
- count=0;
- time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
- time_t now = time(NULL);
- if (now >= expected_time)
- return;
- delay = expected_time-now;
- }
- else
- delay = GetCorpseReclaimDelay(pvp);
- if (!delay)
- return;
- //! corpse reclaim delay 30 * 1000ms or longer at often deaths
- WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
- data << uint32(delay*IN_MILLISECONDS);
- GetSession()->SendPacket(&data);
- }
- Player* Player::GetNextRandomRaidMember(float radius)
- {
- Group* group = GetGroup();
- if (!group)
- return NULL;
- std::vector<Player*> nearMembers;
- nearMembers.reserve(group->GetMembersCount());
- for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
- // IsHostileTo check duel and controlled by enemy
- if (Target && Target != this && IsWithinDistInMap(Target, radius) &&
- !Target->HasInvisibilityAura() && !IsHostileTo(Target))
- nearMembers.push_back(Target);
- }
- if (nearMembers.empty())
- return NULL;
- uint32 randTarget = urand(0, nearMembers.size()-1);
- return nearMembers[randTarget];
- }
- PartyResult Player::CanUninviteFromGroup() const
- {
- Group const* grp = GetGroup();
- if (!grp)
- return ERR_NOT_IN_GROUP;
- if (grp->isLFGGroup())
- {
- uint64 gguid = grp->GetGUID();
- if (!sLFGMgr->GetKicksLeft(gguid))
- return ERR_PARTY_LFG_BOOT_LIMIT;
- LfgState state = sLFGMgr->GetState(gguid);
- if (state == LFG_STATE_BOOT)
- return ERR_PARTY_LFG_BOOT_IN_PROGRESS;
- if (grp->GetMembersCount() <= sLFGMgr->GetVotesNeeded(gguid))
- return ERR_PARTY_LFG_BOOT_TOO_FEW_PLAYERS;
- if (state == LFG_STATE_FINISHED_DUNGEON)
- return ERR_PARTY_LFG_BOOT_DUNGEON_COMPLETE;
- if (grp->isRollLootActive())
- return ERR_PARTY_LFG_BOOT_LOOT_ROLLS;
- // TODO: Should also be sent when anyone has recently left combat, with an aprox ~5 seconds timer.
- for (GroupReference const* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
- if (itr->getSource() && itr->getSource()->isInCombat())
- return ERR_PARTY_LFG_BOOT_IN_COMBAT;
- /* Missing support for these types
- return ERR_PARTY_LFG_BOOT_COOLDOWN_S;
- return ERR_PARTY_LFG_BOOT_NOT_ELIGIBLE_S;
- */
- }
- else
- {
- if (!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
- return ERR_NOT_LEADER;
- if (InBattleground())
- return ERR_INVITE_RESTRICTED;
- }
- return ERR_PARTY_RESULT_OK;
- }
- bool Player::isUsingLfg()
- {
- uint64 guid = GetGUID();
- return sLFGMgr->GetState(guid) != LFG_STATE_NONE;
- }
- void Player::SetBattlegroundRaid(Group* group, int8 subgroup)
- {
- //we must move references from m_group to m_originalGroup
- SetOriginalGroup(GetGroup(), GetSubGroup());
- m_group.unlink();
- m_group.link(group, this);
- m_group.setSubGroup((uint8)subgroup);
- }
- void Player::RemoveFromBattlegroundRaid()
- {
- //remove existing reference
- m_group.unlink();
- if (Group* group = GetOriginalGroup())
- {
- m_group.link(group, this);
- m_group.setSubGroup(GetOriginalSubGroup());
- }
- SetOriginalGroup(NULL);
- }
- void Player::SetOriginalGroup(Group* group, int8 subgroup)
- {
- if (group == NULL)
- m_originalGroup.unlink();
- else
- {
- // never use SetOriginalGroup without a subgroup unless you specify NULL for group
- ASSERT(subgroup >= 0);
- m_originalGroup.link(group, this);
- m_originalGroup.setSubGroup((uint8)subgroup);
- }
- }
- void Player::UpdateUnderwaterState(Map* m, float x, float y, float z)
- {
- LiquidData liquid_status;
- ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
- if (!res)
- {
- m_MirrorTimerFlags &= ~(UNDERWATER_INWATER | UNDERWATER_INLAVA | UNDERWATER_INSLIME | UNDERWARER_INDARKWATER);
- if (_lastLiquid && _lastLiquid->SpellId)
- RemoveAurasDueToSpell(_lastLiquid->SpellId);
- _lastLiquid = NULL;
- return;
- }
- if (uint32 liqEntry = liquid_status.entry)
- {
- LiquidTypeEntry const* liquid = sLiquidTypeStore.LookupEntry(liqEntry);
- if (_lastLiquid && _lastLiquid->SpellId && _lastLiquid->Id != liqEntry)
- RemoveAurasDueToSpell(_lastLiquid->SpellId);
- if (liquid && liquid->SpellId)
- {
- if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER))
- CastSpell(this, liquid->SpellId, true);
- else
- RemoveAurasDueToSpell(liquid->SpellId);
- }
- _lastLiquid = liquid;
- }
- else if (_lastLiquid && _lastLiquid->SpellId)
- {
- RemoveAurasDueToSpell(_lastLiquid->SpellId);
- _lastLiquid = NULL;
- }
- // All liquids type - check under water position
- if (liquid_status.type_flags & (MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN | MAP_LIQUID_TYPE_MAGMA | MAP_LIQUID_TYPE_SLIME))
- {
- if (res & LIQUID_MAP_UNDER_WATER)
- m_MirrorTimerFlags |= UNDERWATER_INWATER;
- else
- m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
- }
- // Allow travel in dark water on taxi or transport
- if ((liquid_status.type_flags & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
- m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
- else
- m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
- // in lava check, anywhere in lava level
- if (liquid_status.type_flags & MAP_LIQUID_TYPE_MAGMA)
- {
- if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK))
- m_MirrorTimerFlags |= UNDERWATER_INLAVA;
- else
- m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
- }
- // in slime check, anywhere in slime level
- if (liquid_status.type_flags & MAP_LIQUID_TYPE_SLIME)
- {
- if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK))
- m_MirrorTimerFlags |= UNDERWATER_INSLIME;
- else
- m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
- }
- }
- void Player::SetCanParry(bool value)
- {
- if (m_canParry == value)
- return;
- m_canParry = value;
- UpdateParryPercentage();
- }
- void Player::SetCanBlock(bool value)
- {
- if (m_canBlock == value)
- return;
- m_canBlock = value;
- UpdateBlockPercentage();
- }
- bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
- {
- for (ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
- if (itr->pos == pos)
- return true;
- return false;
- }
- void Player::StopCastingBindSight()
- {
- if (WorldObject* target = GetViewpoint())
- {
- if (target->isType(TYPEMASK_UNIT))
- {
- ((Unit*)target)->RemoveAurasByType(SPELL_AURA_BIND_SIGHT, GetGUID());
- ((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS, GetGUID());
- ((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET, GetGUID());
- }
- }
- }
- void Player::SetViewpoint(WorldObject* target, bool apply)
- {
- if (apply)
- {
- sLog->outDebug(LOG_FILTER_MAPS, "Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName(), target->GetEntry(), target->GetTypeId());
- if (!AddUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
- {
- sLog->outFatal(LOG_FILTER_PLAYER, "Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName());
- return;
- }
- // farsight dynobj or puppet may be very far away
- UpdateVisibilityOf(target);
- if (target->isType(TYPEMASK_UNIT) && !GetVehicle())
- ((Unit*)target)->AddPlayerToVision(this);
- }
- else
- {
- sLog->outDebug(LOG_FILTER_MAPS, "Player::CreateViewpoint: Player %s remove seer", GetName());
- if (!RemoveUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
- {
- sLog->outFatal(LOG_FILTER_PLAYER, "Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName());
- return;
- }
- if (target->isType(TYPEMASK_UNIT) && !GetVehicle())
- ((Unit*)target)->RemovePlayerFromVision(this);
- //must immediately set seer back otherwise may crash
- m_seer = this;
- //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0);
- //GetSession()->SendPacket(&data);
- }
- }
- WorldObject* Player::GetViewpoint() const
- {
- if (uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
- return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER);
- return NULL;
- }
- bool Player::CanUseBattlegroundObject()
- {
- // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
- // maybe gameobject code should handle that ForceReaction usage
- // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
- return (//InBattleground() && // in battleground - not need, check in other cases
- //!IsMounted() && - not correct, player is dismounted when he clicks on flag
- //player cannot use object when he is invulnerable (immune)
- !isTotalImmune() && // not totally immune
- //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
- !HasStealthAura() && // not stealthed
- !HasInvisibilityAura() && // not invisible
- !HasAura(SPELL_RECENTLY_DROPPED_FLAG) && // can't pickup
- isAlive() // live player
- );
- }
- bool Player::CanCaptureTowerPoint()
- {
- return (!HasStealthAura() && // not stealthed
- !HasInvisibilityAura() && // not invisible
- isAlive() // live player
- );
- }
- uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin)
- {
- uint8 level = getLevel();
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL; // max level in this dbc
- uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
- uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
- uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
- uint8 skincolor = GetByteValue(PLAYER_BYTES, 0);
- if ((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->hair_id == skincolor)))
- return 0;
- GtBarberShopCostBaseEntry const* bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
- if (!bsc) // shouldn't happen
- return 0xFFFFFFFF;
- float cost = 0;
- if (hairstyle != newhairstyle)
- cost += bsc->cost; // full price
- if ((haircolor != newhaircolor) && (hairstyle == newhairstyle))
- cost += bsc->cost * 0.5f; // +1/2 of price
- if (facialhair != newfacialhair)
- cost += bsc->cost * 0.75f; // +3/4 of price
- if (newSkin && skincolor != newSkin->hair_id)
- cost += bsc->cost * 0.75f; // +5/6 of price
- return uint32(cost);
- }
- void Player::InitGlyphsForLevel()
- {
- for (uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
- if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(i))
- if (gs->Order)
- SetGlyphSlot(gs->Order - 1, gs->Id);
- uint8 level = getLevel();
- uint32 value = 0;
- // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
- if (level >= 15)
- value |= (0x01 | 0x02);
- if (level >= 30)
- value |= 0x08;
- if (level >= 50)
- value |= 0x04;
- if (level >= 70)
- value |= 0x10;
- if (level >= 80)
- value |= 0x20;
- SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
- }
- bool Player::isTotalImmune()
- {
- AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
- uint32 immuneMask = 0;
- for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
- {
- immuneMask |= (*itr)->GetMiscValue();
- if (immuneMask & SPELL_SCHOOL_MASK_ALL) // total immunity
- return true;
- }
- return false;
- }
- bool Player::HasTitle(uint32 bitIndex)
- {
- if (bitIndex > MAX_TITLE_INDEX)
- return false;
- uint32 fieldIndexOffset = bitIndex / 32;
- uint32 flag = 1 << (bitIndex % 32);
- return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
- }
- void Player::SetTitle(CharTitlesEntry const* title, bool lost)
- {
- uint32 fieldIndexOffset = title->bit_index / 32;
- uint32 flag = 1 << (title->bit_index % 32);
- if (lost)
- {
- if (!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
- return;
- RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
- }
- else
- {
- if (HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
- return;
- SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
- }
- WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
- data << uint32(title->bit_index);
- data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
- GetSession()->SendPacket(&data);
- }
- bool Player::isTotalImmunity()
- {
- AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
- for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
- {
- if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_ALL) !=0) // total immunity
- {
- return true;
- }
- if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) !=0) // physical damage immunity
- {
- for (AuraEffectList::const_iterator i = immune.begin(); i != immune.end(); ++i)
- {
- if (((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_MAGIC) !=0) // magic immunity
- {
- return true;
- }
- }
- }
- }
- return false;
- }
- void Player::UpdateCharmedAI()
- {
- //This should only called in Player::Update
- Creature* charmer = GetCharmer()->ToCreature();
- //kill self if charm aura has infinite duration
- if (charmer->IsInEvadeMode())
- {
- AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_CHARM);
- for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
- if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent())
- {
- charmer->DealDamage(this, GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
- return;
- }
- }
- if (!charmer->isInCombat())
- GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
- Unit* target = getVictim();
- if (!target || !charmer->IsValidAttackTarget(target))
- {
- target = charmer->SelectNearestTarget();
- if (!target)
- return;
- GetMotionMaster()->MoveChase(target);
- Attack(target, true);
- }
- }
- uint32 Player::GetRuneBaseCooldown(uint8 index)
- {
- uint8 rune = GetBaseRune(index);
- uint32 cooldown = RUNE_BASE_COOLDOWN;
- AuraEffectList const& regenAura = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
- for (AuraEffectList::const_iterator i = regenAura.begin();i != regenAura.end(); ++i)
- {
- if ((*i)->GetMiscValue() == POWER_RUNE && (*i)->GetMiscValueB() == rune)
- cooldown = cooldown*(100-(*i)->GetAmount())/100;
- }
- return cooldown;
- }
- void Player::RemoveRunesByAuraEffect(AuraEffect const* aura)
- {
- for (uint8 i = 0; i < MAX_RUNES; ++i)
- {
- if (m_runes->runes[i].ConvertAura == aura)
- {
- ConvertRune(i, GetBaseRune(i));
- SetRuneConvertAura(i, NULL);
- }
- }
- }
- void Player::RestoreBaseRune(uint8 index)
- {
- AuraEffect const* aura = m_runes->runes[index].ConvertAura;
- // If rune was converted by a non-pasive aura that still active we should keep it converted
- if (aura && !(aura->GetSpellInfo()->Attributes & SPELL_ATTR0_PASSIVE))
- return;
- ConvertRune(index, GetBaseRune(index));
- SetRuneConvertAura(index, NULL);
- // Don't drop passive talents providing rune convertion
- if (!aura || aura->GetAuraType() != SPELL_AURA_CONVERT_RUNE)
- return;
- for (uint8 i = 0; i < MAX_RUNES; ++i)
- {
- if (aura == m_runes->runes[i].ConvertAura)
- return;
- }
- aura->GetBase()->Remove();
- }
- void Player::ConvertRune(uint8 index, RuneType newType)
- {
- SetCurrentRune(index, newType);
- WorldPacket data(SMSG_CONVERT_RUNE, 2);
- data << uint8(index);
- data << uint8(newType);
- GetSession()->SendPacket(&data);
- }
- void Player::ResyncRunes(uint8 count)
- {
- WorldPacket data(SMSG_RESYNC_RUNES, 4 + count * 2);
- data << uint32(count);
- for (uint32 i = 0; i < count; ++i)
- {
- data << uint8(GetCurrentRune(i)); // rune type
- data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
- }
- GetSession()->SendPacket(&data);
- }
- void Player::AddRunePower(uint8 index)
- {
- WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
- data << uint32(1 << index); // mask (0x00-0x3F probably)
- GetSession()->SendPacket(&data);
- }
- static RuneType runeSlotTypes[MAX_RUNES] =
- {
- /*0*/ RUNE_BLOOD,
- /*1*/ RUNE_BLOOD,
- /*2*/ RUNE_UNHOLY,
- /*3*/ RUNE_UNHOLY,
- /*4*/ RUNE_FROST,
- /*5*/ RUNE_FROST
- };
- void Player::InitRunes()
- {
- if (getClass() != CLASS_DEATH_KNIGHT)
- return;
- m_runes = new Runes;
- m_runes->runeState = 0;
- m_runes->lastUsedRune = RUNE_BLOOD;
- for (uint8 i = 0; i < MAX_RUNES; ++i)
- {
- SetBaseRune(i, runeSlotTypes[i]); // init base types
- SetCurrentRune(i, runeSlotTypes[i]); // init current types
- SetRuneCooldown(i, 0); // reset cooldowns
- SetRuneConvertAura(i, NULL);
- m_runes->SetRuneState(i);
- }
- for (uint8 i = 0; i < NUM_RUNE_TYPES; ++i)
- SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
- }
- bool Player::IsBaseRuneSlotsOnCooldown(RuneType runeType) const
- {
- for (uint8 i = 0; i < MAX_RUNES; ++i)
- if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
- return false;
- return true;
- }
- void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
- {
- Loot loot;
- loot.FillLoot (loot_id, store, this, true);
- uint32 max_slot = loot.GetMaxSlotInLootFor(this);
- for (uint32 i = 0; i < max_slot; ++i)
- {
- LootItem* lootItem = loot.LootItemInSlot(i, this);
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreNewItem(bag, slot, dest, lootItem->itemid, lootItem->count);
- if (msg != EQUIP_ERR_OK && slot != NULL_SLOT)
- msg = CanStoreNewItem(bag, NULL_SLOT, dest, lootItem->itemid, lootItem->count);
- if (msg != EQUIP_ERR_OK && bag != NULL_BAG)
- msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, lootItem->itemid, lootItem->count);
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError(msg, NULL, NULL, lootItem->itemid);
- continue;
- }
- Item* pItem = StoreNewItem(dest, lootItem->itemid, true, lootItem->randomPropertyId);
- SendNewItem(pItem, lootItem->count, false, false, broadcast);
- }
- }
- void Player::StoreLootItem(uint8 lootSlot, Loot* loot)
- {
- QuestItem* qitem = NULL;
- QuestItem* ffaitem = NULL;
- QuestItem* conditem = NULL;
- LootItem* item = loot->LootItemInSlot(lootSlot, this, &qitem, &ffaitem, &conditem);
- if (!item)
- {
- SendEquipError(EQUIP_ERR_ALREADY_LOOTED, NULL, NULL);
- return;
- }
- // questitems use the blocked field for other purposes
- if (!qitem && item->is_blocked)
- {
- SendLootRelease(GetLootGUID());
- return;
- }
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item->itemid, item->count);
- if (msg == EQUIP_ERR_OK)
- {
- AllowedLooterSet looters = item->GetAllowedLooters();
- Item* newitem = StoreNewItem(dest, item->itemid, true, item->randomPropertyId, looters);
- if (qitem)
- {
- qitem->is_looted = true;
- //freeforall is 1 if everyone's supposed to get the quest item.
- if (item->freeforall || loot->GetPlayerQuestItems().size() == 1)
- SendNotifyLootItemRemoved(lootSlot);
- else
- loot->NotifyQuestItemRemoved(qitem->index);
- }
- else
- {
- if (ffaitem)
- {
- //freeforall case, notify only one player of the removal
- ffaitem->is_looted = true;
- SendNotifyLootItemRemoved(lootSlot);
- }
- else
- {
- //not freeforall, notify everyone
- if (conditem)
- conditem->is_looted = true;
- loot->NotifyItemRemoved(lootSlot);
- }
- }
- //if only one person is supposed to loot the item, then set it to looted
- if (!item->freeforall)
- item->is_looted = true;
- --loot->unlootedCount;
- SendNewItem(newitem, uint32(item->count), false, false, true);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, item->itemid, item->count);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE, loot->loot_type, item->count);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM, item->itemid, item->count);
- }
- else
- SendEquipError(msg, NULL, NULL, item->itemid);
- }
- uint32 Player::CalculateTalentsPoints() const
- {
- uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
- if (getClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609)
- return uint32(base_talent * sWorld->getRate(RATE_TALENT));
- uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
- talentPointsForLevel += m_questRewardTalentCount;
- if (talentPointsForLevel > base_talent)
- talentPointsForLevel = base_talent;
- return uint32(talentPointsForLevel * sWorld->getRate(RATE_TALENT));
- }
- bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
- {
- // continent checked in SpellInfo::CheckLocation at cast and area update
- uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
- return v_map != 571 || HasSpell(54197); // Cold Weather Flying
- }
- void Player::learnSpellHighRank(uint32 spellid)
- {
- learnSpell(spellid, false);
- if (uint32 next = sSpellMgr->GetNextSpellInChain(spellid))
- learnSpellHighRank(next);
- }
- void Player::_LoadSkills(PreparedQueryResult result)
- {
- // 0 1 2
- // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
- uint32 count = 0;
- if (result)
- {
- do
- {
- Field* fields = result->Fetch();
- uint16 skill = fields[0].GetUInt16();
- uint16 value = fields[1].GetUInt16();
- uint16 max = fields[2].GetUInt16();
- SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(skill);
- if (!pSkill)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
- continue;
- }
- // set fixed skill ranges
- switch (GetSkillRangeType(pSkill, false))
- {
- case SKILL_RANGE_LANGUAGE: // 300..300
- value = max = 300;
- break;
- case SKILL_RANGE_MONO: // 1..1, grey monolite bar
- value = max = 1;
- break;
- default:
- break;
- }
- if (value == 0)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt16(1, skill);
- CharacterDatabase.Execute(stmt);
- continue;
- }
- // enable unlearn button for primary professions only
- if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
- SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill, 1));
- else
- SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill, 0));
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count), MAKE_SKILL_VALUE(value, max));
- SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count), 0);
- mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
- learnSkillRewardedSpells(skill, value);
- ++count;
- if (count >= PLAYER_MAX_SKILLS) // client limit
- {
- sLog->outError(LOG_FILTER_PLAYER, "Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
- break;
- }
- }
- while (result->NextRow());
- }
- for (; count < PLAYER_MAX_SKILLS; ++count)
- {
- SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count), 0);
- SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count), 0);
- }
- // special settings
- if (getClass() == CLASS_DEATH_KNIGHT)
- {
- uint8 base_level = std::min(getLevel(), uint8(sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)));
- if (base_level < 1)
- base_level = 1;
- uint16 base_skill = (base_level-1)*5; // 270 at starting level 55
- if (base_skill < 1)
- base_skill = 1; // skill mast be known and then > 0 in any case
- if (GetPureSkillValue(SKILL_FIRST_AID) < base_skill)
- SetSkill(SKILL_FIRST_AID, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_AXES) < base_skill)
- SetSkill(SKILL_AXES, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_DEFENSE) < base_skill)
- SetSkill(SKILL_DEFENSE, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_POLEARMS) < base_skill)
- SetSkill(SKILL_POLEARMS, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_SWORDS) < base_skill)
- SetSkill(SKILL_SWORDS, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_2H_AXES) < base_skill)
- SetSkill(SKILL_2H_AXES, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_2H_SWORDS) < base_skill)
- SetSkill(SKILL_2H_SWORDS, 0, base_skill, base_skill);
- if (GetPureSkillValue(SKILL_UNARMED) < base_skill)
- SetSkill(SKILL_UNARMED, 0, base_skill, base_skill);
- }
- }
- uint32 Player::GetPhaseMaskForSpawn() const
- {
- uint32 phase = PHASEMASK_NORMAL;
- if (!isGameMaster())
- phase = GetPhaseMask();
- else
- {
- AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
- if (!phases.empty())
- phase = phases.front()->GetMiscValue();
- }
- // some aura phases include 1 normal map in addition to phase itself
- if (uint32 n_phase = phase & ~PHASEMASK_NORMAL)
- return n_phase;
- return PHASEMASK_NORMAL;
- }
- InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
- {
- ItemTemplate const* pProto = pItem->GetTemplate();
- // proto based limitations
- if (InventoryResult res = CanEquipUniqueItem(pProto, eslot, limit_count))
- return res;
- // check unique-equipped on gems
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if (!enchant_id)
- continue;
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!enchantEntry)
- continue;
- ItemTemplate const* pGem = sObjectMgr->GetItemTemplate(enchantEntry->GemID);
- if (!pGem)
- continue;
- // include for check equip another gems with same limit category for not equipped item (and then not counted)
- uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
- ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
- if (InventoryResult res = CanEquipUniqueItem(pGem, eslot, gem_limit_count))
- return res;
- }
- return EQUIP_ERR_OK;
- }
- InventoryResult Player::CanEquipUniqueItem(ItemTemplate const* itemProto, uint8 except_slot, uint32 limit_count) const
- {
- // check unique-equipped on item
- if (itemProto->Flags & ITEM_PROTO_FLAG_UNIQUE_EQUIPPED)
- {
- // there is an equip limit on this item
- if (HasItemOrGemWithIdEquipped(itemProto->ItemId, 1, except_slot))
- return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
- }
- // check unique-equipped limit
- if (itemProto->ItemLimitCategory)
- {
- ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
- if (!limitEntry)
- return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
- // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
- if (limit_count > limitEntry->maxCount)
- return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED;
- // there is an equip limit on this item
- if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory, limitEntry->maxCount - limit_count + 1, except_slot))
- return EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED;
- }
- return EQUIP_ERR_OK;
- }
- void Player::HandleFall(MovementInfo const& movementInfo)
- {
- // calculate total z distance of the fall
- float z_diff = m_lastFallZ - movementInfo.pos.GetPositionZ();
- //sLog->outDebug("zDiff = %f", z_diff);
- //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
- // 14.57 can be calculated by resolving damageperc formula below to 0
- if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
- !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
- !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL))
- {
- //Safe fall, fall height reduction
- int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
- float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
- if (damageperc > 0)
- {
- uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld->getRate(RATE_DAMAGE_FALL));
- float height = movementInfo.pos.m_positionZ;
- UpdateGroundPositionZ(movementInfo.pos.m_positionX, movementInfo.pos.m_positionY, height);
- if (damage > 0)
- {
- //Prevent fall damage from being more than the player maximum health
- if (damage > GetMaxHealth())
- damage = GetMaxHealth();
- // Gust of Wind
- if (HasAura(43621))
- damage = GetMaxHealth()/2;
- uint32 original_health = GetHealth();
- uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
- // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
- if (isAlive() && final_damage < original_health)
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
- }
- //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
- sLog->outDebug(LOG_FILTER_PLAYER, "FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d", movementInfo.pos.GetPositionZ(), height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
- }
- }
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // No fly zone - Parachute
- }
- void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/)
- {
- GetAchievementMgr().UpdateAchievementCriteria(type, miscValue1, miscValue2, unit);
- }
- void Player::CompletedAchievement(AchievementEntry const* entry)
- {
- GetAchievementMgr().CompletedAchievement(entry);
- }
- void Player::LearnTalent(uint32 talentId, uint32 talentRank)
- {
- uint32 CurTalentPoints = GetFreeTalentPoints();
- if (CurTalentPoints == 0)
- return;
- if (talentRank >= MAX_TALENT_RANK)
- return;
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if (!talentInfo)
- return;
- TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
- if (!talentTabInfo)
- return;
- // prevent learn talent for different class (cheating)
- if ((getClassMask() & talentTabInfo->ClassMask) == 0)
- return;
- // find current max talent rank (0~5)
- uint8 curtalent_maxrank = 0; // 0 = not learned any rank
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if (talentInfo->RankID[rank] && HasSpell(talentInfo->RankID[rank]))
- {
- curtalent_maxrank = (rank + 1);
- break;
- }
- }
- // we already have same or higher talent rank learned
- if (curtalent_maxrank >= (talentRank + 1))
- return;
- // check if we have enough talent points
- if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
- return;
- // Check if it requires another talent
- if (talentInfo->DependsOn > 0)
- {
- if (TalentEntry const* depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
- {
- bool hasEnoughRank = false;
- for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
- {
- if (depTalentInfo->RankID[rank] != 0)
- if (HasSpell(depTalentInfo->RankID[rank]))
- hasEnoughRank = true;
- }
- if (!hasEnoughRank)
- return;
- }
- }
- // Find out how many points we have in this field
- uint32 spentPoints = 0;
- uint32 tTab = talentInfo->TalentTab;
- if (talentInfo->Row > 0)
- {
- uint32 numRows = sTalentStore.GetNumRows();
- for (uint32 i = 0; i < numRows; i++) // Loop through all talents.
- {
- // Someday, someone needs to revamp
- const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i);
- if (tmpTalent) // the way talents are tracked
- {
- if (tmpTalent->TalentTab == tTab)
- {
- for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
- {
- if (tmpTalent->RankID[rank] != 0)
- {
- if (HasSpell(tmpTalent->RankID[rank]))
- {
- spentPoints += (rank + 1);
- }
- }
- }
- }
- }
- }
- }
- // not have required min points spent in talent tree
- if (spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
- return;
- // spell not set in talent.dbc
- uint32 spellid = talentInfo->RankID[talentRank];
- if (spellid == 0)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
- return;
- }
- // already known
- if (HasSpell(spellid))
- return;
- // learn! (other talent ranks will unlearned at learning)
- learnSpell(spellid, false);
- AddTalent(spellid, m_activeSpec, true);
- sLog->outInfo(LOG_FILTER_PLAYER, "TalentID: %u Rank: %u Spell: %u Spec: %u\n", talentId, talentRank, spellid, m_activeSpec);
- // update free talent points
- SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
- }
- void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
- {
- Pet* pet = GetPet();
- if (!pet)
- return;
- if (petGuid != pet->GetGUID())
- return;
- uint32 CurTalentPoints = pet->GetFreeTalentPoints();
- if (CurTalentPoints == 0)
- return;
- if (talentRank >= MAX_PET_TALENT_RANK)
- return;
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if (!talentInfo)
- return;
- TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
- if (!talentTabInfo)
- return;
- CreatureTemplate const* ci = pet->GetCreatureTemplate();
- if (!ci)
- return;
- CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
- if (!pet_family)
- return;
- if (pet_family->petTalentType < 0) // not hunter pet
- return;
- // prevent learn talent for different family (cheating)
- if (!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
- return;
- // find current max talent rank (0~5)
- uint8 curtalent_maxrank = 0; // 0 = not learned any rank
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if (talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
- {
- curtalent_maxrank = (rank + 1);
- break;
- }
- }
- // we already have same or higher talent rank learned
- if (curtalent_maxrank >= (talentRank + 1))
- return;
- // check if we have enough talent points
- if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
- return;
- // Check if it requires another talent
- if (talentInfo->DependsOn > 0)
- {
- if (TalentEntry const* depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
- {
- bool hasEnoughRank = false;
- for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
- {
- if (depTalentInfo->RankID[rank] != 0)
- if (pet->HasSpell(depTalentInfo->RankID[rank]))
- hasEnoughRank = true;
- }
- if (!hasEnoughRank)
- return;
- }
- }
- // Find out how many points we have in this field
- uint32 spentPoints = 0;
- uint32 tTab = talentInfo->TalentTab;
- if (talentInfo->Row > 0)
- {
- uint32 numRows = sTalentStore.GetNumRows();
- for (uint32 i = 0; i < numRows; ++i) // Loop through all talents.
- {
- // Someday, someone needs to revamp
- const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i);
- if (tmpTalent) // the way talents are tracked
- {
- if (tmpTalent->TalentTab == tTab)
- {
- for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
- {
- if (tmpTalent->RankID[rank] != 0)
- {
- if (pet->HasSpell(tmpTalent->RankID[rank]))
- {
- spentPoints += (rank + 1);
- }
- }
- }
- }
- }
- }
- }
- // not have required min points spent in talent tree
- if (spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
- return;
- // spell not set in talent.dbc
- uint32 spellid = talentInfo->RankID[talentRank];
- if (spellid == 0)
- {
- sLog->outError(LOG_FILTER_PLAYER, "Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
- return;
- }
- // already known
- if (pet->HasSpell(spellid))
- return;
- // learn! (other talent ranks will unlearned at learning)
- pet->learnSpell(spellid);
- sLog->outInfo(LOG_FILTER_PLAYER, "PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
- // update free talent points
- pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
- }
- void Player::AddKnownCurrency(uint32 itemId)
- {
- if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
- SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (1LL << (ctEntry->BitIndex-1)));
- }
- void Player::UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode)
- {
- if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <= minfo.pos.GetPositionZ() || opcode == MSG_MOVE_FALL_LAND)
- SetFallInformation(minfo.fallTime, minfo.pos.GetPositionZ());
- }
- void Player::UnsummonPetTemporaryIfAny()
- {
- Pet* pet = GetPet();
- if (!pet)
- return;
- if (!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned())
- {
- m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
- m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
- }
- RemovePet(pet, PET_SAVE_AS_CURRENT);
- }
- void Player::ResummonPetTemporaryUnSummonedIfAny()
- {
- if (!m_temporaryUnsummonedPetNumber)
- return;
- // not resummon in not appropriate state
- if (IsPetNeedBeTemporaryUnsummoned())
- return;
- if (GetPetGUID())
- return;
- Pet* NewPet = new Pet(this);
- if (!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
- delete NewPet;
- m_temporaryUnsummonedPetNumber = 0;
- }
- bool Player::canSeeSpellClickOn(Creature const* c) const
- {
- if (!c->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK))
- return false;
- SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(c->GetEntry());
- if (clickPair.first == clickPair.second)
- return true;
- for (SpellClickInfoContainer::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
- {
- if (!itr->second.IsFitToRequirements(this, c))
- return false;
- ConditionList conds = sConditionMgr->GetConditionsForSpellClickEvent(c->GetEntry(), itr->second.spellId);
- ConditionSourceInfo info = ConditionSourceInfo(const_cast<Player*>(this), const_cast<Creature*>(c));
- if (!sConditionMgr->IsObjectMeetToConditions(info, conds))
- return false;
- }
- return true;
- }
- void Player::BuildPlayerTalentsInfoData(WorldPacket* data)
- {
- *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
- *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
- *data << uint8(m_activeSpec); // talent group index (0 or 1)
- if (m_specsCount)
- {
- if (m_specsCount > MAX_TALENT_SPECS)
- m_specsCount = MAX_TALENT_SPECS;
- // loop through all specs (only 1 for now)
- for (uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
- {
- uint8 talentIdCount = 0;
- size_t pos = data->wpos();
- *data << uint8(talentIdCount); // [PH], talentIdCount
- // find class talent tabs (all players have 3 talent tabs)
- uint32 const* talentTabIds = GetTalentTabPages(getClass());
- for (uint8 i = 0; i < MAX_TALENT_TABS; ++i)
- {
- uint32 talentTabId = talentTabIds[i];
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if (!talentInfo)
- continue;
- // skip another tab talents
- if (talentInfo->TalentTab != talentTabId)
- continue;
- // find max talent rank (0~4)
- int8 curtalent_maxrank = -1;
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if (talentInfo->RankID[rank] && HasTalent(talentInfo->RankID[rank], specIdx))
- {
- curtalent_maxrank = rank;
- break;
- }
- }
- // not learned talent
- if (curtalent_maxrank < 0)
- continue;
- *data << uint32(talentInfo->TalentID); // Talent.dbc
- *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
- ++talentIdCount;
- }
- }
- data->put<uint8>(pos, talentIdCount); // put real count
- *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
- for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
- *data << uint16(m_Glyphs[specIdx][i]); // GlyphProperties.dbc
- }
- }
- }
- void Player::BuildPetTalentsInfoData(WorldPacket* data)
- {
- uint32 unspentTalentPoints = 0;
- size_t pointsPos = data->wpos();
- *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
- uint8 talentIdCount = 0;
- size_t countPos = data->wpos();
- *data << uint8(talentIdCount); // [PH], talentIdCount
- Pet* pet = GetPet();
- if (!pet)
- return;
- unspentTalentPoints = pet->GetFreeTalentPoints();
- data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
- CreatureTemplate const* ci = pet->GetCreatureTemplate();
- if (!ci)
- return;
- CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
- if (!pet_family || pet_family->petTalentType < 0)
- return;
- for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
- {
- TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentTabId);
- if (!talentTabInfo)
- continue;
- if (!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
- continue;
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if (!talentInfo)
- continue;
- // skip another tab talents
- if (talentInfo->TalentTab != talentTabId)
- continue;
- // find max talent rank (0~4)
- int8 curtalent_maxrank = -1;
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if (talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
- {
- curtalent_maxrank = rank;
- break;
- }
- }
- // not learned talent
- if (curtalent_maxrank < 0)
- continue;
- *data << uint32(talentInfo->TalentID); // Talent.dbc
- *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
- ++talentIdCount;
- }
- data->put<uint8>(countPos, talentIdCount); // put real count
- break;
- }
- }
- void Player::SendTalentsInfoData(bool pet)
- {
- WorldPacket data(SMSG_TALENTS_INFO, 50);
- data << uint8(pet ? 1 : 0);
- if (pet)
- BuildPetTalentsInfoData(&data);
- else
- BuildPlayerTalentsInfoData(&data);
- GetSession()->SendPacket(&data);
- }
- void Player::BuildEnchantmentsInfoData(WorldPacket* data)
- {
- uint32 slotUsedMask = 0;
- size_t slotUsedMaskPos = data->wpos();
- *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- {
- Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
- if (!item)
- continue;
- slotUsedMask |= (1 << i);
- *data << uint32(item->GetEntry()); // item entry
- uint16 enchantmentMask = 0;
- size_t enchantmentMaskPos = data->wpos();
- *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
- for (uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
- {
- uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
- if (!enchId)
- continue;
- enchantmentMask |= (1 << j);
- *data << uint16(enchId); // enchantmentId?
- }
- data->put<uint16>(enchantmentMaskPos, enchantmentMask);
- *data << uint16(0); // unknown
- data->appendPackGUID(item->GetUInt64Value(ITEM_FIELD_CREATOR)); // item creator
- *data << uint32(0); // seed?
- }
- data->put<uint32>(slotUsedMaskPos, slotUsedMask);
- }
- void Player::SendEquipmentSetList()
- {
- uint32 count = 0;
- WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
- size_t count_pos = data.wpos();
- data << uint32(count); // count placeholder
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
- {
- if (itr->second.state == EQUIPMENT_SET_DELETED)
- continue;
- data.appendPackGUID(itr->second.Guid);
- data << uint32(itr->first);
- data << itr->second.Name;
- data << itr->second.IconName;
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- {
- // ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HIGHGUID_ITEM
- if (itr->second.IgnoreMask & (1 << i))
- data.appendPackGUID(uint64(1));
- else
- data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
- }
- ++count; // client have limit but it checked at loading and set
- }
- data.put<uint32>(count_pos, count);
- GetSession()->SendPacket(&data);
- }
- void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
- {
- if (eqset.Guid != 0)
- {
- bool found = false;
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
- {
- if ((itr->second.Guid == eqset.Guid) && (itr->first == index))
- {
- found = true;
- break;
- }
- }
- if (!found) // something wrong...
- {
- sLog->outError(LOG_FILTER_PLAYER, "Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
- return;
- }
- }
- EquipmentSet& eqslot = m_EquipmentSets[index];
- EquipmentSetUpdateState old_state = eqslot.state;
- eqslot = eqset;
- if (eqset.Guid == 0)
- {
- eqslot.Guid = sObjectMgr->GenerateEquipmentSetGuid();
- WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
- data << uint32(index);
- data.appendPackGUID(eqslot.Guid);
- GetSession()->SendPacket(&data);
- }
- eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
- }
- void Player::_SaveEquipmentSets(SQLTransaction& trans)
- {
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
- {
- uint32 index = itr->first;
- EquipmentSet& eqset = itr->second;
- PreparedStatement* stmt = NULL;
- uint8 j = 0;
- switch (eqset.state)
- {
- case EQUIPMENT_SET_UNCHANGED:
- ++itr;
- break; // nothing do
- case EQUIPMENT_SET_CHANGED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EQUIP_SET);
- stmt->setString(j++, eqset.Name.c_str());
- stmt->setString(j++, eqset.IconName.c_str());
- stmt->setUInt32(j++, eqset.IgnoreMask);
- for (uint8 i=0; i<EQUIPMENT_SLOT_END; ++i)
- stmt->setUInt32(j++, eqset.Items[i]);
- stmt->setUInt32(j++, GetGUIDLow());
- stmt->setUInt64(j++, eqset.Guid);
- stmt->setUInt32(j, index);
- trans->Append(stmt);
- eqset.state = EQUIPMENT_SET_UNCHANGED;
- ++itr;
- break;
- case EQUIPMENT_SET_NEW:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET);
- stmt->setUInt32(j++, GetGUIDLow());
- stmt->setUInt64(j++, eqset.Guid);
- stmt->setUInt32(j++, index);
- stmt->setString(j++, eqset.Name.c_str());
- stmt->setString(j++, eqset.IconName.c_str());
- stmt->setUInt32(j++, eqset.IgnoreMask);
- for (uint8 i=0; i<EQUIPMENT_SLOT_END; ++i)
- stmt->setUInt32(j++, eqset.Items[i]);
- trans->Append(stmt);
- eqset.state = EQUIPMENT_SET_UNCHANGED;
- ++itr;
- break;
- case EQUIPMENT_SET_DELETED:
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EQUIP_SET);
- stmt->setUInt64(0, eqset.Guid);
- trans->Append(stmt);
- m_EquipmentSets.erase(itr++);
- break;
- }
- }
- }
- void Player::_SaveBGData(SQLTransaction& trans)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_BGDATA);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_BGDATA);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, m_bgData.bgInstanceID);
- stmt->setUInt16(2, m_bgData.bgTeam);
- stmt->setFloat (3, m_bgData.joinPos.GetPositionX());
- stmt->setFloat (4, m_bgData.joinPos.GetPositionY());
- stmt->setFloat (5, m_bgData.joinPos.GetPositionZ());
- stmt->setFloat (6, m_bgData.joinPos.GetOrientation());
- stmt->setUInt16(7, m_bgData.joinPos.GetMapId());
- stmt->setUInt16(8, m_bgData.taxiPath[0]);
- stmt->setUInt16(9, m_bgData.taxiPath[1]);
- stmt->setUInt16(10, m_bgData.mountSpell);
- trans->Append(stmt);
- }
- void Player::DeleteEquipmentSet(uint64 setGuid)
- {
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
- {
- if (itr->second.Guid == setGuid)
- {
- if (itr->second.state == EQUIPMENT_SET_NEW)
- m_EquipmentSets.erase(itr);
- else
- itr->second.state = EQUIPMENT_SET_DELETED;
- break;
- }
- }
- }
- void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/)
- {
- m_atLoginFlags &= ~flags;
- if (persist)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG);
- stmt->setUInt16(0, uint16(flags));
- stmt->setUInt32(1, GetGUIDLow());
- CharacterDatabase.Execute(stmt);
- }
- }
- void Player::SendClearCooldown(uint32 spell_id, Unit* target)
- {
- WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
- data << uint32(spell_id);
- data << uint64(target->GetGUID());
- SendDirectMessage(&data);
- }
- void Player::ResetMap()
- {
- // this may be called during Map::Update
- // after decrement+unlink, ++m_mapRefIter will continue correctly
- // when the first element of the list is being removed
- // nocheck_prev will return the padding element of the RefManager
- // instead of NULL in the case of prev
- GetMap()->UpdateIteratorBack(this);
- Unit::ResetMap();
- GetMapRef().unlink();
- }
- void Player::SetMap(Map* map)
- {
- Unit::SetMap(map);
- m_mapRef.link(map, this);
- }
- void Player::_LoadGlyphs(PreparedQueryResult result)
- {
- // SELECT spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 from character_glyphs WHERE guid = '%u'
- if (!result)
- return;
- do
- {
- Field* fields = result->Fetch();
- uint8 spec = fields[0].GetUInt8();
- if (spec >= m_specsCount)
- continue;
- m_Glyphs[spec][0] = fields[1].GetUInt16();
- m_Glyphs[spec][1] = fields[2].GetUInt16();
- m_Glyphs[spec][2] = fields[3].GetUInt16();
- m_Glyphs[spec][3] = fields[4].GetUInt16();
- m_Glyphs[spec][4] = fields[5].GetUInt16();
- m_Glyphs[spec][5] = fields[6].GetUInt16();
- }
- while (result->NextRow());
- }
- void Player::_SaveGlyphs(SQLTransaction& trans)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
- stmt->setUInt32(0, GetGUIDLow());
- trans->Append(stmt);
- for (uint8 spec = 0; spec < m_specsCount; ++spec)
- {
- uint8 index = 0;
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GLYPHS);
- stmt->setUInt32(index++, GetGUIDLow());
- stmt->setUInt8(index++, spec);
- for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
- stmt->setUInt16(index++, uint16(m_Glyphs[spec][i]));
- trans->Append(stmt);
- }
- }
- void Player::_LoadTalents(PreparedQueryResult result)
- {
- // SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, spec FROM character_talent WHERE guid = '%u'", GUID_LOPART(m_guid));
- if (result)
- {
- do
- AddTalent((*result)[0].GetUInt32(), (*result)[1].GetUInt8(), false);
- while (result->NextRow());
- }
- }
- void Player::_SaveTalents(SQLTransaction& trans)
- {
- PreparedStatement* stmt = NULL;
- for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
- {
- for (PlayerTalentMap::iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end();)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL_SPEC);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, itr->first);
- stmt->setUInt8(2, itr->second->spec);
- trans->Append(stmt);
- }
- if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_TALENT);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt32(1, itr->first);
- stmt->setUInt8(2, itr->second->spec);
- trans->Append(stmt);
- }
- if (itr->second->state == PLAYERSPELL_REMOVED)
- {
- delete itr->second;
- m_talents[i]->erase(itr++);
- }
- else
- {
- itr->second->state = PLAYERSPELL_UNCHANGED;
- ++itr;
- }
- }
- }
- }
- void Player::UpdateSpecCount(uint8 count)
- {
- uint32 curCount = GetSpecsCount();
- if (curCount == count)
- return;
- if (m_activeSpec >= count)
- ActivateSpec(0);
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- PreparedStatement* stmt = NULL;
- // Copy spec data
- if (count > curCount)
- {
- _SaveActions(trans); // make sure the button list is cleaned up
- for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); ++itr)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt8(1, 1);
- stmt->setUInt8(2, itr->first);
- stmt->setUInt32(3, itr->second.GetAction());
- stmt->setUInt8(4, uint8(itr->second.GetType()));
- trans->Append(stmt);
- }
- }
- // Delete spec data for removed spec.
- else if (count < curCount)
- {
- _SaveActions(trans);
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_EXCEPT_SPEC);
- stmt->setUInt8(0, m_activeSpec);
- stmt->setUInt32(1, GetGUIDLow());
- trans->Append(stmt);
- m_activeSpec = 0;
- }
- CharacterDatabase.CommitTransaction(trans);
- SetSpecsCount(count);
- SendTalentsInfoData(false);
- }
- void Player::ActivateSpec(uint8 spec)
- {
- if (GetActiveSpec() == spec)
- return;
- if (spec > GetSpecsCount())
- return;
- if (IsNonMeleeSpellCasted(false))
- InterruptNonMeleeSpells(false);
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- _SaveActions(trans);
- CharacterDatabase.CommitTransaction(trans);
- // TO-DO: We need more research to know what happens with warlock's reagent
- if (Pet* pet = GetPet())
- RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
- ClearComboPointHolders();
- ClearAllReactives();
- UnsummonAllTotems();
- RemoveAllControlled();
- /*RemoveAllAurasOnDeath();
- if (GetPet())
- GetPet()->RemoveAllAurasOnDeath();*/
- //RemoveAllAuras(GetGUID(), NULL, false, true); // removes too many auras
- //ExitVehicle(); // should be impossible to switch specs from inside a vehicle..
- // Let client clear his current Actions
- SendActionButtons(2);
- // m_actionButtons.clear() is called in the next _LoadActionButtons
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if (!talentInfo)
- continue;
- TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
- if (!talentTabInfo)
- continue;
- // unlearn only talents for character class
- // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
- // to prevent unexpected lost normal learned spell skip another class talents
- if ((getClassMask() & talentTabInfo->ClassMask) == 0)
- continue;
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- // skip non-existant talent ranks
- if (talentInfo->RankID[rank] == 0)
- continue;
- removeSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells..
- if (const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]))
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellInfo for valid trigger spells
- if (_spellEntry->Effects[i].TriggerSpell > 0 && _spellEntry->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL)
- removeSpell(_spellEntry->Effects[i].TriggerSpell, true); // and remove any spells that the talent teaches
- // if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
- //PlayerTalentMap::iterator plrTalent = m_talents[m_activeSpec]->find(talentInfo->RankID[rank]);
- //if (plrTalent != m_talents[m_activeSpec]->end())
- // plrTalent->second->state = PLAYERSPELL_REMOVED;
- }
- }
- // set glyphs
- for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
- // remove secondary glyph
- if (uint32 oldglyph = m_Glyphs[m_activeSpec][slot])
- if (GlyphPropertiesEntry const* old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph))
- RemoveAurasDueToSpell(old_gp->SpellId);
- SetActiveSpec(spec);
- uint32 spentTalents = 0;
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if (!talentInfo)
- continue;
- TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
- if (!talentTabInfo)
- continue;
- // learn only talents for character class
- if ((getClassMask() & talentTabInfo->ClassMask) == 0)
- continue;
- // learn highest talent rank that exists in newly activated spec
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- // skip non-existant talent ranks
- if (talentInfo->RankID[rank] == 0)
- continue;
- // if the talent can be found in the newly activated PlayerTalentMap
- if (HasTalent(talentInfo->RankID[rank], m_activeSpec))
- {
- learnSpell(talentInfo->RankID[rank], false); // add the talent to the PlayerSpellMap
- spentTalents += (rank + 1); // increment the spentTalents count
- }
- }
- }
- // set glyphs
- for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
- {
- uint32 glyph = m_Glyphs[m_activeSpec][slot];
- // apply primary glyph
- if (glyph)
- if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
- CastSpell(this, gp->SpellId, true);
- SetGlyph(slot, glyph);
- }
- m_usedTalentCount = spentTalents;
- InitTalentForLevel();
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC);
- stmt->setUInt32(0, GetGUIDLow());
- stmt->setUInt8(1, m_activeSpec);
- if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
- _LoadActions(result);
- }
- SendActionButtons(1);
- Powers pw = getPowerType();
- if (pw != POWER_MANA)
- SetPower(POWER_MANA, 0); // Mana must be 0 even if it isn't the active power type.
- SetPower(pw, 0);
- }
- void Player::ResetTimeSync()
- {
- m_timeSyncCounter = 0;
- m_timeSyncTimer = 0;
- m_timeSyncClient = 0;
- m_timeSyncServer = getMSTime();
- }
- void Player::SendTimeSync()
- {
- WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
- data << uint32(m_timeSyncCounter++);
- GetSession()->SendPacket(&data);
- // Schedule next sync in 10 sec
- m_timeSyncTimer = 10000;
- m_timeSyncServer = getMSTime();
- }
- void Player::SetReputation(uint32 factionentry, uint32 value)
- {
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(factionentry), value);
- }
- uint32 Player::GetReputation(uint32 factionentry)
- {
- return GetReputationMgr().GetReputation(sFactionStore.LookupEntry(factionentry));
- }
- std::string Player::GetGuildName()
- {
- return sGuildMgr->GetGuildById(GetGuildId())->GetName();
- }
- void Player::SendDuelCountdown(uint32 counter)
- {
- WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
- data << uint32(counter); // seconds
- GetSession()->SendPacket(&data);
- }
- void Player::AddRefundReference(uint32 it)
- {
- m_refundableItems.insert(it);
- }
- void Player::DeleteRefundReference(uint32 it)
- {
- std::set<uint32>::iterator itr = m_refundableItems.find(it);
- if (itr != m_refundableItems.end())
- {
- m_refundableItems.erase(itr);
- }
- }
- void Player::SendRefundInfo(Item* item)
- {
- // This function call unsets ITEM_FLAGS_REFUNDABLE if played time is over 2 hours.
- item->UpdatePlayedTime(this);
- if (!item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item refund: item not refundable!");
- return;
- }
- if (GetGUIDLow() != item->GetRefundRecipient()) // Formerly refundable item got traded
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item refund: item was traded!");
- item->SetNotRefundable(this);
- return;
- }
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(item->GetPaidExtendedCost());
- if (!iece)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item refund: cannot find extendedcost data.");
- return;
- }
- WorldPacket data(SMSG_ITEM_REFUND_INFO_RESPONSE, 8+4+4+4+4*4+4*4+4+4);
- data << uint64(item->GetGUID()); // item guid
- data << uint32(item->GetPaidMoney()); // money cost
- data << uint32(iece->reqhonorpoints); // honor point cost
- data << uint32(iece->reqarenapoints); // arena point cost
- for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i) // item cost data
- {
- data << uint32(iece->reqitem[i]);
- data << uint32(iece->reqitemcount[i]);
- }
- data << uint32(0);
- data << uint32(GetTotalPlayedTime() - item->GetPlayedTime());
- GetSession()->SendPacket(&data);
- }
- bool Player::AddItem(uint32 itemId, uint32 count)
- {
- uint32 noSpaceForCount = 0;
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount);
- if (msg != EQUIP_ERR_OK)
- count = noSpaceForCount;
- if (count == 0 || dest.empty())
- {
- // -- TODO: Send to mailbox if no space
- ChatHandler(this).PSendSysMessage("You don't have any space in your bags.");
- return false;
- }
- Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
- if (item)
- SendNewItem(item, count, true, false);
- else
- return false;
- return true;
- }
- void Player::RefundItem(Item* item)
- {
- if (!item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item refund: item not refundable!");
- return;
- }
- if (item->IsRefundExpired()) // item refund has expired
- {
- item->SetNotRefundable(this);
- WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4);
- data << uint64(item->GetGUID()); // Guid
- data << uint32(10); // Error!
- GetSession()->SendPacket(&data);
- return;
- }
- if (GetGUIDLow() != item->GetRefundRecipient()) // Formerly refundable item got traded
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item refund: item was traded!");
- item->SetNotRefundable(this);
- return;
- }
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(item->GetPaidExtendedCost());
- if (!iece)
- {
- sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Item refund: cannot find extendedcost data.");
- return;
- }
- bool store_error = false;
- for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
- {
- uint32 count = iece->reqitemcount[i];
- uint32 itemid = iece->reqitem[i];
- if (count && itemid)
- {
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemid, count);
- if (msg != EQUIP_ERR_OK)
- {
- store_error = true;
- break;
- }
- }
- }
- if (store_error)
- {
- WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4);
- data << uint64(item->GetGUID()); // Guid
- data << uint32(10); // Error!
- GetSession()->SendPacket(&data);
- return;
- }
- WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4+4+4+4+4*4+4*4);
- data << uint64(item->GetGUID()); // item guid
- data << uint32(0); // 0, or error code
- data << uint32(item->GetPaidMoney()); // money cost
- data << uint32(iece->reqhonorpoints); // honor point cost
- data << uint32(iece->reqarenapoints); // arena point cost
- for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i) // item cost data
- {
- data << uint32(iece->reqitem[i]);
- data << uint32(iece->reqitemcount[i]);
- }
- GetSession()->SendPacket(&data);
- uint32 moneyRefund = item->GetPaidMoney(); // item-> will be invalidated in DestroyItem
- // Save all relevant data to DB to prevent desynchronisation exploits
- SQLTransaction trans = CharacterDatabase.BeginTransaction();
- // Delete any references to the refund data
- item->SetNotRefundable(this, true, &trans);
- // Destroy item
- DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
- // Grant back extendedcost items
- for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
- {
- uint32 count = iece->reqitemcount[i];
- uint32 itemid = iece->reqitem[i];
- if (count && itemid)
- {
- ItemPosCountVec dest;
- InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemid, count);
- ASSERT(msg == EQUIP_ERR_OK) /// Already checked before
- Item* it = StoreNewItem(dest, itemid, true);
- SendNewItem(it, count, true, false, true);
- }
- }
- // Grant back money
- if (moneyRefund)
- ModifyMoney(moneyRefund); // Saved in SaveInventoryAndGoldToDB
- // Grant back Honor points
- if (uint32 honorRefund = iece->reqhonorpoints)
- ModifyHonorPoints(honorRefund, &trans);
- // Grant back Arena points
- if (uint32 arenaRefund = iece->reqarenapoints)
- ModifyArenaPoints(arenaRefund, &trans);
- SaveInventoryAndGoldToDB(trans);
- CharacterDatabase.CommitTransaction(trans);
- }
- void Player::SetRandomWinner(bool isWinner)
- {
- m_IsBGRandomWinner = isWinner;
- if (m_IsBGRandomWinner)
- {
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM);
- stmt->setUInt32(0, GetGUIDLow());
- CharacterDatabase.Execute(stmt);
- }
- }
- void Player::_LoadRandomBGStatus(PreparedQueryResult result)
- {
- //QueryResult result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '%u'", GetGUIDLow());
- if (result)
- m_IsBGRandomWinner = true;
- }
- float Player::GetAverageItemLevel()
- {
- float sum = 0;
- uint32 count = 0;
- for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- // don't check tabard, ranged, offhand or shirt
- if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_OFFHAND || i == EQUIPMENT_SLOT_BODY)
- continue;
- if (m_items[i] && m_items[i]->GetTemplate())
- sum += m_items[i]->GetTemplate()->GetItemLevelIncludingQuality();
- ++count;
- }
- return ((float)sum) / count;
- }
- void Player::_LoadInstanceTimeRestrictions(PreparedQueryResult result)
- {
- if (!result)
- return;
- do
- {
- Field* fields = result->Fetch();
- _instanceResetTimes.insert(InstanceTimeMap::value_type(fields[0].GetUInt32(), fields[1].GetUInt64()));
- } while (result->NextRow());
- }
- void Player::_SaveInstanceTimeRestrictions(SQLTransaction& trans)
- {
- if (_instanceResetTimes.empty())
- return;
- PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES);
- stmt->setUInt32(0, GetSession()->GetAccountId());
- trans->Append(stmt);
- for (InstanceTimeMap::const_iterator itr = _instanceResetTimes.begin(); itr != _instanceResetTimes.end(); ++itr)
- {
- stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES);
- stmt->setUInt32(0, GetSession()->GetAccountId());
- stmt->setUInt32(1, itr->first);
- stmt->setUInt64(2, itr->second);
- trans->Append(stmt);
- }
- }
- /** World of Warcraft Armory **/
- void Player::InitWowarmoryFeeds() {
- // Clear feeds
- m_wowarmory_feeds.clear();
- }
- void Player::CreateWowarmoryFeed(uint32 type, uint32 data, uint32 item_guid, uint32 item_quality) {
- /*
- 1 - TYPE_ACHIEVEMENT_FEED
- 2 - TYPE_ITEM_FEED
- 3 - TYPE_BOSS_FEED
- */
- if (GetGUIDLow() == 0)
- {
- sLog->outError(LOG_FILTER_UNITS,"[Wowarmory]: player is not initialized, unable to create log entry!");
- return;
- }
- if (type <= 0 || type > 3)
- {
- sLog->outError(LOG_FILTER_UNITS,"[Wowarmory]: unknown feed type: %d, ignore.", type);
- return;
- }
- if (data == 0)
- {
- sLog->outError(LOG_FILTER_UNITS,"[Wowarmory]: empty data (GUID: %u), ignore.", GetGUIDLow());
- return;
- }
- WowarmoryFeedEntry feed;
- feed.guid = GetGUIDLow();
- feed.type = type;
- feed.data = data;
- feed.difficulty = type == 3 ? GetMap()->GetDifficulty() : 0;
- feed.item_guid = item_guid;
- feed.item_quality = item_quality;
- feed.counter = 0;
- feed.date = time(NULL);
- sLog->outDebug(LOG_FILTER_UNITS, "[Wowarmory]: create wowarmory feed (GUID: %u, type: %d, data: %u).", feed.guid, feed.type, feed.data);
- m_wowarmory_feeds.push_back(feed);
- }
- /** World of Warcraft Armory **/
- bool Player::IsInWhisperWhiteList(uint64 guid)
- {
- for (WhisperListContainer::const_iterator itr = WhisperList.begin(); itr != WhisperList.end(); ++itr)
- {
- if (*itr == guid)
- return true;
- }
- return false;
- }
- bool Player::SetHover(bool enable)
- {
- if (!Unit::SetHover(enable))
- return false;
- return true;
- }
- void Player::SendMovementSetCanFly(bool apply)
- {
- WorldPacket data(apply ? SMSG_MOVE_SET_CAN_FLY : SMSG_MOVE_UNSET_CAN_FLY, 12);
- data.append(GetPackGUID());
- data << uint32(0); //! movement counter
- SendDirectMessage(&data);
- }
- void Player::SendMovementSetCanTransitionBetweenSwimAndFly(bool apply)
- {
- WorldPacket data(apply ?
- SMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY :
- SMSG_MOVE_UNSET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY, 12);
- data.append(GetPackGUID());
- data << uint32(0); //! movement counter
- SendDirectMessage(&data);
- }
- void Player::SendMovementSetHover(bool apply)
- {
- WorldPacket data(apply ? SMSG_MOVE_SET_HOVER : SMSG_MOVE_UNSET_HOVER, 12);
- data.append(GetPackGUID());
- data << uint32(0); //! movement counter
- SendDirectMessage(&data);
- }
- void Player::SendMovementSetWaterWalking(bool apply)
- {
- WorldPacket data(apply ? SMSG_MOVE_WATER_WALK : SMSG_MOVE_LAND_WALK, 12);
- data.append(GetPackGUID());
- data << uint32(0); //! movement counter
- SendDirectMessage(&data);
- }
- void Player::SendMovementSetFeatherFall(bool apply)
- {
- WorldPacket data(apply ? SMSG_MOVE_FEATHER_FALL : SMSG_MOVE_NORMAL_FALL, 12);
- data.append(GetPackGUID());
- data << uint32(0); //! movement counter
- SendDirectMessage(&data);
- }
Add Comment
Please, Sign In to add comment