diff --git a/README.md b/README.md index ed53dff0..0b915540 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The flagship feature: run modern Lua 5.1 addon code on 1.12's Lua 5.0 VM. | Feature | Effect | |---------|--------| -| Inline textures | Draws inline texture markup (`\|T…\|t`) as icons in FontStrings, chat, and tooltips. This covers item and spell icons, raid-target markers, and the coin icons in money strings. `GetStringWidth` and `GetStringHeight` count the icons, so measured width and text wrapping stay correct. Done in pure C++ by hooking the engine's text pipeline — no addon. | +| Inline textures | Draws inline texture markup (`\|T…\|t`) and atlas markup (`\|A…\|a`) as icons in FontStrings, chat, and tooltips. This covers item and spell icons, raid-target markers, and the coin icons in money strings. `GetStringWidth` and `GetStringHeight` count the icons, so measured width and text wrapping stay correct. Done in pure C++ by hooking the engine's text pipeline — no addon. | | Tooltip line cap | Lifts `GameTooltip`'s hard 30-line limit to 60 for every `GameTooltipTemplate` frame (`GameTooltip`, `ShoppingTooltip1/2`, `ItemRefTooltip`, AtlasLoot, …). Stat-heavy tooltips and comparison blocks (e.g. pfUI's eqcompare) no longer have their extra lines silently dropped. Done in pure C++ by growing the engine's FontString pool at tooltip-creation time. | | [Event-driven nameplates](docs/API.md#nameplate) | The modern `C_NamePlate` API, driven by real events. `NAME_PLATE_UNIT_ADDED` / `NAME_PLATE_UNIT_REMOVED` fire as plates appear and vanish, `nameplate1`..`nameplateN` tokens resolve with every `UnitX` function (and fire `UNIT_HEALTH`, `UNIT_AURA`, … as `arg1 == "nameplateN"`), and `C_NamePlate.GetNamePlateForUnit` / `GetNamePlates` hand back the live frames. | | [Focus target](docs/API.md#focus) | A sticky focus unit. `FocusUnit("target")` pins it and `ClearFocus()` drops it, with `PLAYER_FOCUS_CHANGED` on every change. The `focus` / `focustarget` tokens resolve with every `UnitX` function and fire unit events (`UNIT_HEALTH`, `UNIT_AURA`, … as `arg1 == "focus"`), and the predefined `FOCUSTARGET` / `TARGETFOCUS` keybinds are ready to set. | @@ -68,7 +68,7 @@ reference in **[docs/API.md](docs/API.md)**. | [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetClassicExpansionLevel` | | [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByID`, `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.IsFactionActive`, `C_Reputation.IsFactionActiveByID`, `C_Reputation.IsFactionInactive`, `C_Reputation.SetFactionActive`, `C_Reputation.SetFactionActiveByID`, `C_Reputation.SetFactionInactive`, `C_Reputation.SetFactionInactiveByID`, `C_Reputation.SetSelectedFaction`, `C_Reputation.SetSelectedFactionByID`, `C_Reputation.SetWatchedFactionByID`, `C_Reputation.ToggleFactionAtWar`, `C_Reputation.ToggleFactionAtWarByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` | | [Focus](docs/API.md#focus) | `ClearFocus`, `FocusUnit` | -| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `GetClickFrame` | +| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetAtlas`, `texture:GetAtlas`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `GetClickFrame` | | [FriendList](docs/API.md#friendlist) | `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` | | [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID`, `ClosestGameObjectPosition` | | [Glue](docs/API.md#glue) | `C_Glue.IsOnGlueScreen` | @@ -99,6 +99,7 @@ reference in **[docs/API.md](docs/API.md)**. | [Talent](docs/API.md#talent) | `GetTalentIDByIndex`, `GetTalentSpellID` | | [Targeting](docs/API.md#targeting) | `GetPlayerFacing`, `TargetDirectionEnemy`, `TargetDirectionFriend`, `TargetNearest`, `TargetNearestEnemyPlayer`, `TargetNearestFriendPlayer` | | [TaxiMap](docs/API.md#taximap) | `C_TaxiMap.GetTaxiNodesForMap`, `C_TaxiMap.GetAllTaxiNodes`, `C_TaxiMap.GetTaxiPaths`, `C_TaxiMap.GetTaxiPathWaypoints`, `C_TaxiMap.GetTaxiRoute` | +| [Texture](docs/API.md#texture) | `C_Texture.GetAtlasElementID`, `C_Texture.GetAtlasElements`, `C_Texture.GetAtlasExists`, `C_Texture.GetAtlasID`, `C_Texture.GetAtlasInfo`, `C_Texture.RegisterAtlas` | | [Time](docs/API.md#time) | `C_DateAndTime.AdjustTimeByDays`, `C_DateAndTime.AdjustTimeByMinutes`, `C_DateAndTime.CompareCalendarTime`, `C_DateAndTime.GetCalendarTimeFromEpoch`, `C_DateAndTime.GetCurrentCalendarTime`, `C_DateAndTime.GetSecondsUntilDailyReset`, `C_DateAndTime.GetServerTimeLocal`, `C_Timer.After`, `C_Timer.NewTicker`, `C_Timer.NewTimer`, `GetServerTime`, `GetTimeCached` | | [Totem](docs/API.md#totem) | `GetTotemInfo`, `GetTotemTimeLeft`, `GetTotemDuration`, `TargetTotem` | | [Tracking](docs/API.md#tracking) | `GetNumTrackingTypes`, `GetTrackingInfo`, `SetTracking` | diff --git a/docs/API.md b/docs/API.md index 616f1c84..f3281fb6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -199,6 +199,8 @@ build instructions. - [`texture:GetNumMaskTextures()`](#texturegetnummasktextures) - [`texture:GetMaskTexture(index)`](#texturegetmasktextureindex) - [`texture:SetColorTexture(colorR, colorG, colorB [, a])`](#texturesetcolortexturecolorr-colorg-colorb--a) + - [`texture:SetAtlas(atlas [, useAtlasSize])`](#texturesetatlasatlas--useatlassize) + - [`texture:GetAtlas()`](#texturegetatlas) - [Texture size and shape](#texture-size-and-shape) - [`fontstring:SetRotation(angle [, cx, cy])`](#fontstringsetrotationangle--cx-cy) - [`editBox:SetCursorPosition(position)`](#editboxsetcursorpositionposition) @@ -603,6 +605,15 @@ build instructions. - [`C_TaxiMap.GetTaxiPathWaypoints(pathID)`](#c_taximapgettaxipathwaypointspathid) - [`C_TaxiMap.GetTaxiRoute(slotIndex)`](#c_taximapgettaxiroutepslotindex) +- [Texture](#texture) + - [`C_Texture.GetAtlasInfo(atlasName)`](#c_texturegetatlasinfoatlasname) + - [`C_Texture.GetAtlasExists(atlasName)`](#c_texturegetatlasexistsatlasname) + - [`C_Texture.GetAtlasID(atlasName)`](#c_texturegetatlasidatlasname) + - [`C_Texture.GetAtlasElementID(atlasName)`](#c_texturegetatlaselementidatlasname) + - [`C_Texture.GetAtlasElements()`](#c_texturegetatlaselements) + - [`C_Texture.RegisterAtlas(name, file, width, height, left, right, top, bottom [, tilesHorizontally, tilesVertically])`](#c_textureregisteratlasname-file-width-height-left-right-top-bottom--tileshorizontally-tilesvertically) + - [Atlas markup](#atlas-markup) + - [Time](#time) - [`GetServerTime()`](#getservertime) - [`GetTimeCached()`](#gettimecached) @@ -4697,6 +4708,30 @@ Returns the number of masks attached to this texture. Returns the mask at `index` (1 is the first one added), or `nil` when there is no mask at that index. +### `texture:SetAtlas(atlas [, useAtlasSize])` + +Points the texture at a named piece of art. This sets the texture file and the +coordinates of the rectangle inside it, so one call replaces a `SetTexture` and a +`SetTexCoord`. See [Texture](#texture) for the atlas names and for +`C_Texture.RegisterAtlas`. + +Pass `true` for `useAtlasSize` to also resize the texture to the art's own pixel +size. Any further arguments are accepted and ignored. + +When the name is not known, the texture keeps whatever it was showing. Call +`_classicapi_DumpAtlasMisses()` to list the names that were asked for and not +found. + +```lua +local t = frame:CreateTexture(nil, "ARTWORK") +t:SetAtlas("MinimapArrow", true) -- draws the art at its own 32x32 size +``` + +### `texture:GetAtlas()` + +Returns the atlas name last set on this texture, or `nil` when it is showing +something else. Pointing the texture at a file with `SetTexture` clears the name. + ### Texture size and shape A texture can have any width and any height. The two sides do not need to be @@ -14424,6 +14459,115 @@ Pairs with `GetTaxiPaths` (each consecutive `(from, to)` names a `pathID`) and `GetTaxiPathWaypoints` (that path's geometry) to measure a chained trip without matching flight-map pixel coordinates back to nodes. +## Texture + +An atlas is a name for one piece of art. The name points to a texture file and to +a rectangle inside that file. `texture:SetAtlas(name)` applies both in one step, +so you never write the coordinates at the call site. + +ClassicAPI ships a small set of built-in atlas names. Call +`C_Texture.GetAtlasElements()` to list them. To use your own art, describe it once +with `C_Texture.RegisterAtlas` and then set it by name like any other atlas. + +Atlas names are not case sensitive. + +### `C_Texture.GetAtlasInfo(atlasName)` + +Returns a table that describes the atlas, or `nil` when the name is not known. + +Table fields: + +| Field | Type | Notes | +|-------|------|-------| +| `elementName` | string | The name in its canonical spelling. | +| `width` | number | Width of the art in pixels. | +| `height` | number | Height of the art in pixels. | +| `leftTexCoord` | number | Left edge of the rectangle, from 0 to 1. | +| `rightTexCoord` | number | Right edge of the rectangle, from 0 to 1. | +| `topTexCoord` | number | Top edge of the rectangle, from 0 to 1. | +| `bottomTexCoord` | number | Bottom edge of the rectangle, from 0 to 1. | +| `tilesHorizontally` | boolean | True when the art repeats across its width. | +| `tilesVertically` | boolean | True when the art repeats down its height. | +| `filename` | string | Path of the texture that holds the art. | + +Textures are named by path, so `filename` carries the texture and the `file` field +is not set. + +```lua +local info = C_Texture.GetAtlasInfo("Repair") +print(info.filename, info.width, info.height) +``` + +### `C_Texture.GetAtlasExists(atlasName)` + +Returns `true` when the name is known and `false` when it is not. This agrees with +`GetAtlasInfo` at all times. A name that exists always returns a table. + +### `C_Texture.GetAtlasID(atlasName)` + +Returns the id of the sheet that holds the atlas, or `nil` when the name is not +known. A built-in atlas has a positive id. An atlas you add with +`C_Texture.RegisterAtlas` gets a negative id, so the two kinds never collide. + +### `C_Texture.GetAtlasElementID(atlasName)` + +Returns the id of this one piece of art, or `nil` when the name is not known. The +same positive and negative rule applies. + +### `C_Texture.GetAtlasElements()` + +Returns an array of every atlas name that is currently known, in alphabetical +order. The list includes the names you registered yourself. + +```lua +for _, name in ipairs(C_Texture.GetAtlasElements()) do + print(name) +end +``` + +### `C_Texture.RegisterAtlas(name, file, width, height, left, right, top, bottom [, tilesHorizontally, tilesVertically])` + +A ClassicAPI extension. Adds an atlas name that points at your own art, so +`SetAtlas` and atlas markup work with a sprite sheet you ship yourself. + +- `name` — the atlas name callers will use. +- `file` — texture path, without the file extension. +- `width`, `height` — size of the art in pixels, used by `useAtlasSize`. +- `left`, `right`, `top`, `bottom` — the rectangle inside the file, from 0 to 1. + +Registering a name a second time replaces its definition and keeps its ids, so a +caller that stored an id keeps a valid one. Returns `true`. + +```lua +-- One 32x32 cell from the top-left of a 128x128 sheet. +C_Texture.RegisterAtlas("myaddon-gem", "Interface\\AddOns\\MyAddon\\sheet", + 32, 32, 0, 0.25, 0, 0.25) + +myTexture:SetAtlas("myaddon-gem", true) +``` + +### Atlas markup + +`|A:atlasName:height:width|a` draws an atlas inside any text, next to the +`|T…|t` form that draws a texture path. Use it in chat messages, tooltip lines, +and font strings. + +- A `height` of `0` uses the atlas's own pixel height. +- A `width` of `0` keeps the atlas's own shape at the height you asked for. +- Two more fields shift the art from the text, as `|A:name:h:w:offsetX:offsetY|a`. + +```lua +print("Repair cost: |A:Repair:0:0|a") +print("Small marker |A:MinimapArrow:12:12|a here") +``` + +An unknown name draws nothing and leaves the rest of the line intact. Art that +repeats is drawn once, so `tilesHorizontally` and `tilesVertically` have no effect +in text. + +Text typed by other players never draws atlas art. This matches how a typed +texture path behaves. + ## Time ### `GetServerTime()` diff --git a/docs/InlineTextureEscapes.md b/docs/InlineTextureEscapes.md index d974035d..8ade2fa4 100644 --- a/docs/InlineTextureEscapes.md +++ b/docs/InlineTextureEscapes.md @@ -556,9 +556,26 @@ Render the modern inline-texture escape (warcraft.wiki.gg/wiki/UI_escape_sequenc |Tpath:height[:width[:offsetX:offsetY[:texWidth:texHeight:left:right:top:bottom[:rV:gV:bV]]]]|t ``` -Atlas markup (`|A:atlas:…|a`) is Legion+ (needs an atlas DB 1.12 lacks) — out -of scope. FileDataID paths are Legion+ — 1.12 resolves texture PATH strings -only. +Atlas markup is also supported: + +``` +|A:atlasName:height:width[:offsetX:offsetY]|a +``` + +It shares every scanner, measure, wrap and placement stage with `|T` — only the +payload parser differs. `ParseAtlasIcon` resolves the name through +`Texture::Atlas` and fills the SAME `IconDesc`, because an atlas is exactly the +"path + normalized sub-rect" that struct already carries for a `|T` span with +texcoords. A `height`/`width` of `0` resolves to the atlas's own pixel size at +PARSE time (not the line font height `|T` falls back to), which is what keeps the +rest of the pipeline marker-agnostic. Tiling atlases draw one quad, so +`tilesHorizontally` / `tilesVertically` are not honored here. + +Adding any further marker means touching `IconStartLen`, `FindIconClose`, +`InlineSpanLen`, the ghost guard in `FlushLayout` — and, mandatory, +`chat/IconFilter.cpp`, or the marker becomes a chat-spoof vector. + +FileDataID paths are Legion+ — 1.12 resolves texture PATH strings only. ## Confirmed: 1.12 has ZERO inline-texture support diff --git a/src/Offsets.h b/src/Offsets.h index d2e3d32d..c0784956 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -474,6 +474,13 @@ enum Offsets { // handler as the 7.0 `SetColorTexture` (which IS exactly the numeric form), so // the clamp and opaque-alpha default come straight from the engine. FUN_SCRIPT_TEXTURE_SET_TEXTURE = 0x0079BB40, + // Script_Texture_SetTexCoord — the Lua `texture:SetTexCoord(...)` handler + // (entry 17 of the Texture method batch at 0x0087C128). Takes the 4-arg + // (left, right, top, bottom) and 8-arg corner forms and writes through to + // FUN_SIMPLETEXTURE_SET_TEXCOORD below. texture/Atlas.cpp delegates to this + // handler rather than the native setter so an atlas set inherits the engine's + // own arg validation and both coordinate forms. + FUN_SCRIPT_TEXTURE_SET_TEXCOORD = 0x0079BEB0, // CSimpleTexture::SetTexCoord — `__thiscall(tex, float[4])`. Struct field // order is {top, left, bottom, right} = {v0, u0, v1, u1} (verified from the // SetTexCoord handler 0x0079BEB0's Lua-arg → struct mapping). Natural diff --git a/src/chat/IconFilter.cpp b/src/chat/IconFilter.cpp index 8545aaa9..244c3e92 100644 --- a/src/chat/IconFilter.cpp +++ b/src/chat/IconFilter.cpp @@ -11,28 +11,32 @@ // You should have received a copy of the GNU General Public License along with // ClassicAPI. If not, see . -// Inline-texture (`|T`) chat anti-spoof. +// Inline-texture (`|T`, `|A`) chat anti-spoof. // // Vanilla neutralizes player-*typed* escapes in chat (a typed `|cff…|r`, // `|Hitem…|h` or `|T…|t` shows as raw text) — only *trusted* text renders them // (addon `AddMessage`, shift-clicked links). Our Text::InlineTexture backport -// breaks that parity for `|T` alone: it detects the neutralized `||T` form and -// draws the icon anyway, so a player could `/say` `|Tpath|t` and have a real -// icon appear in everyone's chat AND in the speech bubble over their head. +// breaks that parity for the two texture markers: it detects the neutralized +// `||T` / `||A` form and draws the art anyway, so a player could `/say` +// `|Tpath|t` and have a real icon appear in everyone's chat AND in the speech +// bubble over their head. // -// This restores vanilla's behavior for `|T` by defanging it in the chat path, -// while leaving `|c`/`|r`/`|H`/`|h` exactly as vanilla (already raw for typed -// input). It CANNOT be done in 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're distinguishable is the source — -// server-delivered chat flows through the chat dispatcher, addon `print` does -// not. Chat::Dispatch owns that hook and calls this on the message. +// This restores vanilla's behavior for both markers by defanging them in the +// chat path, while leaving `|c`/`|r`/`|H`/`|h` exactly as vanilla (already raw +// for typed input). It CANNOT be done in the text emitter: addon `|T` and player +// `|T` reach the emitter as byte-identical `||T` (vanilla doubles the +// unrecognized escape for both), so the only place they're distinguishable is +// the source — server-delivered chat flows through the chat dispatcher, addon +// `print` does not. Chat::Dispatch owns that hook and calls this on the message. // -// Defang = replace the `|` of each `|T` with a space, breaking the pipe→T +// Defang = replace the `|` of each opener with a space, breaking the pipe→letter // adjacency the inline-texture detector keys on (`|T` and `||T` both contain the -// `|T` substring, so this catches the doubled form too). The path text stays -// readable, the closer `|t` is inert without an opener, and every other escape -// is untouched. +// `|T` substring, so this catches the doubled form too). The payload text stays +// readable, the closer is inert without an opener, and every other escape is +// untouched. +// +// ANY new marker the emitter learns MUST be added here in the same change, or it +// becomes a chat-spoof vector. #include "IconFilter.h" @@ -40,10 +44,16 @@ namespace Chat::IconFilter { namespace { -// True if `s` contains an inline-texture opener (`|T`) anywhere. +// True if `s` contains an inline-texture opener anywhere. Both markers count: +// `|T` names a texture path and `|A` names an atlas, and either one would render +// art from player-typed text if it survived to the fontstring. +bool IsIconOpener(const char *s) { + return s[0] == '|' && (s[1] == 'T' || s[1] == 'A'); +} + bool HasIconEscape(const char *s) { for (; *s != '\0'; ++s) - if (s[0] == '|' && s[1] == 'T') + if (IsIconOpener(s)) return true; return false; } @@ -68,12 +78,12 @@ const char *Sanitize(const char *msg, char *buf, size_t bufSize) { // opener survives for the inline-texture detector to fire on. size_t j = 0; for (size_t i = 0; msg[i] != '\0' && j + 1 < bufSize;) { - if (msg[i] == '|' && msg[i + 1] == 'T') { + if (IsIconOpener(msg + i)) { const bool doubledPipe = (i > 0 && msg[i - 1] == '|'); buf[j++] = doubledPipe ? '|' : ' '; // keep pipe only if it completes `||` if (j + 1 < bufSize) - buf[j++] = ' '; // blank the `T` - i += 2; // consumed `|T` + buf[j++] = ' '; // blank the `T` / `A` + i += 2; // consumed the opener } else { buf[j++] = msg[i++]; } diff --git a/src/clipboard/Copy.cpp b/src/clipboard/Copy.cpp index 06db5034..aa4b4249 100644 --- a/src/clipboard/Copy.cpp +++ b/src/clipboard/Copy.cpp @@ -86,13 +86,18 @@ std::string StripMarkup(const char *s, unsigned len) { ++i; break; // the |h is dropped by the 'h' case on the next iteration case 't': // stray texture closer — drop + case 'a': // stray atlas closer — drop i += 2; break; case 'T': // texture opener — skip through to the next |t + case 'A': // atlas opener — skip through to the next |a + { + const char closer = (s[i + 1] == 'A') ? 'a' : 't'; i += 2; - while (i < len && !(s[i] == '|' && i + 1 < len && s[i + 1] == 't')) + while (i < len && !(s[i] == '|' && i + 1 < len && s[i + 1] == closer)) ++i; - break; // the |t is dropped by the 't' case on the next iteration + break; // the closer is dropped by the 't'/'a' case next iteration + } default: // unknown sequence — keep the pipe literally out.push_back('|'); ++i; diff --git a/src/text/InlineTexture.cpp b/src/text/InlineTexture.cpp index ac5bb924..7c10a41b 100644 --- a/src/text/InlineTexture.cpp +++ b/src/text/InlineTexture.cpp @@ -11,12 +11,22 @@ // You should have received a copy of the GNU General Public License along with // ClassicAPI. If not, see . -// Inline texture escape (`|Tpath:height:width:...|t`) backport. +// Inline texture escape (`|Tpath:height:width:...|t`) backport, plus its atlas +// sibling (`|A:atlasName:height:width[:offsetX:offsetY]|a`). // // 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. // +// The two markers share EVERYTHING except the payload parser. An atlas is a +// texture path plus a normalized sub-rect, which is exactly what IconDesc already +// carries for a `|T` span with texcoords, so `ParseAtlasIcon` resolves the name +// through Texture::Atlas and fills the same struct — every scanner, measure, wrap, +// record and placement stage below is marker-agnostic from that point on. Adding +// a THIRD marker means touching IconStartLen / FindIconClose / InlineSpanLen, the +// ghost guard in FlushLayout, and — mandatory — the chat anti-spoof in +// chat/IconFilter.cpp, which is what stops a player rendering art by typing it. +// // 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 @@ -63,6 +73,7 @@ #include "Offsets.h" #include "text/InlineTexturePool.h" #include "text/PtrProbe.h" +#include "texture/Atlas.h" #include "texture/Transform.h" #include @@ -176,6 +187,70 @@ bool ParseIcon(const char *payload, size_t len, IconDesc &out) { return true; } +// Parses the payload between `|A` and `|a` — `atlasName:height:width[:offsetX:offsetY]` +// — into the SAME IconDesc a `|T` span produces, so every stage after this point +// (measure, wrap, record, placement, texcoord) is shared between the two markers. +// An atlas is exactly "a path plus a normalized sub-rect", which is what IconDesc +// already carries. Returns false when the name is unbound, and the span then +// renders as ordinary text. +bool ParseAtlasIcon(const char *payload, size_t len, IconDesc &out) { + const char *end = payload + len; + // The marker is `|A` and the retail payload is `:name:h:w…`, so the name is + // the first field AFTER a leading colon — unlike `|T`, whose path starts + // immediately. Consuming that colon here is what makes the two forms differ. + const char *nameStart = payload; + if (nameStart < end && *nameStart == ':') + ++nameStart; + const char *colon = nameStart; + while (colon < end && *colon != ':') + ++colon; + if (colon == nameStart) + return false; // no name + const std::string name(nameStart, static_cast(colon - nameStart)); + + const Texture::Atlas::Info *info = Texture::Atlas::Find(name.c_str()); + if (info == nullptr) { + Texture::Atlas::RecordMiss(name.c_str()); + return false; + } + out.path = info->file; + out.u0 = info->left; + out.u1 = info->right; + out.v0 = info->top; + out.v1 = info->bottom; + + float f[4] = {0}; + int nf = 0; + const char *p = (colon < end) ? colon + 1 : end; + while (p < end && nf < 4) { + const char *nx = p; + f[nf++] = ParseField(p, end, &nx); + p = nx; + } + // An omitted or 0 height means "the atlas's own pixel size" — resolved HERE, + // not deferred to the line font height the `|T` path falls back to. Doing it + // at parse time is what keeps the rest of the pipeline identical for both. + const float nativeH = info->height; + const float nativeW = info->width; + out.height = (nf >= 1 && f[0] > 0.0f) ? f[0] : nativeH; + if (out.height <= 0.0f) + return false; // no usable size anywhere → nothing to draw + if (nf >= 2 && f[1] > 0.0f) + out.width = f[1]; + else if (nativeH > 0.0f && nativeW > 0.0f) + out.width = out.height * (nativeW / nativeH); // keep the atlas's aspect + else + out.width = out.height; + out.offsetX = (nf >= 3) ? f[2] : 0.0f; + out.offsetY = (nf >= 4) ? f[3] : 0.0f; + return true; +} + +// Parses a span's payload with the parser its marker kind calls for. +bool ParseIconSpan(const char *payload, size_t len, char kind, IconDesc &out) { + return (kind == 'A') ? ParseAtlasIcon(payload, len, out) : ParseIcon(payload, len, out); +} + // --- per-node recorded icons ----------------------------------------------- // One icon to draw, in the render node's node-local coordinate space (the same @@ -526,12 +601,25 @@ constexpr float g_iconPadFrac = 0.18f; // 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; +// `outKind` (optional) receives the marker letter — 'T' for a path span, 'A' for +// an atlas span (`|A:name:h:w|a`), whose name resolves through Texture::Atlas. +// Both markers share every scanner and every downstream stage; only the payload +// parser differs. +int IconStartLen(const uint8_t *text, int len, int i, char *outKind = nullptr) { + char kind = 0; + int mlen = 0; + if (i + 2 < len && text[i] == '|' && text[i + 1] == '|' && + (text[i + 2] == 'T' || text[i + 2] == 'A')) { + kind = static_cast(text[i + 2]); + mlen = 3; + } else if (i + 1 < len && text[i] == '|' && + (text[i + 1] == 'T' || text[i + 1] == 'A')) { + kind = static_cast(text[i + 1]); + mlen = 2; + } + if (mlen != 0 && outKind != nullptr) + *outKind = kind; + return mlen; } // True if [text,text+len) contains any inline-texture escape. @@ -544,17 +632,19 @@ bool HasInlineTexture(const uint8_t *text, int len) { // 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) { +size_t FindIconClose(const uint8_t *text, int len, size_t from, bool doubled, int *closeLen, + char kind = 'T') { const size_t n = static_cast(len); + const uint8_t closer = (kind == 'A') ? 'a' : 't'; // the marker's own closer if (doubled) { for (size_t i = from; i + 2 < n; ++i) - if (text[i] == '|' && text[i + 1] == '|' && text[i + 2] == 't') { + if (text[i] == '|' && text[i + 1] == '|' && text[i + 2] == closer) { *closeLen = 3; return i; } } else { for (size_t i = from; i + 1 < n; ++i) - if (text[i] == '|' && text[i + 1] == 't') { + if (text[i] == '|' && text[i + 1] == closer) { *closeLen = 2; return i; } @@ -567,19 +657,20 @@ size_t FindIconClose(const uint8_t *text, int len, size_t from, bool doubled, in // 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 + if (text[0] == '|' && text[1] == '|' && (text[2] == 'T' || text[2] == 'A')) + mlen = 3; // doubled ||T / ||A + else if (text[0] == '|' && (text[1] == 'T' || text[1] == 'A')) + mlen = 2; // clean |T / |A else return 0; const bool doubled = (mlen == 3); + const uint8_t closer = (text[mlen - 1] == 'A') ? 'a' : 't'; for (int i = mlen; i < 2048 && text[i] != '\0'; ++i) { if (doubled) { - if (text[i] == '|' && text[i + 1] == '|' && text[i + 2] == 't') + if (text[i] == '|' && text[i + 1] == '|' && text[i + 2] == closer) return i + 3; } else { - if (text[i] == '|' && text[i + 1] == 't') + if (text[i] == '|' && text[i + 1] == closer) return i + 2; } } @@ -638,7 +729,8 @@ float SumIconAdvances(const uint8_t *text, int len, float fontHPen, float outlin float sum = 0.0f; int i = 0; while (i < len) { - const int ml = IconStartLen(text, len, i); + char kind = 'T'; + const int ml = IconStartLen(text, len, i, &kind); 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). @@ -649,12 +741,13 @@ float SumIconAdvances(const uint8_t *text, int len, float fontHPen, float outlin continue; } int cl = 0; - const size_t ce = FindIconClose(text, len, static_cast(i) + ml, ml == 3, &cl); + const size_t ce = + FindIconClose(text, len, static_cast(i) + ml, ml == 3, &cl, kind); if (ce == static_cast(-1)) break; // unterminated → the rest is plain text IconDesc d; - if (ParseIcon(reinterpret_cast(text) + i + ml, - ce - (static_cast(i) + ml), d)) + if (ParseIconSpan(reinterpret_cast(text) + i + ml, + ce - (static_cast(i) + ml), kind, d)) sum += IconAdvancePen(d, fontHPen, outlineInk, snap); i = static_cast(ce) + cl; } @@ -676,7 +769,8 @@ float TrailingIconTrimPen(const uint8_t *text, int len, float fontHPen, float ou int i = 0; bool endsInIcon = false; while (i < len) { - const int ml = IconStartLen(text, len, i); + char kind = 'T'; + const int ml = IconStartLen(text, len, i, &kind); if (ml == 0) { if (text[i] == '|' && i + 1 < len && text[i + 1] == '|') i += 2; @@ -686,12 +780,13 @@ float TrailingIconTrimPen(const uint8_t *text, int len, float fontHPen, float ou continue; } int cl = 0; - const size_t ce = FindIconClose(text, len, static_cast(i) + ml, ml == 3, &cl); + const size_t ce = + FindIconClose(text, len, static_cast(i) + ml, ml == 3, &cl, kind); if (ce == static_cast(-1)) return 0.0f; // unterminated → the tail renders as plain text IconDesc d; - endsInIcon = ParseIcon(reinterpret_cast(text) + i + ml, - ce - (static_cast(i) + ml), d); + endsInIcon = ParseIconSpan(reinterpret_cast(text) + i + ml, + ce - (static_cast(i) + ml), kind, d); i = static_cast(ce) + cl; } if (!endsInIcon) @@ -710,7 +805,8 @@ 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); + char kind = 'T'; + const int ml = IconStartLen(text, len, i, &kind); if (ml == 0) { if (text[i] == '|' && i + 1 < len && text[i + 1] == '|') i += 2; @@ -719,12 +815,13 @@ float MaxIconOverflowPx(const uint8_t *text, int len, float fontHPx) { continue; } int cl = 0; - const size_t ce = FindIconClose(text, len, static_cast(i) + ml, ml == 3, &cl); + const size_t ce = + FindIconClose(text, len, static_cast(i) + ml, ml == 3, &cl, kind); if (ce == static_cast(-1)) break; IconDesc d; - if (ParseIcon(reinterpret_cast(text) + i + ml, - ce - (static_cast(i) + ml), d)) { + if (ParseIconSpan(reinterpret_cast(text) + i + ml, + ce - (static_cast(i) + ml), kind, d)) { const float h = ((d.height > 0.0f) ? d.height : fontHPx) * g_sizeScale; if (h > maxH) maxH = h; @@ -1551,7 +1648,8 @@ void __fastcall Emitter_h(void *node, void *edx, uint8_t *text, int len, uint32_ ++i; continue; } - int mlen = IconStartLen(text, len, i); + char kind = 'T'; + int mlen = IconStartLen(text, len, i, &kind); 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. @@ -1563,7 +1661,8 @@ void __fastcall Emitter_h(void *node, void *edx, uint8_t *text, int len, uint32_ } const bool doubled = (mlen == 3); int closeLen = 0; - size_t close = FindIconClose(text, len, static_cast(i) + mlen, doubled, &closeLen); + size_t close = + FindIconClose(text, len, static_cast(i) + mlen, doubled, &closeLen, kind); if (close == static_cast(-1)) { // Unterminated on this line — treat the rest as plain text. break; @@ -1574,8 +1673,9 @@ void __fastcall Emitter_h(void *node, void *edx, uint8_t *text, int len, uint32_ IconDesc d; const char *payload = reinterpret_cast(text) + i + mlen; size_t payloadLen = close - (static_cast(i) + mlen); - if (ParseIcon(payload, payloadLen, d)) { - // height/width of 0 => size to the line's font (retail :0:0). + if (ParseIconSpan(payload, payloadLen, kind, d)) { + // height/width of 0 => size to the line's font (retail :0:0). An + // atlas span has already resolved its own size at parse time. 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; @@ -1766,7 +1866,7 @@ void FlushLayout(void *layout) { bool fsHasMarkup = false; if (LooksReadable(ftext)) { for (int k = 1; k < 2048 && ftext[k] != '\0'; ++k) - if (ftext[k] == 'T' && ftext[k - 1] == '|') { + if ((ftext[k] == 'T' || ftext[k] == 'A') && ftext[k - 1] == '|') { fsHasMarkup = true; break; } diff --git a/src/texture/Atlas.cpp b/src/texture/Atlas.cpp new file mode 100644 index 00000000..48e18889 --- /dev/null +++ b/src/texture/Atlas.cpp @@ -0,0 +1,381 @@ +// 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. + +// The atlas system: `C_Texture.GetAtlasInfo` / `GetAtlasExists` / `GetAtlasID` / +// `GetAtlasElementID` / `GetAtlasElements`, `C_Texture.RegisterAtlas`, and the +// `texture:SetAtlas` / `texture:GetAtlas` widget methods. +// +// An atlas names a texture plus a sub-rect inside it, so `SetAtlas` is exactly the +// two calls 1.12 already has — SetTexture then SetTexCoord — driven off one name. +// Both are performed by delegating to the engine's OWN Lua handlers rather than +// the native setters, so every argument guard and the UI-scale conversion behind +// the size setters stay in force; the only thing this module adds is the name +// lookup. `AtlasData.h` explains where the built-in bindings come from. +// +// All five readers key off the same bound set, so `GetAtlasExists` is true exactly +// when `GetAtlasInfo` returns a table. There is no state where one disagrees. + +#include "Atlas.h" + +#include "AtlasData.h" + +#include "Game.h" +#include "Offsets.h" +#include "debug/Log.h" + +#include +#include +#include +#include +#include + +namespace Texture::Atlas { + +namespace { + +using ScriptFn_t = int(__fastcall *)(void *L); + +int CallScript(uintptr_t fn, void *L) { return reinterpret_cast(fn)(L); } + +std::string Lower(const char *s) { + std::string out; + if (s == nullptr) + return out; + for (const char *p = s; *p != '\0'; ++p) { + char c = *p; + if (c >= 'A' && c <= 'Z') + c = static_cast(c - 'A' + 'a'); + out.push_back(c); + } + return out; +} + +// The whole registry, keyed by lowercased name. `std::map` node storage means an +// `Info *` handed out by `Find` stays valid as later atlases are registered. +std::map &Registry() { + static std::map registry; + static bool seeded = false; + if (!seeded) { + seeded = true; + for (int i = 0; i < AtlasData::kAtlasCount; ++i) { + const AtlasData::Entry &e = AtlasData::kAtlases[i]; + Info info; + info.name = e.name; + info.file = e.file; + info.width = static_cast(e.width); + info.height = static_cast(e.height); + info.left = e.left; + info.right = e.right; + info.top = e.top; + info.bottom = e.bottom; + info.atlasID = e.atlasID; + info.elementID = e.elementID; + info.tilesHorizontally = e.tilesHorizontally; + info.tilesVertically = e.tilesVertically; + registry[Lower(e.name)] = info; + } + } + return registry; +} + +// Names asked for that nothing could resolve. Bounded so a misbehaving addon +// calling SetAtlas in an OnUpdate can't grow it without limit. +constexpr size_t kMaxMisses = 512; +std::set g_misses; + +// `texture:GetAtlas` bookkeeping: which atlas a region was last set to, and the +// HTEXTURE that set installed. Comparing the stored handle against the region's +// current one on read means a plain `SetTexture` afterwards correctly clears the +// atlas — and a recycled region can't report a stale name either, which is what +// lets this module skip a `FUN_SIMPLETEXTURE_CTOR` hook. It must skip one: +// `Texture::Mask` already owns that target, and MinHook refuses a duplicate, +// which would abort the entire hook install. +struct Applied { + std::string name; + void *hTexture = nullptr; +}; +std::unordered_map g_applied; + +void *RegionTexture(void *region) { + if (region == nullptr) + return nullptr; + return *reinterpret_cast(static_cast(region) + + Offsets::OFF_SIMPLETEXTURE_HTEXTURE); +} + +// Synthetic ids for addon-registered atlases, counting down from -1 so they can +// never be mistaken for one of Blizzard's (see Info's comment). +int g_nextSyntheticID = -1; + +// --- C_Texture readers ------------------------------------------------------ + +int __fastcall Script_GetAtlasInfo(void *L) { + if (!Game::Lua::IsString(L, 1)) + return 0; + const Info *info = Find(Game::Lua::ToString(L, 1)); + if (info == nullptr) { + RecordMiss(Game::Lua::ToString(L, 1)); + return 0; + } + + Game::Lua::NewTable(L); + Game::Lua::SetFieldString(L, "elementName", info->name.c_str()); + Game::Lua::SetFieldNumber(L, "width", info->width); + Game::Lua::SetFieldNumber(L, "height", info->height); + Game::Lua::SetFieldNumber(L, "leftTexCoord", info->left); + Game::Lua::SetFieldNumber(L, "rightTexCoord", info->right); + Game::Lua::SetFieldNumber(L, "topTexCoord", info->top); + Game::Lua::SetFieldNumber(L, "bottomTexCoord", info->bottom); + Game::Lua::SetFieldBool(L, "tilesHorizontally", info->tilesHorizontally); + Game::Lua::SetFieldBool(L, "tilesVertically", info->tilesVertically); + // `filename` carries the texture. `file` is a fileDataID, and 1.12 has no + // such id space at all, so it is left absent rather than filled with a value + // that would not resolve — both fields are optional in the contract. + Game::Lua::SetFieldString(L, "filename", info->file.c_str()); + return 1; +} + +int __fastcall Script_GetAtlasExists(void *L) { + const bool exists = + Game::Lua::IsString(L, 1) && Find(Game::Lua::ToString(L, 1)) != nullptr; + Game::Lua::PushBool(L, exists); + return 1; +} + +int __fastcall Script_GetAtlasID(void *L) { + if (!Game::Lua::IsString(L, 1)) + return 0; + const Info *info = Find(Game::Lua::ToString(L, 1)); + if (info == nullptr) + return 0; + Game::Lua::PushNumber(L, info->atlasID); + return 1; +} + +int __fastcall Script_GetAtlasElementID(void *L) { + if (!Game::Lua::IsString(L, 1)) + return 0; + const Info *info = Find(Game::Lua::ToString(L, 1)); + if (info == nullptr) + return 0; + Game::Lua::PushNumber(L, info->elementID); + return 1; +} + +int __fastcall Script_GetAtlasElements(void *L) { + Game::Lua::SetTop(L, 0); + Game::Lua::NewTable(L); + int n = 0; + for (const auto &pair : Registry()) { + Game::Lua::PushNumber(L, ++n); + Game::Lua::PushString(L, pair.second.name.c_str()); + Game::Lua::SetTable(L, -3); + } + return 1; +} + +// `C_Texture.RegisterAtlas(name, file, width, height, left, right, top, bottom +// [, tilesHorizontally, tilesVertically])` +// A ClassicAPI extension: it publishes an addon's own sprite sheet under atlas +// names, which is the case that needs no built-in binding to work. +int __fastcall Script_RegisterAtlas(void *L) { + if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsString(L, 2)) { + Game::Lua::Error(L, "Usage: C_Texture.RegisterAtlas(name, file, width, height, " + "left, right, top, bottom [, tilesH, tilesV])"); + return 0; + } + + Info info; + info.name = Game::Lua::ToString(L, 1); + info.file = Game::Lua::ToString(L, 2); + info.width = static_cast(Game::Lua::ToNumber(L, 3)); + info.height = static_cast(Game::Lua::ToNumber(L, 4)); + if (Game::Lua::IsNumber(L, 5)) + info.left = static_cast(Game::Lua::ToNumber(L, 5)); + if (Game::Lua::IsNumber(L, 6)) + info.right = static_cast(Game::Lua::ToNumber(L, 6)); + if (Game::Lua::IsNumber(L, 7)) + info.top = static_cast(Game::Lua::ToNumber(L, 7)); + if (Game::Lua::IsNumber(L, 8)) + info.bottom = static_cast(Game::Lua::ToNumber(L, 8)); + info.tilesHorizontally = Game::Lua::ToBoolean(L, 9) != 0; + info.tilesVertically = Game::Lua::ToBoolean(L, 10) != 0; + + const std::string key = Lower(info.name.c_str()); + auto ®istry = Registry(); + auto existing = registry.find(key); + if (existing != registry.end()) { + // Re-registering a name keeps its ids stable, so a `/reload` that re-runs + // an addon's registration doesn't renumber anything behind a caller that + // cached the id. + info.atlasID = existing->second.atlasID; + info.elementID = existing->second.elementID; + } else { + info.atlasID = g_nextSyntheticID; + info.elementID = g_nextSyntheticID; + --g_nextSyntheticID; + } + registry[key] = info; + + g_misses.erase(key); + Game::Lua::PushBool(L, true); + return 1; +} + +// --- texture:SetAtlas / GetAtlas ------------------------------------------- + +// `texture:SetAtlas(atlas [, useAtlasSize, filterMode, resetTexCoords, +// wrapModeHorizontal, wrapModeVertical])` +// The trailing arguments are accepted and ignored: 1.12 texture regions have no +// filter or wrap mode to set, and dropping them silently is what lets modern call +// sites pass through unchanged. +int __fastcall Script_SetAtlas(void *L) { + void *region = Game::Lua::ResolveObject(L, 1); + if (region == nullptr) + return 0; + + if (!Game::Lua::IsString(L, 2)) { + // A nil atlas clears the binding without touching the texture, mirroring + // the unknown-name path below. + g_applied.erase(region); + return 0; + } + + const char *name = Game::Lua::ToString(L, 2); + const bool useAtlasSize = Game::Lua::ToBoolean(L, 3) != 0; + + const Info *info = Find(name); + if (info == nullptr) { + // Deliberately NOT retail behaviour, which clears the texture. With few + // built-in bindings a clear would make a ported frame vanish entirely and + // give the author nothing to look at; leaving the previous texture in + // place keeps the frame visible while the miss log says what to bind. + RecordMiss(name); + g_applied.erase(region); + return 0; + } + + // Reshaping the stack for each delegated handler leaves `info` untouched — it + // points into the registry, which none of these calls can reach. + Game::Lua::SetTop(L, 1); // (self) + Game::Lua::PushString(L, info->file.c_str()); + CallScript(Offsets::FUN_SCRIPT_TEXTURE_SET_TEXTURE, L); + + Game::Lua::SetTop(L, 1); // (self) + Game::Lua::PushNumber(L, info->left); + Game::Lua::PushNumber(L, info->right); + Game::Lua::PushNumber(L, info->top); + Game::Lua::PushNumber(L, info->bottom); + CallScript(Offsets::FUN_SCRIPT_TEXTURE_SET_TEXCOORD, L); + + if (useAtlasSize && info->width > 0.0f && info->height > 0.0f) { + Game::Lua::SetTop(L, 1); // (self) + Game::Lua::PushNumber(L, info->width); + CallScript(Offsets::FUN_SCRIPT_REGION_SETWIDTH, L); + Game::Lua::SetTop(L, 1); // (self) + Game::Lua::PushNumber(L, info->height); + CallScript(Offsets::FUN_SCRIPT_REGION_SETHEIGHT, L); + } + + Applied applied; + applied.name = info->name; + applied.hTexture = RegionTexture(region); + g_applied[region] = applied; + + Game::Lua::SetTop(L, 0); + return 0; +} + +// `texture:GetAtlas()` — the atlas last set on this texture, or nil if the +// texture has been pointed somewhere else since. +int __fastcall Script_GetAtlas(void *L) { + void *region = Game::Lua::ResolveObject(L, 1); + if (region == nullptr) + return 0; + auto it = g_applied.find(region); + if (it == g_applied.end()) + return 0; + if (RegionTexture(region) != it->second.hTexture) { + g_applied.erase(it); + return 0; + } + Game::Lua::PushString(L, it->second.name.c_str()); + return 1; +} + +// --- diagnostics ------------------------------------------------------------ + +// Returns every atlas name something asked for that nothing could resolve, and +// writes the same list to the debug log. This is the growth loop for the built-in +// table: load an addon, read what it really wanted, bind those names. +int __fastcall Script_DumpAtlasMisses(void *L) { + Game::Lua::SetTop(L, 0); + Game::Lua::NewTable(L); + int n = 0; + Debug::Log::Printf("[atlas] %d unresolved atlas name(s)", + static_cast(g_misses.size())); + for (const std::string &name : g_misses) { + Debug::Log::Printf("[atlas] %s", name.c_str()); + Game::Lua::PushNumber(L, ++n); + Game::Lua::PushString(L, name.c_str()); + Game::Lua::SetTable(L, -3); + } + return 1; +} + +// --- registration ----------------------------------------------------------- + +const Game::Lua::FrameMethodEntry g_textureMethods[] = { + {"SetAtlas", &Script_SetAtlas}, + {"GetAtlas", &Script_GetAtlas}, +}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterFrameMethods( + reinterpret_cast(Offsets::VAR_TEXTURE_METHOD_REGISTRY), g_textureMethods, + static_cast(sizeof(g_textureMethods) / sizeof(g_textureMethods[0]))); + + Game::Lua::RegisterTableFunction("C_Texture", "GetAtlasInfo", &Script_GetAtlasInfo); + Game::Lua::RegisterTableFunction("C_Texture", "GetAtlasExists", &Script_GetAtlasExists); + Game::Lua::RegisterTableFunction("C_Texture", "GetAtlasID", &Script_GetAtlasID); + Game::Lua::RegisterTableFunction("C_Texture", "GetAtlasElementID", + &Script_GetAtlasElementID); + Game::Lua::RegisterTableFunction("C_Texture", "GetAtlasElements", + &Script_GetAtlasElements); + Game::Lua::RegisterTableFunction("C_Texture", "RegisterAtlas", &Script_RegisterAtlas); + + Game::Lua::RegisterGlobalFunction("_classicapi_DumpAtlasMisses", &Script_DumpAtlasMisses); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; +const Game::ReloadAutoRegister _reloadReg{&PrepareForReload}; + +} // namespace + +const Info *Find(const char *name) { + if (name == nullptr || *name == '\0') + return nullptr; + auto ®istry = Registry(); + auto it = registry.find(Lower(name)); + return (it == registry.end()) ? nullptr : &it->second; +} + +void RecordMiss(const char *name) { + if (name == nullptr || *name == '\0' || g_misses.size() >= kMaxMisses) + return; + g_misses.insert(Lower(name)); +} + +void PrepareForReload() { + g_applied.clear(); + g_misses.clear(); +} + +} // namespace Texture::Atlas diff --git a/src/texture/Atlas.h b/src/texture/Atlas.h new file mode 100644 index 00000000..655eee9b --- /dev/null +++ b/src/texture/Atlas.h @@ -0,0 +1,65 @@ +// 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 . + +#pragma once + +#include + +// `Texture::Atlas` — the atlas name registry behind `C_Texture.*`, +// `texture:SetAtlas`, and the `|A:name:h:w|a` inline markup. An atlas is a name +// bound to a texture plus a sub-rect within it; resolving one is what lets a +// caller set both in a single step. See `AtlasData.h` for where the built-in +// bindings come from and why there are so few of them. +// +// The registry is seeded from that table on first use and extended at runtime by +// `C_Texture.RegisterAtlas`, so an addon that ships its own sprite sheet works +// without needing any binding here. +namespace Texture::Atlas { + +// One resolved atlas. Built-in and addon-registered entries normalize to this +// same shape, so every reader treats them identically. +struct Info { + std::string name; // canonical casing, reported as `elementName` + std::string file; // texture path + float width = 0.0f; + float height = 0.0f; + float left = 0.0f; + float right = 1.0f; + float top = 0.0f; + float bottom = 1.0f; + // Blizzard's own ids for a built-in entry. An addon-registered atlas has no + // Blizzard id, so it gets a NEGATIVE synthetic one — the same + // two-namespaces-in-one-int idiom `Map::Area` uses for uiMapIDs, which keeps + // the two spaces from ever colliding. + int atlasID = 0; + int elementID = 0; + bool tilesHorizontally = false; + bool tilesVertically = false; +}; + +// Resolves an atlas by name, case-insensitively. Null when the name is unbound. +// The returned pointer stays valid for the life of the process. +const Info *Find(const char *name); + +// Records an unresolved atlas name for `_classicapi_DumpAtlasMisses()`. This is +// how the built-in table grows: load a real addon, read what it actually asked +// for, bind those names instead of guessing at thousands. +void RecordMiss(const char *name); + +// Drops the per-region `GetAtlas` bookkeeping and the miss log before a +// `/reload`. Registered atlases are deliberately kept — addon Lua re-runs and +// re-registers by name, and holding the old entries keeps every name resolvable +// across the gap. +void PrepareForReload(); + +} // namespace Texture::Atlas diff --git a/src/texture/AtlasData.h b/src/texture/AtlasData.h new file mode 100644 index 00000000..90098140 --- /dev/null +++ b/src/texture/AtlasData.h @@ -0,0 +1,92 @@ +// 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 . + +#pragma once + +#include + +// Built-in atlas bindings, derived from `UiTextureAtlas` + `UiTextureAtlasMember` +// as shipped by Classic Era 1.15.9 (build 69547). Vanilla 1.12 has no atlas table +// at all, so a modern addon's `SetAtlas("name")` has nothing to resolve against; +// each row here binds one Blizzard atlas name to the 1.12 texture that carries the +// same art, plus the sub-rect within it. +// +// WHY THIS TABLE IS FIVE ROWS AND NOT FIVE THOUSAND +// +// The member table has 5,353 named regions. Almost none of them can be bound +// automatically, for three independent reasons established by measurement: +// +// 1. The sheets do not exist here. Resolving all 868 atlas sheet fileDataIDs +// through the community listfile and testing every path against the client's +// own art (7,640 files) gives ZERO hits — Classic Era repacked its art into +// sheets 1.12 has never shipped. +// 2. Only the names carry over. Blizzard kept the original vanilla filename as +// the atlas name when packing, so 16 member names match a 1.12 file basename. +// That is the entire mechanical overlap. +// 3. A matching name does not prove matching art. Comparing the real BLP headers +// against the member table's sprite sizes, only 5 of those 16 agree. +// `ui-scrollbar-scrollupbutton-up` is 18x16 in the atlas while the 1.12 file +// is 32x32 — and vanilla's own `UIPanelScrollBarButton` template draws it at +// TexCoords 0.25,0.75,0.25,0.75, a CENTERED 16x16 sprite that is neither the +// atlas's size nor a top-left crop. `macropopup-topleft` is 18x71 against a +// 256x256 file: a different asset that happens to share a name. So texcoords +// cannot be derived from the two tables, and a wrong guess renders wrong art +// rather than failing loudly. +// +// The five rows below are the ones where the atlas sprite size and the 1.12 file +// dimensions agree exactly, which makes the whole file the sprite and the texcoords +// a trivial 0..1. Everything else needs a human to pick the 1.12 equivalent and +// read its sub-rect out of the client's own FrameXML. That work is driven by the +// miss log (`_classicapi_DumpAtlasMisses`) rather than done speculatively, so the +// table only ever grows toward what real addons actually ask for. +// +// Two source-data traps, handled during extraction: +// - 28 members have an EMPTY name and must be skipped. +// - 73 names repeat case-insensitively; keep the higher ID, the same rule +// `ui/ColorData.h` documents for duplicate color tags. +// +// `tilesHorizontally` / `tilesVertically` come from `CommittedFlags` bits 0 and 1. +// They are stored as resolved booleans rather than the raw flags word because the +// other set bits (4, 8, 16 appear in the data) have no known meaning and must not +// leak into the public contract. + +namespace Texture::AtlasData { + +struct Entry { + const char *name; // Blizzard's canonical casing, returned as `elementName` + const char *file; // 1.12 texture path, extension omitted as WoW expects + int16_t width; // sprite size, used by SetAtlas's `useAtlasSize` + int16_t height; + float left, right, top, bottom; // normalized sub-rect within `file` + int32_t atlasID; // Blizzard UiTextureAtlas.ID + int32_t elementID; // Blizzard UiTextureAtlasMember.UiTextureAtlasElementID + bool tilesHorizontally; + bool tilesVertically; +}; + +constexpr Entry kAtlases[] = { + {"MinimapArrow", "Interface\\Minimap\\MinimapArrow", 32, 32, 0.0f, 1.0f, 0.0f, 1.0f, 647, + 9441, false, false}, + {"Repair", "Interface\\CURSOR\\Repair", 32, 32, 0.0f, 1.0f, 0.0f, 1.0f, 647, 9509, false, + false}, + {"Rotating-MinimapArrow", "Interface\\Minimap\\ROTATING-MINIMAPARROW", 32, 32, 0.0f, 1.0f, + 0.0f, 1.0f, 647, 9442, false, false}, + {"Rotating-MinimapGroupArrow", "Interface\\Minimap\\Rotating-MinimapGroupArrow", 32, 32, + 0.0f, 1.0f, 0.0f, 1.0f, 647, 9443, false, false}, + {"Rotating-MinimapGuideArrow", "Interface\\Minimap\\ROTATING-MINIMAPGUIDEARROW", 32, 32, + 0.0f, 1.0f, 0.0f, 1.0f, 647, 9444, false, false}, +}; + +constexpr int kAtlasCount = sizeof(kAtlases) / sizeof(kAtlases[0]); + +} // namespace Texture::AtlasData