mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 08:00:42 +00:00
Opt-in player caching
This commit is contained in:
@@ -26,6 +26,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**.
|
||||
| EquipmentSet | `C_EquipmentSet.CanUseEquipmentSets`, `C_EquipmentSet.ClearIgnoredSlotsForSave`, `C_EquipmentSet.CreateEquipmentSet`, `C_EquipmentSet.DeleteEquipmentSet`, `C_EquipmentSet.EquipmentSetContainsLockedItems`, `C_EquipmentSet.GetEquipmentSetID`, `C_EquipmentSet.GetEquipmentSetIDs`, `C_EquipmentSet.GetEquipmentSetInfo`, `C_EquipmentSet.GetIgnoredSlots`, `C_EquipmentSet.GetItemIDs`, `C_EquipmentSet.GetItemLocations`, `C_EquipmentSet.GetNumEquipmentSets`, `C_EquipmentSet.IgnoreSlotForSave`, `C_EquipmentSet.IsSlotIgnoredForSave`, `C_EquipmentSet.ModifyEquipmentSet`, `C_EquipmentSet.SaveEquipmentSet`, `C_EquipmentSet.UnignoreSlotForSave`, `C_EquipmentSet.UseEquipmentSet` (sets persist to `WTF\Account\...\ClassicAPI_EquipmentSets.txt`) |
|
||||
| Events | `C_EventUtils.IsEventValid` |
|
||||
| Faction | `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.SetWatchedFactionByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` |
|
||||
| FriendList | `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName` |
|
||||
| GameTooltip | `GameTooltip:SetInventoryItemByID`, `GameTooltip:SetItemByID`, `GameTooltip:SetSpellByID`, `GameTooltip:SetTalentByID`, `GameTooltip:SetUnitAura` |
|
||||
| Hooks | `hooksecurefunc` |
|
||||
| Input | `IsLeftAltKeyDown`, `IsLeftControlKeyDown`, `IsLeftShiftKeyDown`, `IsModifierKeyDown`, `IsRightAltKeyDown`, `IsRightControlKeyDown`, `IsRightShiftKeyDown` |
|
||||
@@ -35,7 +36,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**.
|
||||
| State | `IsAssistingRitual`, `IsFalling`, `IsMounted`, `IsStealthed`, `IsSwimming` |
|
||||
| Talent | `GetTalentIDByIndex`, `GetTalentSpellID` |
|
||||
| Time | `C_DateAndTime.AdjustTimeByDays`, `C_DateAndTime.AdjustTimeByMinutes`, `C_DateAndTime.CompareCalendarTime`, `C_DateAndTime.GetCalendarTimeFromEpoch`, `C_DateAndTime.GetCurrentCalendarTime`, `C_DateAndTime.GetSecondsUntilDailyReset`, `C_DateAndTime.GetServerTimeLocal`, `GetServerTime` |
|
||||
| Unit | `GetPlayerInfoByGUID`, `UnitGUID`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsPossessed` |
|
||||
| Unit | `C_PlayerInfo.RememberPlayer`, `ClassicAPI.GetPersistentNameCacheEnabled`, `ClassicAPI.SetPersistentNameCacheEnabled`, `GetPlayerInfoByGUID`, `UnitGUID`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsPossessed` |
|
||||
|
||||
### Events
|
||||
|
||||
|
||||
+195
@@ -39,6 +39,9 @@ build instructions.
|
||||
- [`C_Reputation.SetWatchedFactionByID(factionID)`](#c_reputationsetwatchedfactionbyidfactionid)
|
||||
- [`C_Reputation.GetLastStandingChange()`](#c_reputationgetlaststandingchange)
|
||||
- [`FACTION_STANDING_CHANGED` event](#faction_standing_changed-event)
|
||||
- [FriendList](#friendlist)
|
||||
- [`C_FriendList.SendWhoQueryByName(name)`](#c_friendlistsendwhoquerybynamename)
|
||||
- [`C_FriendList.IsWhoQueryPending()`](#c_friendlistiswhoquerypending)
|
||||
- [Item](#item)
|
||||
- [`C_Item.IsBound(itemLocation)`](#c_itemisbounditemlocation)
|
||||
- [`C_Item.GetItemID(itemLocation)`](#c_itemgetitemiditemlocation)
|
||||
@@ -86,6 +89,9 @@ build instructions.
|
||||
- [Unit](#unit)
|
||||
- [`UnitGUID(unit)`](#unitguidunit)
|
||||
- [`GetPlayerInfoByGUID(guid)`](#getplayerinfobyguidguid)
|
||||
- [`C_PlayerInfo.RememberPlayer(guid, name, classToken)`](#c_playerinforememberplayerguid-name-classtoken)
|
||||
- [`ClassicAPI.SetPersistentNameCacheEnabled(enabled)`](#classicapisetpersistentnamecacheenabledenabled)
|
||||
- [`ClassicAPI.GetPersistentNameCacheEnabled()`](#classicapigetpersistentnamecacheenabled)
|
||||
- [`UnitIsAFK(unit)`](#unitisafkunit)
|
||||
- [`UnitIsDND(unit)`](#unitisdndunit)
|
||||
- [`UnitIsFeignDeath(unit)`](#unitisfeigndeathunit)
|
||||
@@ -1114,6 +1120,90 @@ forwarding, which [`C_Reputation.GetLastStandingChange`](#c_reputationgetlaststa
|
||||
exposes — so addons can read the structured payload from inside the
|
||||
chat event without re-parsing the localized string.
|
||||
|
||||
## FriendList
|
||||
|
||||
### `C_FriendList.SendWhoQueryByName(name)`
|
||||
|
||||
Issues a /who name-filter query for a specific player. Results
|
||||
buffer into the engine's WhoList so a normal `WHO_LIST_UPDATE` +
|
||||
`GetWhoInfo(i)` flow can read them — no chat output, no
|
||||
`"Found N players matching..."` system message.
|
||||
|
||||
Vanilla 1.12 exposes `SendWho(query)` and `SetWhoToUI(flag)` only as
|
||||
separate primitives, so addons that want to silently look up a
|
||||
single player's class/level/zone (e.g. to color an unknown name in
|
||||
chat) have to manage state, cooldown timing, and friends-panel
|
||||
suppression themselves. This collapses the invocation half of that
|
||||
dance to one call with a clean true/false return.
|
||||
|
||||
Returns `true` if the query was sent, `false` if any of:
|
||||
|
||||
- the name was empty / nil
|
||||
- the call is within the 5-second cooldown of a previous send
|
||||
- the engine's WhoSystem isn't initialized yet (pre-login)
|
||||
|
||||
A `false` return is a no-op — the engine state isn't touched, no
|
||||
pending flag is set, and the cooldown isn't extended. Safe to call
|
||||
on every chat line that mentions an unknown player; the call will
|
||||
naturally rate-limit.
|
||||
|
||||
The cooldown matches the server's: vanilla's CMSG_WHO is silent-
|
||||
dropped server-side at roughly 5-second granularity, so a faster
|
||||
client just wastes queries that won't get a response.
|
||||
|
||||
```lua
|
||||
if C_FriendList.SendWhoQueryByName("Bob") then
|
||||
-- query sent; result will arrive via WHO_LIST_UPDATE within ~1s
|
||||
end
|
||||
```
|
||||
|
||||
This call alone does **not** suppress the friends-panel popup on
|
||||
response — for that, wrap `FriendsFrame_OnEvent` and gate on
|
||||
[`C_FriendList.IsWhoQueryPending()`](#c_friendlistiswhoquerypending):
|
||||
|
||||
```lua
|
||||
local original = FriendsFrame_OnEvent
|
||||
_G.FriendsFrame_OnEvent = function()
|
||||
if event == "WHO_LIST_UPDATE" and C_FriendList.IsWhoQueryPending() then
|
||||
return
|
||||
end
|
||||
return original()
|
||||
end
|
||||
```
|
||||
|
||||
(Auto-suppressing the popup from C++ would require hooking the
|
||||
engine's `FrameScript_SignalEvent` or the SMSG_WHO opcode handler —
|
||||
both high-traffic / high-risk sites. The wrap above is reliable and
|
||||
takes 5 lines, so it stays addon-side for now.)
|
||||
|
||||
Implementation reads the WhoSystem singleton from `0x00C28168` and
|
||||
calls the inner sender at `0x005AEBB0`
|
||||
(`__thiscall(this = WhoSystem, queryStr)`), the same chokepoint
|
||||
`Script_SendWho` tail-calls. The `whoToUI` flag at `0x00C2A12C` is
|
||||
flipped to `1` first so the SMSG_WHO handler routes results into the
|
||||
list (`WHO_LIST_UPDATE` path) instead of printing to chat.
|
||||
|
||||
### `C_FriendList.IsWhoQueryPending()`
|
||||
|
||||
Returns `true` within ~5 seconds of the most recent
|
||||
[`SendWhoQueryByName`](#c_friendlistsendwhoquerybynamename) that
|
||||
returned `true`; otherwise `false`. Time-based — the engine doesn't
|
||||
expose a "response arrived" hook to C++ yet, so the window is a
|
||||
conservative upper bound on the response RTT, which in practice
|
||||
lands within a few hundred ms.
|
||||
|
||||
The intended use is gating an addon-side `FriendsFrame_OnEvent`
|
||||
wrap so the user-issued `/who` window still works while addon-
|
||||
issued silent queries don't pop the panel — see the example under
|
||||
`SendWhoQueryByName`.
|
||||
|
||||
Concurrent callers see a shared pending flag — if pfUI and another
|
||||
addon both call `SendWhoQueryByName` close in time, both queries
|
||||
contribute to the same pending window. This is acceptable for the
|
||||
"suppress popup for any in-flight DLL-issued query" use case;
|
||||
addons that need per-call tracking should manage their own ticket
|
||||
state on top.
|
||||
|
||||
## Item
|
||||
|
||||
### `C_Item.IsBound(itemLocation)`
|
||||
@@ -2204,12 +2294,117 @@ deliberately does not trigger queries from a passive getter; a
|
||||
future `C_PlayerInfo.RequestLoadPlayerByID` would do that
|
||||
explicitly and fire a load-result event.
|
||||
|
||||
**Persistent fallback**: when
|
||||
[`ClassicAPI.SetPersistentNameCacheEnabled(true)`](#classicapisetpersistentnamecacheenabledenabled)
|
||||
has been opted into, a per-realm on-disk cache extends coverage
|
||||
across sessions. On engine cache miss, `GetPlayerInfoByGUID` falls
|
||||
back to the persistent cache and returns the cached `name` and
|
||||
class (with `realm` as `""` and race/sex slots zeroed — only the
|
||||
two stored fields are recoverable, but for the common chat-coloring
|
||||
use case that's enough). Returns `nil` only when both the engine
|
||||
and persistent caches miss.
|
||||
|
||||
**Implementation**: calls the engine's get-or-fetch primitive at
|
||||
`0x0055F080` with a NULL callback (pure cache read). The cache
|
||||
instance lives at `0x00C0E228`; entry layout (name, realm, race,
|
||||
sex, class) was reverse-engineered from the
|
||||
`SMSG_NAME_QUERY_RESPONSE` write path at `0x0055F310`.
|
||||
|
||||
### `C_PlayerInfo.RememberPlayer(guid, name, classToken)`
|
||||
|
||||
Adds a `(guid → name, classID)` entry to the persistent name cache.
|
||||
For the engine-driven coverage (chat / group / guild / visible
|
||||
objects), no addon-side feeding is needed — those flow into the
|
||||
cache automatically through the engine's `SMSG_NAME_QUERY_RESPONSE`
|
||||
write path. This call exists for the *other* sources libunitscan-
|
||||
style addons harvest from but the engine NameCache doesn't see
|
||||
directly: `/who` results, mouseover, target snapshots, etc.
|
||||
|
||||
Returns `true` on success, `false` if the persistent cache isn't
|
||||
enabled or the args are malformed.
|
||||
|
||||
- `guid` — `"0xHHHHHHHHLLLLLLLL"` string (same format `UnitGUID`
|
||||
returns). 8-hex `"0xLLLLLLLL"` is also accepted (hi-dword zero).
|
||||
- `name` — 1–12 ASCII chars (vanilla character-name range). Tabs,
|
||||
newlines, and high bytes are stripped.
|
||||
- `classToken` — uppercase token like `"WARRIOR"`, `"MAGE"`. Looked
|
||||
up against `ChrClasses.dbc` filename field, case-insensitive.
|
||||
Passing an unknown token keeps the entry's prior class (so a
|
||||
name-only sighting doesn't erase good class data).
|
||||
|
||||
```lua
|
||||
-- Harvest /who results into the persistent cache
|
||||
local function OnWhoUpdate()
|
||||
for i = 1, GetNumWhoResults() do
|
||||
local name, _, _, _, class = GetWhoInfo(i) -- class is localized
|
||||
-- pfUI has L["class"][class] for localized→token mapping
|
||||
local token = L["class"][class]
|
||||
if token then
|
||||
-- GetWhoInfo doesn't expose GUID; addons can pair this
|
||||
-- with GetCurrentChatGUID() at the call site that
|
||||
-- triggered the query, or skip RememberPlayer for /who
|
||||
-- and rely on the engine populating from chat instead.
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
`name`-only updates (no classID) **do not overwrite** an existing
|
||||
classID — useful for "I saw this name in a guild login system msg"
|
||||
sightings that don't have class info but want to refresh the name.
|
||||
|
||||
The "deleted character recreated with same name, different class"
|
||||
collision case that name-keyed caches suffer from doesn't apply
|
||||
here: GUIDs are permanent for the life of a vanilla character, so
|
||||
the new character has a different GUID and gets a different cache
|
||||
entry.
|
||||
|
||||
### `ClassicAPI.SetPersistentNameCacheEnabled(enabled)`
|
||||
|
||||
Opts into (or out of) the persistent name cache. `enabled` is a
|
||||
boolean (numeric `0`/`1` also accepted). Persists to
|
||||
`WTF\Account\<account>\ClassicAPI.txt` as
|
||||
`PersistentNameCacheEnabled=1`/`0`, so the choice survives
|
||||
client restarts.
|
||||
|
||||
When enabled:
|
||||
|
||||
- Every `SMSG_NAME_QUERY_RESPONSE` the engine processes is also
|
||||
written to `WTF\Account\<account>\<realm>\ClassicAPI_NameCache.txt`.
|
||||
- Lua-side `C_PlayerInfo.RememberPlayer` calls become effective
|
||||
(they're no-ops when the cache is disabled).
|
||||
- `GetPlayerInfoByGUID` gains the cross-session fallback path
|
||||
documented above.
|
||||
|
||||
When disabled, the on-disk file is left in place (re-enabling later
|
||||
restores the prior contents); future writes are simply suppressed.
|
||||
|
||||
The cache file is shared across all characters on the same
|
||||
account+realm — a 50-character bank alt's chat-scraping doesn't
|
||||
double the storage cost. Format is tab-separated text
|
||||
(`guidHi guidLo classID name` per line), about 30 bytes per
|
||||
entry, hand-editable if you ever need to.
|
||||
|
||||
```lua
|
||||
ClassicAPI.SetPersistentNameCacheEnabled(true)
|
||||
```
|
||||
|
||||
Returns nothing.
|
||||
|
||||
### `ClassicAPI.GetPersistentNameCacheEnabled()`
|
||||
|
||||
Returns the current state of the persistent name cache as a
|
||||
boolean. `false` until
|
||||
[`SetPersistentNameCacheEnabled`](#classicapisetpersistentnamecacheenabledenabled)
|
||||
has been called (or its prior call survived in the on-disk settings
|
||||
file).
|
||||
|
||||
```lua
|
||||
if ClassicAPI.GetPersistentNameCacheEnabled() then
|
||||
-- persistent fallback is active for GetPlayerInfoByGUID
|
||||
end
|
||||
```
|
||||
|
||||
### `UnitIsAFK(unit)`
|
||||
|
||||
Returns `true` if the unit is currently AFK (toggled via `/afk` or
|
||||
|
||||
@@ -720,6 +720,27 @@ enum Offsets {
|
||||
VAR_PLAYER_NAME_CACHE = 0x00C0E228,
|
||||
FUN_PLAYER_INFO_LOOKUP = 0x0055F080,
|
||||
|
||||
// NameCache write entry — `__thiscall(this = cache, packetData,
|
||||
// guidLo, guidHi)` at 0x0055F310. Called once per
|
||||
// SMSG_NAME_QUERY_RESPONSE after the engine's opcode handler
|
||||
// builds a `packetData` buffer with the layout:
|
||||
// +0x000 name[48]
|
||||
// +0x030 realm[256]
|
||||
// +0x130 unknown[8] (probably (charGuidLo, charGuidHi))
|
||||
// +0x138 race (u32)
|
||||
// +0x13C sex (u32, 0/1 wire)
|
||||
// +0x140 class (u32)
|
||||
// Writes that data into the cache entry and dispatches any
|
||||
// pending callbacks. Decoded by Ghidra; field offsets verified
|
||||
// against the `*(uint*)(param_2 + N)` reads in the function body.
|
||||
//
|
||||
// Hooking here gives us a single chokepoint covering every name-
|
||||
// query response the engine processes — chat, group/raid sync,
|
||||
// guild roster, visible-object resolution. The hook runs after
|
||||
// the engine has settled the entry, so reading from the cache
|
||||
// post-hook is safe.
|
||||
FUN_PLAYER_INFO_CACHE_WRITE = 0x0055F310,
|
||||
|
||||
// Entry-data offsets. The lookup returns `entry + 0x20`, so these
|
||||
// are relative to that pointer (not to the entry's hash-table
|
||||
// header). Field layout verified by decoding the cache writer
|
||||
@@ -769,6 +790,35 @@ enum Offsets {
|
||||
OFF_FACTION_NAMES = 0x4C,
|
||||
OFF_FACTION_DESCRIPTIONS = 0x70,
|
||||
|
||||
// Who-query (the /who system).
|
||||
//
|
||||
// `Script_SendWho` (0x005AD3B0) is a 32-byte wrapper:
|
||||
// - validate arg1 is a string via lua_isstring
|
||||
// - load WhoSystem singleton from `[VAR_WHO_SYSTEM]`
|
||||
// - if non-NULL, lua_tostring(L, 1) for the query string
|
||||
// - tail-call `FUN_WHO_SYSTEM_SEND_QUERY` with
|
||||
// `__thiscall(this = WhoSystem, queryStr)`
|
||||
//
|
||||
// The query string follows the engine's standard /who filter syntax
|
||||
// (`"n-Bob"`, `"r-Alliance"`, `"c-Warlock"`, etc.); the inner
|
||||
// function at `FUN_WHO_SYSTEM_SEND_QUERY` (~1.5KB) does the
|
||||
// parse + CMSG_WHO build + network send.
|
||||
//
|
||||
// `Script_SetWhoToUI` (0x005AD870) is even smaller — 13 bytes that
|
||||
// store arg1 (as int, default 0) to `[VAR_WHO_TO_UI_FLAG]`. The
|
||||
// SMSG_WHO response handler at ~0x005ADF80 reads the flag at
|
||||
// `0x005ADF9C` to decide whether the results buffer into the
|
||||
// engine's WhoList (flag != 0 → list path, friends-frame fires
|
||||
// WHO_LIST_UPDATE; flag == 0 → results go to chat as
|
||||
// `"Found N players matching..."`).
|
||||
//
|
||||
// Server-side cooldown for CMSG_WHO is ~5 seconds — a faster
|
||||
// client gets silent-dropped, so any client-side gating just
|
||||
// matches that.
|
||||
VAR_WHO_SYSTEM = 0x00C28168,
|
||||
VAR_WHO_TO_UI_FLAG = 0x00C2A12C,
|
||||
FUN_WHO_SYSTEM_SEND_QUERY = 0x005AEBB0,
|
||||
|
||||
// Per-faction current standing — `__fastcall(ecx = factionID) → int`.
|
||||
// Returns `base + delta` where the two values are stored at
|
||||
// `+0x08` / `+0x0C` of the player's rep slot (slot stride 0x10,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// 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/>.
|
||||
|
||||
// `C_FriendList.SendWhoQueryByName` — sends a /who name-filter query
|
||||
// invisibly (the server's standard "Players found" chat message
|
||||
// suppressed; results buffer into the engine's WhoList so the
|
||||
// existing `GetWhoInfo` / `WHO_LIST_UPDATE` work normally).
|
||||
//
|
||||
// Vanilla 1.12 exposes only `SendWho(query)` + `SetWhoToUI(flag)` as
|
||||
// separate primitives; addons that want to query a specific player
|
||||
// without triggering the friends-panel popup have to do the dance
|
||||
// pfUI's `chat.lua` does (~50 lines: pending state, cooldown timer,
|
||||
// FriendsFrame_OnEvent wrap, flag toggle). This collapses the
|
||||
// invocation half of that dance to one call.
|
||||
//
|
||||
// The friends-panel suppression itself still needs an addon-side
|
||||
// `FriendsFrame_OnEvent` wrap — gated on `IsWhoQueryPending()` —
|
||||
// because we don't hook the WHO_LIST_UPDATE engine dispatch yet
|
||||
// (that requires interposing on `FrameScript_SignalEvent` or the
|
||||
// SMSG_WHO handler, both higher-risk hook sites). With the wrap +
|
||||
// gate, pfUI's ScanWhoName collapses to a one-liner.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace FriendList::Who {
|
||||
|
||||
namespace {
|
||||
|
||||
// Server-enforced /who cooldown is ~5 seconds — a faster client gets
|
||||
// silent-dropped. We mirror that on the client to avoid wasting
|
||||
// queries that won't get a response, and to give addons a clean
|
||||
// "did my query get sent?" signal via the bool return.
|
||||
constexpr DWORD kCooldownMs = 5000;
|
||||
|
||||
// Window during which `IsWhoQueryPending()` reports true after a
|
||||
// send. Generous upper bound on response RTT — the engine usually
|
||||
// replies within a few hundred ms, but a stalled connection or
|
||||
// dropped packet can stretch it. Larger than the cooldown so a
|
||||
// time-based reset still pins down the worst case.
|
||||
constexpr DWORD kPendingWindowMs = 5000;
|
||||
|
||||
DWORD g_lastSendTick = 0;
|
||||
bool g_haveSent = false;
|
||||
|
||||
bool OnCooldown() {
|
||||
if (!g_haveSent)
|
||||
return false;
|
||||
const DWORD now = GetTickCount();
|
||||
return (now - g_lastSendTick) < kCooldownMs;
|
||||
}
|
||||
|
||||
bool IsPending() {
|
||||
if (!g_haveSent)
|
||||
return false;
|
||||
const DWORD now = GetTickCount();
|
||||
return (now - g_lastSendTick) < kPendingWindowMs;
|
||||
}
|
||||
|
||||
// `__thiscall(this = WhoSystem*, queryStr)` — the inner sender that
|
||||
// `Script_SendWho` tail-calls. Parses the /who filter syntax and
|
||||
// ships CMSG_WHO. Returns void; failure is silent (e.g. NULL system
|
||||
// pointer pre-login).
|
||||
using SendQuery_t = void(__thiscall *)(void *self, const char *queryStr);
|
||||
|
||||
bool SendQueryInternal(const char *fullQuery) {
|
||||
auto *system = *reinterpret_cast<void *const *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_WHO_SYSTEM));
|
||||
if (system == nullptr)
|
||||
return false;
|
||||
auto fn = reinterpret_cast<SendQuery_t>(Offsets::FUN_WHO_SYSTEM_SEND_QUERY);
|
||||
fn(system, fullQuery);
|
||||
return true;
|
||||
}
|
||||
|
||||
void SetWhoToUIFlag(int value) {
|
||||
*reinterpret_cast<int *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_WHO_TO_UI_FLAG)) = value;
|
||||
}
|
||||
|
||||
// `C_FriendList.SendWhoQueryByName(name)` — fires a /who query for
|
||||
// exactly one character name, buffered into the WhoList so a normal
|
||||
// `WHO_LIST_UPDATE` + `GetWhoInfo(i)` flow can read the result.
|
||||
//
|
||||
// Returns:
|
||||
// `true` — query was sent (sets pending state; cooldown begins).
|
||||
// `false` — on cooldown, name was empty, or the WhoSystem isn't
|
||||
// yet initialized (pre-login).
|
||||
//
|
||||
// Does NOT suppress the friends-panel popup on response. Addons that
|
||||
// don't want the popup wrap `FriendsFrame_OnEvent` themselves and
|
||||
// gate on `C_FriendList.IsWhoQueryPending()`:
|
||||
//
|
||||
// local original = FriendsFrame_OnEvent
|
||||
// _G.FriendsFrame_OnEvent = function()
|
||||
// if event == "WHO_LIST_UPDATE" and C_FriendList.IsWhoQueryPending() then
|
||||
// return
|
||||
// end
|
||||
// return original()
|
||||
// end
|
||||
//
|
||||
// (Hooking the engine's signal dispatch to suppress automatically is
|
||||
// a follow-up — would need a hook on `FrameScript_SignalEvent` or
|
||||
// the SMSG_WHO handler, both higher-risk than the surface we have
|
||||
// today.)
|
||||
int __fastcall Script_C_FriendList_SendWhoQueryByName(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1)) {
|
||||
Game::Lua::Error(L,
|
||||
"Usage: C_FriendList.SendWhoQueryByName(name)");
|
||||
return 0;
|
||||
}
|
||||
const char *name = Game::Lua::ToString(L, 1);
|
||||
if (name == nullptr || *name == '\0') {
|
||||
Game::Lua::PushBoolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
if (OnCooldown()) {
|
||||
Game::Lua::PushBoolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Build the "n-<name>" filter the engine's parser expects. Bound
|
||||
// by the realistic max character name length (12) plus the
|
||||
// 2-char prefix plus a NUL — 16 bytes is comfortably enough; cap
|
||||
// at 48 for paranoia in case a server allows longer names.
|
||||
char query[64];
|
||||
const size_t prefixLen = 2;
|
||||
const size_t maxName = sizeof(query) - prefixLen - 1;
|
||||
size_t nameLen = std::strlen(name);
|
||||
if (nameLen > maxName)
|
||||
nameLen = maxName;
|
||||
std::memcpy(query, "n-", prefixLen);
|
||||
std::memcpy(query + prefixLen, name, nameLen);
|
||||
query[prefixLen + nameLen] = '\0';
|
||||
|
||||
// Engine routes responses into the WhoList (and fires
|
||||
// WHO_LIST_UPDATE) when this flag is set; otherwise it prints
|
||||
// "Found N players matching..." to chat. We want list semantics.
|
||||
SetWhoToUIFlag(1);
|
||||
if (!SendQueryInternal(query)) {
|
||||
Game::Lua::PushBoolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
g_lastSendTick = GetTickCount();
|
||||
g_haveSent = true;
|
||||
Game::Lua::PushBoolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `C_FriendList.IsWhoQueryPending()` — true within a short window
|
||||
// (~5s) after the most recent `SendWhoQueryByName` returned true.
|
||||
// Time-based — the engine doesn't expose a "response arrived" hook
|
||||
// from C++ yet, so we conservatively report pending until the
|
||||
// cooldown expires. In practice the WHO_LIST_UPDATE response lands
|
||||
// well inside this window.
|
||||
int __fastcall Script_C_FriendList_IsWhoQueryPending(void *L) {
|
||||
Game::Lua::PushBoolean(L, IsPending() ? 1 : 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterTableFunction("C_FriendList", "SendWhoQueryByName",
|
||||
&Script_C_FriendList_SendWhoQueryByName);
|
||||
Game::Lua::RegisterTableFunction("C_FriendList", "IsWhoQueryPending",
|
||||
&Script_C_FriendList_IsWhoQueryPending);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace FriendList::Who
|
||||
+32
-12
@@ -35,6 +35,7 @@
|
||||
// them, or they appear in guild login spam), they will be.
|
||||
|
||||
#include "Game.h"
|
||||
#include "NameCache.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -145,19 +146,38 @@ int __fastcall Script_GetPlayerInfoByGUID(void *L) {
|
||||
const uint8_t *entry = fn(cache, lo, hi, &cookie,
|
||||
nullptr /*callback*/, nullptr /*userData*/,
|
||||
0 /*retryFlag*/);
|
||||
if (entry == nullptr)
|
||||
return 0; // cache miss / pending → nil
|
||||
|
||||
const char *name = reinterpret_cast<const char *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_NAME);
|
||||
const char *realm = reinterpret_cast<const char *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_REALM);
|
||||
const uint32_t race = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_RACE);
|
||||
const uint32_t sex = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_SEX);
|
||||
const uint32_t classID = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_CLASS);
|
||||
const char *name = nullptr;
|
||||
const char *realm = nullptr;
|
||||
uint32_t race = 0;
|
||||
uint32_t sex = 0;
|
||||
uint32_t classID = 0;
|
||||
|
||||
if (entry != nullptr) {
|
||||
name = reinterpret_cast<const char *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_NAME);
|
||||
realm = reinterpret_cast<const char *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_REALM);
|
||||
race = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_RACE);
|
||||
sex = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_SEX);
|
||||
classID = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_INFO_CLASS);
|
||||
} else {
|
||||
// Engine miss — fall back to the persistent name cache (if
|
||||
// enabled). Only `name` and `classID` are stored there; the
|
||||
// other slots stay zero so race/sex come back nil-ish and
|
||||
// realm comes back "" (matching what the engine reports for
|
||||
// partially-populated entries).
|
||||
const NameCache::Entry *cached = NameCache::Lookup(
|
||||
(static_cast<uint64_t>(hi) << 32) | lo);
|
||||
if (cached == nullptr || cached->name.empty())
|
||||
return 0;
|
||||
name = cached->name.c_str();
|
||||
classID = cached->classID;
|
||||
realm = "";
|
||||
}
|
||||
|
||||
const char *englishClass = DBCStringField(
|
||||
Offsets::VAR_CHRCLASSES_RECORDS, Offsets::VAR_CHRCLASSES_COUNT,
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
// 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/>.
|
||||
|
||||
// Persistent name cache — see NameCache.h for the motivating use case.
|
||||
//
|
||||
// Two persistence files:
|
||||
//
|
||||
// `WTF\Account\<acct>\ClassicAPI.txt`
|
||||
// Account-level settings. Single `PersistentNameCacheEnabled=1`
|
||||
// line for now; other ClassicAPI features may layer here later.
|
||||
// Loaded on first need (when the account-name global is
|
||||
// populated by the engine's login flow). Hand-edits survive.
|
||||
//
|
||||
// `WTF\Account\<acct>\<realm>\ClassicAPI_NameCache.txt`
|
||||
// Per-realm cache contents. One entry per line:
|
||||
// `guidHi guidLo classID name`
|
||||
// (fields tab-separated). Loaded once the realm name is
|
||||
// available post-login. Saved when (a) a recent write hasn't
|
||||
// been flushed AND (b) at least 30 seconds have elapsed since
|
||||
// the prior save, OR (c) DLL teardown / `Flush()` is called.
|
||||
//
|
||||
// Population sources:
|
||||
// 1. The engine's NameCache writer (`FUN_PLAYER_INFO_CACHE_WRITE`)
|
||||
// — every SMSG_NAME_QUERY_RESPONSE the engine processes flows
|
||||
// through here. Covers chat, group/raid sync, guild roster
|
||||
// updates, visible-object resolution.
|
||||
// 2. `C_PlayerInfo.RememberPlayer(guid, name, classToken)` from
|
||||
// Lua — lets addons feed in sources the engine cache doesn't
|
||||
// touch directly (e.g. /who results parsed via GetWhoInfo,
|
||||
// mouseover, target).
|
||||
//
|
||||
// Lookups are GUID-keyed, so the "deleted character recreated with
|
||||
// same name, different class" failure mode of name-keyed caches
|
||||
// (libunitscan, etc.) doesn't apply — different GUIDs are different
|
||||
// entries, period.
|
||||
|
||||
#include "NameCache.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace Player::NameCache {
|
||||
|
||||
namespace {
|
||||
|
||||
// Flush throttling. Per-entry I/O would thrash on first-login when
|
||||
// the engine queries hundreds of names from guild/raid rosters in a
|
||||
// burst; we coalesce within the window so we write at most every
|
||||
// `kFlushIntervalMs`. The flush itself runs from the engine
|
||||
// NameCache write hook (no separate worker thread), so the dirty
|
||||
// flag is just checked on each subsequent write.
|
||||
constexpr DWORD kFlushIntervalMs = 30000;
|
||||
|
||||
// ChrClasses.dbc max ID. Anything above this is a corrupt input.
|
||||
constexpr uint32_t kMaxClassID = 16;
|
||||
|
||||
std::unordered_map<uint64_t, Entry> g_entries;
|
||||
bool g_enabled = false;
|
||||
bool g_settingsLoaded = false;
|
||||
bool g_cacheLoaded = false;
|
||||
bool g_dirty = false;
|
||||
DWORD g_lastSaveTick = 0;
|
||||
|
||||
// ----- engine globals helpers (mirrors EquipmentSet::Storage) -----
|
||||
|
||||
const char *ReadAccountName() {
|
||||
return *reinterpret_cast<const char *const *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ACCOUNT_NAME_PTR));
|
||||
}
|
||||
|
||||
const char *ReadRealmName() {
|
||||
auto *info = *reinterpret_cast<uint8_t **>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_REALM_INFO_PTR));
|
||||
if (info == nullptr)
|
||||
return nullptr;
|
||||
return *reinterpret_cast<const char *const *>(
|
||||
info + Offsets::OFF_REALM_INFO_NAME);
|
||||
}
|
||||
|
||||
// ----- path resolution -----
|
||||
|
||||
std::string SettingsPath() {
|
||||
const char *account = ReadAccountName();
|
||||
if (account == nullptr || account[0] == '\0')
|
||||
return {};
|
||||
std::string out = "WTF\\Account\\";
|
||||
out += account;
|
||||
out += "\\ClassicAPI.txt";
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string CachePath() {
|
||||
const char *account = ReadAccountName();
|
||||
if (account == nullptr || account[0] == '\0')
|
||||
return {};
|
||||
const char *realm = ReadRealmName();
|
||||
if (realm == nullptr || realm[0] == '\0')
|
||||
return {};
|
||||
std::string out = "WTF\\Account\\";
|
||||
out += account;
|
||||
out += '\\';
|
||||
out += realm;
|
||||
out += "\\ClassicAPI_NameCache.txt";
|
||||
return out;
|
||||
}
|
||||
|
||||
// ----- settings load/save -----
|
||||
|
||||
void LoadSettingsIfNeeded() {
|
||||
if (g_settingsLoaded)
|
||||
return;
|
||||
const std::string path = SettingsPath();
|
||||
if (path.empty())
|
||||
return; // pre-login; retry on next call (g_settingsLoaded stays false)
|
||||
g_settingsLoaded = true; // path resolved — even an empty file is "loaded"
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open())
|
||||
return; // no settings file = all defaults (disabled)
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
while (!line.empty() && (line.back() == '\r' || line.back() == '\n'
|
||||
|| line.back() == ' ' || line.back() == '\t'))
|
||||
line.pop_back();
|
||||
if (line.empty() || line[0] == '#')
|
||||
continue;
|
||||
auto eq = line.find('=');
|
||||
if (eq == std::string::npos)
|
||||
continue;
|
||||
const std::string key = line.substr(0, eq);
|
||||
const std::string value = line.substr(eq + 1);
|
||||
if (key == "PersistentNameCacheEnabled")
|
||||
g_enabled = (value == "1" || value == "true");
|
||||
}
|
||||
}
|
||||
|
||||
void SaveSettings() {
|
||||
const std::string path = SettingsPath();
|
||||
if (path.empty())
|
||||
return;
|
||||
const std::string tmp = path + ".tmp";
|
||||
{
|
||||
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
|
||||
if (!out.is_open())
|
||||
return;
|
||||
out << "# ClassicAPI account-level settings\n";
|
||||
out << "PersistentNameCacheEnabled=" << (g_enabled ? 1 : 0) << "\n";
|
||||
if (!out)
|
||||
return;
|
||||
}
|
||||
std::remove(path.c_str());
|
||||
std::rename(tmp.c_str(), path.c_str());
|
||||
}
|
||||
|
||||
// ----- cache load/save -----
|
||||
|
||||
// Lightweight name sanitizer — vanilla player names are 2..12 ASCII
|
||||
// letters, but for paranoia drop anything that would break a line
|
||||
// (tab, newline) and cap length. Anything else passes through.
|
||||
std::string SanitizeName(const char *name) {
|
||||
if (name == nullptr)
|
||||
return {};
|
||||
std::string out;
|
||||
for (const char *p = name; *p && out.size() < 16; ++p) {
|
||||
const char c = *p;
|
||||
if (c == '\t' || c == '\r' || c == '\n')
|
||||
continue;
|
||||
out.push_back(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void LoadCacheIfNeeded() {
|
||||
if (g_cacheLoaded)
|
||||
return;
|
||||
const std::string path = CachePath();
|
||||
if (path.empty())
|
||||
return; // pre-realm; retry on next call (g_cacheLoaded stays false)
|
||||
g_cacheLoaded = true;
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open())
|
||||
return; // first run for this realm
|
||||
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
while (!line.empty() && (line.back() == '\r' || line.back() == '\n'))
|
||||
line.pop_back();
|
||||
if (line.empty() || line[0] == '#')
|
||||
continue;
|
||||
|
||||
// tab-separated: hi lo classID name
|
||||
std::istringstream is(line);
|
||||
std::string hiStr, loStr, classStr, name;
|
||||
if (!(is >> hiStr >> loStr >> classStr))
|
||||
continue;
|
||||
// Consume the single tab/space, then read remaining name
|
||||
// as-is (no spaces in vanilla names but tolerate them).
|
||||
while (is.peek() == ' ' || is.peek() == '\t')
|
||||
is.get();
|
||||
std::getline(is, name);
|
||||
if (name.empty())
|
||||
continue;
|
||||
|
||||
const uint32_t hi = static_cast<uint32_t>(std::strtoul(hiStr.c_str(), nullptr, 16));
|
||||
const uint32_t lo = static_cast<uint32_t>(std::strtoul(loStr.c_str(), nullptr, 16));
|
||||
const uint32_t classID = static_cast<uint32_t>(std::strtoul(classStr.c_str(), nullptr, 10));
|
||||
if (lo == 0 && hi == 0)
|
||||
continue;
|
||||
if (classID > kMaxClassID)
|
||||
continue;
|
||||
const uint64_t guid = (static_cast<uint64_t>(hi) << 32) | lo;
|
||||
Entry e;
|
||||
e.guid = guid;
|
||||
e.name = SanitizeName(name.c_str());
|
||||
e.classID = classID;
|
||||
if (!e.name.empty())
|
||||
g_entries[guid] = std::move(e);
|
||||
}
|
||||
}
|
||||
|
||||
void SaveCache() {
|
||||
const std::string path = CachePath();
|
||||
if (path.empty())
|
||||
return;
|
||||
const std::string tmp = path + ".tmp";
|
||||
{
|
||||
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
|
||||
if (!out.is_open())
|
||||
return;
|
||||
out << "# ClassicAPI name cache v1 (per-realm)\n";
|
||||
out << "# guidHi\tguidLo\tclassID\tname\n";
|
||||
for (const auto &kv : g_entries) {
|
||||
const Entry &e = kv.second;
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof(buf), "%08X\t%08X\t%u\t",
|
||||
static_cast<uint32_t>(e.guid >> 32),
|
||||
static_cast<uint32_t>(e.guid),
|
||||
e.classID);
|
||||
out << buf << e.name << "\n";
|
||||
}
|
||||
if (!out)
|
||||
return;
|
||||
}
|
||||
std::remove(path.c_str());
|
||||
std::rename(tmp.c_str(), path.c_str());
|
||||
g_dirty = false;
|
||||
g_lastSaveTick = GetTickCount();
|
||||
}
|
||||
|
||||
void MaybeFlush() {
|
||||
if (!g_dirty)
|
||||
return;
|
||||
const DWORD now = GetTickCount();
|
||||
if ((now - g_lastSaveTick) < kFlushIntervalMs)
|
||||
return;
|
||||
SaveCache();
|
||||
}
|
||||
|
||||
// ----- engine NameCache hook -----
|
||||
|
||||
// `__thiscall(this = cache, packet, guidLo, guidHi)`. We forward to
|
||||
// the original first (so the engine settles its entry and dispatches
|
||||
// callbacks), then read the same fields back out of the packet and
|
||||
// mirror them into our store.
|
||||
using CacheWrite_t = void(__thiscall *)(void *self, const uint8_t *packet,
|
||||
uint32_t guidLo, uint32_t guidHi);
|
||||
CacheWrite_t CacheWrite_o = nullptr;
|
||||
|
||||
void __fastcall CacheWrite_h(void *self, void *edx, const uint8_t *packet,
|
||||
uint32_t guidLo, uint32_t guidHi) {
|
||||
// __fastcall stub forwards to __thiscall — MSVC's free-function
|
||||
// __fastcall lays out (ECX=self, EDX=unused, stack=packet, lo, hi),
|
||||
// matching the engine's __thiscall(self, packet, lo, hi).
|
||||
CacheWrite_o(self, packet, guidLo, guidHi);
|
||||
(void)edx;
|
||||
|
||||
if (!g_enabled)
|
||||
return;
|
||||
if (packet == nullptr)
|
||||
return;
|
||||
if (guidLo == 0 && guidHi == 0)
|
||||
return;
|
||||
|
||||
LoadCacheIfNeeded();
|
||||
|
||||
const char *name = reinterpret_cast<const char *>(
|
||||
packet + Offsets::OFF_PLAYER_INFO_NAME);
|
||||
const uint32_t classID = *reinterpret_cast<const uint32_t *>(
|
||||
packet + Offsets::OFF_PLAYER_INFO_CLASS);
|
||||
if (name[0] == '\0')
|
||||
return;
|
||||
if (classID == 0 || classID > kMaxClassID)
|
||||
return;
|
||||
|
||||
const uint64_t guid = (static_cast<uint64_t>(guidHi) << 32) | guidLo;
|
||||
Entry &e = g_entries[guid];
|
||||
const std::string sanitized = SanitizeName(name);
|
||||
bool changed = false;
|
||||
if (e.guid != guid) {
|
||||
e.guid = guid;
|
||||
changed = true;
|
||||
}
|
||||
if (e.name != sanitized) {
|
||||
e.name = sanitized;
|
||||
changed = true;
|
||||
}
|
||||
if (e.classID != classID) {
|
||||
e.classID = classID;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
g_dirty = true;
|
||||
MaybeFlush();
|
||||
}
|
||||
}
|
||||
|
||||
static const Game::HookAutoRegister _hookreg{
|
||||
Offsets::FUN_PLAYER_INFO_CACHE_WRITE,
|
||||
reinterpret_cast<void *>(&CacheWrite_h),
|
||||
reinterpret_cast<void **>(&CacheWrite_o)};
|
||||
|
||||
// ----- Lua surface -----
|
||||
|
||||
// Parses `"0xHHHHHHHHLLLLLLLL"` (16-digit) or `"0xLLLLLLLL"` (8-digit
|
||||
// with implicit hi=0). Mirrors `Player::Info::ParseGUID` exactly —
|
||||
// kept inline here so we don't expand the public surface of that TU
|
||||
// just for one helper.
|
||||
bool ParseGUID(const char *str, uint64_t *outGUID) {
|
||||
if (str == nullptr || str[0] != '0' || (str[1] != 'x' && str[1] != 'X'))
|
||||
return false;
|
||||
const char *hex = str + 2;
|
||||
const size_t len = std::strlen(hex);
|
||||
if (len != 8 && len != 16)
|
||||
return false;
|
||||
uint64_t value = 0;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
const char c = hex[i];
|
||||
uint64_t digit;
|
||||
if (c >= '0' && c <= '9') digit = c - '0';
|
||||
else if (c >= 'a' && c <= 'f') digit = 10 + (c - 'a');
|
||||
else if (c >= 'A' && c <= 'F') digit = 10 + (c - 'A');
|
||||
else return false;
|
||||
value = (value << 4) | digit;
|
||||
}
|
||||
*outGUID = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Returns the ChrClasses.dbc record ID for a class token like
|
||||
// `"WARRIOR"`, `"MAGE"`, etc. Case-insensitive. 0 if not matched.
|
||||
// 1.12 has 9 player classes; we walk the DBC each call (cheap — 9
|
||||
// records, each filename a few bytes) rather than building a static
|
||||
// table that risks getting out-of-sync.
|
||||
uint32_t ResolveClassToken(const char *token) {
|
||||
if (token == nullptr || *token == '\0')
|
||||
return 0;
|
||||
const int count = *reinterpret_cast<const int *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_CHRCLASSES_COUNT));
|
||||
const uint8_t *const *records = *reinterpret_cast<const uint8_t *const *const *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_CHRCLASSES_RECORDS));
|
||||
if (records == nullptr)
|
||||
return 0;
|
||||
for (int i = 1; i <= count; ++i) {
|
||||
const uint8_t *rec = records[i];
|
||||
if (rec == nullptr)
|
||||
continue;
|
||||
const char *filename = *reinterpret_cast<const char *const *>(
|
||||
rec + Offsets::OFF_CHRCLASSES_FILENAME);
|
||||
if (filename == nullptr)
|
||||
continue;
|
||||
// Case-insensitive compare; vanilla tokens are uppercase
|
||||
// ("WARRIOR", "MAGE", ...) and modern Classic uses the same.
|
||||
const char *a = filename;
|
||||
const char *b = token;
|
||||
bool match = true;
|
||||
while (*a && *b) {
|
||||
char ca = *a, cb = *b;
|
||||
if (ca >= 'a' && ca <= 'z') ca -= 32;
|
||||
if (cb >= 'a' && cb <= 'z') cb -= 32;
|
||||
if (ca != cb) { match = false; break; }
|
||||
++a; ++b;
|
||||
}
|
||||
if (match && *a == '\0' && *b == '\0')
|
||||
return static_cast<uint32_t>(i);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// `C_PlayerInfo.RememberPlayer(guid, name, classToken)` — stores the
|
||||
// triple in the persistent cache. `classToken` is the uppercase
|
||||
// engine token (`"WARRIOR"`, `"MAGE"`, ...). Returns `true` on
|
||||
// successful insert/update, `false` if the cache is disabled or the
|
||||
// args are malformed.
|
||||
int __fastcall Script_C_PlayerInfo_RememberPlayer(void *L) {
|
||||
if (!IsEnabled()) {
|
||||
Game::Lua::PushBoolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsString(L, 2)
|
||||
|| !Game::Lua::IsString(L, 3)) {
|
||||
Game::Lua::Error(L,
|
||||
"Usage: C_PlayerInfo.RememberPlayer(guid, name, classToken)");
|
||||
return 0;
|
||||
}
|
||||
uint64_t guid;
|
||||
if (!ParseGUID(Game::Lua::ToString(L, 1), &guid) || guid == 0) {
|
||||
Game::Lua::PushBoolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
const char *name = Game::Lua::ToString(L, 2);
|
||||
if (name == nullptr || name[0] == '\0') {
|
||||
Game::Lua::PushBoolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
const char *classToken = Game::Lua::ToString(L, 3);
|
||||
const uint32_t classID = ResolveClassToken(classToken);
|
||||
// classID == 0 is acceptable (caller passed an unknown token);
|
||||
// we keep the prior class if any. This mirrors what Remember()
|
||||
// does when called with classID==0 elsewhere.
|
||||
Remember(guid, name, classID);
|
||||
Game::Lua::PushBoolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `ClassicAPI.SetPersistentNameCacheEnabled(bool)` — opt-in toggle.
|
||||
// Persists to the account-level settings file. Enabling triggers a
|
||||
// lazy load of any prior cache contents for the current realm.
|
||||
int __fastcall Script_ClassicAPI_SetPersistentNameCacheEnabled(void *L) {
|
||||
LoadSettingsIfNeeded();
|
||||
bool desired = false;
|
||||
if (Game::Lua::IsNumber(L, 1))
|
||||
desired = Game::Lua::ToNumber(L, 1) != 0;
|
||||
else
|
||||
desired = Game::Lua::ToBoolean(L, 1) != 0;
|
||||
if (g_enabled != desired) {
|
||||
g_enabled = desired;
|
||||
SaveSettings();
|
||||
if (g_enabled) {
|
||||
LoadCacheIfNeeded();
|
||||
} else {
|
||||
// Flush any pending writes before going quiet.
|
||||
if (g_dirty)
|
||||
SaveCache();
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_ClassicAPI_GetPersistentNameCacheEnabled(void *L) {
|
||||
LoadSettingsIfNeeded();
|
||||
Game::Lua::PushBoolean(L, g_enabled ? 1 : 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterTableFunction("C_PlayerInfo", "RememberPlayer",
|
||||
&Script_C_PlayerInfo_RememberPlayer);
|
||||
Game::Lua::RegisterTableFunction("ClassicAPI", "SetPersistentNameCacheEnabled",
|
||||
&Script_ClassicAPI_SetPersistentNameCacheEnabled);
|
||||
Game::Lua::RegisterTableFunction("ClassicAPI", "GetPersistentNameCacheEnabled",
|
||||
&Script_ClassicAPI_GetPersistentNameCacheEnabled);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
const Entry *Lookup(uint64_t guid) {
|
||||
if (!g_enabled)
|
||||
return nullptr;
|
||||
LoadCacheIfNeeded();
|
||||
auto it = g_entries.find(guid);
|
||||
if (it == g_entries.end())
|
||||
return nullptr;
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
void Remember(uint64_t guid, const char *name, uint32_t classID) {
|
||||
if (!g_enabled || guid == 0 || name == nullptr || name[0] == '\0')
|
||||
return;
|
||||
LoadCacheIfNeeded();
|
||||
if (classID > kMaxClassID)
|
||||
classID = 0;
|
||||
Entry &e = g_entries[guid];
|
||||
const std::string sanitized = SanitizeName(name);
|
||||
bool changed = false;
|
||||
if (e.guid != guid) {
|
||||
e.guid = guid;
|
||||
changed = true;
|
||||
}
|
||||
if (e.name != sanitized) {
|
||||
e.name = sanitized;
|
||||
changed = true;
|
||||
}
|
||||
// classID==0 means "caller doesn't know"; don't overwrite a
|
||||
// real classID with unknown. Only update on real → real change.
|
||||
if (classID != 0 && e.classID != classID) {
|
||||
e.classID = classID;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
g_dirty = true;
|
||||
MaybeFlush();
|
||||
}
|
||||
}
|
||||
|
||||
bool IsEnabled() {
|
||||
LoadSettingsIfNeeded();
|
||||
return g_enabled;
|
||||
}
|
||||
|
||||
void SetEnabled(bool enabled) {
|
||||
LoadSettingsIfNeeded();
|
||||
if (g_enabled == enabled)
|
||||
return;
|
||||
g_enabled = enabled;
|
||||
SaveSettings();
|
||||
if (g_enabled)
|
||||
LoadCacheIfNeeded();
|
||||
else if (g_dirty)
|
||||
SaveCache();
|
||||
}
|
||||
|
||||
} // namespace Player::NameCache
|
||||
@@ -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 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>
|
||||
#include <string>
|
||||
|
||||
// Opt-in persistent name cache, keyed by GUID. When enabled, every
|
||||
// SMSG_NAME_QUERY_RESPONSE the engine processes — plus anything fed
|
||||
// in via `C_PlayerInfo.RememberPlayer` from Lua — is persisted to
|
||||
// `WTF\Account\<acct>\<realm>\ClassicAPI_NameCache.txt` and survives
|
||||
// across sessions on the same realm. Shared across all characters
|
||||
// on that account+realm, so a 50-character bank alt's cache is
|
||||
// available to the player's main without duplication.
|
||||
//
|
||||
// Use case: addons like pfUI's libunitscan currently keep their own
|
||||
// per-character SVPC name DB to color chat names by class. With this
|
||||
// enabled, `GetPlayerInfoByGUID` falls back to the persistent cache
|
||||
// on engine miss, so chat coloring Just Works after a /reload — and
|
||||
// the data isn't duplicated 50 times.
|
||||
|
||||
namespace Player::NameCache {
|
||||
|
||||
struct Entry {
|
||||
uint64_t guid; // full 64-bit GUID (hi << 32 | lo)
|
||||
std::string name; // ASCII, <= 12 chars (vanilla cap)
|
||||
uint32_t classID; // ChrClasses.dbc record ID (1..9), 0 if unknown
|
||||
};
|
||||
|
||||
// Returns a pointer to the cached entry, or nullptr if not cached.
|
||||
// The pointer is stable until the next `Remember` for the same GUID
|
||||
// (which may relocate via map rehash). Treat as transient.
|
||||
const Entry *Lookup(uint64_t guid);
|
||||
|
||||
// Adds or updates an entry. classID==0 leaves the existing classID
|
||||
// alone (so a name-only sighting doesn't erase prior class data).
|
||||
// Marks the cache dirty for the next persistence flush.
|
||||
void Remember(uint64_t guid, const char *name, uint32_t classID);
|
||||
|
||||
// Opt-in toggle. State persists to `WTF\Account\<acct>\ClassicAPI.txt`.
|
||||
// Enabling triggers a load from disk; disabling stops further writes
|
||||
// but leaves the file in place (re-enabling restores prior state).
|
||||
bool IsEnabled();
|
||||
void SetEnabled(bool enabled);
|
||||
|
||||
} // namespace Player::NameCache
|
||||
Reference in New Issue
Block a user