mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 08:00:42 +00:00
c54556f6a18cea4daf99aeb4e0fc045685cd5959
24
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c54556f6a1 |
refactor: centralize engine field/global access via Game::Read/Ref/Ptr
Replace the raw `*reinterpret_cast<const T *>(base + Offsets::OFF_X)` idiom (and its double-cast variant when base wasn't already a byte pointer) with three typed accessors in Game.h: Game::Read<T>(base, offset) field value read Game::Ref<T>(base, offset) writable field lvalue Game::Ptr<T>(base, offset) pointer to a field (arrays / out-params) Game::Read<T>(address) / Ref<T>(address) fixed-VA globals Pure mechanical refactor, zero behavior change: ~330 cast sites across 84 files collapse to 651 helper calls. Offsets stay in Offsets.h per the single-source-of-truth rule — the helpers only remove the cast noise and fold away the inner `reinterpret_cast<uint8_t*>(obj)` base casts. Left as raw casts by design: FUN_* function-pointer casts, void*/char* VA handles passed as arguments (caches, method registries), subobject- anchor pointers fed to __thiscall helpers, `void *volatile` player-ptr readiness gates (converting would strip volatile), and VA-as-array-base captures that are subscripted later. |
||
|
|
dc8a510611 |
feat(spell): add UnitSpellTargetName(unit)
Returns the name of the unit a caster is casting/channeling a spell at, or nil. The cast's target rides in SMSG_SPELL_START (SpellCastTargets: u16 mask + packed GUID when TARGET_FLAG_UNIT) — we already parse that packet for cast timing and just stopped before the target block. Extend the parse to capture the target GUID for the player (g_castTargetGuid) and remote units (RemoteCast.targetGuid), gated on an active cast so a stale target is never returned. nil when the unit isn't casting, the spell has no unit target (self/ground/item), or the target's name can't be resolved. Factor the GUID->name chain (object manager -> friends -> NameCache) out of UnitNameFromGUID into a shared Player::Info::NameFromGuid so both callers use one source of truth. |
||
|
|
7d566f3787 |
fix(spell): stop false cast interrupts on grenades / movement-immune casts
Throwing a grenade and moving mid-cast fired a false UNIT_SPELLCAST_INTERRUPTED and cut the bar short, even though the throw completed (issue #23). A cast is interrupted by movement only if its Spell.dbc InterruptFlags carry SPELL_INTERRUPT_FLAG_MOVEMENT (verified against the server's HandleMovement- Opcodes and the client's own CheckCast); thrown items (e.g. spell 4068) lack it, so the server never interrupts them on movement, but the engine still drops the client cast-state, which our poll surfaced as an interrupt. Fix: when the movement path clears a movement-immune cast WHILE THE PLAYER IS MOVING (PlayerMoving mirrors the engine's 0x200f cast-drop mask), keep it tracked instead of ending it; it then finishes as SUCCEEDED (no INTERRUPTED) or, if its SPELL_GO never comes, ends a grace past its computed end. A real cancel/interrupt happens with the player stationary, so it clears normally. Gated on a per-cast latch, so normal (movement-interruptible) casts are unchanged. Also de-dup UNIT_SPELLCAST_INTERRUPTED: the client fires Spell_C_SpellFailed AND drops the tracked cast for the same interrupt (e.g. an Esc cancel), which fired the event twice; PollPlayer now skips its own when SpellFailed_h already fired one for the same spell. SuperWoW-style kicks (no Spell_C_SpellFailed) stay owned by the poll. New Offsets.h constants: SPELL_INTERRUPT_FLAG_MOVEMENT (InterruptFlags bit 0), MOVEFLAG_MASK_CAST_DROP (0x200f). Wrap-safe deadline/window checks use Time::Clock::Reached / Elapsed. Fixes #23. |
||
|
|
39d22ac124 |
fix(time): centralize engine ms-tick reads in Time::Clock
The engine's OS millisecond counter (FUN_OS_TICKCOUNT_MS, same epoch GetTime() scales by 0.001) is unsigned and wraps at 2^32 ms. Nine files each re-derived the reader; several stored the tick into a signed int, so past 2^31 ms (~24.9 days uptime) every timestamp went negative and `startTime + duration` landed in the past -- callers saw every cooldown, aura, and lockout as already elapsed. The same bug shipped three times (the cooldown by-ID getters and C_LossOfControl). Add one source of truth -- Time::Clock (src/time/Clock.h) -- with a uint32 NowMs() and wrap-safe Reached/Remaining/Elapsed helpers, and route every tick reader through it. No module re-derives the reader or hand- rolls a `now < deadline` compare (which inverts across the wrap) anymore. Also fixes the reported cooldown/LoC getters (unsigned out-params, wrap-safe compares) and three latent instances of the same `now < end` inversion found while sweeping: totem/Tracker's two timer getters and aura/Source's cache-eviction pass. Named Time::Clock, not Time::Tick, because a Time::Tick inner name shadows the global Tick namespace (the WorldTick hook) from inside any Time::* file. Discovered by fuffc in #17. |
||
|
|
93360ce482 |
fix(cast): don't start target-selection casts at the reticle step
Spell_C_CastSpell (0x006E4B60) calls the cast-start writer FUN_CAST_START_SET before Spell_C_TargetSpell raises the reticle, so a target-selection spell (Disenchant, ground-target AoE) stamps g_cast at the green-cursor step - seconds before the item/ground is clicked and the cast actually begins. The later click re-enters Spell_C_CastSpell only to hit its "already this spell" short-circuit, so the writer never re-fires for the real start. Result: UNIT_SPELLCAST_START (and a UnitCastingInfo cast bar) fired far too early, and a cancel fired a phantom START/INTERRUPTED/STOP for a cast that never happened. Drop the client stamp in OnWorldTick while the reticle is up for that spell. On selection the server's SMSG_SPELL_START re-stamps g_cast via the fresh-stamp path (it is 0), so START fires with the correct time and the SENT castGUID; on cancel it stays cleared. Gated on !g_castFromServer (never touches the server re-stamp) and on g_cast.spellID == VAR_PENDING_CAST_SPELL (only the spell whose reticle is actually up). Normal casts have no targeting phase and are unaffected. |
||
|
|
84da9c23df |
Consolidate the duplicated Spell.dbc attribute flag bits
The remaining flag-bit duplicates -- the same drift risk that caused the AttributesEx2/Ex3 mix-up -- now live once in Offsets.h: - SPELL_ATTR_PASSIVE (0x40): was already in Offsets.h yet copied in Info.cpp and Level.cpp; drop both locals. - SPELL_ATTR_EX_CHANNELED (0x4|0x40): identical local in Cast.cpp and CastEvents.cpp; add to Offsets.h and repoint. - SPELL_ATTR_EX2_AUTOREPEAT_FLAG (0x20): the same bit under two names (Cast's _AUTOREPEAT, AutoAttack's _FLAG); unify in Offsets.h. Single-use flag bits (TRADESPELL, RANGED, HEALTH_FUNNEL, HIDDEN_CLIENTSIDE, ON_NEXT_SWING, NOT_RESET_AUTO_ACTIONS) and per-module effect/target enum codes stay local -- they are not duplicated and read clearer at the use site. |
||
|
|
6e58cb81d1 |
Consolidate SpellIcon path and remaining Spell.dbc offset stragglers
Fold the last duplicated DBC offsets into Offsets.h: - SpellIcon.dbc path (+0x04): 4 copies across 3 files -> OFF_SPELLICON_PATH. aura/Data and spell/Cast had local consts; spell/Info used two raw `iconRec + 4` literals. - totem/Tracker's OFF_MISC_VALUE (0x1A8) duplicated the existing OFF_SPELL_RECORD_EFFECT_MISC_VALUE -- repointed. OFF_TOTEM_TOOL (0xA0) is a Spell.dbc field, added as OFF_SPELL_RECORD_TOTEM. Audit result: unit-descriptor offsets were already fully centralized in Offsets.h, and item ItemStats_C fields are read via a named struct rather than offset consts, so neither needed work. Spell.dbc and its sub-DBC record offsets are now a single source of truth. |
||
|
|
8a065481b4 |
Consolidate all Spell.dbc record offsets into Offsets.h
Extend the single-source-of-truth cleanup to the whole Spell.dbc record layout. 40 local constexpr offset copies across 16 files (spell/, totem/, lossofcontrol/, macro/, aura/) redefined field offsets that belong in Offsets.h: name (0x1E0), icon (0x1D4), effect (0xF4), rank (0x204), effect implicit targets (0x148/0x154), powerType (0x7C), manaCost (0x80), rangeIndex (0x90), castingTimeIndex (0x48), maxLevel (0x6C), spellLevel (0x74), manaCostPercent (0x270). Add the ones Offsets.h lacked as OFF_SPELL_RECORD_* and repoint every local use to the Offsets:: constant, deleting the duplicates. Purely mechanical and behavior-preserving -- every local value already matched the canonical (verified before repointing). SpellIcon.dbc / SpellRange.dbc sub-record offsets (0x04/0x08) stay local; they are different structs. |
||
|
|
a989499cae |
Consolidate Spell.dbc attribute offsets into Offsets.h
The Attributes (0x18), AttributesEx (0x1C), and AttributesEx2 (0x20) record offsets were each copied as local constants across several spell modules. AttributesEx2 was 0x24 in three of those copies, which is actually AttributesEx3 -- an off-by-one-field bug. Spell.dbc stores each record as a flat uint32 array by column, so AttributesEx2 (column 8) is at 0x20. Verified against the 1.12.1 client, the server column order, and nampower. Move the record offsets to Offsets.h as the single source of truth (add AttributesEx at 0x1C and InterruptFlags at 0x54; correct AttributesEx2 to 0x20) and remove the local copies in AutoAttack, Cast, CastEvents, Info, and Level. This corrects the autorepeat aim-time skip, the auto-learn hide check, and the spell-mod family gate -- all of which read AttributesEx2 -- and removes the duplication that let one wrong offset become three bugs. |
||
|
|
1da06d4a73 |
frame: attribute backport, modern script args, and SMSG hook consolidation (#13)
* frame: backport Frame:SetAttribute/GetAttribute + unit-frame mouseover/click Adds native SetAttribute / SetAttributeNoHandler / GetAttribute on the base Frame registry: a per-frame, case-insensitive value store with the 3.3.5 prefix/name/suffix getter precedence, stored on the frame's own Lua table. A `unit` attribute makes the frame a mouseover source. A WorldTick poll of the engine's mouse-focus frame (GetMouseFocus's global) calls the real mouseover setter (FUN_00492890) for its unit -- 1:1 with hovering the 3D model: model highlight, mouseover tooltip, UPDATE_MOUSEOVER_UNIT, and the native GUID slot. Stomp-proof (the engine's 3D-hover setter is event-driven) and independent of the frame's scripts, so an addon setting its own OnEnter can't break it. A `type1`/`type2`/`type` attribute installs a chained OnClick on that frame only (PCall-guarded, Button-only) that dispatches target / assist / focus on the unit at click time, then runs any prior handler. No global hooks: mouseover reads the mouse-focus global; clicks use the frame's own OnClick. Deliberately does NOT MinHook the button-click dispatcher (FUN_00779540) -- SuperWoW's click-casting owns that prologue and a second inline hook corrupts the trampoline (ERROR #132). * frame: extend attribute backport (one-verb click dispatcher + OnAttributeChanged) The `type*` click path now mirrors retail's SecureActionButton_OnClick: resolve ONE verb per click from the modifier/button-qualified `type` attribute and perform it, instead of a fixed `type1=target`. - Modifier/button resolution: `[alt-/ctrl-/shift-]type[1..5]` with prefix..name..suffix -> name..suffix -> name precedence, read from the live key state and the click's button. - Verbs: target (with the engine's default-interaction precedence - cast a pending spell / drop a cursor item on the unit instead of switching target), assist, focus, spell, stopcasting, macro, and menu. - Own-the-click: when a verb resolves we perform it and do NOT chain the frame's previous OnClick, so a configured `type1` no longer double- dispatches alongside an addon's own conditional click handler. - Self-healing wire: addons that re-SetScript OnClick (pfUI on every raid relayout) clobber our closure; WireOnClick re-wraps a clobbered Lua handler but skips its own C closure, so re-setting `type*` recovers without double-chaining. Dispatch goes straight to C++ where we own the code - no Lua round-trip through the global table: spell -> Spell::AtUnit::CastByName (a native unit-targeted cast; the unit's GUID is fed to the engine's dispatcher so there's no target juggling, and ground-target spells land at the unit's feet), focus -> Unit::Focus::Set, and the target verb's predicates -> Spell::AtCursor::IsPlacementActive / Cursor::Info::HasItem. Only genuine engine entries (TargetUnit/AssistUnit/SpellTargetUnit/DropItemOnUnit/ SpellStopCasting) and addon-provided functions still go through Lua globals. Spell::AtUnit gains a C++ header sharing its CastCore with the C_Spell.CastAtUnit Lua entry. macro verb: takes the content from the `macrotext`/`macro` attribute and prefers an addon-provided RunMacro (SuperCleveRoidMacros etc. - handles named macros and extended macro text), falling back to running the text natively when no RunMacro global is present. The native path runs each line through the stock FrameXML ChatEdit_ParseText via a throwaway edit-box (GetText closure + no-op __index), so it needs no addon. menu/togglemenu verb: pops the standard unit dropdown at the cursor via the new ClassicAPI_ToggleUnitMenu (Util/SecureUnitMenu.lua), resolving the unit -> menu type with Blizzard's own generic resolver (self->SELF, pet->PET, grouped player->PARTY, other player->PLAYER, NPC->RAID_TARGET_ICON). Keeps the FrameXML dropdown logic in Lua with the C side as a thin call. OnAttributeChanged is now a real SetScript/GetScript/HookScript-able frame script on every frame: SetAttribute fires it, SetAttributeNoHandler suppresses it. Made settable by co-hooking the base-frame script-name resolver FUN_0076a0d0 (the one every frame type delegates through) and handing back an external per-frame {handler, context} cell for that name - frames are immortal in 1.12, so the cell never goes stale. One hook does it (vs the tooltip OnTooltipSet* work's five) because we already own the firing side. 1.12 convention: the handler reads this = frame, arg1 = name, arg2 = value. Recursion-guarded so a handler may itself SetAttribute. * frame: add Frame:ClearAttribute (retail 11.2.0) `cleared = frame:ClearAttribute(name)` removes an attribute and returns whether it was set. Registered on the base Frame method registry next to SetAttribute/GetAttribute, so every frame has it. Routes through DoSet's nil-value path (removes the stored key, drops a `unit` mouseover binding) but does NOT fire OnAttributeChanged — verified against a live retail 11.2 client: SetAttribute fires the handler, ClearAttribute fires nothing, and the return is true for a set attribute / false when there was nothing to clear. * frame: store attributes in the Lua registry, hidden from Lua Attributes were kept as a subtable on the frame's own Lua table under a control-char key ("\1ClassicAPIAttributes"). That key, while collision- safe, is still enumerable via pairs(frame) and readable/writable from Lua. Move the store to registry[frame] in the Lua registry (LUA_REGISTRYINDEX), which has no _G path — so the attribute map is invisible to pairs(frame) and can't be read or tampered with from script, matching how retail keeps attributes C-side. Only PushSub changed (create/fetch now key the registry by the frame table); GetAttribute/DoSet/CopyAttr sit on top unchanged. 1.12 frames are immortal, so the strong registry key never leaks. The dead kAttrKey constant is removed. Verified in-game: SetAttribute/GetAttribute still round-trip, and a pairs(frame) scan no longer finds any ClassicAPI key. * frame: add the `item` click verb (SecureActionButton item action) type*="item" uses the modifier-qualified `item` attribute: - a "bag slot" string (e.g. "0 1") -> UseContainerItem(bag, slot); - otherwise an item name / itemID / link -> C_Item.UseItemByName(item, unit), passing the unit as the use target (self-use items ignore it, targeted ones like scrolls/bandages apply to it); - the deprecated `bag` + `slot` attributes are honored when `item` is unset. Both bag paths go through lua_call (new CallTableFunc2Str / CallGlobalNum2) rather than a direct C++ call: the item-use bag walk does SetTop(L, 0), so it needs its own Lua stack frame — a direct call would wipe the dispatcher's stack. (spell stays direct because Spell::AtUnit is stack-free; the helper comment records the distinction.) Retail's "bag slot" string is the preferred form; the deprecated per-attribute form is supported too. * docs: format the attribute click verbs as a table The verbs were one long paragraph of nested parentheticals - hard to scan. Replace it with a Verb | Extra attributes | Action table so each verb's inputs and behavior are legible at a glance. Content-equivalent; no API change. * frame: clear target on the `target` verb when unit is "none" Retail's SecureActionButton target action treats a "none" unit as "clear target". Match it: the `target` verb calls ClearTarget() when the resolved `unit` is "none" (case-insensitive), before the normal cursor/spell precedence. Mouseover already handles "none" implicitly (it resolves to GUID 0 = no unit). Docs' target-verb row updated. * frame: pass modern positional args to script handlers Vanilla always invokes frame-script handlers with zero Lua args; the handler reads this/arg1/event as globals. Modern addon ports write SetScript("OnMouseWheel", function(self, delta) ...) and get nothing. Co-hook both script runners -- FUN_FRAME_INVOKE_SCRIPT (no-arg scripts) and FUN_FRAME_RUN_SCRIPT_ARGS (scripts with values) -- and reimplement their pcall tail: keep the engine's exact this/argN global save-set- restore and message-handler errfunc, but additionally push self + arg1..argN as real positional arguments and pcall with nargs = 1+N. Purely additive: a zero-param vanilla handler ignores the extras and reads globals; a modern (self, delta) handler binds them. OnEvent gets (self, event, arg1..argN), detected structurally by matching the invoked handler ref against the frame OnEvent slot (frame+0x0C) -- exact, since each SetScript makes a distinct ref. Runtime switch SetModernScriptArgs()/GetModernScriptArgs(), default on; when off both detours are a straight passthrough to the original runner, which matters because FUN_FRAME_RUN_SCRIPT_ARGS is the hottest Lua path in the engine (every OnUpdate frame). Verified in-game across OnMouseWheel/OnClick/OnValueChanged/OnUpdate/OnEnter/OnLeave/OnEvent. * net: consolidate spell SMSG hooks onto one dispatch funnel The spell subsystem's per-opcode SMSG handlers (SpellGo, SpellStart, SpellDelayed, ChannelStart/Update, SpellFailure, SpellFailedOther, SpellCooldown) were each co-hooked directly -- and nampower (hadesmem) plus SuperWoW detour the same prologues. Two inline hookers on one prologue is the documented MinHook collision risk, and a whole-protocol bisect fingered exactly this cluster as the crash-suspect surface. Add Net::PacketDispatch: a receive-side mirror of Net::SendObserver that co-hooks the single incoming-SMSG dispatch funnel FUN_NET_MESSAGE_DISPATCH (0x00537AA0) -- a chokepoint nampower does NOT hook (it detours the leaf handlers) -- and fans each packet out to opcode subscribers with the cursor at the body and centralized save/restore. Migrate all eight handlers to subscribers: aura/Source (SpellGo, which re-decodes the packed guids + spellId the leaf handler used to hand it pre-decoded), spell/Cast (Start/Delayed/Channel*/Failure*), and lossofcontrol (Cooldown). The parse bodies are unchanged; only the hook site moved. Subscribers run before the engine's leaf handler instead of after a co-hook's original -- verified order-independent for all eight (self-contained cache/state updates; SpellGo's aura-application handoff rides a separate SMSG_UPDATE_OBJECT). Cuts the ClassicAPI-nampower shared spell prologues from 10 to 3 (the OnAura* method hooks, which have no packet chokepoint to relocate to). One hook on an uncontended function replaces eight on contended ones. Verified in-game: cast bars, channels (incl. Mind Control cast-then- channel), pushback, remote-cast interrupt eviction, and C_LossOfControl school lockouts all intact. * ScriptArgs is back to opt-in * frame: fix ScriptArgs comments to match opt-in default * frame/net: dedupe packet observers, reuse Lua/token helpers, fix attr edge cases Post-review cleanup of the attribute + SMSG-consolidation work. - net: extract the shared packet-observer plumbing (PacketObserver.h) — the intrusive subscriber list, Subscribe(), and the read-opcode / reset-cursor / fan-out / restore loop — so Net::PacketDispatch (SMSG, u16) and Net::SendObserver (CMSG, u32) each reduce to a one-line hook thunk over FanOutByOpcode<OpcodeT>. Drops the dead per-namespace Callback aliases rather than keeping them as compat shims. - Game::Lua: promote PushGlobalFunction / CallGlobal / CallGlobalString into the shared Lua helpers (a pattern several modules open-code); Frame attributes use them instead of private copies. - frame/Attributes: resolve unit tokens through Unit::Identity::GuidForToken (engine resolver + player fast-path) instead of a duplicate raw-cast wrapper. - frame/Attributes: wire the chained OnClick for every "type" action attribute the click resolver reads (IsTypeAttr: modifier prefixes + type1..type5), not just type/type1/type2 — a middle-click or modifier-only binding now installs. - frame/Attributes: FireAttributeChanged snapshots and restores the caller's arg1/arg2 around the fire, so calling SetAttribute from inside a running script handler no longer clobbers its globals. |
||
|
|
29e3dab24a |
UNIT_SPELLCAST_* event family + GUID unit tokens (#11)
* spell: backport UNIT_SPELLCAST_* events for the local player
Adds the TBC+ cast/channel events (START, STOP, DELAYED, SUCCEEDED,
INTERRUPTED, FAILED, SENT, CHANNEL_START, CHANNEL_UPDATE, CHANNEL_STOP)
for the player, so cast-bar / rotation addons written against the modern
signature work on 1.12. Each carries (unit, castGUID, spellID, spellName,
rank) -- SENT inserts `target` at arg2 -- with a synthesized modern-shape
castGUID (Cast-3-0-0-0-<spellID>-<castUID>) shared across all of a cast's
events so START pairs with STOP. arg1 is always "player" (player-only phase).
The events are derived, not independently tracked: Spell::Cast already
hooks every cast/channel path for UnitCastingInfo/UnitChannelInfo, so
Spell::CastEvents reuses that state.
- START/STOP/DELAYED/CHANNEL_START/STOP: polled from Cast's OnWorldTick
against the previous snapshot.
- SUCCEEDED: fired from the SMSG_SPELL_GO hook (covers instants too).
Deferred for channels so it lands after CHANNEL_START (modern order).
- INTERRUPTED/FAILED: split by result code in a Spell_C_SpellFailed
co-hook -- a started cast that aborts (kick/move/LoS) fires INTERRUPTED
(repeated per retry, reusing the cast guid); a pre-cast rejection fires
FAILED.
- SENT: minted from the CMSG_CAST_SPELL send, threading its castGUID
forward so all of a cast's events share one guid.
- CHANNEL_UPDATE: from a new MSG_CHANNEL_UPDATE co-hook, which also
re-anchors g_channel.endMs to the server's remaining time so channel
pushback (which shortens vanilla channels) shows in UnitChannelInfo.
Every fire is gated on Event::Custom::HasListeners (new), so the system
costs one pointer-compare per transition when no addon registers.
Supporting changes:
- Net::SendObserver: shared co-hook on the NetClient send funnel with an
AutoSubscribe list, so CastEvents (SENT) and ComboDuration (combo-point
capture) both watch outgoing packets without owning the hook. Extracted
from ComboDuration's private hook.
- Cast.cpp: player channel now self-expires at its computed endMs in the
poll (was cleared only by the ~1s-lagged +0x228 field, so CHANNEL_STOP
trailed the real end by ~1s); wrap-safe delta compare so a long-uptime
ms tick past 2^31 can't misfire it.
Player-only; remote-unit fan-out, FAILED_QUIET, and empowered casts are
not implemented.
* spell: extend UNIT_SPELLCAST_* to non-player units (phase 2)
Fires the six observable cast/channel events -- START, STOP,
CHANNEL_START, CHANNEL_STOP, SUCCEEDED, INTERRUPTED -- for other units,
not just the player. Each is fanned out once per unit token currently
mapping to the caster (target / focus / nameplateN / party / raid / pet /
mouseover), so a target frame, a party frame, and a nameplate cast bar
all get their own event with a shared castGUID -- matching retail.
Token fan-out reuses the engine's own GUID->token reverse map
(FUN_00515c50, nampower's unfilled GetNamesFromGUID) for native tokens,
plus focus/nameplate which the engine can't see, via
Unit::Identity::TokensForGUID. SuperWoW's raw-GUID token ("0x...") is
filtered out so only standard tokens fan out.
Remote events are derived from Spell::Cast's existing packet hooks:
- START / CHANNEL_START from HandleSpellStart (SMSG_SPELL_START)
- SUCCEEDED from the SPELL_GO hook (Aura::Source)
- STOP / CHANNEL_STOP at the computed end, or on abort
- INTERRUPTED (casts only) from HandleCastAborted (ClearCastingSpell /
failure packets)
A per-caster state machine (PollRemote, from OnWorldTick) fires them in
modern order; a channel's SPELL_GO cast->channel ClearCastingSpell is
filtered so it doesn't self-interrupt at its own start.
Not fired for remotes (data is caster-only / client-local): SENT,
DELAYED, FAILED, CHANNEL_UPDATE.
Also in this change:
- castGUID follows type rule from https://warcraft.wiki.gg/wiki/GUID#Cast : real casts are Type 3 with a
time-based castUID (low 23 bits = UNIX second, high bits = per-second
counter, matching retail's structure), threaded across a cast's events
(player and remote converge on the same value); FAILED is Type 2 with
a flat incrementing integer.
- Channels never fire INTERRUPTED (player or remote) -- retail emits
only CHANNEL_STOP whether a channel completes or is cut short.
arg1 is the caster's unit token ("player" or another token); the
spellName / rank tail extensions are unchanged.
* spell: return the castGUID as UnitCastingInfo's castID
UnitCastingInfo / CastingInfo now return the cast's castGUID as castID
(return 7) instead of nil -- the same string the UNIT_SPELLCAST_* events
carry, so an addon can correlate the polled info with the events. It's
pulled from Spell::CastEvents (the single source of the castUID) via a new
CurrentCastGuid accessor, and works for the player and remote units. The
timing stays sourced from Spell::Cast -- only the castGUID crosses over,
so there's no duplication of cast state.
UnitChannelInfo is left retail-exact (no castID; channels don't carry
one), even though our channel events do include the shared castGUID.
Also corrects the spell-cast-GUID spec attribution in comments/docs to
warcraft.wiki.gg/wiki/GUID#Cast (it was wrongly credited to Wowhead).
* spell: add UNIT_SPELLCAST_RETICLE_TARGET / _CLEAR events
Backports the ground-target reticle events for the player:
RETICLE_TARGET when an AoE placement reticle comes up (Blizzard, Flare,
Rain of Fire, ...), RETICLE_CLEAR when it's cancelled. Args are
(unit, "", spellID, spellName, rank); arg1 is always "player".
Driven by polling the engine's targeting-flag global (0x00CECAC0 -- the
predicate behind SpellIsTargeting) from OnWorldTick: 0->nonzero fires
RETICLE_TARGET with the pending spellID (0x00CEAC58, written by
Spell_C_CastSpell); nonzero->0 fires RETICLE_CLEAR. CLEAR is suppressed
on placement (a CMSG_CAST_SPELL for the reticle spell went out, seen via
the shared send observer), so it fires only on a genuine cancel --
matching retail, which emits no CLEAR when the spell is placed/cast.
The castGUID slot (arg2) is "" rather than retail's nil: there's no cast
to identify yet, and the engine's event dispatcher can't emit a nil
mid-argument-list (a NULL %s corrupts the args after it -- the nil trick
only survives as the last arg). unit (arg1) and spellID (arg3) are exact.
* spell: fire UNIT_SPELLCAST_FAILED_QUIET for the quiet result whitelist
Vanilla's Spell_C_SpellFailed dropped SPELL_FAILED_DONT_REPORT silently.
Modern surfaces suppressed (no-error-text) failures as
UNIT_SPELLCAST_FAILED_QUIET rather than FAILED.
Verified against the 3.3.5 client's unit-spellcast dispatch (FUN_007fecc0),
which selects the QUIET event for a fixed 3-code whitelist, mapped to 1.12's
SpellCastResult enum (FUN_006e23e0):
CHARMED (0x14) . DONT_REPORT (0x17) . SPELL_IN_PROGRESS (0x61)
SPELL_IN_PROGRESS (casting while already casting / a nampower spell-queue
rejection) is the common case that previously mis-fired as a loud FAILED.
* unit: accept raw GUID literals as unit tokens
Fold a "0x<hex>" branch into the existing FUN_TOKEN_TO_GUID hook so every
Unit* function (UnitName, UnitHealth, UnitClass, UnitExists, ...) accepts a
64-bit GUID literal in place of a token. The parsed GUID goes straight to
the engine's own object-manager lookup (the path "player" takes), so an
unloaded/out-of-range GUID resolves to nil like any absent unit, no error.
Reuses the existing suffix walker, so "0x...target" composes.
Gated on SuperWoW's absence (GetModuleHandleA("SuperWoWhook.dll"), cached):
SuperWoW already provides GUID input via its own resolver hook, so when it
is loaded we defer to avoid two layers parsing the same string. Behaves
identically either way. Input direction only.
|
||
|
|
cedbd04553 |
cast: mirror the server's +500ms ranged aim time in the cast-time prediction
FUN_006e3340 (the spell tooltip's cast-time helper, which our zero-latency CastStartSet_h stamp reuses) omits the flat +500ms "aim time" the server adds to every ranged, non-autorepeat spell -- SpellEntry::GetCastTime does `castTime += 500` for SPELL_ATTR_RANGED. So the client prediction ran ~500ms short of the server on Volley / Aimed Shot / Multi-Shot (Volley's real cast is 3000ms base + 500 = 3500ms), and the confirming SMSG_SPELL_START then snapped the bar out ~1 RTT later. This was the dominant cause of the Volley overhang, present with or without Quick Shots. CastTimeMs now adds the +500 for SPELL_ATTR_RANGED spells (excluding Auto Shot / Shoot via the AttributesEx2 autorepeat bit, matching the server), so the prediction is right from frame 1. Only applied when the spell already has a cast time; instant ranged abilities the server gives a 500ms aim time still surface through the packet path. The HandleSpellStart reconcile stays as the backstop for any residual client/server divergence. |
||
|
|
3b1bba2131 |
cast: reconcile local-player cast time to the server on the confirming packet
The client-side FUN_CAST_START_SET hook stamps g_cast with a zero-latency
prediction from FUN_006e3340, which folds in the caster's cast-speed /
ranged-haste multiplier (descriptor +0x22c). That is correct for spells the
server also hastes (Aimed Shot / Multi-Shot), but wrong for ones it does
not. Volley (1510 / 14294 / 14295) is the case: it is NOT channeled in the
client DBC (AttrEx has no 0x4/0x40) so it takes the regular-cast path, and
its Attributes & 0x30 == 0 so FUN_006e3340 applies the +0x22c multiplier --
yet Volley gains no benefit from Quick Shots server-side. The predicted bar
therefore ended ~before the real cast finished ("still casting after the bar
ends").
SMSG_SPELL_START carries the server's authoritative cast time, but for a
cast the client already stamped we were deduping the packet away entirely to
avoid restarting the bar. Instead, keep startMs (no visual restart) and snap
endMs to the server's castTime (preserving any accumulated pushback). Aimed
Shot / Multi-Shot are unaffected -- the server hastes them too, so client and
server agree and the reconcile is a no-op.
Closes https://github.com/brues-code/pfUI/issues/28
|
||
|
|
1c263152e3 |
spell: fix negative cast/channel startTimeMs/endTimeMs on long-lived tick
C_Spell.UnitCastingInfo/UnitChannelInfo returned negative startTimeMs and endTimeMs for users whose engine ms tick has crossed 2^31. The tick (FUN_OS_TICKCOUNT_MS) has two backends: GetTickCount, or a scaled rdtsc. The rdtsc value survives warm reboots (only a full power-off resets the CPU TSC), so it can sit well past 2^31 even right after a "restart" -- which is why rebooting didn't clear the negatives. We stored the tick in a signed int and pushed it straight to a double, so the high bit read as the sign. Script_GetTime (0x00515EA0) computes (double)(tick & 0xFFFFFFFF) * 0.001, i.e. it masks the tick to the low 32 bits UNSIGNED. New PushMs helper reinterprets our stored tick as uint32 before the double conversion, reproducing GetTime()'s exact value so startTimeMs/endTimeMs stay consistent with GetTime()*1000 across the whole range (both wrap together at the ~49.7-day 2^32 boundary). Carrying full 64-bit precision would be wrong -- it would diverge from GetTime() past 2^32 and break addons' (now-start)/(end-start) math. Routes all four timestamp pushes (cast + channel, local and remote) through PushMs. The aura expirationTime path already handled the tick as unsigned, so no change there. |
||
|
|
23b102c60c |
spell/Cast: clear player channel on early stop; unify player-object access
UnitChannelInfo showed a stale "Ritual of Summoning" countdown after helping a warlock summon: g_channel only cleared at its computed endMs or when a timed cast superseded it, so a ritual that ends early (when the summon fills) lingered, and a following instant cast -- which supersedes neither cast timing nor the channel -- couldn't dislodge it. OnWorldTick now polls the player's UNIT_FIELD_CHANNEL_SPELL (+0x228) and clears g_channel when it drops to 0, gated by a confirm latch so the field's ~1-tick start lag can't wipe a freshly stamped channel. Both channel-stamp sites route through a new StampChannel helper that re-arms the latch. Also fixes early-ended channels generally (interrupt / cancel / LoS break), which previously self-expired only at endMs. Cleanup: factor the player-object/descriptor read into shared Unit::Identity::PlayerObject() / PlayerDescriptor(), now used by State.cpp, Cast.cpp's poll, and ComboDuration. PlayerObject() uses the object-manager GUID resolve (FUN_OBJECT_RESOLVE_BY_GUID) -- the fastest player-object path, non-throwing (null pre-world) -- replacing the duplicated resolves (State.cpp's token resolver, ComboDuration's hand-rolled GUID plumbing). |
||
|
|
07a4cbde43 |
Evict remote casts via CGUnit_C::ClearCastingSpell choke point
Turtle's core doesn't broadcast SMSG_SPELL_FAILURE or SMSG_SPELL_FAILED_OTHER on interrupt (verified by logging both handlers through live tests), so the SPELL_FAILED_OTHER co-hook never fired and interrupted enemy casts (Kick / Earth Shock / Counterspell) lingered as ghost bars. What actually stops the cast visual on Turtle is SuperWoW calling CGUnit_C::ClearCastingSpell (0x0060D040) directly. Co-hook that choke point instead: every unit-stopped-casting path funnels through it (failure packets, SPELL_GO completion, movement, death, animation events, local cancel), gated on the unit's live current-cast field at +0xC8C, so eviction is independent of which signal the server sends. Both failure-packet handlers stay co-hooked as backstops for servers that do broadcast them. Verified in-game: all three interrupts evict; non-interrupting damage doesn't false-evict. Also confirmed via a whole-protocol sniff on the NetClient message dispatch (FUN_NET_MESSAGE_DISPATCH = 0x00537AA0, documented for future use): SMSG_SPELL_DELAYED goes only to the affected caster -- observers receive no packet of any kind for pushback, so remote bars can't stretch. Documented as an inherent 1.12 protocol limitation. |
||
|
|
49865e9b9e |
Fix cast-then-channel spells showing the channel bar at cast start
Mind Control is a 3 s cast on a spell flagged CHANNELED with a 60 s duration. HandleSpellStart branched on the channel attribute alone, so at cast start it stamped g_channel with the 60 s duration and killed the client hook's correct 3 s cast stamp — the bar showed a premature 60 s countdown (pfUI #9). Same story remotely: an observed MC stored a 60 s channel entry instead of the 3 s cast. - Treat a channeled spell with castTime > 0 as its CAST phase in HandleSpellStart (player and remote paths); instant channels keep the immediate stamp. - Co-hook the MSG_CHANNEL_START handler (0x006E7550, layout from nampower's SpellChannelStartHandlerHook: spellId u32, duration u32). The server sends it to the caster the moment the channel begins — after MC's cast completes — with the server-authoritative duration. Stamp g_channel there, before the original fires SPELLCAST_CHANNEL_START, so pollers see fresh data. For instant channels it re-stamps what the SpellStart path just wrote. Verified: MC shows 3 s cast then 60 s channel; Mind Flay-style instant channels unaffected. |
||
|
|
597530d558 |
Evict interrupted casts via SMSG_SPELL_FAILED_OTHER (TODO #98)
Remote casts cached from SMSG_SPELL_START were expired only by their computed end time — an interrupted remote cast lingered as a ghost bar for every UnitCastingInfo consumer (pfUI #11). The interrupt signal does exist at the packet layer: the server broadcasts SMSG_SPELL_FAILED_OTHER to observers whenever a started cast aborts (interrupt, death, movement, fizzle). Co-hook its handler (0x006E8E40, same __stdcall shape as FUN_SPELL_DELAYED; address + layout mirrored from nampower's SpellFailedOtherHandlerHook — body is plain casterGuid(u64), spellId(u32)) and: - evict the matching g_remoteCasts entry (guid + spellID), so remote cast/channel bars drop the same tick the cast dies; - clear the player's own g_cast on a guid match — covers the server-stamped chained recast that the WorldTick VAR==0 poll can't clear (self-receipt is server-dependent; the endMs self-expiry backstop remains if it never fires). Update the stale 'no per-unit interrupt signal in 1.12' notes in Cast.cpp and docs/API.md. |
||
|
|
d9102bae3b |
Relicense source headers from LGPL to GPL v3
The repo was internally inconsistent: the LICENSE file is GPL v3 but every src/ header carried the LGPL v3 notice and the README said "LGPL v3 or later". LGPL was also the wrong fit — this is an injected mod plus a bundled addon, not a library other code links against, so LGPL's linking exception buys nothing. It's also required: src/voicechat/Tts.cpp is ported from awesome_wotlk's VoiceChat.cpp, which is GPL v3, and a derivative of GPL code cannot be relicensed under more permissive terms. Dependencies stay compatible — MinHook (BSD-2) and the nampower-mirrored packet shapes (BSD) are GPL-compatible, and SAPI is covered by the system-library exception. Swept "GNU Lesser General Public License" -> "GNU General Public License" across all 257 src/ headers and changed the README license line to match the GPL v3 LICENSE file. Comment-only; no build impact. |
||
|
|
2403ff7233 |
Detect player cast/channel from packets, not just the cast global
The 1.12 engine short-circuits a chained same-spell recast: Spell_C_CastSpell bails at `spellID == VAR_CURRENT_CAST_SPELL` before setting the global or firing SPELLCAST_START, so the client never runs its cast path for the 2nd of a back-to-back same-spell cast (common with nampower spell queueing). And the player channel field (+0x228) is server-pushed, landing ~1 tick after the channel starts, so polling it shows the bar ~1s late. Rework the player UnitCastingInfo / UnitChannelInfo tracking into a hybrid: - Normal casts: co-hook FUN_CAST_START_SET, stamp g_cast from the spellID arg before the original (zero latency); cleared by the VAR==0 WorldTick poll. - Chained same-spell recasts: stamp g_cast from the SMSG_SPELL_START co-hook (server castTime), deduped against a fresh client stamp, exempt from the VAR clear, self-expiring on endMs. - Channels: stamp g_channel from the same packet (engine-computed duration) instead of the lagging +0x228 poll; self-expire on endMs. - Cast and channel are mutually exclusive for the player. - Co-hook SMSG_SPELL_DELAYED for cast pushback (extends endMs + delayMs). Add FUN_SPELL_DELAYED and FUN_CAST_START_SET offsets. |
||
|
|
b8d55e8dea |
Back UnitCastingInfo / UnitChannelInfo for remote units
Vanilla stores no cast record for other units, so UnitCastingInfo(other) returned nil and remote channels had no timing. Co-hook the SMSG_SPELL_START handler (0x006E7640, gated on opcode 0x131) -- the only packet carrying another unit's cast with a server-authoritative cast time -- and cache it per caster GUID (cast vs. channel split by AttributesEx channel bits). - UnitCastingInfo(unit): full timing for any unit within its cast window; enemy/target/focus/nameplate cast bars now work, not just the player. - UnitChannelInfo(unit): remote channels get real start/end times when the channel's begin was observed, validated against the live +0x228 field so a stale entry never sticks; falls back to the old no-times path otherwise. - Player path unchanged (self-tracked); the cache skips caster==PlayerGuid. Factor the CDataStore packet reader out of Aura::Source into a shared Net::PacketReader header (vtable-correct) used by both packet hooks. Best-effort: only casts begun while the unit was in range are seen, and an interrupted remote cast lingers until its computed end (1.12 sends no per-unit interrupt packet to hook). |
||
|
|
d2672d818d |
Move cast/channel info under C_Spell to free the global names
UnitCastingInfo / CastingInfo / UnitChannelInfo / ChannelInfo were registered as globals (mirroring modern WoW), but that clobbers addons that ship their own vanilla cast-tracking via the `_G.UnitCastingInfo or <fallback>` idiom — notably ShaguTweaks' libcast.lua, which scrapes the combat log for remote/enemy casts the 1.12 engine never exposes. With our global present those addons adopt our player-only version and drop their (superior, for enemies) fallback, killing enemy cast bars. We can't match the combat-log scraper in the DLL (the engine carries no remote regular-cast data), so cede the global names and register under C_Spell instead. Tradeoff: addons calling the global UnitCastingInfo/UnitChannelInfo must use the C_Spell.-prefixed names now; enemy-cast consumers got nil from the global anyway. |
||
|
|
4263bae064 |
UnitChannelInfo: effective channel duration via engine helper
Channel end time read SpellDuration.dbc base directly; route it through the engine's own duration helper FUN_006ea000 (base + level scaling + duration SpellMod op 1, unit arg 0 = local player) — mirroring how the cast time is sourced, so the channel bar matches the engine and any per-level / talent duration is honored. Stock vanilla channels are fixed-duration, so no change there (verified: Blizzard still 8s). Completes the SpellMod op map derived this session: duration 1, range 5, radius 6, cast time 10, cost 14. |
||
|
|
bf9250141a |
Add UnitCastingInfo / CastingInfo / UnitChannelInfo / ChannelInfo (TODO #68)
Cast/channel info for the local player with full timing, plus channel spellID/name/texture for any unit. Vanilla stores no cast times anywhere readable (confirmed via the cross-binary technique: 3.3.5 reads them from per-unit CGUnit fields that don't exist in 1.12), so the player's cast/channel start/end are self-tracked on WorldTick: - cast: VAR_CURRENT_CAST_SPELL 0->nonzero transition stamps startMs = now (FUN_OS_TICKCOUNT_MS) and endMs = now + effective cast time. The cast time comes from the engine's own helper FUN_006e3340 (base + level scaling + cast-time SpellMod op 10 + the caster's haste/cast-speed multiplier), the same one the engine cast-start uses -- so end time matches the cast bar, e.g. a talented Frostbolt reads 2.5s not 3.0s. Instant casts (cast time 0) and channels are filtered out. - channel: player's broadcast UNIT_FIELD_CHANNEL_SPELL (+0x228), endMs = now + SpellDuration base ms. FUN_OS_TICKCOUNT_MS shares GetTime()'s epoch (x0.001), so startMs/endMs feed addon progress math directly. Other units: channel info from the broadcast +0x228 field (no times, since per-unit start isn't tracked); regular casts return nil (no vanilla data -- remote casts are transient spell-visual objects, not a queryable record). isTradeskill is real: the spell's SPELL_ATTR_TRADESPELL flag (Attributes bit 0x20). Remaining placeholders: castID/castBarID nil, notInterruptible false, delayTimeMs 0. Verified in-game: Blizzard channel 8s, Conjure Food cast 3s, talented Frostbolt 2.5s, correct icons/spellIDs, GetTime()*1000 between start/end; isTradeskill true for Rough Blasting Powder (Engineering). Docs: API.md sections + README Spell row; TODO #68 marked done. |