GameTooltip:SetItemByID and better item caching

This commit is contained in:
Brues
2026-05-08 23:54:25 -05:00
parent b893b8eff1
commit 1a6fb7f2be
6 changed files with 323 additions and 45 deletions
+63
View File
@@ -393,6 +393,69 @@ Equivalent to the function of the same name introduced in 3.0.
## GameTooltip
### `GameTooltip:SetItemByID(itemID)`
Modern method that renders an item tooltip from just an itemID. The
1.12 workaround was constructing an item hyperlink and calling
`SetHyperlink` — `tooltip:SetHyperlink("item:" .. id .. ":0:0:0:0:0:0:0")`
— which works but forces every caller to know the hyperlink format.
```lua
GameTooltip:SetOwner(UIParent, "ANCHOR_CURSOR")
GameTooltip:SetItemByID(6948) -- Hearthstone
GameTooltip:Show()
```
Implementation: snprintf the hyperlink string and dispatch to the
existing `Script_GameTooltip_SetHyperlink` (registry slot 12).
> **Item cache caveat.** 1.12 lazy-loads item data into the
> client-side cache at `0x00C0E2A0` — the cache is fed by
> `SMSG_ITEM_QUERY_SINGLE_RESPONSE` only when the player encounters
> an item. For an itemID the player has never seen, the tooltip
> renders only the name; full data appears once the cache is warm.
>
> The fix is to ensure the item is cached before opening the tooltip:
>
> ```lua
> if C_Item.IsItemDataCachedByID(itemID) then
> GameTooltip:SetItemByID(itemID)
> else
> C_Item.RequestLoadItemDataByID(itemID)
> -- register for ITEM_DATA_LOAD_RESULT(loadedItemID, success)
> -- and call SetItemByID once the matching itemID arrives
> end
> ```
>
> This caching behavior matches what `C_Item.GetItemInfoInstant`
> documents — same underlying cache. Modern WoW (5.0+) has the same
> caveat, just with `C_Item.RequestLoadItemData(itemLocation)` /
> `Item:OnItemLoad`-style continuation.
Equivalent to the function of the same name introduced in 8.0.
### `GameTooltip:SetUnitAura(unit, index, [filter])`
Modern unified-aura method. 1.12 splits this into `SetUnitBuff` and
`SetUnitDebuff`; we dispatch to the right one based on the `filter`
string (`"HARMFUL"` → `SetUnitDebuff`, anything else → `SetUnitBuff`).
`filter` defaults to helpful when omitted, matching modern.
```lua
GameTooltip:SetOwner(UIParent, "ANCHOR_CURSOR")
GameTooltip:SetUnitAura("player", 1, "HELPFUL") -- first buff
GameTooltip:SetUnitAura("player", 1, "HARMFUL") -- first debuff
GameTooltip:SetUnitAura("player", 1) -- defaults to HELPFUL
GameTooltip:Show()
```
Pure dispatcher — no engine changes; the underlying logic is whatever
1.12's `SetUnitBuff` / `SetUnitDebuff` already does. Just lets you use
the modern call shape (which most aura libraries backport from)
without conditionally splitting on filter.
Equivalent to the function of the same name introduced in 6.0.
### `GameTooltip:SetSpellByID(spellID)`
Renders a spell tooltip for any `spellID`, including spells the player has
+9
View File
@@ -16,6 +16,7 @@
#include "MinHook.h"
#include "Offsets.h"
#include "event/Custom.h"
#include "item/Data.h"
#include <string>
@@ -87,6 +88,14 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) {
LoadScriptFunctions_o);
HOOK_FUNCTION(Offsets::FUN_FRAME_REGISTER_EVENT, FrameRegisterEvent_h,
FrameRegisterEvent_o);
// Auto-warm the item cache on `GetItemInfo(uncached_id)` calls, so
// subsequent calls return valid data and GET_ITEM_INFO_RECEIVED
// fires when the response arrives — matches modern WoW (5.x+)
// behavior. Without this, vanilla 1.12's `GetItemInfo` returns
// nil for misses and never fires a query, forcing addons to roll
// their own warmup hacks.
HOOK_FUNCTION(Offsets::FUN_SCRIPT_GET_ITEM_INFO, Item::Data::Script_GetItemInfo_h,
Item::Data::Script_GetItemInfo_o);
} else if (reason == DLL_PROCESS_DETACH) {
MH_Uninitialize();
}
+16
View File
@@ -27,6 +27,14 @@ enum Offsets {
// __thiscall(spellID, 0, 0, isPet, 0, 0, 0); we always pass isPet=0.
FUN_GAMETOOLTIP_BUILD_SPELL_TOOLTIP = 0x0052E610,
// Existing GameTooltip method-table entries we dispatch to from
// backported convenience methods. Each is `int __fastcall(void *L)`
// expecting the standard self+args layout on the Lua stack.
// (Slot numbers are the method-registry index per `docs/raw_methods.txt`.)
FUN_SCRIPT_GAMETOOLTIP_SET_HYPERLINK = 0x00531FD0, // slot 12
FUN_SCRIPT_GAMETOOLTIP_SET_UNIT_BUFF = 0x00534AC0, // slot 32
FUN_SCRIPT_GAMETOOLTIP_SET_UNIT_DEBUFF = 0x00534E30, // slot 33
// Iterator that registers an array of frame-method bindings on a per-frame-type
// method registry (e.g. VAR_GAMETOOLTIP_METHOD_REGISTRY for GameTooltip).
// __fastcall(ecx = MethodEntry table, edx = count, [stack] = context).
@@ -126,6 +134,14 @@ enum Offsets {
// address `0xC0E2A0`, not a pointer to it. See Script_GetItemInfo at
// 0x0048E070 which calls `mov ecx, 0xC0E2A0` before the call.
VAR_ITEMDB_CACHE = 0x00C0E2A0,
// `Script_GetItemInfo` Lua C function. We hook this to auto-warm the
// item cache on miss — vanilla 1.12's stock behavior is "return nil
// for uncached items and don't fire any query"; modern WoW (5.x+)
// auto-fires the load and emits `GET_ITEM_INFO_RECEIVED` when data
// arrives. The hook makes `GetItemInfo(uncached_id)` return nil
// first call but kick off the query, so subsequent calls work.
FUN_SCRIPT_GET_ITEM_INFO = 0x0048E070,
// ItemStats_C *(__thiscall *)(void *cache, uint32_t itemID,
// const uint64_t *guid /*may point to zero*/,
// void *callback, void *userData,
+108 -45
View File
@@ -14,9 +14,11 @@
#include "Game.h"
#include "Offsets.h"
#include "event/Custom.h"
#include "item/Data.h"
#include "item/Location.h"
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -26,52 +28,89 @@ using GetItemRecord_t = const uint8_t *(__thiscall *)(void *cache, uint32_t item
const uint64_t *guid, void *callback,
void *userData, int unused);
// `ITEM_DATA_LOAD_RESULT` event-table slot. We never store this directly;
// instead we look it up via `Event::Custom::Register` which caches by
// pointer and retries failed claims. The engine's table isn't populated
// when our boot hook fires, so all early registrations return -1 — the
// retry path inside `Custom::Register` (also driven by our hook on
// `Frame::RegisterEvent`) eventually claims the slot.
// Two events fire on item-data arrival; they are **mutually exclusive**
// based on what triggered the cache fill:
//
// `GET_ITEM_INFO_RECEIVED(itemID, success)` — added in 5.4. Fires for
// **implicit / transparent** cache fills: `GetItemInfo` warmup,
// hyperlink hover, chat-link resolution, our `SetItemByID` warmup,
// etc. This is the event most existing addons listen to.
//
// `ITEM_DATA_LOAD_RESULT(itemID, success)` — added in 8.0. Fires for
// **explicit** request paths only: `C_Item.RequestLoadItemData(ByID)`
// and friends. The completion event for callers who explicitly
// asked the modern Item-data API to load a specific item.
//
// Behavior verified empirically against 1.15.x: a single cache fill
// fires exactly one event, never both, depending on what initiated
// the request. We honor the split with two distinct callbacks.
//
// Slots are looked up via `Event::Custom::Register` which caches by
// pointer and retries failed claims; the engine's event table isn't
// populated when our boot hook fires, so all early registrations
// return -1 until `RetryAll` claims them later.
static constexpr const char *kItemDataLoadResult = "ITEM_DATA_LOAD_RESULT";
static constexpr const char *kGetItemInfoReceived = "GET_ITEM_INFO_RECEIVED";
// Callback the engine invokes from its SMSG response handler after the
// data lands in the cache. We get the itemID back via `userData` (passed
// as `(void *)(uintptr_t)itemID` at request time — the engine just stores
// and replays it without dereferencing) and `success` as the 2nd arg.
static void FireGetItemInfoReceived(int itemID, int success) {
const int slot = Event::Custom::Register(kGetItemInfoReceived);
if (slot >= 0)
Event::Custom::Fire_DD(slot, itemID, success);
}
static void FireItemDataLoadResult(int itemID, int success) {
const int slot = Event::Custom::Register(kItemDataLoadResult);
if (slot >= 0)
Event::Custom::Fire_DD(slot, itemID, success);
}
// Engine callback for **implicit** cache fills (transparent warmup
// triggered by our `Script_GetItemInfo` hook or `SetItemByID`). Fires
// only the broad `GET_ITEM_INFO_RECEIVED` event — `ITEM_DATA_LOAD_RESULT`
// is reserved for explicit `RequestLoadItemData(ByID)` paths to match
// modern API semantics.
//
// Calling convention is __stdcall, 2 args / 8 bytes — matching the
// callback at 0x004FDC30 (used by 4 sites in the binary) which ends in
// `ret 8`. If the engine called us with a different convention, that
// callback would crash the engine, so stdcall is verified by induction.
static void __stdcall ItemLoadCallback(void *userData, int success) {
const int slot = Event::Custom::Register(kItemDataLoadResult);
if (slot < 0)
return;
const auto itemID =
static_cast<int>(reinterpret_cast<uintptr_t>(userData));
Event::Custom::Fire_DD(slot, itemID, success ? 1 : 0);
static void __stdcall ItemLoadCallback_Implicit(void *userData, int success) {
const auto itemID = static_cast<int>(reinterpret_cast<uintptr_t>(userData));
FireGetItemInfoReceived(itemID, success ? 1 : 0);
}
// Calls DBCache_ItemStats_C_GetRecord. With `fireRequest=false`, performs
// only the hash-table lookup; returns the cached record or nullptr.
// With `fireRequest=true`, also kicks off the SMSG_ITEM_QUERY_SINGLE if
// the item isn't cached — the engine fills the cache asynchronously and
// invokes our callback with `userData` (we pass the itemID through it so
// the callback knows which item completed).
// Engine callback for **explicit** cache fills (player-side
// `C_Item.RequestLoadItemData(ByID)` calls). Fires ITEM_DATA_LOAD_RESULT
// only — the implicit GET_ITEM_INFO_RECEIVED path is for ambient cache
// fills, not for callers who explicitly asked.
static void __stdcall ItemLoadCallback_Explicit(void *userData, int success) {
const auto itemID = static_cast<int>(reinterpret_cast<uintptr_t>(userData));
FireItemDataLoadResult(itemID, success ? 1 : 0);
}
using ItemLoadCallback_t = void(__stdcall *)(void *userData, int success);
// Calls DBCache_ItemStats_C_GetRecord. With `callback=nullptr`,
// performs only the hash-table lookup; returns the cached record or
// nullptr. With a non-null callback, also kicks off the
// SMSG_ITEM_QUERY_SINGLE if the item isn't cached — the engine fills
// the cache asynchronously and invokes the supplied callback with the
// itemID smuggled through `userData` (the engine just stores and
// replays it without dereferencing).
//
// Disassembly of `_GetRecord` at 0x55BAAC shows it branches on the
// callback arg (stack slot +0x10), not on the 6th `bool` arg that
// VanillaHelpers documented as `requestIfMissing` — that slot is reused
// as a local immediately after entry, never read. The trigger for the
// request path is `callback != NULL`.
static const uint8_t *CacheFetch(uint32_t itemID, bool fireRequest) {
static const uint8_t *CacheFetch(uint32_t itemID, ItemLoadCallback_t callback) {
auto fn = reinterpret_cast<GetItemRecord_t>(Offsets::FUN_DBCACHE_ITEMSTATS_GET_RECORD);
auto *cache = reinterpret_cast<void *>(Offsets::VAR_ITEMDB_CACHE);
const uint64_t zeroGuid = 0;
void *callback = fireRequest ? reinterpret_cast<void *>(&ItemLoadCallback) : nullptr;
void *cb = reinterpret_cast<void *>(callback);
void *userData =
fireRequest ? reinterpret_cast<void *>(static_cast<uintptr_t>(itemID)) : nullptr;
return fn(cache, itemID, &zeroGuid, callback, userData, 0);
callback ? reinterpret_cast<void *>(static_cast<uintptr_t>(itemID)) : nullptr;
return fn(cache, itemID, &zeroGuid, cb, userData, 0);
}
// Same input shape as `Item::Info::ResolveItemID` — accepts a number or a
@@ -108,7 +147,7 @@ static int ResolveLocationToItemID(void *L, int idx) {
static int __fastcall Script_IsItemDataCachedByID(void *L) {
const int itemID = ParseItemArg(L, 1);
const bool cached =
(itemID > 0) && (CacheFetch(static_cast<uint32_t>(itemID), false) != nullptr);
(itemID > 0) && (CacheFetch(static_cast<uint32_t>(itemID), nullptr) != nullptr);
Game::Lua::PushBoolean(L, cached ? 1 : 0);
return 1;
}
@@ -120,23 +159,45 @@ static int __fastcall Script_IsItemDataCached(void *L) {
}
const int itemID = ResolveLocationToItemID(L, 1);
const bool cached =
(itemID > 0) && (CacheFetch(static_cast<uint32_t>(itemID), false) != nullptr);
(itemID > 0) && (CacheFetch(static_cast<uint32_t>(itemID), nullptr) != nullptr);
Game::Lua::PushBoolean(L, cached ? 1 : 0);
return 1;
}
// If the item is already cached, the engine won't invoke our callback —
// no SMSG round-trip happens. Fire ITEM_DATA_LOAD_RESULT ourselves so
// addons get the same notification regardless of cache state, matching
// modern API semantics.
// Explicit-request path: kicks off the cache fill via the explicit
// callback (which fires ITEM_DATA_LOAD_RESULT). If the item is already
// cached, the engine won't invoke our callback — synthesize the event
// so addons get the same notification regardless of cache state,
// matching modern `C_Item.RequestLoadItemData(ByID)` semantics.
static void RequestAndMaybeNotify(uint32_t itemID) {
const bool wasCached = (CacheFetch(itemID, false) != nullptr);
CacheFetch(itemID, true);
if (wasCached) {
const int slot = Event::Custom::Register(kItemDataLoadResult);
if (slot >= 0)
Event::Custom::Fire_DD(slot, static_cast<int>(itemID), 1);
}
const bool wasCached = (CacheFetch(itemID, nullptr) != nullptr);
CacheFetch(itemID, &ItemLoadCallback_Explicit);
if (wasCached)
FireItemDataLoadResult(static_cast<int>(itemID), 1);
}
// Public C++ API — see Item/Data.h. Implicit (transparent) warmup
// path used by the `Script_GetItemInfo` hook and `SetItemByID`. Fires
// the cache request only if the item isn't already cached; uses the
// implicit callback which fires only `GET_ITEM_INFO_RECEIVED` (not
// `ITEM_DATA_LOAD_RESULT`), matching modern semantics for ambient
// cache fills.
void WarmCache(uint32_t itemID) {
CacheFetch(itemID, &ItemLoadCallback_Implicit);
}
// Hook for `Script_GetItemInfo`. Pre-warms the cache from arg 1, then
// dispatches to the original. Effect: the original still returns nil
// for cache misses (vanilla behavior), but a query is now in flight,
// so subsequent calls will return valid data and
// GET_ITEM_INFO_RECEIVED will fire.
Script_GetItemInfo_t Script_GetItemInfo_o = nullptr;
int __fastcall Script_GetItemInfo_h(void *L) {
const int itemID = ParseItemArg(L, 1);
if (itemID > 0)
WarmCache(static_cast<uint32_t>(itemID));
return Script_GetItemInfo_o(L);
}
static int __fastcall Script_RequestLoadItemDataByID(void *L) {
@@ -173,12 +234,14 @@ static void RegisterLuaFunctions() {
&Script_RequestLoadItemDataByID);
Game::Lua::RegisterTableFunction("C_Item", "RequestLoadItemData", &Script_RequestLoadItemData);
// Seed the cache so `Event::Custom::RetryAll` (driven by our hook on
// `Frame::RegisterEvent`) knows to claim a slot for this name. The
// event table isn't populated yet when this fires, so the call returns
// -1; later attempts via `RetryAll` or any direct `Register` call get
// it. Once claimed, the slot is cached and reused.
// Seed both events so `Event::Custom::RetryAll` (driven by our hook
// on `Frame::RegisterEvent`) knows to claim slots for them. The
// engine's event table isn't populated yet when this fires, so all
// these calls return -1; later attempts via `RetryAll` or any
// direct `Register` call land them. Once claimed, slots are cached
// and reused.
Event::Custom::Register(kItemDataLoadResult);
Event::Custom::Register(kGetItemInfoReceived);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+46
View File
@@ -0,0 +1,46 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <cstdint>
namespace Item::Data {
// Warm the item-stats cache for `itemID`. If already cached this is a
// no-op (caller can read item info immediately). If not cached,
// triggers the engine's `SMSG_ITEM_QUERY_SINGLE_RESPONSE` round-trip
// and fires `GET_ITEM_INFO_RECEIVED` when the response arrives.
//
// Used by:
// - Our `Script_GetItemInfo` hook (so 1.12's `GetItemInfo` becomes
// transparent like 5.x+)
// - `GameTooltip:SetItemByID` (so item tooltips warm the cache when
// opened cold)
//
// Note: this is the **implicit** warmup path — fires GET_ITEM_INFO_RECEIVED
// only. For modern explicit-request semantics (fires
// ITEM_DATA_LOAD_RESULT), use `C_Item.RequestLoadItemData(ByID)` from
// Lua.
void WarmCache(uint32_t itemID);
// Hook for `Script_GetItemInfo` (`0x0048E070`). Pre-warms the cache
// from arg 1 (number or `"item:NNN..."` string), then runs the
// original. The original still returns nil this call for cache
// misses, but the query is now in flight; subsequent calls return
// valid data and `GET_ITEM_INFO_RECEIVED` fires when ready.
using Script_GetItemInfo_t = int(__fastcall *)(void *L);
extern Script_GetItemInfo_t Script_GetItemInfo_o;
int __fastcall Script_GetItemInfo_h(void *L);
} // namespace Item::Data
+81
View File
@@ -0,0 +1,81 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
#include "Game.h"
#include "Offsets.h"
#include "item/Data.h"
#include <cstdint>
#include <cstdio>
namespace Item::Tooltip {
// `GameTooltip:SetItemByID(itemID)` — modern method that renders an
// item tooltip from just an itemID. The 1.12 workaround was to
// construct an item hyperlink and call `SetHyperlink` —
// `tooltip:SetHyperlink("item:" .. id .. ":0:0:0:0:0:0:0")` — which
// works but forces every caller to know the hyperlink format.
//
// Implementation: format the hyperlink string in C and dispatch to the
// existing `Script_GameTooltip_SetHyperlink` (registry slot 12 at
// `0x00531FD0`). Same registration pattern as `SetSpellByID` in
// [src/spell/Tooltip.cpp](src/spell/Tooltip.cpp).
static int __fastcall Script_GameTooltipSetItemByID(void *L) {
if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE) {
Game::Lua::Error(L, "Usage: GameTooltip:SetItemByID(itemID)");
return 0;
}
if (!Game::Lua::IsNumber(L, 2)) {
Game::Lua::Error(L, "Usage: GameTooltip:SetItemByID(itemID)");
return 0;
}
const int itemID = static_cast<int>(Game::Lua::ToNumber(L, 2));
if (itemID <= 0)
return 0;
// Warm the cache if uncached. The cache-load callback fires
// `GET_ITEM_INFO_RECEIVED` when data arrives. Addons that want
// the tooltip to auto-refresh in place should listen for that
// event and re-call SetItemByID — modern WoW (5.x+) does the
// same internally; we don't replicate that engine-level hook
// because the only viable C-side path here is invoking Lua
// from a network callback, which has its own pitfalls.
Item::Data::WarmCache(static_cast<uint32_t>(itemID));
char hyperlink[64];
std::snprintf(hyperlink, sizeof(hyperlink), "item:%d:0:0:0:0:0:0:0", itemID);
// Replace stack[2] (the itemID) with the formatted hyperlink, so
// the existing SetHyperlink sees `(self, "item:...")`.
Game::Lua::SetTop(L, 1); // keep self at stack[1]
Game::Lua::PushString(L, hyperlink); // stack[2] = hyperlink
using Script_t = int(__fastcall *)(void *L);
auto fn = reinterpret_cast<Script_t>(Offsets::FUN_SCRIPT_GAMETOOLTIP_SET_HYPERLINK);
return fn(L);
}
static const Game::Lua::FrameMethodEntry g_methods[] = {
{"SetItemByID", &Script_GameTooltipSetItemByID},
};
static void RegisterLuaFunctions() {
Game::Lua::RegisterFrameMethods(
reinterpret_cast<void *>(Offsets::VAR_GAMETOOLTIP_METHOD_REGISTRY),
g_methods,
static_cast<int>(sizeof(g_methods) / sizeof(g_methods[0])));
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Item::Tooltip