mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 16:10:36 +00:00
b4e5f4f2bb13742c58b4cb2956d8aaf514b4d010
408
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b0585f5628 |
feat(sound): add C_Sound.PlayVocalErrorSound and Enum.Vocalerrorsounds
Plays the player character's spoken complaint for an error ("my bags are
full") in their race's and sex's voice.
This one maps exactly rather than approximately: VocalUISounds.dbc's
second column IS the modern Enum.Vocalerrorsounds value, and this build
carries every one of the 68 values (0..67) across 11 races. Verified by
resolving a row's sound ids to their SoundEntries names — row
{9, 0, 1, 1875, 1999, ...} is error 0 for race 1, whose normal sounds are
HumanMale_InventoryFull and HumanFemale_InventoryFull, which also pins
the column layout {id, enum, race, normal[male,female],
pissed[male,female]}.
The row lookup is ours because the engine has none: it loads the table
and never reads it, the only xrefs to its records/count globals being the
loader's own writes. Only the indexing is reimplemented — the same
records[id] walk every other DBC reader here performs — while the play
goes through the engine's by-id player like every other sound.
Race and sex come from the login-time bytes rather than the unit
descriptor, so this resolves from addon-load onward, before the in-world
player object exists.
The "pissed" column is deliberately unused: many of the ids it names
match no SoundEntries row. Combinations with no recording play nothing
and raise nothing, which is data rather than an error.
Verified in game on a Night Elf female: Inventoryfull, Outofammo and
Nomana each played, and GetRecentSoundFiles showed
Sound\Character\NightElf\NightElfFemaleErrorMessages\... — right race and
sex — with varying file suffixes, so the engine's weighted variant pick
is running too.
|
||
|
|
6013d8b937 |
feat(sound): add C_Sound.PlaySoundWithOptions and GetSoundScaledVolume
The table form of PlaySound, and the volume reader that falls out of it. Four of the params' six fields map onto something real here. volumeOverride is the one that needed finding. FUN_00458DA0(row, stream, scale) computes the row's own volume times `scale` and hands it to FUN_007A5DC0, which stores it on the stream and pushes it to FMOD. The by-id player already calls that with a scale of 1.0 immediately after starting a sound, and the setter writes rather than accumulates, so calling it again with another scale simply replaces the volume — no touching FMOD directly, and no reimplementing the row's volume rules. Resolving the row needs FUN_0045CDA0, since the applicator is a method on it. GetSoundScaledVolume then comes free: that same setter writes the result to stream + 0x74, so the field IS the scaled volume. Read only off a stream still in the engine's live list, because a finished stream's memory returns to a pool. soundKitID and runFinishCallback were already supported. uiSoundSubType, forceNoDuplicates and overridePriority are accepted and ignored, and the docs say so rather than implying they work. Params are read with GetTable rather than a raw read, so a table built from a mixin still resolves. Verified in game: volumeOverride 0.1 is audibly quiet against 1.0, runFinishCallback still fires SOUNDKIT_FINISHED through this path, and GetSoundScaledVolume returned 0.276 for a volumeOverride of 0.4 — the row's own 0.69 scaled, which is what confirms the multiplier semantics the docs describe. |
||
|
|
27277b11aa |
feat(sound): fire SOUNDKIT_FINISHED when an opted-in sound ends
Reports the handle of a finished sound, and only for sounds played with `runFinishCallback` — the documented contract, and what makes it affordable: without the opt-in every footstep and UI click would dispatch a Lua event. Detected on the world tick, NOT from FMOD's end callback. That callback (FUN_007A53C0) runs on the STREAMER thread — it opens with EnterCriticalSection and only moves the stream onto a deferred list — so firing an event there would call into the Lua VM off the main thread. The engine reclaims those streams in FUN_007A4B60, from the per-frame sound update that ends in FSOUND_Update, so noticing completion on the main thread is what the engine itself does. A tracked entry keeps the stream's path hash (+0x80, stamped at creation by FUN_007A51D0) beside the handle. Stream objects come from a pool and their addresses are reused, so "still in the live list" is not enough on its own — a later sound can land on the same address and the event would be deferred to the wrong one. Comparing the hash narrows that to the same file replaying at the same address, for one extra dword read of a node already found alive. C_Sound.PlaySound takes the remaining modern arguments: channel, forceNoDuplicates and runFinishCallback. forceNoDuplicates is accepted and ignored — the engine's by-path dedup is bit 0 of a flag word the row itself supplies, and the by-id player ORs in only bits 1, 2 and 4 from its arguments, so asking for it would mean bypassing that player and re-deriving its weighted file pick. The global PlaySound deliberately does NOT take those: it gains the SoundKitID form and nothing else, staying as close to the global it replaces as the extension allows. |
||
|
|
ccfdb8309c |
feat(sound): add C_Sound.PlayItemSound and Enum.ItemSoundType
Plays the noise an item makes when handled, without performing the action. Almost all of it is the engine's: FUN_00457FF0 takes a sound type and an ItemDisplayInfo id, walks that row's ItemGroupSounds id at +0x2C, and plays the SoundEntries id at row + 0x04 + soundType * 4. Those four columns are in the modern Enum.ItemSoundType order (Pickup, Drop, Use, Close), which makes this a backport rather than a reconstruction — the module only turns an item argument into a display id and calls it. The item argument takes an ItemLocation table and the other forms this project's item APIs accept (GUID string, itemID, link, carried item name), through the shared ResolveItemArgOrLocation. Sound type is read off the stack before resolving, since that resolver drives PackBagSlot and stomps the stack. Only Pickup and Drop play on a stock client, and that is the data rather than a limit of the code: of ItemGroupSounds' 24 rows, the 18 any display row points at (~29,000 displays) populate columns 1 and 2 only. The six rows naming a Use sound are unreachable or broken — groups 1 and 2 have no displays, and the ids they name (273/274/275) match no SoundEntries row — and the Close column is zero in all 24. Use and Close fall through the engine's own bounds checks silently, which is why no item can test them; documented so nobody hunts for one. The type stays a pass-through that indexes the row rather than selecting a branch here, so a server filling those columns in gets Use and Close working with no change on this side. Sound keys off the item's display, not its itemID, so items that look alike sound alike — the engine's grouping, and why every item has a sound without one being recorded per item. Verified in game: Pickup and Drop play, and differ by material. |
||
|
|
be7a8a0dd7 |
feat(sound): mute sound files, play by SoundKitID, and report what played
Five additions, one hook between them.
MuteSoundFile / UnmuteSoundFile stop a given audio file from playing.
They co-hook FUN_007A5450, the single funnel every sound passes through:
this client links only FMOD's FSOUND_Stream_* API, so even a one-shot UI
click is a stream opened by path, and the six callers of that function
are the whole surface (PlaySoundFile, the SoundEntries player behind
PlaySound and every DBC-driven spell/creature/UI sound, and four
music/ambience paths). A muted path returns NULL, which is the engine's
own "did not play" answer — its pre-play gate FUN_007A66A0 already
returns that at a category's concurrency cap, so every caller handles it
and PlaySoundFile already reports it to Lua as nil. Suppressing the open
rather than muting an opened stream means nothing is decoded for a sound
nobody hears; the only visible difference is PlaySoundFile returning nil
instead of 1 for a muted file.
C_Sound.GetRecentSoundFiles reports the last 64 DISTINCT files played,
newest first, with a timestamp and a muted flag — the other half of
muting, since hearing a sound tells you nothing about which of ~9,800
files it was. Always on: the hook exists for muting anyway, recording is
one bounded copy into a preallocated slot on a call that is about to open
and decompress an archive file, and a switch would have to be armed
before hearing the sound you wanted to identify.
C_Sound.PlaySound plays a SoundKitID and returns willPlay, soundHandle. A
SoundKitID is a SoundEntries row id — the same ids the modern client's
SOUNDKIT constants carry, verified against this build's table (850
igMainMenuOpen, 8959 RaidWarning, 8960 ReadyCheck). The engine has always
played by id internally; the only Lua door was the row's NAME string, so
addons written against SOUNDKIT ids could not play a sound here. The
global PlaySound is therefore widened to a strict superset: a number
plays by id, anything else tail-calls the engine with the stack untouched
so the name form is unchanged. It discriminates on lua_type rather than
lua_isnumber, which would also accept a numeric string and reroute
PlaySound("123") away from the name lookup.
C_Sound.IsPlaying validates a handle by walking the engine's live stream
list rather than dereferencing it, since a stream object is freed when
the sound ends, with a step guard so a corrupt list cannot spin inside a
Lua call. Handles are pooled and reused, which the docs call out.
FUN_0045CE60's ABI came from the disassembly, not the decompile — Ghidra
maps its arguments inconsistently against the call site. Re-registering
the PlaySound global was contention-checked first: no sibling DLL
references Script_PlaySound (UnitXP_SP3's "PlaySound" string is the winmm
PlaySoundW import), and the one addon that reassigns the global does a
temporary swap and restore around its own calls.
Verified in game: play by id and by name, mute and unmute across both
entry points, IsPlaying true while a sound runs, and the recent list
filling from sounds the player never triggered (zone music, quest log,
enter world) — which is what shows the funnel sees everything.
|
||
|
|
f9167bac06 |
feat(export): add ExportSoundFiles, and sweep every archive when enumerating
ExportSoundFiles is a sibling of ExportDBCFiles that dumps the MPQ `Sound\` tree to `BlizzardSound\`, with an optional subpath prefix (the full tree is ~3.5 GB and the command runs synchronously). All 8803 SoundEntries rows have a `Sound\...` DirectoryBase, so that one root is the whole corpus. Writing it exposed a bug in the existing enumeration. FUN_00401470's `archiveSelector` is not an archive SET, as the old comment assumed — it is an INDEX into a fixed 10-entry table built by the mount function FUN_00403740 (model, texture, terrain, wmo, sound, misc, interface, fonts, speech, dbc). Each call walks the primary patch archives plus exactly ONE of those ten. We passed 6, copied from the macro-icon loader, so ExportInterfaceFiles was complete only by coincidence — interface.MPQ IS selector 6 — while the sound export opened neither sound.MPQ nor speech.MPQ and silently lost 6,561 of 9,535 indexed files. EnumAllArchives now sweeps all ten, deduped; ExportInterfaceFiles and ExportDBCFiles go through it too. The sound export also unions the archive index with SoundEntries.dbc, because each source holds files the other lacks: an MPQ resolves a read by hashing the path, so the index is optional and 299 shipped files are named by no index at all, while ~300 more (character combat grunts, doodad audio referenced from model data) appear in no SoundEntries row. Same shape ExportDBCFiles already uses to union the index with its .text path-getter scan. Failed reads and writes are now counted and logged rather than silently skipped. A path only reaches that point because an index or the sound table named it, so a failure means the two disagree — which is worth seeing, and was invisible before: the console line gains "(N skipped)" and each path goes to Logs\classicapi_debug.log. Also: no extension filter (the tree is all audio, and the table carries typo'd names like Kill3.wac a whitelist would drop), and the destination is BlizzardSound\ rather than Sound\ — the loose-file VFS index resolves loose files ahead of archives, so exporting into Sound\ would shadow the MPQs with gigabytes of duplicates re-indexed at every launch. Verified on the 1.18.1 build across both fixes: 3,184 files with the original selector, 9,526 once SoundEntries was unioned in, 9,818 with the full archive sweep, and no zero-byte writes. ExportInterfaceFiles holds at 340/340 and reports nothing skipped, so neither it nor ExportDBCFiles was ever affected. Two residuals on this Turtle build, both logged rather than hidden. The 12 `Sound\Creature\Elekk\*` + 4 `Sound\Creature\ElekkPet\*` reads fail because SoundEntries names a folder the archive does not use (the files sit flat in `Sound\Creature\`) — a data inconsistency, not a code fault. Separately, patch-7's 14 flat `Sound\Creature\Elekk_*.wav` index entries do not reach disk, and that one is NOT explained: patch-7's listfile is demonstrably walked (its 4 exclusive interface-code files exported, and interface has no DBC fallback), yet those entries produced neither a file nor a logged failure. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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.
|
||
|
|
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)". |
||
|
|
e5690b1c6a | docs(readme): list texture:ResetTexCoord in the Frame row | ||
|
|
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. |
||
|
|
8637bf05e5 |
feat(config): add -gluescript / -gamescript launch switches
Four switches that run Lua as the client starts: -gluescript <code> run at the glue screens -gluescriptFile <path> the file's contents, run at the glue screens -gamescript <code> run once in-game -gamescriptFile <path> the file's contents, run once in-game None of these exist in 1.12. The strings appear nowhere in the binary, so there is nothing to parse them and nothing to un-gate -- the feature is ours end to end. Registration time is too early for either state. The in-game module callback runs from FUN_LOAD_SCRIPT_FUNCTIONS, before FrameXML loads, and the glue callback runs from FUN_LOAD_GLUE_SCRIPT_FUNCTIONS, before GlueXML does. A script running there could not touch a frame, call a FrameXML function or see an addon, which is most of what one would be written for. So each is armed at registration and run from a tick, where the UI is demonstrably up. Glue uses FrameTick, whose hook is the UI render root and so fires at the login and character-select screens; it is re-armed by the glue module callback on every glue boot, so a script that logs in automatically still works after a logout. Game uses WorldTick, which is world-only, so its first tick is past FrameXML, past the addon load pass and past enter-world init; it latches for the life of the process, since "run once in-game" says once. FUN_LUA_RUN_STRING resolves the Lua state itself rather than taking one, so a single call site reaches whichever state is current and the two paths differ only in when they fire. It installs the FrameScript error handler as the pcall's errfunc, so a faulty script reports itself the way any script error does instead of failing silently, and because every chunk goes through the shared compile chokepoint these scripts get the same 5.1 syntax support the rest of the client's Lua has. A *File is read with Win32 rather than the engine's file layer. The engine resolves relative paths against a loose-file index built once at boot, so it cannot see a file created afterwards and cannot open an absolute path at all -- and an absolute path is what goes in a shortcut. Reading it directly also lets both switches share one execution path, so inline code and file contents cannot diverge. The switch parser moves to Config::CommandLine, shared with -config rather than copied: the quoting and token-boundary rules are exactly where a second copy would drift unnoticed. Lifting it also fixed a latent overread, where a switch name at the very end of the command line was compared past its terminator. Verified in-game on Turtle: inline and file forms in both states; the in-game script silent across /reload and a second login while the glue script re-ran on returning to character select; a syntax error and a missing file each reported without a crash; and -config still applying through the shared parser. |
||
|
|
5528fb5fa4 |
feat(config): add a -config launch switch for settings profiles
`-config Config2.wtf` makes the client read and write WTF\Config2.wtf in place of WTF\Config.wtf, so one install can hold several profiles. The engine already names its config file through a single pointer: boot passes "Config.wtf" to the config initializer, which keeps it at 0x00C4EDD4 and uses it for both sides — the load at 0x0063D428 (MOV ECX,[0x00C4EDD4]; CALL 0x0063D820) and the save in FUN_0063D980, which builds "WTF\" + the same pointer. Supplying a different string is therefore the entire feature, with no second code path and no way for reading and writing to disagree. This is patched rather than hooked because of when it happens. The config is read from FUN_00402350 during boot, several calls before VanillaFixes invokes our Load export — VF hooks GetCPUFrequency (0x0042C060), which is reached from the FUN_0063A230() that runs after the config is already in. DllMain does run in time, since VF injects every dlls.txt DLL while the process is still CREATE_SUSPENDED and resumes it only afterwards. So this is the one module DllMain names directly. It is a 4-byte store into an immediate operand, not a hook, so it carries none of the loader-lock cost that keeps hook installation out of DllMain. VanillaFixes forwards any non-.exe argument to the game verbatim (CmdLineParse/AppendArg), so the switch works from the launcher shortcut. The name must be a plain filename. The engine builds the save path as "WTF\" + name, and a folder that does not exist makes the save fail silently, which would discard a session's settings with no warning. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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). |
||
|
|
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. |
||
|
|
b6698ecc7e |
docs(readme): list UnitCreatedBySpell in the Unit row
Already documented in docs/API.md; only the README summary table was missing it. Inserted in alphabetical position. |
||
|
|
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.
|