mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 08:00:42 +00:00
* feat(text): inline |T...|t texture escapes in chat and display text
Backport modern inline-texture markup to the 1.12 text engine: |Tpath:h|t
renders an icon inline in FontStrings / chat, for BLP and uncompressed TGA.
- Rendering primitive: resolve a path to a resident CGxTexture via FUN_0044acf0
and draw it as a textured quad through the UI text VB path.
- Positioning: co-hook the per-line glyph emitter (FUN_005ccbe0); render plain
runs by delegating to the original per segment (threading the pen through
linkState[4], read as a float), record icon quads at the pen, and flush them
in the paint pass (FUN_005c8fe0) translated by each node origin. Handles the
FontString pipe-doubling (|T -> ||T), the bit-3 per-call batch-clear mode,
multi-icon and multi-line accumulation, and font-relative vertical centering.
- Measure/wrap: co-hook the shared tokenizer (FUN_005c2810) so an inline-texture
span is one near-zero-width token, so icons no longer force early line wrap.
- Editbox exclusion: read the focused-editbox global (DAT_00cf4dc8) and suppress
icon recording while an input field is focused, so editboxes show raw,
editable markup while cached display text keeps its icons.
Diagnostic scaffolding (stats/capture Lua helpers) is still present. Follow-ups:
exact icon width in measure (hover-box accuracy), texcoords for sprite sheets,
vertex color, and the already-built editbox case. See docs/InlineTextureEscapes.md.
* fix(text): exclude editboxes from inline textures via node flag bit 6
Editable text (node flags [+0x5c] bit 6 / 0x40 -- verified in-game: the macro
editbox is 0x4D vs chat display 0x20D and FontStrings 0x0D) now shows raw,
editable |T...|t markup instead of rendered icons, checked per node in the
tokenizer, emitter, and flush. This is the 1.12 analog of 4.3.4's per-render
texture-disable flag (tokenizer bit 0x1000).
Replaces the earlier focus-global-only exclusion, which only caught single-line
inputs that rebuild on each keystroke; bit 6 also covers multi-line editors
(the macro editor) that build once while un-focused. The keyboard-focus global
(DAT_00cf4dc8) is kept as a fallback. Removes the failed monochrome heuristic.
Diagnostic scaffolding remains; a docs update and cleanup pass follow.
* feat(text): inline-texture texcoords + fix vertical flip
- Add the width / offset / texcoord fields to the escape
(:width:offsetX:offsetY:texW:texH:left:right:top:bottom), so a sprite sheet
such as UI-RaidTargetingIcons can be cropped to a single cell.
- Fix a vertical flip: the UI device backend is OpenGL (bottom-left texture
origin), so top screen corners map to v1 and bottom corners to v0. The flip
was invisible on symmetric icons but obvious on directional ones (raid-target
markers, swords).
* docs(text): document the completed inline-texture RE map
Fold this session's findings into InlineTextureEscapes.md now that the feature
ships: the frame -> renderNode -> group -> node -> line render hierarchy;
segmented-delegation positioning (the float linkState[4] pen read, the bit-3
per-call batch-clear handling, first-line multi-line accumulation); font-relative
vertical centring; the FontString pipe-doubling (|T arrives as ||T); the shared
tokenizer measure/wrap fix; editbox exclusion via node flag bit 6 (0x40), with
the failed focus-global and monochrome attempts recorded so they aren't retried;
and the texcoord fields plus the OpenGL bottom-left vertical flip.
* chore(text): enable inline textures by default on this branch
* feat(text): inline-texture vertex colour tint (:r:g:b)
Parse the trailing r:g:b (0-255) positional fields of the inline-texture
escape and apply them as the quad's vertex colour, so |T...:r:g:b|t tints
the icon (the font stage's default MODULATE COLOROP does texture.rgb x
tint; white = untinted). The bytes pack to 0xFFrrggbb -- the same
0xAARRGGBB order the tokenizer builds for |cAARRGGBB text, verified from
FUN_005c2810's colour branch -- so the value flows straight into the
existing vertex colour slot. Threaded parse -> IconDesc -> IconRecord ->
DrawTexturedQuad. Verified in-game (red/green/blue/white diamonds).
Also record the hover-accuracy (measure-width) verdict in the docs: the
tokenizer reports an icon as ~zero width, so GetStringWidth/wrap/hit-test
undercount it. Scoped by disassembly (FUN_005c6940 width backend,
FUN_005c6b70 per-glyph advance, FUN_005cdc20/FUN_005c7260 wrap): the token
contract has no width field, there is no single cold choke, and the only
fixes are hot per-glyph hooks (against the MinHook-collision guidance) or
~6 parallel measure-loop hooks -- for a mostly-cosmetic gain. Deferred.
* docs(text): record editbox/measure findings; strip inline-texture debug scaffolding
No behavior change — functionally identical to the shipped inline-texture
feature. This captures what a long investigation established and removes the
temporary debug instrumentation added during it.
Comments (src/text/InlineTexture.cpp):
- The tokenizer's `flags & 0x40` gate is load-bearing for RENDER, not just
measure: a suppressed editbox delegates to the ORIGINAL emitter, which
re-enters the tokenizer to lay out glyphs, so bit 0x40 (EDITABLE) must make
the tokenizer stand down or the macro editor draws BLANK instead of raw.
- bit 6 (NodeEditable) and the focus global (InputFocused) are COMPLEMENTARY,
not redundant: bit 6 catches the un-focused macro editor; the focus global is
the only signal for single-line focused inputs (chat box, pfChatCopyBox),
whose nodes lack bit 6 (0x0D/0x20D, indistinguishable from display).
- Removed the tokenizer call/pipe/span counters and the ZZWIDTH TokCap capture
(debug-only), and the now-unused g_lastFocused/g_lastMono stats fields.
Docs (docs/InlineTextureEscapes.md):
- Editbox exclusion: two complementary signals, and VERIFIED against retail —
typing `|T` into a chat box or macro editor shows raw there too; only
addon/system text renders. Our editbox-raw + display-renders split matches.
- Measure gap: added the focus-time caveat (icon ~0 width unfocused; counts the
literal path text while an editbox is focused — the editbox-raw tradeoff).
- Vertex-colour tint documented in the descriptor-fields section.
* feat(chat): strip player-injected |T icon spoofs from chat + bubbles
Vanilla neutralizes player-TYPED escapes in chat (a typed |c/|H/|T shows
raw); only trusted text (addon AddMessage, shift-clicked links) renders
them. Our Text::InlineTexture backport broke that parity for |T alone: it
detects the neutralized ||T form and draws the icon anyway, so a player
could /say |Tpath|t and put a real icon in everyone's chat AND the speech
bubble over their head. This restores vanilla behavior for |T while leaving
|c/|r/|H/|h exactly as vanilla.
It can only be done at the chat source, not the text emitter: addon |T and
player |T reach the emitter as byte-identical ||T (vanilla doubles the
unrecognized |T for both), so the only place they differ is provenance --
server chat flows through the chat dispatcher FUN_0049A870, addon print does
not. That one function copies the message into a single buffer fed to BOTH
the chat frame and the say/yell bubble spawn (FUN_00608AC0), so sanitizing
on entry covers both. (ECX is the MESSAGE, not the "sender name" the old
note claimed -- verified from the call site in FUN_0049D560.)
Structure mirrors Net::PacketDispatch (one hook, fanned out), since MinHook
allows only one hook per target and this choke point already had the
GUID-capture concern on it:
- Chat::Dispatch -- single owner of the FUN_0049A870 hook; orchestrates
- Chat::IconFilter -- pure Sanitize(); no hook, no engine state
- Chat::CurrentGUID -- GUID globals + getter + DispatchScope RAII (no
longer owns a hook)
Defang detail (the subtle bit): the message arrives doubled (||T). Blanking
the PIPE would leave a lone `|` + space -- an INVALID escape the chat frame
tolerates but the bubble text setter chokes on, producing an empty bubble
that fades instantly. So we keep the `||` (a valid literal-pipe escape) and
blank the `T`; for a lone |T we blank both chars. No dangling `|`, no |T
opener survives. Verified in-game: typed |T shows raw in chat and bubble,
addon icons still render, colours and links untouched.
* feat(text): per-editbox inline-texture suppression
Inline-texture rendering was globally suppressed whenever any editbox held
focus (VAR_FOCUSED_EDITBOX != 0), so opening the chat box flipped every
rendered icon/emote in chat history to raw |T...|t.
Replace the global check with per-editbox buffer correlation: suppress inline
rendering only for text that belongs to the FOCUSED editbox, matched by
pointer range against its own text buffers. Chat history keeps rendering while
you type.
The editbox keeps its text in two buffers (both verified via Ghidra), and both
must be matched or the field desyncs (raw width but a rendered icon):
- INPUT buffer ([fe+0x32C]/[fe+0x334], selected by [fe+0x318]&8) — the
caret/width MEASURE path reads it in place (FUN_0077da80 -> FUN_00772ae0 ->
FUN_005c6940, which loops the tokenizer).
- DISPLAY buffer (*([fe+0x328]+0xF0)) — a SStrDup'd copy the editbox actually
RENDERS from (FUN_00771d80); the emitter node text and the re-entrant render
tokenizer see this one.
TextInFocusedEditbox() bounds each buffer by a tight strlen (distinct heap
allocations -> no false-match cap) and runs only on pipe-leading tokens after a
null-focus short-circuit, so it stays off the hot path. A display FontString
measured while an editbox is focused matches neither buffer, so its icons now
measure correctly -- an improvement over the old global.
Editbox struct offsets centralized in Offsets.h (OFF_EDITBOX_BUFFER_SELECT /
BUFFER / BUFFER_MASKED / TEXT_FONTSTRING).
* feat(chat): raid-target marker substitutions ({rt1}/{skull}/…)
Expand the modern raid-target marker tokens in chat into inline icons, backported
onto the inline-texture renderer. {rt1}..{rt8} plus the named aliases ({star},
{circle}/{coin}, {diamond}, {triangle}, {moon}, {square}, {cross}/{x}, {skull};
case-insensitive) each become a |T escape cropping Interface\TargetingFrame\
UI-RaidTargetingIcons to the matching 64x64 cell (mapping verified against the
client's UnitPopup.lua: col=(N-1)%4, row=(N-1)/4).
Chat::RaidMarkers::Substitute runs in Chat::Dispatch AFTER the |T anti-spoof
sanitize, so players get the fixed, safe marker icons without a path to inject an
arbitrary texture. It emits the pipe-DOUBLED ||T…||t form: the inline emitter
renders both, but this is what survives into speech bubbles — the vanilla bubble
text builder (FUN_004b1600) truncates a lone |T while preserving ||, and pfUI's
bubble reskin copies the bubble's FontString text into its own FontString, which
then renders the icon through the normal paint path. (This is the form bubbles
rendered before the anti-spoof filter defanged the ||T opener.)
InlineTexture emitter fixes for the standalone-FontString (bit-3, batch-clear)
render path that bubbles/tooltips use — chat lines are unaffected:
- Colour: clearing bit 3 switches the engine to per-glyph colour from
colorState=[node+0x2c], whose alpha byte is a stale ~0x07; force the glyph
alpha opaque (keeping RGB) so a FontString coloured via SetTextColor with plain
text doesn't render near-transparent (which showed only pfUI's dark outline =
"black text"). |c-coloured text already has full alpha, so it's a no-op for chat.
- Horizontal justify: the engine positions centre/right-justified text using the
MEASURED width, which counts inline icons as ~zero (the measure gap), so the
rendered line overflows its box. Pre-sum the line's icon widths and shift the pen
(half for centre, full for right) so text+icons justify as a unit.
- Default centerFrac 0.5 -> 0.6 (better vertical centring across chat + bubbles).
* fix(text): suppress inline textures in editboxes by content match
The per-editbox suppression missed the chat input box: a pasted `|T…|t` rendered
as an icon instead of raw markup. An in-game probe showed why — the editbox
renders its text through a TRANSIENT copy: same bytes as the input buffer, but a
distinct heap allocation with no pointer link to the editbox in either direction
(every offset/back-pointer scan of fe / its FontString / the render node came back
-1). So the prior pointer/node-identity checks (input buffer, SetText copy,
FontString +0x48, node == *(fe+0x328)) could never match the render.
Match on CONTENT instead:
- Emitter: EmitLineIsFocusedEditbox compares the render line's bytes against the
focused editbox's input buffer (the emitter is handed the whole line, so a
bounded strcmp identifies it). Chat-history lines differ, so their icons keep
rendering while an editbox is focused.
- Measure (caret/GetStringWidth): unchanged pointer path — the tokenizer reads the
input buffer in place, so TextInFocusedEditbox still matches by range.
- Re-entrant render: the suppressed emitter brackets its delegated raw layout with
a text range (g_reentryLo/Hi); the tokenizer stands down across the whole span
via TextInReentry, so `|T` isn't eaten as a zero-width token (which drew BLANK).
Drops the dead node-identity/second-and-third-buffer heuristics. Covers any focused
input (chat box, pfChatCopyBox, macro editor).
* fix(text): drop stale icon records for reused chat line FontStrings
Inline-texture icons could paint as a ghost strip at the bottom of the screen
after chat had been busy for a while. The chat frame reuses its line
FontStrings: when a line is cleared (text set empty) or reused for markup-free
text, the draw builder early-returns on it, so the emitter never runs — and so
never erases that node's old icon record. The paint flush still walked the node
and drew its now-stale record at the FontString's parked position.
Gate the flush draw on the node's LIVE text still containing `|T`: if a node has
an icon record but its current text has no markup, the record is stale — drop it
and skip drawing. Kills the bottom-of-screen ghost.
(The separate scroll-freeze — icons only refreshed on the chat's dirty repaints —
is a different, deeper issue tracked next.)
* fix(text): stop chat icons vanishing — suppress only input boxes, not editable chat display
pfUI renders the chat scrollback through EDITABLE nodes (flags 0x45: bit 6
editable, no bit 3). The inline-texture emitter's blanket NodeEditable gate
suppressed inline rendering for ALL editable nodes, so those chat icons blanked
whenever that display was live — during scroll and as messages arrived, which
read as icons "disappearing/reappearing."
Gate suppression on a true INPUT box instead: editable (bit 6) AND bit 3 (0x08).
Macro editor 0x4D and name/chat input 0xC8 all carry 0x08; the chat scrollback
0x45 does not — so real input boxes still show raw |T markup while the chat
display keeps its icons. Also drop the flush's NodeEditable draw-gate: a
suppressed input box never records, so any record reaching the flush is a real
display line.
Pointer/content match alone can't cover a focused input box because its render
form is pipe-doubled (||T) while the input buffer is single-pipe, so the compare
misses.
* feat(text): inline |T icons as fontstring-anchored engine regions
Port 4.3.4's CSimpleEmbeddedTexture model. Each icon the emitter records
becomes a pooled CSimpleTexture ANCHORED TO ITS OWNING FONTSTRING,
configured off-render on the WorldTick, and drawn by the engine's own
region pipeline. 1.12 chat lines are real CSimpleFontStrings (the
ScrollingMessageFrame display refresh FUN_00788750 drives one per visible
line), so a co-hook on CSimpleFontString::RebuildString (0x7724A0) maps
every text node to its owner and one mechanism covers chat, tooltips, and
standalone FontStrings.
This replaces the raw-GxU-quad renderer and every overlay attempt:
- engine-drawn regions keep their textures resident: no flicker, verified
across three concurrent clients
- the anchor system moves icons with their lines: scroll costs nothing
- icons mirror the owner's shown state: faded lines hide their icons
- all engine mutation happens outside the render pass: no pending-layout
corruption, survives /reload (pointers dropped in PrepareForReload)
- placement verified pixel-exact against owner rects
RE landmarks recorded in Offsets.h:
- fs+0xF8 is an HTEXTBLOCK handle; the text node is at handle+8
- Show (0x77FCB0) no-ops unless desired-shown (+0xC4) is set, and
SetParentAndLayer(show=0) clears it on reparent
- the renderer draws the corner array (+0xD4), stored from the rect by
SetTexCoord - realize (0x768060) must run between SetPoint and
SetTexCoord or the corners go stale (the historical invisible-icon and
frozen-top-left-icon bugs)
- pen coords are y-down from the owner fontstring's BOTTOM edge; anchor
offsets use Script_SetPoint's pixel scale (LinePool::PixelToInternal)
* refactor(text): inline |T icons = pixel-perfect quads + residency holders
Replace the fontstring-anchored region approach with a hybrid that
decouples position from residency, because the two live in different
coordinate spaces that no single scale could reconcile:
- POSITION: draw each icon as a raw GxU quad in the text engine's own
render space (pen + node origin), the same coordinate system and
dynamic VB the glyphs use. Pixel-exact by construction — no anchor/
layout-space conversion. This is the original quad math; the region
detour proved pen-space and anchor-space differ by the text paint's
projection, not a scalar, so region anchoring could never be exact.
- RESIDENCY: a raw quad binds an unowned texture the engine evicts under
VRAM pressure (the flicker on scroll / blank on a 2nd client). So for
each distinct texture path, Text::InlineTexturePool creates ONE managed
CSimpleTexture, draws it every frame (a ~2px, alpha 1/255 corner box),
and never touches it again — its engine-managed draw is the live
reference that keeps the texture resident for the quads to bind.
Verified in-game: icons pixel-perfect across chat / bubbles / wrapped
lines / sizes / tint, no flicker on scroll, and two concurrent clients
both render — the residency-holder premise (untested before: the earlier
"disproof" had non-drawing holders) finally validated with a holder that
actually draws. Non-zero holder alpha is load-bearing: a fully
transparent region gets culled and residency is lost.
Diagnostics (probe, perf counters, scale/bias tune knobs) stripped; the
SEH fault guard on the flush stays.
* feat(text): render inline |T icons as engine regions anchored to their fontstring
Replace the raw-quad + residency-holder hybrid as the default renderer with
the 4.3.4 CSimpleEmbeddedTexture model: one pooled CSimpleTexture per visible
icon, anchored RELATIVE TO THE OWNING FONTSTRING. Engine-drawn, so texture
residency (the chat scroll flicker / blank 2nd client) is impossible by
construction; engine-anchored, so icons track their line for free.
The pen<->anchor bridge that unblocked this: RebuildString (0x7724A0)
multiplies every text-unit quantity by fs+0x7C when creating the text node,
and the node origin is the fontstring's justification anchor point mapped by
a single measurable scale K (verified with two-position probes: origin =
rectJustifyRef x K, K ~ 1470 = physical px per anchor unit, both axes, no
drift). Placement pipeline:
- RebuildString co-hook records node -> owning fontstring (a node only
speaks for its fs while it IS fs+0xF8->block+8, killing the stale-node
clear race around rebuilds).
- The paint hook converts each icon's pen-space quad through K and queues
fs-relative placements; regions are keyed BY FONTSTRING (nodes die on
every SetText - node keying orphaned regions into an accumulating wall).
- Placements apply on WorldTick, never mid-render. SetPoint offsets are
divided by the region's effective scale (+0x7C; anchor resolution
multiplies stored offsets by the scale chain - measured 0.0319 stored ->
0.0290 resolved = x0.91), then converged exactly by a per-region rect
readback correction each tick (deterministic, self-healing; a same-call
readback read stale pooled rects and shipped 7.4px crests).
- Engine SetTexCoord (0x770410) takes the 4-float rect Y-FIRST INTERLEAVED
{v0,u0,v1,u1} (diagnosed in-game: {u,v,u,v} rendered the raid-mark moon
as the circle cell); it is absolute, and the +0x124 shrink-by-UV-span
flag stays clear so crops stretch to the rect like modern clients.
- Expired/hidden lines are swept every tick (regions parent to the chat
frame, not the line, so they cannot inherit the line's own hide).
The quad renderer and residency holders remain behind
_classicapi_InlineTexMode (0 = quads, 1 = regions [default], 2 = overlay
A/B) as the bring-up oracle, plus diagnostics (_classicapi_InlineTexProbeFS
/ RegionDump / RegionCal / HolderCfg). Calibrated residual: RegionCal
(3, -1) pen units.
* fix(text): apply the inline-icon LEAD pad at draw time
The emitter reserves w + 1.5x pad in every inline icon's advance (lead 1x,
trail 0.5x), but FlushLayout drew the icon at the raw pen - all reserved gap
landed AFTER the icon, none before. Mid-text icons looked balanced only
because their surplus trailing gap padded the following text; a string-FINAL
icon (the money-string copper coin) sat jammed against its digits, and the
locale format strings had grown per-coin offsetX hacks to compensate.
Draw at pen + w x iconPadFrac (quads and regions share the cx), matching the
emitter's reservation. The coin formats drop to zero offsets - verified
against the texture itself: the three coin arts in UI-MoneyIcons are
byte-identical in alpha (same bounds, same center of mass, measured from the
exported BLP's DXT3 data), so no coin ever needed a positional nudge.
RegionCal's baked x constant drops 3 -> 0: the +3 calibrated pre-fix was
exactly this missing lead pad (user re-calibrated (0,-1) post-fix). The 1px
y residual remains the pen->anchor map's one true constant.
* fix(text): make inline-icon state lifetime-exact; fix every scroll-landing loss
Chat icons randomly landed shown-or-hidden when lines scrolled, and stale
icons ghosted at parked positions. Root causes, each found by in-game
triangulation (FsDump/Broken/Stats diagnostics, included), all fixed:
- Placements are FS-RELATIVE, computed at PAINT time in one coherent
snapshot (icon coords + fs rect in the same flush). The old apply-time fs
rect read raced the chat relayout after SetText and parked icons off
their line, where the dedup froze them.
- The queue tail gate now matches the per-icon build gate EXACTLY (incl.
K); any not-ready input skips-and-retries instead of queueing {} - an
empty queue froze lines iconless via the dedup (early-session K window).
- K (pen->anchor scale) is derived PER NODE from its own fontstring - pen
space scales with each fs's frame-scale chain, so a global chat-derived K
mis-sized icons on differently-scaled fontstrings. Global cache kept as a
+/-10%-clamped fallback.
- Stuck-blockless fontstrings (RebuildString releases the block on a
SetText that lands on an unresolved rect and never rebuilds; the zombie
node keeps painting) are re-dirtied so the engine rebuilds - the icon
pipeline then resumes naturally.
- First-line-of-build detection comes from a draw-builder co-hook
(FUN_005CDC20) build stamp - exact - with the old text-pointer heuristic
only as fallback for emitter paths outside the builder.
- THE LIFETIME FIX: co-hook the gxu text-node free (FUN_005CD950, the
single site where every node dies and its address becomes reusable) and
erase ALL per-node state there. Anything in the maps now refers to a
live node by construction: inherited ghost records on recycled nameplate
fontstrings, orphaned owners (dropNoFs 61k -> 0), and reload leftovers
lose their mechanism of existence.
- Ghost guard rescans the FONTSTRING's text (fs+0xF0, proven trustworthy),
not the node text pointer (which lied on pfUI chat lines and made the old
scan erase LIVE records every frame - the persistent iconless LFG lines).
False matches can only false-keep, never false-erase.
- Freshness TTL: regions stay only while the paint keeps re-queueing their
fontstring (deduped touches count); parked/orphaned fs regions expire in
~1s. Do NOT build-version records against the builder counter - the
builder runs every paint but only emits when dirty, so a version check
erases good records on every clean paint (the all-icons-gone regression).
Diagnostics added (Lua): _classicapi_InlineTexFsDump (pipeline triangulation
with chain classification), _classicapi_InlineTexBroken (names the broken
lines), _classicapi_InlineTexStats gains queued/drop/nudge counters and the
SEH fault address.
Also removes the FrameTick glue-screen attempt (b164d68): hooking the UI
render root regressed in-world chat; glue-screen icon support will be
re-approached without touching the in-world render path. The
FUN_UI_RENDER_ROOT offset stays documented for that retry.
* fix(text): pointer probes must allow Large-Address-Aware heap (>2GB)
LooksReadable capped plausible pointers at 0x7FFF0000. This client is LAA
(VanillaFixes), so heap allocations above 0x80000000 are valid and routine
once the heap grows - and the flush's layout walk BREAKS on an "unreadable"
node, so a single high-heap node silently truncated the walk and every node
AFTER it in the layout list lost its icons. That was the irreducible random
per-ROW missing-chat-icon bug that survived every renderer architecture
since the guard shipped with the first inline-texture commit (aa94ea5): it
fired only when the allocator placed a node/fontstring above 2GB, varying
per session with addon load and uptime. The same check also rejected
high-heap fontstrings (dropNoFs storms, "unreadable" owner chains).
Bound raised to 0xFFFF0000 in both copies.
Diagnosed with the per-node build/emit instrumentation added here: the
smoking-gun Broken() trio was builtKnown=1 (engine built the node),
emitOutcome=8 (emitter recorded its icons), nodeSeenAge=-1 (our walk never
once saw it). _classicapi_InlineTexBroken now reports both new fields.
* feat(text): render inline |T icons on the glue (login) screen
Inline icons never appeared on the login / character-select screens: the
text-pipeline hooks are engine-generic and fire on glue (the |T spans are
consumed there), but InlineTexturePool::Maintain - the step that creates and
shows the icon regions - was driven by Tick::WorldTick, and FUN_WORLD_TICK
(0x0066FD50) is the world-simulation tick, silent on glue. Queued placements
were never applied.
Add Tick::FrameTick, hooked at FUN_UI_RENDER_ROOT (0x00764330) - the
CSimpleTop singleton's per-frame render callback, registered by both the
world-init (FUN_0048FBF0) and glue-boot (FUN_0046A7B0) paths and drained
every frame by the master scene-render pump. Subscribers run at the tail of
the callback (strata walk complete, no frame mid-draw). The pool's Maintain
moves onto FrameTick as its ONLY tick: one driver, fires wherever the UI
renders.
An earlier version of this change was blamed for an in-world chat regression
and reverted. That regression was the Large-Address-Aware pointer-bound bug
(dc61f77) rolling its allocation dice at the moment the tick moved - the
symptom persisted after the revert, which already exonerated the hook.
Glue boot (LoadGlueScriptFunctions_h) now also clears the inline-icon maps:
the world->glue teardown bulk-frees every world fontstring and text node they
reference (glue->world was already covered by FrameScript_Initialize_h, and
the node-free hook covers individual deaths in both states).
WorldTick keeps its world-only subscribers (aura eviction, cast state, raid
targets) - they read world state that is null on glue; the two ticks stay
semantically distinct: WorldTick = "world advanced", FrameTick = "a UI frame
is rendering".
* feat(text): icon-inclusive GetStringWidth + FontString:GetStringHeight backport
GetStringWidth now counts inline |T...|t icons. The old "deliberate
measure gap" analysis was right that the gxu engine has no cold choke
(parallel measure/wrap/hit-test loops, no width field in the token
contract, hot per-glyph helpers) - but the choke sits one level up:
FUN_00772890 = CSimpleFontString::GetStringWidthInternal, a cold,
MinHook-safe funnel for exactly 4 callers (Script_GetStringWidth,
GameTooltip auto-size, editbox caret positioner, effective-width
vmethod). The co-hook calls the original and re-adds the icon advances
the tokenizer hook hid, so measured width matches rendered width - and
tooltips/auto-width layout now size correctly for icon lines.
Shared-source refactor so measure and render can never disagree:
- InlineInterceptActive: the tokenizer's stand-down set factored into
ONE predicate (tokenizer passes gxu flag 0x40; the width hook passes
fs+0x120 & 0x1000, the fs-level bit FUN_0044D670 translates into it,
so editbox carets keep measuring raw markup).
- IconAdvancePen/SumIconAdvances: the emitter's reserved advance
(w + 1.5*pad + positive offsetX) factored out and shared by the
emitter loop, the justify pre-shift, and the width hook. Side fix:
the justify pre-shift previously omitted the positive-offsetX term.
Units (bit us on first flight): escape sizes are UI pixels; convert
px->anchor by the push factor K = [0x832A4C]*1024/[0x832A44] (~1468),
NEVER by fs+0x7C - that's the layout UI scale (~0.68), and dividing by
it measured a 16px icon as +44k px. The hook never writes the fs+0xFC
cache (original may serve cached; the sum is re-added per call).
Verified in-game: delta +19.5 for a 16px icon = 20.32 exact advance
minus the known 0.8 trailing-icon ink-width residual. Wrap-break,
substring measure, and hit-test stay icon-blind (documented).
FontString:GetStringHeight() (2.3.0+ binding) backported in new
src/fontstring/Metrics.cpp: 1.12 already ships the internal wrap-aware
getter FUN_007729B0 (cache fs+0x100, lines*fontH + (lines-1)*spacing,
same wrap engine the render uses, empty -> 0) - it just was never
bound. Registered on the FontString method registry; mirrors
Script_GetStringWidth's resolve + anchor->px push conversion.
Verified in-game: one-line 11.7, wrapped 46.9 (4 lines), empty 0.
* fix(text): wrap lines account for inline icon advances
Wrap decisions measured inline |T icons as ~0 (the tokenizer hook), so
icon-bearing chat lines broke as if the icons weren't there and the
emitter's real advances ran past the frame's right edge.
Choke: FUN_TEXT_WRAP_STEPPER (0x005C7260), the wrap-stepper dispatcher
that lays out one wrapped line per call. Its exactly 4 callers are
every wrap consumer - the draw builder (render breaks), the height
measure (GetStringHeight), the chars-that-fit counter (ellipsis), and
the break-array computer - so one co-hook keeps render, height,
truncation, and break arrays mutually consistent. outBreak and
outNext-text are byte counts (==len means "all fit"); outWidth is the
measured icons-at-zero line width in the caller's units.
The hook shrinks the wrapWidth argument by a minimal feasible shrink,
found by probing the stepper sandboxed (local out-params + a copy of
the p10 first-line state byte): feasible(s) iff the line's icon
advances fit in the shrink plus the spare the break left
(iconSum <= s + probeW - outWidth). s=0 feasible -> no shrink (the
common fits-anyway case); otherwise escalate by the measured deficit,
then bisect the [infeasible, feasible] bracket to a quarter-glyph
(<=8 probes). Never overflows; packs each line to its physical
capacity. Gated on the shared InlineInterceptActive predicate + the
editbox flag bit 0x40 the dispatcher already carries.
Unit trap #2 (cost one flight): each caller passes fontH/wrapWidth in
its OWN space - node text units from the builder, the small
anchor-converted space from the fs-level callers chat wraps through.
px -> caller units = fontH / FUN_TEXT_FONT_HEIGHT(flag, fontH), the
engine's own pixel realization of the fontH param (FUN_005C6940's
final scale proves the convention for every gxu caller).
Rejected en route (documented in docs/InlineTextureEscapes.md): raw-px
subtraction (shredded lines to 2-glyph fragments), whole-remaining-
text sums (8-icon line -> one word per line), icon-count fixed-point
iteration (oscillates - 55-byte zero-width escapes make the
break<->count coupling discontinuous), max/average tiebreaks.
Cross-checked against 4.3.4 (renders |T natively): Blizzard extended
the token contract instead - texture token type 7 + a shared parser
(FUN_00617ba0) called inline by all five layout loops, fontH passed in
for :0 defaults, plain width, no padding. No single-choke trick exists
at source level; the probe search is the 1.12-shaped equivalent.
Diagnostics: _classicapi_InlineTexWrap(n) dumps the last 8
icon-bearing calls (widths, per-probe sums/breaks/raw out-params,
final shrink, floor hits).
* fix(text): wrap-shrink search refinements from in-game shakeout
Three fixes to the minimal-feasible-shrink search (2450522), each from a
live regression the _classicapi_InlineTexWrap diag pinned down:
- Full bracket bisection (<=8 probes, quarter-glyph epsilon). The first
cut abandoned the [infeasible, feasible] bracket after one stale
escalation candidate, costing the Marks harness line a whole
mark+word pair per line (3+5 instead of the optimal 4+4).
- Half-glyph feasibility tolerance. The width hook and the wrap hook
derive the icon sum through different unit chains (FUN_007727B0xK vs
FUN_005C6FA0 ratio, OUTLINE extras, the trailing-glyph ink/advance
quirk); the drift can read "fits exactly" as "1px over" and shrink a
zero-slack line. Genuine icon overflow is >= a full icon, so half a
glyph separates drift from real overflow.
- Auto-width bail (all text fits at s=0 AND slack <= 1.5 glyphs). A
single-anchor, no-width fontstring (pfUI's addon-list labels) wraps
at its own text-only measure plus a ~1-glyph engine margin (measured
1.07xfontH), so icons "never fit" its budget - but the box is
synthetic, icons draw past it harmlessly, and any shrink FABRICATES a
wrap ("Twitch Emotes" split across two lines). Real frames stay
covered: overflowing lines break, fitting lines carry frame-sized
slack (Marks measures ~3.5xfontH). The narrow give-up band - text
within 1.5 glyphs of exactly filling a real frame - reverts to the
pre-hook overflow, bounded by the line's icon sum.
Diag reshaped for /dump's ~30-value print cap: 8 numeric headers plus
ONE pass-summary string (shrink candidate, icon sum, line length, raw
outBreak/outNext/outWidth per probe), so no record truncates.
* feat(texture): add Texture:SetRotation via corner-vertex rotation
Backports the modern texture:SetRotation(angle [, cx, cy]) method, which
vanilla 1.12 lacks entirely.
4.3.4's SetRotation (Script FUN_0052cb50) rotates the four texture
COORDINATES around a centre and feeds the 8-arg SetTexCoord, which clips
the corners of an off-axis square. 1.12 can't mirror that — its
CSimpleTexture::SetTexCoord takes only a min/max UV rect.
1.12 has a cleaner seam: a CSimpleTexture stores its drawn quad as four
independent corner positions at +0xD4, and the draw enqueue (FUN_00772fd0)
hands region+0xD4 straight to the vertex batch as four free vertices — no
axis-aligned rect is re-derived. So rotating those four corner positions
draws a truly rotated quad with no corner clipping.
The engine fills the corners axis-aligned from the layout rect via
FUN_REGION_STORE_CORNERS; a co-hook there re-applies rotation right after
each store, so a static rotation is written once and costs nothing per
frame while moves/resizes re-rotate automatically. Angle is radians
(positive = counter-clockwise); optional (cx, cy) is a normalized pivot
in [0,1], default centre; an angle of 0 clears.
Per-region state keys on the raw region pointer and is cleared on /reload
and world->glue (Texture::Rotation::PrepareForReload). A texture freed and
instantly re-pooled mid-session could briefly carry a stale rotation —
accepted; a destructor-evict hook is the later hardening.
New in Offsets.h (all verified against WoW.exe): OFF_SIMPLETEXTURE_CORNERS,
FUN_REGION_TEXCOORD_CROP, FUN_REGION_GET_RECT.
* feat(texture): add Texture:SetVertexOffset, generalize corner transforms
Backports Texture:SetVertexOffset / GetVertexOffset (plus GetRotation),
generalizing the SetRotation module (texture/Rotation.* -> texture/Transform.*)
into one corner-transform primitive that backs both methods.
Both write the four drawn corner POSITIONS at region+0xD4 — the vertices the
draw enqueue FUN_00772fd0 hands straight to the batch; no stock 1.12 function
exposes them. Per-region state widened from an angle to {rotation, four vertex
offsets}, applied through the same FUN_REGION_STORE_CORNERS co-hook: after the
engine writes the axis-aligned corners, rotate about the pivot, then add the
offsets. The two transforms compose (matching retail) and persist across layout
resolve / move / resize / SetTexture with no per-frame cost.
SetVertexOffset offsets are UI coordinate units (like SetPoint x/y), converted
to the engine's internal layout space with the same factor Tooltip::LinePool
uses; +y is up. vertexIndex maps to a corner via VertexSlot; the
UPPER_LEFT_VERTEX / ... constants are defined FrameXML-style in the embedded
addon's Util/Constants.lua.
Non-inverting warps (perspective, skew, trapezoid, wave) are free; a warp that
mirrors the quad past edge-on inverts its winding and the region draw culls it
(documented).
* feat(texture): add Texture:SetColorTexture
Backports the 7.0 SetColorTexture(colorR, colorG, colorB [, a]) as a second
name on the engine's own Script_Texture_SetTexture handler (0x0079BB40): its
numeric branch already clamps r/g/b/a to [0,1] and fills a solid colour via
FUN_00770360 (the string branch loads a path). So SetColorTexture is exactly
vanilla's numeric SetTexture form under the modern name — zero reimplementation,
with the clamp and opaque-alpha default coming straight from the engine.
The alias also accepts a path string (a harmless superset of the retail
contract). SetDesaturated / IsDesaturated are already native (real Desaturate.bls
pixel shader); SetDesaturation is not addable — vanilla desaturation is a fixed
effect handle with no strength constant in the setter, draw command, or effect
table.
* fix(text): correct the emitter's lazy pen read-back; drop quad render mode
The inline-icon emitter hook threaded the pen between text runs by
reading the engine's linkState[4] after each delegated run. That value
is LAZY (verified in FUN_005ccbe0): the engine places each glyph at
pen + pairAdvance(prev, cur) and its final write re-adds the LAST PAIR
as a stand-in for the last glyph's own advance. For a one-glyph run the
stand-in is 0 (no pair exists), so the run read back as zero-width and
the icon drew on top of the digit — the money-string "coin covers the
lone 0/1" bug. For "] 1" the stand-in was the space's advance, ~3px
short: the single-digit clip. "11" matched by luck (same-glyph pair).
Fix (the 4.3.4 model — FUN_0061ea10 case 7 computes the pending last-
glyph advance explicitly instead of trusting a stored pen): drawRun now
token-walks each run with the engine's own tokenizer and, when it ends
in a glyph, replaces the stand-in with the truth:
pen = linkState[4] - pairAdvance(prev, last)*scale
+ baseAdvance(last)*scale
using the engine's own advance functions (FUN_005ca240 base,
FUN_005ca2d0/FUN_005ca4b0 pair, per the node's kerning flag) and its
per-placement __ftol snap. Runs ending in a non-glyph token (trailing
|c/|r) need no correction — the trailing iteration already folded the
last glyph's base advance into the write.
Also:
- The per-icon breathing pad is now FONT-relative (fontH * padFrac),
not icon-width-relative: the gap no longer scales with icon size, so
a small icon doesn't jam its neighbour while a big one floats.
- Quad render mode is removed entirely (DrawTexturedQuad, residency
holders, _classicapi_InlineTexMode/_InlineTexHolders/_InlineTexHolderCfg).
Engine regions (the 4.3.4 CSimpleEmbeddedTexture model) are the only
render path.
* feat(currency): GetCoinTextureString / C_CurrencyInfo.GetCoinTextureString
The retail coin-icon money string, backported as a C function
(src/currency/CoinText.cpp) the way retail ships it (behaviour from
3.3.5's Script_GetCoinTextureString FUN_00510d00): split copper into
gold/silver/copper, emit only non-zero denominations in that order,
zero shows "0<copper>". Each denomination formats through the
GOLD/SILVER/COPPER_AMOUNT_TEXTURE GlobalStrings, backported in the
embedded addon's locale layer (stock 1.12 doesn't have them), so
locales can override.
1.12 has no per-coin icon textures — the |T markup crops vanilla's
UI-MoneyIcons 4-cell sheet (gold 0:1, silver 1:2, copper 2:3; the
three coin arts are byte-identical in alpha, verified by decoding the
exported BLP's DXT3 data). height/width 0 = size to the display
font's height (the retail default, honoured by the inline-texture
renderer). No offsetX nudges and no separator spaces: correct spacing
comes from the renderer's font-relative pad plus the lazy-pen fix
(550cf5e) — per-coin offsets were compensations for that bug and must
not return.
FormattingUtil.lua comment updates only (GetMoneyString stays the
text-symbol form; the coin form now exists). docs/API.md: new
Currency section.
* docs(readme): list GetCoinTextureString in the API table
* refactor(text): purge the quad-mode leftovers
Follow-through on 550cf5e (quad render mode removed): delete everything
that existed only for the raw-GxU-quad path and no longer has a single
reference.
- Offsets.h: drop the GxU device primitives (dynamic-VB lock/data/
submit/unlock, texture bind, vertex stride/selector), the standalone
path->CGxTexture loader trio (FUN_TEXTURE_LOAD_BY_PATH,
PTR_TEXLOAD_DESC_VTBL, FUN_GX_TEXFLAGS_INIT), the colorop render-state
and direct-D3D state setters, FUN_TEXTURE_FORCE_DECODE, and
FUN_TEXTURE_GET_RENDERABLE. All were quad/residency-era scaffolding;
the VAs stay recorded in docs/InlineTextureEscapes.md and git history.
FUN_TEXT_PAINT (the flush co-hook site) and VAR_TEXTURE_BLEND_DEFAULT
(the pool's SetTexture blend arg) remain, with comments rewritten for
the region path.
- InlineTexture.cpp: drop IconRecord.z / penZ (only the quad draw read
them); rewrite the paint-flush section comments to describe what the
flush actually does now (queue fontstring-relative region placements).
* feat(addon): backport TextureUtil.lua (Blizzard_SharedXMLBase)
The non-atlas slice of the Classic Era reference, ported to Lua 5.0
(string.format instead of string-method syntax):
- SetClampedTextureRotation / ClearClampedTextureRotation — the retail
90-degree-step texcoord shuffle with width/height swap. Works
unchanged because 1.12's Texture:GetTexCoord() natively returns the
8-value corner form and SetTexCoord accepts it (both operate on the
same engine corner array, verified at Script_Texture_GetTexCoord
0x0079BDF0). One deviation, commented in-file: Clear also nils
rotationDegrees — the reference leaves 0 behind, which is truthy in
Lua and breaks the next Set's origTexCoords re-capture.
- GetTexCoordsByGrid — pure math.
- CreateTextureMarkup / CreateSimpleTextureMarkup — |T markup builders;
output renders via the inline-texture backport.
- TextureUtil = {} for namespace parity.
Omitted: everything atlas-based (CreateAtlasMarkup*, the TextureKit
family, CheckSetAtlas, GetAtlasSize, SetTextureWithAddressModeOptions —
1.12 has no atlas system), the LFG role-icon tables, and
GetTextureInfo (reads the atlas/fileID getters).
* refactor(text): remove the inline-texture bring-up diagnostics
The pool's _classicapi_InlineTexRegionDump / _InlineTexFsDump /
_InlineTexBroken were bring-up triage for the scroll-landing /
ghost-icon bug class, which the node-free lifetime hook ended
(b5df20d) — they have no remaining job. Removing them also kills their
entire support tree, none of which had another consumer:
- the five Debug* chain-state exports on Text::InlineTexture
(DebugChainState / NodeFlags / NodeSeenAge / NodeBuiltKnown /
NodeEmitOutcome),
- g_nodeSeen + g_flushSeq (flush visit stamps),
- g_nodeEmit (per-node emitter-outcome tracking — map churn on every
emitted line, purely diagnostic),
- g_nodeBuilt + g_buildCounter + NodeIcons.builtSeq (write-only: the
build-version check they were made for was deliberately REJECTED —
the builder runs every paint but only emits when dirty, so version
mismatches on clean paints erased live records). g_buildNode /
g_buildEmitSeq stay — they are the live firstLine detection.
NodeIcons collapses to a plain std::vector<IconRecord> map value, and
the pool drops its Game.h / InlineTexture.h includes (nothing left
uses them). The stale "versioned by build" struct comment is rewritten
to describe the actual invariant (node-free hook + firstLine erase).
Kept: _classicapi_InlineTexEnable / Suppress / Tune / Stats / ProbeFS /
RegionCal / Wrap — the live control surface and field telemetry.
* refactor(text): reduce the inline-texture Lua surface to the kill switch
Only _classicapi_InlineTexEnable remains — the feature toggle the SEH
latch pairs with. Removed with their entire backing state, none of
which had a non-diagnostic consumer:
- _InlineTexSuppress + g_suppressInline (the manual global override —
editbox exclusion has been per-node/per-buffer for a while) and the
now-unreferenced InputFocused() helper
- _InlineTexTune: g_vBias / g_sizeScale / g_centerFrac / g_iconPadFrac
become constexpr (calibrated during bring-up, fixed now)
- _InlineTexRegionCal: g_regionCalX/Y become constexpr (0 / -1)
- _InlineTexStats + the six flush-gate counters (the queue gate
if/else collapses to the plain condition; the nudge drops its
counter-guard and just sets the dirty bit — idempotent)
- _InlineTexWrap + the WrapDiag ring and every capture site in the
wrap-stepper hook (the minimal-feasible-shrink algorithm is
untouched — it always ran on locals)
- _InlineTexProbeFS (the pen<->anchor bridge verification probe)
- the SEH filter no longer records fault code/address (nothing read
them); the latch still disables the feature on a flush fault
- the Arg() Lua helper and <cstdio> (last users removed)
* feat(text): inline icons fade with their chat line
The one visible seam left in the region renderer: icon regions parent
to the CHAT FRAME (regions cannot parent regions), so they inherited
the frame's alpha but not the LINE's — a fading chat line's text
dimmed while its inline icons stayed opaque until the end-of-fade
hide.
RE (verified in the 1.12 binary): chat fading is engine-side in the
ScrollingMessageFrame's fader FUN_00788460 — gated on the SetFading
flag (smf+0x360; the 40-method SMF registry's SetFading 0x007939A0
writes it), it counts down each visible line's timeVisible then
fadeDuration ({rgba@+4, shown@+8, timeLeft@+0xC, fadeLeft@+0x10} in
the stride-0x10 line array at smf+0x3A4) and animates the LINE
FONTSTRING's color alpha byte through the fs SetColor (0x0077F750)
every frame, hiding the fs at zero. SetColor stores the dword at
(*(u32**)(fs+0xB8))[0] (count fs+0xB4; alpha = byte 3), and the
per-line setter FUN_00788af0 resets alpha to 0xFF on message reset —
so that byte IS the line's live fade state, whoever wrote it.
The mirror (InlineTexturePool): Maintain reads FsColorAlpha(fs) each
tick and, on change only, rewrites the shown regions' colors with the
markup tint's alpha modulated by the line's alpha (RGB preserved).
ApplyPlacement folds the live alpha in at placement time, so a line
placed mid-fade starts at the right opacity. Composition is exact by
construction: the fs's on-screen alpha is frameAlpha(+0xC8) ×
fsColorAlpha, and the regions share the same parent frame, so
mirroring the fs byte alone makes icon and text alpha identical.
Steady state costs one byte compare per icon-bearing fontstring per
tick; scroll-back/un-fade restores (the SMF resets the line color and
the mirror follows). Verified in-game: fade lockstep, reappear on
scroll.
* feat(text): line-height growth for tall inline icons
An inline icon taller than the font (a 32px TwitchEmotes emote in 15px
chat) used to overlap its neighbouring lines — the line box stayed
fontH-sized. Retail grows the line: 4.3.4's measure and wrap loops
export a max-texture-height out-param (FUN_00618b90 / FUN_00618e40
case 7) and the layout takes it.
1.12 equivalent, one cold co-hook: FUN_FONTSTRING_STRING_HEIGHT
(GetStringHeightInternal, cache fs+0x100) gains the tallest icon's
overflow past the font height (MaxIconOverflowPx — explicit |T heights
only; the :0 default IS the font height). Its three binary consumers
(verified via xrefs) split exactly right:
- FUN_00772A60, the anchor effective-height vmethod — chat line
fontstrings get only a SetWidth from the ScrollingMessageFrame
refresh, so their rect height resolves here -> the rect grows;
- FUN_00788750, the SMF display refresh — budgets vertical space and
anchors each line to the previous line's rect -> the stack spaces by
the grown height;
- FUN_0077D4D0, the multi-line editbox self-size — excluded by the
same editbox gate as the width hook (editboxes render raw markup).
Same rules as the width hook: shared InlineInterceptActive predicate,
px->anchor via the push factor (never fs+0x7C), the fs+0x100 cache is
never written (delta re-derived per call — idempotent). The backported
fontstring:GetStringHeight routes through the hooked VA and becomes
icon-inclusive automatically.
Draw side: tall icons CENTRE on the line like any other icon. The text
centres itself inside the grown rect, so the extra space appears half
above and half below — a centred icon fills exactly that, matching
retail. (A bottom-aligned first cut clipped the neighbouring line;
verified in-game against retail's centred, no-clip rendering.)
v1 limit (documented in-code): the delta is the whole text's max
overflow — exact when a message's tall icons share one wrapped line
(the emote case); tall icons on two different wrapped lines of one
message under-grow.
Verified in-game: 32px emotes between normal chat lines each take
their own vertical room, centred, no neighbour overlap.
* fix(text): full-height hyperlink hover for tall inline icons
With line-height growth (49934b0), a tall emote inside a |H...|h link
was only hoverable across its text-high middle band: the hyperlink hit
rect is registered at layout time (FUN_TEXT_LINK_RECT_ADD 0x005CD310,
the GXUFONTHYPERLINKINFO append — record {y,x,y,x} normalized + link
ptr/len pairs) with the TEXT band's y extent, fontH tall.
Consumer geometry (FUN_00788c00 -> FUN_007a3350 decompile + two in-game
experiments): the ScrollingMessageFrame rebuilds a hit-region frame per
record, anchored to the LINE FONTSTRING's top-left with the record's
band as offset/height. The band's y values are Y-UP (numeric max =
screen top — extending the max visibly grew the region into the line
above), and the band is TEXT-relative — but the grown rect's top sits
half the icon overflow above the text (the text centres in the grown
rect), pre-shifting the whole hit band up. Net: the unmodified band
already covered from the icon's top down to textBottom − overflow/2,
and the single correct fix is pushing the screen bottom DOWN by the
full overflow — decreasing the numeric MIN edge.
Co-hook on the append: when the |H...|h escape span contains a |T icon
taller than the line's font (the same MaxIconOverflowPx the
string-height hook grows the line by), decrease the band's min edge by
the overflow before the original stores it. All consumers of the
record (hover, click) inherit the expansion. Gated on the shared
InlineInterceptActive predicate so raw-rendered contexts stay literal.
Known v1 rough edge (commented in-code): a tall icon outside the link
but on the same line grows the line without this hook firing for that
link, leaving its band half-overflow high.
Verified in-game: a 32px emote link hits across its full height, no
bleed into neighbouring lines.
* docs(text): truth-pass on the inline-texture RE docs
InlineTextureEscapes.md and InlineTextureResidency.md described the
removed raw-quad renderer and a bring-up plan as if current. Bring them
in line with the shipped engine-region design.
InlineTextureEscapes.md:
- New "Current design (shipped)" section up front: region renderer, the
three fs-level measure hooks (width/height/wrap), the lazy-pen fix,
chat fade, tall-icon line growth + full-height hover, editbox
exclusion, the payload, and anti-spoof — each with its commit.
- Banner the quad "rendering primitive" section as REMOVED (bring-up
record; the address log for code deleted in 56c2670).
- Fix the DrawTexturedQuad / quad-flush references to region-queue
language; vertical centring is g_centerFrac (0.6) with the tall-icon
grown-rect note; the flip note becomes the region SetTexCoord
Y-first order.
- "Remaining/optional": diagnostics removed (only InlineTexEnable
left), measure/height/wrap DONE, animation is addon-side, the TGA
convert command is -compress none only.
- "Reality check": correct the prediction that we would reimplement the
emitter — the shipped design segment-delegates and co-hooks instead.
InlineTextureResidency.md: rewritten from a "not-yet-implemented plan"
into an accurate reference. States the region design, records the
CSimpleTexture entry points / layout the pool uses (VAs verified
against Offsets.h), and corrects the root cause honestly — the flicker
was the LAA pointer-bound truncation (dc61f77), NOT texture residency;
regions are kept for 4.3.4 parity and are resident by construction as a
bonus. Keeps the D3D "ruled out" notes as a do-not-re-investigate
record.
* fix(text): stop inline-icon Maintain from dereferencing stale fontstrings
A destroyed chat-line fontstring left a dangling key in the icon pool's
per-fontstring map. Its heap memory was reused as a string buffer, and
Maintain's weak LooksReadable() range check waved the reused pointer
through; reading the "parent" field (fs+0x9C) then yielded string bytes
(ASCII "-Rac"), which the engine's region attach (FUN_0076a750)
dereferenced at *(parent+0x1B4) -> ACCESS_VIOLATION (ERROR #132 at
0x0076A7CE).
Two compounding defects, both in Maintain:
- the stale-entry expiry was gated on shown > 0, so a scrolled-off line
(shown == 0) never expired and its dead key was re-dereferenced every
frame, waiting for its memory to be reused;
- LooksReadable is a bare VA-range test that a reused buffer passes.
Fix: verify a key is a LIVE fontstring by its object+0x00 vtable before
using it. The vtable is learned at paint time from fontstrings the engine
is actively drawing (QueuePlacements), so every fontstring class -- chat's
internal ScrollingMessageFrame lines, tooltip/CreateFontString lines,
addon fontstrings -- is recognized without hardcoding (one hardcoded value
filtered live chat icons out entirely). Maintain now iterates with erase:
a key whose memory no longer carries a learned fontstring vtable has its
regions hidden (our tex pointers stay valid, parented to the chat frame)
and the entry erased, so dead keys can neither accumulate nor be
dereferenced.
* fix(text): guard inline-icon pool hide loops against short region vector
CreateRegion can fail when the region pool is exhausted, breaking the
apply loop with fewer regions than `want`. The code still set
`np.shown = want`, so a later tick's freshness-expiry and fs-hidden hide
loops indexed np.regions[i] past regions.size() -- an out-of-bounds
std::vector access.
Clamp np.shown to min(want, regions.size()) so it never exceeds the
vector, and add the same i < regions.size() bound the eviction loop
already carries to the other two hide loops so all three self-guard.
* refactor(text): centralize inline-texture offsets and pointer probe
Enforce the single-source-of-truth offset rule on the inline-texture
files:
- Read the fontstring text pointer via Offsets::OFF_FONTSTRING_TEXT
instead of a raw `fs + 0xF0` in FlushLayout's ghost guard; the symbol
already existed and is used elsewhere in the same file.
- Add OFF_TEXT_NODE_JUSTIFY (0x54) to Offsets.h with a verification note
and use it for the two node-justify reads (DeriveK and the emitter
pre-shift) that previously hardcoded 0x54 in two places.
- Move the LAA-aware LooksReadable probe into a shared text/PtrProbe.h
(namespace Text) so InlineTexture.cpp and InlineTexturePool.cpp share
one definition instead of two copies plus a third raw-bounds copy in
LearnFontStringVtable. The 0xFFFF0000 bound now lives in exactly one
place -- this is the constant whose earlier 0x7FFF0000 form caused the
missing-chat-icon bug, so keeping the copies from drifting matters.
No behavior change; full build compiles and links.
* fix(currency): clamp GetCoinTextureString to the uint32 copper ceiling
An amount above INT_MAX gold copper (e.g. 1e15) made `gold =
(int)(amount / 10000)` overflow: the long long division was truncated to
its low 32 bits, so GetCoinTextureString(1e15) printed a garbage gold
count (1215752192). silver/copper were already bounded by the % math.
Vanilla money is a uint32 copper field, so clamp amount to 0xFFFFFFFF
copper (~429,496 gold) -- the most the game can represent -- which keeps
gold within int range for the "%d" GlobalString format. Can't widen the
type instead: the count is formatted through the retail-compatible "%d"
coin GlobalString, and passing a long long to %d is undefined.
* fix(text): SEH-guard the inline-icon Maintain tick; document region leak
#6 (SEH backstop): Maintain's liveness probe dereferences a fontstring
pointer that may have been freed (the documented IsLiveFontString
residual). The paint path already latches off on a fault via SafeFlush,
but Maintain ran bare under the render-root tick, so a fault there was an
uncaught client crash. Split the body into MaintainImpl (holds the C++
objects) and a thin Maintain() SEH wrapper that latches g_maintainDisabled
on fault -- mirroring the paint latch. Re-armed on /reload.
#7 (region leak): document why the stale-key eviction intentionally drops
np.regions without reclaiming the pooled CSimpleTextures. Any reclaim (a
free list or explicit destroy) would touch a region whose parent frame may
already be gone -- a use-after-free on the very path this liveness check
was added to stop crashing. The leak is bounded and near-zero in practice
(chat/tooltip fontstrings are reused, never evicted).
* fix(chat): stop raid-marker expansion from dropping the message tail
A token inflates ~28x ({rtN} -> ~85-byte |T markup), so a marker-dense
message could fill the 0x800 buffer and silently truncate everything after
it -- a DLL user would see a shorter chat line than a non-DLL user (a mild
content-hiding vector).
Reserve room for the literal tail before expanding a token: only iconify a
marker when the expansion plus the whole remaining input (worst case copied
1:1) still fits. Past that point later tokens stay literal {rtN}, so the
full message text is always preserved -- just with fewer icons.
* fix(text): gate eviction Hide on region liveness to avoid a UAF
The stale-key eviction Hid its regions unconditionally, assuming they
outlive the fontstring. They usually do (regions are parented to the
fontstring's parent FRAME, which persists as lines churn) -- but if the
fontstring became non-live because that parent frame was destroyed, the
frame freed the fontstring AND its child regions together. Hiding a region
pointer there wrote to freed/recycled memory: a use-after-free that could
crash.
Learn the pooled CSimpleTexture vtable in CreateRegion and gate each
eviction Hide on IsLiveRegion (the same vtable-liveness technique
IsLiveFontString already uses). A recycled region is skipped (it needs no
hiding -- it's already gone); a live one is still hidden so it can't ghost.
Factored the shared WoW-image-range check into InWowImage so the two Learn*
functions don't duplicate the constant.
1623 lines
84 KiB
C++
1623 lines
84 KiB
C++
// This file is part of ClassicAPI.
|
||
//
|
||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||
// of the GNU General Public License as published by the Free Software Foundation, either
|
||
// version 3 of the License, or (at your option) any later version.
|
||
//
|
||
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
|
||
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
|
||
// PURPOSE. See the GNU General Public License for more details.
|
||
//
|
||
// You should have received a copy of the GNU General Public License along with
|
||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||
|
||
// Inline texture escape (`|Tpath:height:width:...|t`) backport.
|
||
//
|
||
// Vanilla 1.12 has ZERO inline-texture support: the shared `|`-tokenizer
|
||
// (FUN_005c2810) has no `T`/`t` case, so `|T...|t` renders as literal text.
|
||
// This module teaches the text engine to render the icon inline.
|
||
//
|
||
// Two working pieces:
|
||
// 1. POSITIONING — co-hook the per-line glyph emitter (FUN_005ccbe0) and, for
|
||
// a line containing `|T…|t`, render the plain text runs by DELEGATING to the
|
||
// original emitter per segment (threading the pen through linkState[4]) while
|
||
// recording an icon at the pen between runs. This avoids reimplementing the
|
||
// emitter's intricate vertex math: the engine still lays out every glyph; we
|
||
// only track where each icon goes.
|
||
// 2. RENDERING — the 4.3.4 CSimpleEmbeddedTexture model, ported faithfully
|
||
// (the ONLY render path; a raw-GxU-quad mode existed during bring-up and
|
||
// was removed). A co-hook on CSimpleFontString::RebuildString
|
||
// (FUN_007724A0) maps each fresh text node to its OWNING FONTSTRING (1.12
|
||
// chat lines are real CSimpleFontStrings — the ScrollingMessageFrame's
|
||
// display refresh FUN_00788750 SetTexts/anchors/shows one per visible
|
||
// line). The paint-tail flush walks the icon records and queues each to
|
||
// `Text::InlineTexturePool`, which configures a pooled engine-managed
|
||
// CSimpleTexture ANCHORED TO THE OWNING FONTSTRING at the pen offset —
|
||
// exactly how 4.3.4's UpdateEmbeddedTextures anchors its embedded
|
||
// textures. The engine draws the region every frame (residency) and the
|
||
// anchor system moves it with its line on every scroll/shift (zero
|
||
// per-frame work, no render transforms, no mid-render mutation). See
|
||
// docs/InlineTextureResidency.md.
|
||
//
|
||
// Supports the full positional payload
|
||
// `|Tpath:height:width:offsetX:offsetY:texW:texH:left:right:top:bottom:r:g:b|t`
|
||
// (size, pen offset, sprite-sheet texcoord crop, and r:g:b vertex tint). MEASURE
|
||
// is corrected at the fs-level chokes: the tokenizer still reports an icon as
|
||
// ~zero to every measure/wrap loop (the token contract has no size fields), but
|
||
// a co-hook on the internal string-width getter (FUN_FONTSTRING_STRING_WIDTH)
|
||
// re-adds the same per-icon advances the emitter reserves — so GetStringWidth,
|
||
// the tooltip auto-size, and auto-width layout match the rendered width — a
|
||
// co-hook on the internal string-height getter (FUN_FONTSTRING_STRING_HEIGHT)
|
||
// adds the tallest icon's overflow past the font height — so a tall icon's
|
||
// LINE grows to fit it (chat stacking + auto-height rects; tall icons
|
||
// bottom-align at draw so the overflow points into the grown space) — and a
|
||
// co-hook on the shared wrap-stepper dispatcher (FUN_TEXT_WRAP_STEPPER)
|
||
// shrinks the wrap width by the line's icon advances so wrapped lines break at
|
||
// the visible edge instead of overflowing. Still icon-blind (documented,
|
||
// accepted): the substring measure (FUN_00772AE0) and hyperlink hit-testing.
|
||
// See docs/InlineTextureEscapes.md for the RE map.
|
||
|
||
#include "text/InlineTexture.h"
|
||
|
||
#include "Game.h"
|
||
#include "Offsets.h"
|
||
#include "text/InlineTexturePool.h"
|
||
#include "text/PtrProbe.h"
|
||
|
||
#include <windows.h>
|
||
|
||
#include <cmath>
|
||
#include <cstdint>
|
||
#include <cstdlib>
|
||
#include <string>
|
||
#include <unordered_map>
|
||
#include <vector>
|
||
|
||
namespace Text::InlineTexture {
|
||
|
||
namespace {
|
||
|
||
// LAA-aware pointer sanity probe: Text::LooksReadable (text/PtrProbe.h).
|
||
|
||
// --- inline-texture descriptor parse ---------------------------------------
|
||
|
||
// Parsed
|
||
// `|Tpath:height:width:offsetX:offsetY:texW:texH:left:right:top:bottom:r:g:b|t`
|
||
// payload. Trailing fields are optional; texcoords crop a sprite sheet (e.g. the
|
||
// raid-target icons) to one cell, and r:g:b (0-255) tint the icon.
|
||
struct IconDesc {
|
||
std::string path;
|
||
float height = 0.0f;
|
||
float width = 0.0f; // defaults to height when the width field is absent/0
|
||
float offsetX = 0.0f; // pen-relative pixel shift
|
||
float offsetY = 0.0f;
|
||
float u0 = 0.0f, v0 = 0.0f, u1 = 1.0f, v1 = 1.0f; // full texture by default
|
||
// Vertex colour (modulates the texture). Packed 0xAARRGGBB — the same order
|
||
// the engine builds for `|cAARRGGBB` text (verified in the tokenizer's colour
|
||
// path), so full white = no tint. Set from the optional r:g:b (0-255) fields.
|
||
uint32_t color = 0xFFFFFFFFu;
|
||
};
|
||
|
||
// Reads a numeric field starting at `s` (bounded by `end`), stopping at the next
|
||
// ':' or the end. Returns the parsed value; sets `next` past the field's
|
||
// terminating ':' (or to `end`). Tolerates leading spaces and decimals.
|
||
float ParseField(const char *s, const char *end, const char **next) {
|
||
char buf[32];
|
||
int n = 0;
|
||
const char *p = s;
|
||
while (p < end && *p != ':' && n < static_cast<int>(sizeof(buf) - 1)) {
|
||
buf[n++] = *p;
|
||
++p;
|
||
}
|
||
buf[n] = '\0';
|
||
// Skip to just past the delimiter for the caller's next field.
|
||
while (p < end && *p != ':')
|
||
++p;
|
||
if (p < end && *p == ':')
|
||
++p;
|
||
*next = p;
|
||
return static_cast<float>(atof(buf));
|
||
}
|
||
|
||
// Parses the payload between `|T` and `|t` (`payload`, length `len`) into `out`.
|
||
// Returns false if there's no path or no positive height (nothing to draw).
|
||
bool ParseIcon(const char *payload, size_t len, IconDesc &out) {
|
||
const char *end = payload + len;
|
||
const char *colon = payload;
|
||
while (colon < end && *colon != ':')
|
||
++colon;
|
||
if (colon == payload)
|
||
return false; // empty path
|
||
out.path.assign(payload, static_cast<size_t>(colon - payload));
|
||
|
||
if (colon >= end)
|
||
return false; // path with no height
|
||
|
||
// Parse up to 13 numeric fields after the path: height, width, offsetX,
|
||
// offsetY, texW, texH, left, right, top, bottom, r, g, b.
|
||
float f[13] = {0};
|
||
int nf = 0;
|
||
const char *p = colon + 1;
|
||
while (p < end && nf < 13) {
|
||
const char *nx = p;
|
||
f[nf++] = ParseField(p, end, &nx);
|
||
p = nx;
|
||
}
|
||
if (nf < 1)
|
||
return false; // need at least the height field
|
||
// height/width of 0 means "auto" — resolved to the line's font height at emit
|
||
// time (retail's `:0:0` convention, e.g. GetCoinTextureString coins).
|
||
out.height = f[0];
|
||
out.width = (nf >= 2 && f[1] > 0.0f) ? f[1] : out.height;
|
||
out.offsetX = (nf >= 3) ? f[2] : 0.0f;
|
||
out.offsetY = (nf >= 4) ? f[3] : 0.0f;
|
||
// texW=f[4] texH=f[5] left=f[6] right=f[7] top=f[8] bottom=f[9] -> normalized
|
||
// texcoords cropping the sheet to one cell.
|
||
if (nf >= 10 && f[4] > 0.0f && f[5] > 0.0f) {
|
||
out.u0 = f[6] / f[4];
|
||
out.u1 = f[7] / f[4];
|
||
out.v0 = f[8] / f[5];
|
||
out.v1 = f[9] / f[5];
|
||
}
|
||
// r=f[10] g=f[11] b=f[12] (0-255) -> vertex tint. All three required (they're
|
||
// the last positional fields); clamped to a byte and packed 0xFFrrggbb.
|
||
if (nf >= 13) {
|
||
auto clampByte = [](float v) -> uint32_t {
|
||
if (v < 0.0f)
|
||
v = 0.0f;
|
||
if (v > 255.0f)
|
||
v = 255.0f;
|
||
return static_cast<uint32_t>(v + 0.5f);
|
||
};
|
||
out.color = 0xFF000000u | (clampByte(f[10]) << 16) | (clampByte(f[11]) << 8) |
|
||
clampByte(f[12]);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// --- per-node recorded icons -----------------------------------------------
|
||
|
||
// One icon to draw, in the render node's node-local coordinate space (the same
|
||
// space glyph verts live in — the paint pass translates it by the node origin).
|
||
struct IconRecord {
|
||
std::string path; // texture path
|
||
float x; // node-local pen x at the icon
|
||
float y; // node-local pen reference (penXYZ[1]) — near the text top
|
||
float fontH; // font pixel height of the line, for vertical centering
|
||
float w;
|
||
float h;
|
||
float offsetX, offsetY; // pen-relative pixel shift
|
||
float u0, v0, u1, v1; // texture crop
|
||
uint32_t color; // vertex tint (0xAARRGGBB; white = untinted)
|
||
};
|
||
|
||
// Icons keyed by render node. Stale-record safety is structural, not
|
||
// versioned: the node-free co-hook (below) erases a node's records the moment
|
||
// its address can be reused, and the emitter's firstLine erase resets them on
|
||
// every rebuild. (An explicit per-build version check was tried and REJECTED —
|
||
// the builder runs every paint but only emits when dirty, so a version
|
||
// mismatch on a clean paint erased live records: the all-icons-gone
|
||
// regression.)
|
||
std::unordered_map<void *, std::vector<IconRecord>> g_nodeIcons;
|
||
|
||
// node → owning CSimpleFontString, recorded by the RebuildString co-hook (the
|
||
// 4.3.4 ownership model — 1.12 chat lines ARE fontstrings). Consulted by the
|
||
// flush to anchor icon regions to their line. Stale fs pointers are guarded by
|
||
// LooksReadable at use (chat/bubble fontstrings are pooled and long-lived);
|
||
// the map clears on /reload.
|
||
std::unordered_map<void *, void *> g_nodeOwner;
|
||
|
||
// Cached pen-units-per-anchor-unit scale (K). Derived per flush from any icon
|
||
// node whose fontstring rect is resolved: the node origin is the fontstring's
|
||
// justification anchor point mapped by K (verified empirically: two probe
|
||
// fontstrings gave origin = rectJustifyRef × K with K ≈ 1470, both axes, no
|
||
// offset). 0 until first derivation → region placement waits for it.
|
||
float g_penPerAnchor = 0.0f;
|
||
|
||
// Region calibration, PEN units added to the region's position. x needs no
|
||
// constant — the +3 once calibrated here turned out to be the missing lead pad,
|
||
// now applied at draw. y keeps a 1px residual (the pen→anchor map's one true
|
||
// constant). Calibrated in-game during bring-up; fixed now.
|
||
constexpr float g_regionCalX = 0.0f;
|
||
constexpr float g_regionCalY = -1.0f;
|
||
|
||
// Draw-builder co-hook: exact build boundaries for first-line detection. The
|
||
// builder runs once per node build and calls the emitter per wrapped line;
|
||
// stamping the node + zeroing the emit counter here lets the emitter know
|
||
// "this is the first line of a fresh build" with certainty. (The previous
|
||
// heuristic — comparing the emit text pointer against node+text — failed on
|
||
// pfUI-processed lines and caused both the erased-live-records bug and the
|
||
// ghost-icons-on-reused-nodes bug.)
|
||
void *g_buildNode = nullptr;
|
||
uint32_t g_buildEmitSeq = 0;
|
||
|
||
using DrawBuilder_t = void(__fastcall *)(void *node);
|
||
DrawBuilder_t g_builderOriginal = nullptr;
|
||
|
||
void __fastcall DrawBuilder_h(void *node) {
|
||
g_buildNode = node;
|
||
g_buildEmitSeq = 0;
|
||
g_builderOriginal(node);
|
||
g_buildNode = nullptr;
|
||
}
|
||
|
||
static const Game::HookAutoRegister _builderHook{Offsets::FUN_TEXT_DRAW_BUILDER,
|
||
reinterpret_cast<void *>(&DrawBuilder_h),
|
||
reinterpret_cast<void **>(&g_builderOriginal)};
|
||
|
||
// Node-free co-hook: THE lifetime fix. Every gxu text node dies through
|
||
// FUN_TEXT_NODE_FREE (single engine call site) before its address goes back to
|
||
// the free list for reuse. Erasing all per-node state here makes it a hard
|
||
// invariant that anything in our maps refers to a LIVE node — the entire class
|
||
// of stale-record/stale-owner bugs (inherited ghost icons on recycled
|
||
// nameplates, orphaned records inflating dropNoFs, reload leftovers) becomes
|
||
// structurally impossible rather than heuristically guarded.
|
||
using NodeFree_t = void(__fastcall *)(void *node);
|
||
NodeFree_t g_nodeFreeOriginal = nullptr;
|
||
|
||
void __fastcall NodeFree_h(void *node) {
|
||
if (node != nullptr) {
|
||
g_nodeIcons.erase(node);
|
||
g_nodeOwner.erase(node);
|
||
}
|
||
g_nodeFreeOriginal(node);
|
||
}
|
||
|
||
static const Game::HookAutoRegister _nodeFreeHook{Offsets::FUN_TEXT_NODE_FREE,
|
||
reinterpret_cast<void *>(&NodeFree_h),
|
||
reinterpret_cast<void **>(&g_nodeFreeOriginal)};
|
||
|
||
// RebuildString co-hook: after the engine (re)builds a fontstring's text block,
|
||
// record node → fontstring. `fs+0xF8` is an HTEXTBLOCK handle; the node lives
|
||
// at handle+8.
|
||
using RebuildString_t = void(__fastcall *)(void *fs);
|
||
RebuildString_t g_rebuildOriginal = nullptr;
|
||
|
||
void __fastcall RebuildString_h(void *fs) {
|
||
g_rebuildOriginal(fs);
|
||
if (!LooksReadable(fs))
|
||
return;
|
||
void *block = *reinterpret_cast<void **>(reinterpret_cast<uint8_t *>(fs) +
|
||
Offsets::OFF_FONTSTRING_TEXT_BLOCK);
|
||
if (!LooksReadable(block))
|
||
return;
|
||
void *node = *reinterpret_cast<void **>(reinterpret_cast<uint8_t *>(block) +
|
||
Offsets::OFF_TEXTBLOCK_NODE);
|
||
if (LooksReadable(node))
|
||
g_nodeOwner[node] = fs;
|
||
}
|
||
|
||
static const Game::HookAutoRegister _rebuildHook{Offsets::FUN_FONTSTRING_REBUILD_STRING,
|
||
reinterpret_cast<void *>(&RebuildString_h),
|
||
reinterpret_cast<void **>(&g_rebuildOriginal)};
|
||
|
||
// Derives K for THIS node from its own fontstring: K = originX / justifyRefX
|
||
// (node+0x54: 0 = left, 1 = centre, 2 = right — the draw builder's encoding).
|
||
// K is PER-FONTSTRING, not global: pen space is scaled by the fs's effective
|
||
// scale chain, so a pfUI money display at a custom frame scale has a different
|
||
// K than chat (the deterministic 0.53× half-size icons were exactly this —
|
||
// a global chat-derived K applied to a differently-scaled fs). The node's own
|
||
// derivation is preferred; the global cache is a fallback for nodes whose
|
||
// justify ref sits too close to 0 to divide by (guarded), updated only within
|
||
// ±10% (a mid-layout stale-rect read must not poison it).
|
||
float DeriveK(const uint8_t *n, const uint8_t *f, float originX) {
|
||
if (LooksReadable(f)) {
|
||
const float left = *reinterpret_cast<const float *>(f + Offsets::OFF_REGION_RECT + 4);
|
||
const float right = *reinterpret_cast<const float *>(f + Offsets::OFF_REGION_RECT + 12);
|
||
const float insetX = *reinterpret_cast<const float *>(f + Offsets::OFF_FONTSTRING_INSET_X);
|
||
if (left < right && std::fabs(insetX) < 1e-6f) {
|
||
const int justify =
|
||
*reinterpret_cast<const int *>(n + Offsets::OFF_TEXT_NODE_JUSTIFY);
|
||
const float ref =
|
||
(justify == 1) ? (left + right) * 0.5f : ((justify == 2) ? right : left);
|
||
if (std::fabs(ref) > 0.02f && originX > 1.0f) {
|
||
const float k = originX / ref;
|
||
if (k > 1.0f) {
|
||
if (g_penPerAnchor <= 1.0f ||
|
||
(k > g_penPerAnchor * 0.9f && k < g_penPerAnchor * 1.1f))
|
||
g_penPerAnchor = k;
|
||
return k; // this node's own K — always right for its fs
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return g_penPerAnchor;
|
||
}
|
||
|
||
// Runtime toggle (default ON — the feature is proven; `_classicapi_InlineTexEnable(false)`
|
||
// still turns it off, and the SEH latch trips it on a flush fault). When off, the
|
||
// emitter/tokenizer co-hooks fast-path straight to the originals.
|
||
bool g_inlineEnabled = true;
|
||
|
||
// True if `t` points into [buf, buf+strlen(buf)] — a TIGHT, exact extent (bounded
|
||
// strlen, cap 0x4000). The editbox's buffers are distinct heap allocations, so an
|
||
// in-range pointer is unambiguously that buffer's, with no false-match cap. Guards
|
||
// every deref: a null/unreadable buffer or below-range pointer just returns false.
|
||
bool PtrInBuffer(const uint8_t *t, const uint8_t *buf) {
|
||
if (!LooksReadable(buf) || t < buf)
|
||
return false;
|
||
size_t n = 0;
|
||
while (n < 0x4000u && buf[n] != '\0')
|
||
++n;
|
||
return t <= buf + n;
|
||
}
|
||
|
||
// The focused editbox's INPUT buffer ([fe+0x32C]/[fe+0x334]), or nullptr. This is
|
||
// the buffer the caret/width MEASURE path reads IN PLACE (FUN_0077da80 →
|
||
// FUN_00772ae0 → … → FUN_005c6940 loops the tokenizer), so the measure tokenizer's
|
||
// `text` points directly into it.
|
||
const uint8_t *FocusedEditboxInput() {
|
||
const void *fe = *reinterpret_cast<const void *const *>(Offsets::VAR_FOCUSED_EDITBOX);
|
||
if (!LooksReadable(fe))
|
||
return nullptr;
|
||
auto *f = reinterpret_cast<const uint8_t *>(fe);
|
||
const uint8_t sel = f[Offsets::OFF_EDITBOX_BUFFER_SELECT];
|
||
const uint8_t *inBuf = *reinterpret_cast<const uint8_t *const *>(
|
||
f + ((sel & 8u) ? Offsets::OFF_EDITBOX_BUFFER_MASKED : Offsets::OFF_EDITBOX_BUFFER));
|
||
return LooksReadable(inBuf) ? inBuf : nullptr;
|
||
}
|
||
|
||
// True if `text` points into the focused editbox's input buffer — the MEASURE path
|
||
// (caret/GetStringWidth), which must measure RAW `|T…|t` so the caret stays aligned
|
||
// with the raw glyphs. Per-editbox, so a display FontString measured while an
|
||
// editbox is focused still measures icons (an improvement over the old global).
|
||
// Cheap: one pointer-range check on pipe-leading tokens, null-short-circuited.
|
||
bool TextInFocusedEditbox(const void *text) {
|
||
return PtrInBuffer(reinterpret_cast<const uint8_t *>(text), FocusedEditboxInput());
|
||
}
|
||
|
||
// True if `text`'s content equals the focused editbox's input text. The editbox
|
||
// RENDERS its content through a TRANSIENT copy — same bytes, different allocation,
|
||
// no pointer link to the editbox (verified in-game: the render buffer matched the
|
||
// input buffer's string exactly but sat in an unrelated heap block). The emitter
|
||
// gets that whole copy as one line, so a content compare identifies it. Bounded to
|
||
// 0x1000 bytes; only reached on a pipe-leading emit line while an editbox is focused.
|
||
bool EmitLineIsFocusedEditbox(const uint8_t *text) {
|
||
const uint8_t *inBuf = FocusedEditboxInput();
|
||
if (inBuf == nullptr || !LooksReadable(text))
|
||
return false;
|
||
// Compare render vs input with `||` collapsed to a single `|` on BOTH sides.
|
||
// Different editboxes handle typed escapes differently: some render the text
|
||
// as-is (render == input buffer, both single-pipe), some neutralize each `|`
|
||
// to `||` in the render while the buffer stays single-pipe. Collapsing pairs
|
||
// on both sides makes the compare robust to either, so the focused input's OWN
|
||
// line is recognized (and shown raw) regardless of doubling — no flag gate
|
||
// (which mis-fires on pfUI's editable chat display) needed. A chat history
|
||
// line's content differs, so it never matches and keeps its icons.
|
||
size_t r = 0, in = 0;
|
||
for (int guard = 0; guard < 0x1000; ++guard) {
|
||
uint8_t a = text[r];
|
||
if (a == '|' && text[r + 1] == '|') {
|
||
r += 2; // collapse `||` -> `|`
|
||
} else {
|
||
r += 1;
|
||
}
|
||
uint8_t b = inBuf[in];
|
||
if (b == '|' && inBuf[in + 1] == '|') {
|
||
in += 2; // collapse `||` -> `|`
|
||
} else {
|
||
in += 1;
|
||
}
|
||
if (a != b)
|
||
return false;
|
||
if (a == '\0')
|
||
return true; // both reached the terminator together
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// Text range currently being delegated to the ORIGINAL emitter from a suppressed
|
||
// editbox render. The re-entrant tokenizer stands down across this whole span (not
|
||
// just the first token) so the delegated raw layout doesn't eat `|T` as a
|
||
// zero-width token. Single-threaded engine → a plain pair is safe.
|
||
const uint8_t *g_reentryLo = nullptr;
|
||
const uint8_t *g_reentryHi = nullptr;
|
||
inline bool TextInReentry(const uint8_t *t) {
|
||
return g_reentryLo != nullptr && t >= g_reentryLo && t < g_reentryHi;
|
||
}
|
||
|
||
// The tokenizer's stand-down environment, factored into ONE predicate so measure
|
||
// and render can never disagree: true when inline-texture interception is ACTIVE
|
||
// for `text` (spans are eaten as zero-width tokens and icons render). `editable`
|
||
// is the caller's editbox bit at its own representation level — gxu flags bit
|
||
// 0x40 at the tokenizer, fs+0x120 bit 0x1000 at the string-width co-hook
|
||
// (FUN_0044D670 translates the latter into the former, so both call shapes
|
||
// evaluate the same engine bit). The tokenizer's `text[0] == '|'` position check
|
||
// stays at its call site — it's about where the tokenizer stands in the text,
|
||
// not about whether the feature is active.
|
||
bool InlineInterceptActive(const uint8_t *text, bool editable) {
|
||
return g_inlineEnabled && !editable && text != nullptr && !TextInReentry(text) &&
|
||
!TextInFocusedEditbox(text);
|
||
}
|
||
|
||
// A text node's flags (`[node+0x5c]`) bit 6 (0x40) distinguishes editable input
|
||
// text (set on the macro editbox: flags 0x4D) from display text (chat 0x20D,
|
||
// FontStrings 0x0D — bit 6 clear). It's a per-node property the emitter and
|
||
// tokenizer don't otherwise use, and it rides in the tokenizer's flags argument,
|
||
// so we can suppress inline rendering per node — covering editboxes the focus
|
||
// global misses (multi-line editors build once, un-focused). This mirrors 4.3.4's
|
||
// per-render texture-disable flag, adapted to 1.12's layout.
|
||
inline bool NodeEditable(const void *node) {
|
||
return (*reinterpret_cast<const uint32_t *>(reinterpret_cast<const uint8_t *>(node) +
|
||
Offsets::OFF_TEXT_NODE_FLAGS) &
|
||
0x40u) != 0;
|
||
}
|
||
|
||
// Geometry constants, calibrated in-game during bring-up (via a since-removed
|
||
// live-tune surface) and now fixed.
|
||
constexpr float g_vBias = 0.0f; // extra node-local Y added to the icon centre
|
||
constexpr float g_sizeScale = 1.0f; // multiplies the parsed icon size
|
||
// Icon vertical centre = penY + fontHeight * centerFrac. penY sits near the text
|
||
// top; ~0.6 centres the icon on the line across the fonts we render into (chat +
|
||
// pfUI's bubble).
|
||
constexpr float g_centerFrac = 0.6f;
|
||
// Horizontal breathing room around every inline icon, as a fraction of the LINE'S
|
||
// FONT HEIGHT — a text-relative gap, like the space between words. It is NOT a
|
||
// fraction of the icon's own width: that made the gap scale with icon size, so a
|
||
// small icon (e.g. a font-height coin next to a digit) jammed its neighbour while a
|
||
// huge icon floated away from it. Keying off the font height makes the gap constant
|
||
// for a given text size regardless of how big the icon is drawn — and a font-height
|
||
// icon is unchanged, so marks / default coins / default emotes keep their spacing.
|
||
// Applied FULL on the lead (left) and HALF on the trail (right): the preceding
|
||
// glyph's right-side bearing extends past the reported pen and eats into the left
|
||
// gap visually, so a lead-heavy split makes the left and right gaps LOOK even.
|
||
// Without any pad an icon crowds the char before it. 0.18 ≈ 2.7px lead / 1.35px
|
||
// trail at a 15px font.
|
||
constexpr float g_iconPadFrac = 0.18f;
|
||
|
||
// The 1.12 FontString text sanitizer DOUBLES any pipe that doesn't begin a
|
||
// recognized escape (so it renders as a literal `|`). Since 1.12 doesn't know
|
||
// `|T`, a caller's `|Tpath:h|t` arrives at the emitter as `||Tpath:h||t`
|
||
// (verified in-game: emitter text length +2, pipes doubled). So we accept both the
|
||
// doubled form (the real-world case) and a clean `|T` (should one ever reach us
|
||
// undoubled, e.g. after a future sanitizer hook). A literal user `||T…||t` is
|
||
// effectively nonexistent, and ordinary doubled pipes (`|| `) never match because
|
||
// the char after must be `T`.
|
||
|
||
// If an inline-texture escape starts at text[i], returns its opening-marker
|
||
// length: 3 for the doubled `||T`, 2 for a clean `|T`; 0 otherwise. The doubled
|
||
// form is checked first so the leading `|` of `||T` wins over reading the 2nd `|`
|
||
// as a clean `|T`.
|
||
int IconStartLen(const uint8_t *text, int len, int i) {
|
||
if (i + 2 < len && text[i] == '|' && text[i + 1] == '|' && text[i + 2] == 'T')
|
||
return 3;
|
||
if (i + 1 < len && text[i] == '|' && text[i + 1] == 'T')
|
||
return 2;
|
||
return 0;
|
||
}
|
||
|
||
// True if [text,text+len) contains any inline-texture escape.
|
||
bool HasInlineTexture(const uint8_t *text, int len) {
|
||
for (int i = 0; i + 1 < len; ++i)
|
||
if (IconStartLen(text, len, i))
|
||
return true;
|
||
return false;
|
||
}
|
||
|
||
// Finds the matching close (`||t` for the doubled form, `|t` for clean) at or
|
||
// after `from`. Returns its offset and sets *closeLen, or npos.
|
||
size_t FindIconClose(const uint8_t *text, int len, size_t from, bool doubled, int *closeLen) {
|
||
const size_t n = static_cast<size_t>(len);
|
||
if (doubled) {
|
||
for (size_t i = from; i + 2 < n; ++i)
|
||
if (text[i] == '|' && text[i + 1] == '|' && text[i + 2] == 't') {
|
||
*closeLen = 3;
|
||
return i;
|
||
}
|
||
} else {
|
||
for (size_t i = from; i + 1 < n; ++i)
|
||
if (text[i] == '|' && text[i + 1] == 't') {
|
||
*closeLen = 2;
|
||
return i;
|
||
}
|
||
}
|
||
return static_cast<size_t>(-1);
|
||
}
|
||
|
||
// Length of an inline-texture escape starting at `text[0]` (through its close
|
||
// marker), or 0 if none. Null-terminated variant for the tokenizer hook, which
|
||
// gets no length. Bounded so a malformed/unterminated span can't run away.
|
||
int InlineSpanLen(const uint8_t *text) {
|
||
int mlen;
|
||
if (text[0] == '|' && text[1] == '|' && text[2] == 'T')
|
||
mlen = 3; // doubled ||T
|
||
else if (text[0] == '|' && text[1] == 'T')
|
||
mlen = 2; // clean |T
|
||
else
|
||
return 0;
|
||
const bool doubled = (mlen == 3);
|
||
for (int i = mlen; i < 2048 && text[i] != '\0'; ++i) {
|
||
if (doubled) {
|
||
if (text[i] == '|' && text[i + 1] == '|' && text[i + 2] == 't')
|
||
return i + 3;
|
||
} else {
|
||
if (text[i] == '|' && text[i + 1] == 't')
|
||
return i + 2;
|
||
}
|
||
}
|
||
return 0; // unterminated → let the engine treat it as ordinary text
|
||
}
|
||
|
||
// THE per-icon pen advance the emitter reserves: icon width + full lead pad +
|
||
// half trail pad + any positive offsetX (a negative offsetX — deliberate
|
||
// leftward overlap — doesn't shrink the advance). Each pad is
|
||
// `fontHPen * g_iconPadFrac` — a font-relative gap, NOT icon-width-relative (see
|
||
// g_iconPadFrac). Single source shared by the emitter's icon loop, its
|
||
// centre/right-justify pre-shift, and the string-width co-hook — the three MUST
|
||
// agree or measured and rendered width drift. `fontHPen` resolves the retail `:0`
|
||
// auto-size (icon dims default to the line's font height); pen units in, out.
|
||
float IconAdvancePen(const IconDesc &d, float fontHPen) {
|
||
const float baseH = (d.height > 0.0f) ? d.height : fontHPen;
|
||
const float baseW = (d.width > 0.0f) ? d.width : baseH;
|
||
const float w = baseW * g_sizeScale;
|
||
const float offX = d.offsetX * g_sizeScale;
|
||
return w + 1.5f * (fontHPen * g_iconPadFrac) + (offX > 0.0f ? offX : 0.0f);
|
||
}
|
||
|
||
// Sum of IconAdvancePen over every well-formed `|T…|t` (or sanitizer-doubled
|
||
// `||T…||t`) span in [text, text+len). Malformed/unterminated spans contribute
|
||
// nothing — mirroring the emitter, which renders them as plain text.
|
||
float SumIconAdvances(const uint8_t *text, int len, float fontHPen) {
|
||
float sum = 0.0f;
|
||
int i = 0;
|
||
while (i < len) {
|
||
const int ml = IconStartLen(text, len, i);
|
||
if (ml == 0) {
|
||
// Skip an escaped pipe as a pair so its 2nd `|` isn't re-read as a
|
||
// clean `|T` next iteration (same walk the emitter does).
|
||
if (text[i] == '|' && i + 1 < len && text[i + 1] == '|')
|
||
i += 2;
|
||
else
|
||
++i;
|
||
continue;
|
||
}
|
||
int cl = 0;
|
||
const size_t ce = FindIconClose(text, len, static_cast<size_t>(i) + ml, ml == 3, &cl);
|
||
if (ce == static_cast<size_t>(-1))
|
||
break; // unterminated → the rest is plain text
|
||
IconDesc d;
|
||
if (ParseIcon(reinterpret_cast<const char *>(text) + i + ml,
|
||
ce - (static_cast<size_t>(i) + ml), d))
|
||
sum += IconAdvancePen(d, fontHPen);
|
||
i = static_cast<int>(ce) + cl;
|
||
}
|
||
return sum;
|
||
}
|
||
|
||
// The tallest icon's VERTICAL OVERFLOW past the font height, in px, over every
|
||
// well-formed span in [text, text+len) — 0 when every icon fits the line.
|
||
// Only explicit `|T…:H|t` heights can overflow (the `:0` default IS the font
|
||
// height). Drives the line-height growth: the string-height co-hook adds this
|
||
// so a tall icon's line takes real vertical room (the 4.3.4 model, whose wrap
|
||
// and measure loops export a max-texture-height for exactly this), and the
|
||
// draw bottom-aligns tall icons so the overflow points INTO the grown space.
|
||
float MaxIconOverflowPx(const uint8_t *text, int len, float fontHPx) {
|
||
float maxH = 0.0f;
|
||
int i = 0;
|
||
while (i < len) {
|
||
const int ml = IconStartLen(text, len, i);
|
||
if (ml == 0) {
|
||
if (text[i] == '|' && i + 1 < len && text[i + 1] == '|')
|
||
i += 2;
|
||
else
|
||
++i;
|
||
continue;
|
||
}
|
||
int cl = 0;
|
||
const size_t ce = FindIconClose(text, len, static_cast<size_t>(i) + ml, ml == 3, &cl);
|
||
if (ce == static_cast<size_t>(-1))
|
||
break;
|
||
IconDesc d;
|
||
if (ParseIcon(reinterpret_cast<const char *>(text) + i + ml,
|
||
ce - (static_cast<size_t>(i) + ml), d)) {
|
||
const float h = ((d.height > 0.0f) ? d.height : fontHPx) * g_sizeScale;
|
||
if (h > maxH)
|
||
maxH = h;
|
||
}
|
||
i = static_cast<int>(ce) + cl;
|
||
}
|
||
return (maxH > fontHPx) ? (maxH - fontHPx) : 0.0f;
|
||
}
|
||
|
||
// --- tokenizer co-hook (measure/wrap correction) ---------------------------
|
||
|
||
// FUN_005c2810 — the shared `|`-escape tokenizer. Returns a token-type code,
|
||
// writes bytes-consumed to *bytesConsumed and the payload char to *payloadOut.
|
||
using Tokenizer_t = uint32_t(__fastcall *)(uint8_t *text, int *bytesConsumed, uint32_t *colorOut,
|
||
uint32_t flags, uint32_t *payloadOut);
|
||
Tokenizer_t g_tokenizerOriginal = nullptr;
|
||
|
||
uint32_t __fastcall Tokenizer_h(uint8_t *text, int *bytesConsumed, uint32_t *colorOut,
|
||
uint32_t flags, uint32_t *payloadOut) {
|
||
// Intervene at a pipe when enabled, not manually suppressed, flags bit 0x40
|
||
// (EDITABLE) clear, and the text is NOT the focused editbox's own text.
|
||
//
|
||
// Bit 0x40 (EDITABLE, set on the macro editor 0x4D) means "leave `|T` as
|
||
// literal" — it keeps the macro editor's measure literal so its caret stays
|
||
// aligned with the raw glyphs the emitter draws for it. Chat DISPLAY is
|
||
// editable=0 (flags 0x205, ICON-NODE probe), so this does NOT touch it — its
|
||
// icons still measure ~zero. Single-line inputs (chat / name box) lack bit 6
|
||
// and are handled by the two focused-input signals:
|
||
// • MEASURE (caret/GetStringWidth loops this tokenizer over the input buffer
|
||
// in place) → TextInFocusedEditbox: `text` points into that buffer.
|
||
// • Re-entrant RENDER (the suppressed emitter delegates the raw line to the
|
||
// original, which re-enters here) → TextInReentry: `text` is inside the
|
||
// line span the emitter bracketed. Without it the span is eaten as a
|
||
// zero-width token and the editbox draws BLANK.
|
||
if (text != nullptr && text[0] == '|' &&
|
||
InlineInterceptActive(text, (flags & 0x40u) != 0)) {
|
||
const int span = InlineSpanLen(text);
|
||
if (span > 0) {
|
||
// Consume the whole escape as one glyph-type token with a payload that
|
||
// resolves to no glyph — so every measure/wrap caller advances past the
|
||
// path text and counts it as near-zero width instead of ~40 literal
|
||
// characters. The emitter detects icons itself and is unaffected (it
|
||
// only ever delegates plain, `|T`-free segments).
|
||
if (bytesConsumed)
|
||
*bytesConsumed = span;
|
||
if (payloadOut)
|
||
*payloadOut = 0;
|
||
return 6; // ordinary-glyph token type
|
||
}
|
||
}
|
||
return g_tokenizerOriginal(text, bytesConsumed, colorOut, flags, payloadOut);
|
||
}
|
||
|
||
static const Game::HookAutoRegister _tokenizerHook{Offsets::FUN_TEXT_TOKENIZER,
|
||
reinterpret_cast<void *>(&Tokenizer_h),
|
||
reinterpret_cast<void **>(&g_tokenizerOriginal)};
|
||
|
||
// --- string-width co-hook (measure-width icon fix) --------------------------
|
||
//
|
||
// FUN_FONTSTRING_STRING_WIDTH = CSimpleFontString::GetStringWidthInternal (see
|
||
// Offsets.h for the full derivation). The tokenizer hook above makes every
|
||
// measure path count a `|T` span as ~zero while the emitter reserves the real
|
||
// advance — so GetStringWidth, the GameTooltip auto-size, and auto-width layout
|
||
// undercount by the icons' widths. Fix at the single fs-level choke: call the
|
||
// original, then, when the tokenizer WOULD have eaten the spans (the shared
|
||
// InlineInterceptActive predicate) and the fs isn't an editbox, add the same
|
||
// per-icon advances the emitter reserves (the shared IconAdvancePen math).
|
||
//
|
||
// UNITS: escape sizes ("|T…:16|t") are UI pixels; the internal getter returns
|
||
// ANCHOR units. Convert px→anchor with the same global factor the Script push
|
||
// chain uses: K = [VAR_UI_COORD_SCALE_DIV] × 1024 / [VAR_UI_COORD_SCALE_MUL]
|
||
// (anchor→px), i.e. sum_px / K. Do NOT divide by fs+0x7C — that's the layout
|
||
// UI SCALE (~0.68-1.0), and the original's own `out / fs+0x7C` applies to a
|
||
// value FUN_0044D670 already ran through the FUN_0041AD80 gxu→internal
|
||
// converter, not to raw pixels (a /0x7C here inflated a 16px icon to +44k px
|
||
// on first flight). The `:0` auto-size default gets fontH in px as
|
||
// internal × K, which also tracks a scaled fs correctly.
|
||
//
|
||
// Idempotence: the original may serve the cached fs+0xFC — the icon sum is
|
||
// re-derived and re-added on EVERY call, and the cache is NEVER written.
|
||
//
|
||
// Residuals (documented in docs/InlineTextureEscapes.md): the measure loop ends
|
||
// on the last glyph's INK width rather than its advance, so a trailing icon
|
||
// leaves a ~≤1px artifact; wrap-break (FUN_00772B60), substring measure
|
||
// (FUN_00772AE0), and hyperlink hit-test stay icon-blind. The focused chat
|
||
// editbox's own display fontstring (editable bit CLEAR — only multi-line
|
||
// editors carry it) can reach this through the caret positioner's line-boundary
|
||
// branch with a content-suppressed raw render; that branch is multi-line-only
|
||
// in practice, so no content compare is spent here.
|
||
using StringWidthInternal_t = float(__fastcall *)(void *fs);
|
||
// FUN_FONTSTRING_FONT_HEIGHT is __thiscall(fs, mode-on-stack) — dummy-EDX
|
||
// __fastcall matches the register/stack layout (established pattern).
|
||
using FsFontHeight_t = float(__fastcall *)(void *fs, void *edx, int mode);
|
||
StringWidthInternal_t g_stringWidthOriginal = nullptr;
|
||
|
||
float __fastcall StringWidth_h(void *fs) {
|
||
const float base = g_stringWidthOriginal(fs);
|
||
if (!LooksReadable(fs))
|
||
return base;
|
||
const auto *f = reinterpret_cast<const uint8_t *>(fs);
|
||
// fs+0x120 bit 0x1000 → gxu editbox bit 0x40: an editbox measures the raw
|
||
// markup it renders, so its width must stay unadjusted (caret alignment).
|
||
const bool editable =
|
||
(*reinterpret_cast<const uint32_t *>(f + Offsets::OFF_FONTSTRING_MEASURE_FLAGS) &
|
||
0x1000u) != 0;
|
||
const uint8_t *text =
|
||
*reinterpret_cast<const uint8_t *const *>(f + Offsets::OFF_FONTSTRING_TEXT);
|
||
if (!LooksReadable(text) || !InlineInterceptActive(text, editable))
|
||
return base;
|
||
int len = 0;
|
||
while (len < 0x4000 && text[len] != '\0')
|
||
++len;
|
||
if (!HasInlineTexture(text, len))
|
||
return base;
|
||
const float mul = *reinterpret_cast<const float *>(Offsets::VAR_UI_COORD_SCALE_MUL);
|
||
const float div = *reinterpret_cast<const float *>(Offsets::VAR_UI_COORD_SCALE_DIV);
|
||
if (!(mul > 0.0f) || !(div > 0.0f))
|
||
return base;
|
||
const float anchorToPx = div * Offsets::UI_COORD_SCALE_UNIT / mul; // ≈1468 (the push K)
|
||
// Font height in UI pixels for the `:0` auto-size default (internal × K).
|
||
const float fontHPx =
|
||
reinterpret_cast<FsFontHeight_t>(Offsets::FUN_FONTSTRING_FONT_HEIGHT)(fs, nullptr, 1) *
|
||
anchorToPx;
|
||
return base + SumIconAdvances(text, len, fontHPx) / anchorToPx;
|
||
}
|
||
|
||
static const Game::HookAutoRegister _stringWidthHook{
|
||
Offsets::FUN_FONTSTRING_STRING_WIDTH, reinterpret_cast<void *>(&StringWidth_h),
|
||
reinterpret_cast<void **>(&g_stringWidthOriginal)};
|
||
|
||
// --- string-height co-hook (line growth for tall icons) ---------------------
|
||
//
|
||
// FUN_FONTSTRING_STRING_HEIGHT = GetStringHeightInternal (cache fs+0x100,
|
||
// lines×fontH + (lines−1)×spacing — icon-blind). Its three binary consumers
|
||
// (verified via xrefs):
|
||
// • FUN_00772A60 — the anchor's effective-height vmethod: explicit height if
|
||
// set, else THIS. Chat line fontstrings get only a SetWidth from the
|
||
// ScrollingMessageFrame refresh, so their rect height resolves here.
|
||
// • FUN_00788750 — the SMF display refresh: budgets vertical space per line
|
||
// with THIS and anchors each line to the previous line's rect.
|
||
// • FUN_0077D4D0 — the multi-line EDITBOX self-size (excluded below; editbox
|
||
// text renders raw markup, so its height must stay literal).
|
||
// Adding the tallest icon's overflow past the font height therefore grows the
|
||
// line's rect AND the chat stack's spacing in one place — a 24px emote in 15px
|
||
// chat takes real vertical room instead of overlapping its neighbours. This is
|
||
// the 4.3.4 model: its measure/wrap loops export a max-texture-height out-param
|
||
// and the layout grows the line (FUN_00618b90/FUN_00618e40 case 7).
|
||
//
|
||
// The draw side bottom-aligns tall icons (see FlushLayout's cy), so the
|
||
// overflow points UP — into the grown space — which matches the SMF's
|
||
// bottom-anchored stacking (older lines shift up by the growth).
|
||
//
|
||
// Same rules as the width hook: NEVER write the fs+0x100 cache (the delta is
|
||
// re-derived and re-added per call — idempotent); px→anchor via the push
|
||
// factor, not fs+0x7C. v1 limit (documented): the delta is the WHOLE text's
|
||
// max overflow, exact when the tall icons sit on one wrapped line (the emote
|
||
// case); two tall icons on different wrapped lines of one message under-grow.
|
||
using StringHeightInternal_t = float(__fastcall *)(void *fs);
|
||
StringHeightInternal_t g_stringHeightOriginal = nullptr;
|
||
|
||
float __fastcall StringHeight_h(void *fs) {
|
||
const float base = g_stringHeightOriginal(fs);
|
||
if (!LooksReadable(fs))
|
||
return base;
|
||
const auto *f = reinterpret_cast<const uint8_t *>(fs);
|
||
const bool editable =
|
||
(*reinterpret_cast<const uint32_t *>(f + Offsets::OFF_FONTSTRING_MEASURE_FLAGS) &
|
||
0x1000u) != 0;
|
||
const uint8_t *text =
|
||
*reinterpret_cast<const uint8_t *const *>(f + Offsets::OFF_FONTSTRING_TEXT);
|
||
if (!LooksReadable(text) || !InlineInterceptActive(text, editable))
|
||
return base;
|
||
int len = 0;
|
||
while (len < 0x4000 && text[len] != '\0')
|
||
++len;
|
||
if (!HasInlineTexture(text, len))
|
||
return base;
|
||
const float mul = *reinterpret_cast<const float *>(Offsets::VAR_UI_COORD_SCALE_MUL);
|
||
const float div = *reinterpret_cast<const float *>(Offsets::VAR_UI_COORD_SCALE_DIV);
|
||
if (!(mul > 0.0f) || !(div > 0.0f))
|
||
return base;
|
||
const float anchorToPx = div * Offsets::UI_COORD_SCALE_UNIT / mul;
|
||
const float fontHPx =
|
||
reinterpret_cast<FsFontHeight_t>(Offsets::FUN_FONTSTRING_FONT_HEIGHT)(fs, nullptr, 1) *
|
||
anchorToPx;
|
||
return base + MaxIconOverflowPx(text, len, fontHPx) / anchorToPx;
|
||
}
|
||
|
||
static const Game::HookAutoRegister _stringHeightHook{
|
||
Offsets::FUN_FONTSTRING_STRING_HEIGHT, reinterpret_cast<void *>(&StringHeight_h),
|
||
reinterpret_cast<void **>(&g_stringHeightOriginal)};
|
||
|
||
// --- hyperlink-rect co-hook (tall icons stay hoverable) ----------------------
|
||
//
|
||
// FUN_TEXT_LINK_RECT_ADD appends a link's hit rect with the TEXT band's y
|
||
// extent (fontH tall — see Offsets.h). A tall inline icon inside a link
|
||
// (|H…|h with a |T…:32|t emote) centres on the line and pokes past that band,
|
||
// so only its text-high middle slice was hoverable.
|
||
//
|
||
// The consumer geometry (FUN_00788c00 → FUN_007a3350 + two in-game
|
||
// experiments): the SMF rebuilds a HIT REGION per record, anchored to the
|
||
// LINE FONTSTRING's TOP-LEFT with the record's y band as offset/height. The
|
||
// band's y values are Y-UP (numeric max = screen top; extending the max
|
||
// visibly grew the region into the line ABOVE), and the band is TEXT-relative
|
||
// — but the string-height co-hook grew the fs rect by the icon overflow and
|
||
// the text centres in the grown rect, so the anchor (rect top) already sits
|
||
// HALF the overflow above the text top, pre-shifting the whole hit band up.
|
||
// Net: the unmodified band covers [iconTop .. textBottom − half] — the
|
||
// original "only the top half hovers" symptom — and the ONLY correction
|
||
// needed is pushing the screen BOTTOM down by the FULL overflow, i.e.
|
||
// DECREASING the numeric MIN edge. (Symmetric ± expansion moved the bottom
|
||
// edge UP — bottom third dead; extending the max grew the top into the line
|
||
// above — both verified in-game and both consistent with this model.)
|
||
// escStart/escLen span the whole |H…|h escape, so any |T inside is found; the
|
||
// InlineInterceptActive gate keeps raw-rendered contexts (suppressed editbox
|
||
// delegation) literal. Known v1 rough edge: a tall icon OUTSIDE the link but
|
||
// on the same line grows the line without this hook firing for the link,
|
||
// leaving that link's band half-overflow high.
|
||
using LinkRectAdd_t = void(__fastcall *)(void *node, void *edx, float yA, float xLeft, float yB,
|
||
float xRight, const char *linkStart, uint32_t linkLen,
|
||
const uint8_t *escStart, uint32_t escLen);
|
||
LinkRectAdd_t g_linkRectAddOriginal = nullptr;
|
||
|
||
void __fastcall LinkRectAdd_h(void *node, void *edx, float yA, float xLeft, float yB, float xRight,
|
||
const char *linkStart, uint32_t linkLen, const uint8_t *escStart,
|
||
uint32_t escLen) {
|
||
if (g_inlineEnabled && LooksReadable(node) && LooksReadable(escStart) && escLen > 0 &&
|
||
escLen < 0x4000 && InlineInterceptActive(escStart, false)) {
|
||
const int len = static_cast<int>(escLen);
|
||
if (HasInlineTexture(escStart, len)) {
|
||
// The line's font pixel height, the emitter's own recipe (ecx =
|
||
// (nodeFlags>>7)&1, stack = node fontSize).
|
||
const uint32_t nodeFlags = *reinterpret_cast<const uint32_t *>(
|
||
reinterpret_cast<const uint8_t *>(node) + Offsets::OFF_TEXT_NODE_FLAGS);
|
||
const float fontSize = *reinterpret_cast<const float *>(
|
||
reinterpret_cast<const uint8_t *>(node) + Offsets::OFF_TEXT_NODE_FONT_SIZE);
|
||
const float fontH = reinterpret_cast<float(__fastcall *)(int, float)>(
|
||
Offsets::FUN_TEXT_FONT_HEIGHT)(static_cast<int>((nodeFlags >> 7) & 1u), fontSize);
|
||
const float overflow = MaxIconOverflowPx(escStart, len, fontH);
|
||
if (overflow > 0.0f) {
|
||
// Push the SCREEN BOTTOM down: decrease the numeric MIN edge
|
||
// (y-up band) — see the anchor-shift analysis above.
|
||
if (yA <= yB)
|
||
yA -= overflow;
|
||
else
|
||
yB -= overflow;
|
||
}
|
||
}
|
||
}
|
||
g_linkRectAddOriginal(node, edx, yA, xLeft, yB, xRight, linkStart, linkLen, escStart, escLen);
|
||
}
|
||
|
||
static const Game::HookAutoRegister _linkRectAddHook{Offsets::FUN_TEXT_LINK_RECT_ADD,
|
||
reinterpret_cast<void *>(&LinkRectAdd_h),
|
||
reinterpret_cast<void **>(&g_linkRectAddOriginal)};
|
||
|
||
// --- wrap-stepper co-hook (icon-aware line breaks) ---------------------------
|
||
//
|
||
// FUN_TEXT_WRAP_STEPPER lays out one wrapped line per call (see Offsets.h).
|
||
// It measures the line through the tokenizer, which eats each `|T` span as
|
||
// ~zero width — so the break lands as if the icons weren't there, and the
|
||
// emitter's real advances then overflow the right edge (chat lines with
|
||
// prefix icons ran past the frame). Fix: shrink the wrapWidth argument by the
|
||
// advances of the icons in the remaining text (same IconAdvancePen math the
|
||
// emitter reserves), then call the original. `text` always points at the
|
||
// REMAINING text, so a continuation line whose icons are already behind it
|
||
// gets sum = 0 — chat prefix icons come out exact. An icon that would land on
|
||
// a LATER wrapped line still shrinks the earlier calls' width, wrapping those
|
||
// lines slightly early — the safe direction (never overflow), cosmetic only.
|
||
//
|
||
// Because all four wrap consumers route through this one dispatcher, the
|
||
// render's breaks, GetStringHeight's line count, ellipsis truncation, and the
|
||
// break arrays all shift together — no cross-consumer drift.
|
||
//
|
||
// UNITS (bit us on first flight): each caller passes fontH/wrapWidth in its
|
||
// OWN space — the draw builder passes the node's fontSize (+0x1C) and wrap
|
||
// width (+0x3C) in internal text units, while the fs-level callers (height,
|
||
// fit, break arrays — the path CHAT wraps through) pass the much smaller
|
||
// anchor-converted space. Subtracting a raw pixel advance annihilated those
|
||
// small widths to the floor and shredded icon-bearing chat lines into
|
||
// 2-glyph fragments. The space-agnostic conversion uses the engine's own
|
||
// convention: every gxu caller passes fontH in the units FUN_TEXT_FONT_HEIGHT
|
||
// expects, and the measure loops use FUN_TEXT_FONT_HEIGHT(flag, fontH) as the
|
||
// PIXEL realization of that fontH (see FUN_005c6940's final scale). So
|
||
// px→caller-units is exactly (fontH / fontHPx): compute the icon sum in true
|
||
// pixels (same value the emitter reserves), then scale by that ratio.
|
||
using WrapStepper_t = void(__fastcall *)(void *font, uint8_t *text, float fontH,
|
||
float wrapWidth, int *outBreak, float *outWidth,
|
||
void *outNext, float indent, uint32_t flags,
|
||
uint8_t *p10);
|
||
WrapStepper_t g_wrapStepperOriginal = nullptr;
|
||
|
||
void __fastcall WrapStepper_h(void *font, uint8_t *text, float fontH, float wrapWidth,
|
||
int *outBreak, float *outWidth, void *outNext, float indent,
|
||
uint32_t flags, uint8_t *p10) {
|
||
// flags bit 0x80 routes to the no-wrap path (wrapWidth unused); bit 0x40 is
|
||
// the editbox bit the tokenizer stands down on — same predicate, same gate.
|
||
// Positive fontH/wrapWidth gates mirror the original's own validation: a
|
||
// shrink below zero would trip its bail-to-zero-outputs path and blank the
|
||
// line, so the floor keeps a couple of glyphs' worth of progress instead.
|
||
if ((flags & 0x80u) == 0 && wrapWidth > 0.0f && fontH > 0.0f &&
|
||
InlineInterceptActive(text, (flags & 0x40u) != 0)) {
|
||
int len = 0;
|
||
while (len < 2048 && text[len] != '\0' && text[len] != '\n')
|
||
++len;
|
||
if (HasInlineTexture(text, len)) {
|
||
// Pixel realization of this caller's fontH — the same helper the
|
||
// measure loops and the emitter use. px → caller units is then
|
||
// (fontH / fontHPx); see the units note above.
|
||
const int fontFlag = static_cast<int>((flags >> 7) & 1u);
|
||
const float fontHPx = reinterpret_cast<float(__fastcall *)(int, float)>(
|
||
Offsets::FUN_TEXT_FONT_HEIGHT)(fontFlag, fontH);
|
||
if (fontHPx > 0.0f) {
|
||
const float toUnits = fontH / fontHPx;
|
||
const float minWidth = fontH * 2.0f;
|
||
// Only icons that actually LAND on this line may shrink its
|
||
// width — subtracting every icon in the remaining text made an
|
||
// 8-icon line wrap absurdly early (one word per line). The
|
||
// break position depends on the shrink and vice versa, so run
|
||
// the stepper as a sandboxed probe (local out-params + a COPY
|
||
// of the p10 in/out state byte, so the caller's first-line
|
||
// state isn't consumed) and iterate to a fixed point: probe
|
||
// unshrunk first (latest possible break = upper bound on the
|
||
// line's icons), re-count icons before the resulting break,
|
||
// re-probe with that shrink. Converges when the icon set
|
||
// stabilizes (exact); on boundary oscillation take the larger
|
||
// of the last two sums (wraps at most one icon early — the
|
||
// safe direction).
|
||
//
|
||
// The probe width MUST be floored like the final width: a ≤0
|
||
// probe width trips the stepper's bail-to-zero-outputs path,
|
||
// the zeroed break falls back to lineLen = len, the sum snaps
|
||
// back to EVERY icon, and the loop "converges" on the naive
|
||
// whole-text shrink (the v2 bug — multi-icon lines still
|
||
// shredded while single-icon lines worked).
|
||
// Minimal-feasible-shrink search. The stepper reports the
|
||
// line's measured (icons-at-zero) width in outWidth, so each
|
||
// probe yields a direct feasibility check: the line renders
|
||
// inside the frame iff its icons fit in the shrink plus the
|
||
// spare the break left — iconSum ≤ s + (probeW − outWidth).
|
||
// Search for the SMALLEST feasible s (fullest lines):
|
||
// • s = 0 feasible → no shrink at all (line fits its icons
|
||
// in the natural slack — the common short-message case).
|
||
// • infeasible with no feasible found yet → escalate to the
|
||
// measured deficit (iconSum − slack; strictly increasing).
|
||
// • once a [lo = infeasible, best = feasible] bracket
|
||
// exists → bisect it, feasible probes lowering best,
|
||
// infeasible ones raising lo, until the bracket is under
|
||
// a quarter-glyph. Giving up on the first stale
|
||
// escalation candidate (an earlier version) left the
|
||
// bracket unsearched and cost the Marks line a whole
|
||
// mark+word pair per line.
|
||
// Bounded at 8 probes; if none lands feasible, the last
|
||
// escalation target is used (an upper-bound shrink — wraps
|
||
// early rather than overflowing).
|
||
float lo = -1.0f; // largest known-infeasible s
|
||
float best = -1.0f; // smallest known-feasible s
|
||
float s = 0.0f;
|
||
for (int pass = 0; pass < 8; ++pass) {
|
||
int pBreak = 0;
|
||
float pWidth = 0.0f;
|
||
uint8_t *pNext = nullptr;
|
||
uint8_t p10copy = (p10 != nullptr) ? *p10 : 0;
|
||
float probeW = wrapWidth - s;
|
||
if (probeW < minWidth)
|
||
probeW = minWidth;
|
||
g_wrapStepperOriginal(font, text, fontH, probeW, &pBreak, &pWidth,
|
||
static_cast<void *>(&pNext), indent, flags,
|
||
(p10 != nullptr) ? &p10copy : nullptr);
|
||
// outBreak and outNext−text are both BYTE counts (verified
|
||
// during bring-up); outBreak == len means the whole text fit.
|
||
int lineLen = len;
|
||
if (pBreak > 0 && pBreak < len)
|
||
lineLen = pBreak;
|
||
else if (pNext > text && pNext - text < len)
|
||
lineLen = static_cast<int>(pNext - text);
|
||
const float sumPx = SumIconAdvances(text, lineLen, fontHPx);
|
||
const float iconUnits = sumPx * toUnits;
|
||
float slack = probeW - pWidth;
|
||
if (slack < 0.0f)
|
||
slack = 0.0f;
|
||
// AUTO-WIDTH bail: the whole text fits its budget with at
|
||
// most ~a glyph of slack — the signature of a
|
||
// single-anchor, no-width fontstring whose wrap budget is
|
||
// its own text-only measure plus a ~1-glyph engine margin
|
||
// (measured 1.07×fontH on pfUI's addon-list labels; the
|
||
// half-glyph first cut missed it). There is no real frame
|
||
// edge to protect there: the box is synthetic, the icons
|
||
// draw past it harmlessly, and any shrink FABRICATES a
|
||
// wrap on a line the engine would never have wrapped.
|
||
// Real-width content stays covered: an overflowing line
|
||
// breaks (lineLen < len), and a fitting line in a real
|
||
// frame carries frame-sized slack (the Marks harness line
|
||
// measures ~3.5×fontH) — only a text that lands within
|
||
// 1.5 glyphs of exactly filling its frame gives up its
|
||
// shrink, and its overflow is bounded by its icon sum
|
||
// (the pre-hook status quo).
|
||
if (pass == 0 && lineLen == len && slack <= fontH * 1.5f)
|
||
break; // s == 0, best unset → final shrink = 0
|
||
// Half-glyph feasibility tolerance. An AUTO-WIDTH
|
||
// fontstring's wrap width IS the icon-inclusive string
|
||
// width (the GetStringWidth hook feeds the effective-width
|
||
// vmethod), so its line fits with EXACTLY zero slack —
|
||
// iconSum == slack up to cross-computation drift (the two
|
||
// hooks derive the icon sum through different unit chains,
|
||
// plus OUTLINE extras and the trailing-glyph ink/advance
|
||
// quirk). Without tolerance that drift reads "fits
|
||
// exactly" as "1px over", shrinks a zero-slack line, and
|
||
// forces a wrap that had no business existing (the
|
||
// TwitchEmotes addon-list label). Genuine icon overflow is
|
||
// >= a full icon (~1.27 fontH), so half a glyph separates
|
||
// drift from real overflow; the cost is that a real
|
||
// overflow may render up to half a glyph past the edge.
|
||
if (iconUnits <= s + slack + fontH * 0.5f) {
|
||
if (best < 0.0f || s < best)
|
||
best = s;
|
||
if (s <= 0.0f)
|
||
break; // can't beat zero shrink
|
||
} else {
|
||
if (s > lo)
|
||
lo = s;
|
||
if (best < 0.0f) {
|
||
// No feasible found yet — escalate by the
|
||
// measured deficit (strictly increasing).
|
||
float next = iconUnits - slack;
|
||
if (next <= s)
|
||
next = s + fontH;
|
||
s = next;
|
||
continue;
|
||
}
|
||
}
|
||
// A [lo, best] bracket exists — bisect until it's tighter
|
||
// than a quarter-glyph.
|
||
if (lo < 0.0f || best < 0.0f)
|
||
break; // feasible with no infeasible below → best = s
|
||
if (best - lo < fontH * 0.25f)
|
||
break;
|
||
s = (lo + best) * 0.5f;
|
||
}
|
||
const float finalShrink = (best >= 0.0f) ? best : s;
|
||
float shrunk = wrapWidth - finalShrink;
|
||
if (shrunk < minWidth)
|
||
shrunk = minWidth;
|
||
wrapWidth = shrunk;
|
||
}
|
||
}
|
||
}
|
||
g_wrapStepperOriginal(font, text, fontH, wrapWidth, outBreak, outWidth, outNext, indent,
|
||
flags, p10);
|
||
}
|
||
|
||
static const Game::HookAutoRegister _wrapStepperHook{
|
||
Offsets::FUN_TEXT_WRAP_STEPPER, reinterpret_cast<void *>(&WrapStepper_h),
|
||
reinterpret_cast<void **>(&g_wrapStepperOriginal)};
|
||
|
||
// --- emitter co-hook (positioning) -----------------------------------------
|
||
|
||
// FUN_005ccbe0 — the per-line glyph emitter. __thiscall(node, text, len,
|
||
// colorState, penXYZ, pageMask, linkState); declared __fastcall with a dummy edx
|
||
// (the established pattern for co-hooking __thiscall engine methods).
|
||
using Emitter_t = void(__fastcall *)(void *node, void *edx, uint8_t *text, int len,
|
||
uint32_t *colorState, float *penXYZ, uint32_t *pageMask,
|
||
int *linkState);
|
||
Emitter_t g_emitterOriginal = nullptr;
|
||
|
||
void __fastcall Emitter_h(void *node, void *edx, uint8_t *text, int len, uint32_t *colorState,
|
||
float *penXYZ, uint32_t *pageMask, int *linkState) {
|
||
// Fast path — feature off: delegate verbatim, touching nothing.
|
||
if (!g_inlineEnabled) {
|
||
g_emitterOriginal(node, edx, text, len, colorState, penXYZ, pageMask, linkState);
|
||
return;
|
||
}
|
||
|
||
// Suppressed — render the node's text verbatim and drop any icons previously
|
||
// recorded for it, so editable input shows raw markup. Covers the FOCUSED
|
||
// editbox's own text (this render line's CONTENT equals the editbox input —
|
||
// the editbox renders through a transient copy with no pointer link), the
|
||
// pointer path (`text` inside the input buffer, rare), and any editable node
|
||
// (flags bit 6, e.g. the un-focused macro editor). Per-editbox, not global: a
|
||
// chat-history line's content differs, so its icons keep rendering while an
|
||
// editbox is focused.
|
||
const bool sup_ptr = TextInFocusedEditbox(text);
|
||
const bool sup_content = !sup_ptr && EmitLineIsFocusedEditbox(text);
|
||
// Suppress on the editable bit (bit 6). Verified via the ICON-NODE probe: chat
|
||
// DISPLAY is editable=0 (flags 0x205), the macro editor is editable=1 (0x4D),
|
||
// the focused chat edit box is editable=0 but content-matched (0x20D). So the
|
||
// editable bit cleanly catches the un-focused macro editor (which content-match
|
||
// can't, since it's not the focused editbox) without touching chat display.
|
||
// Content-match still handles the focused chat/name box.
|
||
const bool sup_editable = node != nullptr && NodeEditable(node);
|
||
if (sup_ptr || sup_content || sup_editable) {
|
||
if (node != nullptr)
|
||
g_nodeIcons.erase(node);
|
||
// Bracket the delegated raw layout so the re-entrant tokenizer stands down
|
||
// across the whole line (else it eats `|T` as a zero-width token → BLANK).
|
||
g_reentryLo = text;
|
||
g_reentryHi = (text != nullptr && len > 0) ? text + len : text;
|
||
g_emitterOriginal(node, edx, text, len, colorState, penXYZ, pageMask, linkState);
|
||
g_reentryLo = nullptr;
|
||
g_reentryHi = nullptr;
|
||
return;
|
||
}
|
||
|
||
if (node == nullptr || text == nullptr || len <= 0) {
|
||
g_emitterOriginal(node, edx, text, len, colorState, penXYZ, pageMask, linkState);
|
||
return;
|
||
}
|
||
|
||
// The draw builder walks a node's wrapped lines by calling the emitter once
|
||
// per line on the SAME node. First-line detection comes from the builder
|
||
// co-hook's build stamp (exact), NOT from comparing text pointers against
|
||
// node+text — that heuristic silently failed on pfUI-processed lines,
|
||
// leaving reused nodes' inherited records alive (ghost icons). Clear the
|
||
// icon list once per build so wrapped lines ACCUMULATE their icons instead
|
||
// of each wiping the previous.
|
||
// Build-stamp detection when this emit is inside a tracked builder run
|
||
// (exact); the old text-pointer heuristic as fallback for any emitter
|
||
// caller that doesn't route through FUN_TEXT_DRAW_BUILDER — `false` there
|
||
// would mean never-erase, which is how reused nodes kept dead records.
|
||
const bool firstLine =
|
||
(node == g_buildNode)
|
||
? (g_buildEmitSeq++ == 0)
|
||
: (text == *reinterpret_cast<uint8_t **>(reinterpret_cast<uint8_t *>(node) +
|
||
Offsets::OFF_TEXT_NODE_TEXT));
|
||
if (firstLine)
|
||
g_nodeIcons.erase(node);
|
||
|
||
if (!HasInlineTexture(text, len)) {
|
||
// No inline texture on this line — render it normally. Note: firstLine
|
||
// already erased the node's stale records above, so a REUSED node
|
||
// address whose new text has no markup is cleaned HERE, by the emitter.
|
||
// This is the ghost-icon protection; the flush must NOT re-derive it by
|
||
// scanning node text (that scan read a stale/preprocessed pointer on
|
||
// pfUI chat lines and erased LIVE records every frame — the persistent
|
||
// iconless LFG lines).
|
||
g_emitterOriginal(node, edx, text, len, colorState, penXYZ, pageMask, linkState);
|
||
return;
|
||
}
|
||
|
||
// This line owns inline textures — append them, rendering the plain runs by
|
||
// delegating to the original per segment.
|
||
std::vector<IconRecord> &icons = g_nodeIcons[node];
|
||
|
||
// Bit 3 of the node flags gates the emitter's per-call batch-clear. When set
|
||
// (the standalone-FontString case), each original call would wipe the page
|
||
// batches, so segmenting would lose all but the last run. Handle it by doing
|
||
// the batch-clear ONCE per build (a len-0 original call with bit 3 still set,
|
||
// only on the first wrapped line), then clearing bit 3 so our per-segment calls
|
||
// APPEND. Restore the flags before returning.
|
||
uint32_t *const flagsPtr = reinterpret_cast<uint32_t *>(reinterpret_cast<uint8_t *>(node) +
|
||
Offsets::OFF_TEXT_NODE_FLAGS);
|
||
const uint32_t savedFlags = *flagsPtr;
|
||
const bool batchClearMode = (savedFlags & 8u) != 0;
|
||
if (batchClearMode) {
|
||
if (firstLine)
|
||
g_emitterOriginal(node, edx, text, 0, colorState, penXYZ, pageMask, linkState);
|
||
*flagsPtr = savedFlags & ~8u;
|
||
|
||
// Clearing bit 3 switches the engine from the FontString's UNIFORM colour
|
||
// (RGB from SetTextColor + opacity applied wholesale) to PER-GLYPH colour
|
||
// taken from colorState = [node+0x2c]. That field's RGB is correct, but its
|
||
// ALPHA byte is a stale default (observed 0x07 ≈ 3%) rather than the
|
||
// FontString's real opacity — so the segmented glyphs draw ~transparent,
|
||
// and a FontString with a dark outline (pfUI's reskinned bubble) shows only
|
||
// the outline: "black text". Force the glyph alpha opaque, keeping the RGB
|
||
// (so a coloured bubble stays its colour). `|c`-driven text already carries
|
||
// alpha 0xFF, so this is a no-op for chat lines.
|
||
colorState[0] |= 0xFF000000u;
|
||
}
|
||
|
||
// Font pixel height of this line — used to centre icons vertically (penY sits
|
||
// near the text top). Mirrors the emitter's own call: ecx = (nodeFlags>>7)&1,
|
||
// stack = the node's font size [node+0x1c].
|
||
const int fontFlag = static_cast<int>((savedFlags >> 7) & 1u);
|
||
const float fontSize =
|
||
*reinterpret_cast<float *>(reinterpret_cast<uint8_t *>(node) +
|
||
Offsets::OFF_TEXT_NODE_FONT_SIZE);
|
||
const float fontH = reinterpret_cast<float(__fastcall *)(int, float)>(
|
||
Offsets::FUN_TEXT_FONT_HEIGHT)(fontFlag, fontSize);
|
||
|
||
// Font face + native→pen advance scale, mirroring the emitter's own
|
||
// `local_10 = fontH / (float)nativeHeight`. Used by drawRun's terminal-
|
||
// advance correction (glyph-record advances are native-font units).
|
||
void *const fontFace = *reinterpret_cast<void **>(reinterpret_cast<uint8_t *>(node) +
|
||
Offsets::OFF_TEXT_NODE_FONT_FACE);
|
||
using FontNativeHeight_t = int(__fastcall *)(void *font);
|
||
const int fontNativeH =
|
||
(fontFace != nullptr)
|
||
? reinterpret_cast<FontNativeHeight_t>(Offsets::FUN_TEXT_FONT_NATIVE_HEIGHT)(fontFace)
|
||
: 0;
|
||
const float penScale = (fontNativeH > 0) ? fontH / static_cast<float>(fontNativeH) : 0.0f;
|
||
|
||
// The original emitter never writes penXYZ[0]; we mutate it to thread the pen
|
||
// across segments, so snapshot and restore it. The draw builder does NOT reset
|
||
// penXYZ[0] between left-justified lines, so leaving it mutated would cascade-
|
||
// shift every following line.
|
||
const float startX = penXYZ[0];
|
||
const float penY = penXYZ[1];
|
||
float penX = penXYZ[0];
|
||
|
||
// Centre/right-justify correction. The engine positioned the pen (penXYZ[0])
|
||
// using this line's MEASURED width, which counts inline icons as ~zero (the
|
||
// tokenizer measure gap). The rendered line is wider by the icons' reserved
|
||
// width, so a centred line overflows its box to the right (empty space on the
|
||
// left) and a right-aligned line overflows past the right edge. Pre-sum this
|
||
// line's icon widths and shift the pen left by half that (centre) or all of it
|
||
// (right) so the whole text+icons block is justified as a unit. Left-justify
|
||
// (chat, justify 0) needs no shift. node+0x54: 1 = centre, 2 = right (verified
|
||
// in the draw builder FUN_005cdc20's justify branch).
|
||
const int justify = *reinterpret_cast<const int *>(
|
||
reinterpret_cast<const uint8_t *>(node) + Offsets::OFF_TEXT_NODE_JUSTIFY);
|
||
if (justify == 1 || justify == 2) {
|
||
// Shared helper so the pre-shift matches the real advances exactly
|
||
// (including the positive-offsetX term an earlier inline copy omitted).
|
||
const float iconW = SumIconAdvances(text, len, fontH);
|
||
penX -= (justify == 1) ? iconW * 0.5f : iconW;
|
||
}
|
||
|
||
// Draws a plain run [start,start+n) via the original emitter, threading the
|
||
// pen: the original starts at penXYZ[0] and leaves its final pen x in
|
||
// linkState[4] (a FLOAT bit pattern — `FSTP dword`; an int-cast yields
|
||
// garbage). n == 0 is a safe no-op that just finalizes linkState.
|
||
//
|
||
// THE READ-BACK IS LAZY AND NEEDS CORRECTION (verified in FUN_005ccbe0):
|
||
// the emitter's pen consumes a glyph's advance only when the NEXT token
|
||
// lands (each glyph is placed at pen + pairAdvance(prev, cur)), and its
|
||
// final write is `linkState[4] = x(lastGlyph) + pairAdvance(secondLast,
|
||
// last)` — the last PAIR re-added as a stand-in for the LAST glyph's own
|
||
// advance. For a 1-glyph run the stand-in is 0 (no pair exists), so the
|
||
// run reads as zero-width — the money-string "coin sits on the lone digit"
|
||
// bug ("|cffffffff0" → penAfter 0). For "…] 1" the stand-in is the SPACE's
|
||
// advance (narrower than the digit's) — the single-digit clip. Fix: walk
|
||
// the run with the engine's own tokenizer, and when it ends in a glyph
|
||
// replace the stand-in with the truth:
|
||
// pen = linkState[4] − pairAdvance(prev, last)·scale + baseAdvance(last)·scale
|
||
// (both terms truncated to int when node-flags bit 7 is clear, mirroring
|
||
// the emitter's per-placement __ftol snap). Runs ending in a NON-glyph
|
||
// token (trailing |c/|r) need no correction: the trailing iteration's
|
||
// recompute already folded pairAdvance(lastGlyph, junkPayload) ≈
|
||
// baseAdvance(lastGlyph) into the write. This mirrors 4.3.4's texture case,
|
||
// which computes the pending last-glyph advance explicitly at the icon
|
||
// (FUN_0061ea10 case 7) instead of trusting a stored pen.
|
||
using GlyphPairAdvance_t = float(__thiscall *)(void *font, uint32_t prevCh, uint32_t curCh);
|
||
using GlyphBaseAdvance_t = float(__thiscall *)(void *font, uint32_t ch);
|
||
auto drawRun = [&](size_t start, int n) {
|
||
penXYZ[0] = penX;
|
||
g_emitterOriginal(node, edx, text + start, n, colorState, penXYZ, pageMask, linkState);
|
||
penX = *reinterpret_cast<float *>(&linkState[4]);
|
||
if (n <= 0 || penScale <= 0.0f || fontFace == nullptr)
|
||
return;
|
||
// Token-walk the run (the ORIGINAL tokenizer — our co-hook would eat
|
||
// |T spans, but runs never contain them by construction) for its last
|
||
// two glyph payloads.
|
||
uint32_t prevCh = 0, lastCh = 0;
|
||
int glyphCount = 0;
|
||
bool endsInGlyph = false;
|
||
const uint8_t *p = text + start;
|
||
int rem = n;
|
||
while (rem > 0 && *p != 0) {
|
||
int consumed = 0;
|
||
uint32_t colorOut = 0, payload = 0;
|
||
const uint32_t tok = g_tokenizerOriginal(const_cast<uint8_t *>(p), &consumed,
|
||
&colorOut, savedFlags, &payload);
|
||
if (consumed <= 0 || consumed > rem)
|
||
break;
|
||
p += consumed;
|
||
rem -= consumed;
|
||
// Emitter switch handles 0(color)/1(reset)/2(break)/4(|H)/5(|h)
|
||
// specially; everything else (6 = glyph, 3 = literal ||) draws.
|
||
if (tok != 0 && tok != 1 && tok != 2 && tok != 4 && tok != 5) {
|
||
prevCh = lastCh;
|
||
lastCh = payload;
|
||
++glyphCount;
|
||
endsInGlyph = true;
|
||
} else {
|
||
endsInGlyph = false;
|
||
}
|
||
}
|
||
if (!endsInGlyph)
|
||
return;
|
||
const bool snap = (savedFlags & 0x80u) == 0;
|
||
// The stand-in the engine's final write added: pairAdvance(prev, last),
|
||
// 0 for a 1-glyph run (never computed). Same kerning variant the
|
||
// emitter picks (flags bit 4).
|
||
float standIn = 0.0f;
|
||
if (glyphCount >= 2) {
|
||
const uintptr_t pairFn = ((savedFlags & 0x10u) != 0)
|
||
? Offsets::FUN_TEXT_GLYPH_PAIR_ADVANCE_ALT
|
||
: Offsets::FUN_TEXT_GLYPH_PAIR_ADVANCE;
|
||
standIn =
|
||
reinterpret_cast<GlyphPairAdvance_t>(pairFn)(fontFace, prevCh, lastCh) * penScale;
|
||
if (snap)
|
||
standIn = static_cast<float>(static_cast<int>(standIn));
|
||
}
|
||
float terminal = reinterpret_cast<GlyphBaseAdvance_t>(
|
||
Offsets::FUN_TEXT_GLYPH_BASE_ADVANCE)(fontFace, lastCh) *
|
||
penScale;
|
||
if (snap)
|
||
terminal = static_cast<float>(static_cast<int>(terminal));
|
||
penX += terminal - standIn;
|
||
};
|
||
|
||
size_t runStart = 0;
|
||
int i = 0;
|
||
while (i < len) {
|
||
if (text[i] != '|') {
|
||
++i;
|
||
continue;
|
||
}
|
||
int mlen = IconStartLen(text, len, i);
|
||
if (mlen == 0) {
|
||
// Not an icon. Skip an escaped pipe as a pair so its 2nd `|` isn't
|
||
// re-read as a clean `|T` next iteration; otherwise advance one.
|
||
if (i + 1 < len && text[i + 1] == '|')
|
||
i += 2;
|
||
else
|
||
++i;
|
||
continue;
|
||
}
|
||
const bool doubled = (mlen == 3);
|
||
int closeLen = 0;
|
||
size_t close = FindIconClose(text, len, static_cast<size_t>(i) + mlen, doubled, &closeLen);
|
||
if (close == static_cast<size_t>(-1)) {
|
||
// Unterminated on this line — treat the rest as plain text.
|
||
break;
|
||
}
|
||
// Render the plain run before the icon (finalizes pen at the icon).
|
||
drawRun(runStart, i - static_cast<int>(runStart));
|
||
|
||
IconDesc d;
|
||
const char *payload = reinterpret_cast<const char *>(text) + i + mlen;
|
||
size_t payloadLen = close - (static_cast<size_t>(i) + mlen);
|
||
if (ParseIcon(payload, payloadLen, d)) {
|
||
// height/width of 0 => size to the line's font (retail :0:0).
|
||
const float baseH = (d.height > 0.0f) ? d.height : fontH;
|
||
const float baseW = (d.width > 0.0f) ? d.width : baseH;
|
||
const float w = baseW * g_sizeScale;
|
||
const float h = baseH * g_sizeScale;
|
||
IconRecord r;
|
||
r.path = d.path;
|
||
r.x = penX;
|
||
r.y = penY;
|
||
r.fontH = fontH;
|
||
r.w = w;
|
||
r.h = h;
|
||
r.offsetX = d.offsetX * g_sizeScale;
|
||
r.offsetY = d.offsetY * g_sizeScale;
|
||
r.u0 = d.u0;
|
||
r.v0 = d.v0;
|
||
r.u1 = d.u1;
|
||
r.v1 = d.v1;
|
||
r.color = d.color;
|
||
icons.push_back(std::move(r));
|
||
// Reserve the icon width + a LEAD pad (full) and a TRAIL pad (half) so
|
||
// it never jams against adjacent text. Lead-heavy on purpose: the
|
||
// preceding glyph's right-side bearing eats into the left gap visually,
|
||
// so a symmetric layout pad looks tighter on the left / looser on the
|
||
// right — a half trail balances that. The lead pad is applied to the
|
||
// draw position in FlushLayout. Shared with the justify pre-shift and
|
||
// the string-width co-hook — never inline this math.
|
||
penX += IconAdvancePen(d, fontH);
|
||
}
|
||
penXYZ[0] = penX;
|
||
i = static_cast<int>(close) + closeLen; // skip past the closing marker
|
||
runStart = static_cast<size_t>(i);
|
||
}
|
||
|
||
// Trailing plain run (also finalizes pen/link state for the builder).
|
||
drawRun(runStart, len - static_cast<int>(runStart));
|
||
|
||
// Restore the pen origin to match the engine's own post-call invariant, and the
|
||
// node flags (bit 3) we cleared for the segmented append.
|
||
penXYZ[0] = startX;
|
||
if (batchClearMode)
|
||
*flagsPtr = savedFlags;
|
||
}
|
||
|
||
static const Game::HookAutoRegister _emitterHook{Offsets::FUN_TEXT_EMITTER,
|
||
reinterpret_cast<void *>(&Emitter_h),
|
||
reinterpret_cast<void **>(&g_emitterOriginal)};
|
||
|
||
// --- paint co-hook: queue recorded icons as region placements ---------------
|
||
|
||
using Paint_t = void(__fastcall *)(void *layout);
|
||
Paint_t g_paintOriginal = nullptr;
|
||
|
||
// Walks the layout's live render nodes and, for each recorded icon, computes
|
||
// its screen geometry (node-local pen coords translated by the node's screen
|
||
// origin +0x70/+0x74 — the SAME transform the paint pass applies to glyph
|
||
// batches) and queues it to Text::InlineTexturePool as a placement RELATIVE TO
|
||
// THE OWNING FONTSTRING. Runs after the original paint so icon coords and the
|
||
// fs rect are read in one coherent snapshot; the pool applies placements on
|
||
// the next FrameTick (regions are never mutated mid-render).
|
||
void FlushLayout(void *layout) {
|
||
if (!LooksReadable(layout))
|
||
return;
|
||
auto *L = reinterpret_cast<uint8_t *>(layout);
|
||
const int linkOff = *reinterpret_cast<int *>(L + Offsets::OFF_TEXT_LAYOUT_NODE_LINK);
|
||
void *node = *reinterpret_cast<void **>(L + Offsets::OFF_TEXT_LAYOUT_NODE_HEAD);
|
||
|
||
for (int guard = 0; node != nullptr && (reinterpret_cast<uintptr_t>(node) & 1) == 0 &&
|
||
guard < 4096;
|
||
++guard) {
|
||
if (!LooksReadable(node))
|
||
break;
|
||
auto *n = reinterpret_cast<uint8_t *>(node);
|
||
void *const next = *reinterpret_cast<void **>(n + linkOff + 4);
|
||
|
||
// Resolve the owning fontstring up front: a node with NO icons must
|
||
// still clear its fontstring's regions — the fs may have just been
|
||
// re-SetText'd from icon text to plain text (chat line slot reuse).
|
||
// A node only speaks for its fontstring while it IS the fontstring's
|
||
// CURRENT text node (fs+0xF8 → handle+8): around a rebuild, the old and
|
||
// new node can both be walked in one paint, and letting the stale one
|
||
// queue (especially a clear) made icons vanish nondeterministically.
|
||
void *fs = nullptr;
|
||
{
|
||
auto ow = g_nodeOwner.find(node);
|
||
if (ow != g_nodeOwner.end() && LooksReadable(ow->second)) {
|
||
auto *of = reinterpret_cast<uint8_t *>(ow->second);
|
||
void *block =
|
||
*reinterpret_cast<void **>(of + Offsets::OFF_FONTSTRING_TEXT_BLOCK);
|
||
if (LooksReadable(block) &&
|
||
*reinterpret_cast<void **>(reinterpret_cast<uint8_t *>(block) +
|
||
Offsets::OFF_TEXTBLOCK_NODE) == node) {
|
||
fs = ow->second;
|
||
} else if (block == nullptr) {
|
||
// Stuck-blockless fs: RebuildString released the block (a
|
||
// SetText landed on an unresolved rect) and never rebuilt;
|
||
// this zombie node keeps painting the old text. Re-set the
|
||
// fs's rebuild-dirty bit so the engine rebuilds next update
|
||
// and the icon pipeline resumes. Byte write only — safe
|
||
// from the paint tail (consumed by the fs's own update).
|
||
uint8_t *flags = of + Offsets::OFF_FONTSTRING_DIRTY_FLAGS;
|
||
*flags |= 1u;
|
||
}
|
||
}
|
||
}
|
||
|
||
auto it = g_nodeIcons.find(node);
|
||
// Ghost guard, scanned against the FONTSTRING's text (fs+0xF0 — proven
|
||
// trustworthy by the Broken() dumps, unlike the node's text pointer,
|
||
// which lied on pfUI chat lines and made the old node-text scan erase
|
||
// LIVE records). A node with records whose owning fs currently shows
|
||
// text WITHOUT any |T (e.g. a recycled nameplate name that inherited a
|
||
// dead emote node's address) is stale: erase and clear. False matches
|
||
// can only false-KEEP (safe), never false-erase.
|
||
// (NOTE: do NOT build-version records against the builder counter — the
|
||
// builder runs every paint but only emits when dirty, so a version
|
||
// check erases good records on every clean paint: the all-icons-gone
|
||
// regression.)
|
||
if (it != g_nodeIcons.end() && !it->second.empty() && fs != nullptr) {
|
||
const char *ftext = *reinterpret_cast<const char *const *>(
|
||
reinterpret_cast<uint8_t *>(fs) + Offsets::OFF_FONTSTRING_TEXT);
|
||
bool fsHasMarkup = false;
|
||
if (LooksReadable(ftext)) {
|
||
for (int k = 1; k < 2048 && ftext[k] != '\0'; ++k)
|
||
if (ftext[k] == 'T' && ftext[k - 1] == '|') {
|
||
fsHasMarkup = true;
|
||
break;
|
||
}
|
||
}
|
||
if (!fsHasMarkup) {
|
||
g_nodeIcons.erase(it);
|
||
it = g_nodeIcons.end();
|
||
}
|
||
}
|
||
if (it == g_nodeIcons.end() || it->second.empty()) {
|
||
if (fs != nullptr)
|
||
Text::InlineTexturePool::QueuePlacements(fs, {});
|
||
node = next;
|
||
continue;
|
||
}
|
||
|
||
// NOTE: no node-text stale scan here. Records are authoritative from the
|
||
// emitter alone: a reused node address is always rebuilt → dirty → the
|
||
// emitter runs before any flush walks it, and its firstLine erase (or
|
||
// suppression erase) cleans stale records. The old flush-side scan of
|
||
// node+text for |T read a stale/preprocessed pointer on pfUI chat lines
|
||
// and ERASED LIVE RECORDS every frame — the persistent iconless LFG
|
||
// lines (FsDump chain bucket 3).
|
||
|
||
// Never draw over editable text (flags bit 6) — safety net for records
|
||
// made before the emitter's editable-suppress applied.
|
||
if (!NodeEditable(node)) {
|
||
const float ox = *reinterpret_cast<float *>(n + Offsets::OFF_TEXT_NODE_ORIGIN_X);
|
||
const float oy = *reinterpret_cast<float *>(n + Offsets::OFF_TEXT_NODE_ORIGIN_Y);
|
||
// The fs rect, read HERE in the same flush as the icon coords — a
|
||
// coherent snapshot. Placements are stored FS-RELATIVE: an
|
||
// apply-time rect read raced the chat relayout (SetText invalidates
|
||
// the rect briefly), and a placement applied against a mid-relayout
|
||
// rect parked the icon off the line — then the dedup (unchanged
|
||
// absolute want) froze it there. Relative offsets are also
|
||
// position-invariant, so scrolling no longer re-places anything.
|
||
const float K = DeriveK(n, reinterpret_cast<uint8_t *>(fs), ox);
|
||
float fsLeft = 0.0f, fsBottom = 0.0f;
|
||
bool fsRectValid = false;
|
||
if (fs != nullptr) {
|
||
const float *rc = reinterpret_cast<const float *>(
|
||
reinterpret_cast<uint8_t *>(fs) + Offsets::OFF_REGION_RECT);
|
||
fsBottom = (rc[0] < rc[2]) ? rc[0] : rc[2];
|
||
fsLeft = (rc[1] < rc[3]) ? rc[1] : rc[3];
|
||
fsRectValid = rc[1] != rc[3]; // unresolved rect reads 0-width
|
||
}
|
||
std::vector<Text::InlineTexturePool::Placement> places;
|
||
for (const IconRecord &r : it->second) {
|
||
// Screen left = pen + the FULL lead pad. The emitter reserves
|
||
// w + 1.5×pad in the advance (lead 1×, trail 0.5×) — drawing at
|
||
// the raw pen put all of that gap AFTER the icon, which is why
|
||
// a string-final icon (money-string copper) looked jammed
|
||
// against its digits and grew per-coin offset hacks. The pad is
|
||
// fontH-relative (NOT r.w) — must match IconAdvancePen exactly.
|
||
const float cx = r.x + ox + r.offsetX + r.fontH * g_iconPadFrac;
|
||
// Centre on the line: penY sits near the text top, so add a
|
||
// fraction of the font height (plus the fine-tune bias). offsetY
|
||
// shifts up (WoW convention), so subtract it.
|
||
//
|
||
// TALL icons (h > fontH) centre too: the string-height co-hook
|
||
// grew the line by the overflow, and the text centres itself
|
||
// inside the grown rect (verified in-game — a bottom-aligned
|
||
// icon clipped the neighbouring line while retail shows tall
|
||
// emotes centred with no clip), so the extra space appears half
|
||
// above and half below the text. A centred icon fills exactly
|
||
// that — the retail look.
|
||
const float cy = r.y + r.fontH * g_centerFrac + oy + g_vBias - r.offsetY;
|
||
if (K > 1.0f && fs != nullptr && fsRectValid) {
|
||
const float rx = cx + g_regionCalX;
|
||
const float ry = cy + g_regionCalY;
|
||
Text::InlineTexturePool::Placement p;
|
||
p.path = r.path;
|
||
p.x0 = rx / K - fsLeft;
|
||
p.y0 = (ry - r.h * 0.5f) / K - fsBottom;
|
||
p.x1 = (rx + r.w) / K - fsLeft;
|
||
p.y1 = (ry + r.h * 0.5f) / K - fsBottom;
|
||
p.color = r.color;
|
||
p.u0 = r.u0;
|
||
p.v0 = r.v0;
|
||
p.u1 = r.u1;
|
||
p.v1 = r.v1;
|
||
places.push_back(std::move(p));
|
||
}
|
||
}
|
||
// The queue gate must match the per-icon build gate EXACTLY —
|
||
// including K. If any input wasn't ready this paint (unresolved fs
|
||
// rect, K not yet derived), SKIP the queue and retry next paint: an
|
||
// empty queue here would HIDE the line's icons and the dedup would
|
||
// freeze it hidden forever (identical empty re-queues never dirty).
|
||
// That was the scroll-landing bug's second head: lines painted
|
||
// before the session's first K derivation queued {} and stayed
|
||
// iconless until their text changed.
|
||
if (fs != nullptr && fsRectValid && K > 1.0f)
|
||
Text::InlineTexturePool::QueuePlacements(fs, std::move(places));
|
||
} else if (fs != nullptr) {
|
||
Text::InlineTexturePool::QueuePlacements(fs, {});
|
||
}
|
||
node = next;
|
||
}
|
||
}
|
||
|
||
// SEH latch: a fault anywhere in the flush disables the whole feature for the
|
||
// session instead of crashing the client (re-enable via
|
||
// _classicapi_InlineTexEnable after a /reload if it was transient).
|
||
void SafeFlush(void *layout) {
|
||
__try {
|
||
FlushLayout(layout);
|
||
} __except (EXCEPTION_EXECUTE_HANDLER) {
|
||
g_inlineEnabled = false;
|
||
}
|
||
}
|
||
|
||
void __fastcall Paint_h(void *layout) {
|
||
g_paintOriginal(layout);
|
||
if (g_inlineEnabled)
|
||
SafeFlush(layout);
|
||
}
|
||
|
||
static const Game::HookAutoRegister _paintHook{Offsets::FUN_TEXT_PAINT,
|
||
reinterpret_cast<void *>(&Paint_h),
|
||
reinterpret_cast<void **>(&g_paintOriginal)};
|
||
|
||
// --- Lua control surface ---------------------------------------------------
|
||
|
||
// _classicapi_InlineTexEnable([on]) -> enabled. The feature kill switch (also
|
||
// what the SEH latch trips on a flush fault).
|
||
int __fastcall Script_InlineTexEnable(void *L) {
|
||
if (Game::Lua::GetTop(L) == 0)
|
||
g_inlineEnabled = true;
|
||
else
|
||
g_inlineEnabled = Game::Lua::ToBoolean(L, 1) != 0;
|
||
Game::Lua::PushBool(L, g_inlineEnabled);
|
||
return 1;
|
||
}
|
||
|
||
void RegisterLuaFunctions() {
|
||
Game::Lua::RegisterGlobalFunction("_classicapi_InlineTexEnable", &Script_InlineTexEnable);
|
||
}
|
||
|
||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||
|
||
} // namespace
|
||
|
||
void PrepareForReload() {
|
||
// /reload frees every gxu text node — g_nodeIcons/g_nodeOwner hold stale
|
||
// node pointers. Forget them (records rebuild as the reloaded UI re-emits
|
||
// its text). K survives (resolution/uiScale don't change across /reload).
|
||
g_nodeIcons.clear();
|
||
g_nodeOwner.clear();
|
||
}
|
||
|
||
} // namespace Text::InlineTexture
|