mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 16:10:36 +00:00
718e5a31fe2f986aade5509b930d78c19f19efdd
175
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3e4db9279e |
perf(debugtools): stop the event trace churning memory
The trace kept 1000 entries under an index that only grows, so each of its 22 column tables rehashed and reallocated every few events. Entries now go into a ring of fixed slots. An event no longer redraws the list (OnUpdate redraws it once per frame while shown), packs its arguments into a table, or formats its time and marker text; that text is built when a row is drawn. /etrace clear now rebuilds all 19 argument columns. |
||
|
|
62cabb2acb |
Add the combat log: COMBAT_LOG_EVENT, filters and kept entries (#108)
* feat(combatlog): add COMBAT_LOG_EVENT and CombatLogGetCurrentEventInfo Port 4.3.4's combat log events (UnitCombatLog_C.cpp) in its argument layout: timestamp, subevent, hideCaster, source and dest GUID, name, flags and raid flags, then the spell prefix and the subevent suffix. - Swing, range, spell and periodic damage, misses, heals, energize, drain and leech, damage shields, split damage and environmental damage, read from the combat log messages through Net::PacketDispatch. - Spell misses from the one function every miss goes through, so a missile's miss is sent when it arrives. - Object flags and raid flags from the fields 4.3.4 reads. Names follow the 1.12 combat log namer's steps. - CombatLogGetCurrentEventInfo returns the values only while the events are being sent, as on Classic Era. - Event::Custom::FireValues sends an event with Lua values, so booleans and nils land where 4.3.4 puts them. - COMBATLOG_OBJECT_* constants in the addon. Overkill, overhealing and healing absorbs are 0: the server does not send them. * feat(combatlog): add casts, auras, dispels, interrupts and deaths Port 4.3.4's layer 2 combat log subevents: SPELL_CAST_START/SUCCESS/ FAILED, SPELL_AURA_APPLIED/REMOVED and their _DOSE forms, SPELL_DISPEL, SPELL_DISPEL_FAILED, SPELL_INTERRUPT, SPELL_EXTRA_ATTACKS, SPELL_DRAIN, SPELL_LEECH, SPELL_RESURRECT, SPELL_DURABILITY_DAMAGE(_ALL), SPELL_INSTAKILL, UNIT_DIED, UNIT_DESTROYED and PARTY_KILL, plus proc resists as SPELL_MISSED. Casts come from SPELL_START / SPELL_GO and the cast-fail log line, effects from SPELLLOGEXECUTE as the 1.12 client reads it, auras from the engine's aura handlers through a new Aura::Source change observer that carries the bound caster, and deaths from the death presentation. * feat(combatlog): add filters, kept entries and CombatLog_Object_IsA Port 4.3.4's UnitCombatLog_C_Scripts surface: CombatLogAddFilter / ResetFilter, the kept-entry functions (GetNumEntries, SetCurrentEntry, GetCurrentEntry, AdvanceEntry, ClearEntries), the retention time with its combatLogRetentionTime CVar, and CombatLog_Object_IsA. COMBAT_LOG_EVENT now fires only for entries that match the filters. Entries and filters clear on the return to the login screen. Adds the COMBATLOG_FILTER_* masks from 4.3.4's Constants.lua. * docs(combatlog): move the combat log events into the Events section * fix(combatlog): bound the execute-log loop and the retention time - Stop an execute log's target loop at an effect that carries nothing, so a huge target count cannot spin. - Clamp the retention time to what the wrap-safe age test can measure. - Bound GetCurrentEntry's index by the entry count. - List ENCHANT_APPLIED and ENCHANT_REMOVED among the subevents that do not fire, and note why effect 59 casts log SPELL_CAST_SUCCESS. |
||
|
|
fd7843b8b3 |
feat(aura): add RAID and CANCELABLE filters, fix stale player timers
Use the engine's own aura tests where C_UnitAuras guessed or gave up: - RAID calls the two tests behind UnitBuff/UnitDebuff's raid-filter argument (castable buff 0x4B3870, known dispel type 0x4B3920); isRaid reports the same answer. - CANCELABLE / NOT_CANCELABLE read the descriptor's cancelable bit. - PLAYER also counts a caster whose charmer or creator is the player (totems, guardians, charmed units), as 4.3.4's IsAuraCaster does. The charmer-or-creator read moves to Unit::Identity::OwnerGuid. - Filter tokens and spell-name lookups ignore case (SStrCmpI). - castByPlayer (UnitAura position 13) is a player caster only, as in 4.3.4; isFromPlayerOrPlayerPet keeps pets. - canApplyAura: the player or pet knows the spell and it applies an aura. - Player timers look up the buff record by slot and honour its until-cancelled flag, so a permanent aura no longer reads the stale expiry its slot kept from an earlier aura. Corrects the player-buff record and visible-aura comments in Offsets.h. |
||
|
|
9ab6627d90 |
feat(unit): add InteractUnit and the INTERACTTARGET / INTERACTMOUSEOVER bindings
InteractUnit(unit [, exactMatch]) is 4.3.4's Script_InteractUnit. It resolves the argument the way 4.3.4 does: - "mouseover" reads the hovered-object GUID, which in 1.12 is any object type (units, game objects, corpses). - A unit token resolves to its GUID. - Any other text runs the engine's by-name search with TYPEMASK_OBJECT. It then calls 1.12's own OnSpriteRightClick (0x00492820), the function a world right-click runs, so targeting, the object's right-click and the autoloot modifier all come from the engine. 4.3.4's taint gate is dropped because 1.12 has no secure environment. Both bindings are spliced into the TARGETING group, as in 4.3.4. Their names are added to every locale, using Blizzard's strings. |
||
|
|
90b4691130 |
fix(debugtools): show all 19 event arguments in the event trace
The event trace passed only arg1..arg9 from its XML OnEvent and kept nine argument columns, so it never showed arg10 that 1.12 already sends with every CHAT_MSG_*, nor anything after it. The engine sets at most arg1..arg19 for an event, so the trace now passes and stores all 19, with trailing nils marking the end as before. |
||
|
|
7cd891e86c |
fix(bindings): follow 4.3.4's bindings, modified clicks and key state
Modified clicks: IsModifiedClick, GetModifiedClick, SetModifiedClick, GetNumModifiedClickActions and GetModifiedClickAction, with 4.3.4's <ModifiedClick> Bindings.xml node and its 18 defaults. Each binding set loads, saves and copies them through co-hooks on the engine's own binding-set steps, in 4.3.4's "modifiedclick" file lines. [mod:] asks IsModifiedClick, as 4.3.4's macro conditions do. Direct actions run as 4.3.4's ExecKey runs them: SPELL / ITEM / MACRO on key release through 1.12's spellbook, item and macro functions, cast at you for SELFCAST and at your focus for FOCUSCAST; CLICK sends the frame a mouse down and up, with 4.3.4's virtual-click button logic built from the button's own methods. RunBinding no longer runs them. While a key binding runs, its own modifiers count as released for every modifier read, the engine's IsKeyDown included. Overrides follow 4.3.4: two lists per key, checked inside the key lookup at both of 1.12's lookup steps; GetBindingAction takes checkOverride; isPriority is loose; "" removes; the owner must be a frame. ActionButtonUseKeyDown (default 0) and 4.3.4's action-button key handlers, ported onto 1.12's bars. |
||
|
|
4b47059788 |
feat(debugtools): build /fstack with GameTooltip:SetFrameStack
Replace the Lua EnumerateFrames walk with the engine method, as Blizzard_DebugTools does. /fstack also accepts "true" for hidden frames. |
||
|
|
5962ccc83d |
fix(frame): follow 4.3.4's attribute system and unit-frame mouseover
Compared against 4.3.4's CSimpleFrame attribute code and CGWorldFrame::OnLayerUpdate: - OnAttributeChanged gets (self, name, value) as real arguments, like 4.3.4's RunOnAttributeChangedScript, plus the this/arg1/arg2 globals. It used to fire through the no-argument invoker with globals only, so a modern function(self, name, value) saw name == nil. The engine's runners only carry %d/%s values, so Frame::ScriptArgs gains RunWithValues for arguments already on the Lua stack. - No recursion guard: a handler that sets attributes fires their handlers too, as in 4.3.4. The guard silenced every nested OnAttributeChanged on every frame. - SetAttribute requires the value argument; the 3-arg GetAttribute form needs exactly four arguments and treats a nil prefix/suffix as empty; usage errors name the frame like the engine's (GetName ?: <unnamed>). - The mouseover unit of a hovered frame comes from FrameXML's SecureButton_GetModifiedUnit, pcalled under the engine's error handler, as 4.3.4 does, so unitsuffix and modifier-qualified unit attributes count. 4.3.4 asks protected frames; with no protection in 1.12 the analog is a frame that has attributes. The mouseover tooltip stays (4.3.4 shows it only over the world frame). - SecureStateDriver.lua is 4.3.4's file again: it drives itself through SecureStateDriverManager attributes and reads OnUpdate's elapsed, both of which the guard and the old no-argument handlers had ruled out. - Game::Lua::ObjectLuaRef / PushObject / ObjectDisplayName replace the copies in ScriptArgs and Modern. Verified in-game: handler arguments and globals, a nested handler firing, both usage errors, the nil-prefix lookup, mouseover following shift-unit / unit, and a visibility state driver. |
||
|
|
9d3bdfb6ad |
feat(focus): follow 4.3.4's focus, and give every unit event to focus, nameplates and marks
Every unit event the engine fires now reaches focus, nameplateN and
markN, as 4.3.4 does for its focus: the unit gets a script-registration
bit, so the engine watches its fields, and whatever the engine fires
for the unit fires for the token too.
- A co-hook on the registration recompute (FUN_0060c520) keeps bit
0x8000 on units with one of these tokens. Post-init runs it too, so a
unit coming back into range is watched again. 0x2000 is SuperWoW's
and WeirdUtils' sparkle bit on every unit.
- nampower replaces the broadcast (0x00515E50) and the combat feedback
(0x00494600) with detours that never call the original, so neither
can be co-hooked. Their 38 + 4 CALL/JMP sites, which no loaded DLL
touches, are redirected to functions that call the original address
and then fire for the unit's tokens. Sites are found by a .text scan
and patched only when the counts match Ghidra's xrefs.
- The tokens gain UNIT_COMBAT, UNIT_NAME_UPDATE, UNIT_PORTRAIT_UPDATE,
UNIT_MODEL_CHANGED, UNIT_CLASSIFICATION_CHANGED and group-stat
updates. TokenObserver now serves only focustarget: with SuperWoW
every unit is engine-watched, so an observer would double-fire.
Focus drop rules follow 4.3.4 where 1.12 has the data: out of range is
kept for you, your pet, a party or raid member or their pet (the
engine's own target rule); death while not friendly, or arrival already
dead and not friendly; becoming not selectable. Death and the flag act
on the change. 1.12 has no duel exception and no SMSG_BREAK_TARGET.
%f in sent chat (4.3.4's ChatParserParseText) becomes the focus's name,
with a {rtN} prefix when marked, or FOCUS_TOKEN_NOT_FOUND.
The .text bounds move into Offsets.h (shared with interface/Export).
The focus still survives /reload; focustarget events stay as a
ClassicAPI extension.
|
||
|
|
af4a379311 |
feat(equipmentset): follow 4.3.4's equipment manager
UseEquipmentSet now behaves like 4.3.4's CGEquipmentManager: - in combat only the weapon slots swap (one COMBAT_SWAP message); - missing items and full bags report through UI_ERROR_MESSAGE; - bank items are used only while the bank is open, and then equip straight from the bank; - a swap in flight or an item on the cursor refuses the call. EQUIPMENT_SWAP_FINISHED now fires when the swap settles instead of during the call: success when the paperdoll matches, failure on an SMSG_INVENTORY_CHANGE_FAILURE for one of the moved items, or when the paperdoll stops changing short of the target. Its failure value is nil, not 0. CanUseEquipmentSets and the set buttons are blocked meanwhile. GetEquipmentSetInfo uses 4.3.4's GetSetStatus counts and strict IsSetEquipped; GetItemIDs and GetItemLocations return all 19 slots with the 0/1/-1 markers; set buttons also grey when a replaced item is locked. Set names go through a port of ScrubString. Item tooltips get the "Equipment Sets:" line (dontShowEquipmentSetsOnItems hides it). |
||
|
|
721f32ac77 |
feat(map): keep the closed world map on the player's zone (#71)
* feat(map): keep the closed world map on the player's zone
GetPlayerMapPosition("player") reads the map the world map is set to,
open or closed, and returns 0,0 off it. The 3.x FrameXML resets that
map to the player's zone in WorldMapFrame_OnHide and in WatchFrame's
PLAYER_ENTERING_WORLD and (map closed) ZONE_CHANGED_NEW_AREA handlers;
vanilla has neither, so after zoning the closed map stays on the old
zone. Do the same resets from the bundled addon. Zygor Guides Viewer's
travel steps read the player's position this way.
Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
after logging in, the closed world map is on the player's zone (Darkshore)
and GetPlayerMapPosition("player") returns the player's position there.
Not checked yet: changing zones with the map closed (the
ZONE_CHANGED_NEW_AREA reset) and closing the map on another zone (the
OnHide reset).
* docs(map): describe the closed world map without version history
State what the map does and when it goes back to the player's zone,
and add that a zone change does not move the map while it is open.
Remove the 3.x and vanilla comparison and the FrameXML handler names;
the code comment in Util/WorldMap.lua already records them.
* docs(readme): keep Highlights for major features
Single-behavior fixes (faction while loading, <Script file> paths, the
closed world map, the quest completed line, SetParent frame levels,
frame alpha, OnSizeChanged sizes) each had a row in the Modern client
behaviors table. Remove those rows and point to docs/API.md, where each
fix keeps its own section.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
47b258ad95 |
fix(text): size, space and align inline icons by the engine's own rules
The inline-texture backport placed icons with hand-tuned constants: a 0.18 x font lead/trail pad, a 0.6 x font vertical centre, a -1px region nudge, and written sizes taken as raw screen pixels. Replace all of them with the rules from the 3.3.5 / 4.3.4 clients (decompiled; the size formula's helpers confirmed against the real 4.3.4 binary): - A written size multiplies by fontPx / (14 x ddcWidthScale), so it follows the text's size, the UI scale and the resolution, and then by the fontstring's layout scale, as 3.3.5 does. Size defaults follow ParseEmbeddedTexture: ":0:2" is a width ratio, ":20:0" is font-wide. - An icon starts at the previous glyph's ink edge (bearing + cell width) plus the face's outline gap, found by replaying the run's placements with the emitter's own glyph helpers; the next glyph starts at the rounded icon edge. - Vertical alignment follows the node's justify-V (node+0x50). - Offsets move only the drawn icon; a positive offsetY now moves it up. GetCoinTextureString now matches 3.3.5: default height 14, a space between denominations, and retail's 2:0 coin offset in the strings. The four Coordinate statics at 0x00832A40 get their real names (VAR_COORD_DDC_WIDTH_SCALE and siblings). Known gap: the fs-level wrap callers can't see the fontstring, so they budget icons at layout scale 1. |
||
|
|
7ccbbaaf68 |
fix(compat): stop Turtle's Toggle Movement button erroring
Turtle's Options frame sets GroupFrame_ToggleMovement(state) directly as the button's OnClick. With modern script args the handler receives the button as `state`, and `1 - state` errors (Turtle_GroupUI.lua:409). Wrap the global so only a number reaches the original. |
||
|
|
85619155f8 |
feat(equipmentset): add C_EquipmentSet.PickupEquipmentSet
Equipment sets become action-bar buttons, as in 3.3.5: action type 0x20000000 | setID and cursor type 13. The set can be picked up, placed, dragged off, and swapped with other actions. The button shows the set icon, name and tooltip, and grays out while a set item is locked. A click fires WEAR_EQUIPMENT_SET(setID) and the embedded EquipmentManager equips the set. The server drops action type 0x20 without saving it, so placements are kept in the per-character equipment-set file. The server is sent an empty slot, and the saved buttons are merged into the SMSG_ACTION_BUTTONS buffer at login. GetActionInfo and GetCursorInfo report "equipmentset", name. |
||
|
|
a33146241e |
feat(macro): make [button:N] read the click it is running inside
The condition existed but was a stub: it matched only "1" / "leftbutton" and always passed, because nothing on this client could say which mouse button had driven the current click. GetMouseButtonClicked can now answer that, so the condition asks it. Numbers use the modern API order -- 1 left, 2 RIGHT, 3 middle, 4, 5 -- which is deliberately NOT the order of the engine's internal click bitmask (where 2 is the middle button); that mask never reaches Lua. A name is matched as written, so [button:rightbutton] and [button:2] are the same test, case-insensitively. Outside a click the answer stays "left button". That is not a cosmetic default: Macro::ShowTooltip re-evaluates conditional directives off the world tick with no click in progress, so a nil-means-no-match rule would change which icon a `/cast [button:2] X; Y` macro displays at rest. The engine's own no-argument Button:Click() means the left button, so it is also the honest resting answer for a state-driver poll. Verified in-game with all five buttons, both directly from OnClick and through a real macro body -- click -> attribute macro -> EXECUTE_CHAT_LINE -> SlashCmdList -> SecureCmdOptionParse, which confirms the click context survives the whole chain -- plus the name form, the btn alias, and the no-click resting answer. |
||
|
|
449841b4eb |
fix(debugtools): draw the title bars above the backdrop, fit the scroll bar
The Backdrop of each frame draws its background and border into the BACKGROUND layer, and it is applied after the textures declared in the XML, so a title bar in that layer ends up underneath it. On ScriptErrorsFrame, whose backdrop is the 32px dialog border, the header came out behind the window edge; on EventTraceFrame and TableInspectorFrame the bar is a translucent one inside the frame, so it was buried rather than misplaced. Every Blizzard frame that uses UI-DialogBox-Header puts it in ARTWORK. The title text of all three is in OVERLAY and still reads over the top. ScriptErrorsFrame is also the only frame here that takes its scroll bar from UIPanelScrollFrameTemplate, which hangs the bar off the right edge of the scroll frame rather than inside it, so the bar ran past the border. Narrow the scroll frame, and its child edit box with it, to end where the Close button does. Blizzard's own measurements do not carry over: its ScriptErrorsFrame inherits UIPanelDialogTemplate, a thin GearManager border, not this backdrop. The other two frames place their sliders by hand and already sat inside. |
||
|
|
bf79ee1d93 |
feat(macro): add /stopmacro
Stops the rest of the macro body, split the way 3.3.5 splits it: the command is addon Lua, and the flag belongs to the body runner, which is what makes "stop the rest of THIS macro" mean anything. The runner clears the flag for each body it starts and restores the previous value when that body ends, so a line that runs another macro re-enters the runner and the inner /stopmacro ends the inner body only. A stray StopMacro() outside a macro leaves nothing armed for the next one. Each line is dispatched synchronously through ChatEdit_SendText into its handler, so the flag is already set when the fire returns. The command binds ClassicAPI.StopMacro rather than the bare global. StopMacro is a plain name in a crowded space, and the global is only ours until an addon declares one of its own -- after which the command would set THEIR flag and the macro would keep running with nothing to show for it. The mirror captured our function at registration. |
||
|
|
4f99a1ed95 |
feat(macro): add /castsequence, /castrandom and /userandom
Ports the three remaining cast-family commands from FrameXML, including the macro icon, which is half the feature: a sequence whose button does not show the current step is barely usable. The sequence state lives in Lua and the icon asks for it by name. That is Blizzard's own split -- 3.3.5's macro code calls the Lua global QueryCastSequence through lua_pcall and takes the item over the spell -- so execution and display read one index and cannot disagree about which step is current. Macro::ShowTooltip mirrors that call for any option line that came from a castsequence command. The random pair is faithful to 3.3.5 rather than nicer than it: the binary has no query beside QueryCastSequence, so a comma list reaches the resolver whole, names nothing, and greys the button. Being a static line it also ends the collection, so a /castrandom above a /cast takes the icon. #showtooltip gives one of these macros an icon. QueryCastSequence stops answering if the contested-command pass hands /castsequence to another macro addon: our table only advances while our handler runs, so a frozen step one on a sequence somebody else drives would be worse than no icon at all. Three adaptations the 1.12 client forces: item detection uses the carried-item test, since there is no name to item lookup here; the cast events carry the spell in different argument positions per event; and CastSpellByName takes no unit, so a targeted step routes through C_Spell.CastAtUnit like /cast already does. /cast, /use and both random commands now share one action dispatch instead of four copies of it. |
||
|
|
108a91a843 |
feat(api): describe the API in the code, browse it with /classicapi
docs/API.md is 18.7k lines and its anchors are signature slugs, so editing a signature breaks the 281 internal and 88 README links into it. Blizzard solved the same problem by shipping the API as data plus a browser addon, and warcraft.wiki.gg renders those same tables. One set of descriptors can feed all three. Each registration now carries one next to it: typed arguments and returns, nilability, defaults, and a sentence. Events, enumerations and returned table shapes are described the same way. No Script_* body changed. Game.h gains namespace Game::Doc (Field with Req/Opt/Vararg, FieldList, Function, Method, Structure, Event) and a trailing descriptor argument on all six Game::Lua::Register* plus Event::Custom::AutoReserve. api/Documentation.cpp records every registration on the first pass of each Lua state and seals it, so /reload re-registers but records nothing and the environment comes from which pass saw the name. Export is lazy: nothing is materialized until C_APIDocumentation.GetSystem asks for one system, because eager export would build thousands of tables per reload for a slash command. _classicapi_UndocumentedAPI lists what still has no descriptor. AddOns/!!!ClassicAPI/APIDocumentation/ ports Blizzard_APIDocumentation's eight files. Named /classicapi, not /api: the browser holds only what ClassicAPI adds, so /api would have implied the whole 1.12 surface. Two deliberate differences from the retail source, both noted in the file headers: a system search also matches its namespace, since that is the name people type; and an undocumented function says so, because an empty signature otherwise reads as a real one. LinkUtil gains the SetItemRef to LinkUtil.ProcessLink dispatch. That handler registry was dead code; a new link type now registers a handler instead of stacking another SetItemRef override. Also defines assertsafe there, which was undefined and only mattered once the function went live. Documented: the C_Spell and C_SpellBook surface, the spell globals, both spellbook enumerations, the 13 UNIT_SPELLCAST_* events, GameTooltip as the widget-method example and C_Glue as the glue and mixed-environment example. 66 of 692 function registrations. tools/New-ApiDocSkeletons.ps1 emits paste-ready skeletons to make the rest of the sweep tractable. Verified in game: the browser lists, searches, and prints detail; links render and click through; right-click copies and shift-click dumps. |
||
|
|
d4ac5dc210 |
fix(slash): only give back a command that is still ours
The contested-command heal cleared any key we added whose command string another addon also claimed. Both halves of that test read the live table a frame later, so an addon that takes one of our keys OVER broke it. SuperCleveRoidMacros registers into our own `CANCELAURA` key: it replaces the handler with its conditional one and writes `SLASH_CANCELAURA2 = "/unbuff"` over our alias. The heal then tested `/unbuff` -- a command we never registered -- and on a hit cleared the key, deleting that addon's `/cancelaura` rather than handing ours back. `/unbuff` kept working through its own owner, so the symptom was `/cancelaura` alone falling through to `ChatEdit_ParseText`'s "Type '/help'" message. Snapshot the handler and the command strings at file scope, while the table holds exactly what this file registered, and skip a key whose handler is no longer ours. Taking a key over is already how an addon wins a command, so there is nothing left to resolve. The `/petattack` case that motivated the heal is unchanged: that addon registers a rival key beside ours, our handler stays in our key, and the contested string is one we registered. Reported downstream as brues-code/SuperCleveRoidMacros#6. |
||
|
|
fedccf5b95 |
fix(macro): give a contested slash command back to whoever owned it
Vanilla has no `/petattack`, so the conditional slash-command registry ADDS it. SuperCleveRoidMacros ships the same command under its own SlashCmdList key -- `PETATTACK` where we register `PET_ATTACK` -- and both set a `SLASH_*` string of "/petattack". Neither ever overwrites the other, so loading first decides nothing: `ChatEdit_ParseText` walks SlashCmdList with `pairs` and takes the first match, making the winner hash order. When ours won, `/petattack [hastarget,alive,harm]` fed that addon's conditions to `SecureCmdOptionParse`, which does not know `hastarget` or `alive`, so no clause matched and the line did nothing. Rejecting a condition we cannot evaluate is right by itself -- retail does the same -- so the fault is owning the command at all. A command we add and someone else already binds is handed back. Splitting one command across two condition parsers would be worse than one owner: the dialects disagree, and ours deliberately differs from 3.3.5 for an `[@unit]`-only group. Only added commands are given up. One we replace (`/cast`, `/target`) has no second entry to lose to, and an addon that wraps ours still chains through it. The check runs a frame after load, not at file scope -- this addon loads first, so nothing is registered to detect yet -- and not on PLAYER_LOGIN, which has already fired during a `/reload` and would run the check immediately to the same empty result. The addon load pass is synchronous, so one frame is enough on both paths. A command registered by a load-on-demand addon later keeps its own entry, and its coin flip. |
||
|
|
0ba73b8457 |
fix(macro): leave GetMacroInfo alone and expose the shown icon instead
`Macro::Info` re-registered `GetMacroInfo` to answer with the icon a `?` macro's `#showtooltip` resolved to, so the Macro UI's list would match the action button. But the Macro UI seeds its icon selector from that same return -- `MacroFrame_Update` sets `MacroPopupFrame.selectedIconTexture` from it, and `MacroPopupFrame_Update` checks the grid button whose name matches -- so opening the selector on such a macro pre-selected an icon the player never picked, in the one place that edits the stored icon. Saving was never at risk (an unclicked selector leaves `selectedIcon` nil and `EditMacro` then leaves the icon alone), but the display was wrong. One return cannot serve both readers, and the one that edits state has the stronger claim, so `GetMacroInfo` goes back to the engine's: it is the read side of the icon `C_Macro.EditMacro` writes, and every addon that captures it now gets the stored icon. The icon a macro SHOWS becomes something a caller asks for, through `C_Macro.GetMacroIcon`. It reads the macro icon getter this DLL already hooks, so the `?` rule and the active-icon choice stay in one place and the answer matches what the action button and the drag cursor get. Util/MacroIconSelection.lua paints the Macro UI's list buttons from it after the stock update, which is additive -- an empty slot or a macro with a chosen icon answers with what stock already drew. Dropping the re-registration also takes a commonly captured global out of the override chain. |
||
|
|
3191c4dcfc |
fix(macro): leave a macro alone when its conditions are not ours
A macro written for another macro addon names conditions this parser does not have. SuperCleveRoidMacros' `[alive]` is one. The `#showtooltip` reader scans every macro body, so it met that condition and printed "SecureCmdOptionParse: unknown condition 'alive'" at login, about a macro that works. Worse than the noise: a condition we cannot evaluate cannot pass, so its group fails. A macro with no unconditional fallback clause then matched nothing, and the reader wrote 0 over the spellID the engine's own parse had put in the per-macro cache - costing that button its cooldown, range and usable state. `SecureCmdOptionParse` now records the keywords it does not own on its cached parse and returns the first one as a third value. It still names them, once each, for a caller the player drove. The reader passes the new `quiet` flag and reads that value instead: on a foreign dialect it resolves nothing, writes nothing, and stops re-evaluating until the body changes. The engine's parse stays in the cache, and the addon that owns those conditions can still claim the macro through `C_Macro.SetMacroDisplay`. Such an entry also stays out of `dirty`, because a dirty entry nothing evaluates would keep `HasPendingWork` true and re-run the catch-up on every reader. Moving the warn-once bookkeeping from parse time to call time also stops a quiet scan from consuming the one warning a keyword gets, so a condition the player later types is still named. This is not a load-order fault. SuperCleveRoidMacros creates `_G.CleveRoids` at the top of Init.lua, and that same file sets `ClassicAPIMacroDisplay`, which lifts our wholesale yield on purpose so it can publish per macro. The window is between our first tick and its first publish, which it cannot make until the player object exists. |
||
|
|
373dce8202 |
ShaguTweaks nil check
Fixes #49 |
||
|
|
36c367a6d6 |
feat(macro): native #showtooltip, conditional slash commands, and a display API for addons (#48)
* feat(macro): native #showtooltip/#show, conditional /cast and /use
Backport the macro display system to the engine:
- Macro::ShowTooltip resolves `#showtooltip [cond] value` / `#show` (and
the bare form over the macro's /cast and /use lines, first match wins)
through the Lua SecureCmdOptionParse on the world tick and writes the
result into the engine's per-macro spell cache (+0x564/+0x568), which
every action reader already consumes. Repaints go through the engine's
own slot-changed notifier. Item targets are cached alongside.
Re-evaluates on modifier / mouseover / target / combat changes and every
200 ms otherwise. Yields entirely when SuperCleveRoidMacros is loaded.
- The `?` icon rule is a co-hook on the macro icon getter, so action
buttons and the drag cursor both show the resolved icon; GetMacroInfo,
GameTooltip:SetAction, GetActionCooldown, GetActionCount and
IsConsumableAction are re-registered in front of the engine for macro
slots with a resolved directive and tail-call it otherwise.
- Macro::RunBody re-implements the engine's body runner so `#` lines
never reach chat; Macro::Execute skips them too.
- /cast and /use in the embedded addon (3.3.5 handler shape): items
first, [@unit] via C_Spell.CastAtUnit, 1..19 = inventory slot, other
numbers stay spellIDs. SecureCmdOptionParse: a group whose only piece
is @unit passes only while the unit exists (3.3.5 passes it
unconditionally). C_Item.GetItemCount accepts names. GetMacroItem
added; GetMacroSpell now reflects the directive.
- Offsets.h: 0x004F0F40 was the macroID -> MacroEntry resolver,
mislabeled as a spell-state cache; renamed FUN_MACRO_ID_TO_ENTRY, with
the action-bar / macro-runner constants this needs added and verified.
* feat(unit): add IsUnitToken for token-vs-name dispatch
Vanilla ships each "act on a unit" verb as two Lua entries, one taking a
unit token and one taking a character name, and each errors on the other
kind of input. Conditional slash commands need to accept either, because
SecureCmdOptionParse hands back a token for `/target [@focus]` and a name
for `/target Bob` through the same variable.
IsUnitToken(value) answers which one a string is by calling the engine's
own token resolver inside lua_pcall and reporting whether it returned or
threw. Consulting the resolver rather than matching a token list here
keeps the answer correct for every family it knows, including this
client's native GUID literals and our own focus / nameplateN / markN,
which unit/TokenExtensions.cpp hooks onto the same function. It reports
whether the text names a token, not whether a unit is there, so "target"
with nothing targeted is still true.
if IsUnitToken(x) then TargetUnit(x) else TargetByName(x) end
Additive on purpose. Merging the pairs into a modern TargetUnit /
AssistUnit / FollowUnit was written and reverted: those names are common
enough for other DLLs and addons to replace that re-registration is
silently last-one-wins, with no error and no trampoline to chain. That
mechanism is only safe for names nobody else contends.
Offsets.h records two findings from decompiling the resolver. The throw
is raised by its callee, not by FUN_RESOLVE_UNIT_TOKEN, which is a thin
wrapper returning 0 on a miss. And this client reaches the error through
a patched fallthrough that first parses a 0x<hex> GUID literal, so GUID
unit tokens resolve natively with no SuperWoW loaded.
* feat(addon): backport the conditional slash commands
Adds 27 commands that take [conditions] through SecureCmdOptionParse,
following the 3.3.5 SecureCmdList handler shapes: targeting
(/targetexact, /cleartarget, /targetlasttarget, /targetlastenemy,
/targetenemy, /targetfriend, /targetenemyplayer, /targetfriendplayer,
/targetparty, /targetraid), casting and state (/stopcasting, /cancelaura,
/cancelform, /dismount), equipment (/equip, /equipslot), action bars
(/changeactionbar, /swapactionbar) and the pet family.
/target, /assist and /follow gain conditions by replacing the FrameXML
handlers, which is the only way to add them. Plain input keeps working:
each routes through IsUnitToken to the engine's token entry or its
by-name entry, where the old handler always went by name.
Three natives have a different shape here than the 3.3.5 handlers assume,
so those bodies are not straight ports. PetAttack takes no target and
always sends the pet at the current target. ChangeActionBarPage takes no
page and only fires ACTIONBAR_PAGE_CHANGED, so CURRENT_ACTIONBAR_PAGE is
set first. Pet autocast is a spellbook-slot toggle with no enable and
disable entries, so a name is resolved against the pet book and on/off
read the state and toggle only on a mismatch. /cancelaura needs no buff
walk, since CancelSpellByName already matches a player buff by name.
Not ported for want of a native: /targetlastfriend, and the /mt and /ma
family, which needs party assignments the client does not have.
Command names come from the locale files, with the localized name taken
from the matching Blizzard GlobalStrings and the English one alongside.
zhCN ships English for all 27. The short aliases retail also carries
(/eq, /tar) are left out, since those collide with addon shorthands.
* fix(macro): resolve item link values in #showtooltip
`#showtooltip` over a `/use item:6948` line showed no icon. The directive
evaluator built its item argument as `{0, 0, value}`, hardcoding the whole
value as a NAME, so the `item:N` and pasted-link forms could never match
and the value fell through to the spell lookup. `/use` itself was fine,
which is why the macro cast the item but the button stayed blank.
The link parsing already existed for the Lua entries. Split it out as
`Item::Arg::ResolveString` and call that instead of hand-building the
argument, so both paths read the forms the same way.
A bare number keeps skipping the item lookup: `ResolveString` reads "6948"
as an itemID, and a bare number that is not an equipment slot has to stay
a spellID per the documented `/cast 5019` rule.
An explicit itemID now also resolves when none is carried, falling back to
the ID after the bag and equipment walk misses. The icon and tooltip come
from the item record, and the tooltip path already handled an unheld item
through a hyperlink, so a macro naming an item in the bank or one written
before looting it now displays. Names are still limited to what you hold,
since 1.12 has no name-keyed item cache.
* fix(macro): make [@cursor] work in /cast, /use and #showtooltip
`/use [@cursor] item:4390` did nothing and its `#showtooltip` showed the
question mark. Two causes, both in the addon.
The parser rejected the clause. A group whose only piece is `@unit` passes
only while that unit exists, and the existence test ran UnitExists on
`cursor`, which is not a unit token. The engine raises there, the pcall
caught it, and the group failed. `none` was already exempt; `cursor` joins
it, since both name something other than a unit and neither can be tested
that way.
Nothing routed the target once it did pass. `SecureCmdUseItem` sent every
target through UseItemByName, which takes a unit GUID, and the spell branch
had only the on-unit and default cases. A `cursor` target now goes to
C_Item.UseAtCursor and C_Spell.CastAtCursor, which were written as the
`[@cursor]` analogs but had no caller. SecureCmdItemParse has already
turned a bag or inventory slot into a link, so one item call covers every
value form.
`#showtooltip` needed no change: the value resolves once the clause passes.
* feat(macro): accept a character name as a macro target
`/cast [target=Feral] Rejuvenation` did nothing. A `@unit` or `target=unit`
piece takes a character name as well as a unit token, but nothing here
turned a name into something the unit functions accept, and the existence
gate ran UnitExists on it, which raises for a string that names no token.
`UnitTokenFromName(name [, exactMatch])` runs the engine's own by-name
search — `FUN_UNIT_FIND_BY_NAME`, the one behind TargetByName, AssistByName
and FollowByName — and reports the winner as a token: a standard one when
it fits, else the GUID literal, which this client's resolver takes too. It
walks party, then raid, then every loaded unit, so it reaches units no
token names. Prefix match by default, nearest first, like TargetByName.
`GroupPasses` now resolves a named target once and uses it for both jobs:
the bare-group existence test (`[@Feral][] Spell` falls through when they
are not around) and the conditions, which previously raised on a name.
The pcall that already guarded the existence test is what tells a token
from a name, so a token target costs no more than before.
The slash handlers resolve the target the same way before handing it to
CastAtUnit, UseItemByName, FocusUnit or StartAttack, and drop the command
when a named unit is not around.
* feat(macro): drop a ground-target item at your feet with [@player]
`/use [@player] item:4390` sent the grenade through UseItemByName, which
passes a target GUID but never commits the placement, so the reticle came
up instead of the grenade landing. Route a `player` target to
`C_Item.UseAtUnit` instead, which commits at the unit's position.
Only your own position is offered. Aiming a ground-target item at another
unit is not something the game lets you do by hand, so the slash handler
does not either; every other unit target keeps going to UseItemByName.
`C_Item.UseAtUnit` now dispatches with the unit's GUID rather than a zero
target, matching `C_Spell.CastAtUnit`. Without that, routing `@player`
through it would have cost a non-ground item its target: a bandage or a
scroll would fire at the current selection instead of at you. It now
covers both kinds of on-use item, the way CastAtUnit covers both kinds of
spell.
* fix(macro): stop /cast [@unit] aiming ground spells at that unit
The same aim the item side was just denied: `/cast [@target] Flamestrike`
dropped the reticle on the target with no click, for any unit. Placing a
ground spell somewhere you could not put it by hand is aim the player has
not earned, and it should not differ between a spell and a grenade.
`/cast [@player]` and `/cast [@cursor]` still place, since both name a
position you can already aim at. Every other unit still has the spell cast
on it when it takes a unit target, which is what `@unit` is for; only the
ground-placement leg is dropped, leaving the reticle up exactly as casting
by hand does.
`C_Spell.CastAtUnit` keeps the whole primitive and gains a third argument
for the choice, defaulting to placing so the API and its callers are
unchanged. The restriction lives in the slash handler, the same split the
item side uses, where `C_Item.UseAtUnit` stays unrestricted and only
`/use` limits itself to `@player`.
`Spell::AtCursor::GroundPlacementPending` reports whether the in-flight
placement is a ground one, so the handler can leave that reticle up while
still cancelling a placement for a unit the engine did not accept. Leaving
that armed would strand the cursor.
* fix(item): stop a bad unit raising out of C_Item.UseItemByName
The optional `unit` went straight to the engine's token resolver, which
raises for a string that names no token. Both the code comment and the
API docs promised the opposite, that an unrecognized string is no target,
matching the no-op contract the item argument already has.
It is reachable without an addon calling the function directly: secure
button attributes and key bindings both feed it a configured string, so a
`unit="foo"` attribute raised inside a click handler.
Probe with Unit::TokenResolve::IsUnitToken first and treat anything else
as no target, which makes the documented contract true.
C_Item.UseAtUnit keeps raising, which is deliberate and now stated in its
docs: it is the companion of C_Spell.CastAtUnit, which documents the same
behavior as matching UnitHealth("garbage").
* feat(macro): let an addon publish its own macro display
`C_Macro.SetMacroDisplay(macroSlot, value)` hands a macro's resolution to
the display path, for an addon that parses macros itself. It is aimed at
SuperCleveRoidMacros, which today replaces ten action globals plus
GameTooltip.SetAction to put its answers on the bar, and borrows an
unrelated action slot to get a range check for a macro.
None of that is needed. Writing the spell into the engine's own per-macro
cache is what makes cooldown, range, usable, current and auto-repeat
correct for a macro button, with nothing overridden, and the icon then
reaches two places a Lua override cannot: the cursor while a macro is
dragged, and the macro window grid, both of which come from an engine
getter we hook.
The value takes the forms a `#showtooltip` value takes, so a publisher
hands over what it would have written in the macro. Three states: a value
to show, false for claimed-but-nothing-matched, nil to release.
Ownership is per macro. A published one is not parsed or re-evaluated by
us and is honored even while yielding; the rest stay ours. Nothing is
re-evaluated for the publisher, but a published resolution is re-applied
whenever the engine's re-parse overwrites the cache, so a macro edit
cannot silently replace it.
The wholesale stand-down when SuperCleveRoidMacros is loaded is lifted by
`CleveRoids.ClassicAPIMacroDisplay`, which a build sets to say it drives
us. Forks without it keep the all-or-nothing yield, so an older one cannot
end up fighting for the same buttons.
* fix(macro): accept the !Name prefix in /cast and #showtooltip
`#showtooltip` over `/cast !Shoot` showed nothing and the line cast
nothing: the `!` prefix, which asks for a toggle ability to be started
but never turned off, was never part of vanilla and no name resolver
knew it.
Split it in two.
The NAME is normalized in the one co-hook on the engine's single
name -> spellbook-slot resolver, which already owned the numeric
spellID form (so `spell/CastByID.cpp` becomes `spell/NameResolve.cpp`).
`FUN_RESOLVE_SPELL_NAME_TO_BOOK_ID` calls that resolver, so a single
strip covers the runtime cast, `Spell::Arg`, the `#showtooltip`
resolution and the engine's own macro parser -- which is what lets
`IsAutoRepeatAction` light a `/cast !Shoot` button even while macro
display is yielded to SuperCleveRoidMacros.
The BEHAVIOR stays in Lua: `SecureCmdCast` strips the prefix and casts
through the existing `CastSpellNoToggle`, which asks the engine whether
the ability is already up first. `CastSpellByName` cannot carry it --
re-registering that global is off limits and nampower already co-hooks
it.
`CastSpellNoToggle` gains the `placeGroundSpell` argument that
`C_Spell.CastAtUnit` has, so `/cast [@target] !X` keeps the rule that
only your own feet and the cursor place a ground-target spell. It also
tolerates a `!` on its own input now, since its auto-repeat name
compare is ours rather than the engine's.
* feat(item): take an item location wherever an item action takes an item
`C_Item.UseAtCursor`, `UseAtUnit`, `UseItemByName` and `EquipItemByName`
took an item reference only - an itemID, `item:N`, a link, or a name - and
resolved it by searching the bags for the first match. Holding two stacks of
the same item, or two copies enchanted differently, there was no way to say
which one you meant.
They now also take an item location: `{bagID=B, slotIndex=S}`,
`{equipmentSlotIndex=N}`, or an item GUID string - the shapes
`C_Item.GetItemID` already took. A location names one exact item.
`Item::Location::FindItemArgOrLocation` owns the overload; the old `Resolve`
(locations, pointer) and the new `ResolveItemArgOrLocation` (either, pointer)
are wrappers over it, so the classification and the walk live in one place.
None of the four call sites resolves anything itself any more.
A table is only ever a location, and so is a string that parses as a strict
`0x` + 16 hex digit GUID, which no item link or item name can look like. The
form is decided from the argument alone and committed to: a location resolve
STOMPS the Lua stack (`PackBagSlot` overwrites the first slots with its own
arguments), so falling back to the reference forms after one had run would
re-read the argument as whatever it left behind - a bag index read as an
itemID, which names an unrelated item.
`EquipItemByName` needs the source coordinates too, since the swap packet
carries them, which is what the detail form is for. An
`{equipmentSlotIndex=N}` location names a worn item, so with a `dstSlot` it
routes to `Item::Swap::FromPaperdoll` - that is how a ring 11<->12, trinket
13<->14 or weapon 16<->17 move is expressed. Without a `dstSlot` there is no
slot for the engine to pick, so that combination does nothing.
Its `lua_settop(L, 0)` ahead of `ClearCursor` is gone: `Script_ClearCursor`
(`0x004895B0`) is `FUN_00495190(1, 1)` and a return - no arguments, no stack
reads. Dropping it lets the item resolve run after the cursor clear, which a
location needs: while an item is held its slot reads empty, so the location
it came from would otherwise resolve to nothing.
* refactor: centralize the item constants and the icon-path build
Four copies of the ItemStats displayInfoID -> `Interface\Icons\<name>`
chain had accumulated - `item/GetData`, `item/Info`, `container/ItemInfo`
and the new `item/Icon` - and they had already drifted: two checked for an
empty icon name and two did not. `Item::Icon::PathForDisplayInfoID` is now
the one builder and the other three call it, so a change to that chain has
a single site. `PathForItemID` is it plus the cache lookup.
`action/ItemState` had local constants shadowing values already in
`Offsets.h`: `kItemSpellSlots` for `ITEMSTATS_SPELL_SLOT_COUNT`, and a bare
`trigger == 0` for `ITEM_SPELLTRIGGER_ON_USE`. `INVTYPE_AMMO` / `THROWN`
existed in two files, and the engine runner's `0x400` macro line buffer in
two more, so those move to `Offsets.h` as well - `INVTYPE_*` next to the
string table they index, `MACRO_LINE_BUFFER_SIZE` next to the delimiters.
CLAUDE.md's rule, and duplicated offsets drifting is exactly what it was
written for.
* fix(macro): indented directives, release, and icon-getter re-entry
Three defects found reviewing the `#showtooltip` work, plus dead code.
A directive typed with a leading space was lost AND leaked to chat.
`ParseDirective` and the two `#`-line filters all tested byte 0, but the
tokenizer splits on `\r\n` only, so ` #showtooltip` arrives with its space:
the parse missed it, and then `Macro::RunBody` / `Macro::Execute` failed to
recognize the comment and dispatched the line through `EXECUTE_CHAT_LINE` -
the /say this feature exists to stop. All three skip blanks now, as does
`CastCommandArgs` so an indented `/cast` line is still collected, and the
runner dispatches the trimmed line so an indented command works at all.
`C_Macro.SetMacroDisplay(slot, nil)` left the publisher's spell in place.
`Release` cleared our entry and asked for a rescan, but `Rescan` only marks
an entry dirty when it has a directive with options - so for a macro with
no directive of its own, nothing ever rewrote `+0x564`, and the button, its
tooltip, cooldown and auto-repeat state stayed on the published spell until
the engine happened to re-parse. It now hands the field back to the engine
by running the engine's own parser, then repaints.
The macro icon getter could run Lua from under a click. `FUN_MACRO_ICON_PATH`
has two callers and one is `FUN_MACRO_PICKUP`, inside the UseAction core, so
`Lookup`'s catch-up could evaluate conditions through `SecureCmdOptionParse`
and fire `ACTIONBAR_SLOT_CHANGED` into addon handlers while the drag was on
the stack - the re-entrancy hazard CLAUDE.md records for `Tooltip::SetEvents`.
`LookupPassive` reads only what the entries already hold; the world tick
does the work and repaints, so a resolution can be one tick behind an edit.
Also drop `Active()` (no callers) and `RunBody`'s unused trampoline, and
correct the header's reference to a module that does not exist: the icon
comes from `Macro::IconPath`, not `Action::Texture`.
* fix(slash): five conditional-command defects, and cheaper option passes
`/cast 5019` could consume an item. A bare number that is not an
equipment slot is a spellID, but it reached the item lookup, which reads a
number as an itemID - so carrying item 5019 used it instead of casting the
spell. `Macro::ShowTooltip::ResolveValue` already guarded this exact case,
so the button showed the spell while the click used an item.
Every bare `/targetenemy` stepped backwards. The cycling selectors pass
the parsed value as their reverse flag, and a clause that matches with no
value yields the empty string - which is a true boolean in Lua. Six
commands were affected in their most common form.
`/cast [@none] Spell` did nothing. `@none` names no unit, but only
`@cursor` was exempted from the token resolve, so `none` went to the
by-name search and the cast was dropped. It now means no unit, which is
the untargeted form of the verb; `/target [@none]` clears the target, as
documented. The other unit verbs no longer feed `none` to that search
either - it matches on the START of a name, so it would find a Nonek.
`/assist [@target] Bob` ignored Bob. `/target` and `/follow` both let a
trailing name win over an explicit `target=target`; assist did not.
`/use [@player] 0 1` used the wrong item. The position branches ran before
the bag branch, so a named slot was thrown away and the item re-found by
link - the first match anywhere, which with two stacks is the wrong one.
Every form now resolves to one item and goes through one call, which also
means a slot is aimed by `@unit` like a name is, and that `/use` always
uses: clicking a bag slot sells the item at a merchant and repairs it
under the repair cursor (`Script_UseContainerItem` branches on the
merchant GUID and on cursor mode 0x11), which a typed command must not do.
`GroupPasses` also stopped paying for an answer it discards. A group with
conditions only needs a token, so it asks `IsUnitToken` rather than
`pcall(UnitExists)` - the conditions test existence themselves. The
existence path keeps its single pcall, and a name, which costs an
object-manager search, is remembered for the rest of the pass.
|
||
|
|
fe9e7dddcd |
fix(color): keep ColorMixin on the standard color globals
An addon that carries a copy of Blizzard's own definition -- a plain
NORMAL_FONT_COLOR = {r=1.0, g=0.82, b=0} and its friends -- assigns it
over ours at file scope, so every addon that loads after it finds a color
with no methods. pfUI's who list then fails on NORMAL_FONT_COLOR:GetRGB()
(brues-code/pfUI#56).
Re-apply the color globals after each addon loads, not only at our own
load, and mix ColorMixin INTO the table that is there instead of replacing
it: the values that addon chose stay, and each reference it already handed
out gets the methods too. ITEM_QUALITY_COLORS entries are repaired on the
same pass. This replaces the SpecialTalentUI special case.
C_UIColor.GetColors() makes a color object for each of its 187 rows, so
the values are kept from the first call and each later pass costs one
lookup per tag. Only a color that is absent or has lost its methods is
touched; a tag holding something else, and a <TAG>_CODE string that is
already set, are left alone.
|
||
|
|
e26f8958e9 |
fix(compat): let a ClassicAPI-aware addon opt out of its whole shim
pfUI's `handlesHookScript` and ShaguTweaks' `API.classicapi_version` now return at the top of the compat callback instead of gating one branch inside it. An addon that advertises ClassicAPI awareness handles its own color globals, HookScript path and event registrations, so no part of the shim should run against it. Previously the pfUI flag suppressed only the CreateFrame shim while the RAID_CLASS_COLORS override and the UpdateColors no-op still applied, and a ClassicAPI-aware ShaguTweaks still had its libpredict events unregistered underneath it. The "brues" X-Website tag now gates the pfUI HookScript shim on its own, so an unflagged fork carrying that tag behaves as before. |
||
|
|
f0a83f1f31 |
fix(compat): restore Compost:Erase when a 5.1-stubbed copy wins
Compost-2.0 rev 17406 replaces most of its own body with stubs once it believes it is on Lua 5.1, and our 5.1 syntax backport makes its loadstring probe pass. Losing GetTable and Reclaim is harmless -- both are pure recycling hints -- but Erase is not: callers hand it a live table and expect its keys gone, and the stub takes no parameter at all. So every call site that clears in place, rather than assigning the returned table, silently stops clearing. One addon shipping that revision hands it to every other Ace2 addon, because AceLibrary arbitrates on the highest $Revision and ignores load order. Puppeteer is the reported casualty: PTUnit:ClearAuras erases its debuff-type and aura-ID sets in place, so a dispel type never leaves the set once applied and a cursed raid member keeps its debuff colour after the curse is cleaned. Restore an in-place Erase, picked by behaviour rather than by revision or addon name so a Compost that already clears is left alone. Checked on every ADDON_LOADED because AceLibrary can upgrade a library at any point during load and an upgrade installs the new copy's functions over ours; the verdict is cached against the function that earned it, so a repeat check costs two identity comparisons and reuses one probe table. |
||
|
|
b39c16578b |
feat(addon): add the /startattack and /stopattack slash commands
Blizzard ships both in FrameXML's ChatFrame.lua; the handlers here are 3.3.5a's verbatim, routed to ClassicAPI's StartAttack / StopAttack. Every locale file gets the client's own command names, taken from the per-locale GlobalStrings dumps: /angriffstart, /empezarataque, /lanceattaque, /начатьатаку, /開始攻擊 and their stop counterparts, next to the English names. Gives users a clean /startattack without the macro-addon trick of placing the Attack spell on an action slot to read its state. Refs #46 |
||
|
|
be03d45f0c |
feat(frame): add frame:RegisterUnitEvent, unit-aware IsEventRegistered
Modern ports call frame:RegisterUnitEvent("UNIT_HEALTH", "player") to receive
an event for one unit instead of for every unit. Vanilla has no such method, so
the call errored, and FrameUtil.RegisterFrameForUnitEvents was left out of the
FrameXML backport for the same reason.
The engine already owns registration and dispatch, so this is only a filter.
Chain membership delegates to the engine's own Script_RegisterEvent; the filter
is stored per frame here; the check is one gate on the per-frame OnEvent fire,
where the dispatcher has already set _G.event and calls the arg'd script runner
with the OnEvent slot. Suppressing there also covers HookScript chains and
Frame::ScriptArgs' positional path, both downstream, as retail does.
Semantics follow Blizzard's 5.4.8 implementation, where the filter lives on the
subscriber node and the node's kind is fixed at creation: RegisterEvent over a
filtered registration keeps the filter, RegisterUnitEvent over a plain one stays
plain, RegisterUnitEvent over a filtered one replaces the units, and no usable
unit is a plain RegisterEvent. The filter dies with the node, through co-hooks
on Frame::UnregisterEvent and Frame::UnregisterAllEvents -- the latter also
being the CScriptObject destructor's path, so frame destruction is covered.
Two divergences from 5.4.8, both additive. Unit tokens are kept as strings and
compared case-insensitively, since focus/nameplateN/markN are not in the
engine's canonical token table. And the unit count is not capped: 5.4.8 reads
exactly two units and folds each token index into a byte of one dword, and
retail later filled that dword and documents four, but we have no dword to fill,
so every string argument past the event name is a unit.
The filter applies only when the event's first argument is a string. A
number-first event, or a no-arg event (dispatched through a runner this never
sees), fires as with RegisterEvent -- one rule that holds on every dispatch
path, and one that fails toward an extra event rather than a lost one.
FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT was already hooked by Frame::ClickEvents for
PreClick/PostClick, and MinHook allows only one hook per address -- a second
aborts the entire install. Frame::RunnerHook now owns that hook and fans out to
subscribers claiming disjoint slot addresses; ClickEvents moves onto it with no
behavior change.
Verified in-game: 28 assertions over the branch table above, the
PreClick/OnClick/PostClick bracket still firing in order through the shared
runner, and a capture window in which a filtered frame received only its own
token (20 of 20) while a plain control frame on the same events took 115 fires
across six token spellings.
|
||
|
|
d14f0b44c1 |
fix(compat): restore vanilla script args for LunaUnitFrames headers
Fixes #41. LunaUnitFrames sets SetupGroupHeader(groupType) as its group headers' OnEvent while also calling it directly with a group name. As a handler it relies on groupType being nil so it falls back to this.unitGroup. Our modern script arguments hand it `self` instead, so it looks the header up by frame rather than by name, gets nothing, and indexes nil at units.lua:358. The addon is correct vanilla code. A function that is both called directly and used as a script handler is an ordinary vanilla idiom, and passing positional arguments to handlers breaks it wherever the first parameter means something other than self. Adds CAPI_VanillaScriptArgsCompat(frame, script), which rewraps one handler in a no-parameter closure so the extra arguments stop there and the original runs with the empty argument list it was written for. The globals survive the nesting, so it still reads `this` and `event`. Same shape as the existing CAPI_MouseoverClearedCompat. Only the group headers need it. SetupRaidHeader takes the header frame itself, so `self` is already the value it wants. This covers one addon, not the class. Any addon using the same idiom hits the same failure, and each will need its own entry here until handlers opt in to modern arguments rather than receiving them unconditionally. |
||
|
|
8e1429bfac |
feat(texture): publish raid target markers as atlases
All eight markers live in one 4x4 sheet on this client, and the per-marker files other clients ship are absent here — the art directory holds only UI-RaidTargetingIcons.blp. So naming a single marker requires a sheet plus a sub-rect, which is what an atlas is. A port referencing an individual marker file otherwise gets nothing. Blizzard publishes no atlas names for these. Checked: zero hits for raidtarget / targeting / raidmarker in UiTextureAtlasMember, and current Classic Era still draws them by computing texcoords in SetRaidTargetIconTexture and by per-file |T markup in chat. The names here therefore follow the standalone marker filenames other clients ship, so an addon written against those finds the art under the name it already knows. This lives in the addon rather than AtlasData.h on purpose: the DLL's built-in table means "names Blizzard defined", and adding invented ones there would quietly corrupt that contract. Cell math matches the chat marker tokens, and markers 4 and 8 were confirmed on screen. Also adds CreateAtlasMarkup alongside the existing texture markup helper. |
||
|
|
622882725f |
feat(map): C_Map user waypoint (Tier 3)
Add the eight user-waypoint calls and USER_WAYPOINT_UPDATED: set, get, has, clear, per-map position, the two hyperlink converters, and the can-set check. The pin is one piece of session state (a uiMapID, a 0..1 position and an optional z) that survives a UI reload. GetUserWaypointPositionForMap re-projects it onto any other map through world coordinates, so a zone pin resolves on its continent and back. The hyperlink is the standard worldmap:uiMapID:x:y payload with both coordinates scaled by 10000, and the parser accepts a whole link or the bare payload. UiMapPoint's factories go in the addon, matching where retail ships them. Extract the shared vector2 marshalling to map/Vector2.h so the waypoint and coordinate modules don't each carry a copy. |
||
|
|
bd1bd9f5d8 |
feat(aura): slot-batching API and lazy caster match
C_UnitAuras.GetAuraSlots / GetAuraDataBySlot / UnitAuraBySlot: enumerate a unit's auras once into opaque slot ids and fetch each by id, so a full scan walks the aura array once instead of once per index (the by-index getters re-walk from slot 0 on every call). Slot ids cover live descriptor slots, the stealth / range cache fallback, and the out-of-range group array, so the slot path keeps every source the by-index path had. GetAuraSlots also takes a table as a 5th argument (ClassicAPI extension) and fills it in place, returning `continuationToken, n`. Lua 5.0 allocates an `arg` table for EVERY vararg call (luaD_precall 0x006F6050 -> adjust_varargs 0x006F6200 -> luaH_new, verified in Ghidra), so a Lua helper receiving the retail multi-return costs one table per batch. The fill form keeps per-frame scans allocation-free; AuraUtil.ForEachAura / FindAura use it with a per-nesting-depth buffer pool instead of retail's vararg helpers. The descriptor walkers (FindNthSlot, FindSlotBySpellID/Name, GetUnitAuras) now evaluate IsPlayerCast only when the filter restricts on caster. It scans the Aura::Source cache (~1000 entries in a raid) and was paid for every populated slot on every call, PLAYER token or not. Cache-fallback eligibility is centralized (EligibleFallbacks / EligibleGroupFallbacks) so the by-index, bulk, and by-slot paths share one ordering, which is the ordinal an opaque cache slot id encodes. |
||
|
|
695077b6da |
refactor(callbacks): lighter EventRegistry dispatch
Modernize the frame-event forwarder: OnEvent now takes its (self, event, ...)
positionally (modern script args, on by default) and forwards straight to
TriggerEvent — dropping the DispatchGameEvent hop and the unpack(arg) repack,
and forwarding the exact arg count instead of a padded arg1..arg9 (which
silently dropped args for events that emit more than nine). A fallback reads
the event/arg globals when SetModernScriptArgs is off, so the registry stays
robust to that switch.
Keep the ordinary {[event]=count} ref-count table rather than storing counts
as frame attributes: SetAttribute is heavier per call (it lowercases the name,
runs the secure-attribute parsing, and fires OnAttributeChanged) for the same
steady-state memory, so a plain table is lighter on the register/unregister
path.
|
||
|
|
8b106ae0d6 |
fix(addons): define global HookScript for ModernSpellBook
ModernSpellBook's MSB_Spellbook.lua re-hooks its "show all ranks" checkbox by calling HookScript(frame, "OnClick", handler) as a GLOBAL. That global never existed on any client -- HookScript has always been the widget method frame:HookScript, which our DLL provides -- so the call errors with "attempt to call global 'HookScript' (a nil value)". Define the global in AddOnCompat, forwarding to the method, gated on the addon being present so the global namespace stays clean otherwise. |
||
|
|
5279c463ed |
feat(slash): add /click handler and SLASH_CLICK locale strings
Register SlashCmdList["CLICK"], routing through SecureCmdOptionParse and GetClickFrame to click a named button. Parse name + button only: 1.12's Button:Click has no down/up path (verified in the base vmethod), so the retail `down` arg has nothing to act on and a nil button defaults to LeftButton natively. Add SLASH_CLICK1/2 to all locale files from Classic Era GlobalStrings. |
||
|
|
6ca6af1497 | fix(slash): route /focus, /clearfocus, /equipset through SecureCmdOptionParse | ||
|
|
be6dc200fe |
fix(addon): restore MouseIsOver's stock 1/nil return contract
The embedded addon replaces FrameXML's MouseIsOver with a wrapper over the native region:IsMouseOver(), which returns a boolean. Stock 1.12's MouseIsOver (UIParent.lua:1718) returns 1 on hit and nil otherwise, and vanilla-era addons compare against that literal - Quiver gates every widget click on `MouseIsOver(f) == 1`, which `true` silently fails, deadening its entire config dialog (buttons, checkboxes, icon clicks). Return 1/nil from the wrapper. 1 is truthy, so modern-style `if MouseIsOver(f) then` callers are unaffected. |
||
|
|
6ae3299041 |
Add Secure Action Button Templates and Comma-Split Support (#32)
* feat: port SecureActionButtonTemplate + CreateFrame comma-split
- Hook Script_CreateFrame (0x007060B0) to split comma-separated template
strings. Vanilla only accepts a single template name; modern addons pass
lists like 'UIPanelButtonTemplate, SecureActionButtonTemplate'.
- Add SecureTemplates.xml registering SecureFrameTemplate,
SecureActionButtonTemplate, SecureUnitButtonTemplate, and
InsecureActionButtonTemplate as real virtual XML templates.
- Add SecureTemplates.lua with modifier/button attribute resolution helpers
(SecureButton_GetModifiedAttribute, GetModifierPrefix, GetButtonSuffix,
GetModifiedUnit) and OnClick dispatchers.
- Remove duplicate SecureButton_GetAttribute/GetUnit from SecureStateDriver.lua
(now provided by SecureTemplates.lua which loads earlier).
- Include SecureTemplateTest debug addon for verification.
* Include AuraUtil.lua in ClassicAPI.toc
mistake from merge
* fix(frame): apply every template in a CreateFrame comma list
Vanilla 1.12 CreateFrame resolves the 4th arg as a single template name.
The initial comma-split hook only applied one template, and its tokenizer
dropped everything after the first entry for the common "A, B" format
(writing the NUL terminator clobbered the delimiter the advance step
checked). Rework it into real multi-inheritance:
- SplitTemplates: record whether a comma was hit before writing the
terminator, so "A, B" / "A,,B" / leading-comma inputs all split.
- CreateFrame_h: build the frame with the first resolved template through
the engine, then graft each remaining template onto the created object
with the engine's own inherit primitive - content (frameObj->vtable[+8],
FUN_00769820) and child <Frames> ((frameObj+0x24)->vtable[+8],
FUN_0076a060), the two __thiscall calls the builder FUN_006ee280 emits
per inherited node. Regions, backdrop, attributes, script handlers, and
child frames all apply, in left-to-right override order; OnLoad runs once.
- Offsets: add FUN_FRAMESCRIPT_STATUS_RESET (the XML-build error
accumulator reset, __thiscall) and document the status object layout.
Also fix the relocated SecureButton_GetUnit/GetModifiedUnit pet-token
pattern: "[^%%d]"/"[%%d]" matched literal % and d instead of the digit
class %d, so raid1pet never normalized to raidpet1. Restore single %d.
Verified in-game: a comma list applies both templates' regions/text in
either order; pet-suffix normalization works.
* refactor(secure): tidy SecureTemplates review follow-ups
- Guard RunMacroText (absent on this client) so a type=macro button with
only a macrotext attribute no-ops instead of erroring.
- Honor a SecureUnitButton_OnLoad menufunc: the menu/togglemenu action now
calls self.menu when set, else falls back to ClassicAPI_ToggleUnitMenu
(self.menu was previously stored but never read).
- InsecureActionButtonTemplate now inherits SecureActionButtonTemplate
instead of duplicating its OnClick block.
- Drop the committed SecureTemplateTest debug addon; test harnesses live in
the WoW install, not the repo.
* refactor(secure): make Frame::Attributes the single click dispatcher
The Lua SecureActionButton_OnClick from the secure-templates work
duplicated the native C++ dispatcher and only backfilled the verbs C++
lacked. Fold those into DispatchVerb so C++ is the sole dispatcher for
every secure button (template or plain SetAttribute), and drop the Lua
redundancy.
- DispatchVerb gains `action` (UseAction), `pet` (CastPetAction), `click`
(forward to the frame in the `clickbutton` attribute via
delegate:Click), and a custom fallback (a function stored as a raw
field on the frame named by the verb). `menu`/`togglemenu` now cancels
spell-targeting when a spell is on the cursor (the old
SecureUnitButton_OnClick nuance).
- Numeric spell IDs work as the `spell` attribute: SetAttribute("spell",
id) (a Lua number) or a numeric string cast the EXACT rank by ID via
the spellbook-slot resolver (Spell::AtUnit::CastByID at a unit,
Spell::AtCursor::DispatchSpellCast with none) - not name resolution,
which fired the highest known rank.
- CopyAttr coerces a number-valued attribute to its digits, so numeric
IDs also read for `item` and any other string attribute.
- Remove SecureActionButton_OnClick / SecureUnitButton_OnClick from
SecureTemplates.lua, simplify SecureUnitButton_OnLoad, and strip the
<OnClick> from the templates (plain Button templates now; the C++
closure installs on SetAttribute("type*")). The attribute-reader
helpers stay - public API and SecureStateDriver depend on them.
* fix(frame): restore the Lua stack after the multi-template graft
The comma-template graft can run a grafted template's child-frame OnLoad,
and in this hook-saturated environment a nested Lua op can shift the stack
slot the caller reads its return value from. Snapshot lua_gettop after the
engine build and restore it once the graft finishes, so the caller always
reads back the frame the engine left. Mirrors the Tooltip::SetEvents
save/restore discipline.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
f97379795d | Localize UnitAura call for performance | ||
|
|
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. |
||
|
|
76043fcdef |
fix(compat): stub WorldMapDeathRelease for Cartographer under the 5.1 probe
Cartographer_Notes gates a WorldMap release-spirit hook behind the Ace2-era
`lua51` probe (loadstring("return function(...) return ... end")), treating a
5.1-capable Lua as a modern client:
if lua51 then
WorldMapDeathRelease:SetScript("OnMouseUp", func)
end
Our 5.1 syntax backport makes that probe pass, so Cartographer takes the modern
branch and hooks WorldMapDeathRelease -- a WorldMap frame 1.12 never had. The
nil index crashes Cartographer_Notes:OnEnable. On real vanilla the probe was
false and the line never ran.
Same 5.1-probe fallout as the Dewdrop table-length heal: making the client pass
5.1 probes makes addons assume modern-client frames exist. Provide an inert,
hidden WorldMapDeathRelease stub (gated on Cartographer being installed) so the
hook succeeds and does nothing -- the vanilla outcome. The embedded
!!!ClassicAPI addon loads first, so the frame exists before Cartographer's
OnEnable.
Fixes #29
|
||
|
|
998deeac4a |
Fix pfUI HookScript compatibility shim
Tightens the pfUI compatibility shim in AddOnCompat.lua. The temporary CreateFrame wrapper now leaves the maintained brues pfUI fork alone when either its X-Website tag or the pfUI.handlesHookScript capability flag is present, and only applies the HookScript workaround when neither signal exists. |
||
|
|
99c0ab3ba3 |
refactor(tradeskill): use SetFormattedText
The trade-skill link frame's rank and summary FontStrings built their text with SetText(string.format(...)). Use the backported FontString:SetFormattedText instead -- one call, and it routes through the engine's own SetText path. |
||
|
|
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 (
|
||
|
|
46cae9d465 |
fix(unitmenu): stop stacking Focus/Cancel when a submenu opens
ClassicAPI_ToggleUnitMenu's initialize closure ran the same level-1 customization at every level. When the mouse crossed a nested entry (Loot Method / Loot Threshold / Raid Target Icon) the menu builds its level-2 submenu and re-invokes initialize; our AddFocusButton / AddCancelButton call UIDropDownMenu_AddButton with no level, which defaults to level 1 (not the current level), appending onto the still- open level-1 list. Level 1 is not reset while a submenu rebuilds, so the list grew every hover until "Too many buttons in UIDropDownMenu: ClassicAPIUnitMenuDropDown", pushing the real entries out of reach. Make initialize level-aware: at level >= 2 hand off to UnitPopup_ShowMenu (it resolves the submenu from UIDROPDOWNMENU_MENU_VALUE and adds its own Cancel); do the scratch-copy + Focus/Cancel append only at level 1 - mirroring how Blizzard's own unit dropdowns init. |
||
|
|
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 |