mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 16:10:36 +00:00
f55893fdf47475af62e341b5ebc0b9f903ff12cc
538
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f55893fdf4 |
feat(frame): Button:Set/GetNormalFontObject and Frame:IsProtected (#93)
* feat(frame): Button:Set/GetNormalFontObject and Frame:IsProtected - button:SetNormalFontObject / GetNormalFontObject: 3.0's names for vanilla's SetTextFontObject / GetTextFontObject; delegate to them. Zygor Guides Viewer 2.0 and AceGUI-3.0 call the new names. - frame:IsProtected() returns false, false: vanilla has no protected frames (the secure system arrived in 2.0). AceHook-3.0 asks before hooking scripts. Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0): Zygor sets its guide window's tab fonts with SetNormalFontObject while it builds, without an error. Not yet checked: that the font set reads back through GetTextFontObject and the reverse, and IsProtected's two values; the testkit check for those runs at the next login. * docs(frame): drop version and implementation notes from the new methods The SetNormalFontObject and IsProtected sections named the patches the APIs came from, said what 1.12 lacks, and described how the methods are implemented. User docs describe the contract only. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
e0b2e56070 |
feat(frame): multiply frame alpha into child frames, as 3.x does (#70)
* feat(frame): multiply frame alpha into child frames, as 3.x does A frame now draws at its own alpha times its parent's drawn alpha, and GetAlpha returns the frame's own alpha. Vanilla keeps one alpha per frame and copies it into the children that exist when SetAlpha runs: - an XML frame with alpha="0" drew its child frames at full alpha, because the attribute is applied before its <Frames> are built; - a child's own alpha was overwritten whenever its parent's changed; - a frame created or reparented under a transparent frame drew opaque. Zygor Guides Viewer's border glow is the first case. It is an alpha="0.0" frame whose child holds the glow textures, so on vanilla the glow covered the guide frame from login until the first step flash. Co-hooks the engine's alpha setter, SetParent, the frame destructor and frame GetAlpha. Own alpha lives in a table keyed by frame. The engine's byte holds the drawn value, so region recolors and the Model family's model alpha read it unchanged. Children are recomputed through their own vtable setter, as the engine's copy-down calls it. Vanilla code that shows a child under a transparent parent (parent:SetAlpha(0); child:SetAlpha(1)) now leaves the child hidden, as 3.x does. Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0): Zygor's guide frame no longer shows its border glow from login. With own alphas 0.5 / 0.8 / 1.0, a child and a grandchild draw at 0.4; the child of an XML frame with alpha="0" keeps its own 1.0 and draws at 0; a child keeps its own 0.5 while its parent goes to 0.2 and back to 1; a frame with its own 0.6 draws at 0.3 under a 0.5 parent and at 0.18 once moved under a 0.3 one. * fix(frame): match 3.3.5's effective-alpha math and read it from the byte - Multiply child alpha by truncating (a*b/255), as 3.3.5's CSimpleFrame::UpdateAlpha and GetEffectiveAlpha do, instead of rounding. - GetEffectiveAlpha reads the frame's alpha byte, which Frame::Alpha keeps at the drawn value, instead of multiplying GetAlpha up the parent chain. This is 3.3.5's Script_GetEffectiveAlpha. Drops the now-unused FUN_SCRIPT_REGION_GETPARENT. - Drop the reload cleanup of the own-alpha table. The frame destructor hook already removes each frame's entry, and a frame that outlives a /reload would have lost its own alpha. - Rewrite the API.md frame-alpha and GetEffectiveAlpha sections as user-facing behavior. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
20dc9fc962 |
fix(frame): move a frame's children along when SetParent sets its level (#61)
* fix(frame): move a frame's children along when SetParent sets its level Vanilla's SetParent gives the frame its new parent's strata and level + 1, but calls the level setter without its children flag, so the frames under it keep the levels they had. A panel built on its own and then moved into a raised window draws its contents behind that window: Zygor Guides Viewer 2.0's AceConfigDialog-3.0 panel in the Interface Options window had its widgets at levels 1-4 under a window at level 5. Hook the level setter (0x0076A4F0) and pass the children flag on SetParent's two calls, recognized by their return addresses. The setter then moves each same-strata child by the same amount, recursively. Script SetFrameLevel and the setter's other callers are unchanged. Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0): the AceConfigDialog-3.0 panel's widgets draw above the Interface Options window, and none of its 18 frames sit below the window's container any more. A frame with a child and a grandchild moved under a level-20 frame sits at 21/22/23, and at 0/1/2 once moved to no parent. * refactor(frame): patch SetParent's children flag instead of hooking the setter The two `push 0` that pass the level setter's children flag from SetParent become `push 1`, which is what 3.3.5's SetParent passes. This drops the MinHook on the level setter, which 11 call sites share, and the return-address checks. Each site's bytes are checked before the write, as in Quest::CompleteMessage. Docs: describe only the current behavior in API.md and the README row. Verified in-game: a frame with a child and a grandchild moved under a level-20 frame sits at 21/22/23, and at 0/1/2 once moved to no parent. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
51d226f67d |
feat(tooltip): SetHyperlink takes full links and spell:/quest: links (#68)
* feat(tooltip): SetHyperlink takes full links and spell:/quest: links
Vanilla's GameTooltip:SetHyperlink matches only a bare `item:` or
`enchant:` payload and raises "Unknown link type" for anything else,
including the full |cff..|H..|h[..]|h|r links 2.0+ GetItemInfo and chat
hand out. Co-hook it:
- a full link is reduced to the payload between |H and |h;
- spell:<id> builds the SetSpellByID tooltip;
- quest:<id> shows the cached title and objectives text (tokens
expanded by the engine's quest-text substituter); an uncached quest
leaves the tooltip empty and queues the quest query once;
- everything else runs the engine function on the payload.
Quest::Cache::Lookup gains `unique`, the engine's own dedup flag (the
last _GetRecord argument, previously passed as an unused 0), so a
tooltip redrawn every frame waits on one queued callback.
Zygor Guides Viewer reads quest titles with
SetHyperlink("|Hquest:<id>:1|h[q]|h") and item names with full links.
Verified in-game (1.12.1 client via VanillaFixes): on a
GameTooltipTemplate tooltip, a full Hearthstone link shows Hearthstone's
tooltip, "spell:133" shows Fireball's, and "quest:957" shows Bashal'Aran's
title and objectives.
* refactor(tooltip): share the C tooltip line helpers; tidy SetHyperlink
- Add tooltip/Lines.h (Clear / Add / Show over the engine's tooltip clear,
raw add-line and Script_Show) and use it in place of the four local
copies in Hyperlink, CompareItem, totem/Tracker and equipmentset/Tooltip.
EquipmentSet keeps its exact colors as packed constants.
- SetHyperlink quest colors come from UI::ColorData (HIGHLIGHT_FONT_COLOR,
NORMAL_FONT_COLOR) instead of hand-packed doubles.
- spell:<bad id> now clears the tooltip, like quest:<bad id>, instead of
leaving the previous tooltip's lines.
- Rewrite the SetHyperlink API.md section in plain English without version
or vanilla-gap notes.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
eb3c32094c |
feat(pvp): add IsActiveBattlefieldArena (#77)
* feat(pvp): add IsActiveBattlefieldArena Stock 1.12 has no arenas, so it answers nil there. Turtle-lineage clients add arena matches, run in instances IsInInstance reports as "pvp": in a "pvp" instance their scoreboard asks for arena scores over the hidden TW_ARENA channel, only an arena answers, and the scoreboard keeps the reply in WorldStateScoreFrame.arenaData until the world states update outside an instance. isArena follows that state, as the scoreboard's own arena view does (Octo's FrameXML, patch-4.mpq: WorldStateFrame.lua and Turtle_ArenaUI.lua). isRegistered is always nil: the reply has no rated flag, and the client's queue window only joins skirmishes. Zygor Guides Viewer 2.0 calls it, unguarded, to decide whether to set its corpse arrow when the player is dead outside a battleground. Verified in-game (OctoWoW 1.12.1 client via VanillaFixes): outside an instance it returns nil, nil. The arena branch has not been exercised in a match yet. * refactor(pvp): answer IsActiveBattlefieldArena from DBC data in C The Lua version read Turtle's scoreboard state (WorldStateScoreFrame.arenaData), which is nil until the server's TW_ARENA reply lands and depends on Turtle's FrameXML. The client's own data already marks an arena: a pvp-type map (Map.dbc instanceType 3) whose area carries AreaTable flag 0x80, the flag Script_GetZonePVPInfo reports as isArena. Check the zone as well as the subzone, since the arena maps' areas are top-level zones. The type-3 gate keeps the open-world rings (Gurubashi, The Maul) out. Returns booleans, as retail does; isRegistered is always false. Offsets.h: add OFF_AREATABLE_FLAGS, AREA_FLAG_ARENA and VAR_PLAYER_SUBZONE_AREA_ID, and correct the zone-change handler's second argument (the subzone ID, not the parent area ID). * docs(pvp): note the server only ever creates arena map 26 tortoise-wow's GetBattleGrounMapIdByTypeId sends its one arena type, BATTLEGROUND_BR, to map 26 (Blood Ring); map 28 (Lordaeron Arena) is client data only. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
26ca1b4e84 |
feat(quest): print "<quest> completed." for chain quests too (#76)
* feat(quest): print "<quest> completed." for chain quests too The client prints ERR_QUEST_COMPLETE_S on SMSG_QUESTGIVER_QUEST_COMPLETE only for a quest with no next quest in its chain. The handler (and the callback it leaves for a quest not yet cached) skips the message when the cached record's NextQuestInChain (+0x24) is set, so a turn-in in the middle of a chain printed only the experience and money lines. Zygor Guides Viewer 2.0 completes a turn-in step only on that line, so its steps for chain quests stayed open until the next login. NOP the two `jne` over the message (0x005DC4DC, 0x005DC756), after checking the bytes, so every turn-in goes through the engine's own message path: same text, sound and CHAT_MSG_SYSTEM chat type, ahead of the experience and money lines. That later clients print the line for every turn-in is an inference, not read from a later client's binary: the 3.3.5a build of Zygor Guides Viewer completes chain turn-ins on this line the same way. Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0): mid-chain turn-ins (The Harvest Golem Mystery 40470, The Red Crystal 4811, As Water Cascades 4812, Bashal'Aran 956, Buzzbox 323 1002) print "<quest> completed." and Zygor completes the turn-in step at once; a quest at the end of its chain prints it as before. * docs(quest): the completed line's order depends on the quest cache When the quest record is not cached at turn-in, the callback 0x005DC710 prints the line on the record's arrival: after the experience and money lines, and after QUEST_TURNED_IN. Stop promising a fixed order. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
27d8f90f03 |
fix(unit): UnitFactionGroup("player") answers while addons load (#79)
* fix(unit): UnitFactionGroup("player") answers while addons load
Script_UnitFactionGroup resolves "player" through the in-world unit
descriptor, so it returns nil at file scope, ADDON_LOADED and
VARIABLES_LOADED and only answers from PLAYER_LOGIN. UnitName, UnitRace
and UnitClass already answer then, and later clients answer
UnitFactionGroup too, so ported addons read it at file scope. AceDB-3.0
does exactly that to build its "<faction> - <realm>" profile key, and
fails to load on nil ("attempt to concatenate local 'factionKey'").
Co-hook the engine function: when it answers nothing for the "player"
token, fall back to the login-time race byte (VAR_PLAYER_RACE_BYTE) and
the same race -> faction-group chain its player branch uses. That chain
moves out of C_CreatureInfo.GetFactionInfo into a shared
Creature::Info::FactionGroupForRace; GetFactionInfo's behavior is
unchanged. Once the player object exists the engine answers by itself.
Adds FUN_SCRIPT_UNIT_FACTION_GROUP (slot 13 of table 0x00850438).
Measured in-game before the fix (Octo 1.18.1 client, Human):
UnitFactionGroup("player") = nil at file load / ADDON_LOADED /
VARIABLES_LOADED, "Alliance" from PLAYER_LOGIN; UnitName/UnitRace
answer at every stage.
Verified in-game after the fix (same client and character):
UnitFactionGroup("player") is "Alliance" at file load, ADDON_LOADED and
VARIABLES_LOADED, and AceDB-3.0 sets up Zygor Guides Viewer 2.0's saved
settings.
* fix(unit): keep UnitFactionGroup's in-world nil; describe both engine branches
Script_UnitFactionGroup reads the live faction template when the unit's
object is in the world, and only falls back to the name cache's race when
it isn't. The race fallback now runs only under that same condition (no
player object), so an in-world nil (e.g. charmed by a monster) stays nil
instead of turning into the race's faction. Comments and API.md now say
which engine branch the fallback mirrors.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
35ef1228eb |
feat(lua): give each pass of a for loop its own loop variables, as in 5.1 (#66)
* feat(lua): give each pass of a for loop its own loop variables, as in 5.1 Lua 5.0 declares a for loop's variables once for the whole loop (its parser's forbody activates them before entering the loop block), so every function made in the body shares one variable, which is nil once a generic for ends. Lua 5.1 declares them per pass, and 5.1 code relies on it. Zygor Guides Viewer 2.0's recent-guides menu gives each entry `checked = function() return ... guide.full end`; on 1.12 it errored with "attempt to index a nil value" whenever the menu opened. A new transpile pass rewrites such a loop to the 5.1 manual's own equivalent, `for __cf_k, __cf_v in e do local k, v = __cf_k, __cf_v;`, on the same line. It applies only to loops whose body contains a function, and not when the body assigns to a loop variable (5.0 carries that into the next pass and 5.1 doesn't). Chunks whose blocks don't balance are left alone. The trigger scan follows blocks and brackets without allocating. Toggle: "ForLoopScopes". Tested offline on the rewriter's own code: 21 targeted cases, and 1,417 addon and Classic Era FrameXML files (67.7 MB). 184 loops were rewritten, and every rewritten file still compiles under Lua 5.1. The pass adds about 0.03-0.05 s over the whole 67.7 MB. Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0): the recent-guides menu opens without an error, and functions made in a generic for, a numeric for and a pair of nested loops each return their own pass's values. * refactor(lua): close loop upvalues per pass in the compiler instead of rewriting source Replace the token-scanning source rewrite with a hook on the parser's forbody. Lua 5.0's loop variables are the loop's control registers, and a function made in the body keeps them open until forstat's block ends. Emitting one OP_CLOSE at the end of each pass, before OP_FORLOOP / OP_TFORLOOP, gives each function its own pass's values. The OP_CLOSE is emitted only when a nested function names a loop variable. markupval already records that on forstat's block, so nothing is guessed from tokens. A loop that captures nothing compiles to the engine's exact bytecode. This fixes the gaps in the source rewrite (indexed and dotted targets, `function v()`, nested elseif, long target lists). It adds no locals, so it can't push a function past the 200-local limit, and it adds no scan to every chunk load. Assignment to a loop variable still steers the loop, as stock 5.0 code may rely on. The ForLoopScopes toggle is gone with the rewrite. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
76cc907bd0 |
feat(tooltip): add GameTooltip:AddTexture on the engine's own routine (#67)
* feat(tooltip): add GameTooltip:AddTexture on the engine's own routine
Vanilla has the 3.x tooltip-texture feature built in and unexposed:
GameTooltipTemplate declares <name>Texture1..3, the XML-OnLoad scan
binds them (tooltip+0x34C), FUN_005303D0 lays the next one out on the
last line (sized to the line, text shifted right) and the tooltip clear
undoes it. Nothing in the 1.12 binary calls that routine; expose it as
GameTooltip:AddTexture. The engine's limits stay: three textures per
tooltip, none on the header line. Zygor Guides Viewer adds guide
images to its tooltips this way.
Verified in-game (1.12.1 client via VanillaFixes): on a
GameTooltipTemplate tooltip with two lines,
AddTexture("Interface\\Icons\\INV_Misc_Bag_08") shows <name>Texture1
with that file, and ClearLines hides it again.
* fix(tooltip): repair AddTexture layout around the engine routine
The engine's texture routine was never called before, and its layout has
two defects. The tooltip clear re-anchors the line below a textured line
at (0, 0) instead of the template's 2px gap, so that line sat too close on
every later tooltip from the frame. And every re-anchor replaces the
line's offset, so a second texture on one line, or one on the line right
below a texture, broke the text alignment.
Tooltip::ClearItemGuid becomes Tooltip::Clear: the one clear co-hook now
also restores the gap below each textured line. AddTexture refuses a
texture on or right below a textured line, accepts only strings, and
returns whether it placed the texture. Correct the Offsets.h description
of the routine and keep the user doc to the contract.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
e9e431e014 |
feat(frame): add SetClampRectInsets / GetClampRectInsets (#69)
* feat(frame): add SetClampRectInsets / GetClampRectInsets Later clients let a frame that is clamped to the screen keep a different rect on screen than its own: SetClampRectInsets(left, right, top, bottom) grows or shrinks the rect the clamp uses. Zygor Guides Viewer 2.0 sets them on its frames while building them (a negative top inset lets a frame's top go off screen), and 3.3.5's own FrameXML uses them too. The engine clamps a frame to the screen inside its rect calculation (0x00767A20): it resolves the edges and, for a clamped frame, slides the rect onto the screen. Hook that calculation: for a frame with insets, take the unclamped rect, grow it by the insets (converted from the frame's units to layout units with the inverse of Script GetLeft's scaling), slide that onto the screen with the engine's own steps and order, and move the frame's rect by the same amount. Frames without insets go through the engine's clamp as before. SetClampRectInsets re-lays the frame out, as SetClampedToScreen does, and (0, 0, 0, 0) clears the insets. Sign convention from 3.3.5's own calls: WorldMapFrame (0, 0, 0, -60) "don't overlap the xp/rep bars", chat frames (-35, 35, 26, -50). Verified in-game (1.12.1 client via VanillaFixes): a clamped 100x100 frame placed 10 above the bottom of the screen stays at 10, moves to 60 with (0, 0, 0, -60) and back to 10 once cleared; a frame placed 20 over the top is clamped to the edge and, with a top inset of -25, keeps its 20 over. GetClampRectInsets returns the insets set. * refactor(frame): address review of SetClampRectInsets Use the existing OFF_REGION_ANCHOR and UI coordinate globals instead of new duplicate offsets, and move the pixel/anchor-unit conversion into one shared Game::PixelToInternal / InternalToPixel pair (replacing the copies in LinePool, Transform and Metrics). Restore only the clamp bit around the unclamped rect calculation so other layout flag bits survive. Add doc descriptors for both methods and drop version/implementation notes from the user docs. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
fbcc1c9ae1 |
feat(editbox): add SetCountInvisibleLetters / IsCountInvisibleLetters (#88)
* feat(xml): read parentKey, function= and button font style= from XML Later clients' XML has three attributes vanilla's parser keeps on the node but never reads. Ported UIs lean on all three: Zygor Guides Viewer 2.0 uses parentKey 69 times (its arrow, skin buttons and step frames), binds its main frame's whole OnLoad with function=, and names button fonts with style=. All three hook the engine's per-object XML node loaders. Those run on the object's layout sub-object ((object+0x24)->vtable[+8], called from the frame builder at 0x006EE4D9 and the region factory at 0x006F2756), so the object is `this - OFF_XML_LOADER_SUBOBJECT`. The loaders: frames FUN_00769820 (every derived frame type's loader calls it first), textures FUN_0076FE20, font strings FUN_00770F40, and Button's FUN_XML_BUTTON_LOAD (CheckButton's calls it first). Each hook runs the engine's loader, then: - parentKey="Name" sets parent[Name] = object on the Lua wrappers, the parent being the object's script-region parent (OFF_REGION_PARENT, which GetParent reads). An unnamed element has no wrapper yet, so it is registered the way the engine's own lazy path does (ScriptRegister(object, NULL), as GetParent does); a named one is never registered here, since SetName already did that under its name. The builder loads content and child frames before it finalizes, so a parent's <OnLoad> already sees its keys, and keys inside a virtual template bind on every frame built from it. - A script element with function="Name" becomes frame:SetScript(<element>, _G[Name]). The loader runs before the builder's finalize, so a bound OnLoad fires at the usual point. - A NormalFont / HighlightFont / DisabledFont with style and no inherits is applied through the engine's own setter for that state with _G[style]. Vanilla reads only inherits there and otherwise leaves the button's embedded font empty, so its text had no font. Adds FUN_XML_FRAME_LOAD / FUN_XML_TEXTURE_LOAD / FUN_XML_FONTSTRING_LOAD / FUN_XML_BUTTON_LOAD, OFF_XML_LOADER_SUBOBJECT and OFF_SCRIPT_REGION_NAME, with their derivations. Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0): probe XML gets its parent keys on a Frame, a Texture, a FontString, a button's NormalTexture and a frame inside an inherited template; an <OnShow function="..."/> handler runs; a button with <NormalFont style="GameFontHighlightSmall"/> reports that font object. Zygor's frames build with their keys, its main frame's OnLoad runs, and it loads without a Lua error. * feat(editbox): add SetCountInvisibleLetters / IsCountInvisibleLetters 3.3.5's EditBox can count color codes and hyperlink markup toward its SetMaxLetters limit: SetCountInvisibleLetters(true), or countInvisibleLetters="true" in XML (its macro text, friends broadcast and BNet report boxes). Off is the default. AceGUI-3.0's MultiLineEditBox calls the setter while building. 1.12's SetMaxLetters limit (+0x340) counts only visible letters: its counter (0x0077BC80) skips the markup classes in the edit box's per-byte table (+0x330), so with a limit of 5 "|cffff0000abcdefg|r" keeps "|cffff0000abcde" (checked in-game). That is 3.x's default (off). With the flag on, the limit check's three counts (returns 0x0077C09F, 0x0077C0C1, 0x0077C0E9) count each markup token at its length instead. The counter's other callers, the cursor movement and GetUTF8CursorPosition, are unchanged. For XML, hook the EditBox node loader (0x00779FB0, identified by the "letters"/"autoFocus"/"multiLine" attributes it reads after calling the frame loader) and, after it runs, read the attribute and parse it with the engine's own boolean parser (0x006F1B30, as for autoFocus). The loader follows the node-loader convention of the XML attributes change (OFF_XML_LOADER_SUBOBJECT), which this builds on. Verified in-game (1.12.1 client via VanillaFixes): with SetMaxLetters(12), "|cffff0000abcdefg|r" is kept whole with the flag off and cut to "|cffff0000ab" with it on; an XML EditBox with letters="12" and countInvisibleLetters="true" reports the flag on and cuts the text the same way. * docs: correct GetNumLetters note, drop version comparisons GetNumLetters counts the letters you see (FUN_007992C0 calls the same counter as the limit check), not bytes. Remove the 3.3.5 / stock 1.12 / later-client comparisons from the new XML and edit box sections. * fix(frame): build extra templates' child frames in CreateFrame The multi-template graft called the main vtable's +8 slot, which is the Lua method lookup FUN_00778590, not a node applier, passing the XML node as the Lua state. Its second call (the +0x24 sub-object's node loader) applied the template's content, but <Frames> children are built only by FUN_0076A060 from the finalize step, so an extra template's child frames were never created. Call the node loader, then FUN_XML_FRAME_LOAD_CHILD_FRAMES directly, so OnLoad is not re-run. Correct the notes in Offsets.h and CreateFrame.cpp. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
142faafb13 |
feat(frame): add SetHyperlinksEnabled / GetHyperlinksEnabled (#92)
* feat(frame): add SetHyperlinksEnabled / GetHyperlinksEnabled 3.3.5 has SetHyperlinksEnabled/GetHyperlinksEnabled on ScrollingMessageFrame and SimpleHTML only, so register them on those two types' method tables (0x00CF5294, 0x00CF5328), and hook the three functions both types fire OnHyperlinkEnter/Leave/Click through (0x007A3780, 0x007A37B0, 0x007A37E0) to skip the script while a frame's hyperlinks are off. On stays the default, which is vanilla's behavior. Zygor Guides Viewer 2.0 turns hyperlinks off on the step lines it fills with Gold Guide item lists, and back on when they show guide steps. Verified in-game (1.12.1 client via VanillaFixes): both types report true by default, false after SetHyperlinksEnabled(false) and true again after SetHyperlinksEnabled(true), and a plain Frame has neither method, as in 3.3.5. Not yet checked: the skipped script itself (a click on a link with hyperlinks off), which needs the mouse; that check runs next session. * refactor(frame): gate hyperlink scripts via RunnerHook, keep Leave Replace the three MinHooks on the per-type hyperlink fire functions with a Frame::RunnerHook subscriber keyed on the script slot (+0x320 Enter, +0x330 Click). OnHyperlinkLeave is never suppressed, so a tooltip shown before hyperlinks were disabled still closes. Parse the argument with the engine's loose boolean (default on), as 3.3.5's setter does. --------- Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com> |
||
|
|
917b15640e |
feat(quest): add C_QuestLog.GetInfo and C_QuestLog.GetQuestLogTitle
Both run the engine's Script_GetQuestLogTitle (0x004DF930) and repackage its returns, so title, level, header, collapse and complete/failed state match the stock GetQuestLogTitle. Also registers Enum.QuestFrequency and Enum.QuestClassification. Corrects the Quest::Cache note on +0x14..+0x24: those slots are RepObjectiveFaction, RepObjectiveValue, the two opposite-rep fields and NextQuestInChain, not SuggestedPlayers and friends. The 1.12 wire carries no suggested group size, so suggestedGroup is always 0. |
||
|
|
85619155f8 |
feat(equipmentset): add C_EquipmentSet.PickupEquipmentSet
Equipment sets become action-bar buttons, as in 3.3.5: action type 0x20000000 | setID and cursor type 13. The set can be picked up, placed, dragged off, and swapped with other actions. The button shows the set icon, name and tooltip, and grays out while a set item is locked. A click fires WEAR_EQUIPMENT_SET(setID) and the embedded EquipmentManager equips the set. The server drops action type 0x20 without saving it, so placements are kept in the per-character equipment-set file. The server is sent an empty slot, and the saved buttons are merged into the SMSG_ACTION_BUTTONS buffer at login. GetActionInfo and GetCursorInfo report "equipmentset", name. |
||
|
|
46dc198505 |
feat(tooltip): add GameTooltip:GetUnit
GetUnit() returns (name, unitToken). The engine drops the token after
SetUnit resolves it to a GUID, so it is kept where it enters:
- SetUnit is re-registered in front of the engine method and stages
the token; it binds in the unit-builder co-hook that SetEvents
already owns, before OnTooltipSetUnit fires.
- A build with no staged token is the world mouseover ("mouseover");
the in-place refresh keeps the bound token.
- Unit-frame hover (Frame::Attributes) stages the frame's unit, since
the engine resolves "mouseover" only for a live object and an
offline or far group member has none.
The name follows Script_UnitName's order (live object, group roster
slot, name cache), so offline members resolve for GetUnit and
GetUnitGUID alike.
|
||
|
|
7707127d5f |
fix(macro): add the question-mark icon to the macro icon list
The stock 1.12 macro icon list holds only Ability_* and Spell_* icons, so on a client without Turtle or pfUI the macro picker cannot select INV_Misc_QuestionMark, and #showtooltip never gets a macro to take over. Mirror 3.3.5's loader: seed the icon through pass 3's own append before the walks, then move it to index 0 after the engine sorts and dedups. |
||
|
|
3467513df9 |
feat(container): group sorted gear by equip slot
Gear was one category per quality tier, ordered inside by class, subclass and name, so a helm could sit between two pairs of boots and an epic helm landed far from a green one. Gear is now one category, ordered by class, then equip slot, then subclass, then quality (best first), then name, so like pieces sit together. The slot key ranks Item.dbc inventoryType through a table rather than the raw INVTYPE number, which does not follow the character pane (robe is 20, chest 5; cloak 16). The order is Baganator's: weapons by hand, ranged and ammo, then armor with shields and off-hands first, head to feet, then jewelry, shirt and tabard. |
||
|
|
6000df8009 |
feat(cvar): add C_CVar.SetTempCVar and RemoveTempCVar
SetTempCVar changes a cvar for the session without saving it to Config.wtf; RemoveTempCVar restores the value from before the first temp set. The temp set passes a6 = 0 to the engine setter, the only argument that marks the config dirty, so it applies the value and runs the change callback without asking for a save. When something else dirties the config, a co-hook on the config writer (0x0063D980) points each temp cvar's value at its saved string for the write and restores it after. A plain SetCVar over a temp value wins: the entry drops itself, so the user's set is saved and never rolled back. Errors mirror Script_SetCVar. Registered in-game and on glue. |
||
|
|
fde3beca9d |
fix(table): keep the stored length on weak-valued tables
The getn heal read a nil at the stored last slot as proof that nobody maintained the length. For a weak-VALUED table that is false: the collector clears those slots behind the writer, so `luaL_setn` is still exactly what the last append left and the holes below it come and go between two reads. Compost-2.0 is the casualty. `secondarycache` is `__mode = "v"`, filled with `table.insert`; `GetTable` walks it with `pairs` and calls `table.remove(cache, i)` on a live index. Once the GC clears slot 1 and the stored last slot, the heal bisects to border 0, `luaB_tremove` takes its `e == 0` empty-table early-out and returns NOTHING, and the next line indexes with the nil it got back -- "table index is nil" at Compost-2.0.lua:81, once per recycled table, in every addon that pulls Compost in through AceLibrary. The border search is what exposed it (5aa382b's table.insert switch is not involved -- Compost never appends a nil, so no mark ever applied to its tables). The walk-down it replaced returned the HIGHEST populated slot, which is always at or above the live index the pairs loop holds, so remove still found something; a bisect returns some border and probes its way down to 0 through the collected slots. That tradeoff was known and written down -- a weak cache read through table.remove is where it bites. So gate the heal: `__mode` mentioning "v" returns the stored length untouched, as rule 3, ahead of the mark. It costs one getmetatable and a raw `__mode` fetch on the already-rare unhealthy path, so the bisect keeps its win everywhere else, and the mode is read raw -- the same fetch the collector's own check uses. New plumbing: Game::Lua::GetMetatable, from the offset already catalogued in LuaCAPI.md. LuaEnv::Fenv had rolled its own copy; it now shares this one. Verified in game: a three-slot weak table with slots 1 and 3 collected reports getn 3 and hands back its live slot (0 and nothing before), and the Compost errors are gone. |
||
|
|
bbefdb847d |
fix(aura): include the player's pet in the PLAYER filter
Blizzard defines the token as "Include only auras that were cast by the
player, or by the player's pet or vehicle"
(AuraUtil.AuraFilters.Player). There are no vehicles here, so the caster
set is player + pet -- but all three comparisons tested
`casterGuid == PlayerGuid()` and nothing else.
A pet's cast carries the PET's guid in the Aura::Source cache, since
that is who SMSG_SPELL_GO names, so "HARMFUL|PLAYER" silently dropped
every aura the pet applied. `!PLAYER` had the mirror bug: it returned
the pet's auras as though a third party cast them.
Centralize on one IsPlayerOrPetCaster predicate rather than fixing each
site -- IsPlayerCast, GroupIsPlayerCast and CachedMatches had already
grown three separate copies of the comparison, which is how they would
drift again. The pet guid comes from VAR_PET_GUID, a live engine global,
so the predicate stays two compares with no object resolve; it runs per
aura slot. A caster of 0 (cache miss) still matches nothing.
Unrelated and untouched: the `isFromPlayerOrPlayerPet` aura field, which
means "applied by ANY player or a player's pet" and is answered from the
caster's HIGHGUID prefix.
Verified in-game: a Hunter pet's Scorpid Poison now returns from
C_UnitAuras.GetAuraDataByIndex("target", 1, "HARMFUL|PLAYER").
|
||
|
|
0296e0e5a4 |
feat(player): add WEAPON_SLOT_CHANGED
Fires with no payload when the item in inventory slot 16, 17 or 18 changes -- equip, unequip and swap alike. The narrow sibling of PLAYER_EQUIPMENT_CHANGED that swing-timer consumers want, so they no longer filter three slots out of a 19-slot event in Lua on every gear change. Blizzard's own Blizzard_SwingTimer registers this event. Rides the descriptor-field observers Player::Equipment already installs for PLAYER_EQUIPMENT_CHANGED -- the weapon slots are three of the 19 -- so there is no new hook, no second registration and no polling. The dispatcher invokes the callback only when a slot's item GUID actually changed, and seeds each node's mirror from live at registration, so login and /reload produce no fire. Coalesced to at most one fire per frame via a dirty flag drained on WorldTick: one action can change two weapon slots (a two-hander replacing a one-hander plus an off-hand) and the per-slot observer would otherwise fire twice for it. The drain checks the reservation slot before clearing the flag, so a change marked while the reservation is still unclaimed is held rather than swallowed. Slot 18 is exempted for the classes whose slot 18 is a relic slot -- a Libram/Idol/Totem is a passive stat item, not something you swing. Gated on the same data Script_UnitHasRelicSlot (0x00519E50) reads rather than a hardcoded class list: ChrClasses.dbc[class] + 0x40, verified in the disassembly at 0x00519EAE-0x00519EC0 and against the client's own ChrClasses.dbc, where that column is 1 for PALADIN/SHAMAN/DRUID and 0 for the other six. Read live, since the class-byte global is repopulated per character-enter. Not verified in-game yet: built and deployed only. |
||
|
|
4d835aa674 |
feat(combat): add PLAYER_SWING / PLAYER_SWING_RANGE_UPDATE / C_SwingTimer
Backports the Forever beta swing-timer API. PLAYER_SWING and PLAYER_SWING_RANGE_UPDATE fire off the packets the engine already sends for melee/ranged auto-attacks, mirrored as state (parry haste, extra attacks, on-next-swing abilities, cast-time resets) rather than relayed 1:1, so N packets for one logical reset collapse into one event. Two bugs surfaced only by in-game testing, not by reading the disassembly: - FUN_UNIT_CAN_ATTACK (0x00606980) is __thiscall with the second unit pushed on the stack, not __fastcall(ecx,edx) -- Ghidra's decompile of the one caller renders it as a plain two-arg call either way, so the wrong convention crashed on a bogus ecx read off [ebp+8] garbage. Same trap as FUN_SET_CVAR_VALUE. - The generic engine range core (FUN_006e3480, what C_Spell.IsSpellInRange already uses) computes full 3D distance, but the server's actual melee-attack gate (Unit::CanReachWithMeleeAutoAttackAtPosition, WorldObject::CanReachWithMeleeSpellAttack) is explicitly 2D -- verified by landing hits at 5.08yd 3D distance that the 3D check rejected. Melee now gets its own 2D check (Combat::Swing::InMeleeRange), reading the same live engine reach constants; ranged keeps the 3D core, which matches the server's own (also 3D) generic spell-range gate. Also: attack-start no longer resets the off-hand timer unless the target is actually in range. Unit::Attack's off-hand reset fires the instant an attack is declared, even out of range, and the server just silently re-arms it every 100ms until you're close enough -- firing PLAYER_SWING there promised a swing time that was not real. Slam is special-cased for Turtle: every rank in Turtle's own client Spell.dbc carries AttributesEx2's swing-reset exemption, but packet timestamps show Turtle's server does not honor it for Slam -- both melee timers delay after casting it, contradicting both the client data and the public tortoise-wow reference source. Combat::Swing::AutoSwingResetOverride is a small extension point (mirroring Turtle::ComboDuration's Rip override) for this kind of server/client divergence; src/turtle/SwingReset.cpp registers the known Slam ranks. Verified in-game: swing detection (dual-wield, extra attacks coalescing to one event, cast-time resets), the melee range fix, and the attack-start range gate. The Slam override has not been rebuilt/retested yet. |
||
|
|
dfbba225d2 |
fix(macro): correct the loose/mpq split in the icon enumeration
The three macro-icon scan callbacks were named and tagged for the wrong walker. FUN_LOAD_MACRO_ICONS hands 0x004F0220 to FUN_MPQ_ENUM_FILES (the archive listfile walk) and 0x004F0350 / 0x004F04F0 to the disk walker, but Icons.cpp had it exactly inverted: the archive pass was tagged SRC_LOOSE and both disk passes SRC_MPQ. So GetMacroIcons / GetMacroItemIcons returned the loose on-disk icons -- nothing at all on a stock install -- while GetLooseMacroIcons / GetLooseMacroItemIcons returned the archive set. It went unnoticed because the only consumer, IconDataProviderMixin, calls all four and concatenates, so only the ordering within each list changed and never the content. Tags corrected, and the offsets renamed to what the loader actually hands them to, with each one's filter recorded since that is the load-bearing difference between the two disk passes: FUN_MACRO_ICON_CB_DISK -> FUN_MACRO_ICON_CB_MPQ FUN_MACRO_ICON_CB_USER_MPQ -> FUN_MACRO_ICON_CB_DISK_PREFIXED FUN_MACRO_ICON_CB_INSTALL_MPQ -> FUN_MACRO_ICON_CB_DISK_ANY Also replaces a wrong guess in the Offsets.h block. It claimed a filter inside the SStrDup/array-append helpers downstream of all three callbacks was what kept INV_* out of the engine's own list. Decompiling the loader and all three callbacks shows there is no shared downstream helper at all: the grow-and-append code is inlined identically into each callback, so the only filtering is what each one does itself. The list is Ability_*/Spell_* only because passes 1-2 prefix-filter and pass 3 -- the one that does not -- is a disk walk over a folder that ships empty. A loose INV_*.blp dropped into Interface\Icons\ does enter the list, through pass 3 alone. The block now also records the qsort + adjacent SStrCmpI dedup, that GetMacroIconInfo pushes the empty string rather than nil for a bad index, and that only GetNumMacroIcons triggers the lazy build. Verified in-game. |
||
|
|
930b0c6492 |
Add C_LossOfControl.GetSchoolLockout
Serving the school-interrupt lockout through the generic list costs a caller two full BuildList passes -- GetActiveLossOfControlDataCount runs one and GetActiveLossOfControlData runs another -- plus a Lua table per entry, and BuildList classifies up to 16 debuff slots with RecordForID on each. All of that aura work is waste for a caller that only wants the lockout, and a macro conditional reading it every frame pays it every frame. The state behind it is g_schoolLock, seven pairs of ticks. Read it directly: no table, no debuff scan, one pass. Return a mask rather than a school. Each SMSG_SPELL_COOLDOWN batch locks one school, so being kicked on fire and then frost leaves two entries active, and a caller walking the list and stopping at the first SCHOOL_INTERRUPT drops the rest. filterMask narrows the scan, which is how a caller gets one school's own remaining time instead of the aggregate. Also document that the ADDED/UPDATE events diff which effects are active, so re-locking an already-locked school extends endMs without firing either one -- that expiry cannot be cached on the events. |
||
|
|
a33146241e |
feat(macro): make [button:N] read the click it is running inside
The condition existed but was a stub: it matched only "1" / "leftbutton" and always passed, because nothing on this client could say which mouse button had driven the current click. GetMouseButtonClicked can now answer that, so the condition asks it. Numbers use the modern API order -- 1 left, 2 RIGHT, 3 middle, 4, 5 -- which is deliberately NOT the order of the engine's internal click bitmask (where 2 is the middle button); that mask never reaches Lua. A name is matched as written, so [button:rightbutton] and [button:2] are the same test, case-insensitively. Outside a click the answer stays "left button". That is not a cosmetic default: Macro::ShowTooltip re-evaluates conditional directives off the world tick with no click in progress, so a nil-means-no-match rule would change which icon a `/cast [button:2] X; Y` macro displays at rest. The engine's own no-argument Button:Click() means the left button, so it is also the honest resting answer for a state-driver poll. Verified in-game with all five buttons, both directly from OnClick and through a real macro body -- click -> attribute macro -> EXECUTE_CHAT_LINE -> SlashCmdList -> SecureCmdOptionParse, which confirms the click context survives the whole chain -- plus the name form, the btn alias, and the no-click resting answer. |
||
|
|
c7af8d396e |
feat(frame): accept AnyUp / AnyDown in Button:RegisterForClicks
The engine's RegisterForClicks (0x00782490) SStrCmpI's each argument against exactly ten literals -- LeftButtonDown 0x1 / LeftButtonUp 0x100, Middle 0x2 / 0x200, Right 0x4 / 0x400, Button4 0x8 / 0x800, Button5 0x10 / 0x1000 -- treats anything else as contributing nothing, and ASSIGNS the OR to the click mask. So the collective names later clients take, "AnyUp" and "AnyDown", did not fall back to the default here: they zeroed the mask and the button silently stopped answering every real click, while Button:Click (which ignores the mask) kept working and hid it. That is what broke the first click-bracket harness yesterday. Frame::ClickMask re-registers RegisterForClicks on the Button method registry (0x00CF4E14, new VAR_BUTTON_METHOD_REGISTRY; most recent registration wins, CheckButton inherits through the type walk). It does not reimplement the parser: for each AnyUp / AnyDown argument it appends the five names that collective stands for onto the Lua stack and tail-calls the engine's own function, which then does the self typecheck, the parse, the setter and any error text itself. The collective string is left in place -- the engine's unknown-name -> 0 rule already makes it inert -- so the reshape is purely additive and the engine's loop terminates exactly as before. Verified in-game with left, middle and right: AnyUp fires OnClick on release; AnyDown on press; "anyup" + "LeftButtonDown" (case check) fires left on both press and release and the others on release only; a LeftButtonUp control is unchanged; "Fnord" alone still yields no clicks. |
||
|
|
a2a2ccb804 |
feat(frame): bracket the click at the engine's click vmethod
PreClick/PostClick now fire on every click, with or without an OnClick
handler, and GetMouseButtonClicked is live inside OnMouseDown and
OnMouseUp on any frame -- the two things 3.3.5 does that the previous
runner-only bracket could not.
3.3.5 (CSimpleButton::Click FUN_0096fd70 -> FUN_0096f090) fires PreClick,
OnClick and PostClick as three independent `if (slot)` blocks, so
Pre/Post never depended on OnClick. And the frame-manager field behind
GetMouseButtonClicked is written by exactly four dispatches -- that
click, the double-click, and CSimpleFrame::OnMouseDown FUN_0048fc30 /
OnMouseUp FUN_0048fce0 on every frame type -- not by OnDragStart.
Confirmed live on 3.3.5: `down LeftButton LeftButton`, `up LeftButton
LeftButton`, `drag LeftButton nil`.
|
||
|
|
7a4ab29cb0 |
fix(input): scope GetMouseButtonClicked to the click dispatch
It read a button captured from the WH_GETMESSAGE mouse-message hook and evicted two world ticks later, so it reported a button for as long as one was held, and for a couple of frames after every click -- useless as the "am I inside a click handler" test it exists to be. 3.3.5 does none of that. The getter (FUN_0050f950) pushes a frame-manager field that only the four click dispatches ever write -- button OnClick FUN_0048fc30, OnDoubleClick FUN_0048fce0, and the two secure click paths FUN_0096fd70/FUN_0096fdd0 that wrap PreClick -> OnClick -> PostClick -- each saving the old value on the C stack, setting its own button argument, running the handler, then restoring. That C-stack save is what makes a nested click shadow the outer one and restore on unwind. 1.12 has no such field but the same bracket point: FUN_00779540 (OnClick) and FUN_00779650 (OnDoubleClick) fire their handler through the runner Frame::ClickEvents already intercepts, passing the button name as the fire's only "%s" argument. Mirror the engine's bracket there and read the name out of the fire, which also inherits the engine's own naming: Button:Click (FUN_007826C0) folds its optional string down to a numeric mask, so a bare Click() arrives as "LeftButton" and an unrecognized name as "UNKNOWN". GetMouseButtonClicked moves to Frame::ClickEvents with the dispatch it describes. IsMouseButtonDown and GLOBAL_MOUSE_* keep the message hook, which is the right source for a device query. The recursion guard now covers only the PreClick/PostClick pair, so a nested click still gets its own button scope. It now returns nil in OnMouseDown / OnMouseUp / OnDragStart, matching 3.3.5, where those paths never touch the field. Verified in-game across all four dispatches: real and programmatic clicks, OnDoubleClick, PreClick/PostClick, the nested inner/outer restore, Click() argument folding, and an OnUpdate watcher that never saw a value outside a handler. |
||
|
|
a2d7d4e9e6 |
feat(classes): add C_ClassColor.GetClassColor
Returns a class's color as a ColorMixin, nil for anything that is not a class name. There is no engine source for the colors on this client: ChrClasses.dbc has 17 columns and none of them is a color, and the binary carries no class-color table (searched it for the class float triples and for the hex strings, no hits). RAID_CLASS_COLORS is what the client actually has -- FrameXML builds it in Fonts.xml, Util/Color*.lua gives it the mixin, and every UI colors classes from it -- so the function reads that table instead of carrying a second copy of the nine colors. Same call C_UnitAuras.GetAuraDispelTypeColor makes with the DEBUFF_TYPE_*_COLOR globals: one source of truth, one shared object per class, and a class another addon recolors stays recolored here. The lookup runs metamethods, so the pfUI shim in Util/AddOnCompat.lua keeps answering grey for unknown keys. Verified in-game: "WARRIOR" returns 0.78/0.61/0.43 with hex, colorStr and the mixin methods; an unknown name returns nil; the result is identical to GetClassColorObj for the same class. |
||
|
|
89c705b922 |
docs: describe the four macro commands added today
Covers /castsequence, /castrandom, /userandom and /stopmacro in the Lua reference, plus StopMacro beside GetMacroSpell, and updates the README groups and counts. Two caveats are worth having written down rather than found: a list names no single action, so the random commands give the action button nothing to show, and being static lines they end the #showtooltip collection -- a /castrandom above a /cast takes the icon from it. |
||
|
|
298eff528c |
fix(quest): fire QUEST_ACCEPTED from the engine's own accept gate
The client announces "Quest accepted" from a per-quest-slot descriptor observer, while the quest log is rebuilt from a separate one. Slot 0's announcer shares a descriptor anchor with the rebuild node and is registered first, so accepting into an empty quest log announced a quest no quest-log API could see yet. Rebuild the log at the top of the observer, as 3.3.5 does, and source QUEST_ACCEPTED / QUEST_REMOVED from the engine's own per-slot gates instead of a log diff. That drops the set-diff login heuristic, catches the re-announce when a quest goes complete to incomplete, and makes the message precede the event on every path. A cold quest cache rides the engine's own callback queue so the deferred announce still comes first. |
||
|
|
40abcabe9d |
fix(unit): read the creature id from the unit's live entry, not the GUID
UnitCreatureID and C_CreatureInfo.GetCreatureID extracted the template from
GUID bits 24-47. On the (v)mangos family that is the spawn row's FIRST
creature id: Creature::CreateFromProto builds the GUID from creature_id[0]
and applies the rolled template through UpdateEntry -> SetEntry only, and a
respawn re-rolls. Turtle's creature table has up to four ids per row (6,935
of 79,773 rows use more than one), so mobs with different names reported the
same id — every Gordunni ogre from a {5236, 5238, 5239} row read 5236.
New Unit::CreatureID reads the entry the engine keys the creature NAME query
on: the instance block at [[unit+0x08]+0x0C] (FUN_00604600's own read), with
the GUID bits only as the out-of-view fallback for creature GUIDs. The
descriptor's OBJECT_FIELD_ENTRY slot reads 0 for creatures on this client,
as it does for items, so it is documented as unusable. Pet GUIDs pack the pet
number, not a template, so Guid::CreatureEntry now returns 0 for them; pets
in view report their real template from the block.
Verified in-game on Turtle: Gordunni Shaman / Battlemaster / Mage-Lord read
5236 / 5238 / 5239 while all three carry 5236 in the GUID.
|
||
|
|
108a91a843 |
feat(api): describe the API in the code, browse it with /classicapi
docs/API.md is 18.7k lines and its anchors are signature slugs, so editing a signature breaks the 281 internal and 88 README links into it. Blizzard solved the same problem by shipping the API as data plus a browser addon, and warcraft.wiki.gg renders those same tables. One set of descriptors can feed all three. Each registration now carries one next to it: typed arguments and returns, nilability, defaults, and a sentence. Events, enumerations and returned table shapes are described the same way. No Script_* body changed. Game.h gains namespace Game::Doc (Field with Req/Opt/Vararg, FieldList, Function, Method, Structure, Event) and a trailing descriptor argument on all six Game::Lua::Register* plus Event::Custom::AutoReserve. api/Documentation.cpp records every registration on the first pass of each Lua state and seals it, so /reload re-registers but records nothing and the environment comes from which pass saw the name. Export is lazy: nothing is materialized until C_APIDocumentation.GetSystem asks for one system, because eager export would build thousands of tables per reload for a slash command. _classicapi_UndocumentedAPI lists what still has no descriptor. AddOns/!!!ClassicAPI/APIDocumentation/ ports Blizzard_APIDocumentation's eight files. Named /classicapi, not /api: the browser holds only what ClassicAPI adds, so /api would have implied the whole 1.12 surface. Two deliberate differences from the retail source, both noted in the file headers: a system search also matches its namespace, since that is the name people type; and an undocumented function says so, because an empty signature otherwise reads as a real one. LinkUtil gains the SetItemRef to LinkUtil.ProcessLink dispatch. That handler registry was dead code; a new link type now registers a handler instead of stacking another SetItemRef override. Also defines assertsafe there, which was undefined and only mattered once the function went live. Documented: the C_Spell and C_SpellBook surface, the spell globals, both spellbook enumerations, the 13 UNIT_SPELLCAST_* events, GameTooltip as the widget-method example and C_Glue as the glue and mixed-environment example. 66 of 692 function registrations. tools/New-ApiDocSkeletons.ps1 emits paste-ready skeletons to make the rest of the sweep tractable. Verified in game: the browser lists, searches, and prints detail; links render and click through; right-click copies and shift-click dumps. |
||
|
|
b4e5f4f2bb |
feat(spell): fill notInterruptible in UnitCastingInfo / UnitChannelInfo
Mirror the 3.3.5 client's own predicate on 1.12 data instead of pushing a placeholder false. The value is relative to the local player: the spellbook is folded into school masks of INTERRUPT_CAST spells and MOD_SILENCE spells (cached on Player::StatSignal), a cast is not interruptible when its PreventionType is not SILENCE or when the caster's immunity auras (effect / state / school / mechanic immunity) strip every mask, and the flag is never reported while the player knows no interrupt or silence at all. 1.12 differences, each documented in Spell::Interruptible: the vanilla server's interrupt effect also needs InterruptFlags 0x02 (channels: ChannelInterruptFlags 0x04), which silence ignores; SMSG_SPELL_START carries no immunity block, so creature_template interrupt immunity stays invisible; Feral Charge's interrupt lives on its triggered spell, so the capability walk follows one TRIGGER_SPELL hop. Verified in-game: a paladin's Holy Light reads false, flips to true while Divine Shield is up, and back to false when it drops. Also centralize SPELL_EFFECT_APPLY_AURA in Offsets.h (was local to Level.cpp). |
||
|
|
390eec4749 |
docs(nameplate): correct stale frame-identity and token-shift prose
The API.md nameplate prose contradicted the code in two places, and both were resolved in the code's favor after verifying it. Frame identity: the prose claimed default engine plates get a fresh wrapper table per call with unstable identity. UI::FrameObject::Push has one path for both plate kinds — a registry ref at +0x08 of <= 0 delegates to the engine's ScriptRegister, which builds the wrapper and writes the ref back, so every later call rawgeti's that same cached slot. Identity is stable for both kinds and addon-set fields survive. Dropped the registry/metatable mechanics that only existed to justify the wrong claim; kept the pooled-frame caveat, restated with its real reason. Token stability: the NAME_PLATE_UNIT_ADDED note said "nameplate3" can resolve elsewhere after a slot "vacates and shifts". AssignSlot never shifts an entry and removal frees the slot in place. Kept the advice to store the GUID, fixed the reason: slots are reused, never shifted. Also fixed the iteration example one code block above the slot rules, which broke at the first vacant slot and so missed every plate past a gap in the sparse slot array. |
||
|
|
f86893c8ef |
fix(spell): make IsUsableSpell the engine's own usability verdict
IsUsableSpell hand-rolled five checks (known, alive, off cooldown, power, reagents) and diverged from IsUsableAction exactly where the engine does more or less: it never tested stance, so Whirlwind in Battle Stance reported usable, and it tested cooldown first, so a 0-rage Whirlwind on cooldown reported (nil, nil) instead of (nil, 1). IsUsableAction reads a per-slot cache that FUN_004E5050 fills by calling FUN_SPELL_IS_USABLE (0x006E3D60) on a player spell's record, or by comparing the pet's power against the spell cost for a pet spell. Run those same two paths live, plus the knowledge gate the helper lacks. Cooldown is not part of usability: the helper has no cooldown branch and FrameXML greys and swipes as separate states. Item::Usable had been calling the helper all along. A pet-book spell given by ID now takes the pet path instead of always reporting not usable. Offsets.h: add VAR_PET_GUID and FUN_PET_ACTIONS_USABLE (verified via Script_HasPetUI, Script_GetPetActionsUsable and the recompute's pet branch); replace the FUN_SPELL_IS_USABLE comment with the decompiled check list. Fixes #51 |
||
|
|
b0585f5628 |
feat(sound): add C_Sound.PlayVocalErrorSound and Enum.Vocalerrorsounds
Plays the player character's spoken complaint for an error ("my bags are
full") in their race's and sex's voice.
This one maps exactly rather than approximately: VocalUISounds.dbc's
second column IS the modern Enum.Vocalerrorsounds value, and this build
carries every one of the 68 values (0..67) across 11 races. Verified by
resolving a row's sound ids to their SoundEntries names — row
{9, 0, 1, 1875, 1999, ...} is error 0 for race 1, whose normal sounds are
HumanMale_InventoryFull and HumanFemale_InventoryFull, which also pins
the column layout {id, enum, race, normal[male,female],
pissed[male,female]}.
The row lookup is ours because the engine has none: it loads the table
and never reads it, the only xrefs to its records/count globals being the
loader's own writes. Only the indexing is reimplemented — the same
records[id] walk every other DBC reader here performs — while the play
goes through the engine's by-id player like every other sound.
Race and sex come from the login-time bytes rather than the unit
descriptor, so this resolves from addon-load onward, before the in-world
player object exists.
The "pissed" column is deliberately unused: many of the ids it names
match no SoundEntries row. Combinations with no recording play nothing
and raise nothing, which is data rather than an error.
Verified in game on a Night Elf female: Inventoryfull, Outofammo and
Nomana each played, and GetRecentSoundFiles showed
Sound\Character\NightElf\NightElfFemaleErrorMessages\... — right race and
sex — with varying file suffixes, so the engine's weighted variant pick
is running too.
|
||
|
|
6013d8b937 |
feat(sound): add C_Sound.PlaySoundWithOptions and GetSoundScaledVolume
The table form of PlaySound, and the volume reader that falls out of it. Four of the params' six fields map onto something real here. volumeOverride is the one that needed finding. FUN_00458DA0(row, stream, scale) computes the row's own volume times `scale` and hands it to FUN_007A5DC0, which stores it on the stream and pushes it to FMOD. The by-id player already calls that with a scale of 1.0 immediately after starting a sound, and the setter writes rather than accumulates, so calling it again with another scale simply replaces the volume — no touching FMOD directly, and no reimplementing the row's volume rules. Resolving the row needs FUN_0045CDA0, since the applicator is a method on it. GetSoundScaledVolume then comes free: that same setter writes the result to stream + 0x74, so the field IS the scaled volume. Read only off a stream still in the engine's live list, because a finished stream's memory returns to a pool. soundKitID and runFinishCallback were already supported. uiSoundSubType, forceNoDuplicates and overridePriority are accepted and ignored, and the docs say so rather than implying they work. Params are read with GetTable rather than a raw read, so a table built from a mixin still resolves. Verified in game: volumeOverride 0.1 is audibly quiet against 1.0, runFinishCallback still fires SOUNDKIT_FINISHED through this path, and GetSoundScaledVolume returned 0.276 for a volumeOverride of 0.4 — the row's own 0.69 scaled, which is what confirms the multiplier semantics the docs describe. |
||
|
|
27277b11aa |
feat(sound): fire SOUNDKIT_FINISHED when an opted-in sound ends
Reports the handle of a finished sound, and only for sounds played with `runFinishCallback` — the documented contract, and what makes it affordable: without the opt-in every footstep and UI click would dispatch a Lua event. Detected on the world tick, NOT from FMOD's end callback. That callback (FUN_007A53C0) runs on the STREAMER thread — it opens with EnterCriticalSection and only moves the stream onto a deferred list — so firing an event there would call into the Lua VM off the main thread. The engine reclaims those streams in FUN_007A4B60, from the per-frame sound update that ends in FSOUND_Update, so noticing completion on the main thread is what the engine itself does. A tracked entry keeps the stream's path hash (+0x80, stamped at creation by FUN_007A51D0) beside the handle. Stream objects come from a pool and their addresses are reused, so "still in the live list" is not enough on its own — a later sound can land on the same address and the event would be deferred to the wrong one. Comparing the hash narrows that to the same file replaying at the same address, for one extra dword read of a node already found alive. C_Sound.PlaySound takes the remaining modern arguments: channel, forceNoDuplicates and runFinishCallback. forceNoDuplicates is accepted and ignored — the engine's by-path dedup is bit 0 of a flag word the row itself supplies, and the by-id player ORs in only bits 1, 2 and 4 from its arguments, so asking for it would mean bypassing that player and re-deriving its weighted file pick. The global PlaySound deliberately does NOT take those: it gains the SoundKitID form and nothing else, staying as close to the global it replaces as the extension allows. |
||
|
|
ccfdb8309c |
feat(sound): add C_Sound.PlayItemSound and Enum.ItemSoundType
Plays the noise an item makes when handled, without performing the action. Almost all of it is the engine's: FUN_00457FF0 takes a sound type and an ItemDisplayInfo id, walks that row's ItemGroupSounds id at +0x2C, and plays the SoundEntries id at row + 0x04 + soundType * 4. Those four columns are in the modern Enum.ItemSoundType order (Pickup, Drop, Use, Close), which makes this a backport rather than a reconstruction — the module only turns an item argument into a display id and calls it. The item argument takes an ItemLocation table and the other forms this project's item APIs accept (GUID string, itemID, link, carried item name), through the shared ResolveItemArgOrLocation. Sound type is read off the stack before resolving, since that resolver drives PackBagSlot and stomps the stack. Only Pickup and Drop play on a stock client, and that is the data rather than a limit of the code: of ItemGroupSounds' 24 rows, the 18 any display row points at (~29,000 displays) populate columns 1 and 2 only. The six rows naming a Use sound are unreachable or broken — groups 1 and 2 have no displays, and the ids they name (273/274/275) match no SoundEntries row — and the Close column is zero in all 24. Use and Close fall through the engine's own bounds checks silently, which is why no item can test them; documented so nobody hunts for one. The type stays a pass-through that indexes the row rather than selecting a branch here, so a server filling those columns in gets Use and Close working with no change on this side. Sound keys off the item's display, not its itemID, so items that look alike sound alike — the engine's grouping, and why every item has a sound without one being recorded per item. Verified in game: Pickup and Drop play, and differ by material. |
||
|
|
be7a8a0dd7 |
feat(sound): mute sound files, play by SoundKitID, and report what played
Five additions, one hook between them.
MuteSoundFile / UnmuteSoundFile stop a given audio file from playing.
They co-hook FUN_007A5450, the single funnel every sound passes through:
this client links only FMOD's FSOUND_Stream_* API, so even a one-shot UI
click is a stream opened by path, and the six callers of that function
are the whole surface (PlaySoundFile, the SoundEntries player behind
PlaySound and every DBC-driven spell/creature/UI sound, and four
music/ambience paths). A muted path returns NULL, which is the engine's
own "did not play" answer — its pre-play gate FUN_007A66A0 already
returns that at a category's concurrency cap, so every caller handles it
and PlaySoundFile already reports it to Lua as nil. Suppressing the open
rather than muting an opened stream means nothing is decoded for a sound
nobody hears; the only visible difference is PlaySoundFile returning nil
instead of 1 for a muted file.
C_Sound.GetRecentSoundFiles reports the last 64 DISTINCT files played,
newest first, with a timestamp and a muted flag — the other half of
muting, since hearing a sound tells you nothing about which of ~9,800
files it was. Always on: the hook exists for muting anyway, recording is
one bounded copy into a preallocated slot on a call that is about to open
and decompress an archive file, and a switch would have to be armed
before hearing the sound you wanted to identify.
C_Sound.PlaySound plays a SoundKitID and returns willPlay, soundHandle. A
SoundKitID is a SoundEntries row id — the same ids the modern client's
SOUNDKIT constants carry, verified against this build's table (850
igMainMenuOpen, 8959 RaidWarning, 8960 ReadyCheck). The engine has always
played by id internally; the only Lua door was the row's NAME string, so
addons written against SOUNDKIT ids could not play a sound here. The
global PlaySound is therefore widened to a strict superset: a number
plays by id, anything else tail-calls the engine with the stack untouched
so the name form is unchanged. It discriminates on lua_type rather than
lua_isnumber, which would also accept a numeric string and reroute
PlaySound("123") away from the name lookup.
C_Sound.IsPlaying validates a handle by walking the engine's live stream
list rather than dereferencing it, since a stream object is freed when
the sound ends, with a step guard so a corrupt list cannot spin inside a
Lua call. Handles are pooled and reused, which the docs call out.
FUN_0045CE60's ABI came from the disassembly, not the decompile — Ghidra
maps its arguments inconsistently against the call site. Re-registering
the PlaySound global was contention-checked first: no sibling DLL
references Script_PlaySound (UnitXP_SP3's "PlaySound" string is the winmm
PlaySoundW import), and the one addon that reassigns the global does a
temporary swap and restore around its own calls.
Verified in game: play by id and by name, mute and unmute across both
entry points, IsPlaying true while a sound runs, and the recent list
filling from sounds the player never triggered (zone music, quest log,
enter world) — which is what shows the funnel sees everything.
|
||
|
|
f9167bac06 |
feat(export): add ExportSoundFiles, and sweep every archive when enumerating
ExportSoundFiles is a sibling of ExportDBCFiles that dumps the MPQ `Sound\` tree to `BlizzardSound\`, with an optional subpath prefix (the full tree is ~3.5 GB and the command runs synchronously). All 8803 SoundEntries rows have a `Sound\...` DirectoryBase, so that one root is the whole corpus. Writing it exposed a bug in the existing enumeration. FUN_00401470's `archiveSelector` is not an archive SET, as the old comment assumed — it is an INDEX into a fixed 10-entry table built by the mount function FUN_00403740 (model, texture, terrain, wmo, sound, misc, interface, fonts, speech, dbc). Each call walks the primary patch archives plus exactly ONE of those ten. We passed 6, copied from the macro-icon loader, so ExportInterfaceFiles was complete only by coincidence — interface.MPQ IS selector 6 — while the sound export opened neither sound.MPQ nor speech.MPQ and silently lost 6,561 of 9,535 indexed files. EnumAllArchives now sweeps all ten, deduped; ExportInterfaceFiles and ExportDBCFiles go through it too. The sound export also unions the archive index with SoundEntries.dbc, because each source holds files the other lacks: an MPQ resolves a read by hashing the path, so the index is optional and 299 shipped files are named by no index at all, while ~300 more (character combat grunts, doodad audio referenced from model data) appear in no SoundEntries row. Same shape ExportDBCFiles already uses to union the index with its .text path-getter scan. Failed reads and writes are now counted and logged rather than silently skipped. A path only reaches that point because an index or the sound table named it, so a failure means the two disagree — which is worth seeing, and was invisible before: the console line gains "(N skipped)" and each path goes to Logs\classicapi_debug.log. Also: no extension filter (the tree is all audio, and the table carries typo'd names like Kill3.wac a whitelist would drop), and the destination is BlizzardSound\ rather than Sound\ — the loose-file VFS index resolves loose files ahead of archives, so exporting into Sound\ would shadow the MPQs with gigabytes of duplicates re-indexed at every launch. Verified on the 1.18.1 build across both fixes: 3,184 files with the original selector, 9,526 once SoundEntries was unioned in, 9,818 with the full archive sweep, and no zero-byte writes. ExportInterfaceFiles holds at 340/340 and reports nothing skipped, so neither it nor ExportDBCFiles was ever affected. Two residuals on this Turtle build, both logged rather than hidden. The 12 `Sound\Creature\Elekk\*` + 4 `Sound\Creature\ElekkPet\*` reads fail because SoundEntries names a folder the archive does not use (the files sit flat in `Sound\Creature\`) — a data inconsistency, not a code fault. Separately, patch-7's 14 flat `Sound\Creature\Elekk_*.wav` index entries do not reach disk, and that one is NOT explained: patch-7's listfile is demonstrably walked (its 4 exclusive interface-code files exported, and interface has no DBC fallback), yet those entries produced neither a file nor a logged failure. |
||
|
|
7d82ae8e92 |
docs: record where hooksecurefunc's unhookable list comes from
`kUnhookableNames` is patch 11.0.0's own refusal list, verbatim — the 23 taint-relevant names, not "the Lua base library". Nothing said so, and with the base-library luaL_reg table (0x00811E28, 36 entries) freshly catalogued the two looked like they should be one thing. They must not be: 11.0 leaves tostring / error / loadstring / assert / collectgarbage hookable and includes secure-family names that are no base function, so deriving the list from the engine table would move it away from the client. No earlier client on this machine (3.3.5, 4.3.4, 5.4.8) has the restriction at all. Say so in the source comment and the TODO section, and list the names in the API reference, which documented every other hooksecurefunc error but this one. Comment-only in the source; no behavior change. |
||
|
|
d98d3a9fd5 |
perf(luasyntax): decide with one allocation-free lex before tokenizing a chunk
The load hook gated on raw bytes — memchr for `#`/`%` and three scalar scans for `...`, `0x` and `[=` — then tokenized the whole chunk, and RewriteAll threw the token vector away when no operator token existed. A `%` in a format string or a `...` in prose was enough, so nearly every addon file and every SavedVariables file paid for a token stream it did not need: on the dev install, 723 of 1391 addon files (101.6 of 160 MB on disk) and 39 of 301 SV files (16.7 of 16.9 MB). The lexer is now `Lex<Sink>`, one body with two sinks. RunPasses runs it first with `FlagSink`, which records only whether `#`, `%`, `...`, a hex number or a leveled long bracket occurred outside a string or comment, and tokenizes only when one did. The byte gates are gone (the flag lex replaces all five) and RewriteAll takes the flags instead of rescanning the tokens. A chunk with no real 5.1 syntax costs one pass and no allocation, and the string/comment skipping stays single-sourced. Measured in game after the change: 40,921 chunks / 19.1 MB per login, 112 chunks / 2.8 MB tokenized, 39 ms inside the rewrite in total. `_classicapi_TranspileStats()` exposes those counters. |
||
|
|
3d91ae0f91 |
feat(macro): show a spell named by ID even when it is not learned
`#showtooltip 1539` resolved its value through the engine's name resolver, which maps a name -- or an ID through its name -- to a spellbook SLOT. An unlearned spell has no slot, so the directive matched nothing and the button greyed with no icon and no tooltip. That constraint is right for `/cast`, which needs the slot, but an icon and a tooltip need only the spell record. A value the directive names itself is the author saying what to display, so it now falls back to `Spell.dbc` when the spellbook has no slot for it. The button still greys, because the spell still cannot be cast, which is the honest result: the macro shows what it is about and says you cannot use it. `spell:N` is accepted as the display counterpart of `item:N`, and skips the spellbook unconditionally -- nobody writes that form except to name a spell for display. A bare number skips it only for an explicitly named value; one lifted off a `/cast` line resolves exactly as far as that cast would, which keeps the bare form honest about what the macro will actually do. A spell NAME cannot be rescued either way, since 1.12 has no name-keyed spell index. The name path still runs first, so a learned spell keeps its real spellbook resolution including the pet-book flag; the record fallback only sees what the spellbook rejected, and forces `isPet = 0` there, a pet slot being exactly what just failed to resolve. The 1..19 inventory-slot rule stays ahead of it, so `#show 13` is still slot 13 rather than spell 13. A published value counts as explicit for the same reason a directive's does. |
||
|
|
0ba73b8457 |
fix(macro): leave GetMacroInfo alone and expose the shown icon instead
`Macro::Info` re-registered `GetMacroInfo` to answer with the icon a `?` macro's `#showtooltip` resolved to, so the Macro UI's list would match the action button. But the Macro UI seeds its icon selector from that same return -- `MacroFrame_Update` sets `MacroPopupFrame.selectedIconTexture` from it, and `MacroPopupFrame_Update` checks the grid button whose name matches -- so opening the selector on such a macro pre-selected an icon the player never picked, in the one place that edits the stored icon. Saving was never at risk (an unclicked selector leaves `selectedIcon` nil and `EditMacro` then leaves the icon alone), but the display was wrong. One return cannot serve both readers, and the one that edits state has the stronger claim, so `GetMacroInfo` goes back to the engine's: it is the read side of the icon `C_Macro.EditMacro` writes, and every addon that captures it now gets the stored icon. The icon a macro SHOWS becomes something a caller asks for, through `C_Macro.GetMacroIcon`. It reads the macro icon getter this DLL already hooks, so the `?` rule and the active-icon choice stay in one place and the answer matches what the action button and the drag cursor get. Util/MacroIconSelection.lua paints the Macro UI's list buttons from it after the stock update, which is additive -- an empty slot or a macro with a chosen icon answers with what stock already drew. Dropping the re-registration also takes a commonly captured global out of the override chain. |
||
|
|
d9565fbe1f |
fix(macro): correct macro display on a client that owns the macro tooltip
SuperWoW detours the engine's macro tooltip builder and reimplements 3.3.5's version of it: build the cached spell's tooltip when the macro's primary-spell field is non-zero, else add the macro's name. We write that field on purpose -- it is what makes a macro button's icon, cooldown, range, usable and auto-repeat state correct -- so every display fault here traced back to what we put in it. Four things were wrong: - `MaintainExternal` re-derived "the publisher had a value" from `kind != None`, but `Publish` marks a claimed macro `ShowTooltip` either way. One tick after `SetMacroDisplay(i, false)` it turned the publisher's "nothing matched" (cache 0, button usable) into "named an unknown spell" (the grey-out sentinel), and then stuck, because the next pass saw the sentinel already in place. The button greyed and the tooltip came up empty -- a spell tooltip for -1 builds nothing and skips the name. `matched` is stored on the entry now. - A publisher's claim outlived the publisher. `PrepareForReload` never cleared the entries and `Rescan` deliberately never re-reads a claimed body, so an addon disabled between reloads left every macro it had ever claimed frozen on its last answer. Claims are dropped on reload, each one handed back to the engine's own parse first. - `LookupEntries` scanned all 36 entries for a matching macroID. That is not sound: `FUN_MACRO_CREATE` bumps one of two per-scope counters, so a general and a per-character macro can share an id, and an entry whose slot-map index shifted keeps its old id until the next rescan. Either way another macro's resolution could answer. It resolves through the slot map now and requires the entry to still agree. - `#show` is icon-only, but the tooltip is not ours to delegate on this client: the field we fill for the icon is the same one the detoured builder reads, and it cannot carry the distinction. `#show` builds the macro's name through `Script_SetText`, which runs the identical sequence. `Publish` takes the kind from the body for the same reason, so a claim can no longer promote `#show` to `#showtooltip`. Also: a resolved spellID with no Spell.dbc row goes back to the engine rather than rendering an empty frame, matching the fallback 3.3.5's own macro tooltip ends with; and a conditional directive keeps its tooltip refreshing while hovered, which is 3.3.5's `dynamic | built` return. |
||
|
|
f895d38f76 |
refactor(time): drop C_DateAndTime.GetServerTime for the ClassicAPI mirror
The alias existed because FrameXML takes the GetServerTime global on some clients, and an addon needs some reachable name for the epoch. ClassicAPI.GetServerTime now is that name, so the hand-made one is redundant surface. Docs now point the GetServerTime caveat at the mirror. |
||
|
|
804ed61c76 |
feat(lua): mirror every registration under a ClassicAPI namespace
Registering a Lua name is not the same as owning it. The engine's
registrars write _G, FrameXML and every addon load after that, and
whoever writes last wins with no error and no way for the loser to
notice. GetServerTime is the case on record: a client whose GameTime.lua
declares its own replaced ours on every login, and no addon could reach
the C function again.
Every name RegisterGlobalFunction, RegisterGlueFunction and
RegisterTableFunction bind is now also bound under _G.ClassicAPI, which
nothing else writes -- ClassicAPI.GetServerTime,
ClassicAPI.C_Item.IsBound, namespaces kept as subtables. All three
registrars are single chokepoints, so this is one helper covering 637
in-game registrations plus 26 glue ones, and anything added later needs
no extra call.
Two properties, both of which depend on doing this in the registrar
rather than from addon Lua:
- It runs at registration, so the mirror captures OUR function. A
Lua-side `ClassicAPI.X = X` in the embedded addon would run after
FrameXML and faithfully copy the clobbered version.
- It mirrors by VALUE, reading the name back rather than making a
second closure over the same C function. So `ClassicAPI.X == X`
holds until something replaces the global, and the pair doubles as a
clobber check:
if GetServerTime ~= ClassicAPI.GetServerTime then ... end
EnsureSubTable uses raw get/set so a namespace carrying a metatable
cannot divert either side, and MirrorRegistration restores the stack via
an absolute gettop rather than counting pops.
Not covered, and documented as such: frame methods, which live in the
per-frame-type registry rather than _G, and RegisterIntegerEnum values,
where a mirror would be a stale copy rather than a reference.
Verified in-game: ClassicAPI.GetServerTime == GetServerTime is false on
a client whose FrameXML takes that global, while
ClassicAPI.GetTimeCached == GetTimeCached is true.
|
||
|
|
aacace1645 |
fix(time): take the server clock from the engine's own time sync
`GetServerTime` had two separate problems. The global is not ours to keep. Registration happens inside FUN_LOAD_SCRIPT_FUNCTIONS and FrameXML loads after that, so a client whose GameTime.lua declares its own `function GetServerTime()` replaces it on every login and every /reload, and no addon can reach the C function again. Turtle's version returns (serverHour, serverMinute) -- which is itself just the player's own machine clock, since it only diverges from date() if the realm answers a TW_TIME broadcast, and nothing in the public core does. Add C_DateAndTime.GetServerTime: the same C function under a name FrameXML never touches. The value was also the wrong clock. It was rebuilt from the broadcast gametime struct, which carries minute granularity, no timezone, and whatever per-map time offset the realm folded in before sending. The engine already has a better source: FUN_004DE430 (quest-log enter-world setup) sends CMSG_QUERY_TIME unconditionally, and the handler caches localEpoch - serverEpoch at VAR_SERVER_TIME_DELTA, refreshed hourly. The reply is a raw time(nullptr), so the skew yields a true UTC epoch with real seconds, free of both the timezone and the map offset. The sign is confirmed by the engine's own use of it -- the timed-quest expiry check in FUN_004DE510 converts a server timestamp into local-clock space by ADDING the delta. The two clocks answer different questions, so Time::Server exposes both and each function takes the one its contract names: CurrentEpoch() the instant GetServerTime, GetSecondsUntilDailyReset RealmClockEpoch() the display GetCurrentCalendarTime, GetServerTimeLocal GetServerTimeLocal is "the epoch offset by the server's timezone", which RealmClockEpoch already is by construction, so its round-trip through the *player's* timezone is gone. GetSecondsUntilDailyReset moves the other way: a realm buckets its day over a raw time(nullptr), so the boundary is UTC midnight rather than the displayed midnight. Verified in-game across an Azeroth -> Kalimdor port on two realms, one on UTC and one on UTC-5. The instant stays continuous (+51 s across the port, matching real elapsed time) while GetGameTime jumps 12 hours; GetServerTimeLocal tracks the realm's displayed clock and rolls the date with it; GetCurrentCalendarTime's hour matches GetGameTime in both zones. Fixes #50 |