mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 08:00:42 +00:00
0ba73b84571f5bc83d86215dff2fc9631be208b2
493
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
0ba73b8457 |
fix(macro): leave GetMacroInfo alone and expose the shown icon instead
`Macro::Info` re-registered `GetMacroInfo` to answer with the icon a `?` macro's `#showtooltip` resolved to, so the Macro UI's list would match the action button. But the Macro UI seeds its icon selector from that same return -- `MacroFrame_Update` sets `MacroPopupFrame.selectedIconTexture` from it, and `MacroPopupFrame_Update` checks the grid button whose name matches -- so opening the selector on such a macro pre-selected an icon the player never picked, in the one place that edits the stored icon. Saving was never at risk (an unclicked selector leaves `selectedIcon` nil and `EditMacro` then leaves the icon alone), but the display was wrong. One return cannot serve both readers, and the one that edits state has the stronger claim, so `GetMacroInfo` goes back to the engine's: it is the read side of the icon `C_Macro.EditMacro` writes, and every addon that captures it now gets the stored icon. The icon a macro SHOWS becomes something a caller asks for, through `C_Macro.GetMacroIcon`. It reads the macro icon getter this DLL already hooks, so the `?` rule and the active-icon choice stay in one place and the answer matches what the action button and the drag cursor get. Util/MacroIconSelection.lua paints the Macro UI's list buttons from it after the stock update, which is additive -- an empty slot or a macro with a chosen icon answers with what stock already drew. Dropping the re-registration also takes a commonly captured global out of the override chain. |
||
|
|
d9565fbe1f |
fix(macro): correct macro display on a client that owns the macro tooltip
SuperWoW detours the engine's macro tooltip builder and reimplements 3.3.5's version of it: build the cached spell's tooltip when the macro's primary-spell field is non-zero, else add the macro's name. We write that field on purpose -- it is what makes a macro button's icon, cooldown, range, usable and auto-repeat state correct -- so every display fault here traced back to what we put in it. Four things were wrong: - `MaintainExternal` re-derived "the publisher had a value" from `kind != None`, but `Publish` marks a claimed macro `ShowTooltip` either way. One tick after `SetMacroDisplay(i, false)` it turned the publisher's "nothing matched" (cache 0, button usable) into "named an unknown spell" (the grey-out sentinel), and then stuck, because the next pass saw the sentinel already in place. The button greyed and the tooltip came up empty -- a spell tooltip for -1 builds nothing and skips the name. `matched` is stored on the entry now. - A publisher's claim outlived the publisher. `PrepareForReload` never cleared the entries and `Rescan` deliberately never re-reads a claimed body, so an addon disabled between reloads left every macro it had ever claimed frozen on its last answer. Claims are dropped on reload, each one handed back to the engine's own parse first. - `LookupEntries` scanned all 36 entries for a matching macroID. That is not sound: `FUN_MACRO_CREATE` bumps one of two per-scope counters, so a general and a per-character macro can share an id, and an entry whose slot-map index shifted keeps its old id until the next rescan. Either way another macro's resolution could answer. It resolves through the slot map now and requires the entry to still agree. - `#show` is icon-only, but the tooltip is not ours to delegate on this client: the field we fill for the icon is the same one the detoured builder reads, and it cannot carry the distinction. `#show` builds the macro's name through `Script_SetText`, which runs the identical sequence. `Publish` takes the kind from the body for the same reason, so a claim can no longer promote `#show` to `#showtooltip`. Also: a resolved spellID with no Spell.dbc row goes back to the engine rather than rendering an empty frame, matching the fallback 3.3.5's own macro tooltip ends with; and a conditional directive keeps its tooltip refreshing while hovered, which is 3.3.5's `dynamic | built` return. |
||
|
|
f895d38f76 |
refactor(time): drop C_DateAndTime.GetServerTime for the ClassicAPI mirror
The alias existed because FrameXML takes the GetServerTime global on some clients, and an addon needs some reachable name for the epoch. ClassicAPI.GetServerTime now is that name, so the hand-made one is redundant surface. Docs now point the GetServerTime caveat at the mirror. |
||
|
|
804ed61c76 |
feat(lua): mirror every registration under a ClassicAPI namespace
Registering a Lua name is not the same as owning it. The engine's
registrars write _G, FrameXML and every addon load after that, and
whoever writes last wins with no error and no way for the loser to
notice. GetServerTime is the case on record: a client whose GameTime.lua
declares its own replaced ours on every login, and no addon could reach
the C function again.
Every name RegisterGlobalFunction, RegisterGlueFunction and
RegisterTableFunction bind is now also bound under _G.ClassicAPI, which
nothing else writes -- ClassicAPI.GetServerTime,
ClassicAPI.C_Item.IsBound, namespaces kept as subtables. All three
registrars are single chokepoints, so this is one helper covering 637
in-game registrations plus 26 glue ones, and anything added later needs
no extra call.
Two properties, both of which depend on doing this in the registrar
rather than from addon Lua:
- It runs at registration, so the mirror captures OUR function. A
Lua-side `ClassicAPI.X = X` in the embedded addon would run after
FrameXML and faithfully copy the clobbered version.
- It mirrors by VALUE, reading the name back rather than making a
second closure over the same C function. So `ClassicAPI.X == X`
holds until something replaces the global, and the pair doubles as a
clobber check:
if GetServerTime ~= ClassicAPI.GetServerTime then ... end
EnsureSubTable uses raw get/set so a namespace carrying a metatable
cannot divert either side, and MirrorRegistration restores the stack via
an absolute gettop rather than counting pops.
Not covered, and documented as such: frame methods, which live in the
per-frame-type registry rather than _G, and RegisterIntegerEnum values,
where a mirror would be a stale copy rather than a reference.
Verified in-game: ClassicAPI.GetServerTime == GetServerTime is false on
a client whose FrameXML takes that global, while
ClassicAPI.GetTimeCached == GetTimeCached is true.
|
||
|
|
aacace1645 |
fix(time): take the server clock from the engine's own time sync
`GetServerTime` had two separate problems. The global is not ours to keep. Registration happens inside FUN_LOAD_SCRIPT_FUNCTIONS and FrameXML loads after that, so a client whose GameTime.lua declares its own `function GetServerTime()` replaces it on every login and every /reload, and no addon can reach the C function again. Turtle's version returns (serverHour, serverMinute) -- which is itself just the player's own machine clock, since it only diverges from date() if the realm answers a TW_TIME broadcast, and nothing in the public core does. Add C_DateAndTime.GetServerTime: the same C function under a name FrameXML never touches. The value was also the wrong clock. It was rebuilt from the broadcast gametime struct, which carries minute granularity, no timezone, and whatever per-map time offset the realm folded in before sending. The engine already has a better source: FUN_004DE430 (quest-log enter-world setup) sends CMSG_QUERY_TIME unconditionally, and the handler caches localEpoch - serverEpoch at VAR_SERVER_TIME_DELTA, refreshed hourly. The reply is a raw time(nullptr), so the skew yields a true UTC epoch with real seconds, free of both the timezone and the map offset. The sign is confirmed by the engine's own use of it -- the timed-quest expiry check in FUN_004DE510 converts a server timestamp into local-clock space by ADDING the delta. The two clocks answer different questions, so Time::Server exposes both and each function takes the one its contract names: CurrentEpoch() the instant GetServerTime, GetSecondsUntilDailyReset RealmClockEpoch() the display GetCurrentCalendarTime, GetServerTimeLocal GetServerTimeLocal is "the epoch offset by the server's timezone", which RealmClockEpoch already is by construction, so its round-trip through the *player's* timezone is gone. GetSecondsUntilDailyReset moves the other way: a realm buckets its day over a raw time(nullptr), so the boundary is UTC midnight rather than the displayed midnight. Verified in-game across an Azeroth -> Kalimdor port on two realms, one on UTC and one on UTC-5. The instant stays continuous (+51 s across the port, matching real elapsed time) while GetGameTime jumps 12 hours; GetServerTimeLocal tracks the realm's displayed clock and rolls the date with it; GetCurrentCalendarTime's hour matches GetGameTime in both zones. Fixes #50 |
||
|
|
4bf2c17e0f |
docs: repair the broken links in the API reference
Fourteen anchors in docs/API.md pointed at headings that do not exist, so those links went nowhere. Most are typos in the slug (`doesitemexit`, `gettaxiroutep`, `afters`) or a slug that was never updated after its heading gained an argument (`C_Spell.CastAtUnit` picked up `placeGroundSpell`, `GetItemSubClassInfo` picked up its `C_Item` twin). `C_QuestLog.GetQuestIDForLogIndex` was written in camel case, which a heading anchor never is. `GetMacroInfo` has no entry of its own in this document, so that reference is now plain text instead of a link to nothing. Also correct the table-of-contents text for `C_Spell.CastAtUnit`, which still named the two-argument signature. Found while checking the anchors this branch touched. A pass over both documents now reports no broken link, in either direction. |
||
|
|
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. |
||
|
|
4c7f1c36d6 |
docs: cover the macro conditions and #showtooltip in the README
The README said nothing about either, and its Macros section still claimed the macro work added no Lua functions. Two rows in Modern client behaviors: the `[conditions]` / `@unit` syntax across 38 slash commands, and what `#showtooltip` drives on a macro button. The Macros section now lists the body forms a macro accepts - the directive, the conditions, the `!Name` prefix, and `#` comment lines, which no longer reach chat. A new Slash commands section names all 38 commands by group, and the bundled-addon section mentions that it holds them and `SecureCmdOptionParse`. `C_Macro.SetMacroDisplay` and `GetMacroItem` join the Macros row of the call table, and `IsUnitToken` / `UnitTokenFromName` join the Unit row. Also add the `## MerchantFrame` heading the README already linked to. The six `C_MerchantFrame.*` entries sat inside `## Map` with no heading of their own, so that link went nowhere. |
||
|
|
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.
|
||
|
|
8b06caf708 |
docs(api): rewrite the EquipmentSet intro for the caller
The paragraph explained the storage choice rather than the API: which opcode carries set data, that "this server" does not speak it, and that the file format matches a sibling project. None of that changes what a caller writes, and "this server" names nothing. Say what the namespace does, in the section-opener style the rest of the file uses, and keep the one storage fact a caller acts on -- sets belong to one character. |
||
|
|
4684088675 |
docs(api): give GetWeaponEnchantInfo real numbers for both enchant kinds
The example claimed charges = 5 for Brilliant Mana Oil and hid the enchant ID behind a placeholder. Live dumps of both kinds correct it: the oil returns charges = 0 with enchant 2629, and Instant Poison returns charges = 40 with enchant 323. Show each case, so the zero reads as a property of time-based enchants rather than as the only answer the field ever gives. |
||
|
|
9a26207df2 |
feat(item): read a bagged weapon's temporary enchant
C_Item.GetWeaponEnchantInfo covers only the three equipped weapon slots, so a poisoned or oiled weapon sitting in a bag reported nothing. Add C_Item.GetItemTempEnchantInfo(itemLocation), returning the same (hasEnchant, expirationMs, charges, enchantID) tuple for any location the rest of the C_Item location family accepts. The temporary-enchant reader already needed nothing but a CGItem, so it now takes one directly, with a thin wrapper for the paperdoll path. Its local copy of the slot offset (0x4C) gives way to the block layout Offsets.h already carried for spell/BonusDamage.cpp, extended with the within-slot duration and charges deltas and a named temporary-slot index. Verified in game: a staff carrying Brilliant Mana Oil reports enchant 2629 both equipped and in a bag, and the remaining duration keeps counting down while the weapon sits there. Fixes #47 |
||
|
|
2adfaff020 |
docs(api): move the enchant functions into the Item section
C_Item.GetWeaponEnchantInfo and C_Item.GetEnchantInfo were documented inside the Spell section, sandwiched between C_Spell entries, and neither appeared in the Contents at all. Both now sit in Item after C_Item.GetStackCount, kept adjacent since the second resolves the IDs the first returns, and listed in that section's Contents block so body and Contents order agree. The headings are unchanged, so existing links to them still resolve. |
||
|
|
8a7ab490f4 |
docs(api): move CURSOR_CHANGED in with the other events
It was documented under Cursor while every other standalone event lives in the Events section, placed there to follow that section's alphabetical run. The heading text is unchanged, so existing links to #cursor_changed-event still resolve, and Cursor keeps a pointer to it so a reader of GetCursorInfo can still find it. |
||
|
|
5070c892e2 |
feat(texture): add Texture:SetDesaturation and GetDesaturation
Backports the parametric desaturation methods. The engine desaturates a region by storing one pixel-shader object in the region's shader slot and binding it per draw, so an amount is a matter of having more shader objects: one CGxShader per level (256 levels, framebuffer precision), created lazily through the engine's own loader under a path that exists nowhere and filled with hand-encoded ps_2_0 / ps_1_1 bytecode, then compiled the way the loader does. No draw hooks, no per-region state. SetDesaturated is re-registered on the Texture registry (the registrar front-inserts and the dispatcher walks from the front) so all three methods share one state and `false` clears a partial amount. Every desaturation path, including SetDesaturated(true), now multiplies the vertex-colour tint in like retail; the stock shader dropped it. The first ps_2_0 program was rejected by the D3D9 runtime validator: an lrp may not write a register it reads as src0 or src2. The shipped program is the instruction shape fxc emits, and both programs were validated on a NULLREF device. A build attempted while the device is lost is not latched, and a level that cannot be built falls back to the engine's stock shader. |
||
|
|
8295ec9442 |
docs(api): clarify the multi-flavor TOC section
The intro claimed this client is the Vanilla game type, which read as a contradiction against the paragraph below it saying `_Vanilla` files are not used. Both are true: `_Vanilla` as a file suffix names the Classic Era client, while `vanilla` as a directive value names this client's game type. Drop the intro sentence, since the [Family] / [Game] table already states it where a reader can use it, and add a note about the shared word where the collision is first hit. Explain why `_Vanilla` and `_Classic` are skipped instead of saying only that they target an engine this build does not match, and state the consequence: an addon shipping just `_Vanilla` and `_Mainline` TOCs does not load at all, so it needs a `_ClassicAPI.toc`. List both flavor sets in probe order, and give the Bindings half the same shape as the TOC half. The `## Interface:` subsection showed a multi-version line and then said nothing about it. Say that the addon loads when 11200 appears anywhere in the list. |
||
|
|
c5b1431073 |
feat(cvar): default scriptMemory to 0
Sets the cvar most people already set by hand, so a fresh install does not meet the interface memory popup. Only the default is overridden: the write happens when the live value still equals the cvar's registered value (read from +0x30, so no hardcoded 49152), which leaves a deliberate Config.wtf choice alone. The archive flag makes the 0 persist, so the comparison fails on every later boot and the write happens once per install. What the cvar gates, since none of it is obvious: FUN_00495590 polls Lua's live allocation (KB) against it, forces a full GC when over, and if still over fires MEMORY_EXHAUSTED and starts a 15-second timer, after which FUN_00401560(0) exits the process. FrameXML shows the event as the "disable some interface add-ons and restart" popup. The poll is gated on `limit > 0`, so 0 disables it, and nothing else caps Lua memory (lmemPool's allocator is six size classes falling through to the Storm heap, with no ceiling of its own). Timing is load-bearing: scriptMemory is writable on the glue state and read-only in the world, where the innermost setter's `if (flags & 4) return;` makes any write a silent no-op. The glue registration is what makes this land; the in-game one stays as a second chance. Verified by deleting the Config.wtf line, launching, and finding 0 in the AddOns dialog and back in Config.wtf on exit. Adds CVar::Factory::GetDefaultString for the comparison. |
||
|
|
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 |
||
|
|
7d7e392924 |
fix(spellbook): flag talent ranks by name when the next-rank link is missing
SkillLineAbility's next-rank column is empty for whole chains — every Mind Flay rank (15407, 17311..17314, 18807) holds 0 — and the engine's own rank-chain walk (FUN_SPELL_RANK_CHAIN_KNOWN) reads that same field, so IsClassTalentSpellBookItem flagged only Mind Flay rank 1. Fall back to the engine's other notion of a rank set: a spellbook spell that shares a talent rank spell's localized name, the same rule a name-cast uses to pick the highest rank. |
||
|
|
14fa610bc8 |
feat(spellbook): add the skill-line, cast-count, and loss-of-control surface
Nine C_SpellBook functions, two C_Spell functions, and one event, all
backed by engine data the stock Lua surface never exposed:
- LEARNED_SPELL_IN_SKILL_LINE(spellID, skillLineIndex, isGuildPerkSpell),
fired from the learn-spell hook under the engine's own
LEARNED_SPELL_IN_TAB gate (notified AND appended to the book). The
learn/unlearn co-hooks move from spell/Info.cpp to spell/Learn.cpp.
- GetNumSpellBookSkillLines / GetSpellBookSkillLineInfo /
GetSpellBookItemSkillLineIndex / GetSkillLineIndexByID, reading the
engine's tab array ({skillLineID, numSpells} entries at 0x00B71160).
The info table calls the engine's own Script_GetSpellTabInfo for the
name and icon.
- C_Spell.GetSpellCastCount / GetSpellBookItemCastCount: the minimum
over reagent slots of floor(carried / required), where carried is
equipped + bags 0..4. GetActionCount / IsConsumableAction are
item-only in this client, so the count is computed, not mirrored.
- C_Spell.GetSpellLossOfControlCooldown /
GetSpellBookItemLossOfControlCooldownInfo / ...Duration: the
C_LossOfControl effect that blocks a given spell, shaped as a
cooldown. Silence and pacify gate on Spell.dbc PreventionType
(+0x294, verified against six known spells).
- IsClassTalentSpellBookItem: Talent.dbc rank spells plus trained
higher ranks via SkillLineAbility's next-rank link (+0x20, verified
on Mortal Strike). Talent::SpellSet now owns the talent spell set
that GetCurrentLevelSpells already used.
- ContainsAnyDisenchantSpell: any known spell with effect 99.
Shared helpers added along the way: Spell::Lookup::SpellBankArgToBookType
and SpellbookItemArgsToID, Spell::Cooldown::Query, and
LossOfControl::LockoutForSpell.
|
||
|
|
8ca415e9a0 |
feat(spellbook): add C_SpellBook.GetPlayerSpellsByAura
Every spell the player currently knows with an effect applying the given
aura, as a 1-based ascending array of spell IDs. This is IsPlayerSpell
turned around: it walks the same known-spell bitmap and reports the set
bits whose Spell.dbc record carries the aura, so only a set bit ever
touches a record -- a few hundred lookups, not the ~28,000-row table.
It replaces a C_Spell.GetSpellsByAura that scanned the whole table and
was never committed. That answered "which spells anywhere apply this
aura", when the caller summing aura amounts is asking "which of MY
spells do" -- and the bitmap is that set. It also holds only a talent's
current rank, so a sum over the result never double-counts ranks.
Known is not active. A passive is in effect while known and never shows
in the buff list; a castable buff in the result is merely learned; a
buff another player put on us is not in the bitmap at all. Callers split
on C_Spell.IsSpellPassive and check the buff list for the rest. auraName
0 (no aura) and negatives return the empty array, as does pre-login.
Lives beside PlayerKnowsSpell in spell/Info.cpp rather than in a new
file, so the bitmap read is not copied an eighth time.
Verified in-game. Rogue: aura 217 -> {52508}, rank 2 only. Priest: aura
134 -> {14777, 45553} -- Meditation rank 3 only, plus Improved
Shadowform, a source no one had listed and the data surfaced on its
own. Each class returns empty for the other's aura.
Motivated by pfUI's energytick module: its energy-tick interval needed
the SPELL_AURA_MOD_ENERGY_REGEN_TIME amount, which it had as constants
derived from two hardcoded spell IDs. With this and GetSpellEffectInfo it
names no spell at all.
|
||
|
|
becf2f4866 |
feat(spell): add C_Spell.GetSpellEffectInfo
Returns one table per spell effect holding that effect's raw Spell.dbc fields: effect, auraName, basePoints, baseDice, dieSides, pointsPerLevel, dicePerLevel, miscValue. Three entries always, an unused slot all zeros. Deliberately raw rather than one computed magnitude per effect. The engine's figure also folds in a die roll the client cannot reproduce, combo points against the combo target, the caster's spell mods, and a level rescale for flagged spells -- a number carrying none of those while looking authoritative is worse than the inputs. The docs carry the formula and say that dieSides > 1 means the magnitude is rolled. Three new offsets. DieSides was already established by the EFFECT_BASE_DICE note, which records the verified column run as Effect@61, DieSides@64, BaseDice@67, BasePoints@76 -- it just had no named constant. The two per-level fields extend the same run at columns 70 and 73, and both are FLOAT, not int: field 73 on spells 10/17/43/91/122 decodes as 0.1/0.8/1.0/-1.0/0.5 as float and as garbage as int32. Verified in-game against answers known independently of the code: Power Word: Fortitude rank 1 reports auraName 29, basePoints 2, baseDice 1 and miscValue 2 (STAT_STAMINA), i.e. the +3 Stamina on its tooltip; Blizzard rank 1 reports effect 27 / auraName 3 with pointsPerLevel 0.1 (float32 widened), confirming the float read from Lua; Blade Rush rank 2 reports auraName 217 with basePoints 11 and baseDice 1, the 12 the server sums for SPELL_AURA_MOD_ENERGY_REGEN_TIME. Motivated by that last one: computing a rogue's energy tick interval needs the aura's amount, and the only alternative from Lua was hardcoding it or parsing a localized spell description. |
||
|
|
28658c2995 |
docs(api): move Enum.UICursorType in with the other enums
API.md already groups every Enum.* table in one run under Globals, with its own block of TOC entries. UICursorType was written into the Cursor section instead, which split that convention and gave one enum a top-level spot none of the other seven has. Moved next to Enum.SpellBookItemType, reformatted to the value-first table shape the neighbouring sections use, and left the CURSOR_CHANGED payload pointing at it by link. Also corrects "macro index" to "macro slot" in that payload list, matching what the argument now carries. |
||
|
|
f5cce25d23 |
feat(cursor): add the CURSOR_CHANGED event
Fires CURSOR_CHANGED(isDefault, newCursorType, oldCursorType, oldCursorVirtualID) and registers the Enum.UICursorType table its two type arguments index. Classic Era's Vanilla PaperDollFrame uses this event for the equip-slot highlight, so ported UI code looks for it. The trigger is a once-per-frame diff of the cursor globals on Tick::WorldTick, NOT the engine's CURSOR_UPDATE. That event only has three fire sites and none announces a non-item pickup: the cursor clear FUN_00495190 fires for every type but zeroes VAR_CURSOR_TYPE first, so the read there always says "empty", while FUN_00494b60 and FUN_004950f0 fire after a set only when a GUID or itemID is present. An interceptor on CURSOR_UPDATE therefore reported item cursors correctly and nothing else -- money, spells, macros and the two pet cursors were silent. There is no common choke point on the set side (each type writes VAR_CURSOR_TYPE in its own path), so a state diff is what covers them all. CURSOR_UPDATE is left completely untouched. Info::ReadRaw is the cheap half of the diff -- seven plain global reads, no object-manager lookup -- so the bag-item itemID resolve only happens on a frame where something actually changed. The cost of the diff is that the event lands one frame after the change. Also fixes a bug this uncovered in the shipped GetCursorInfo: Script_PickupMacro converts the Lua 1-based index into a macroID via VAR_MACRO_SLOT_MAP before storing it, so the cursor global holds e.g. 0x01000003, and PushMacroCursor pushed that straight through as the "macro index". docs/API.md already documented the return as macroIndex, so the contract was right and the code was wrong. Both paths now convert through the engine's own reverse scan FUN_MACRO_ID_TO_SLOT, the same conversion the legacy CreateMacro wrapper does. VAR_CURSOR_MACRO_INDEX is renamed VAR_CURSOR_MACRO_ID, since the old name invited the mistake. Verified in-game: item, spell (vanilla and Turtle-range IDs) and macro cursors all fire with correct old/new types, the repeated CURSOR_UPDATEs from moving a stack produce no CURSOR_CHANGED, and GetCursorInfo returns slot 4 for a General macro and 21 for a Character one. oldCursorVirtualID has no faithful equivalent here -- the modern client's "virtual ID" is not a concept this client has -- so it carries the previous content's identifying number and says so in the docs. No consumer is known to read it; Blizzard's own users treat the event as a bare notification. |
||
|
|
1306eaf1b8 |
feat(container): add four C_Container getters
GetContainerFreeSlots(bagID) returns which slots are empty as an array
of slot numbers, beside the existing count. A full bag gives an empty
table and a bag that is not there gives nothing, matching the
MayReturnNothing that Blizzard's own EquipmentManager branches on.
GetContainerItemQuestInfo(bag, slot) returns the {isQuestItem, questID,
isActive} table that draws the two quest markers on a bag button.
questID is the item's m_startQuest, isActive asks Quest::Log, and
isQuestItem is item class 12; questID stays absent rather than 0 because
every caller tests it for truth. An uncached item reports the empty
answer and warms the cache, so the next bag update draws what the first
hover could not. Verified in-game: item 18423 reports questID 7495
"Victory for the Alliance", and a quest-class item that starts nothing
reports isQuestItem with no questID.
GetContainerItemEquipmentSetInfo(bag, slot) returns whether the item
belongs to an equipment set, plus the set names joined with ", ".
Blizzard's own version is documented as non-functional, so there is no
working output to match; the lookup goes through the new
EquipmentSet::Data::SetsContainingItem, which matches on the saved
per-instance GUID. That identifies the one physical item saved into the
set rather than any copy of its itemID, and survives the item being
moved between bags. The reserved GUID_EMPTY / GUID_IGNORED slot markers
are rejected there so they cannot match a caller.
Get/SetBackpackAutosortDisabled and Get/SetBankAutosortDisabled keep the
backpack out of SortBags and the main bank container out of
SortBankBags. Both persist as cvars, like sortBagsRightToLeft. This
mirrors the per-bag BagSlotFlags.DisableAutoSort in Blizzard's generated
docs; the backpack and main bank have no slot to carry that flag, which
is why each gets its own pair.
Dropped as unimplementable rather than shipped inert:
Get/SetInsertItemsLeftToRight (the server picks the destination slot,
stack merges included, so there is no client-side insertion point to
steer) and Get/SetBackpackSellJunkDisabled (nothing sells junk here).
SortBank would be a pure alias, since kBankBags already covers the main
bank container.
|
||
|
|
c26afcc050 |
feat(baselib): forward trailing arguments through xpcall
Ports Lua 5.2's `xpcall(f, msgh, ...)` shape. This client's xpcall takes only (f, msgh), and its implementation is explicit about the rest: `lua_settop(L, 2)` discards any further arguments, then `lua_pcall(L, 0, ...)` calls f with none. So the argument-forwarding form did not fail loudly -- it called f with nothing, and a function that read its parameters saw nil. (Not a 5.0-vs-5.1 difference: both take (f, msgh). Forwarding arrived in 5.2.) Replacing the base-library function rather than wrapping it in Lua, for the same two reasons `select` and `unpack` are C in this directory. A Lua wrapper would allocate a closure AND an `arg` table per call, putting an allocation on every error-guarded path including per-frame ones; and HookSecureFunc's kUnhookableNames lists xpcall precisely because shadowing a core primitive with a Lua closure diverges from what C-side callers see. lua_pcall wants the callee and its arguments contiguous on top with the handler at a fixed index, but the incoming order puts the handler between them, so: PushValue(2) -> f, msgh, a1..aN, msgh Insert(1) -> msgh, f, msgh, a1..aN Remove(3) -> msgh, f, a1..aN then PCall(top - 2, MULTRET, errfunc = 1), push the status boolean, Insert(2), and return GetTop - 1 so the handler drops out of the result set. 5.2 does the same reshuffle with one lua_rotate, which this Lua has no equivalent of. Purely additive: a two-argument call forwards zero arguments and is the old behavior exactly, so the capturing-closure idiom in ExecuteFrameScript and the plain two-argument call in ItemUtil both keep working untouched. Verified with 25 assertions across both halves. Backward: exact return counts, embedded and trailing nil returns keeping their slots, reference identity, the handler running once and receiving the message, a non-function handler tolerated on the success path, nil f caught, an erroring handler still yielding false, and the load-bearing one -- a two-argument call still passing f zero arguments. Forward: false and embedded/trailing nil arguments surviving, twelve arguments intact, forwarding composing with multiple returns, arguments still arriving on the error path, and the two cases that target the shuffle -- the handler not leaking in as argument 1, and the handler also being passable as an argument. Two incidental confirmations: C-side lua_error does longjmp (the missing-handler case is caught by an enclosing pcall), which the notes had flagged as uncertain; and Lua-level error() still does not unwind, so f runs past it and xpcall reports success with the handler never consulted. Closes #45 |
||
|
|
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.
|
||
|
|
3ad87eb2f3 |
feat(container): add C_Container.Get/SetSortBagsRightToLeft
Sets which end of the bags a sort fills from, matching the modern pair. Backed by a `sortBagsRightToLeft` cvar through CVar::Factory, so it persists to Config.wtf and GetCVar reads it under the same name retail uses, rather than resetting every session. The whole implementation is reversed cell lists. Both placement passes still fill from the "front" and the "far end"; those ends have simply swapped which physical slot they mean, so the sorted run and the junk block flip together and junk stays opposite everything else. Not adding libbagsort's other option, which flips the category ranking so junk sorts first. It has no Blizzard counterpart, and it is mostly redundant with this one: what it is reaching for is which end of the bags the important items live at, and the fill direction already answers that by moving the sorted run and the junk block at once. |
||
|
|
a9d2ad73f3 |
feat(container): add C_Container.SortBags and SortBankBags
Two phases, because every item move is a server round trip and the second phase reads slot contents the first changed. Phase one packs partial stacks; phase two runs on the next Bag::UpdateDelayed, plans the whole layout, and fires the swaps as one batch, tracking each item's live position rather than re-reading a layout it is mutating. The ordering is ours, since retail computes it in code we cannot read and its categories have no counterpart here: hearthstone, gear by descending quality, consumables, reagents, trade goods, quest items, everything else by quality, junk last and filled from the far end. Then class, subclass, name, fuller stacks first - a real tuple comparator, so there is no zero-padding to overflow and no placeholder name to wedge an unnamed item among real ones. An item whose data has not arrived is pinned in place with its slot withheld, rather than ranked by guesswork. Neither phase may touch the Lua stack, since phase two runs from a bag update callback. Hence Lua-free ContainersFrom / AutoStoreFrom / MoveCountFrom, with the Lua-taking forms reduced to resolving the source pointer and delegating, plus a direct invMgr walk instead of ResolveBag. Five things had to be found the hard way, every one of them the client's local state disagreeing with the server's: - Never plan a swap between two stacks of the same item. Player::SwapItem tries a MERGE before it considers swapping and returns if that succeeds, collapsing two slots into one or redistributing counts and leaving both in place. Neither is a swap, so a single collision invalidated the bookkeeping for every move after it in the batch. One collision in a 55-item bag turned one pass into three. - Entry marked "unplaced" with destBag = -1, safe while bag IDs were 0..4 and wrong the moment the main bank joined as bagID -1: every item bound for the main bank read as unplaced and had its move dropped, so nothing could move into the main bank at all. The sentinel is destSlot now, which cannot collide because slots are 1-based. - FUN_INVENTORY_SWAP's last argument gates a pre-send confirmation check. With 0, a Bind-on-Equip item the character could wear is stashed behind the bind dialog and NO PACKET IS SENT - silently, since the builder returns void. Now passes 1, which is what the engine itself does when re-issuing a swap after the dialog is accepted, and is correct here because both endpoints are always bag content slots where nothing binds. - CMSG_AUTOSTORE_BAG_ITEM cannot merge across bags. Its destination byte can only be INVENTORY_SLOT_BAG_0 (255) for the player, and server-side that is the specific-container branch: keyring and backpack only. The search-every-bag path is NULL_BAG (0), which the builder cannot emit. Both sets now use one explicit two-pointer merge that addresses both endpoints and works everywhere. It costs a packet per transfer rather than per emptied source, which is the price of being correct. - The merge loop must choose split-versus-swap from its own model, not the item's live stack count. The batch goes out in one frame with no replies, so descriptors still hold pre-batch counts; a move the model knew was the last of a stack went out as a split, and the server rejects a split that would empty its source. Consolidation packs fully rather than stopping once a slot is freed: 9 and 2 with a cap of 10 become 10 and 1. It settles in one pass and sends nothing on the next call, because a packed group has every stack full except the last, so the first step walks straight to the end. Bank specifics: ViewForBag gains the main bank (bagID -1, inside the player's own invMgr) and bank bags (5..10, each with its own), which can themselves be specialty bags. Bank bags resolve only once the bank window has been opened, which is the right gate rather than an accident - the server refuses bank moves without it, so a bank sort with the bank closed finds no cells and does nothing instead of dispatching a batch that would be rejected wholesale. _classicapi_SortBagsStats() and _classicapi_SortBagsBags() report the last pass and the per-bag view. Both earned their keep: the stats ruled out our side of the swap divergence by showing a complete plan fully dispatched with zero local failures, and the per-bag dump ended the sentinel hunt by eliminating the entire area three successive guesses had been aimed at. |
||
|
|
db88fca050 |
feat(container): add C_Container.AutoStoreItem
Moves an item and lets the server pick the destination slot, which is worth having because the server does not merely find an empty one: it first merges the stack into existing stacks of the same item, splitting it across several when that is what fits, and places a remainder only if one is left. So one call consolidates a partial stack. Two engine builders back it, because the wire has two autostore opcodes. FUN_005E12E0 sends CMSG_AUTOSTORE_BAG_ITEM (0x10B) and takes a destination container, so it can confine an item to one equipped bag or let the server search the whole inventory. FUN_005E18F0 sends CMSG_AUTOSTORE_BANK_ITEM (0x282) and takes no destination at all - the server derives the direction from the source, so a bank source travels to the inventory and an inventory source to the bank. AutoStore picks between them and accepts only the pairs the wire can honestly serve. Bank-to-bank is not among them, so consolidating stacks within the bank still needs per-pair moves. Both builders' stack-arg counts come from their RET, not from a decompiler parameter list. 0x10B's last slot is never read by the body but is still popped, and declaring seven args instead of eight made the callee pop four bytes we never pushed - which shifted the caller's frame and surfaced as a garbage Lua state pointer in the next function to run, several frames from the call. Noted at both offsets, since this family is not uniform in arity. Three fixes to the shared bagID encoder found while doing it: - EncodeBagSlot had no case for the keyring (bagID -2), so SwapItems, MoveItem and AutoStoreItem all rejected keyring slots. The engine's own map in FUN_PACK_BAG_SLOT has had it all along, and the linear base was already recorded in the invMgr slot map. - Its bank constants restated named Offsets::INVMGR_* values, so they now derive from them, and the slot map is fully named rather than half constants and half comment. Each player-container range is bounded by both its own last linear slot and the live invMgr count - stricter than before, where the backpack had no upper bound at all. - FUN_PACK_BAG_SLOT's fourth out-param was labelled outUnused. It is the bank flag, and it is what makes right-clicking a bank item send 0x282 instead of using the item. |
||
|
|
e7156caa47 |
feat(console): add the rest of the console API
Eight functions alongside ConsoleGetAllCommands, completing the surface: ConsoleExec, ConsoleEcho, ConsolePrintAllMatchingCommands, ConsoleIsActive, ConsoleGetColorFromType, ConsoleGetFontHeight, SetConsoleKey and CalculateStringEditDistance. ConsoleExec is the one with real reach. Nothing in this client's Lua could run a console command before, so every entry ConsoleGetAllCommands returns was visible and unreachable at once. It is the engine's own executor -- FUN_0063CE00, which resolves the name and calls the node's +0x18 handler, the same field the enumeration reports -- and it is what replays each `SET` line of Config.wtf at boot. That includes `set`, and `set` is not SetCVar: the console handler uses the unfiltered lookup and performs no read-only test, while Script_SetCVar checks flag bit 0x4 first. So ConsoleExec can write a cvar SetCVar refuses and reach cvars no Lua getter can see. Inherent to exposing the console rather than introduced here, and documented as such. The remaining state came out of the console module: FUN_0063C860 toggles VAR_CONSOLE_VISIBLE when the key matches VAR_CONSOLE_TOGGLE_KEY and the `-console` switch flag VAR_CONSOLE_ENABLED is set, which gives an honest ConsoleIsActive; FUN_00638A60 seeds nine ARGB colours whose index is the second argument to the writer, stored per line at +0x1C; FUN_0063CB00 is a one-line setter for the toggle key. There is deliberately no ConsoleSetFontHeight, and the crash that settled it is recorded at FUN_CONSOLE_FONT_INIT in Offsets.h. Writing the height global alone does nothing, and the only thing that rebuilds the font has no code callers at all -- one table entry at 0x0080E170 -- so it runs once at startup before any console line exists. Its null-check-and-free of the previous handle reads like re-entrancy and is not: every line holds a cached font-dependent draw object at +0x20, so re-running it faults on the NEXT frame inside the texture manager, not in the call. The console's own shutdown frees the font and those objects together, which is what the pairing is for. A safe setter would mean replaying that teardown across every line to change a text size nothing asks to change. SetConsoleKey takes the client's numeric key code rather than a key name, because the console stores and compares exactly that and nothing in it translates names. Verified in-game with -console: edit distance 3 for kitten/sitting and 2 for help/hepl, red and yellow at types 3 and 4 with nil out of range, ConsoleIsActive false while closed, and exec output, a yellow echo and a prefix match for both Export commands all present in the console. |
||
|
|
02ad0ea6ab |
feat(cvar): add C_CVar.GetCVarBitfield / SetCVarBitfield
Treat a cvar's numeric value as a bitfield and read or write one bit, so a single cvar carries many independent booleans. Upstream this backs the record of which tutorial popups a player has dismissed: one cvar, one bit per popup, persisted by the config machinery for free. Namespaced only. Blizzard's FrameXML calls the bare globals, but those are its own wrappers rather than the API, and nothing here needs them. Both wiki pages are stubs, so the details come from Blizzard's generated documentation: `index` is typed `luaIndex`, which is what settles that it is 1-based; the getter's return is nilable; and the setter names its requirements as a valid and public cvar, a non-read-only one, a non-secure one, and an index in range. The first two are questions this client can genuinely answer -- the lookup is the same filtering one behind C_CVar.DoesCVarExist, so a cvar preserved out of Config.wtf without being implemented is refused here exactly as by every other Lua cvar function -- and nothing here is ever secure. The value is parsed and rewritten as a uint64 in C++, never handed through a Lua number, so all 64 bits are exact and the 1..64 index range is the arithmetic type's own width rather than a limit chosen here. Writing goes through CVar::Factory::SetString rather than the engine setter directly: that wrapper already declares FUN_SET_CVAR_VALUE as the __thiscall it is, and getting that wrong corrupts the stack silently. It also means a bitfield write fires the change callback and marks the config dirty, exactly as SetCVar does. Verified in-game against a registered cvar: bits 1 and 5 give 17, clearing bit 1 gives 16 with bit 5 untouched, and bit 64 gives 9223372036854775824 and reads back true -- a value past Lua 5.0's exact integer range, which is what proves the arithmetic is not round-tripping through a double. Out-of-range indices read nil, and setting refuses for an out-of-range index, an unknown cvar, and a read-only one. |
||
|
|
1dee8e5683 |
feat(cvar): add C_CVar.AreCVarsLoaded
Reports the cvar registry's own initialised state rather than a constant, so the function states a fact instead of an assumption. VAR_CVAR_HASH_MASK holds 0xFFFFFFFF until the first registration builds the table, and every lookup already gates on that sentinel, which makes it the closest thing this client has to "the cvar system is up". It can only return true from Lua, and that is worth being plain about. The config system runs off the boot path -- FUN_0063D380 is reached straight from the entry point, registers the console commands and replays Config.wtf -- long before a Lua state exists, so there is no window in which anything could observe false. The question is real upstream, where an account's cvars can be stored server-side and arrive after login; nothing here is fetched over the network, so once boot has run there is nothing left to wait for. Kept anyway because ported code that gates on it would otherwise call a nil, which is the whole reason the function is worth having. Verified in-game: returns true, as a boolean. |
||
|
|
583f4bb011 |
feat(cvar): add C_CVar.DoesCVarExist
A ClassicAPI addition -- no such function exists upstream -- named for the
DoesAddOnExist / DoesSpellExist pair already here.
It uses FUN_FIND_CVAR, the same lookup GetCVar and SetCVar go through,
because the question a caller actually has is whether those will work.
That makes the invariant exact:
C_CVar.DoesCVarExist(name) == (C_CVar.GetCVarInfo(name) ~= nil)
The alternative lookup FUN_0063DE30 skips the bit-31 test and would also
find a cvar preserved out of Config.wtf without the client implementing a
setting by that name. Reporting one of those as existing would mislead
every caller who then tried to read it, since no Lua getter can, so the
filtering lookup is the honest one here.
Returns false rather than raising for a non-string, matching the two
Does*Exist functions it is named after: a predicate should answer.
Verified in-game: true for a real cvar, false for an unimplemented
Config.wtf name, for a console command, for an unknown name, and for nil
and a number. A sweep over every entry ConsoleGetAllCommands returns finds
zero disagreements with GetCVarInfo.
|
||
|
|
23ebfbe7ab |
docs(cvar): record why some cvars are invisible to Lua
Chasing four cvars that ConsoleGetAllCommands reported but GetCVar raised on turned up the mechanism behind both. FUN_FIND_CVAR is not a plain by-name lookup. After matching it tests `if (-1 < (int)flags) return 0` -- the flags read as SIGNED, so it returns only cvars with bit 31 set. GetCVar, SetCVar and C_CVar.* all go through it, so a cvar without that bit cannot be reached from Lua at all. FUN_0063DE30 is the same hash walk without the test. Bit 31 is set when the registrar's registerConsole argument is 0, and the config loader FUN_0063D820 runs each `SET` line in Config.wtf as a console command, whose handler FUN_0063D500 registers an unknown name as a fresh cvar with registerConsole = 1 and flags 0 -- into which the registrar ORs the archive bit, so the config writer saves it straight back out. So any line left in Config.wtf becomes a cvar on the next boot whether or not the client implements a setting by that name: preserved across sessions, writable from the console, invisible to Lua. realmlist.wtf runs through the same path, so a line there materialises in Config.wtf too. Nothing to fix. C_CVar.GetCVarInfo already uses the filtering lookup, so it returns nil exactly where GetCVar and SetCVar do and the Lua cvar surface agrees with itself, while ConsoleGetAllCommands lists these because the console genuinely can reach them. Both functions were already right; only the reason was unrecorded. |
||
|
|
18927551d5 |
feat(cvar): add C_CVar.GetCVarInfo
Returns a cvar's value, its default, and what may be done to it. Two of
the seven returns are real here and five are structurally false, which is
worth stating precisely rather than leaving as unimplemented:
isReadOnly REAL, flag bit 0x4. Script_SetCVar tests it
before anything else and raises `"%s" is read
only`, so this answers in advance whether
SetCVar will work. Three cvars carry it on this
client: realmList, realmName, scriptMemory.
isStoredServerAccount Always false. These describe a cvar the server
isStoredServerCharacter stores per account or per character, kept in
step by the synchronizeConfig cvar. No such
mechanism and no flag bit for one exists here,
so false is accurate rather than a placeholder.
isLockedFromUser Always false. No flag governs it.
isSecure Always false. Marks cvars that cannot be set in
combat, a protection with no analogue here.
Derived by reading 3.3.5's own GetCVarInfo, which returns the first four:
value and default from the struct, then flag bits 4 and 5 for the two
server-stored booleans. The flag OFFSET transfers -- +0x1C in both -- but
the string offsets do not (3.3.5 keeps them at +0x28 and +0x40), so the
ones used here come from this client's own cvarlist handler, which
compares +0x20 against +0x30 to print "(default: %s)".
Unknown names return nil rather than raising, so a caller can tell "no
such cvar" from "set to empty". FUN_FIND_CVAR searches the cvar registry
alone, so a console COMMAND's name finds nothing and returns nil -- the
contract's "console variables only" for free, with no test needed.
Namespaced only. A bare GetCVarInfo global is nil on a live client, and
C_CVar.GetCVarBool already established the namespace here.
Offsets.h gains OFF_CVAR_DEFAULT_STR and names three flag bits, each from
the code that acts on it: archive (the config writer skips cvars without
it), staged (the setter stores to +0x38 and marks the config dirty
instead of applying), and read only.
Verified in-game: realmList reports its value, its stock default and
isReadOnly true; gxResolution reports 2560x1080 against a 640x480 default
with every boolean false; an unknown name and the console command `help`
both return nil; and a sweep over every cvar finds exactly the three
read-only ones.
|
||
|
|
2c2f280c51 |
feat(console): add ConsoleGetAllCommands
Returns every console command and console variable as ConsoleCommandInfo tables, backed by the registry FUN_CONSOLE_COMMAND_REGISTER fills. The walk mirrors the `help` handler (FUN_0063FDC0), the only other thing that enumerates it: step with next = *(uint32_t *)(node + LINK_OFFSET + 4), stop on null or a low-bit-tagged sentinel. Commands and CVars are ONE list, not two. The CVar registrar's last act is FUN_CONSOLE_COMMAND_REGISTER(cvar->name, 0x0063DDE0, categoryId, help) -- which is what makes `/console <cvar> <value>` work -- so the command list already holds every CVar, and walking the CVar list that `cvarlist` and the config saver use would report each one twice. That shared handler address is also an exact commandType test: a node pointing at it is a Cvar, anything else a Command. A pointer comparison against a value the registrar itself writes, not a name or category heuristic. Named as a global, not a C_Console member. The wiki files it under C_Console.GetAllCommands, but on a live 12.1.0 client C_Console is nil and ConsoleGetAllCommands is the real name -- the page is stale about the namespace. The field names come from Blizzard's own generated API docs and were then confirmed against a live entry: command, help, category, commandType, scriptContents, scriptParameters, with the two script fields empty strings rather than nil there too. Enum.ConsoleCategory and Enum.ConsoleCommandType are stated in full rather than derived from the engine's nine categories. Deriving works -- reading VAR_CONSOLE_CATEGORY_TABLE and capitalizing "debug" to "Debug" was verified in-game -- but it makes the enum track the wrong thing. It is a Blizzard contract, not a description of the local console, and it carries values this client cannot produce: Reveal 9 and None 10 have no category here, Macro 2 and Script 3 no registration path. A client that renamed its `gm` category would silently register Enum.ConsoleCategory.Master and turn Enum.ConsoleCategory.Gm into nil, breaking a constant meant to be fixed everywhere. Offsets.h keeps the verification: ids 0..8 are debug, graphics, console, combat, game, default, net, sound, gm in that order, so a category read off a node lands inside the enum without translation. scriptContents and scriptParameters describe console macros and scripts, which have no registration path here, so both are always "". Verified in-game: 538 entries, 487 of them CVars. `help` -> Command / Console with its description, `realmList` -> Cvar / Default, and our own `ExportDBCFiles` -> Command / Debug, which also proves the walk sees runtime registrations rather than only boot-time ones. C_Console is absent, both enums resolve including the values this client cannot return, and every field has its declared type. |
||
|
|
991baa2610 |
feat(lua): cap upvalues at Lua 5.1's 60 rather than the byte
The limit shipped at 255, the structural ceiling -- f->nups and LClosure.nupvalues are lu_byte, so that is the most a closure can hold. But the point of the change is that a function valid on a 5.1 client should load here, and 5.1's own MAXUPVALUES is 60. Anything past that is not a compatibility gap, it is an invitation to write something no other client would accept, which is not a thing to be first at. One constant. Nothing in either hook depends on which number it is: the spill path, the stale-clear and the emission loop are unchanged, and the refusal still comes from the engine's own luaY_checklimit, so its message carries whichever limit is in force. Verified in-game: 60 upvalues load and sum correctly, 61 fails with "too many upvalues (limit=60)". |
||
|
|
e68b690cf1 |
feat(lua): raise the parser's upvalue limit from 32 to 255
Lua 5.0 refuses the 33rd upvalue of a function with "too many upvalues (limit=32)", as a syntax error on the whole file. Lua 5.1 allows 60, so a large handler that reads many file-level locals can be valid on a modern client and unloadable here -- and it is the one class of 5.1 difference the source transpiler cannot reach, because the limit sits in the parser. The limit is not the `PUSH 0x20` immediate in indexupvalue. It is the size of a fixed array: FuncState carries `expdesc upvalues[32]` at +0x38, and the next field, actvar[200], begins at +0x2B8 -- exactly 0x38 + 32 * 0x14. Raising the immediate alone writes the 33rd upvalue over actvar[0], the stack of locals in scope, and the function compiles wrong without raising. In 5.0 that array has exactly two readers, both located in the binary: indexupvalue (FUN_006FDF80), which scans it and appends, and pushclosure (FUN_006FD980), which walks it after the body to emit one OP_MOVE or OP_GETUPVAL per entry behind OP_CLOSURE. Everything past the parser is dynamic -- f->nups and LClosure.nupvalues are bytes, OP_GETUPVAL's B field is 9 bits, closures are sized per instance, the debug-name array grows on demand -- so the byte is the ceiling and the array the only obstacle. Co-hook both readers and keep entries 33+ in side storage keyed by the FuncState's address. A function within 32 never leaves engine code: both hooks call the original for it. Only a function the engine would have rejected takes the reimplemented path, and that path calls the same helpers the original does -- luaY_checklimit with 255 in place of 32, so an overflow still raises the engine's own message; luaM_growaux for the name array; luaK_codeABx / luaK_codeABC for emission. Bytecode and VM are untouched: a 40-upvalue closure is one 5.0's VM already builds and runs. Staleness is self-correcting without an open_func hook. A parse error longjmps out, so side storage keyed by a stack address can outlive its function and the next chunk may reuse the address. But side entries exist only while nups > 32 and indexupvalue is the only writer, so a FuncState arriving there with nups <= 32 cannot own any -- whatever is filed under its address is cleared on the new function's first upvalue, before anything could read it. Compile-time only, so no per-frame cost, and nothing else hooks lparser internals -- LuaSyntax's transpiler hooks luaL_loadbuffer, a different function, and the other Octo DLLs do not touch the compiler. The Proto offsets Frame::ScriptArgs kept locally move to Offsets.h now that a second file reads the struct; its numparams @+0x45 / is_vararg @+0x46 independently pin nups to the byte before them. Verified in-game: 32 and 33 both load (engine path, first spill); 40 upvalues through the OP_MOVE path and again through a middle function's OP_GETUPVAL path each return the right sum; a syntax error inside a 40-upvalue body followed by a clean parse still returns the right sum (the stale-clear); 255 split across two scopes loads, and 256 fails with the engine's own "too many upvalues (limit=255)". |
||
|
|
09c5832ae8 |
fix(texture): make texture coordinates address the atlas art, not the file
With an atlas applied, SetTexCoord was addressing the whole sheet, so a crop showed a slice of the surrounding art rather than a part of the sprite, and GetTexCoord reported the atlas rect where a caller expected what it had asked for. Both came from one cause: SetAtlas was writing the atlas rect into the region's only set of coordinates, leaving the caller's own nowhere to live. A live client shows the two are separate state there: GetTexCoord reads the full 0..1 rect immediately after SetAtlas, with GetAtlas still reporting the atlas, so 0..1 means all of the sprite rather than all of the sheet. Keep the caller's coordinates alongside the atlas name and compose: SetTexCoord records them in sprite space and writes the mapped result for the engine to draw, GetTexCoord hands them back. Both handlers are co-hooked and pass straight through for a texture with no atlas, which is every texture in the game until an addon calls SetAtlas -- the empty-map test is the whole cost in that case. Both the 4-argument and 8-argument corner forms compose; anything else is left to the engine to reject so its own error text is what the author sees. ResetTexCoord becomes a plain restore of identity, which is what it always was conceptually -- the atlas rect now falls out of composing identity rather than being a special case. Also clear the atlas on SetTexture rather than inferring it from the texture handle. The handle comparison cannot detect a re-set to the very file the atlas names, because the engine returns the same HTEXTURE, so GetAtlas kept reporting an atlas that was no longer showing. That guard predates this change. It stays for recycled regions, which is the case it is actually good for and the reason this module needs no region constructor hook. Verified in-game against a registered quarter-rect atlas: identity is reported after SetAtlas, a crop reads back in sprite space, the engine receives the composed file-space rect from both argument forms, reset returns to the full sprite, SetTexture clears the atlas even to the same file, and a texture with no atlas behaves exactly as before. |
||
|
|
4015fee5e2 |
feat(texture): add texture:ResetTexCoord
Drops a crop made with SetTexCoord or SetSpriteSheetCell and goes back to showing the whole of whatever the texture points at. What "the whole of it" means was the only open question, and the generated API docs answer none of it -- ResetTexCoord is listed with no arguments, no returns and no description, and Blizzard's own FrameXML never calls it. Settled by testing a live client instead: with an atlas applied, GetTexCoord reads the full 0..1 rect, and a reset after a SetTexCoord returns to that with GetAtlas still reporting the atlas. So the source and the user's texcoords are separate state there, and 0..1 means "all of the sprite" rather than "all of the sheet". Here an atlas IS its texcoords -- SetAtlas is SetTexture plus SetTexCoord, with no second layer to hold the sub-rect -- so identity for an atlas'd texture is the atlas's own rect. Resetting to a literal 0,0,1,1 would show the whole sheet where retail shows the sprite, so the atlas rect is restored instead, which reproduces the visible result. Reuses GetAtlas's staleness guard, so a texture pointed elsewhere since resets to the full rect. Verified in-game against a registered quarter-rect atlas: SetAtlas gives the rect, SetTexCoord replaces it, ResetTexCoord restores it with the atlas still set, and a plain textured region with no atlas resets to 0,0,1,1 with GetAtlas nil. |
||
|
|
8706d1d99b |
docs: combine the launch switches into one API.md section
The two README rows covered one subject -- things you put on the command line that starts the game -- and each carried its full detail inline, which is the one place in that table where a row was doing a reference page's job. Fold them into a single linked row and give the detail a Launch section in API.md, next to the console commands, which are the other entries that are not Lua functions. The section also states what the two switches share, which neither row had room for: the name matching is case-insensitive, `-name value`, `-name=value` and `/name value` are equivalent, and a value with spaces needs quoting. For -config it now says what does and does not follow a profile, since the addon enable list living under WTF\Account\ is the part that surprises people. |
||
|
|
9a8c314d69 |
fix(aura): scope flag-nibble polarity to Turtle
The aura flag nibble does not mean the same thing on every server, and
reading it as polarity everywhere was badly wrong off Turtle.
Stock (vmangos SpellAuraDefines.h + SetAuraFlag): the bits are
CANCELABLE 0x01, EFF_INDEX_2 0x02, EFF_INDEX_1 0x04, EFF_INDEX_0 0x08 —
one per spell effect index that carries an aura, plus cancelable for a
positive aura. No polarity is encoded at all. So testing 0x08 for
"harmful" was really testing "effect index 0 has an aura", which is true
of nearly every aura, and reported almost every BUFF as a debuff.
Turtle (tortoise-wow SetAuraFlag) replaces those effect-index bits with
polarity: 0x04 positive, 0x08 negative. It needs to, because it also
drops the else in the slot search so a debuff spills into 0..31 once the
16 harmful slots are full — the range stops being reliable there and the
nibble is what preserves the answer. Stock keeps a strict either/or, so
nothing ever crosses over and the range is exact.
IsSlotHarmful now picks per server and is the one place that decides.
Every other site defers to it rather than testing either signal.
Identity detection rather than behavioral: on Turtle every nibble is one
of {0x04,0x05,0x08}, while stock nibbles routinely fall outside that set,
so an out-of-set nibble proves stock — but the converse never arrives,
since single-effect stock auras land on 0x08 by coincidence. Stock is
provable, Turtle is not, and the unprovable direction is the catastrophic
one. A Turtle fork still detects (clones keep the TURTLE_* global names).
A non-Turtle server that copied the spill patch falls back to the range
and reports spilled debuffs as buffs, matching what native
UnitBuff/UnitDebuff already do there.
|
||
|
|
7ab32df2aa |
feat(texture): add texture:SetSpriteSheetCell
Crops a texture to one cell of an evenly divided grid, which is the arithmetic every sprite-sheet call site would otherwise repeat. It is the primitive behind raid target markers, whose eight icons share one 4x4 sheet, and this client already ships the FrameXML helper (SetRaidTargetIconTexture) that wants it. `cell` is 1-based and counts left to right then top to bottom — Blizzard types the argument `luaIndex`, and its own callers pass GetRaidTargetIndex straight through without adjusting it. cellWidth and cellHeight are accepted and ignored. Both call sites in Blizzard's UI pass the three-argument form, and the grid alone already fixes each cell's coordinates, so honoring them would mean guessing at their meaning. The coordinates go through the engine's own SetTexCoord handler, so this module contributes only the grid math. |
||
|
|
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. |
||
|
|
c3cf9e6f3a |
feat(texture): add atlas support — C_Texture, SetAtlas, and |A markup
An atlas names a texture plus a sub-rect inside it, so SetAtlas is the engine's own SetTexture + SetTexCoord (+ the size setters for useAtlasSize) driven off one lookup. Every step delegates to the engine's Lua handlers, so the argument guards and the UI-scale conversion stay in force and this module only adds the name resolution. Adds C_Texture.GetAtlasInfo / GetAtlasExists / GetAtlasID / GetAtlasElementID / GetAtlasElements, the RegisterAtlas extension for addons that ship their own sprite sheet, texture:SetAtlas / GetAtlas, and the |A:name:h:w|a inline markup alongside the existing |T form. All five readers key off one bound set, so GetAtlasExists is true exactly when GetAtlasInfo returns a table. The built-in table is five rows on purpose. Measured against Classic Era's UiTextureAtlas tables and the community listfile: 0 of 868 atlas sheets exist in this client's art, and while Blizzard kept the original vanilla filename as the atlas name for 16 members, only 5 have dimensions that agree — vanilla's own scrollbar template draws a centered 16x16 out of a 32x32 file that the atlas calls 18x16. Texcoords are not derivable from the two tables, so the rest grow from _classicapi_DumpAtlasMisses() rather than from guesses. AtlasData.h carries the full derivation. |A shares every scanner, measure, wrap and placement stage with |T — ParseAtlasIcon fills the same IconDesc, since an atlas is exactly the path-plus-sub-rect that struct already holds. That makes the chat anti-spoof mandatory, not optional: IconFilter now defangs |A too, or a player could render art by typing it into /say and the speech bubble. GetAtlas stores the HTEXTURE it installed and clears itself when the region points elsewhere, which gives the correct nil-after-SetTexture behavior and avoids a second hook on FUN_SIMPLETEXTURE_CTOR — Texture::Mask owns that target and MinHook refuses a duplicate, which would abort the whole hook install. |
||
|
|
f5d6046523 |
feat(map): add C_Map.GetMapArtLayers
Describes the single fixed layer a map's background is drawn as: a 1002x668 canvas cut into 256-pixel tiles (the 4x3 grid of twelve the world map frame draws), scale 1 to 1 with no extra zoom steps, since a map does not zoom here. A map with no art returns an empty table. Canvas and tile sizes come from the client's own WorldMapFrame.xml, and move to Map::Area so the overlay hit-rect math shares them instead of keeping a second copy. They stay constants on purpose. A live read of WorldMapDetailFrame looks more engine-driven but is wrong twice: the frame is addon-mutable while the DBC coordinates it normalizes are authored against the shipped size, and these are logical sizes -- an HD map patch ships larger tiles, which Map::Overlays already detects and scales, and reporting a patched tile's real size would break the canvas/tile division that yields the grid. |
||
|
|
e1ebf6ecce |
feat(map): add C_Map.MapHasArt and GetMapArtLayerTextures
A map's background is the tile set Interface\WorldMap\<dir>\<dir>1..12, where <dir> is the WorldMapArea row's own name -- the path the world map frame builds its tiles from. So "does this map have art" and "give me its tiles" are both answerable by probing that set, even though the modern atlas art model has no counterpart here. MapHasArt is independent of whether a map has coordinates: the whole-world map has art but a zero rect, and instance rows can have a rect but ship no art. GetMapArtLayerTextures returns texture PATHS rather than the numeric file ids of the modern call. A texture is named by its path on this client and SetTexture takes that path, so ids would be both unavailable and unusable; GetMapOverlays already makes the same substitution for its fileDataIDs. There is one art layer, so layerIndex 1 returns the background and any other index an empty table. Path convention and the 12-tile count taken from the client's own FrameXML rather than assumed. |
||
|
|
698827e9c5 |
fix(addons): report a real loaded state from IsAddOnLoaded
The engine sets an addon entry's loaded byte at the START of its load, before dependencies and before the addon's own files run, clearing it again only if a required dependency fails. That byte therefore means "load has begun" -- it is loadedOrLoading, not loaded. IsAddOnLoaded returned it for both values, so an addon checking itself at file scope got (true, true) where it should get (true, false). The old comment claimed the in-flight window was unobservable from Lua; it is plainly observable, since the addon's own files and every dependency pulled in during them execute inside it. Add AddOns::LoadState, which co-hooks the per-addon loader and keeps a stack of the names currently loading -- a stack because dependency loads nest, and the name is copied because LoadAddOn passes a transient Lua string. loadedOrLoading stays the engine byte; loaded now also requires the addon not to be mid-load. Known gap, documented: an addon asking about itself from its own ADDON_LOADED handler still reads (true, false), as that event fires just before the load call returns. Also mirror the stock LoadAddOn global into C_AddOns. It already returns the modern (loaded, value) shape -- 1/nil plus a locale-independent reason token -- so it registers as the engine's own handler. |
||
|
|
60530e32fc |
feat(faction): add C_Reputation inactive getters and by-id setters
Adds SetFactionInactiveByID / SetFactionActiveByID, which file a faction into or out of the "Inactive" category by id rather than by displayed-list position, plus IsFactionActive and IsFactionActiveByID to read that state back. IsFactionActive is a real backport and takes a sort index, returning a boolean; the ByID forms are ClassicAPI extensions. Both stock setters are just an index resolve around one shared engine setter that already takes a faction id, so the by-id pair is that call with 1 or 0. It sends the change to the server, rebuilds the displayed list (so positions shift), and being the function UnitFactionPolyfill hooks, fires UNIT_FACTION. The inactive getter is the odd one out: unlike the at-war getter, its worker takes the 0-based index and resolves internally. So both read forms are built from Resolver() plus a factored rep-slot read, which reproduces the engine's own index -> factionID -> repListID -> flag chain and lets them share one implementation. Also mirror the stock SetFactionInactive, SetFactionActive and IsFactionInactive globals into the namespace, registering the engine's own handlers rather than reimplementing them. |