mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 08:00:42 +00:00
14fa610bc80ddcd0585f604ca672a6b57b53811f
474
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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. |
||
|
|
3cffb71b20 |
feat(faction): add C_Reputation.ToggleFactionAtWarByID
Flips a faction's at-war state by ID rather than by displayed-list position. A ClassicAPI extension -- Blizzard has no such call. The stock FactionToggleAtWar(index) resolves its index to a faction id and then reads, negates and writes through two helpers that already take an id, so the by-id form is that pair without the resolve. Every rule stays in the engine: the refusal to make peace below -3000 standing, the peace-forced flag, the loot-session bail, and CMSG_SET_FACTION_ATWAR. Going through the engine's setter also picks up UnitFactionPolyfill's hook on it, so UNIT_FACTION fires, and its change detection keeps that silent when the engine refuses the toggle. Declare the setter's newState as int, matching the polyfill's detour: a char argument defines only the low byte of EDX and would leave the detour's int parameter with undefined high bits. Also mirror the stock global into the namespace as C_Reputation.ToggleFactionAtWar, registering the engine's own handler rather than reimplementing it. Adds the getter and script-wrapper addresses, which existed only as comment references. |
||
|
|
7887237a6e |
feat(faction): add C_Reputation.SetSelectedFactionByID
Selects a reputation-pane faction by ID rather than by displayed-list position, matching what SetWatchedFactionByID gives over the stock index call. A ClassicAPI extension -- Blizzard has no such call. The engine already holds the selection AS a faction id: the stock SetSelectedFaction(index) resolves its argument through the faction index resolver and stores the resulting id, and GetSelectedFaction maps that id back to an index. So this writes the id straight through, with no list walk, and works even while the faction is not listed. Also mirror the stock SetSelectedFaction global into C_Reputation. Its handler already has the Lua C ABI, so it registers as-is rather than being reimplemented. |
||
|
|
98af79137b |
feat(faction): add C_Reputation.GetFactionDataByID
Keys the modern FactionData table by faction ID instead of by displayed-list position. Reuses the shared ReadFactionData chain and table builder, so it needs no new engine work. Unlike GetFactionInfoByID this is not limited to the player's reputation list: an unencountered faction fills cleanly with currentStanding 0 and atWarWith false, so any real faction's name, description and thresholds are readable. |
||
|
|
622882725f |
feat(map): C_Map user waypoint (Tier 3)
Add the eight user-waypoint calls and USER_WAYPOINT_UPDATED: set, get, has, clear, per-map position, the two hyperlink converters, and the can-set check. The pin is one piece of session state (a uiMapID, a 0..1 position and an optional z) that survives a UI reload. GetUserWaypointPositionForMap re-projects it onto any other map through world coordinates, so a zone pin resolves on its continent and back. The hyperlink is the standard worldmap:uiMapID:x:y payload with both coordinates scaled by 10000, and the parser accepts a whole link or the bare payload. UiMapPoint's factories go in the addon, matching where retail ships them. Extract the shared vector2 marshalling to map/Vector2.h so the waypoint and coordinate modules don't each carry a copy. |
||
|
|
0517bb3753 |
feat(map): C_Map map hierarchy (Tier 2)
Add GetMapInfo, GetMapChildrenInfo, GetMapInfoAtPosition and GetFallbackWorldMapID, giving the World -> Continent -> Zone tree. Continents carry no AreaTable id (their WorldMapArea rows have areaID 0), so they are named by a negative -(WorldMapArea row) -- mirroring the engine's own zoneOrSort idiom, where positive is an AreaTable zone and negative a QuestSort row. Names and mapType for those come from Map.dbc. Move the row math into Map::Area (RowForUiMapID, ContinentRowForMapID, RowRect, PercentInRow, WorldFromRow) and put the Tier 1 coordinate functions on it, so they accept continent ids too and GetMapRectOnMap honors topUiMapID. |
||
|
|
fb17488237 |
feat(map): C_Map coordinate transforms (Tier 1)
Add GetPlayerMapPosition, GetWorldPosFromMapPos, GetMapPosFromWorldPos, and GetMapRectOnMap on the existing AreaTable-id=uiMapID scheme, reusing Map::Area's world<->map projection. Positions returned as Vector2DMixin. |
||
|
|
c08ded6db4 |
feat(texture): BLP loads at any size; guard the async fallback
BLP decodes into the shared scratch BEFORE it calls the allocator, so the size cave (which fires from the allocator) was always too late for it — a 2048x2048 BLP overran the scratch on this client. A pre-hook on the decompressor FUN_005A8430, which carries the level-0 dimensions, grows the scratch first and repoints the caller's already-copied scratch slot at the new buffer, or fails cleanly for a texture the GPU cannot hold. It acts only when the slot IS the shared scratch; the IMG path decodes into its own right-sized buffer and is left alone. GrowScratch now retires the previous buffer one generation late (frees at the next growth) so any unaccounted holder reads stale bytes, not unmapped memory. Verified: a 2048x2048 DXT1 BLP renders and grows the scratch to 2048. The async force-load path shoves a read that never fit the shared buffer into a 512 KiB static fallback with no size check — the engine bug behind "big BLPs crash". The hook refuses a request larger than the fallback; the texture stays blank. Growing the fallback to fit was tried and reverted: the read runs on the engine's async reader thread, which has no crash handler, and a read into a right-sized heap buffer froze then killed the process where the same read into the oversized shared buffer does not — not yet isolated. Consequence: an uncompressed BLP file larger than the shared buffer (2 MiB stock, 32 MiB with VanillaHelpers) does not load; DXT stays far under it and TGA is synchronous, so only a pathological input is lost. Verified: a 2900x2900 uncompressed BLP draws nothing and does not freeze. |
||
|
|
640f78b2eb |
docs: texture size and shape
README gains an "Any texture size" row in Modern client behaviors; API.md gains a "Texture size and shape" section under Frame, after the texture methods: any width and height, no fixed upper limit beyond the graphics card's maximum, memory allocated only when a large texture loads, and the two remaining file-level limits (BLP files over ~2 MB / 32 MB with VanillaHelpers stay blank; NPOT BLPs with DXT or mips are untested). |
||
|
|
b81f672ad7 |
fix(aura): classify auras by polarity flag, not slot range
The server seats buffs in slots 0..31 and debuffs in 32..47 only while it can: once the 16 debuff slots are full, _AddSpellAuraHolder parks further debuffs in free BUFF slots and sets UNIT_FLAG_AURAS_VISIBLE so the client still renders them (tortoise-wow, verified). Classifying by slot range therefore reported those as buffs -- absent from HARMFUL, and wrong in isHelpful / isHarmful. Confirmed live on a 20-aura target: 18 harmful, two of them sitting in buff slots, where the old code returned 16. Every visible aura carries its real polarity in the per-slot flag nibble (SpellAuraHolder::SetAuraFlag writes 0x04 positive / 0x08 negative), so HELPFUL / HARMFUL now select on that instead. All the walkers -- by index, by spell ID, by name, GetUnitAuras, GetAuraSlots -- share one order helper, SlotInFilterOrder, which visits the polarity's home range first and the other range after, so every index is unchanged whenever nothing has spilled. Aura::Source's KindForSlot classifies the same way, keeping the descriptor-drop fallback consistent with the query paths. The out-of-range group array carries spell IDs with no flags, so that path stays range-based -- the seating range is the only polarity it has. GameTooltip:SetUnitAura now bridges the two index spaces. The engine's SetUnitBuff / SetUnitDebuff index their own slot RANGE, which diverges from the polarity index space as soon as a debuff spills, so the method resolves (index, filter) to an absolute slot and hands the engine the index that slot holds within its own range, picking the method by where the slot lives. It counts with the engine's TOOLTIP visibility predicate (FUN_GAMETOOLTIP_AURA_VISIBLE = 0x00534DF0), not the UnitBuff one (0x00519860): the latter adds a per-player immunity-bitmap check off record +0x2B0, so the two index spaces are not interchangeable. Both decompiled to confirm the walks being mirrored. The aura tooltip builder only ever receives spellId / level / stacks, so a debuff parked in a buff slot renders identically through SetUnitBuff. Note this is deliberately MORE than the engine does: stock UnitBuff / UnitDebuff split by slot range and show a spilled debuff as a buff. Retail's contract is the aura's actual polarity, and the descriptor already carries it, so we report that. |
||
|
|
fdbe66b057 |
fix(aura): let a duration rule edit an aura its own trigger creates
Turtle's Bestial Wrath gives the hunter's pet Scent of Blood for 18s, but C_UnitAuras reported 8s and then dropped the timer entirely while the buff was still up. Server-side (tortoise-wow spell_hunter_bestial_wrath) Bestial Wrath neither applies the aura nor carries its duration on the wire: effect 0 is TRIGGER_SPELL(Scent of Blood, 52995), and the script then stretches the holder that trigger just created via SetAuraMaxDuration/SetAuraDuration. Both are plain field writes, and 1.12's only duration packet is scoped to an aura-bearer that is a PLAYER, which a pet is not -- so the client never hears the 18s and keeps the 8s base it computed when the aura landed. Exactly the class of edit Aura::Source's duration rules exist to mirror; two things had to change before one could express it. The affected-aura selector demanded a SpellFamilyFlags overlap, and every Turtle custom spell carries flags of 0 (308 in the hunter family alone), so no mask could ever name this aura. It now takes a family-flag overlap and/or a SpellIconID, at least one of the two -- an icon is shared across a spell's whole rank ladder, so it stays as rank-proof as a flag, and icon 2245 picks out exactly the four Scent of Blood records and nothing else. Registrars reject the mask-0 + icon-0 rule that would match a whole class family, and RefreshDurationByFamily takes the same invariant so the two entry points cannot disagree about what they match. A trigger can also CREATE the aura it edits, which the immediate-apply model could not see. The trigger's SMSG_SPELL_GO arrives before the triggered cast's, so editing at trigger time either matches nothing or is overwritten moments later when the triggered cast stores its own base duration -- the edit is lost either way. Idempotent ops now ARM the target as well, and the next matching store re-applies the edit, from the cast path or the application path, whichever the aura arrives on. Only refresh and set arm: re-running those lands on the same value, while reduce would shave twice and remove would kill an aura that was legitimately re-applied, so Conflagrate behaves exactly as before. The rule reads Bestial Wrath's own duration from the client's spell data instead of hardcoding the server's 18s, so a rebalance that patches the DBC carries over on its own. Fixes brues-code/pfUI#50 |
||
|
|
bd1bd9f5d8 |
feat(aura): slot-batching API and lazy caster match
C_UnitAuras.GetAuraSlots / GetAuraDataBySlot / UnitAuraBySlot: enumerate a unit's auras once into opaque slot ids and fetch each by id, so a full scan walks the aura array once instead of once per index (the by-index getters re-walk from slot 0 on every call). Slot ids cover live descriptor slots, the stealth / range cache fallback, and the out-of-range group array, so the slot path keeps every source the by-index path had. GetAuraSlots also takes a table as a 5th argument (ClassicAPI extension) and fills it in place, returning `continuationToken, n`. Lua 5.0 allocates an `arg` table for EVERY vararg call (luaD_precall 0x006F6050 -> adjust_varargs 0x006F6200 -> luaH_new, verified in Ghidra), so a Lua helper receiving the retail multi-return costs one table per batch. The fill form keeps per-frame scans allocation-free; AuraUtil.ForEachAura / FindAura use it with a per-nesting-depth buffer pool instead of retail's vararg helpers. The descriptor walkers (FindNthSlot, FindSlotBySpellID/Name, GetUnitAuras) now evaluate IsPlayerCast only when the filter restricts on caster. It scans the Aura::Source cache (~1000 entries in a raid) and was paid for every populated slot on every call, PLAYER token or not. Cache-fallback eligibility is centralized (EligibleFallbacks / EligibleGroupFallbacks) so the by-index, bulk, and by-slot paths share one ordering, which is the ordinal an opaque cache slot id encodes. |
||
|
|
4d744b6638 |
feat(interface): INTERFACE_VERSION global constant
Publishes INTERFACE_VERSION (11200 on this client) — the client interface/TOC version, read from the engine's own accessor (FUN_ADDON_CLIENT_INTERFACE_ VERSION, the same value the addon loader compares each `## Interface:` against) rather than a literal. A global number re-published every /reload via ModuleAutoRegister, mirroring CLASSIC_API_VERSION, since it is a fixed client constant. Verified in-game: /dump INTERFACE_VERSION -> 11200. |
||
|
|
c2a4cbdf27 |
docs: drop WoW-version and vanilla-gap phrasing
The docs are a modern-API backport onto 1.12, so "added in <patch>" and "vanilla 1.12 lacks/does X differently" are implied by the doc existing — they were noise. Swept both across docs/API.md and README.md: dropped the version-introduction and vanilla-limitation clauses, and where a version note was the only thing explaining a hardcoded/degenerate return value, kept the reason without the version. Behavior notes and "ClassicAPI extension" provenance are unchanged. The large line count is mostly paragraph reflow after clause removal; no API names, signatures, or code examples changed. |
||
|
|
d30ae53fbf |
feat(editbox): ClearHistory
Empties the up/down input history. The engine's SetHistoryLines internal (FUN_0077cd90) frees the whole history ring when called with 0, so clear = free (0) then reallocate at the saved max — dropping every entry and resetting the write position while keeping the line limit, so the box keeps recording afterward (matching modern semantics, not "history disabled"). No-op when the box has no history. New offsets: OFF_EDITBOX_HISTORY_MAX (+0x388, the ring capacity GetHistoryLines reads), FUN_EDITBOX_SET_HISTORY_MAX. Verified in-game: AddHistoryLine + ClearHistory leaves GetHistoryLines unchanged and the up-arrow history empty; new lines still record. |
||
|
|
8f32955823 |
feat(editbox): SetHighlightColor / GetHighlightColor
The engine paints the text selection with three Texture regions (start-line
+0x350, middle-block +0x354, end-line +0x358; positioned by FUN_0077d950),
and their vertex color IS the highlight color — there's no single color field.
So SetHighlightColor packs {b,g,r,a} and writes it to all three via the
engine's own generic region color setter (FUN_0077f750, the same one behind
Texture:SetVertexColor / FontString:SetTextColor), and GetHighlightColor reads
the first region back through the matching getter FUN_0077f8c0 (the read half
of Texture:GetVertexColor). The blinking caret is a separate region (+0x3d4),
left untouched.
Colors are 0..1, alpha defaults to 1. New offsets: FUN_REGION_GET_COLOR,
OFF_EDITBOX_HIGHLIGHT_REGION; FUN_FONTSTRING_SET_COLOR relabeled as the
generic region color setter it always was.
Verified in-game: SetHighlightColor(1,0,0) reads back 1 0 0 1 and a selection
paints red.
|
||
|
|
2778643f4f |
feat(editbox): GetUTF8CursorPosition, ClearHighlightText, HasFocus, HasText
Round out the EditBox method backports alongside Set/GetCursorPosition, all reusing state the engine already maintains: - GetUTF8CursorPosition — caret as a character index (vs GetCursorPosition's byte offset), via the engine's own byte->char counter FUN_0077bc80. - ClearHighlightText — drop the selection but keep the caret (collapse selStart/selEnd onto the cursor + highlight-dirty bit). Vanilla can only clear a selection with HighlightText(0,0), which yanks it to offset 0. - HasFocus — pointer identity against VAR_FOCUSED_EDITBOX (the global the engine's SetFocus writes / ClearFocus clears). - HasText — text byte length (+0x338) is non-zero. Registered on the EditBox method registry, so only EditBox frames dispatch them. New offsets: OFF_EDITBOX_TEXT_LENGTH, FUN_EDITBOX_COUNT_CHARS. The module now covers cursor / selection / focus / text-state, so it moves from editbox/Cursor.cpp to editbox/Methods.cpp (namespace EditBox::Methods). Documented in docs/API.md and the README under the Frame widget section. Verified in-game: SetText+SetFocus reports HasFocus/HasText true and both cursor getters 5; an empty box reports both predicates false. |
||
|
|
c20be0cef1 |
feat(editbox): SetCursorPosition / GetCursorPosition
Vanilla's EditBox registry has 48 methods (HighlightText, Insert, SetText, ...) but no cursor accessor, so modern addons that set text then place the caret error with "attempt to call method 'SetCursorPosition' (a nil value)" (reported: TwitchEmotes autocomplete). The caret already exists in the engine — a byte offset at editbox+0x36c — with reusable primitives: FUN_0077e360 clamps and sets it (the engine's own "restore caret" step in the insert path), FUN_0077ccf0 collapses the selection onto it. Modern SetCursorPosition is byte-based too, so it maps 1:1. New EditBox::Cursor module registers both methods on the EditBox method registry (0x00CF5378); registering under that context means only EditBox frames dispatch them, so `this` is always a real CSimpleEditBox. Set path: clamp+set the caret, collapse the selection, flag the highlight dirty. Verified in-game: SetText + SetCursorPosition + GetCursorPosition round-trips and the caret lands at the requested offset. |
||
|
|
1ad6b57202 |
fix(table): writer-side mark for deliberate nil appends
The v1.12.8 gap heuristic (keep the stored length when it overshoots the border by exactly one) protected `table.insert(t, nil)` slots (#36) but broke every 5.1-dialect table that is stale by exactly one — a pairs-cleared one-element table, or a recycled table whose previous life was one slot longer. Tablet-2.0's del()/copy() pool produces the latter on every tooltip refresh, so FuBar/Ace2/Tablet menus and tooltips shifted by one with a nil hole at slot 1. The two states are byte-identical, and both consumers reach the heal through table.insert — neither the table nor the caller can split them. Only the writer knows which dialect the table speaks, and the write is observable: co-hook the engine's table.insert (FUN_LUA_TABLE_INSERT = 0x7FB6B0, verified against the table-lib luaL_reg pair in .data and a decompile matching 5.0.2 tinsert line for line) and record {table -> stored length} in a weak-keyed registry table whenever the two-arg form appends a literal nil. Rule 3 now heals every stale table to the border (the 5.1 answer) and keeps the stored length only when the gap is one AND the mark still matches. Stale marks die on their own: any later insert/remove moves the stored length off the recorded value, and the weak key collects with the table. Verified in-game with a 21-test suite (directed regressions for #29/#36/#39, byte-identical twin discrimination, metamethod isolation, coroutine-side marking, and a seeded differential fuzzer against an executable model of the contract): 15/21 on the broken build, 21/21 with the fix, #36's nil-append cases among the passes both times. New plumbing: LUA_SET_METATABLE (0x6F4020, from LuaCAPI.md) and Game::Lua::SetMetatable for building the weak mark table from C. Fixes #39 |
||
|
|
94e77ef5af |
feat(unit): UnitCreatedBySpell + consolidate the unit-token resolver
Add `UnitCreatedBySpell(unit)` — the spell that summoned a unit (a totem's totem-drop spell, a pet/guardian's summon spell), read from the unit's UNIT_CREATED_BY_SPELL descriptor field (byte +0x230). It is the same field the engine's unit-title builder consults to pick the Pet/Minion/Guardian/ Creation title, and it is broadcast, so it resolves for any unit in range. This is the summoning spell, distinct from the (server-only) spell a totem casts. Also add a single `Game::ResolveUnitToken(token)` helper that wraps the engine token->CGUnit* resolver, and route unit/Pet.cpp through it plus the Game::Read<T> field accessors — removing the hand-rolled ResolveUnitToken_t typedef and raw reinterpret_casts from this module. The name was already referenced in Offsets.h and CLAUDE.md but had never been implemented. |