diff --git a/AddOns/!!!ClassicAPI/locales/enUS.lua b/AddOns/!!!ClassicAPI/locales/enUS.lua index 88e8488e..cf293561 100644 --- a/AddOns/!!!ClassicAPI/locales/enUS.lua +++ b/AddOns/!!!ClassicAPI/locales/enUS.lua @@ -75,6 +75,7 @@ MINUTES_SECONDS = "%.2d:%.2d"; PAPERDOLL_EQUIPMENTMANAGER = "Equipment Manager"; PAPERDOLL_NEWEQUIPMENTSET = "New Set"; PERCENTAGE_STRING = "%d%%"; +PLAYER_LIST_DELIMITER = ", "; SET_FRIENDNOTE_LABEL = "Set Notes for %s:"; SET_NOTE = "Set Note"; SILVER_AMOUNT_SYMBOL = "s"; diff --git a/docs/API.md b/docs/API.md index 136a48f2..d2e75413 100644 --- a/docs/API.md +++ b/docs/API.md @@ -319,6 +319,7 @@ build instructions. - [`OnTooltipSet*` scripts (Item / Spell / Unit / GameObject)](#ontooltipset-scripts) - [`GameTooltip:SetItemByGUID(itemGUID)`](#gametooltipsetitembyguiditemguid) - [`GameTooltip:SetEquipmentSet(name)`](#gametooltipsetequipmentsetname) + - [Equipment sets on item tooltips](#equipment-sets-on-item-tooltips) - [`GameTooltip:SetTotem(slot)`](#gametooltipsettotemslot) - [`GameTooltip:GetItem()`](#gametooltipgetitem) - [`GameTooltip:GetSpell()`](#gametooltipgetspell) @@ -2504,8 +2505,9 @@ inSet, setList = C_Container.GetContainerItemEquipmentSetInfo(containerIndex, sl ``` - `inSet` — `true` when the item is part of at least one equipment set. -- `setList` — the set names joined with `", "`, in the order the sets - are stored. `nil` when the item is in no set. +- `setList` — the set names, in the order the sets are stored, joined + with `PLAYER_LIST_DELIMITER` (`", "` in English). `nil` when the item + is in no set. ```lua local inSet, setList = C_Container.GetContainerItemEquipmentSetInfo(bag, slot) @@ -3521,21 +3523,14 @@ set 2 ... ``` -Identity is by **item GUID**, snapshotted at `CreateEquipmentSet` / -`SaveEquipmentSet` time. `UseEquipmentSet` searches every player-owned -container for those GUIDs and dispatches pickup→equip pairs for items -that aren't already where they belong. The search reads the -underlying GUID arrays directly (same trick `C_Item.GetItemCount` -uses for its `includeBank=true` path), so bank items resolve **even -without the bank window being open** — the bank gate at -`VAR_BANK_GATE_GUID` only suppresses `GetItemBySlot`, not the -underlying data. +Identity is by **item GUID**, saved at `CreateEquipmentSet` / +`SaveEquipmentSet` time. A set remembers the exact items you wore, not +the kind of item. `UseEquipmentSet` finds those items in your bags and +moves each one that is not already in its slot. -One limitation worth knowing about: - -- **Equipping from the bank** is not supported by the protocol - — `UseEquipmentSet` skips bank items rather than try and fail. - Retrieve the items first, then re-run. +Items in the bank count only while the bank window is open. Then +`UseEquipmentSet` can equip them directly from the bank. When the bank +is closed, a set item in the bank counts as missing. We accept icon path strings (e.g. `"INV_Shield_06"`), since there is no fileDataID system here. Missing or unknown icons fall back to a default. @@ -3552,8 +3547,8 @@ file from scratch). ### `C_EquipmentSet.CanUseEquipmentSets()` -Returns `true` unconditionally. There is no banker/feature gate on -equipment-set storage; the feature ships for every character. +Returns `false` while a swap from `UseEquipmentSet` is in progress, and +`true` at all other times. ### `C_EquipmentSet.GetNumEquipmentSets()` @@ -3581,11 +3576,22 @@ name, icon, setID, isEquipped, numItems, numEquipped, numInInventory, numMissing, numIgnored ``` -`isEquipped` is `true` when every resolvable item in the set is in -its target slot (missing items don't disqualify — useful so a set -that includes a bank-stored cloak still shows as equipped after you -swap in the rest). `numItems` excludes ignored slots; `numIgnored` -counts them separately. Returns nothing for an unknown setID. +Each slot of the set that holds an item counts one time: + +- `numEquipped` — you wear the item, in any equipment slot. +- `numInInventory` — the item is in your bags, or in the bank while the + bank window is open. +- `numMissing` — the item is in none of these places. +- `numIgnored` — the slot is ignored. + +`numItems` is `numEquipped + numInInventory + numMissing`. Slots that +the set saved as empty are not counted. + +`isEquipped` is `true` only when every slot that is not ignored holds +exactly what the set saved. A slot that the set saved as empty must be +empty. A missing item makes `isEquipped` `false`. + +Returns nothing for an unknown setID. ### `C_EquipmentSet.GetIgnoredSlots(setID)` @@ -3596,14 +3602,20 @@ slots are recorded **per-set at save time**, by reading the global ### `C_EquipmentSet.GetItemIDs(setID)` -Returns a hash table `{ [slot] = itemID }` for every set slot whose -item is currently resolvable. Missing items (GUID stored but client -can't find a CGItem) are omitted because the engine doesn't keep an -itemID separate from the live CGItem record. +Returns a table `{ [slot] = value }` with an entry for each of the 19 +slots: + +- `0` — the set saved the slot as empty. +- `1` — the slot is ignored. +- the itemID — for an item slot. The set saves the itemID with the item, + so you get it also when the item is gone. +- `-1` — the itemID is not known. This occurs only for sets that were + saved before ClassicAPI saved itemIDs. ### `C_EquipmentSet.GetItemLocations(setID)` -Returns a hash table `{ [slot] = locationCode }`. Location codes use +Returns a table `{ [slot] = locationCode }` with an entry for each of +the 19 slots. Location codes use the same bit-packed encoding Blizzard's FrameXML `EquipmentManager_UnpackLocation` decodes (constants in `Blizzard_FrameXMLBase/Classic/Constants.lua`): @@ -3629,9 +3641,13 @@ to give back bag IDs 5..10. Composition: | Bank bag 5..10 | `BANK | BAGS | ((bag-4)<<8) | slot` | `0x600101` = bank bag 5 slot 1 | Special values returned in the table entry: +- `0` — the set saved the slot as empty - `1` — slot is ignored (`GetIgnoredSlots` lists these) - `-1` — item is missing (was in the set, can't find now) +Bank locations are returned only while the bank window is open. When +the bank is closed, an item in the bank is `-1`. + The packed codes pass cleanly through Blizzard's `EquipmentManager_UnpackLocation` if you want to use the shared-FrameXML helpers in your addon UI. @@ -3646,6 +3662,10 @@ GUID. Returns the new setID on success. Returns nothing if the name is empty or already in use. +The name must be valid UTF-8, have no line break, and be shorter than 32 +characters. If not, the call raises the error `Invalid string for +setName`. The `|` character is removed from the name. + `icon` defaults to `"INV_Misc_QuestionMark"` if omitted. ### `C_EquipmentSet.SaveEquipmentSet(setID [, icon])` @@ -3658,7 +3678,8 @@ the icon is left unchanged. ### `C_EquipmentSet.ModifyEquipmentSet(setID, newName)` Renames an existing set. Fails silently if the new name is empty, -already in use by a different set, or the setID doesn't exist. +already in use by a different set, or the setID doesn't exist. The new +name follows the same rules as in `CreateEquipmentSet`. ### `C_EquipmentSet.DeleteEquipmentSet(setID)` @@ -3683,38 +3704,34 @@ by the engine — a pending pickup or use is in flight that ### `C_EquipmentSet.UseEquipmentSet(setID)` -Walks the set and dispatches one **atomic server-side swap** per item -that isn't already in its target slot. Items in the bank are skipped -silently (the protocol can't equip from bank). Missing items are skipped -silently. Returns `true` if the call ran (the set existed), `false` -otherwise. +Equips the set. Each item that is not in its slot moves with one +server-side swap. Slots that the set saved as empty are emptied into +free bag slots. The cursor is not used. -Implementation uses the same `FUN_INVENTORY_SWAP` primitive -[`C_Item.EquipItemByName`](#c_itemequipitembynameitem--dstslot) -uses for its explicit-slot path. Each swap is a single -CMSG_SWAP_INV_ITEM (or CMSG_AUTOEQUIP_ITEM) packet that the server -applies atomically — the two-cycle "ring A in slot 11, ring B in -slot 12, set swaps them" case resolves in one packet because the -opcode swaps both slots in a single server transaction. The cursor -is never touched; an item held on the cursor when -`UseEquipmentSet` is called stays on the cursor. +Returns `true` when the swap starts. Returns `false` when the setID is +unknown, or when the swap cannot start. The result of the swap comes +later, in `EQUIPMENT_SWAP_FINISHED`. -Longer dependency chains (3+ items rotating) are rare with 1.12's -slot set — the realistic conflicts are paired slots (rings 11/12, -trinkets 13/14, weapons 16/17), all 2-cycles. +The swap does not start when another swap from `UseEquipmentSet` is in +progress, or when the cursor holds an item. Then the error frame shows +`ERR_CLIENT_LOCKED_OUT` ("You can't do that right now."). -> **`CURSOR_UPDATE` fires per item moved.** The engine's swap -> primitive (`FUN_005E0C40`) runs a generic cursor-state cleanup at -> the end of each call, which fires `CURSOR_UPDATE` regardless of -> whether the cursor was actually touched. So one -> `UseEquipmentSet` call that moves N items will fire N -> `CURSOR_UPDATE` events in quick succession. Addons that react to -> `CURSOR_UPDATE` (cursor-attached tooltips, drag-state tracking) -> should debounce — or check `CursorHasItem()` before doing work — -> since most of those fires won't reflect a real cursor change. -> This is engine behavior, not a bug in the implementation; the -> old cursor-based path actually fired more (one per pickup, one -> per equip, one per cursor-clear). +Rules for each slot: + +- **In combat**, only the main hand, off hand, and ranged slots change. + If a different slot had to change, the error frame shows + `ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S` one time. +- **A missing item** is skipped. The error frame shows + `ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S` one time. +- **Items in the bank** are equipped only while the bank window is open. +- **No free bag slot** for an item that the set takes off: that slot + keeps its item. When the swap ends, `EQUIPMENT_SWAP_FINISHED` reports + a failure, and the error frame shows `ERR_EQUIPMENT_MANAGER_BAGS_FULL`. + +> **`CURSOR_UPDATE` fires one time for each item that moves.** The +> game's swap does a cursor cleanup after each move, also when the +> cursor did not change. Addons that react to `CURSOR_UPDATE` should +> check `CursorHasItem()` before they do work. ### `C_EquipmentSet.PickupEquipmentSet(setID)` @@ -3723,8 +3740,9 @@ equipment-set button. An unknown `setID` does nothing. An equipment-set button shows the icon and the name of the set. When the player uses the button, `WEAR_EQUIPMENT_SET` fires, and the -built-in handler equips the set. The button is grayed out while an item -of the set is locked. Its tooltip is the `GameTooltip:SetEquipmentSet` +built-in handler equips the set. The button is grayed out while a swap +is in progress, while an item of the set is locked, and while an item +that the set would replace is locked. Its tooltip is the `GameTooltip:SetEquipmentSet` tooltip. The button works like other action buttons. Drag it off to put the set @@ -4118,25 +4136,27 @@ should re-read its set list / button state when this fires. ### `EQUIPMENT_SWAP_PENDING` event -Fires with a single payload arg — `setID` — at the **start** of -`UseEquipmentSet`, right after the set-exists check passes and -before any pickup/equip work begins. Addons use this to -gate "swap in progress" UI state (grey out the set button, show -a spinner, etc.) until `EQUIPMENT_SWAP_FINISHED` arrives. - -Doesn't fire if `UseEquipmentSet` is called with an unknown -setID — in that case only `EQUIPMENT_SWAP_FINISHED(false, setID)` -fires. +Fires with one payload argument, `setID`, when `UseEquipmentSet` starts +a swap. Until `EQUIPMENT_SWAP_FINISHED` fires, `CanUseEquipmentSets()` +returns `false` and equipment-set buttons are grayed out. ### `EQUIPMENT_SWAP_FINISHED` event -Fires at the end of every `UseEquipmentSet` call with two payload -args: `success` (1 if the set existed and we dispatched the swap, 0 -if the setID was unknown) and `setID`. Note this is "we ran the -dispatch" success — not "every item ended up in its target slot." -Items that were in the bank or that couldn't complete a swap cycle -in one pass still report success=1. Listen for this if you want to -re-paint the character pane / refresh tooltips after a swap. +Fires with two payload arguments, `success` and `setID`, when a swap +from `UseEquipmentSet` ends. It always comes after +`EQUIPMENT_SWAP_PENDING`, and never during the `UseEquipmentSet` call. + +`success` is `1` when every slot that the swap changed holds its set +item. `success` is `nil` when: + +- the server refused a move of a set item, or +- an item could not be taken off because the bags were full, or +- the equipped items stopped changing before the swap was complete. + This occurs, for example, when you cancel the bind-on-equip + confirmation for a set item. + +Slots that the swap skipped (missing items, combat, a closed bank) do +not make the swap fail. ### `WEAR_EQUIPMENT_SET` event @@ -7803,9 +7823,10 @@ Silent no-op if no set with that name exists. The owner anchor must be set before the call — `SetEquipmentSet` only fills the lines, it doesn't re-anchor the tooltip frame. -Item classification reuses `Locations::FindGUID` (the same walk -`GetItemCount` uses), so items in the bank count as "in inventory" -without requiring the bank window to be open. +The counts are the same as in +[`C_EquipmentSet.GetEquipmentSetInfo`](#c_equipmentsetgetequipmentsetinfosetid). +An item in the bank counts as "in inventory" only while the bank window +is open. **Localization.** The count lines are formatted through [`Game::Lua::PushLocalizedFormatInt`](#) — Blizzard's `ITEMS_VARIABLE_QUANTITY`, @@ -7837,6 +7858,18 @@ before the itemID field was added load fine but render their missing slots with the count summary `%d missing` instead of named lines; re-saving a set repopulates itemIDs. +### Equipment sets on item tooltips + +An item tooltip shows the line `Equipment Sets: ` when the item +belongs to one or more sets. The line uses `EQUIPMENT_SETS` and +`PLAYER_LIST_DELIMITER`, and is added before `OnTooltipSetItem` runs. + +Set the cvar `dontShowEquipmentSetsOnItems` to `1` to hide the line: + +```lua +SetCVar("dontShowEquipmentSetsOnItems", "1") +``` + ### `GameTooltip:SetTotem(slot)` Fills the tooltip with the shaman totem currently active in `slot` diff --git a/src/Offsets.h b/src/Offsets.h index 4da6b140..f5c19933 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -2464,6 +2464,15 @@ enum Offsets { // `Combat::Swing` treats this as an OffHand reset for the local player. SMSG_ATTACKSTART = 0x143, + // An inventory move the server refused. Routed to the shared handler + // `FUN_005E38C0` (registered at `0x005E3039`), whose 0x112 case reads: + // u8 error (0 = no error, nothing follows); u32 required level only when + // error == 1; u64 item1; u64 item2; u8 bag. It shows the message itself + // (`FUN_00622630` maps the code to a game-message row, then + // `FUN_00496720`) and unlocks both items. `EquipmentSet::Pending` reads it + // to fail a set swap that touched either item. + SMSG_INVENTORY_CHANGE_FAILURE = 0x112, + // NetClient send — `__thiscall void(void *conn, CDataStore *packet)`. // The outgoing counterpart of FUN_NET_MESSAGE_DISPATCH: every CMSG the // client sends funnels through it (the argless wrapper `FUN_005AB630`, @@ -5056,6 +5065,11 @@ enum Offsets { // arrays at `0x00BC6B60` / `0x00BC67A0`, which `IsUsableAction` reads. // Only those two callers; both are event-driven. FUN_ACTION_SLOT_USABLE = 0x004E5050, + // The bulk recompute above — `void __cdecl()`: FUN_ACTION_SLOT_USABLE for + // slots 0..0x77, store any changed value into both arrays, and fire + // ACTIONBAR_UPDATE_USABLE (0xD7, via FUN_FIRE_EVENT_NO_ARGS) when one did. + // Disassembled; it is 4.3.4's `CGActionBar::UpdateUsable` line for line. + FUN_ACTION_UPDATE_USABLE = 0x004E5C00, // Drop the cursor onto a slot — `__fastcall(uint slot0)`. Sole entry // for `PlaceAction`, and the tail of both FUN_ACTION_PICKUP and // nampower's detoured `CGActionBar_UseAction` (`0x004E5EE0`) when the diff --git a/src/container/EquipmentSetInfo.cpp b/src/container/EquipmentSetInfo.cpp index 91743460..623d7ca3 100644 --- a/src/container/EquipmentSetInfo.cpp +++ b/src/container/EquipmentSetInfo.cpp @@ -24,30 +24,25 @@ // reserved empty / ignored slot markers can never match a real GUID, // and `Data::SetsContainingItem` rejects them outright. // -// `setList` is the set names joined with `", "`, in set order, which is -// the shape a caller formats straight into a tooltip line. It is `nil` +// `setList` is 4.3.4's `GetSetList`: the set names in set order, joined by +// PLAYER_LIST_DELIMITER — the shape a caller formats straight into a +// tooltip line. It is `nil` // rather than an empty string when the item is in no set, so the usual // `if inSet then … setList … end` guard is all a caller needs. #include "Game.h" #include "Offsets.h" -#include "equipmentset/Data.h" -#include "equipmentset/Set.h" +#include "equipmentset/Text.h" #include "item/CGItem.h" #include "item/Location.h" #include #include -#include namespace Container::EquipmentSetInfo { namespace { -// The separator between names in `setList`. One place, so the string a -// caller splits on is stated once. -constexpr const char *kSeparator = ", "; - uint64_t ItemGuid(const uint8_t *cgItem) { auto *instance = Item::InstanceBlock(cgItem); if (instance == nullptr) @@ -71,23 +66,15 @@ int __fastcall Script_C_Container_GetContainerItemEquipmentSetInfo(void *L) { const uint64_t guid = ItemGuid(Item::Location::ResolveBag(L, bagID, slotIndex)); - const std::vector sets = - EquipmentSet::Data::SetsContainingItem(guid); + const std::string setList = EquipmentSet::Text::SetList(guid); Game::Lua::SetTop(L, 0); - if (sets.empty()) { + if (setList.empty()) { Game::Lua::PushBool(L, false); Game::Lua::PushNil(L); return 2; } - std::string setList; - for (size_t i = 0; i < sets.size(); ++i) { - if (i > 0) - setList += kSeparator; - setList += sets[i]->name; - } - Game::Lua::PushBool(L, true); Game::Lua::PushString(L, setList.c_str()); return 2; diff --git a/src/equipmentset/Action.cpp b/src/equipmentset/Action.cpp index ec51feb4..de121246 100644 --- a/src/equipmentset/Action.cpp +++ b/src/equipmentset/Action.cpp @@ -56,6 +56,7 @@ #include "Game.h" #include "Locations.h" #include "Offsets.h" +#include "Pending.h" #include "event/Custom.h" #include @@ -236,15 +237,21 @@ int __fastcall GetActionText_h(void *L) { return 1; } -// 3.3.5 `FUN_005a9e20`'s set branch: unusable while the set is gone or -// holds an item mid-transaction. +// 4.3.4 `CGActionBar::UpdateUsableAction`'s set branch: unusable while a +// swap is in flight, the set is gone, one of its items is mid-transaction, +// or an item it would replace is. uint32_t __fastcall Usable_h(uint32_t slot0, int *outNoMana) { const uint32_t setID = SetIDAt(slot0); if (setID == 0) return g_origUsable(slot0, outNoMana); *outNoMana = 0; + if (!Pending::CanUse()) + return 0; const Set *s = Data::FindByID(setID); - return (s != nullptr && !Locations::ContainsLockedItems(*s)) ? 1 : 0; + return (s != nullptr && !Locations::ContainsLockedItems(*s) && + !Locations::UsesLockedSlots(*s)) + ? 1 + : 0; } void __fastcall Notify_h(uint32_t slot0, int sendToServer, int quiet) { diff --git a/src/equipmentset/Api.cpp b/src/equipmentset/Api.cpp index c41e7a46..68b1ca6e 100644 --- a/src/equipmentset/Api.cpp +++ b/src/equipmentset/Api.cpp @@ -19,10 +19,9 @@ // the same way `VanillaMinimapTracking` keeps its tracking config. // // Identity is by item GUID — `SaveEquipmentSet` snapshots the GUIDs -// currently worn, and `UseEquipmentSet` searches every player-owned -// container for those GUIDs at use time. The GUID search reads -// invMgr GUID arrays directly (same trick `C_Item.GetItemCount` -// uses), so bank items resolve without the bank window being open. +// currently worn, and `UseEquipmentSet` searches the player's bags (and +// the bank, while it is open) for those GUIDs at use time. Behavior +// follows 4.3.4's native equipment manager (`CGEquipmentManager`). // // Modern Classic Era's signatures use a numeric `iconFileID`; we // accept icon paths (e.g. `"INV_Shield_06"`) instead because vanilla @@ -34,14 +33,17 @@ #include "Game.h" #include "Locations.h" #include "Offsets.h" +#include "Pending.h" #include "Set.h" -#include "event/Custom.h" +#include "Text.h" #include "item/CGItem.h" #include "item/Location.h" #include "item/Swap.h" +#include "unit/Identity.h" #include #include +#include namespace EquipmentSet::Api { @@ -87,11 +89,9 @@ void PushTableEntry(void *L, int key, double value) { Game::Lua::SetTable(L, -3); } -// 1.12 has no concept of "uncomingable equipment-set support", so -// `CanUseEquipmentSets` is always true (we mirror what Classic Era -// 1.15 does — it returns true unconditionally there as well). +// 4.3.4 `CanUseEquipmentSets`: false while a swap is in flight. int __fastcall Script_CanUseEquipmentSets(void *L) { - Game::Lua::PushBool(L, 1); + Game::Lua::PushBool(L, Pending::CanUse()); return 1; } @@ -131,55 +131,25 @@ int __fastcall Script_GetEquipmentSetID(void *L) { // Returns the 9-tuple Blizzard ships: // name, icon, setID, isEquipped, numItems, numEquipped, // numInInventory, numMissing, numIgnored -// -// `numItems` excludes ignored slots — matches modern semantics where -// an ignored slot is "not part of the set", not "part of the set but -// unfilled". `isEquipped` is the boolean equivalent of -// `numEquipped == numItems`; modern flips it true even when missing -// items exist, as long as everything currently *resolvable* is in its -// target slot. We follow that — strict-equipped semantics break in -// useful cases (e.g. you're at a bank without your bank-stored cloak). +// — 4.3.4 `Script_GetEquipmentSetInfo`: the counts are +// `Locations::GetStatus`, `isEquipped` is the strict +// `Locations::IsEquipped`. int __fastcall Script_GetEquipmentSetInfo(void *L) { const uint32_t setID = ArgSetID(L, 1); const Set *s = Data::FindByID(setID); if (s == nullptr) return 0; - int numItems = 0; - int numEquipped = 0; - int numInInventory = 0; - int numMissing = 0; - int numIgnored = 0; - for (int i = 0; i < SLOT_COUNT; ++i) { - const uint64_t g = s->items[i]; - if (g == GUID_IGNORED) { - ++numIgnored; - continue; - } - if (g == GUID_EMPTY) - continue; - ++numItems; - const int loc = Locations::FindGUID(g); - if (loc == 0) { - ++numMissing; - } else if ((loc & LOC_BAGS) == 0 && (loc & LOC_BANK) == 0 && - (loc & LOC_SLOT_MASK) == (i + 1)) { - ++numEquipped; - } else { - ++numInInventory; - } - } - + const Locations::Status st = Locations::GetStatus(*s); Game::Lua::PushString(L, s->name.c_str()); Game::Lua::PushString(L, s->icon.c_str()); Game::Lua::PushNumber(L, static_cast(s->setID)); - Game::Lua::PushBoolean(L, (numItems > 0 && numEquipped + numMissing == numItems && - numInInventory == 0)); - Game::Lua::PushNumber(L, static_cast(numItems)); - Game::Lua::PushNumber(L, static_cast(numEquipped)); - Game::Lua::PushNumber(L, static_cast(numInInventory)); - Game::Lua::PushNumber(L, static_cast(numMissing)); - Game::Lua::PushNumber(L, static_cast(numIgnored)); + Game::Lua::PushBoolean(L, Locations::IsEquipped(*s) ? 1 : 0); + Game::Lua::PushNumber(L, static_cast(st.total)); + Game::Lua::PushNumber(L, static_cast(st.equipped)); + Game::Lua::PushNumber(L, static_cast(st.inInventory)); + Game::Lua::PushNumber(L, static_cast(st.missing)); + Game::Lua::PushNumber(L, static_cast(st.ignored)); return 9; } @@ -201,10 +171,10 @@ int __fastcall Script_GetIgnoredSlots(void *L) { return 1; } -// Modern returns a hash table { [slot] = itemID } with one entry per -// non-empty, non-ignored slot. Missing items still get an entry — but -// since we can't recover an itemID from a GUID alone after the item -// has left the client (e.g. mailed away), missing slots are omitted. +// 4.3.4 `Script_GetEquipmentSetItemIDs`: { [slot] = value } for all 19 +// slots — 0 empty, 1 ignored, else the itemID, or -1 when it can't be +// resolved. An item no longer in the client still has the itemID saved +// with the set, so -1 is left for sets saved before that was recorded. int __fastcall Script_GetItemIDs(void *L) { const uint32_t setID = ArgSetID(L, 1); const Set *s = Data::FindByID(setID); @@ -214,39 +184,39 @@ int __fastcall Script_GetItemIDs(void *L) { Game::Lua::NewTable(L); for (int i = 0; i < SLOT_COUNT; ++i) { const uint64_t g = s->items[i]; - if (g == GUID_EMPTY || g == GUID_IGNORED) - continue; - const uint8_t *item = Locations::ResolveItemByGUID(g); - const int itemID = ResolveItemID(item); - if (itemID == 0) - continue; - PushTableEntry(L, i + 1, static_cast(itemID)); + int value = static_cast(g); // GUID_EMPTY 0 / GUID_IGNORED 1 + if (g != GUID_EMPTY && g != GUID_IGNORED) { + value = ResolveItemID(Locations::ResolveItemByGUID(g)); + if (value == 0) + value = static_cast(s->itemIDs[i]); + if (value == 0) + value = -1; + } + PushTableEntry(L, i + 1, static_cast(value)); } return 1; } -// Hash table { [slot] = locationCode } — same encoding modern uses, -// see Set.h's pack helpers. Ignored slots produce `LOC_IGNORED`, -// missing items produce `LOC_MISSING`, found items produce the -// packed `LOC_PLAYER|...|slot` code. Empty (uninitialized) slots -// don't appear in the table. +// 4.3.4 `Script_GetEquipmentSetLocations`: { [slot] = locationCode } for +// all 19 slots — 0 empty, `LOC_IGNORED`, the packed location (see Set.h), +// or `LOC_MISSING`. Bank items count only while the bank is open, the +// same rule `UseEquipmentSet` swaps by. int __fastcall Script_GetItemLocations(void *L) { const uint32_t setID = ArgSetID(L, 1); const Set *s = Data::FindByID(setID); if (s == nullptr) return 0; + const bool bank = Locations::BankerOpen(); Game::Lua::SetTop(L, 0); Game::Lua::NewTable(L); for (int i = 0; i < SLOT_COUNT; ++i) { const uint64_t g = s->items[i]; - if (g == GUID_EMPTY) - continue; - int loc; + int loc = 0; if (g == GUID_IGNORED) { loc = LOC_IGNORED; - } else { - loc = Locations::FindGUID(g); + } else if (g != GUID_EMPTY) { + loc = Locations::FindGUID(g, bank); if (loc == 0) loc = LOC_MISSING; } @@ -255,14 +225,27 @@ int __fastcall Script_GetItemLocations(void *L) { return 1; } +// The name argument at `idx`, scrubbed as 4.3.4 does. Raises its +// "Invalid string for setName" error and returns false when the scrub +// rejects it. +bool ArgName(void *L, int idx, std::string *out) { + if (Data::ScrubName(ArgString(L, idx), out)) + return true; + Game::Lua::Error(L, "Invalid string for setName"); + return false; +} + int __fastcall Script_CreateEquipmentSet(void *L) { - const char *name = ArgString(L, 1); - if (name == nullptr || name[0] == '\0') { + const char *raw = ArgString(L, 1); + if (raw == nullptr || raw[0] == '\0') { Game::Lua::Error(L, "Usage: C_EquipmentSet.CreateEquipmentSet(name [, icon])"); return 0; } + std::string name; + if (!ArgName(L, 1, &name)) + return 0; const char *icon = ArgString(L, 2); - const uint32_t setID = Data::Create(name, icon); + const uint32_t setID = Data::Create(name.c_str(), icon); if (setID == 0) return 0; Game::Lua::PushNumber(L, static_cast(setID)); @@ -283,13 +266,16 @@ int __fastcall Script_SaveEquipmentSet(void *L) { int __fastcall Script_ModifyEquipmentSet(void *L) { const uint32_t setID = ArgSetID(L, 1); - const char *newName = ArgString(L, 2); - if (setID == 0 || newName == nullptr || newName[0] == '\0') { + const char *raw = ArgString(L, 2); + if (setID == 0 || raw == nullptr || raw[0] == '\0') { Game::Lua::Error(L, "Usage: C_EquipmentSet.ModifyEquipmentSet(setID, newName)"); return 0; } - if (Data::Rename(setID, newName)) + std::string name; + if (!ArgName(L, 2, &name)) + return 0; + if (Data::Rename(setID, name.c_str())) Action::Repaint(setID); // buttons show the name return 0; } @@ -340,211 +326,215 @@ int __fastcall Script_EquipmentSetContainsLockedItems(void *L) { return 1; } -// Walks the set and dispatches one atomic server-side swap per item -// that isn't already in its target slot. Items currently in the main -// bank or bank bags are skipped silently — vanilla rejects equip -// from bank slots server-side, so the user needs to retrieve them -// first. +// 4.3.4 `CGEquipmentManager::UseEquipmentSet`, over 1.12's per-item swap +// packets instead of its single CMSG_EQUIPMENT_SET_USE: +// - refused (ERR_CLIENT_LOCKED_OUT, the same "You can't do that right +// now." text as 4.3.4's SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW) while a +// swap is in flight or the cursor holds a bag item; +// - in combat only the weapon slots swap, with one COMBAT_SWAP message +// when another slot would have changed; +// - an item that can't be found is skipped, with one MISSING_ITEM +// message; +// - bank items are used only while the bank is open (the server refuses +// them otherwise); +// - the result arrives later as EQUIPMENT_SWAP_FINISHED (see +// `EquipmentSet::Pending`). // -// Cycle handling: with cursor-based pickup+equip, swap cycles (e.g. -// rings A↔B wanting each other's slots) needed a temp-bag-slot -// shuffle. We now call the engine's own `FUN_INVENTORY_SWAP` per -// item, which sends opcode 0x10D / 0x10C through the engine's -// packet pipeline — an atomic server-side swap. A two-cycle resolves -// in one call (server swaps both slots from one packet); the cursor -// is never touched. See TODO #59 for the primitive's decoding and -// TODO #73 for the cycle-resolution rationale. +// Each move is the engine's own `FUN_INVENTORY_SWAP` (opcodes 0x10D / +// 0x10C), an atomic server-side swap that never touches the cursor, so a +// two-item cycle (rings A<->B) resolves in one packet. Sources are resolved +// against the state BEFORE anything is sent: the engine's inventory only +// changes when the server answers, so a lookup between packets would see +// stale locations. A virtual paperdoll tracks the moves instead. + +bool CursorHoldsBagItem() { + return Game::Read(Offsets::VAR_CURSOR_TYPE) == 1 && + (Game::Read(Offsets::VAR_CURSOR_ITEM_GUID_LO) != 0 || + Game::Read(Offsets::VAR_CURSOR_ITEM_GUID_HI) != 0); +} + +bool PlayerInCombat() { + const uint8_t *desc = Unit::Identity::PlayerDescriptor(); + return desc != nullptr && + (Game::Read(desc, Offsets::OFF_UNIT_FIELD_FLAGS) & + Offsets::UNIT_FLAG_IN_COMBAT) != 0; +} + +// The Lua bagID and 1-based slot of a bag or bank location code (see +// Set.h's pack helpers): 0..4 player bags, -1 main bank, 5..10 bank bags. +void UnpackContainer(int loc, int *bagID, int *slot) { + *slot = loc & LOC_SLOT_MASK; + const int bag = (loc >> LOC_BAG_SHIFT) & 0xFF; + if ((loc & LOC_BANK) == 0) + *bagID = bag; + else if ((loc & LOC_BAGS) == 0) + *bagID = -1; + else + *bagID = bag + BANK_BAG_OFFSET; +} + int __fastcall Script_UseEquipmentSet(void *L) { const uint32_t setID = ArgSetID(L, 1); const Set *s = Data::FindByID(setID); if (s == nullptr) { - const int evt = kEvtSwapFinished.Slot(); - if (evt >= 0) - Event::Custom::Fire(evt, "%d%d", 0, static_cast(setID)); + Game::Lua::PushBoolean(L, 0); + return 1; + } + if (!Pending::CanUse() || CursorHoldsBagItem()) { + Text::UIError("ERR_CLIENT_LOCKED_OUT", "You can't do that right now."); Game::Lua::PushBoolean(L, 0); return 1; } - // Fire PENDING right after the set-exists check, before any of - // the swap work. Addon UI can use this to gate swap-in-progress - // visuals. - const int pendingEvt = kEvtSwapPending.Slot(); - if (pendingEvt >= 0) - Event::Custom::Fire(pendingEvt, "%d", static_cast(setID)); - - // If the cursor is holding anything, return it to its source slot - // and unlock it server-side BEFORE our swap chain runs. The - // engine's FUN_INVENTORY_SWAP ends each call with a cursor-state - // cleanup that clears the LOCAL cursor view, but never sends the - // server-side cancel-pickup packet — so a held item would stay - // server-locked until relog. ClearCursor sends the right packet. - // No-op when the cursor is idle (still fires one CURSOR_UPDATE, - // negligible). - Game::Lua::SetTop(L, 0); - reinterpret_cast( - Offsets::FUN_SCRIPT_CLEAR_CURSOR)(L); - - // Snapshot the set's items into a local — Locations::FindGUID - // can shuffle the Lua stack, and we've already passed validation. + // Copy what the swap needs: the free-slot scan below stomps the Lua + // stack, and the error messages run Lua handlers. + const std::string name = s->name; uint64_t guids[SLOT_COUNT]; std::memcpy(guids, s->items, sizeof(guids)); - // Snapshot empty bag slots up front. The CGItem state doesn't - // update between packet sends (server has to acknowledge each - // swap), so iterating the bag walk fresh per unequip would - // repeatedly pick the same "first empty" slot — second packet - // collides with what packet 1 just put there, and the server - // tries to swap that item back onto the wrong paperdoll slot - // → "This item cannot be equipped". + Pending::Request req{}; + req.setID = setID; + auto noteMoved = [&req](uint64_t g) { + if (g != 0) + req.moved[req.movedCount++] = g; + }; + + uint64_t virtualPaperdoll[SLOT_COUNT]; + Locations::SnapshotPaperdoll(virtualPaperdoll); + + // Decide every slot against the original state. + const bool inCombat = PlayerInCombat(); + const bool bank = Locations::BankerOpen(); + bool combatWarned = false; + bool missingWarned = false; + int sourceLoc[SLOT_COUNT] = {}; + for (int i = 0; i < SLOT_COUNT; ++i) { + const uint64_t g = guids[i]; + if (g == GUID_IGNORED) + continue; + if (inCombat && !SwapsInCombat(i + 1)) { + if (!combatWarned && g != virtualPaperdoll[i]) { + Text::UIError("ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S", + "Some items from set %s cannot be swapped because " + "you are in combat.", + name.c_str()); + combatWarned = true; + } + continue; + } + if (g != GUID_EMPTY) { + sourceLoc[i] = Locations::FindGUID(g, bank); + if (sourceLoc[i] == 0) { + if (!missingWarned) { + Text::UIError("ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S", + "One or more items from set %s were missing and " + "could not be equipped.", + name.c_str()); + missingWarned = true; + } + continue; + } + } + req.want[i] = g; + req.cares[i] = true; + } + + // Free bag slots for phase 3, snapshotted up front for the same + // stale-state reason: a fresh scan per unequip would keep finding the + // same "first empty" slot. At most every slot comes off. struct FreeSlot { int bag; int slot; }; - FreeSlot freeSlots[64]; + FreeSlot freeSlots[SLOT_COUNT]; int freeSlotCount = 0; - for (int bag = 0; bag <= 4 && freeSlotCount < 64; ++bag) { + for (int bag = 0; bag <= 4 && freeSlotCount < SLOT_COUNT; ++bag) { const int slots = Item::Location::GetBagSlotCount(bag); - for (int slot = 1; slot <= slots && freeSlotCount < 64; ++slot) { + for (int slot = 1; slot <= slots && freeSlotCount < SLOT_COUNT; ++slot) { if (Item::Location::ResolveBag(L, bag, slot) == nullptr) freeSlots[freeSlotCount++] = {bag, slot}; } } int nextFreeSlot = 0; - // Pre-snapshot each set item's location against the ORIGINAL - // state, before any swap packets fly. This mirrors how 4.3.4's - // `Script_UseEquipmentSet` (`0x009A15D0`) builds its action list: - // resolve all 19 source locations up front, then execute. The - // engine's CGItem / InvMgr state lags behind our packet sends - // (waits for server ACK), so any `FindGUID` mid-execution would - // return stale answers and we'd re-resolve items into the wrong - // place. - int sourceLoc[SLOT_COUNT]; - for (int i = 0; i < SLOT_COUNT; ++i) { - const uint64_t g = guids[i]; - if (g == GUID_EMPTY || g == GUID_IGNORED) { - sourceLoc[i] = 0; - continue; - } - sourceLoc[i] = Locations::FindGUID(g); - } - - // Virtual paperdoll occupant model — seeded from the engine's - // initial paperdoll GUID array, then updated in-place after each - // swap so phase 1 can chain rotations and phase 3 can spot - // already-empty slots. - uint64_t virtualPaperdoll[SLOT_COUNT]; - Locations::SnapshotPaperdoll(virtualPaperdoll); - - // Locates the current virtual slot of a GUID on the paperdoll, - // or 0 if it's not currently there. Used during phase 1 so - // chained paperdoll-to-paperdoll moves operate on the *current* - // virtual position, not the stale pre-snapshot. auto currentPaperdollSlot = [&](uint64_t g) -> int { - if (g == 0) - return 0; - for (int slot = 1; slot <= SLOT_COUNT; ++slot) { + for (int slot = 1; slot <= SLOT_COUNT; ++slot) if (virtualPaperdoll[slot - 1] == g) return slot; - } return 0; }; - // ── Phase 1: paperdoll → paperdoll ───────────────────────────── - // Move items already on the paperdoll into their target slots. - // Source and destination are both paperdoll, so atomic swaps - // never touch bag state — phase 2's bag lookups stay accurate. + // Phase 1: paperdoll -> paperdoll. Neither side is a bag, so phase 2's + // bag sources stay valid. for (int i = 0; i < SLOT_COUNT; ++i) { const int targetSlot = i + 1; const uint64_t g = guids[i]; - if (g == GUID_EMPTY || g == GUID_IGNORED) + if (!req.cares[i] || g == GUID_EMPTY || + (sourceLoc[i] & (LOC_BAGS | LOC_BANK)) != 0) continue; - - const int loc = sourceLoc[i]; - if (loc == 0) - continue; - if (loc & LOC_BANK) - continue; // server rejects equip-from-bank - if (loc & LOC_BAGS) - continue; // phase 2 - const int srcSlot = currentPaperdollSlot(g); if (srcSlot == 0 || srcSlot == targetSlot) - continue; // missing or already there - - const uint8_t *item = Locations::ResolveItemByGUID(g); - if (item == nullptr) continue; - const uint64_t displaced = virtualPaperdoll[targetSlot - 1]; - if (Item::Swap::FromPaperdoll(item, srcSlot, targetSlot)) { + if (Item::Swap::FromPaperdoll(Locations::ResolveItemByGUID(g), srcSlot, + targetSlot)) { virtualPaperdoll[targetSlot - 1] = g; virtualPaperdoll[srcSlot - 1] = displaced; + noteMoved(g); + noteMoved(displaced); + } else { + req.cares[i] = false; } } - // ── Phase 2: bag → paperdoll ─────────────────────────────────── - // Move items from bag slots onto the paperdoll. Each atomic swap - // displaces the current paperdoll occupant into the bag slot the - // incoming item vacated. Anything we still wanted on the paperdoll - // was already placed by phase 1, so phase 2 displacements can't - // strand a future set item in a bag. + // Phase 2: bag / bank -> paperdoll. The paperdoll occupant lands where + // the incoming item was. Anything the set still wanted worn was placed + // by phase 1, so a displacement here can't strand a set item. for (int i = 0; i < SLOT_COUNT; ++i) { const int targetSlot = i + 1; const uint64_t g = guids[i]; - if (g == GUID_EMPTY || g == GUID_IGNORED) + if (!req.cares[i] || g == GUID_EMPTY || + (sourceLoc[i] & (LOC_BAGS | LOC_BANK)) == 0) continue; - if (virtualPaperdoll[targetSlot - 1] == g) - continue; // already at target (probably by phase 1) - - const int loc = sourceLoc[i]; - if (loc == 0) - continue; - if (loc & LOC_BANK) - continue; - if ((loc & LOC_BAGS) == 0) - continue; // not from a bag — phase 1 handled, or item missing - - const uint8_t *item = Locations::ResolveItemByGUID(g); - if (item == nullptr) - continue; - - const int srcBag = (loc >> LOC_BAG_SHIFT) & 0xFF; - const int srcSlot = loc & LOC_SLOT_MASK; - if (Item::Swap::FromBag(item, srcBag, srcSlot, targetSlot)) { + int bagID = 0; + int slot = 0; + UnpackContainer(sourceLoc[i], &bagID, &slot); + const uint64_t displaced = virtualPaperdoll[targetSlot - 1]; + if (Item::Swap::FromBag(Locations::ResolveItemByGUID(g), bagID, slot, + targetSlot)) { virtualPaperdoll[targetSlot - 1] = g; - // The displaced item lands in (srcBag, srcSlot). We - // don't track bag-side virtual state — by phase 3 we - // only care about the paperdoll occupant. + noteMoved(g); + noteMoved(displaced); + } else { + req.cares[i] = false; } } - // ── Phase 3: unequip slots the set wants empty ───────────────── - // For each `GUID_EMPTY` slot, send the current paperdoll occupant - // (if any) to a pre-snapshotted free bag slot. Runs last so any - // displaced items from phases 1/2 that landed in the slot get - // unequipped here too. + // Phase 3: take off what the set wants empty. Runs last so an item + // phases 1/2 displaced into such a slot comes off too. No free bag slot + // is 4.3.4's bags-full result. for (int i = 0; i < SLOT_COUNT; ++i) { const int targetSlot = i + 1; - if (guids[i] != GUID_EMPTY) - continue; const uint64_t occupant = virtualPaperdoll[targetSlot - 1]; - if (occupant == 0) + if (!req.cares[i] || guids[i] != GUID_EMPTY || occupant == 0) continue; - if (nextFreeSlot >= freeSlotCount) - continue; - const uint8_t *equipped = Locations::ResolveItemByGUID(occupant); - if (equipped == nullptr) + if (nextFreeSlot >= freeSlotCount) { + req.bagsFull = true; + req.cares[i] = false; continue; + } const FreeSlot &fs = freeSlots[nextFreeSlot++]; - if (Item::Swap::ToBag(equipped, targetSlot, fs.bag, fs.slot)) + if (Item::Swap::ToBag(Locations::ResolveItemByGUID(occupant), targetSlot, + fs.bag, fs.slot)) { virtualPaperdoll[targetSlot - 1] = 0; + noteMoved(occupant); + } else { + req.cares[i] = false; + } } - const int evt = kEvtSwapFinished.Slot(); - if (evt >= 0) - Event::Custom::Fire(evt, "%d%d", 1, static_cast(setID)); - + Pending::Begin(req); + Game::Lua::SetTop(L, 0); Game::Lua::PushBoolean(L, 1); return 1; } diff --git a/src/equipmentset/Data.cpp b/src/equipmentset/Data.cpp index e66d8f50..b7c51ed3 100644 --- a/src/equipmentset/Data.cpp +++ b/src/equipmentset/Data.cpp @@ -85,6 +85,29 @@ void Persist() { Storage::Save(g_path, g_sets); } +// 4.3.4's `ValidateStringIsUTF8` rejects a malformed sequence: a lead +// byte without its continuation bytes, or a stray continuation byte. +bool ValidUtf8(const char *s) { + for (auto *p = reinterpret_cast(s); *p != 0;) { + int extra = 0; + if (*p < 0x80) + extra = 0; + else if ((*p & 0xE0) == 0xC0) + extra = 1; + else if ((*p & 0xF0) == 0xE0) + extra = 2; + else if ((*p & 0xF8) == 0xF0) + extra = 3; + else + return false; + ++p; + for (int i = 0; i < extra; ++i, ++p) + if ((*p & 0xC0) != 0x80) + return false; + } + return true; +} + } // namespace void EnsureLoaded() { @@ -162,6 +185,28 @@ std::vector SetsContainingItem(uint64_t itemGuid) { return found; } +bool ScrubName(const char *src, std::string *out) { + out->clear(); + if (src == nullptr) + return true; + bool valid = ValidUtf8(src); + for (const char *c = src; *c != '\0'; ++c) { + // Line break: a real CR/LF, or the escaped `\n` / `|n` forms. + if (*c == '\r' || *c == '\n' || ((*c == '\\' || *c == '|') && c[1] == 'n')) + return false; + if (*c != '|') + out->push_back(*c); + } + int chars = 0; + for (size_t i = 0; i < out->size(); ++i) { + if ((static_cast((*out)[i]) & 0xC0) != 0x80 && ++chars == MAX_NAME_CHARS) { + out->resize(i); + return false; + } + } + return valid; +} + uint32_t Create(const char *name, const char *icon) { EnsureLoaded(); if (g_path.empty() || name == nullptr || name[0] == '\0') @@ -171,8 +216,6 @@ uint32_t Create(const char *name, const char *icon) { Set s; s.setID = NextAvailableID(); s.name = name; - if (s.name.size() > MAX_NAME_LEN) - s.name.resize(MAX_NAME_LEN); s.icon = (icon != nullptr && icon[0] != '\0') ? icon : DefaultIcon(); PopulateFromEquipped(&s); g_sets.push_back(std::move(s)); @@ -209,8 +252,6 @@ bool Rename(uint32_t setID, const char *newName) { if (clash != nullptr && clash->setID != setID) return false; g_sets[idx].name = newName; - if (g_sets[idx].name.size() > MAX_NAME_LEN) - g_sets[idx].name.resize(MAX_NAME_LEN); Persist(); FireChanged(); return true; diff --git a/src/equipmentset/Data.h b/src/equipmentset/Data.h index 4ca65d0f..f842621e 100644 --- a/src/equipmentset/Data.h +++ b/src/equipmentset/Data.h @@ -43,10 +43,17 @@ int IndexOf(uint32_t setID); // 0-based; -1 if missing // until the next mutation. std::vector SetsContainingItem(uint64_t itemGuid); +// 4.3.4 `ScrubString(src, dest, MAX_NAME_CHARS, …, flags 1)`: drops `|`, +// cuts at the first line break (`\r`, `\n`, or a literal `\n` / `|n`), and +// cuts at the MAX_NAME_CHARS-th character. Writes what survives to `out` +// and returns false when anything was cut or `src` isn't valid UTF-8 — +// the caller's "Invalid string for setName" error. +bool ScrubName(const char *src, std::string *out); + // Mutations — bump-and-save semantics. Each returns the affected // set's ID (or 0 on failure), persists to disk, and fires // `EQUIPMENT_SETS_CHANGED`. Callers don't need to manage the file -// directly. +// directly. Names must already be scrubbed (`ScrubName`). uint32_t Create(const char *name, const char *icon); bool SaveExisting(uint32_t setID, const char *icon); bool Rename(uint32_t setID, const char *newName); diff --git a/src/equipmentset/Locations.cpp b/src/equipmentset/Locations.cpp index 129a6afa..4ce9a2a5 100644 --- a/src/equipmentset/Locations.cpp +++ b/src/equipmentset/Locations.cpp @@ -13,6 +13,7 @@ #include "Locations.h" +#include "Game.h" #include "Offsets.h" #include "item/Location.h" #include "object/Resolve.h" @@ -88,7 +89,11 @@ int WalkBagContents(uint64_t bagGuid, uint64_t targetGuid) { } // namespace -int FindGUID(uint64_t targetGuid) { +bool BankerOpen() { + return Game::Read(Offsets::VAR_BANK_GATE_GUID) != 0; +} + +int FindGUID(uint64_t targetGuid, bool includeBank) { if (targetGuid == GUID_EMPTY || targetGuid == GUID_IGNORED) return 0; @@ -110,14 +115,6 @@ int FindGUID(uint64_t targetGuid) { return PackBag(0, s - LINEAR_BACKPACK_FIRST + 1); } - // Main bank (linear 39..62 → slots 1..24). Direct read; the bank - // gate at `VAR_BANK_GATE_GUID` doesn't affect the underlying data. - for (int s = Offsets::INVMGR_BANK_MAIN_FIRST_SLOT; - s <= Offsets::INVMGR_BANK_MAIN_LAST_SLOT; ++s) { - if (guids[s] == targetGuid) - return PackMainBank(s - Offsets::INVMGR_BANK_MAIN_FIRST_SLOT + 1); - } - // Player bags 1..4 — bag containers live at linear 19..22 of the // player invMgr; their contents live in each bag's own invMgr. for (int bag = 1; bag <= 4; ++bag) { @@ -127,6 +124,17 @@ int FindGUID(uint64_t targetGuid) { return PackBag(bag, slot); } + if (!includeBank) + return 0; + + // Main bank (linear 39..62 → slots 1..24). Direct read; the bank + // gate at `VAR_BANK_GATE_GUID` doesn't affect the underlying data. + for (int s = Offsets::INVMGR_BANK_MAIN_FIRST_SLOT; + s <= Offsets::INVMGR_BANK_MAIN_LAST_SLOT; ++s) { + if (guids[s] == targetGuid) + return PackMainBank(s - Offsets::INVMGR_BANK_MAIN_FIRST_SLOT + 1); + } + // Bank bags 5..10 — bag containers at linear 63..68. Same walk as // player bags; works without the bank window being open. for (int linear = Offsets::INVMGR_BANK_BAG_FIRST_SLOT; @@ -158,19 +166,68 @@ void SnapshotPaperdoll(uint64_t *out) { out[i] = guids[i]; } +Status GetStatus(const Set &set) { + Status st{}; + const bool bank = BankerOpen(); + for (int i = 0; i < SLOT_COUNT; ++i) { + const uint64_t g = set.items[i]; + if (g == GUID_EMPTY) + continue; + if (g == GUID_IGNORED) { + ++st.ignored; + continue; + } + const int loc = FindGUID(g, bank); + if (loc == 0) + st.missingSlots[st.missing++] = i + 1; + else if ((loc & (LOC_BAGS | LOC_BANK)) == 0) + ++st.equipped; + else + ++st.inInventory; + } + st.total = st.equipped + st.inInventory + st.missing; + return st; +} + +bool IsEquipped(const Set &set) { + uint64_t worn[SLOT_COUNT]; + SnapshotPaperdoll(worn); + for (int i = 0; i < SLOT_COUNT; ++i) { + if (set.items[i] != GUID_IGNORED && set.items[i] != worn[i]) + return false; + } + return true; +} + +namespace { + +bool IsLocked(uint64_t guid) { + const uint8_t *item = ResolveItemByGUID(guid); + if (item == nullptr) + return false; + const uint32_t flags = *reinterpret_cast( + item + Offsets::OFF_ITEM_CLIENT_LOCK); + return (flags & Offsets::ITEM_CLIENT_LOCK_BIT) != 0; +} + +} // namespace + bool ContainsLockedItems(const Set &set) { for (int i = 0; i < SLOT_COUNT; ++i) { const uint64_t g = set.items[i]; if (g == GUID_EMPTY || g == GUID_IGNORED) continue; - if (FindGUID(g) == 0) - continue; - const uint8_t *item = ResolveItemByGUID(g); - if (item == nullptr) - continue; - const uint32_t flags = *reinterpret_cast( - item + Offsets::OFF_ITEM_CLIENT_LOCK); - if (flags & Offsets::ITEM_CLIENT_LOCK_BIT) + if (FindGUID(g, true) != 0 && IsLocked(g)) + return true; + } + return false; +} + +bool UsesLockedSlots(const Set &set) { + uint64_t worn[SLOT_COUNT]; + SnapshotPaperdoll(worn); + for (int i = 0; i < SLOT_COUNT; ++i) { + if (set.items[i] != GUID_IGNORED && worn[i] != 0 && IsLocked(worn[i])) return true; } return false; diff --git a/src/equipmentset/Locations.h b/src/equipmentset/Locations.h index 72070cdd..47aa7da0 100644 --- a/src/equipmentset/Locations.h +++ b/src/equipmentset/Locations.h @@ -19,23 +19,45 @@ namespace EquipmentSet::Locations { -// Searches every location the local player owns for an item whose -// GUID matches `targetGuid`, and returns the packed location code -// (see Set.h's `PackEquipped`/`PackBag`/`PackMainBank`/`PackBankBag`). -// Returns 0 if the GUID isn't found anywhere. +// True while the bank window is open (the engine's banker GUID at +// `VAR_BANK_GATE_GUID` is set) — 4.3.4's `CGBankInfo::m_banker`. The +// server only lets an item leave the bank while a banker is in range +// (`HandleSwapItem`'s `CanUseBank`), so a set treats bank items as +// usable only then. +bool BankerOpen(); + +// Searches the local player's paperdoll, backpack and bags — and the +// bank when `includeBank` — for an item whose GUID matches `targetGuid`, +// and returns the packed location code (see Set.h's +// `PackEquipped`/`PackBag`/`PackMainBank`/`PackBankBag`). Returns 0 if +// the GUID isn't found. // -// Coverage — ALL locations are read via the player invMgr's flat -// GUID array at `+0x04` and (for bag contents) via each bag's own -// invMgr reached through the bag's vtable `+0x10`. None of this -// goes through the engine's `GetItemBySlot` / `PackBagSlot` path, -// so: -// - no Lua stack is touched (safe to call from any callback) -// - bank items resolve without the bank window ever being open -// (the GUIDs are populated from server data at login; only -// `GetItemBySlot` is gated by `VAR_BANK_GATE_GUID`, the -// underlying data is always present — same trick -// `C_Item.GetItemCount` uses) -int FindGUID(uint64_t targetGuid); +// Every location is read via the player invMgr's flat GUID array at +// `+0x04` and (for bag contents) via each bag's own invMgr reached +// through the bag's vtable `+0x10`. None of this goes through the +// engine's `GetItemBySlot` / `PackBagSlot` path, so no Lua stack is +// touched (safe to call from any callback), and bank GUIDs read even +// with the window closed (populated from server data at login). +int FindGUID(uint64_t targetGuid, bool includeBank); + +// 4.3.4 `CGEquipmentManager::GetSetStatus`. Each non-empty slot counts +// once: ignored, worn (in ANY equipment slot), carried (bags, and the +// bank only while `BankerOpen`), else missing. `total` excludes +// ignored slots. `missingSlots[0..missing)` are 1-based slots. +struct Status { + int total; + int equipped; + int inInventory; + int missing; + int ignored; + int missingSlots[SLOT_COUNT]; +}; +Status GetStatus(const Set &set); + +// 4.3.4 `CGEquipmentManager::IsSetEquipped`: every slot the set doesn't +// ignore holds exactly what the set saved — including empty for a slot +// saved empty. +bool IsEquipped(const Set &set); // Resolves a GUID to a `CGItem*` via the engine's GUID→CObject // resolver (`FUN_OBJECT_RESOLVE_BY_GUID`). Returns null if the item @@ -66,4 +88,9 @@ void SnapshotPaperdoll(uint64_t *out); // missing item is missing, not locked. bool ContainsLockedItems(const Set &set); +// 4.3.4 `CGEquipmentManager::SetUsesLockedSlots`: whether an item worn in +// a slot the set would change (any slot it doesn't ignore) is locked. The +// action bar greys a set button on this as well as `ContainsLockedItems`. +bool UsesLockedSlots(const Set &set); + } // namespace EquipmentSet::Locations diff --git a/src/equipmentset/Pending.cpp b/src/equipmentset/Pending.cpp new file mode 100644 index 00000000..cb789fab --- /dev/null +++ b/src/equipmentset/Pending.cpp @@ -0,0 +1,141 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#include "Pending.h" + +#include "Game.h" +#include "Locations.h" +#include "Offsets.h" +#include "Text.h" +#include "event/Custom.h" +#include "net/PacketDispatch.h" +#include "tick/WorldTick.h" +#include "time/Clock.h" + +#include + +namespace EquipmentSet::Pending { + +namespace { + +// How long the paperdoll may sit unchanged before a swap that never reached +// its target is given up on. Each change restarts the wait, so this only +// has to cover one server round trip, not the whole swap. +constexpr uint32_t kSettleMs = 3000; + +bool g_active = false; +bool g_refused = false; +Request g_req; +uint64_t g_lastWorn[SLOT_COUNT]; +uint32_t g_deadline = 0; + +// 4.3.4 calls `CGActionBar::UpdateUsable` whenever the pending state flips, +// so set buttons grey out and come back. +void UpdateUsable() { + reinterpret_cast(Offsets::FUN_ACTION_UPDATE_USABLE)(); +} + +// 4.3.4 `OnEquipmentSetResult`: the event, then the bags-full message, then +// the action bar. +void Finish(bool success) { + g_active = false; + const int evt = kEvtSwapFinished.Slot(); + if (evt >= 0) { + const int id = static_cast(g_req.setID); + if (success) + Event::Custom::Fire(evt, "%d%d", 1, id); + else + Event::Custom::Fire(evt, "%s%d", static_cast(nullptr), id); + } + if (g_req.bagsFull) + Text::UIError("ERR_EQUIPMENT_MANAGER_BAGS_FULL", + "Equipment swap failed. Inventory is full."); + UpdateUsable(); +} + +void OnTick() { + if (!g_active) + return; + if (g_refused) + return Finish(false); + + uint64_t worn[SLOT_COUNT]; + Locations::SnapshotPaperdoll(worn); + bool done = true; + bool changed = false; + for (int i = 0; i < SLOT_COUNT; ++i) { + changed = changed || worn[i] != g_lastWorn[i]; + done = done && (!g_req.cares[i] || worn[i] == g_req.want[i]); + } + if (done) + return Finish(!g_req.bagsFull); + + const uint32_t now = Time::Clock::NowMs(); + if (changed) { + std::memcpy(g_lastWorn, worn, sizeof(worn)); + g_deadline = now + kSettleMs; + } else if (Time::Clock::Reached(now, g_deadline)) { + Finish(false); + } +} + +bool Moved(uint64_t guid) { + for (int i = 0; i < g_req.movedCount; ++i) + if (g_req.moved[i] == guid) + return true; + return false; +} + +// SMSG_INVENTORY_CHANGE_FAILURE — see Offsets.h for the body. The engine's +// own handler shows the message; we only note that the swap failed, and +// settle on the next tick rather than firing Lua from the packet funnel. +void OnPacket(uint32_t opcode, Net::CDataStore *packet) { + if (opcode != Offsets::SMSG_INVENTORY_CHANGE_FAILURE || !g_active) + return; + const uint8_t error = Net::Read(packet); + if (error == 0) + return; + if (error == 1) + Net::Read(packet); // required level + const uint64_t item1 = Net::Read(packet); + const uint64_t item2 = Net::Read(packet); + if ((item1 != 0 && Moved(item1)) || (item2 != 0 && Moved(item2))) + g_refused = true; +} + +// 4.3.4 clears the pending swap on enter-world; a login or /reload is the +// point nothing can still be in flight for the UI that started it. +void OnInGameInit() { g_active = false; } + +const Tick::WorldTick::AutoSubscribe _tick{&OnTick}; +const Net::PacketDispatch::AutoSubscribe _packet{&OnPacket}; +const Game::ModuleAutoRegister _init{&OnInGameInit}; + +} // namespace + +bool CanUse() { return !g_active; } + +void Begin(const Request &req) { + g_req = req; + g_active = true; + g_refused = false; + Locations::SnapshotPaperdoll(g_lastWorn); + g_deadline = Time::Clock::NowMs() + kSettleMs; + + const int evt = kEvtSwapPending.Slot(); + if (evt >= 0) + Event::Custom::Fire(evt, "%d", static_cast(req.setID)); + UpdateUsable(); +} + +} // namespace EquipmentSet::Pending diff --git a/src/equipmentset/Pending.h b/src/equipmentset/Pending.h new file mode 100644 index 00000000..241fe5a9 --- /dev/null +++ b/src/equipmentset/Pending.h @@ -0,0 +1,57 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include "Set.h" + +#include + +// The swap in flight — 4.3.4's `m_swapPending` / `m_pendingSetID`. +// +// 4.3.4 sends one CMSG_EQUIPMENT_SET_USE and waits for +// SMSG_USE_EQUIPMENT_SET_RESULT. 1.12 has neither: a set swap is a series of +// ordinary CMSG_SWAP_ITEMs, and only a refused one answers +// (SMSG_INVENTORY_CHANGE_FAILURE). So the result is read off the engine: +// success — the paperdoll holds what the swap asked for; +// failure — the server refused a move that touched one of our items, or +// the swap found no room for an item it had to take off; +// neither — nothing more will arrive, because a move can wait on the +// player (the engine parks a bind-on-equip item behind +// EQUIP_BIND_CONFIRM, and a declined prompt sends nothing) or on +// an item-cache query. The swap then ends as a failure once the +// paperdoll has stopped changing for kSettleMs. +namespace EquipmentSet::Pending { + +// 4.3.4 `CanUseEquipmentSets`: false while a swap is in flight. +bool CanUse(); + +// What one swap asked for. `want[i]` is what slot i+1 must end up holding +// (0 = empty); `cares[i]` is false for slots the swap left alone (ignored, +// combat-locked, missing items, or a move that could not be sent). `moved` +// lists every item GUID a move touched — set items and the items they +// displaced — so a refusal can be matched to this swap. +struct Request { + uint32_t setID; + uint64_t want[SLOT_COUNT]; + bool cares[SLOT_COUNT]; + uint64_t moved[SLOT_COUNT * 2]; + int movedCount; + bool bagsFull; // an item to take off had no free bag slot +}; + +// Starts tracking `req`, fires EQUIPMENT_SWAP_PENDING and greys the set +// buttons. Settles on a later world tick (see above). +void Begin(const Request &req); + +} // namespace EquipmentSet::Pending diff --git a/src/equipmentset/Set.h b/src/equipmentset/Set.h index 57a971c6..45176c8c 100644 --- a/src/equipmentset/Set.h +++ b/src/equipmentset/Set.h @@ -59,9 +59,16 @@ struct Set { // FrameXML defaults to the question-mark icon when callers pass nil. inline const char *DefaultIcon() { return "INV_Misc_QuestionMark"; } -// Vanilla 1.12 engine accepts equipment-set names up to 32 chars -// (1.15.x is also 32). 4.3.4 used the same buffer size. -constexpr int MAX_NAME_LEN = 31; +// 4.3.4's `Script_SaveEquipmentSet` / `Script_ModifyEquipmentSet` scrub the +// name with `ScrubString(name, dest, 32, …)`, which rejects a name that +// reaches 32 characters (so 31 is the longest that passes). Its 10-set cap +// (`CanCreateSet`) sized a server-side buffer we don't have, so there is +// no set limit here. +constexpr int MAX_NAME_CHARS = 32; + +// 4.3.4 `UseEquipmentSet`: in combat only these slots swap (0-based 15..17 — +// main hand, off hand, ranged); every other slot keeps what it wears. +inline bool SwapsInCombat(int slot1Based) { return slot1Based >= 16 && slot1Based <= 18; } // `GetItemLocations` encoding — matches Blizzard FrameXML's // `EquipmentManager_UnpackLocation` (constants are in @@ -124,20 +131,12 @@ constexpr int LOC_IGNORED = 1; // (create / save / modify / delete / // ignore-slot change). Addon UI re-reads // its list / button state on this. -// EQUIPMENT_SWAP_PENDING — `(setID: int)`; fires at the START of -// `UseEquipmentSet`, right after the set -// exists check passes. Modern addons -// gate "swap-in-progress" UI state on -// this (grey out the set button until -// FINISHED arrives). +// EQUIPMENT_SWAP_PENDING — `(setID: int)`; fires once +// `UseEquipmentSet` has sent its swaps. // EQUIPMENT_SWAP_FINISHED — `(success: bool, setID: int)`; fires -// at the end of `UseEquipmentSet`. -// `success` is false when the set -// doesn't exist, true otherwise (we -// don't probe whether each individual -// pickup→equip pair actually completed, -// matching modern's "we dispatched" -// definition of success). +// when the swap settles — see +// `EquipmentSet::Pending`. `success` is +// 1 or nil, never 0 (a Lua 0 is true). inline const Event::Custom::AutoReserve kEvtSetsChanged{"EQUIPMENT_SETS_CHANGED"}; inline const Event::Custom::AutoReserve kEvtSwapPending{"EQUIPMENT_SWAP_PENDING"}; inline const Event::Custom::AutoReserve kEvtSwapFinished{"EQUIPMENT_SWAP_FINISHED"}; diff --git a/src/equipmentset/Storage.cpp b/src/equipmentset/Storage.cpp index e3585e8f..1aa330bd 100644 --- a/src/equipmentset/Storage.cpp +++ b/src/equipmentset/Storage.cpp @@ -101,8 +101,6 @@ bool Load(const std::string &path, std::vector *outSets) { std::string value; if (ParseField(line, "name", &value)) { - if (value.size() > MAX_NAME_LEN) - value.resize(MAX_NAME_LEN); current->name = std::move(value); continue; } diff --git a/src/equipmentset/Text.cpp b/src/equipmentset/Text.cpp new file mode 100644 index 00000000..94fd6192 --- /dev/null +++ b/src/equipmentset/Text.cpp @@ -0,0 +1,68 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#include "Text.h" + +#include "Data.h" +#include "Game.h" +#include "event/Custom.h" + +namespace EquipmentSet::Text { + +std::string Global(const char *name, const char *fallback) { + void *L = Game::Lua::State(); + if (L == nullptr) + return fallback; + // Raw read: callers include the world tick, where no `__index` may run. + const int top = Game::Lua::GetTop(L); + Game::Lua::PushString(L, name); + Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX); + std::string out = fallback; + if (Game::Lua::Type(L, -1) == Game::Lua::TYPE_STRING) { + const char *s = Game::Lua::ToString(L, -1); + if (s != nullptr) + out = s; + } + Game::Lua::SetTop(L, top); + return out; +} + +std::string FormatS(const std::string &format, const std::string &arg) { + const size_t at = format.find("%s"); + if (at == std::string::npos) + return format; + return format.substr(0, at) + arg + format.substr(at + 2); +} + +void UIError(const char *globalName, const char *fallback, const char *setName) { + const int evt = Event::Custom::LookupByName("UI_ERROR_MESSAGE"); + if (evt < 0) + return; + std::string text = Global(globalName, fallback); + if (setName != nullptr) + text = FormatS(text, setName); + Event::Custom::Fire(evt, "%s", text.c_str()); +} + +std::string SetList(uint64_t itemGuid) { + std::string list; + const std::string delimiter = Global("PLAYER_LIST_DELIMITER", ", "); + for (const Set *s : Data::SetsContainingItem(itemGuid)) { + if (!list.empty()) + list += delimiter; + list += s->name; + } + return list; +} + +} // namespace EquipmentSet::Text diff --git a/src/equipmentset/Text.h b/src/equipmentset/Text.h new file mode 100644 index 00000000..6dc11a81 --- /dev/null +++ b/src/equipmentset/Text.h @@ -0,0 +1,40 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include +#include + +// The equipment manager's player-facing text: localized globals, the error +// messages 4.3.4 shows through UI_ERROR_MESSAGE, and the set-name list its +// item tooltips and `GetContainerItemEquipmentSetInfo` share. +namespace EquipmentSet::Text { + +// `_G[name]` when it is a string, else `fallback` (4.3.4 FrameScript_GetText). +std::string Global(const char *name, const char *fallback); + +// Fires UI_ERROR_MESSAGE with `_G[globalName]` (or `fallback`), its first +// `%s` replaced by `setName` when one is given — 4.3.4's +// `FrameScript_SignalEvent(UI_ERROR_MESSAGE, "%s", text)`. +void UIError(const char *globalName, const char *fallback, const char *setName = nullptr); + +// 4.3.4 `CGEquipmentManager::GetSetList`: the names of every set holding the +// item instance `itemGuid`, joined by PLAYER_LIST_DELIMITER. Empty when none. +std::string SetList(uint64_t itemGuid); + +// `format` with its first `%s` replaced by `arg`. By hand, not printf: the +// format is a Lua global any addon can reassign. +std::string FormatS(const std::string &format, const std::string &arg); + +} // namespace EquipmentSet::Text diff --git a/src/equipmentset/Tooltip.cpp b/src/equipmentset/Tooltip.cpp index 24baefc7..712349dd 100644 --- a/src/equipmentset/Tooltip.cpp +++ b/src/equipmentset/Tooltip.cpp @@ -26,10 +26,8 @@ // // We back the implementation with the same equipment-set storage // `C_EquipmentSet.*` already uses (`EquipmentSet::Data`) — no new data -// model needed. Item classification reuses `Locations::FindGUID`, -// which walks the player's flat inventory + bag invMgrs the same way -// `GetItemCount` does, so bank items count as "in inventory" without -// needing the bank window open. +// model needed. The counts are `Locations::GetStatus`, 4.3.4's +// `GetSetStatus`, shared with `C_EquipmentSet.GetEquipmentSetInfo`. // // Stock 4.3.4 enumerates each missing item by name (looks up the // itemID via the engine's full item-cache name resolver). Our storage @@ -51,13 +49,17 @@ #include "Game.h" #include "Offsets.h" +#include "cvar/Factory.h" #include "equipmentset/Data.h" #include "equipmentset/Locations.h" #include "equipmentset/Set.h" +#include "equipmentset/Text.h" #include "item/Record.h" #include "tooltip/Lines.h" +#include "ui/ColorData.h" #include +#include namespace EquipmentSet::Tooltip { @@ -68,6 +70,8 @@ constexpr uint32_t kWhite = 0xFFFFFFFFu; constexpr uint32_t kGreen = 0xFF00FF00u; constexpr uint32_t kGray = 0xFF808080u; constexpr uint32_t kRed = 0xFFFF0000u; +// 4.3.4's tooltip title color, which its "Equipment Sets:" line uses. +constexpr uint32_t kNormal = UI::ColorData::ByTag("NORMAL_FONT_COLOR"); // Adds one localized "N unit" line: `string.format(_G[globalName] or // fallback, n)` (the project's GlobalString localize-or-fallback helper, @@ -83,51 +87,6 @@ void AddLocalizedLineInt(void *L, void *self, const char *globalName, Game::Lua::SetTop(L, savedTop); } -struct Tally { - int equipped; - int inInventory; - int ignored; - int missing; - // ItemIDs of slots classified as missing. Indexed 0..missing-1. - // Capacity matches SLOT_COUNT (worst case: every slot is missing). - // Stays 0 for entries loaded from pre-itemID-format files. - uint32_t missingItemIDs[SLOT_COUNT]; -}; - -// Walks a set's slots, classifying each non-empty entry into the -// equipped / in-inventory / ignored / missing buckets via -// `Locations::FindGUID`. For missing slots, also records the saved -// itemID so the tooltip can resolve names. Stack-free. -Tally TallySet(const Set &s) { - Tally t{}; - for (int i = 0; i < SLOT_COUNT; ++i) { - const uint64_t g = s.items[i]; - if (g == GUID_IGNORED) { - t.ignored++; - continue; - } - if (g == GUID_EMPTY) - continue; - const int loc = Locations::FindGUID(g); - if (loc == 0) { - // Live GUID isn't in the player's object map. The saved - // itemID (if any) is the only handle we have for naming. - t.missingItemIDs[t.missing++] = s.itemIDs[i]; - continue; - } - // LOC_BAGS covers backpack / player bags / bank bags; LOC_BANK - // alone (no LOC_BAGS) covers main bank slots. Both count as - // "in inventory" for the tooltip summary — matches the modern - // category where everything-but-equipped is one bucket. - if ((loc & (LOC_BAGS | LOC_BANK)) != 0) { - t.inInventory++; - } else { - t.equipped++; - } - } - return t; -} - } // namespace int __fastcall Script_GameTooltipSetEquipmentSet(void *L) { @@ -151,8 +110,8 @@ int __fastcall Script_GameTooltipSetEquipmentSet(void *L) { if (self == nullptr) return 0; - const Tally t = TallySet(*s); - const int totalSlots = t.equipped + t.inInventory + t.missing; + const Locations::Status t = Locations::GetStatus(*s); + const int totalSlots = t.total; // Header — set name, white. Clear first so it lands as line 0 // (the clear resets the line count the add-line body indexes from). @@ -187,7 +146,7 @@ int __fastcall Script_GameTooltipSetEquipmentSet(void *L) { // a `(N unnamed missing)` line below. int unnamedMissing = 0; for (int i = 0; i < t.missing; ++i) { - const uint32_t id = t.missingItemIDs[i]; + const uint32_t id = s->itemIDs[t.missingSlots[i] - 1]; if (id == 0) { unnamedMissing++; continue; @@ -233,6 +192,28 @@ int __fastcall Script_GameTooltipSetEquipmentSet(void *L) { namespace { +CVar::Factory::Handle g_hideSetsCVar = nullptr; + +} // namespace + +void AfterItemBuild(void *self, const void *itemGuidPtr) { + if (itemGuidPtr == nullptr || CVar::Factory::GetInt(g_hideSetsCVar) != 0) + return; + const uint64_t itemGuid = *static_cast(itemGuidPtr); + // The builder adds no lines when it bailed on an item-cache miss; it + // runs again once the item arrives. + if (itemGuid == 0 || Game::Read(self, Offsets::OFF_GAMETOOLTIP_NUM_LINES) == 0) + return; + const std::string list = Text::SetList(itemGuid); + if (list.empty()) + return; + const std::string line = Text::FormatS( + Text::Global("EQUIPMENT_SETS", "Equipment Sets: |cFFFFFFFF%s|r"), list); + ::Tooltip::Lines::Add(self, line.c_str(), kNormal, /*wrap*/ true); +} + +namespace { + const Game::Lua::FrameMethodEntry g_methods[] = { {"SetEquipmentSet", &Script_GameTooltipSetEquipmentSet}, }; @@ -240,6 +221,8 @@ const Game::Lua::FrameMethodEntry g_methods[] = { } // namespace static void RegisterLuaFunctions() { + // 4.3.4's switch for the item-tooltip line; dedups by name on /reload. + g_hideSetsCVar = CVar::Factory::Register("dontShowEquipmentSetsOnItems", "0"); Game::Lua::RegisterFrameMethods( reinterpret_cast(Offsets::VAR_GAMETOOLTIP_METHOD_REGISTRY), g_methods, diff --git a/src/equipmentset/Tooltip.h b/src/equipmentset/Tooltip.h index a4de73fd..2edb8c34 100644 --- a/src/equipmentset/Tooltip.h +++ b/src/equipmentset/Tooltip.h @@ -20,4 +20,11 @@ namespace EquipmentSet::Tooltip { // button the same way. int __fastcall Script_GameTooltipSetEquipmentSet(void *L); +// 4.3.4 `CGTooltip::SetItem`'s "Equipment Sets: A, B" line: appended to an +// item tooltip just built for the item instance at `itemGuidPtr` (the item +// builder's second GUID argument; may be null), unless the +// `dontShowEquipmentSetsOnItems` cvar is set. Called by +// `Tooltip::SetEvents`' item-builder co-hook, before OnTooltipSetItem. +void AfterItemBuild(void *self, const void *itemGuidPtr); + } // namespace EquipmentSet::Tooltip diff --git a/src/tooltip/SetEvents.cpp b/src/tooltip/SetEvents.cpp index 54accd21..fd9fdf3c 100644 --- a/src/tooltip/SetEvents.cpp +++ b/src/tooltip/SetEvents.cpp @@ -42,6 +42,7 @@ #include "Game.h" #include "Offsets.h" +#include "equipmentset/Tooltip.h" #include "unit/Tooltip.h" #include @@ -170,7 +171,8 @@ int __fastcall Resolver_h(void *self, void *edx, const char *name) { // Builders whose callers use the return value (spell, unit) are declared to // return it so the co-hook forwards it. -// Item — FUN_GAMETOOLTIP_BUILD_ITEM, 9 stack args, return unused. +// Item — FUN_GAMETOOLTIP_BUILD_ITEM, 9 stack args, return unused. `guid2` +// (stack +0x10) is the item instance GUID the builder stores at +0x380. using BuildItem_t = void(__fastcall *)(void *self, void *edx, uint32_t itemID, const void *guid, const void *guid2, int a4, int a5, int a6, int headerFlag, int a8, int a9); @@ -180,6 +182,7 @@ void __fastcall BuildItem_h(void *self, void *edx, uint32_t itemID, const void * const void *guid2, int a4, int a5, int a6, int headerFlag, int a8, int a9) { g_buildItemOriginal(self, edx, itemID, guid, guid2, a4, a5, a6, headerFlag, a8, a9); + EquipmentSet::Tooltip::AfterItemBuild(self, guid2); FireScript(self, SK_ITEM); }