mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 16:10:36 +00:00
4d744b66380964d893e43dc6331e9bc1fd586154
432
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
4d744b6638 |
feat(interface): INTERFACE_VERSION global constant
Publishes INTERFACE_VERSION (11200 on this client) — the client interface/TOC version, read from the engine's own accessor (FUN_ADDON_CLIENT_INTERFACE_ VERSION, the same value the addon loader compares each `## Interface:` against) rather than a literal. A global number re-published every /reload via ModuleAutoRegister, mirroring CLASSIC_API_VERSION, since it is a fixed client constant. Verified in-game: /dump INTERFACE_VERSION -> 11200. |
||
|
|
c2a4cbdf27 |
docs: drop WoW-version and vanilla-gap phrasing
The docs are a modern-API backport onto 1.12, so "added in <patch>" and "vanilla 1.12 lacks/does X differently" are implied by the doc existing — they were noise. Swept both across docs/API.md and README.md: dropped the version-introduction and vanilla-limitation clauses, and where a version note was the only thing explaining a hardcoded/degenerate return value, kept the reason without the version. Behavior notes and "ClassicAPI extension" provenance are unchanged. The large line count is mostly paragraph reflow after clause removal; no API names, signatures, or code examples changed. |
||
|
|
d30ae53fbf |
feat(editbox): ClearHistory
Empties the up/down input history. The engine's SetHistoryLines internal (FUN_0077cd90) frees the whole history ring when called with 0, so clear = free (0) then reallocate at the saved max — dropping every entry and resetting the write position while keeping the line limit, so the box keeps recording afterward (matching modern semantics, not "history disabled"). No-op when the box has no history. New offsets: OFF_EDITBOX_HISTORY_MAX (+0x388, the ring capacity GetHistoryLines reads), FUN_EDITBOX_SET_HISTORY_MAX. Verified in-game: AddHistoryLine + ClearHistory leaves GetHistoryLines unchanged and the up-arrow history empty; new lines still record. |
||
|
|
8f32955823 |
feat(editbox): SetHighlightColor / GetHighlightColor
The engine paints the text selection with three Texture regions (start-line
+0x350, middle-block +0x354, end-line +0x358; positioned by FUN_0077d950),
and their vertex color IS the highlight color — there's no single color field.
So SetHighlightColor packs {b,g,r,a} and writes it to all three via the
engine's own generic region color setter (FUN_0077f750, the same one behind
Texture:SetVertexColor / FontString:SetTextColor), and GetHighlightColor reads
the first region back through the matching getter FUN_0077f8c0 (the read half
of Texture:GetVertexColor). The blinking caret is a separate region (+0x3d4),
left untouched.
Colors are 0..1, alpha defaults to 1. New offsets: FUN_REGION_GET_COLOR,
OFF_EDITBOX_HIGHLIGHT_REGION; FUN_FONTSTRING_SET_COLOR relabeled as the
generic region color setter it always was.
Verified in-game: SetHighlightColor(1,0,0) reads back 1 0 0 1 and a selection
paints red.
|
||
|
|
2778643f4f |
feat(editbox): GetUTF8CursorPosition, ClearHighlightText, HasFocus, HasText
Round out the EditBox method backports alongside Set/GetCursorPosition, all reusing state the engine already maintains: - GetUTF8CursorPosition — caret as a character index (vs GetCursorPosition's byte offset), via the engine's own byte->char counter FUN_0077bc80. - ClearHighlightText — drop the selection but keep the caret (collapse selStart/selEnd onto the cursor + highlight-dirty bit). Vanilla can only clear a selection with HighlightText(0,0), which yanks it to offset 0. - HasFocus — pointer identity against VAR_FOCUSED_EDITBOX (the global the engine's SetFocus writes / ClearFocus clears). - HasText — text byte length (+0x338) is non-zero. Registered on the EditBox method registry, so only EditBox frames dispatch them. New offsets: OFF_EDITBOX_TEXT_LENGTH, FUN_EDITBOX_COUNT_CHARS. The module now covers cursor / selection / focus / text-state, so it moves from editbox/Cursor.cpp to editbox/Methods.cpp (namespace EditBox::Methods). Documented in docs/API.md and the README under the Frame widget section. Verified in-game: SetText+SetFocus reports HasFocus/HasText true and both cursor getters 5; an empty box reports both predicates false. |
||
|
|
c20be0cef1 |
feat(editbox): SetCursorPosition / GetCursorPosition
Vanilla's EditBox registry has 48 methods (HighlightText, Insert, SetText, ...) but no cursor accessor, so modern addons that set text then place the caret error with "attempt to call method 'SetCursorPosition' (a nil value)" (reported: TwitchEmotes autocomplete). The caret already exists in the engine — a byte offset at editbox+0x36c — with reusable primitives: FUN_0077e360 clamps and sets it (the engine's own "restore caret" step in the insert path), FUN_0077ccf0 collapses the selection onto it. Modern SetCursorPosition is byte-based too, so it maps 1:1. New EditBox::Cursor module registers both methods on the EditBox method registry (0x00CF5378); registering under that context means only EditBox frames dispatch them, so `this` is always a real CSimpleEditBox. Set path: clamp+set the caret, collapse the selection, flag the highlight dirty. Verified in-game: SetText + SetCursorPosition + GetCursorPosition round-trips and the caret lands at the requested offset. |
||
|
|
1ad6b57202 |
fix(table): writer-side mark for deliberate nil appends
The v1.12.8 gap heuristic (keep the stored length when it overshoots the border by exactly one) protected `table.insert(t, nil)` slots (#36) but broke every 5.1-dialect table that is stale by exactly one — a pairs-cleared one-element table, or a recycled table whose previous life was one slot longer. Tablet-2.0's del()/copy() pool produces the latter on every tooltip refresh, so FuBar/Ace2/Tablet menus and tooltips shifted by one with a nil hole at slot 1. The two states are byte-identical, and both consumers reach the heal through table.insert — neither the table nor the caller can split them. Only the writer knows which dialect the table speaks, and the write is observable: co-hook the engine's table.insert (FUN_LUA_TABLE_INSERT = 0x7FB6B0, verified against the table-lib luaL_reg pair in .data and a decompile matching 5.0.2 tinsert line for line) and record {table -> stored length} in a weak-keyed registry table whenever the two-arg form appends a literal nil. Rule 3 now heals every stale table to the border (the 5.1 answer) and keeps the stored length only when the gap is one AND the mark still matches. Stale marks die on their own: any later insert/remove moves the stored length off the recorded value, and the weak key collects with the table. Verified in-game with a 21-test suite (directed regressions for #29/#36/#39, byte-identical twin discrimination, metamethod isolation, coroutine-side marking, and a seeded differential fuzzer against an executable model of the contract): 15/21 on the broken build, 21/21 with the fix, #36's nil-append cases among the passes both times. New plumbing: LUA_SET_METATABLE (0x6F4020, from LuaCAPI.md) and Game::Lua::SetMetatable for building the weak mark table from C. Fixes #39 |
||
|
|
94e77ef5af |
feat(unit): UnitCreatedBySpell + consolidate the unit-token resolver
Add `UnitCreatedBySpell(unit)` — the spell that summoned a unit (a totem's totem-drop spell, a pet/guardian's summon spell), read from the unit's UNIT_CREATED_BY_SPELL descriptor field (byte +0x230). It is the same field the engine's unit-title builder consults to pick the Pet/Minion/Guardian/ Creation title, and it is broadcast, so it resolves for any unit in range. This is the summoning spell, distinct from the (server-only) spell a totem casts. Also add a single `Game::ResolveUnitToken(token)` helper that wraps the engine token->CGUnit* resolver, and route unit/Pet.cpp through it plus the Game::Read<T> field accessors — removing the hand-rolled ResolveUnitToken_t typedef and raw reinterpret_casts from this module. The name was already referenced in Offsets.h and CLAUDE.md but had never been implemented. |
||
|
|
1458d60b51 |
feat(spell): GetSpellInfo accepts a spell name, link, or "Name(Rank N)"
The shared spell-arg resolver errored on any non-number arg1, so
GetSpellInfo("Fireball") raised instead of resolving. Match retail's
full argument set: arg1 may now be a spellID, a spell name, or a spell
hyperlink.
A name resolves against the player's then pet's spellbook (retail's
scope) and returns the highest rank you know; an unknown name returns
nil rather than raising. A trailing "(Rank N)" subtext pins that exact
rank -- the vanilla SpellName(Rank N) form CastSpellByName uses, with a
space before the paren tolerated. A link's embedded spellID is parsed
directly, so it works for any spell, learned or not.
Because GetSpellLink / IsPassiveSpell / IsHarmfulSpell / IsHelpfulSpell
share this resolver, they gain the same name and link forms.
Verified in-game: "Mind Blast" -> rank 9 (max known); "Mind Blast
(Rank 8)" and "Mind Blast(Rank 8)" -> rank 8; "Mind Blast (Rank 99)"
-> nil.
|
||
|
|
6aea4a1752 |
Retail-like /reload: new addons, new files, ## metadata edits, deletions (#37)
* feat(addons): retail-like /reload — new addons and new files load Two engine limitations kept anything created after boot from loading until a client restart: 1. File visibility: every relative-path read resolves through a loose-file hash index built once at boot (FUN_00646EA0, latched); the archive layer's live disk probe is dead code (DAT_00865B44 ships 1, boot clears it) and writes never register. New files - including a new addon's TOC and first-ever SavedVariables - were invisible until restart. 2. Registry membership: the addon registry is built once at login; new folders are never walked. Addons::Rescan runs per /reload from the ModuleAutoRegister callback (before the AddOns.txt re-read, progress count, and load pass) and: - re-indexes Interface\AddOns + WTF\Account with the engine's own dedup-safe boot indexer (FUN_VFS_INDEX_SUBTREE) - new files in existing addons then load natively, since the per-addon loader re-reads the TOC from disk on every load pass; a newly installed addon's first SV save now also survives /reload; - replays login scan walk #2 verbatim (FUN_ADDON_SCAN_DISK_DIRS with the engine's own dir-to-parser callback) so new folders register as complete normal entries via the dedup-guarded TOC parser; - mirrors the two structures the login scan would have filled: reverse-LoadWith links (tail-loop grow+append, restricted to pairs involving a new entry - the engine's lists have no dedup) and the flat GetNumAddOns display array (FUN_0051DA70 phase 2: filter byte +0x29, engine grow + qsort comparator). Append-only by design: no teardown, no eviction, no mutation of existing entries - the prior hot-reload attempt died re-running the login-only FUN_ADDON_INIT teardown mid-reload. Still login-only (no safe mechanism): ## metadata edits of already-registered addons and folder deletions. Also centralizes Embedded.cpp's addon-entry field constants into Offsets.h now that a second module reads them. * refactor(addons): centralize the registry list walk; record dedup-guard probe The intrusive linked-list walk (head at [VAR_ADDON_LIST_HEAD], next at entry + [VAR_ADDON_LIST_CTRL] + 4, low-bit-1/NULL sentinel) was implemented twice -- a template in Rescan.cpp and an inline loop in Embedded.cpp's FinalizeEmbeddedEntry. Move it to addons/Registry.h as Addons::ForEachEntry, with a void- or bool-returning visitor (false stops early). The early stop is load-bearing for Embedded: re-linking the found entry to the head invalidates the current next-pointer, so the walk must not continue past it -- the shared helper makes that contract explicit. Also record the TOC-parser dedup-guard verification in Rescan.cpp's scan-call comment: the guard is the parser's FIRST block (hash lookup + name compare, early return before the TOC path is even built), and both the Storm hash (uppercases a-z, folds '/'->'\') and the SStrCmpI compare are case-insensitive -- so the per-/reload scan replay can never re-read or mutate a registered entry's ## metadata, and a case-renamed folder matches its existing entry instead of registering a duplicate. * feat(addons): /reload re-parses edited ## metadata and drops deleted addons The TOC parser's dedup guard makes a registered entry's ## metadata read-once: an edited ## SavedVariables: / ## Dependencies: / any ## line never re-parsed until re-login, and a deleted folder's entry lingered in the addon list. Both were documented login-only limits of the retail-like /reload feature. Rescan's new step 1.5 closes them with evict + re-register, all engine machinery: - Change detection: FNV-1a over the TOC's ## lines only (BOM skipped like the parser, line terminators excluded), read through the hooked FUN_FILE_READ so flavor selection is hashed exactly as the parser reads it. File-reference edits never trigger the evict path -- the load pass re-reads those natively. Baselines seed at login and for newly registered folders in the same Run(), so an edit is always diffed against what was actually parsed. - Evict: scrub the victim from every other entry's reverse-LoadWith list (the one reference the destructor cannot clean -- the loader's post-ADDON_LOADED loop dereferences those entries), then call the engine's own complete per-entry destructor FUN_ADDON_ENTRY_DESTROY (0x005200A0, __stdcall, RET 4; vtable slot 0 of the registry node factory at [0x00BE1B60], dispatched per entry by the login teardown). Verified by decompile: frees every owned allocation (name, dep/SV arrays + buffers, reverse-LoadWith buffer, the ## metadata table) and self-unlinks from both the intrusive list (FUN_00520A60, no-ops when already unlinked) and the hash bucket chain. - Re-register: feed the name back to FUN_TOC_PARSER -- the dedup guard now misses and the entry rebuilds from the edited TOC exactly like a fresh registration. Refreshed entries join the existing FixupReverseLoadWith/RebuildDisplayArray fix-ups; the refresh runs before the before-snapshot so an address-reusing allocator cannot make the added-diff double-count or miss one. Any eviction forces the display-array rebuild (it holds the dead entry's freed name pointer until then). Victims are collected during the walk and processed after it -- the dtor zeroes the link node under the iterator. - Deletion: an unreadable TOC evicts without re-registering; a folder the scan still finds simply re-registers the same reload. Exempt: !!!ClassicAPI (Addons::Embedded owns its entry) and ## Secure: / SMSG-managed entries (the parser cannot restore packet-delivered state; new OFF_ADDON_ENTRY_SECURE = 0x28, parser write site verified). Verified in-game: ## X-Test metadata edit picked up across /reload (GetAddOnMetadata returns the new value), SavedVariables list edit takes effect, folder deletion drops the entry from GetNumAddOns, folder restore re-registers it, and a no-change /reload is a pure hash-compare no-op. * fix(addons): address review — hash commit timing, evict flag, README row - README: the /reload row said `##` metadata edits still need a re-login — stale from before the metadata-refresh step landed. Now matches docs/API.md: edits take effect, deleted folders drop from the addon list. - Rescan: commit g_metaHash only after the re-registration actually happened, so a failed resolve/parse retries next /reload instead of silently absorbing the edit forever; a victim the parse cannot restore is erased (treated as deleted) so a reappearing folder re-seeds. - Rescan: RefreshChangedMetadata returns whether anything was actually destroyed, not whether victims were collected — no display-array rebuild when every victim failed to resolve. - Rescan: comment the load-order consequence of evict + re-register (the fresh entry appends at the list tail; declared deps still force-load first). |
||
|
|
fbe40743c0 |
fix(table): keep length on a deliberate single nil append
The stale-length heal (Length.cpp) could not tell a cleared-and-reused
table from a deliberate table.insert(t, nil): both leave the stored
length pointing at a nil slot with no explicit n field, but they want
opposite answers. Rule 3 healed both, so the next table.insert on a
single-nil-appended array wrote over the nil and shifted every later
element down by one -- silent corruption in Ace2-era addons (Waterfall's
{key1,val1,...} arg builder inserts a nil whenever an option has no
passValue, the common case), with no error anywhere.
The issue's preferred fix -- make table.insert always use the raw stored
length -- reintroduces #29: Dewdrop clears `values` with a pairs loop +
no-op table.setn, then rebuilds it via table.insert, and that append is
exactly what the heal fixed. Both consumers reach the heal through
table.insert, so the caller cannot distinguish them; only the staleness
gap can. A cleared table is stale by many slots; a deliberate nil append
is off by exactly one. So heal only when the stored length overshoots
the border by more than one slot, and keep it otherwise.
Verified in-game via CAPI_DemoTableLengthHeal (AddOnCompat.lua): nil
append preserved (getn=3, t[2]=nil, t[3]=b), Waterfall pairs intact, and
the cleared-table rebuild still heals to slot 1.
Fixes #36
|
||
|
|
a962c76f09 |
feat(aura): real isFromPlayerOrPlayerPet; fix castByPlayer to Era semantics
Populate AuraData's isFromPlayerOrPlayerPet from the cached caster GUID's HIGHGUID prefix (player 0x0000 / pet 0xF140, confirmed in tortoise-wow ObjectGuid.h) instead of hardcoding false. The UnitAura tuple's castByPlayer (position 13) is the same value under retail's older name -- Era defines it as "applied by a player, their pet or vehicle", not the local player -- so both now share one HIGHGUID test in ResolveDisplay. The local-player question stays with the PLAYER filter, unchanged. False on a cache miss (cast not observed this session); totem buffs read false (vanilla totems carry the creature prefix, not pet). |
||
|
|
eef7140722 |
feat(combat): add StartAttack / StopAttack globals
Backport the non-toggling melee auto-attack verbs. 1.12 ships only the toggling AttackTarget (FUN_006131A0), so /startattack can't guarantee it won't cancel an in-progress swing. These call the engine's own start (FUN_005ECB70, sends CMSG_ATTACKSWING) and stop (FUN_005ECAC0) primitives directly, split into the two idempotent verbs. StartAttack takes an optional unit-token target (resolved under pcall so a name/bad token can't raise, falling back to the current target); with no arg it validates and attacks the current target via FUN_00612DF0. |
||
|
|
855b338736 |
feat(frame): add GetClickFrame global
Backport the engine-registered C global behind the /click command: resolve a frame by its global name, returning it only when _G[name] holds a real frame whose GetName() matches. Mirrors 3.3.5's Script_GetClickFrame; reads the name from CFrameScriptObject vtable slot +4, verified against 1.12's own Script_GetName. |
||
|
|
1170a4e63a |
fix(texture): mask via texgen for SetMask so SetTexCoord sprites clip right
SetMask rode the minimap BLIP recipe (explicit second UV stream, uv1 = uv0), so the mask sampled at the base's texcoords - a SetTexCoord'd sprite made unit 1 sample that same sub-rect of the MASK image, showing a corner chunk of the shape instead of the shape. Retire that path: the path mask is now one extra unit in the texgen draw (MaskedRegionDrawImpl), its matrix built from the BASE region's own rect (SetTexCoordModifiesRect crop gate included) plus the base's SetRotation so a mask keeps following a rotated texture. The angle-0 matrix is exactly the old recipe's formula re-expressed through positions (see BuildMaskMatrix), so default 0..1-texcoord textures render identically; sprites become the fixed case, matching retail (SetMask ignores SetTexCoord). Side effect: SetMask and AddMaskTexture now compose (alpha intersection) instead of object masks winning; the path mask occupies one of the 7 units. |
||
|
|
536c5e3c51 |
feat(frame): add PreClick/PostClick button scripts
Backport the modern PreClick/PostClick button scripts as real,
SetScript/GetScript/HookScript-able handlers. Vanilla 1.12 has only
OnClick and OnDoubleClick on buttons.
Two co-hooks (same technique as Tooltip::SetEvents):
- FUN_BUTTON_SCRIPT_RESOLVER: recognize the two names, returning an
external per-button {handler, context} cell (a button has no free
slot, and the resolver contract is just "return where the handler
lives"). This makes them SetScript/GetScript/HookScript-able.
- FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT (the arg'd script runner), gated on
slotPtr == frame + OFF_BUTTON_ONCLICK_HANDLER (0x4CC): fire PreClick
before / PostClick after the OnClick, re-invoking with the same
(fmt, varargs) so both receive arg1 = the button name like OnClick.
Deliberately NOT the button click vmethod FUN_00779540 -- SuperWoW
inline-hooks it for click-casting and a second MinHook there faults
(ERROR #132). The runner is uncontested and fires at the same top-level
dispatch level, so its exec-context stamp is valid.
Cells are keyed by button pointer and cleared on /reload
(PrepareForReload, wired in FrameScript_Initialize_h), matching the
tooltip-cell lifetime.
Limitation (documented): PreClick/PostClick fire only when the button
also has an OnClick handler, since the runner only runs for a non-empty
slot. Bracketing an existing OnClick is the common case; the no-OnClick
path would need the SuperWoW-owned vmethod.
Verified in-game: programmatic and real mouse clicks fire pre,click,post
with matching button-name args, and GetScript round-trips.
- Add offsets FUN_BUTTON_SCRIPT_RESOLVER, OFF_BUTTON_ONCLICK_HANDLER,
FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT.
- Document under docs/API.md (Frame section) and the README index.
|
||
|
|
c06bed9158 |
feat(unit): add GetSheathState
Vanilla 1.12 ships ToggleSheath but no getter for the player's drawn-weapon type. Add GetSheathState(), which returns the modern 1-based value: 1 = None (sheathed), 2 = Melee, 3 = Ranged. The engine stores the sheath state as a plain CGUnit int member at +0xD40 (0-based: 0 sheathed, 1 melee, 2 ranged) -- the same field its own toggler FUN_005EB480 reads to pick the next state and its setter FUN_00611CF0 writes. GetSheathState reads the local player's value and adds 1 for the Lua contract. - Add OFF_UNIT_SHEATH_STATE (0xD40) with RE-provenance comment. - Document under docs/API.md (State section) and the README index. - Also list the Tracking API in the README function index (missed in the prior tracking commit). |
||
|
|
e793f80f6b |
feat(spell): add minimap tracking enumeration
Vanilla 1.12 only stores the single active tracking spell
(VAR_ACTIVE_TRACKING_SPELL, 0xBC6378) and never enumerates the tracking
abilities the player knows. Add GetNumTrackingTypes/GetTrackingInfo/
SetTracking, which rebuild that list by scanning the player spellbook for
spells whose EffectApplyAuraName is Track Creatures/Resources/Stealthed
(44/45/151) -- the same discriminator the engine's own active-tracker
updater (FUN_004E4170) uses. This reproduces pfUI's hardcoded tracking
table with no table to maintain and auto-covers server-custom trackers
(e.g. Turtle's Find Trees, 52917).
- GetTrackingInfo returns name, texture, active, category ("spell"),
spellID; active is read from VAR_ACTIVE_TRACKING_SPELL.
- SetTracking selects a tracker by tail-calling the engine's
Script_CastSpell(slot, "spell").
- Add offsets VAR_ACTIVE_TRACKING_SPELL and FUN_SCRIPT_CAST_SPELL
(0x4B42F0), both with RE-provenance comments.
- Document under docs/API.md (Tracking section).
Verified in-game on a Hunter (8 trackers) and a Dwarf racial (1):
active flips on SetTracking, texture matches native GetTrackingTexture,
out-of-range returns nil.
|
||
|
|
3c6b449df5 |
feat(aura): zero-alloc positional accessors + AuraUtil
C_UnitAuras.GetAuraDataByIndex builds a fresh Lua table per call, churning
Lua 5.0's mark-sweep GC when addons scan many units' auras in an OnUpdate
loop. Add Blizzard's own answer: positional (multi-return) accessors plus the
AuraUtil helper library, so hot loops allocate nothing.
DLL: C_UnitAuras.UnitAura / UnitBuff / UnitDebuff return the 15-value
Classic-Era UnitAura tuple with no table allocation. Built on a shared
Emit { Table, Positional } seam through PushEnriched -- selection, cache
fallback, out-of-range group, and timing resolution are the same code as the
table path; only the terminal leaf differs (BuildTable vs the new
PushPositional, both fed by an extracted ResolveDisplay). Namespaced under
C_UnitAuras so the native UnitBuff/UnitDebuff globals keep their vanilla
short return.
Addon: Util/AuraUtil.lua backports ForEachAura / FindAura / FindAuraByName /
UnpackAuraData over those accessors. ForEachAura (non-packed) and FindAura
both source from the positional accessor, so they allocate nothing per aura --
FindAura included, where retail itself allocates a table per aura scanned.
Verified in-game: positional values match GetAuraDataByIndex field-by-field
(#12 isBossDebuff / #13 castByPlayer differ by design, matching retail's
UnitAura-vs-AuraData divergence); ForEachAura counts match GetUnitAuras; and
the positional path allocates ~0 KB/scan where the table path allocates
~1.3 KB per aura.
Fixes #30
|
||
|
|
7960266969 |
feat(addon): add [known] macro conditional to SecureCmdOptionParse
ClassicAPI extension (not a 3.3.5 conditional). [known:spellID] uses IsPlayerSpell (broad knowledge: spellbook, talents, recipes, racials); [known:name] falls back to a spellbook name scan via GetSpellName, since 1.12 has no name-to-id resolver -- so a name matches castable spellbook entries only. Verified in-game: [known:133] false on a non-Mage, [known:45651] and [known:Aspect of the Viper] both true by id and by name. |
||
|
|
85ed4eb378 |
feat(addon): backport SecureStateDriver + SecureCmdOptionParse
RegisterStateDriver / RegisterUnitWatch / attribute drivers, driven by a Lua SecureCmdOptionParse whose macro-conditional grammar is reverse- engineered from the 3.3.5 client. Builds entirely on the shipped frame attribute system -- no DLL change. - MacroOptions.lua: parse-once cached SecureCmdOptionParse. 33 conditions mapped to 1.12 / ClassicAPI queries; states 1.12 lacks (flying, vehicle) are constant-false, an unknown keyword warns once and never matches. - SecureStateDriver.lua: 0.2s-poll manager with instant event rescans, state-visibility Show/Hide, state-* attribute drivers, unit-existence watch, SecureButton_GetAttribute/GetUnit. Registers via plain tables + an immediate top-level resolve instead of the upstream attribute bootstrap, so the synchronous OnAttributeChanged recursion guard never swallows a target frame's handler. Verified in-game: parser grammar, both drivers, and druid [stance:N] bar numbering. |
||
|
|
7f1e632b49 |
feat(texture): add MaskTexture object API with multi-mask and rotation
Backport frame:CreateMaskTexture plus texture:AddMaskTexture / RemoveMaskTexture / GetNumMaskTextures / GetMaskTexture -- positioned, rect-based masks, the object form later clients use (SetMask(path) stays the simple single-shape form). Positioned masks sample via texgen (object-space vertex position through a per-unit texture matrix), the mechanism of the engine's own minimap disc mask, so no vertex UV stream is consumed per mask. That lifts both v1 limits at once: - Up to 7 masks apply at once (device stage cap); a texture shows only the intersection of all of them. - mask:SetRotation rotates the clip shape (folded into the matrix), and a mask can move/resize each frame, so the clip animates. State is restored in a co-hook on the indexed submit (FUN_GX_PRIM_INDEXED) the engine issues after the stream call, not inside the stream hook -- restoring earlier reverts the state the queued draw is flushed with. Two incidental fixes: a SetTexCoord-cropped base now masks against the same rect the engine's corner store uses, and a recycled mask region is detached from every base still holding it. Offsets.h: add the texgen / coord-transform / texture-matrix / state-journal / indexed-submit constants (decoded from the D3D9 backend state flush FUN_005a2f00), and fix the FUN_GX_TEXUNIT_ENABLE/_DISABLE mislabel (they are texture-matrix push/pop, not stage enable/disable). |
||
|
|
b9d23fbc8c |
feat(texture): add Texture:SetMask(path) alpha-mask backport
Backports the modern Texture:SetMask, clipping a texture to a mask's alpha shape - round portraits, round minimap buttons, and other shaped art. Vanilla 1.12 has no general masking (only the special-cased minimap disc). Mirrors the engine's own masked-quad draw (the minimap blip mask FUN_004eae10): a co-hook on the vertex-stream primitive FUN_0058a2a0 recovers the owning CSimpleTexture from the batch positions pointer (region = positions - OFF_SIMPLETEXTURE_CORNERS), and for a region with a mask set binds the mask on texture unit 1 with a MODULATE combiner, then re-runs the engine's own submit with uv1 = uv0 so unit 1 samples the mask at the texture's own coordinates. The unit is enabled/disabled around the draw so the mask never leaks onto other textures. A cold co-hook on the region ctor clears a region's mask on pooled reuse; a kill switch and SEH latch guard the draw path. The recipe was pinned by an in-game probe on the live GL backend and matched against FUN_004eae10; the full RE is in the "Texture masking" block in Offsets.h and the Mask.cpp header. Masks must be BLP or uncompressed 32-bit TGA with the shape in the alpha channel; two round masks ship in the client, other shapes are addon-supplied content. |
||
|
|
d5c8db9c2e |
docs+ci: contract-only table-length docs; rename release map asset
* README behaviors row + API.md section for the 5.1 table-length healing now describe the behavior (cleared tables count as empty without table.setn; arg tables and setn callers unaffected) instead of the implementation and the Dewdrop/FuBar bug story -- that history lives in the commit message and the Length.cpp comment. * Release workflow ships the linker map as USE_FOR_DEBUGGING_CAPI_CRASHES.map (copy before upload), so users know to attach it to crash reports -- it resolves the logical addresses in an ERROR #132 stack trace to function names. |
||
|
|
813a10f696 |
fix(lua): heal stale 5.0 table lengths for 5.1-detecting libraries
The 5.1 syntax backport made the Ace2-era Lua-version probe pass:
local lua51 = loadstring("return function(...) return ... end")
and true or false
Every Ace2 library gates on it, and Dewdrop-2.0 (the menu library
behind FuBarPlugin minimap buttons -- SuperAPI, NampowerSettings) uses
it to no-op table.setn: correct on real 5.1, where lengths are computed
borders, but wrong on this VM, whose table functions still read 5.0's
out-of-band length. Cleared-and-reused menu tables kept stale lengths,
table.insert appended past the nil'd slots, and the menus silently
broke ("clicking the minimap button does nothing"). Bisect confirmed:
forcing the probe back to 5.0 (VarargExpansion off) restores them.
Since we made the client PASS 5.1 probes, 5.1 length semantics must
hold. The engine funnels every length read through luaL_getn
(LUAL_GETN = 0x6F5050 -- table.insert/getn/remove/concat/sort/foreachi,
plus our unpack), so one co-hook closes the gap for every consumer:
1. reported slot populated -> unchanged (one rawgeti of cost);
2. t[n] nil but t.n is a number -> unchanged: an explicit n field is
the 5.0 vararg-arg contract, where trailing nils are intentional
(unpack({10,nil,30,n=3}) keeps all three slots);
3. otherwise the out-of-band length is stale (keys cleared without
setn) -> return the true border, the 5.1 answer. Read-only, no
write-back: reads never mutate state, and the engine's own
table.insert re-syncs the stored length on the next append.
table.setn keeps working; the heal only changes the answer when the
stored length points past the last populated slot -- exactly the case
where 5.0 and 5.1 disagree.
Docs: API.md "Stale table lengths (5.1 healing)" section + README
behaviors row.
Fixes #29
|
||
|
|
7225eeb32c |
feat(lua): close the remaining 5.0->5.1 stdlib gaps
Systematic sweep of the Lua 5.1 stdlib delta against what ClassicAPI
already backports found five gaps, all confirmed by in-game probes:
* unpack(list [, i [, j]]) -- 5.0's unpack silently ignored the range
args, so unpack(t, 2) returned the WHOLE table (wrong values, no
error; the only silent gap). Replaced with a port of 5.1's
luaB_unpack: ranges via luaL_getn + lua_rawgeti, so a vararg arg
table's n field keeps its embedded-nil count. Both states.
* string.gsub table replacement -- 5.0 accepts only string/function
and errors on a table. Shim on string.gsub AND the bare gsub global:
a table becomes an adapter closure over the engine's own gsub
(FUN_LUA_STR_GSUB = 0x007FD0E0, pinned by registration-table
position, name string, and decode). Because this engine's add_value
drops a non-string function result (match -> empty) where 5.1 keeps
the match on nil/false, the shim wraps the pattern in one outer
capture (^/$ anchors kept outside) so the closure receives the whole
match and can hand it back for missing keys -- exact 5.1 keep-match.
Patterns with a %1..%9 backref skip the wrap (renumbering hazard);
their missing-key behavior stays the engine's (documented residual).
* collectgarbage 5.1 options -- "count" -> gcinfo, "collect" ->
original collectgarbage(0), "step" -> loop-safe true, stop/restart/
setpause/setstepmul -> no-op 0, numbers forwarded untouched. The
originals are function objects stashed in the state's registry
before the overwrite, so no new engine offsets and each /reload
re-stashes the fresh engine original. Both states.
* table.maxn -- 5.1 luaB_maxn port (largest positive numeric key,
full next-walk so nil holes don't stop it). Both states.
* coroutine.running -- returns the running coroutine, nil on the main
thread. 5.0 has no lua_pushthread, so the thread TValue (tag 8 +
the running L, this build's {tt@0, value@+8} layout) is written to
the stack raw; main-thread detection via the registration-time L.
Verified in-game: ranged/holed/n-field unpack shapes, all four gsub
shapes (populated table, keep-match on missing key, whole-match key,
anchored pattern), maxn past a nil hole, collectgarbage("count"/
"collect"), and coroutine.running from main + inside a wrap.
Docs: five new API.md sections + TOC entries; README Lua list updated.
|
||
|
|
5a1d94c001 |
feat(lua): harden string methods -- kill switch + fail-closed captures
Follow-up hardening for the 5.1 string-method backport (
|
||
|
|
9b9d80d807 |
feat(lua): backport Lua 5.1 string methods (("s"):upper(), s:format(...))
Lua 5.0 has no string methods at all -- the shared string metatable with
__index = string is a 5.1 addition, and both halves of the would-be
mechanism in this build match stock 5.0 exactly: lua_setmetatable
(0x006F4020) accepts only tables/userdata, and luaT_gettmbyobj
(0x006F7BD0) hardcodes &nilobject for every other type. So nothing can
be re-enabled; the 5.1 read path has to be added.
Transplant 5.1's mechanism at the one choke every string index reaches:
co-hook FUN_LUA_INDEX_NONTABLE (0x006F7EE0, luaV_gettable's non-table
continuation; 3 call sites -- the gettable else-branch plus
luaV_execute's OP_GETTABLE/OP_SELF fallbacks). When the indexed object
is a string, answer with luaV_gettable(L, <string library table>, key,
loop) -- byte-for-byte what the original's own TM-table branch does had
gettmbyobj returned that table, loop passed through unchanged. The
engine's unmodified lookup then yields exact 5.1 semantics, including
nil (not an error) for unknown keys. Non-strings fall through to the
original; settable on a string is a different continuation, untouched.
The site is cold: table __index dispatch (all frame/OO traffic) reads
the table's own metatable via fasttm (FUN_006F7D60) and never lands
here -- today's only callers are about-to-error non-table indexes.
One captured slot per Lua state (in-game + glue), keyed by global_State
so coroutine threads resolve too; each capture anchors the string table
in that state's registry against GC and re-runs per /reload and per
glue boot. Since baselib/StringLib already registers string.match /
gmatch / reverse into the same table, modern idioms like
msg:match("^!(%w+)") work with no further top-up.
Docs: new API.md "String methods" section; replaced the now-obsolete
"only string.foo(s), never s:foo()" caveat under string.match with a
pointer to it.
Verified in-game: literal and variable receivers, :format, 5.1 nil-miss,
and resolution inside a coroutine thread.
|
||
|
|
a4d6290b80 |
Lua 5.1 syntax transpile + modern addon-loading compatibility (#28)
* feat(lua): backport 5.1 `#` and `%` operators via source transpile
Vanilla's Lua is 5.0, which lacks the `#` (length) and `%` (modulo)
operators, so modern addon ports that use them fail to COMPILE. Rather than
patch the 5.0 parser/VM (no OP_LEN/OP_MOD, no free opcode), rewrite the
SOURCE before it reaches the parser.
src/luasyntax/Transpile.cpp co-hooks luaL_loadbuffer (0x006F5690) — the one
function every compile funnels through (file scripts, loadstring, XML
handlers) — tokenizes each chunk with a small Lua-aware lexer, and runs a
precedence-climbing parser that rewrites, in one pass:
#operand -> __len(operand)
a % b -> __mod(a, b)
`#` is prefix but `%` is binary infix, so its operands are delimited by
PRECEDENCE: a*b%c -> __mod(a*b,c), a+b%c -> a+__mod(b,c), a%b%c chains
left-assoc as __mod(__mod(a,b),c), a%b^c -> __mod(a,b^c). The two operators
compose in the same pass (#t%2 -> __mod(__len(t),2)). No newlines are
inserted, so error line numbers are preserved.
Runtime helpers (registered on both the in-game and glue states):
- __len: string length, or a table border via bisection (5.1 `#`
semantics — ignores any table.setn count).
- __mod: a - floor(a/b)*b. NOT the engine's math.mod, which is C fmod
(truncated toward zero) and disagrees with `%` for negatives
(-1 % 3 == 2, but fmod(-1,3) == -1).
Safety: the rewrite runs only when a chunk contains `#`/`%`, and either as an
operator already fails to compile on 5.0 — so it cannot regress working code
except by misreading one inside a string/comment ("%d", "%a+", --[[ # ]]).
The lexer's string/comment skipping is the one safety-critical part and is
exact. Gated behind default-on toggles (_classicapi_SetLengthOperator /
SetModuloOperator); diagnostic _classicapi_TranspileLength returns the
rewrite. `...` is a separate, larger phase.
Adds FUN_LUAL_LOADBUFFER to Offsets.h with its derivation.
* feat(lua): honor the 5.1 `__environment` metatable field in getfenv/setfenv
Lua 5.1 lets a sandbox hide an environment: put `__environment` in the env
table's metatable and `getfenv` returns that value instead of the real env,
while `setfenv` refuses to change it. 1.12's engine already has this
protection but reads a RAW `__fenv` field on the env table itself — the older
5.0 form. Modern addons ported from 5.1 use the metatable `__environment`
spelling, which 1.12 silently ignored, so their sandboxes leaked.
getfenv (0x00702AC0) and setfenv (0x00702BF8) share one predicate
(0x00702BA0) that reads the marker and, when present, substitutes it / errors
"cannot change a protected environment". src/luaenv/Fenv.cpp co-hooks and
fully replaces that predicate to read `rawget(getmetatable(env),
"__environment")` first, falling back to the raw `env.__fenv` field. One hook
updates both consumers. The reimplementation preserves the predicate's exact
stack contract (push env, push marker, net +2, boolean return) that getfenv
(settop -2) and setfenv (settop -3) depend on; both metatable and env lookups
are RAW, so an `__index` metatable on the env is not disturbed.
The 5.1 mechanism was verified against 3.3.5's `FUN_0084F2F0` (raw
`__environment` off the metatable; no `"__fenv"` string exists there — Blizzard
renamed it and moved it to the metatable at the 5.0->5.1 jump). The change is
additive and inert: nothing on disk sets either marker, so every existing
getfenv/setfenv caller keeps getting the real env — it only activates when
code deliberately marks an environment.
Adds LUA_GET_METATABLE, LUA_GET_FENV, and FUN_LUA_ENV_PROTECT_PREDICATE to
Offsets.h.
* Use Lua length operator for class count
* feat(lua): backport the 5.1 `...` vararg expression via source transpile
This build is pure Lua 5.0 varargs: `function(...)` parses and populates the
`arg` table (with `arg.n`), but `...` used as an EXPRESSION is a parse error
("unexpected symbol near '...'") — verified in-game. So modern 5.1 addon code
using `...` (`{...}`, `local a,b = ...`, `f(...)`, `return ...`,
`select('#', ...)`) fails to compile.
Add a vararg pass to the transpiler (RewriteChunk runs it before the # / %
precedence parser) that rewrites the `...` EXPRESSION to `unpack(arg)`. This is
a faithful, position-independent substitution: `unpack(arg)` is itself a
multi-value expression, so it spreads in tail position and truncates to one
value elsewhere exactly as `...` does, and this build's `unpack(arg)` preserves
embedded nils via `arg.n` (verified: `f(1,nil,3)` -> `1 nil 3`). No precedence
analysis needed — unlike `%`, it's a token substitution once one case is
excluded: the `...` in a function's PARAMETER LIST (the vararg declaration that
creates `arg`) is left intact, found by scanning each `function` keyword and
skipping its param parens. Nested vararg functions work for free — each
`function(...)` makes its own `arg` and `unpack(arg)` binds to the nearest one
(verified: inner arg count 2, outer 3).
Safety mirrors # / %: only chunks containing `...` are touched, and `...` as an
expression already fails to compile on 5.0, so it can't regress working code;
`...` inside strings/comments is skipped by the lexer, and `.` (field) / `..`
(concat) are distinguished by run length. Gated behind the default-on
`_classicapi_SetVarargExpansion` toggle; `_classicapi_TranspileLength` now shows
the full rewrite (vararg + # + %).
File-scope `...` (the `local name, addon = ...` idiom) transpiles fine but only
yields values if the client passes varargs to addon chunks — a loader question,
separate from this syntax rewrite.
* feat(lua): provide addon-args so file-scope `local name, ns = ...` works
Modern addons open files with `local name, ns = ...` — the addon name plus a
per-addon shared namespace table, passed by the loader as the chunk's varargs.
Vanilla 1.12 never passed those (its main chunk has no `arg`), so with the
`...` backport in place the idiom resolved to `unpack(nil)` and errored. This
supplies the args ourselves.
In the luaL_loadbuffer hook, for an addon-file chunk (chunkname
`@Interface\AddOns\<Name>\...`, parsed case-insensitively) that uses a real
`...`, prepend a chunk-local `arg = {"<Name>", __addonns("<Name>"), n=2}`. The
existing `... -> unpack(arg)` pass then makes `local name, ns = ...` yield the
name and the namespace table. The preamble is newline-free (line numbers
preserved), placed after any UTF-8 BOM, and only injected for AddOns\ chunks
(FrameXML and loadstring are untouched); the addon name is rejected if it
contains characters that would break the string literal.
`__addonns(name)` returns the per-addon table — created once and returned
identically for every file of the addon (backed by a name->table map in the
Lua registry), matching modern WoW's shared second vararg. Registered in-game.
Verified in-game: an addon file's `local name, ns = ...` yields
`("<AddonName>", <table>)` with `ns == __addonns(name)` (shared across the
addon's files). File-scope `...` was the last piece; the in-function case was
already handled by the `...` pass.
* feat(lua): add C_AddOns.GetAddOnLocalTable(name)
Public alias of the addon-args namespace: returns the same per-addon table the
`local name, ns = ...` idiom yields — create-once and shared across every file
of the addon, backed by the same registry map as the internal `__addonns`
(both call Script_AddonNS). Lets code fetch an addon's namespace by name.
Registered via RegisterTableFunction on C_AddOns (non-destructive; coexists
with the existing C_AddOns.* functions regardless of module init order).
Currently ungated — it returns a table for any name, create-on-demand. TODO #99
records the follow-up to match retail: return nil unless the addon is loaded
AND its TOC declares `## AllowAddOnTableAccess: 1`, gating only this public
entry point while leaving the internal preamble path ungated.
* feat(lua): gate C_AddOns.GetAddOnLocalTable behind loaded + TOC opt-in
GetAddOnLocalTable was a raw alias of the addon-args namespace accessor:
it returned any addon's private table by name, loaded or not, with no
access control. Retail (11.0) gates this -- one addon reads another's
local table only when the target opts in via the `## AllowAddOnTableAccess`
TOC directive. Mirror that.
The public accessor now lives in addons/LocalTable.cpp and returns the
table only when the named addon is loaded (FUN_ADDON_IS_LOADED, by-name)
AND its .toc declares `## AllowAddOnTableAccess: <nonzero>` (scanned via
FUN_FILE_READ, read as a TOC boolean flag). Either check failing returns
nil. Directive spelling and function name both verified present in the
1.15.8 Classic Era binary.
The internal preamble path (an addon receiving its OWN table via the
injected `local _, ns = ...`) stays ungated -- an addon never needs
permission for its own namespace. Both paths now resolve to the same
per-addon table through LuaSyntax::PushAddonNamespace (AddonNamespace.h),
the single owner of the registry-backed name->table map.
Also close the bypass in the `__addonns` global itself. The map lives in
the Lua registry (unreachable from Lua -- this build ships no
debug.getregistry / debug introspection), so `__addonns` was the sole
Lua-visible door, and it was ungated. It is now context-gated: it answers
only while an addon's own chunk is mid-load, for its own name, one-shot.
At runtime it denies every name. Verified safe against the loader: the
addon file loader is strictly per-file load-then-run
(FUN_006edb90 -> FUN_006ede10 -> FUN_00704bc0 -> FUN_00704ae0, where
luaL_loadbuffer is immediately followed by lua_pcall), so nothing runs
between the grant being set and the preamble consuming it.
Net result: the only runtime path to another addon's local table is the
TOC-gated GetAddOnLocalTable.
* fix(lua): close the __addonns loadstring-forgery vector
The addon-args grant (`g_loadingAddon`) that lets a chunk's injected
preamble fetch its own namespace via the `__addonns` global was armed
whenever luaL_loadbuffer saw an `Interface\AddOns\...` chunkname with a
`...`. That chunkname is forgeable: `loadstring(s, chunkname)` takes a
caller-controlled chunkname (arg 2) and compiles WITHOUT running, so
loadstring("return ...", "@Interface\AddOns\Victim\x")
__addonns("Victim") -- returned Victim's private table
armed the grant and leaked another addon's local table, with no
`## AllowAddOnTableAccess` opt-in.
Fix: arm the grant only when the loadbuffer call comes from the engine's
immediate-run file funnel FUN_00704AE0 (it pcalls the chunk right after
compiling, so the preamble consumes the grant before anything else runs).
The hook checks `_ReturnAddress()` against RET_LUA_FILE_COMPILE
(0x00704B11, the instruction after that funnel's `call luaL_loadbuffer`).
`loadstring` (FUN_00703280) and `RunScript` (FUN_00704C70) call from
different return addresses, so neither can arm — even a loadstring nested
inside a RunScript body that itself runs through the file funnel. The two
callers that DO reach 0x00704B11 (FUN_00704bc0 DoFile, FUN_00704cd0
inline-XML-script) both supply engine-built chunknames, not caller data.
Verified in-game: forged loadstring compiles but yields nil.
Also fix two lexer/scan bugs found in review:
- SkipNumber treated e/E as an exponent marker in hex literals, so
`0xE-1 % 2` lexed `0xE-1` as one token and rewrote to __mod(0xE-1,2)
(=1) instead of 0xE-(1%2) (=13). Hex literals now use p/P only.
- The addon-path marker matched a backslash separator only while its
own terminator scan accepted both; it now matches `addons\` or
`addons/`, consistent with addons/Embedded.cpp.
* refactor(addons,lua): dedup CI helpers, share TOC scan, table-driven toggles
Review cleanups, behavior-preserving:
- Drop the hand-rolled LowerAscii/EqualsCI copies in luasyntax/Transpile.cpp
and addons/LocalTable.cpp for `_stricmp`/`_strnicmp` (the codebase norm).
- Add addons/Toc.h `FindValue(buf, size, directive, ...)` — the `## Key:`
line-start scan in one place. Embedded.cpp (Version) and LocalTable.cpp
(AllowAddOnTableAccess) both consume it; the file-read stays per-caller
since Embedded's is entangled with its disk-vs-embedded decision.
- Collapse the six per-switch transpile toggle functions to a {name, bool*}
table plus one `_classicapi_SetTranspileOption(name, bool)` /
`_classicapi_GetTranspileOption(name)` pair (name = Length / Modulo /
VarargExpansion). Nothing outside Transpile.cpp referenced the old names.
* feat(addons): load multi-flavor addons via _Vanilla/_Classic TOC selection
Modern addons target several game flavors from one folder by shipping
`<Name>_Vanilla.toc` / `_Mainline.toc` / `_Cata.toc` / … and frequently no
plain `<Name>.toc`. Vanilla 1.12 only ever opens `<Name>\<Name>.toc`, so such
an addon never registers -- it is invisible, not merely mis-loaded.
Backport the retail client's flavor-file selection at the file-read layer.
The scan's TOC parser FUN_0051C9B0 reads Interface\AddOns\<Name>\<Name>.toc
via FUN_FILE_READ (0x00648620) and registers the addon only if that read
succeeds; the load pass and GetAddOnMetadata read the same path. We already
co-hook FUN_FILE_READ for the embedded addon, so FileRead_h now calls
AddOns::FlavorToc::TryHandle in its non-!!!ClassicAPI branch: for a base-TOC
read it probes <Name>_Vanilla.toc then <Name>_Classic.toc via the original
reader and serves the first that exists in place of the base (the parser
passes outSize=NULL, so it just forwards args with a different path).
Precedence mirrors retail: flavor wins over an existing base, and _Vanilla
beats _Classic. Does NOT fall back to _Mainline/_Cata/etc -- an addon shipping
only those doesn't support vanilla and stays unlisted. Folder enumeration
already lists flavor-only folders, so only the TOC read needed redirecting.
Verified in-game: a folder with only FlavorTest_Vanilla.toc registers and
loads; GetAddOnInfo returns the _Vanilla title/notes.
* feat(addons): prefer _Turtle.toc flavor on Turtle-lineage clients
Extend multi-flavor TOC selection with a _Turtle.toc suffix, a ClassicAPI
extension (not a retail flavor) for addons targeting Turtle's server content.
Probe order becomes _Turtle -> _Vanilla -> _Classic, with _Turtle offered
first and only when Turtle::Detected() is true, so stock 1.12 never prefers
Turtle-only code.
The redirect fires at both the registration scan (glue/char-select) and the
in-world load pass, which must select the same flavor -- so detection has to
read consistently at glue-scan time and in-world. The in-world signal
(TURTLE_WOW_VERSION, engine-set) is absent on the glue state, so Turtle::Detect
now also recognizes Turtle's glue-time TURTLE_* GlueXML string globals
(AUTH_TURTLE_WEBSITE / TURTLE_ARMORY / TURTLE_KNOWLEDGE_DATABASE, set in
GlueStrings.lua at glue boot, before the scan). Clones keep those names and
only rebrand the URL values, so name presence is clone-robust where realmList
is not. Detected() now latches on either signal and works in both states;
Version() still fills from TURTLE_WOW_VERSION once in-world.
Verified in-game: a folder shipping only FlavorTest2_Turtle.toc registers and
loads on Turtle (GetAddOnInfo returns the _Turtle title), while the earlier
_Vanilla-only test still works.
* feat(addons): narrow flavor TOC selection to _Turtle + _ClassicAPI
Drop `_Vanilla`/`_Classic` from the flavor probe list. Those are the 1.15
Classic Era client's suffixes -- a modern engine with the full modern API and
modern FrameXML templates. Adopting them told a multi-flavor addon "I'm 1.15",
so its `_Vanilla` build would assume APIs/templates this 1.12 + partial-backport
client doesn't fully have, load, and then break. A clean non-load is better.
Select only the two flavors that describe THIS environment, most specific first:
_Turtle -- Turtle client/content, only when Turtle::Detected();
_ClassicAPI -- 1.12 + ClassicAPI, always (ClassicAPI is present by
definition -- it is the code doing the redirect).
Both are ClassicAPI conventions the addon author opts into, not an attempt to
impersonate a retail flavor. If neither exists, TryHandle returns false and the
caller does the normal base read, which chains through any other FUN_FILE_READ
hooker before reaching the engine.
Verified in-game: a folder with only `<Name>_ClassicAPI.toc` registers/loads; a
`_Turtle`-only folder registers on Turtle; a `_Vanilla`-only folder no longer
registers (correctly, now that `_Vanilla` is not a selected flavor).
* feat(addons): backport per-line TOC directives (conditions + variables)
Single-TOC multi-flavor addons gate individual file-reference lines and
expand path variables:
[Family]\Init.lua -> Classic\Init.lua
Vanilla.lua [AllowLoadGameType vanilla] kept
Mainline.lua [AllowLoadGameType mainline] dropped
Localization\[TextLocale].lua -> Localization\enUS.lua
Vanilla 1.12's TOC readers understand none of it: the scan parser
FUN_0051C9B0 only parses `##` metadata, and the load pass FUN_006edb90
hands each file line to FUN_006ede10 verbatim, where a trailing ` [...]`
breaks the extension check so the file silently never loads.
New module AddOns::TocRewrite rewrites the TOC buffer at the FUN_FILE_READ
chokepoint (alongside FlavorToc/Embedded), so the engine's own load loop
sees clean paths and both parsers are covered by one edit.
On this client the tokens resolve to: [AllowLoadGameType] keeps iff the
list has `vanilla`; [AllowLoadTextLocale] keeps iff it has the client
locale; [AllowLoad] keeps `game` and drops `glue`; [Family]->Classic,
[Game]->Vanilla, [TextLocale]->the client locale code. Locale comes from
VAR_LOCALE_NAME_TABLE (0x008558A4), the exact source Script_GetLocale
reads, so it matches GetLocale() byte-for-byte.
Gated to ...\AddOns\...\*.toc reads (a .lua `t[1]` would otherwise be
mangled); bracket-free TOCs stay zero-copy via a memchr bail; a rewritten
TOC goes into a fresh Storm buffer the engine frees like its own. Unknown
conditions fail safe (drop the line); gated-out lines become `#` comments.
Verified in-game on Turtle: 8 keep-cases loaded, 4 drop-cases (bare
mainline, glue, deDE, unknown keyword) did not.
* docs: document the branch's Lua 5.1 and TOC compatibility features
User-facing docs for the feat/lua-syntax-transpile branch.
docs/API.md:
- New "Lua 5.1 syntax: length, modulo, and vararg" section: the source
rewrite for `#`, `%`, and `...`-as-expression; what each form becomes
(`#` = border, ignores table.setn; `%` = 5.1 sign-of-b, contrasted with
math.mod); the `local name, tbl = ...` addon-args idiom; limits
(string/comment safety, first-close long-bracket matching, preserved
line numbers) and the diagnostic kill-switch.
- New "getfenv / setfenv environment protection" section: the 5.1
`__environment` metatable field, with the `__fenv` fallback noted.
- New "Conditional and multi-flavor TOC loading" section under AddOns:
`_ClassicAPI` / `_Turtle` flavor file selection and per-line
`[AllowLoadGameType]` / `[AllowLoadTextLocale]` / `[AllowLoad]`
conditions and `[Family]` / `[Game]` / `[TextLocale]` path variables,
with the token resolution table and limits.
- Table-of-contents entries for all three.
README.md:
- Add C_AddOns.GetAddOnLocalTable to the AddOns calls row (was missing).
- Add three rows to the Behaviors table (Lua 5.1 syntax, Lua 5.1
environment protection, multi-flavor & conditional TOC loading), each
linking to its API.md section.
* feat(addons): accept multi-flavor `## Interface:` version lists
A retail TOC can list several interface versions on one line
(`## Interface: 120100, 50504, 38002, 20506, 11200`). Vanilla's parse is a
plain atoi (FUN_0064ade0) that reads only the first number into entry+0x1C,
and the loadability resolver FUN_0051e780 compares that to the client
version FUN_0051d7d0() (0x2BC0 = 11200): a mismatch is the OUT_OF_DATE
reason that blocks loading while checkAddonVersion is on. So a list whose
first entry isn't 11200 never loads even when 11200 appears later in it.
TocRewrite now special-cases the `## Interface:` line: parse the whole
list, and if the client version (read live via
FUN_ADDON_CLIENT_INTERFACE_VERSION, not hardcoded) is present but not
first, rewrite the value to that single number so the engine stores 11200
and marks the addon compatible. A list without 11200 (or already leading
with it) is left verbatim, so it stays out of date exactly as before. The
fast-path gate widened to `[` or `,`; the content-compare bail keeps
comma-bearing TOCs (e.g. `## Dependencies: A, B`) zero-copy.
Docs (API.md, README.md) describe the behavior and the 11200-only
compatibility rule.
Verified in-game on Turtle: GetAddOnInfo on an addon listing
120100,50504,38002,20506,11200 returned no reason (loaded); the ...,11509
control returned INTERFACE_VERSION (out of date).
* feat(addons): honor ## LoadSavedVariablesFirst
Modern addons use `## LoadSavedVariablesFirst: 1` so their SavedVariables
are restored before their Lua runs, letting file-scope code read config.
Vanilla always runs an addon's files first, then loads SavedVariables,
then fires ADDON_LOADED (verified in FUN_0051f240), and never parses the
directive — so file-scope SV is always nil.
New module AddOns::SavedVarsFirst co-hooks the per-addon file loader
FUN_ADDON_LOAD_FILES (FUN_006edb90). For an addon whose TOC declares the
directive, it loads the SavedVariables first, mirroring the engine's own
path construction two steps later:
account : WTF\Account\<account>\SavedVariables\<Name>.lua
per-char: WTF\Account\<account>\<realm>\<character>\SavedVariables\<Name>.lua
(falling back to the realm-less path)
account = *VAR_ACCOUNT_NAME_PTR, realm = FUN_GET_REALM_NAME, character =
FUN_GET_LOGIN_ACCOUNT_NAME (whose offset label is a misnomer — it is the
character name). Then it calls the original so the files run with SV
present. FUN_FILE_EXISTS picks the same per-char variant the engine would;
FUN_LUA_LOAD_FILE no-ops on a missing file.
v1 caveat (documented): the engine still runs its own SV load right after
the files, so a file-scope READ works but a file-scope WRITE is overwritten
before ADDON_LOADED. Writes belong in an ADDON_LOADED handler, as usual.
Docs: API.md "SavedVariables loaded first" + a README behaviors row.
Verified in-game on Turtle (login -> /reload): flagged SVFirst saw its DB
at file scope (sawAtFileScope=true), control SVNormal did not (false).
* feat(addons): suppress the redundant SavedVariables re-load (LoadSavedVariablesFirst v2)
v1 loaded a flagged addon's SavedVariables before its files, but the engine
still ran its OWN SV load right after the files — overwriting any value the
addon wrote to its SavedVariable at file scope before ADDON_LOADED.
v2 co-hooks FUN_LUA_LOAD_FILE and skips that one redundant re-load per
pre-loaded path: RunLuaFile loads each SV via the trampoline (bypassing the
hook) and records its full path; LuaLoad_h matches the engine's imminent
FUN_00704bc0(svPath, 0, 0) (case-insensitive, one-shot erase) and returns 0
without loading. The SV-load call sites ignore the return and the SV file
feeds nothing into the TOC checksum, so the skip is side-effect-free.
FUN_00704bc0 loads files only (RunScript runs strings through a different
path), so the extra hook is a cold addon-load-time path.
Now file-scope reads AND writes both survive — matching true
LoadSavedVariablesFirst. Docs (API.md) drop the write-clobber caveat.
Verified in-game on Turtle (fresh SavedVariables, repeated /reload): flagged
SVFirst's file-scope write persists (runs counter climbs 2, 3, 4), control
SVNormal stays 1.
* feat(addons): flavor-specific addon Bindings (Bindings_Turtle/_ClassicAPI.xml)
The Bindings.xml analog of FlavorToc. A modern addon may ship a
flavor-specific keybinding file instead of / alongside a plain
Bindings.xml. Vanilla only ever builds Interface\AddOns\<Name>\Bindings.xml,
gates it on an exists-check (FUN_00648a30), and — only then — loads it via
FUN_004b6f70, which reads through FUN_FILE_READ. So flavor selection needs
two pieces (a FileRead redirect alone can't help a flavor-only addon,
because the exists-check is on the base name):
- AddOns::FlavorBindings::TryHandle, called from the FUN_FILE_READ hook
after FlavorToc: for a …\AddOns\<Name>\Bindings.xml read, serve a flavor
variant if present (flavor wins over a plain Bindings.xml). Probe order
Bindings_Turtle.xml (Turtle only) -> Bindings_ClassicAPI.xml.
- A co-hook on FUN_FILE_EXISTS: report Bindings.xml as existing when the
base is absent but a flavor variant is present, so the loader runs for a
flavor-only addon. Non-Bindings paths pass straight through.
Suffixes are _Turtle / _ClassicAPI, never _Vanilla / _Classic (a _Vanilla
bindings file pairs with the 1.15 build we don't load, so its handlers
wouldn't exist). Docs: API.md flavor section + README behaviors row.
Verified in-game: on Turtle all three cases load (flavor-only ClassicAPI,
flavor-only Turtle, flavor-over-base with the flavor winning); on stock the
Turtle-only one correctly drops while the ClassicAPI ones still load.
* feat(lua): backport 5.1 hexadecimal number literals via source transpile
Lua 5.0's lexer reads only decimal digits + one '.' + 'e' exponent, so a
`0x...` literal is a compile error (hence addons resort to
`tonumber("0x...", 16)`). Lua 5.1 added hex literals. As with `#` / `%` /
`...`, we rewrite the SOURCE at the luaL_loadbuffer chokepoint: each hex
INTEGER token becomes the exact decimal it denotes (unsigned), which 5.0's
lexer accepts and reads as the same double 5.1 would.
RewriteHex runs first in the transpile pipeline, gated on a "0x"/"0X"
presence scan; it reuses the tokenizer (so strings/comments are never
touched) and inserts no newlines (line numbers preserved). Hex floats
(0x1.8p3) and > 64-bit literals are left as-is — vanishingly rare, and they
fail exactly as today (no regression). Also fixed SkipNumber to stop a
number at a `..` so `0xFF.."x"` (hex then concat) tokenizes cleanly.
Toggle: _classicapi_SetTranspileOption("HexLiterals", false).
Docs: API.md "Lua 5.1 syntax" section + README behaviors row.
Verified in-game (19/19 harness asserts) and cross-checked against retail:
0xFF->255, 0xFFFFFFFF->4294967295, bit.band(0xF0,0x0F)->0, "0xFF" untouched
all match modern WoW exactly.
* feat(frame): enable modern positional script args by default
Modern handler signatures — `function(self, delta)` / OnEvent
`(self, event, ...)` — are core Lua 5.1 behavior, so flip Frame::ScriptArgs
on by default instead of opt-in. Ports that use them now work with no
`SetModernScriptArgs(true)` call.
It's purely additive (the `this`/`arg1`/`event` globals are still set, so
vanilla-style handlers keep working). `SetModernScriptArgs(false)` remains
the escape valve — it reimplements the tail of the engine's hottest Lua
path (fires for every OnUpdate frame), and disabling it makes both runners
a straight passthrough to exact vanilla dispatch.
Docs + code comments updated from "default OFF (opt-in)" to "default ON".
* docs: surface modern script-handler arguments as a behavior
Add a README Behaviors-table row for the now-default modern positional
script arguments (function(self, delta), OnEvent (self, event, ...)),
alongside the Lua 5.1 syntax row. The SetModernScriptArgs / GetModernScriptArgs
functions stay in the Frame calls table as the off-switch.
* fix(lua): correct transpiler lexer edge cases and operator env-independence
Review findings against the Lua 5.1 syntax transpiler:
- Tokenize `.`/`..`/`...` as multi-char tokens like Lua's own lexer, so a
`...` vararg adjacent to a `..` concat (e.g. `x .. ...`) is recognized
instead of forming an unsplittable five-dot run that left `...`
un-rewritten and failed to compile. Guard the `#`/`%` field-access check
to a single-char `.` so `a..b` isn't misread as `a.b`.
- Nest level-0 `[[ ]]` long brackets in SkipLongBracket to match the engine's
own long-string reader (FUN_00700010 keeps a nesting counter). First-close
matching mis-identified nested-string boundaries and could rewrite `#`/`%`
bytes the parser treats as string content.
- Capture `__len`/`__mod`/`unpack` as chunk-locals in the load-time preamble
so the lowered `#`/`%`/`...` operators resolve under a setfenv sandbox with
no _G fall-through, mirroring real 5.1's environment-independent operators.
- Skip precompiled bytecode (0x1B chunk signature) instead of tokenizing it
as source and corrupting the chunk.
- Cap parse recursion at 200 (Lua's LUAI_MAXCCALLS) so a pathologically
nested chunk fails to compile cleanly instead of overflowing the C stack
inside the hook.
- Case-fold the addon-namespace map key in PushAddonNamespace so a
case-mismatched C_AddOns.GetAddOnLocalTable request lands on the addon's
real table instead of minting a fresh empty one.
The `.. ...` vararg and nested-long-bracket fixes verified in-game via
_classicapi_TranspileLength.
* fix(addons): gate LoadSavedVariablesFirst pre-load on the declared scope
LoadSavedVarsEarly chose which SavedVariables files to pre-load from file
existence alone, but the engine loads the account file only when the addon
declares `## SavedVariables` and the per-char file only when it declares
`## SavedVariablesPerCharacter`. So a stale file for a scope the addon no
longer declares got executed early (Lua the engine never runs) and queued in
g_pendingSuppress, which the engine then never drained — a leak of one entry
per stale file per /reload.
Mirror the engine: read the TOC once (ReadSvFlags, replacing
TocWantsSavedVarsFirst) for the reorder flag plus whether each SV scope is
declared, and load each file only when its directive is declared and the file
exists. Every suppress entry we queue is now a file the engine re-loads and
drains.
* fix(turtle): only trust glue markers on the glue Lua state
Probe() checked the `TURTLE_*` glue markers whenever detection wasn't yet
latched, on whatever Lua state was current — including in-world. Those names
are set by Turtle's GlueXML and are only trustworthy on the glue state; in
world any loaded addon can define a global by one of them (a Turtle-UI port
shipping the strings, say), which permanently mis-latched Turtle detection on
a stock client and skewed flavor TOC/Bindings selection for the session.
Gate the marker probe on a `g_onGlue` phase flag driven by the engine's own
per-state script-registration hooks: the in-world ModuleAutoRegister (fires
before the addon load pass) clears it, each glue boot's GlueModuleAutoRegister
sets it. Neither reads a forgeable Lua global. Turtle still detects via the
markers at the glue scan and via TURTLE_WOW_VERSION in-world; a stock client
can no longer be latched by an in-world global.
Also make Version() return nullptr (not "") in the glue-detected-but-no-version
window, matching the header contract.
* revert MAX_CLASSES
* fix(frame): only pass positional script args to handlers that declare them
Default-ON modern script args changed behavior for every handler on the
engine's hottest Lua path, and the docs' "purely additive" claim was wrong:
a handler that DECLARES a parameter received a real value where vanilla always
passed nil.
Gate the reimplemented positional path on the handler's arity: a Lua closure
that declares a parameter or is vararg (function(self, delta) / function(self,
...)) takes it; a param-less handler (the vast majority of vanilla handlers,
which read this/arg1 globals) and a C-closure handler tail-call the original
engine runner unchanged. So param-less handlers are provably identical to
vanilla AND off the hot path (also the efficiency win: OnUpdate handlers that
gain nothing no longer pay the modern tail every frame). Only param-declaring
handlers observe the (self, [event,] arg1..N) shape.
Arity is read from the handler's Proto; offsets verified against the engine's
own luaD_precall (numparams @ +0x45, is_vararg @ +0x46), lua_dump, and
lua_iscfunction/lua_tocfunction (closure @ TValue+8, isC @ +6, Proto @ +0xC).
The param-declaring-vanilla-handler case (a function reused as both a direct
call and a handler) is inherently ambiguous and still gets the value; documented
honestly in ScriptArgs.cpp, docs/API.md, and README with SetModernScriptArgs
(false) as the opt-out. Verified in-game across both runners, both paths, the
toggle, and the caveat.
* refactor(addons): centralize engine-IO typedefs and CI string helpers
The `__stdcall` FUN_FILE_READ / FUN_FILE_EXISTS / Storm-allocator function
types were copied into ~8 places across the addon files, and Lower/EqCI into
three. These are ABI-critical: a copy declared __cdecl by mistake drifts ESP
per call and kills the process with no crash log. Hoist them to one home:
- new addons/EngineIO.h — FileReadFn / FileExistsFn / SMemAllocFn / SMemFreeFn,
used by Embedded, FlavorToc.h, FlavorBindings.h/.cpp, SavedVarsFirst,
LocalTable, TocRewrite.
- addons/Toc.h gains Lower / EqCI, used by FlavorBindings, SavedVarsFirst,
TocRewrite.
Also drop EvalCondition's dead `known` out-parameter in TocRewrite (nothing
read it — an unknown keyword already returns false). Pure refactor, no behavior
change.
* perf(lua): tokenize each chunk once and gate the #/% parse on an operator token
The transpiler ran on every compiled chunk at login/reload, and:
- RewriteHex / RewriteVararg / RewriteAll each re-tokenized the whole chunk, so
a file that trips more than one pre-check was lexed two or three times;
- RewriteAll's fast-bail was a raw memchr for '%', which is present in nearly
every chunk via format strings ("%d"), so almost every chunk paid a full
recursive parse only to discard an empty edit list.
New RunPasses tokenizes once and shares the stream across the passes, re-lexing
only after a pass actually rewrites the buffer (rare). RewriteAll now gates the
parse on an actual '#'/'%' OPERATOR token — a '%' inside a string is a TK_STRING
token, not a punct, so the format-string case skips the parse entirely.
RunPasses also unifies the previously duplicated RewriteChunk / LoadBuffer_h
pipelines. Output is identical (verified in-game via _classicapi_TranspileLength:
vararg-next-to-concat, nested long brackets, and a format-string vs operator '%'
all rewrite exactly as before).
* feat(lua): backport 5.1 leveled long brackets; fix top-level vararg fallback
Adversarial testing of the transpiler surfaced two gaps beyond PR 28:
- Leveled long brackets ([=[ ]=], [==[ ]==]) are the one 5.1 syntax
construct still missing. The 5.0 engine lexer has no =-level handling
(verified in FUN_006ff610), so they fail to compile. A new source-walking
pre-pass rewrites a leveled long string to [[body]] when the body is safe
(byte-exact, keeps the leading-newline strip) or to a quoted literal with
\-newline continuations otherwise, and blanks leveled long comments to
spaces. Line numbers preserved. Gated by the new LongBrackets toggle.
- Top-level ... outside the addon file funnel (RunScript, XML <OnLoad>,
loadstring) expanded to unpack(arg) and threw on nil arg, where 5.1
yields nothing. Non-addon vararg chunks now get a local arg={n=0}
fallback.
Adds a /capitranspile self-test suite (19 cases, all passing in-game) and
updates docs/API.md (also fixing a stale limits note that described plain
long strings as non-nesting: they nest by depth, matching the engine) and
README.
|
||
|
|
f2af2734f0 |
docs: trim internal implementation detail from FontString entries
User-facing API docs should describe the contract (behavior, inputs, outputs, errors, observable caveats), not how a method is built or which engine path it uses. Drop the "engine already computes this internally / only adds the binding / comes from the engine's own wrap math / reads what it last drew and compares" narration from the FontString entries, keeping every observable behavior and caveat (the setup requirements, the must-have-rendered-once note, the icon-inclusive widths, the <=1px rounding note). |
||
|
|
dc13d7bbfc |
fix(fontstring): SetFormattedText uses engine str_format, not _G
SetFormattedText resolved _G.string.format and called it, so an addon
that replaced string.format could hijack or break it. Push the engine's
own str_format C function instead (strlib "format" entry 0x007FD3D0,
verified by decode) and pcall it -- immune to global replacement, and
matching retail, whose SetFormattedText formats in C. Also simpler: one
PushCClosure replaces the _G table walk and its two failure branches.
Verified in-game: with both string.format and the format global replaced
by a stub, SetFormattedText("%d apples", 5) still renders "5 apples".
|
||
|
|
87acb70c5b |
feat(fontstring): add IsTruncated, SetMaxLines/GetMaxLines
Backport three FontString methods, each working WITH the engine's own text-layout machinery instead of reconstructing it: - IsTruncated(): did the engine cut the text off with an ellipsis? Reads render truth -- the built text node keeps a copy of the string it actually laid out (node+0x48), the ellipsized form on truncation -- and compares it to the source. Same "displayed vs full" check retail does (5.4.8 inner fn 0x0045E001). Re-calling the display-text resolver from Lua cannot work: it reads the laid-out rect (fs+0x64), which is zero between frames, so it never sees the bound. - SetMaxLines(n)/GetMaxLines(): cap the fontstring to n wrapped lines, ellipsizing the rest. Writes the engine's own per-fontstring maxLines field (fs+0x128, already honored by the truncation resolver) and re-invalidates the layout the way SetText does (drop caches, release node, notify region). Vanilla has no SetWordWrap -- the fs->layout flag translator exposes no no-wrap bit -- so SetMaxLines(1) is how you make a single-line, ellipsized label. Also correct a mislabeled bit in the inline-texture notes: fs+0x120 bit 0x1000 (gxu/node bit 0x40) is NON-SPACE-WRAP (what SetNonSpaceWrap toggles), not a dedicated "editable" flag. The inline-texture code uses it as an editbox proxy, which works because multi-line editors enable non-space-wrap while display text does not; the comments now say so, with the rare-edge-case caveat. Documentation only, no logic change. Verified in-game: IsTruncated true/false across bounded/unbounded boxes; SetMaxLines caps of 1/2/9/0 with matching GetNumLines and IsTruncated. |
||
|
|
92a959c381 |
feat(fontstring): backport GetWrappedWidth
The rendered width: the widest wrapped line -- the method that
completes the width trio (GetStringWidth and GetUnboundedStringWidth
both measure the string on ONE line; verified in-game they agree to
float noise). Uses the tooltip auto-size's own recipe: break positions
from FUN_FONTSTRING_BREAK_ARRAY, widest per-segment measure through
FUN_FONTSTRING_MEASURE_SUBSTRING -- both icon-aware through the
existing co-hooks. Segments are trimmed of the whitespace the wrap
consumed (the render never draws it, and a trailing space flips the
last real letter from ink to full-advance treatment, +~1.5px measured).
The wrap budget (shared with GetNumLines' unbuilt fallback via
WrapBudget) is rectWidth / fs+0x7C, calibrated EMPIRICALLY against the
render with a three-point probe on a 100px box at ~0.91 scale, using
text whose candidate lines measure 78.1 / 94.6 / 101.6 px:
raw rectW -> effective budget ~91px -> broke one word EARLY
rectW/scale^2 -> effective budget ~110px -> broke one word LATE
rectW/scale -> effective budget 100px -> breaks exactly where the
render does (94.6 <= 100 < 101.6)
All three observations fit budget_px = pxOf(param) x scale. A paper
derivation from the rebuild's node-budget chain predicted /scale^2 --
one hop of that chain models live behaviour wrong; the probe data is
recorded in the code comment so the broken paper chain doesn't get
re-derived. (FUN_00772B60 multiplying its width arg by fs+0x7C before
gxu, and FUN_0044DB50 normalizing through FUN_0041AE40, are verified
decompiles.)
Verified in-game: 100px box, wrapped 93.8 / one-line 165.7 / 2 lines,
break at the render's own position. Residual <=1px vs a direct measure
of the line text -- the engine's own per-glyph measure conventions
(ink-vs-advance, kerning-variant flag), the same class GetStringWidth
carries; documented in API.md.
|
||
|
|
efc6b29b6b |
docs(fontstring): correct GetUnboundedStringWidth vs GetStringWidth
The entry claimed GetStringWidth measures inside the wrap box -- it does not, on any client: both methods measure the string on ONE line (verified in-game: a fontstring wrapping in a 100px box reports ~165px from both). They differ only on modern clients and only for ellipsis-truncated text, where GetStringWidth reports the displayed width; 1.12's getter never applies truncation, so the two always agree here. The as-rendered width (widest wrapped line) is GetWrappedWidth, which 1.12 lacks. |
||
|
|
b09db4d5a5 |
feat(fontstring): backport GetUnboundedStringWidth, GetNumLines, GetLineHeight, SetFormattedText
Four modern FontString bindings 1.12 never shipped, all thin wrappers over engine machinery already verified in this codebase (fontstring/Metrics.cpp grows from the GetStringHeight backport into the general metrics module): - GetUnboundedStringWidth(): the substring measure (FUN_FONTSTRING_MEASURE_SUBSTRING) over the whole string (len 0). Icon-aware for free -- the call routes through the InlineTexture co-hook. Verified in-game it agrees with GetStringWidth to float noise, which is retail parity: both measure unwrapped (the classic gotcha; the rendered width is GetWrappedWidth, a future backport). - GetNumLines(): render truth from the node's built-line count (OFF_TEXT_NODE_BUILT_LINES = 0x9C, the draw builder's own counter / early-out gate) once painted; for an unbuilt node, the engine's break-array computer (FUN_FONTSTRING_BREAK_ARRAY = 0x00772B60, the tooltip auto-size's own segment source -- icon-aware via the wrap-stepper hook) against the fs's rect width. Empty text 0; no wrap constraint 1. Verified: 165px text in a 100px box reports 2. - GetLineHeight(): the fs font-height getter (FUN_007727b0) through the standard push conversion; excludes spacing, like retail. - SetFormattedText(fmt, ...): resolves the LIVE string.format (addon replacements honoured), pcalls it over the varargs, propagates format errors as real Lua errors, and sets through the engine's FUN_FONTSTRING_SET_TEXT so sanitizer/escape handling is identical to SetText. New Offsets entries carry the derivations; docs/API.md documents all four under the FontString section. |
||
|
|
67172c95f7 |
feat(model): add Model:SetCreature; dress character displays natively
SetCreature(creatureID) resolves through the client creature cache to a display ID, then loads like SetDisplayInfo (uncached entry = no-op, documented with a RequestLoadCreatureByID recipe). Character-based displays (extendedDisplayInfoID != 0) are now dressed by the engine's own CharComponent compositor, mirroring CGUnit_C::UpdateCharacterCustomization's NPC branch field for field: baked body texture, hair/facial-hair geosets (CharHairGeosets, CharacterFacialHairStyles), equipment geosets (sleeves, robe->trousers, tabard), and helm/shoulder attachment models with HelmetGeosetVisData hiding. Dress jobs run on WorldTick behind the engine's own model-loaded gate, one compositor per Model frame, kept until the frame loads another display or the reload teardown (PrepareForReload). Attached helm/shoulder children additionally get the frame's light/fog pre-render callback: the frame only registers it on its own instance, so the children rendered pure black (verified in-game -- a light tint colored the body but not the equipment). Weapons cannot show: NPC weapons are server-pushed per spawned unit, not in any client table. The manual baked-skin/hair-texture appliers are superseded by the compositor and removed, along with the geoset debug probes (_classicapi_ModelInstance/Peek/Poke). Creature::Info gains a public DisplayID(creatureID) for the cache resolve. |
||
|
|
6b13368e65 |
feat(fontstring): backport FontString:SetRotation / GetRotation
Generalizes the region-transform module (formerly texture-only) to serve the FontString method registry too, backporting the modern `fontstring:SetRotation(angle [, cx, cy])` and `GetRotation()`. Rotation is visual only, matching retail: GetStringWidth/GetStringHeight/ GetRect/SetPoint stay axis-aligned. A positive angle is CCW, same convention as Texture:SetRotation; the optional cx,cy pivot is a superset of retail (centre-only). How it works: the text paint copy-out (FUN_005c8710) is translate-only, so a rotation baked into the node-local glyph verts survives to screen. SetRotation rotates the live verts immediately (like the texture path) around the vert bounding-box centre, idempotently via an axis-aligned baseline snapshot (restore -> rotate). The baseline is re-captured on every fresh vertex bake, wired through inline-texture's DrawBuilder co-hook (gated on g_buildEmitSeq > 0 so clean paints never double-rotate, since inline-texture owns every text-render hook). Node page-buffer vertex layout added to Offsets.h (cross-verified across the emitter, FUN_005c8710, and FUN_005ce0c0). Known limitation: inline |T icons in a rotated fontstring don't turn with the text (separate anchored regions). Plain text rotates correctly. |
||
|
|
9b34ceff9e |
feat(unit): add UnitCreatureID(unit)
The unit-token twin of C_CreatureInfo.GetCreatureID — resolves the token to a GUID and reads the creature-template entry vanilla packs into bits 24-47. nil for players, empty tokens, and non-creature/pet GUIDs. Factor the entry extraction + creature/pet gate out of GetCreatureID into a shared Guid::CreatureEntry so both callers use one source of truth for the GUID bit layout. |
||
|
|
a373a775cf | Clarify UnitSpellTargetName docs | ||
|
|
e9014801b6 |
docs: move UnitSpellTargetName to the Unit section
It's a Unit* function taking a unit token, so it belongs with the other Unit calls, not under Spell. Relocates the API.md section + ToC entry and the README calls-table row. |
||
|
|
dc8a510611 |
feat(spell): add UnitSpellTargetName(unit)
Returns the name of the unit a caster is casting/channeling a spell at, or nil. The cast's target rides in SMSG_SPELL_START (SpellCastTargets: u16 mask + packed GUID when TARGET_FLAG_UNIT) — we already parse that packet for cast timing and just stopped before the target block. Extend the parse to capture the target GUID for the player (g_castTargetGuid) and remote units (RemoteCast.targetGuid), gated on an active cast so a stale target is never returned. nil when the unit isn't casting, the spell has no unit target (self/ground/item), or the target's name can't be resolved. Factor the GUID->name chain (object manager -> friends -> NameCache) out of UnitNameFromGUID into a shared Player::Info::NameFromGuid so both callers use one source of truth. |
||
|
|
621d1a9db9 |
feat(attributes): cast spell without a unit via CastSpellByName
A `type="spell"` click-cast button with no `unit` attribute did nothing: the `spell` verb bailed the moment no unit resolved. Now it reads the `spell` attribute first, then branches — with a `unit` it casts at that unit via C_Spell.CastAtUnit (unchanged), and with no `unit` it falls back to the plain global CastSpellByName on the current target, like `/cast`. Fixes #18. |
||
|
|
acc9a85bc6 |
feat(spell): CastSpellNoToggle accepts an optional unit token
CastSpellNoToggle(name | spellID [, unit]) now takes a unit token as an
optional second argument, so the spell fires at that unit without
changing the current target:
CastSpellNoToggle("Auto Shot", "focus")
CastSpellNoToggle("Shoot", "targettarget")
The spam-safe toggle gates run first and are unchanged: if the requested
spell is already auto-repeating or its self-aura is already up, the call
stays a no-op and the unit is ignored. When the spell does cast and a
unit is supplied, it dispatches through the existing Spell::AtUnit core
(resolve token -> GUID -> dispatch) instead of the plain CastSpellByName
-- a unit-target/auto-repeat spell fires straight at the unit, a ground
spell lands at its feet, and an unknown token raises the engine's
standard "Unknown unit" error. No new offsets or hooks.
Fixes #22.
|
||
|
|
207d47c8b8 |
feat(bindings): backport direct-action and override binding APIs (#19)
* feat(bindings): backport direct-action and override binding APIs
Add SetBindingSpell/Item/Macro/Click plus the owner-scoped
SetOverrideBinding family. Store permanent commands through vanilla
SetBinding, execute SPELL/ITEM/MACRO/CLICK in the resolved-command hook,
and layer priority overrides ahead of the native binding table.
Factor raw and saved macro dispatch into Macro::Execute so click
attributes and binding commands share the same parser fallback. Preserve
key-down/key-up pairing when overrides change during an action.
Document return values, persistence, precedence, macro-text usage, and
the deliberate 1.12 differences in README and docs/API.md.
* fix(bindings): normalize override key order and preserve command exec-context
Two fidelity gaps in the override binding layer, both verified against the
1.12 binary:
- Override key matching now normalizes modifier order to the engine's own
keypress form (ALT-CTRL-SHIFT- before the base key, per FUN_004b6630), so a
caller passing "CTRL-ALT-F" matches the "ALT-CTRL-F" the engine builds at
keypress. Prefix-stripping keeps the minus base key intact ("SHIFT--").
- Override-dispatched commands now run inside the same execution context the
engine wraps around a native keypress (save/zero/restore DAT_00ceeac0, its
nesting depth DAT_00ceeac4, and the manager +0xD8 mid-command flag, per
FUN_004b7990). Without it, an ordinary Bindings.xml command routed through
SetOverrideBinding ran without the context its handler expects. The native
binding-table path is untouched (the engine already establishes context
before the co-hooked FUN_004b7b50).
Adds the three verified offsets to Offsets.h and documents the any-order,
case-insensitive key handling in docs/API.md.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
76f48de67f |
Inline |T…|t texture escapes (with coin strings, texture methods, and TextureUtil) (#24)
* feat(text): inline |T...|t texture escapes in chat and display text
Backport modern inline-texture markup to the 1.12 text engine: |Tpath:h|t
renders an icon inline in FontStrings / chat, for BLP and uncompressed TGA.
- Rendering primitive: resolve a path to a resident CGxTexture via FUN_0044acf0
and draw it as a textured quad through the UI text VB path.
- Positioning: co-hook the per-line glyph emitter (FUN_005ccbe0); render plain
runs by delegating to the original per segment (threading the pen through
linkState[4], read as a float), record icon quads at the pen, and flush them
in the paint pass (FUN_005c8fe0) translated by each node origin. Handles the
FontString pipe-doubling (|T -> ||T), the bit-3 per-call batch-clear mode,
multi-icon and multi-line accumulation, and font-relative vertical centering.
- Measure/wrap: co-hook the shared tokenizer (FUN_005c2810) so an inline-texture
span is one near-zero-width token, so icons no longer force early line wrap.
- Editbox exclusion: read the focused-editbox global (DAT_00cf4dc8) and suppress
icon recording while an input field is focused, so editboxes show raw,
editable markup while cached display text keeps its icons.
Diagnostic scaffolding (stats/capture Lua helpers) is still present. Follow-ups:
exact icon width in measure (hover-box accuracy), texcoords for sprite sheets,
vertex color, and the already-built editbox case. See docs/InlineTextureEscapes.md.
* fix(text): exclude editboxes from inline textures via node flag bit 6
Editable text (node flags [+0x5c] bit 6 / 0x40 -- verified in-game: the macro
editbox is 0x4D vs chat display 0x20D and FontStrings 0x0D) now shows raw,
editable |T...|t markup instead of rendered icons, checked per node in the
tokenizer, emitter, and flush. This is the 1.12 analog of 4.3.4's per-render
texture-disable flag (tokenizer bit 0x1000).
Replaces the earlier focus-global-only exclusion, which only caught single-line
inputs that rebuild on each keystroke; bit 6 also covers multi-line editors
(the macro editor) that build once while un-focused. The keyboard-focus global
(DAT_00cf4dc8) is kept as a fallback. Removes the failed monochrome heuristic.
Diagnostic scaffolding remains; a docs update and cleanup pass follow.
* feat(text): inline-texture texcoords + fix vertical flip
- Add the width / offset / texcoord fields to the escape
(:width:offsetX:offsetY:texW:texH:left:right:top:bottom), so a sprite sheet
such as UI-RaidTargetingIcons can be cropped to a single cell.
- Fix a vertical flip: the UI device backend is OpenGL (bottom-left texture
origin), so top screen corners map to v1 and bottom corners to v0. The flip
was invisible on symmetric icons but obvious on directional ones (raid-target
markers, swords).
* docs(text): document the completed inline-texture RE map
Fold this session's findings into InlineTextureEscapes.md now that the feature
ships: the frame -> renderNode -> group -> node -> line render hierarchy;
segmented-delegation positioning (the float linkState[4] pen read, the bit-3
per-call batch-clear handling, first-line multi-line accumulation); font-relative
vertical centring; the FontString pipe-doubling (|T arrives as ||T); the shared
tokenizer measure/wrap fix; editbox exclusion via node flag bit 6 (0x40), with
the failed focus-global and monochrome attempts recorded so they aren't retried;
and the texcoord fields plus the OpenGL bottom-left vertical flip.
* chore(text): enable inline textures by default on this branch
* feat(text): inline-texture vertex colour tint (:r:g:b)
Parse the trailing r:g:b (0-255) positional fields of the inline-texture
escape and apply them as the quad's vertex colour, so |T...:r:g:b|t tints
the icon (the font stage's default MODULATE COLOROP does texture.rgb x
tint; white = untinted). The bytes pack to 0xFFrrggbb -- the same
0xAARRGGBB order the tokenizer builds for |cAARRGGBB text, verified from
FUN_005c2810's colour branch -- so the value flows straight into the
existing vertex colour slot. Threaded parse -> IconDesc -> IconRecord ->
DrawTexturedQuad. Verified in-game (red/green/blue/white diamonds).
Also record the hover-accuracy (measure-width) verdict in the docs: the
tokenizer reports an icon as ~zero width, so GetStringWidth/wrap/hit-test
undercount it. Scoped by disassembly (FUN_005c6940 width backend,
FUN_005c6b70 per-glyph advance, FUN_005cdc20/FUN_005c7260 wrap): the token
contract has no width field, there is no single cold choke, and the only
fixes are hot per-glyph hooks (against the MinHook-collision guidance) or
~6 parallel measure-loop hooks -- for a mostly-cosmetic gain. Deferred.
* docs(text): record editbox/measure findings; strip inline-texture debug scaffolding
No behavior change — functionally identical to the shipped inline-texture
feature. This captures what a long investigation established and removes the
temporary debug instrumentation added during it.
Comments (src/text/InlineTexture.cpp):
- The tokenizer's `flags & 0x40` gate is load-bearing for RENDER, not just
measure: a suppressed editbox delegates to the ORIGINAL emitter, which
re-enters the tokenizer to lay out glyphs, so bit 0x40 (EDITABLE) must make
the tokenizer stand down or the macro editor draws BLANK instead of raw.
- bit 6 (NodeEditable) and the focus global (InputFocused) are COMPLEMENTARY,
not redundant: bit 6 catches the un-focused macro editor; the focus global is
the only signal for single-line focused inputs (chat box, pfChatCopyBox),
whose nodes lack bit 6 (0x0D/0x20D, indistinguishable from display).
- Removed the tokenizer call/pipe/span counters and the ZZWIDTH TokCap capture
(debug-only), and the now-unused g_lastFocused/g_lastMono stats fields.
Docs (docs/InlineTextureEscapes.md):
- Editbox exclusion: two complementary signals, and VERIFIED against retail —
typing `|T` into a chat box or macro editor shows raw there too; only
addon/system text renders. Our editbox-raw + display-renders split matches.
- Measure gap: added the focus-time caveat (icon ~0 width unfocused; counts the
literal path text while an editbox is focused — the editbox-raw tradeoff).
- Vertex-colour tint documented in the descriptor-fields section.
* feat(chat): strip player-injected |T icon spoofs from chat + bubbles
Vanilla neutralizes player-TYPED escapes in chat (a typed |c/|H/|T shows
raw); only trusted text (addon AddMessage, shift-clicked links) renders
them. Our Text::InlineTexture backport broke that parity for |T alone: it
detects the neutralized ||T form and draws the icon anyway, so a player
could /say |Tpath|t and put a real icon in everyone's chat AND the speech
bubble over their head. This restores vanilla behavior for |T while leaving
|c/|r/|H/|h exactly as vanilla.
It can only be done at the chat source, not the text emitter: addon |T and
player |T reach the emitter as byte-identical ||T (vanilla doubles the
unrecognized |T for both), so the only place they differ is provenance --
server chat flows through the chat dispatcher FUN_0049A870, addon print does
not. That one function copies the message into a single buffer fed to BOTH
the chat frame and the say/yell bubble spawn (FUN_00608AC0), so sanitizing
on entry covers both. (ECX is the MESSAGE, not the "sender name" the old
note claimed -- verified from the call site in FUN_0049D560.)
Structure mirrors Net::PacketDispatch (one hook, fanned out), since MinHook
allows only one hook per target and this choke point already had the
GUID-capture concern on it:
- Chat::Dispatch -- single owner of the FUN_0049A870 hook; orchestrates
- Chat::IconFilter -- pure Sanitize(); no hook, no engine state
- Chat::CurrentGUID -- GUID globals + getter + DispatchScope RAII (no
longer owns a hook)
Defang detail (the subtle bit): the message arrives doubled (||T). Blanking
the PIPE would leave a lone `|` + space -- an INVALID escape the chat frame
tolerates but the bubble text setter chokes on, producing an empty bubble
that fades instantly. So we keep the `||` (a valid literal-pipe escape) and
blank the `T`; for a lone |T we blank both chars. No dangling `|`, no |T
opener survives. Verified in-game: typed |T shows raw in chat and bubble,
addon icons still render, colours and links untouched.
* feat(text): per-editbox inline-texture suppression
Inline-texture rendering was globally suppressed whenever any editbox held
focus (VAR_FOCUSED_EDITBOX != 0), so opening the chat box flipped every
rendered icon/emote in chat history to raw |T...|t.
Replace the global check with per-editbox buffer correlation: suppress inline
rendering only for text that belongs to the FOCUSED editbox, matched by
pointer range against its own text buffers. Chat history keeps rendering while
you type.
The editbox keeps its text in two buffers (both verified via Ghidra), and both
must be matched or the field desyncs (raw width but a rendered icon):
- INPUT buffer ([fe+0x32C]/[fe+0x334], selected by [fe+0x318]&8) — the
caret/width MEASURE path reads it in place (FUN_0077da80 -> FUN_00772ae0 ->
FUN_005c6940, which loops the tokenizer).
- DISPLAY buffer (*([fe+0x328]+0xF0)) — a SStrDup'd copy the editbox actually
RENDERS from (FUN_00771d80); the emitter node text and the re-entrant render
tokenizer see this one.
TextInFocusedEditbox() bounds each buffer by a tight strlen (distinct heap
allocations -> no false-match cap) and runs only on pipe-leading tokens after a
null-focus short-circuit, so it stays off the hot path. A display FontString
measured while an editbox is focused matches neither buffer, so its icons now
measure correctly -- an improvement over the old global.
Editbox struct offsets centralized in Offsets.h (OFF_EDITBOX_BUFFER_SELECT /
BUFFER / BUFFER_MASKED / TEXT_FONTSTRING).
* feat(chat): raid-target marker substitutions ({rt1}/{skull}/…)
Expand the modern raid-target marker tokens in chat into inline icons, backported
onto the inline-texture renderer. {rt1}..{rt8} plus the named aliases ({star},
{circle}/{coin}, {diamond}, {triangle}, {moon}, {square}, {cross}/{x}, {skull};
case-insensitive) each become a |T escape cropping Interface\TargetingFrame\
UI-RaidTargetingIcons to the matching 64x64 cell (mapping verified against the
client's UnitPopup.lua: col=(N-1)%4, row=(N-1)/4).
Chat::RaidMarkers::Substitute runs in Chat::Dispatch AFTER the |T anti-spoof
sanitize, so players get the fixed, safe marker icons without a path to inject an
arbitrary texture. It emits the pipe-DOUBLED ||T…||t form: the inline emitter
renders both, but this is what survives into speech bubbles — the vanilla bubble
text builder (FUN_004b1600) truncates a lone |T while preserving ||, and pfUI's
bubble reskin copies the bubble's FontString text into its own FontString, which
then renders the icon through the normal paint path. (This is the form bubbles
rendered before the anti-spoof filter defanged the ||T opener.)
InlineTexture emitter fixes for the standalone-FontString (bit-3, batch-clear)
render path that bubbles/tooltips use — chat lines are unaffected:
- Colour: clearing bit 3 switches the engine to per-glyph colour from
colorState=[node+0x2c], whose alpha byte is a stale ~0x07; force the glyph
alpha opaque (keeping RGB) so a FontString coloured via SetTextColor with plain
text doesn't render near-transparent (which showed only pfUI's dark outline =
"black text"). |c-coloured text already has full alpha, so it's a no-op for chat.
- Horizontal justify: the engine positions centre/right-justified text using the
MEASURED width, which counts inline icons as ~zero (the measure gap), so the
rendered line overflows its box. Pre-sum the line's icon widths and shift the pen
(half for centre, full for right) so text+icons justify as a unit.
- Default centerFrac 0.5 -> 0.6 (better vertical centring across chat + bubbles).
* fix(text): suppress inline textures in editboxes by content match
The per-editbox suppression missed the chat input box: a pasted `|T…|t` rendered
as an icon instead of raw markup. An in-game probe showed why — the editbox
renders its text through a TRANSIENT copy: same bytes as the input buffer, but a
distinct heap allocation with no pointer link to the editbox in either direction
(every offset/back-pointer scan of fe / its FontString / the render node came back
-1). So the prior pointer/node-identity checks (input buffer, SetText copy,
FontString +0x48, node == *(fe+0x328)) could never match the render.
Match on CONTENT instead:
- Emitter: EmitLineIsFocusedEditbox compares the render line's bytes against the
focused editbox's input buffer (the emitter is handed the whole line, so a
bounded strcmp identifies it). Chat-history lines differ, so their icons keep
rendering while an editbox is focused.
- Measure (caret/GetStringWidth): unchanged pointer path — the tokenizer reads the
input buffer in place, so TextInFocusedEditbox still matches by range.
- Re-entrant render: the suppressed emitter brackets its delegated raw layout with
a text range (g_reentryLo/Hi); the tokenizer stands down across the whole span
via TextInReentry, so `|T` isn't eaten as a zero-width token (which drew BLANK).
Drops the dead node-identity/second-and-third-buffer heuristics. Covers any focused
input (chat box, pfChatCopyBox, macro editor).
* fix(text): drop stale icon records for reused chat line FontStrings
Inline-texture icons could paint as a ghost strip at the bottom of the screen
after chat had been busy for a while. The chat frame reuses its line
FontStrings: when a line is cleared (text set empty) or reused for markup-free
text, the draw builder early-returns on it, so the emitter never runs — and so
never erases that node's old icon record. The paint flush still walked the node
and drew its now-stale record at the FontString's parked position.
Gate the flush draw on the node's LIVE text still containing `|T`: if a node has
an icon record but its current text has no markup, the record is stale — drop it
and skip drawing. Kills the bottom-of-screen ghost.
(The separate scroll-freeze — icons only refreshed on the chat's dirty repaints —
is a different, deeper issue tracked next.)
* fix(text): stop chat icons vanishing — suppress only input boxes, not editable chat display
pfUI renders the chat scrollback through EDITABLE nodes (flags 0x45: bit 6
editable, no bit 3). The inline-texture emitter's blanket NodeEditable gate
suppressed inline rendering for ALL editable nodes, so those chat icons blanked
whenever that display was live — during scroll and as messages arrived, which
read as icons "disappearing/reappearing."
Gate suppression on a true INPUT box instead: editable (bit 6) AND bit 3 (0x08).
Macro editor 0x4D and name/chat input 0xC8 all carry 0x08; the chat scrollback
0x45 does not — so real input boxes still show raw |T markup while the chat
display keeps its icons. Also drop the flush's NodeEditable draw-gate: a
suppressed input box never records, so any record reaching the flush is a real
display line.
Pointer/content match alone can't cover a focused input box because its render
form is pipe-doubled (||T) while the input buffer is single-pipe, so the compare
misses.
* feat(text): inline |T icons as fontstring-anchored engine regions
Port 4.3.4's CSimpleEmbeddedTexture model. Each icon the emitter records
becomes a pooled CSimpleTexture ANCHORED TO ITS OWNING FONTSTRING,
configured off-render on the WorldTick, and drawn by the engine's own
region pipeline. 1.12 chat lines are real CSimpleFontStrings (the
ScrollingMessageFrame display refresh FUN_00788750 drives one per visible
line), so a co-hook on CSimpleFontString::RebuildString (0x7724A0) maps
every text node to its owner and one mechanism covers chat, tooltips, and
standalone FontStrings.
This replaces the raw-GxU-quad renderer and every overlay attempt:
- engine-drawn regions keep their textures resident: no flicker, verified
across three concurrent clients
- the anchor system moves icons with their lines: scroll costs nothing
- icons mirror the owner's shown state: faded lines hide their icons
- all engine mutation happens outside the render pass: no pending-layout
corruption, survives /reload (pointers dropped in PrepareForReload)
- placement verified pixel-exact against owner rects
RE landmarks recorded in Offsets.h:
- fs+0xF8 is an HTEXTBLOCK handle; the text node is at handle+8
- Show (0x77FCB0) no-ops unless desired-shown (+0xC4) is set, and
SetParentAndLayer(show=0) clears it on reparent
- the renderer draws the corner array (+0xD4), stored from the rect by
SetTexCoord - realize (0x768060) must run between SetPoint and
SetTexCoord or the corners go stale (the historical invisible-icon and
frozen-top-left-icon bugs)
- pen coords are y-down from the owner fontstring's BOTTOM edge; anchor
offsets use Script_SetPoint's pixel scale (LinePool::PixelToInternal)
* refactor(text): inline |T icons = pixel-perfect quads + residency holders
Replace the fontstring-anchored region approach with a hybrid that
decouples position from residency, because the two live in different
coordinate spaces that no single scale could reconcile:
- POSITION: draw each icon as a raw GxU quad in the text engine's own
render space (pen + node origin), the same coordinate system and
dynamic VB the glyphs use. Pixel-exact by construction — no anchor/
layout-space conversion. This is the original quad math; the region
detour proved pen-space and anchor-space differ by the text paint's
projection, not a scalar, so region anchoring could never be exact.
- RESIDENCY: a raw quad binds an unowned texture the engine evicts under
VRAM pressure (the flicker on scroll / blank on a 2nd client). So for
each distinct texture path, Text::InlineTexturePool creates ONE managed
CSimpleTexture, draws it every frame (a ~2px, alpha 1/255 corner box),
and never touches it again — its engine-managed draw is the live
reference that keeps the texture resident for the quads to bind.
Verified in-game: icons pixel-perfect across chat / bubbles / wrapped
lines / sizes / tint, no flicker on scroll, and two concurrent clients
both render — the residency-holder premise (untested before: the earlier
"disproof" had non-drawing holders) finally validated with a holder that
actually draws. Non-zero holder alpha is load-bearing: a fully
transparent region gets culled and residency is lost.
Diagnostics (probe, perf counters, scale/bias tune knobs) stripped; the
SEH fault guard on the flush stays.
* feat(text): render inline |T icons as engine regions anchored to their fontstring
Replace the raw-quad + residency-holder hybrid as the default renderer with
the 4.3.4 CSimpleEmbeddedTexture model: one pooled CSimpleTexture per visible
icon, anchored RELATIVE TO THE OWNING FONTSTRING. Engine-drawn, so texture
residency (the chat scroll flicker / blank 2nd client) is impossible by
construction; engine-anchored, so icons track their line for free.
The pen<->anchor bridge that unblocked this: RebuildString (0x7724A0)
multiplies every text-unit quantity by fs+0x7C when creating the text node,
and the node origin is the fontstring's justification anchor point mapped by
a single measurable scale K (verified with two-position probes: origin =
rectJustifyRef x K, K ~ 1470 = physical px per anchor unit, both axes, no
drift). Placement pipeline:
- RebuildString co-hook records node -> owning fontstring (a node only
speaks for its fs while it IS fs+0xF8->block+8, killing the stale-node
clear race around rebuilds).
- The paint hook converts each icon's pen-space quad through K and queues
fs-relative placements; regions are keyed BY FONTSTRING (nodes die on
every SetText - node keying orphaned regions into an accumulating wall).
- Placements apply on WorldTick, never mid-render. SetPoint offsets are
divided by the region's effective scale (+0x7C; anchor resolution
multiplies stored offsets by the scale chain - measured 0.0319 stored ->
0.0290 resolved = x0.91), then converged exactly by a per-region rect
readback correction each tick (deterministic, self-healing; a same-call
readback read stale pooled rects and shipped 7.4px crests).
- Engine SetTexCoord (0x770410) takes the 4-float rect Y-FIRST INTERLEAVED
{v0,u0,v1,u1} (diagnosed in-game: {u,v,u,v} rendered the raid-mark moon
as the circle cell); it is absolute, and the +0x124 shrink-by-UV-span
flag stays clear so crops stretch to the rect like modern clients.
- Expired/hidden lines are swept every tick (regions parent to the chat
frame, not the line, so they cannot inherit the line's own hide).
The quad renderer and residency holders remain behind
_classicapi_InlineTexMode (0 = quads, 1 = regions [default], 2 = overlay
A/B) as the bring-up oracle, plus diagnostics (_classicapi_InlineTexProbeFS
/ RegionDump / RegionCal / HolderCfg). Calibrated residual: RegionCal
(3, -1) pen units.
* fix(text): apply the inline-icon LEAD pad at draw time
The emitter reserves w + 1.5x pad in every inline icon's advance (lead 1x,
trail 0.5x), but FlushLayout drew the icon at the raw pen - all reserved gap
landed AFTER the icon, none before. Mid-text icons looked balanced only
because their surplus trailing gap padded the following text; a string-FINAL
icon (the money-string copper coin) sat jammed against its digits, and the
locale format strings had grown per-coin offsetX hacks to compensate.
Draw at pen + w x iconPadFrac (quads and regions share the cx), matching the
emitter's reservation. The coin formats drop to zero offsets - verified
against the texture itself: the three coin arts in UI-MoneyIcons are
byte-identical in alpha (same bounds, same center of mass, measured from the
exported BLP's DXT3 data), so no coin ever needed a positional nudge.
RegionCal's baked x constant drops 3 -> 0: the +3 calibrated pre-fix was
exactly this missing lead pad (user re-calibrated (0,-1) post-fix). The 1px
y residual remains the pen->anchor map's one true constant.
* fix(text): make inline-icon state lifetime-exact; fix every scroll-landing loss
Chat icons randomly landed shown-or-hidden when lines scrolled, and stale
icons ghosted at parked positions. Root causes, each found by in-game
triangulation (FsDump/Broken/Stats diagnostics, included), all fixed:
- Placements are FS-RELATIVE, computed at PAINT time in one coherent
snapshot (icon coords + fs rect in the same flush). The old apply-time fs
rect read raced the chat relayout after SetText and parked icons off
their line, where the dedup froze them.
- The queue tail gate now matches the per-icon build gate EXACTLY (incl.
K); any not-ready input skips-and-retries instead of queueing {} - an
empty queue froze lines iconless via the dedup (early-session K window).
- K (pen->anchor scale) is derived PER NODE from its own fontstring - pen
space scales with each fs's frame-scale chain, so a global chat-derived K
mis-sized icons on differently-scaled fontstrings. Global cache kept as a
+/-10%-clamped fallback.
- Stuck-blockless fontstrings (RebuildString releases the block on a
SetText that lands on an unresolved rect and never rebuilds; the zombie
node keeps painting) are re-dirtied so the engine rebuilds - the icon
pipeline then resumes naturally.
- First-line-of-build detection comes from a draw-builder co-hook
(FUN_005CDC20) build stamp - exact - with the old text-pointer heuristic
only as fallback for emitter paths outside the builder.
- THE LIFETIME FIX: co-hook the gxu text-node free (FUN_005CD950, the
single site where every node dies and its address becomes reusable) and
erase ALL per-node state there. Anything in the maps now refers to a
live node by construction: inherited ghost records on recycled nameplate
fontstrings, orphaned owners (dropNoFs 61k -> 0), and reload leftovers
lose their mechanism of existence.
- Ghost guard rescans the FONTSTRING's text (fs+0xF0, proven trustworthy),
not the node text pointer (which lied on pfUI chat lines and made the old
scan erase LIVE records every frame - the persistent iconless LFG lines).
False matches can only false-keep, never false-erase.
- Freshness TTL: regions stay only while the paint keeps re-queueing their
fontstring (deduped touches count); parked/orphaned fs regions expire in
~1s. Do NOT build-version records against the builder counter - the
builder runs every paint but only emits when dirty, so a version check
erases good records on every clean paint (the all-icons-gone regression).
Diagnostics added (Lua): _classicapi_InlineTexFsDump (pipeline triangulation
with chain classification), _classicapi_InlineTexBroken (names the broken
lines), _classicapi_InlineTexStats gains queued/drop/nudge counters and the
SEH fault address.
Also removes the FrameTick glue-screen attempt (b164d68): hooking the UI
render root regressed in-world chat; glue-screen icon support will be
re-approached without touching the in-world render path. The
FUN_UI_RENDER_ROOT offset stays documented for that retry.
* fix(text): pointer probes must allow Large-Address-Aware heap (>2GB)
LooksReadable capped plausible pointers at 0x7FFF0000. This client is LAA
(VanillaFixes), so heap allocations above 0x80000000 are valid and routine
once the heap grows - and the flush's layout walk BREAKS on an "unreadable"
node, so a single high-heap node silently truncated the walk and every node
AFTER it in the layout list lost its icons. That was the irreducible random
per-ROW missing-chat-icon bug that survived every renderer architecture
since the guard shipped with the first inline-texture commit (
|
||
|
|
d366fec43e |
fix(attributes): restore the previous target after a macro click-cast
The `macro` verb selected the clicked unit and left it targeted (Clique's click-heal minus the restore). Snapshot the current selection GUID, retarget the clicked unit, run the macro, then restore the prior target via FUN_TARGET_BY_GUID (which validates the GUID and drops a stale one), or ClearTarget when there was no prior target. The macro's actions dispatch synchronously while the clicked unit is selected, so restoring afterward doesn't affect them. |
||
|
|
4d5fe8d41b |
feat(spellbook): add C_SpellBook.GetSpellBookItemInfo
Backport C_SpellBook.GetSpellBookItemInfo(slotIndex, spellBank) -> table, reusing Spell::Info's DBC reader. slotIndex is 1-based across the book; spellBank is Enum.SpellBookSpellBank (0 = Player, 1 = Pet), resolved via Spell::Lookup::SpellbookSlotToID. Returns nil for an empty/out-of-range slot, matching retail. Fields map from Spell.dbc: itemType is Spell (player) or PetAction (pet) - vanilla's book holds only real spells, so None/FutureSpell/Flyout never occur; actionID == spellID (no override system); name/subName from the localized Name/Rank; isPassive from Attributes; isOffSpec always false. iconID is the icon PATH string (vanilla has no fileID), the same deviation as C_Spell.GetSpellInfo.iconID; skillLineIndex is omitted. Also register the two Enum tables the return contract references (non-destructively, like the other Enum.* additions) so info.itemType == Enum.SpellBookItemType.Spell comparisons work: Enum.SpellBookSpellBank and Enum.SpellBookItemType. Document in docs/API.md (SpellBook section + both Enum entries) and list in README. |
||
|
|
783ffd05bf |
feat(aura): Carnage Rip/Rake refresh + signal duration-mod changes
Turtle's Carnage refreshes the caster's Rip and Rake off Ferocious Bite, behind a per-combo-point roll whose outcome the client only sees as the combo point the proc returns. A src/turtle/Carnage watcher arms on a Ferocious Bite send and confirms on the first combo-point rise, then refreshes the cached auras. Verified against tortoise-wow spell_druid_carnage: icons 108 (Rip) / 494 (Rake), family bits 0x800000 / 0x1000, caster scoping, and RefreshHolder (restore the aura's own applied duration). A cache duration edit has no engine packet behind it, so nothing re-fired UNIT_AURA and event-driven aura bars never saw the change. The trigger mods (ApplyMod) and the Carnage refresh now enqueue the affected unit, and the WorldTick flush re-broadcasts UNIT_AURA via the engine's own per-token signal (FUN_UNIT_EVENT_BROADCAST), deferred off the SMSG_SPELL_GO subscriber. Also move the two static Turtle duration mods (Conflagrate -> Immolate, Molten Blast -> Flame Shock) from Lua into src/turtle/DurationMods via a new C++ entry Aura::Source::AddDurationMod, and drop the now-unused exact-spellID RegisterAuraDurationModifier Lua export (RegisterAuraDurationModifierByTrigger stays for Shadow Weaving). Based on the approach from @fuffc in #15. Closes #15 |
||
|
|
f559eb4d07 |
docs(api): move UNIT_SPELLCAST_* events into the Events section, fix TOC link
The TOC entry pointed at #unit_spellcast_-events-player, but the heading generates #unit_spellcast_-events (no -player suffix) — broken link. Move both the TOC entry and the content block out of the Spell section and into the Events section where the other event docs live, and correct the anchor. |
||
|
|
f293653837 |
docs: clarify GetNumWhoResults second return is server-dependent
The second value's meaning varies by server core. Mangos/cmangos cores send the query match count; Turtle (tortoise-wow) sends the whole realm's online population whenever more than 49 players are online, ignoring the filter (verified against tortoise-wow MiscHandler.cpp: data.put(4, count > 49 ? count : clientcount), count = online players). Earlier wording claimed it was always the match total, which is wrong off Turtle -- confirmed by a Twinstar /who priest returning 15/15. |