diff --git a/README.md b/README.md index a8746e6b..04a02441 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ reference in **[docs/API.md](docs/API.md)**. | [Class](docs/API.md#class) | `FillLocalizedClassList` | | [ColorUtil](docs/API.md#colorutil) | `C_ColorUtil.ConvertRGBToHSV`, `C_ColorUtil.ConvertHSVToRGB`, `C_ColorUtil.ConvertHSVToHSL`, `C_ColorUtil.ConvertHSLToHSV`, `C_ColorUtil.ConvertHSLToRGB`, `C_ColorUtil.GenerateTextColorCode`, `C_ColorUtil.WrapTextInColor`, `C_ColorUtil.WrapTextInColorCode` | | [Combat](docs/API.md#combat) | `InCombatLockdown`, `StartAttack`, `StopAttack` | -| [Console](docs/API.md#console) | `ConsoleGetAllCommands` | +| [Console](docs/API.md#console) | `CalculateStringEditDistance`, `ConsoleEcho`, `ConsoleExec`, `ConsoleGetAllCommands`, `ConsoleGetColorFromType`, `ConsoleGetFontHeight`, `ConsoleIsActive`, `ConsolePrintAllMatchingCommands`, `SetConsoleKey` | | [CVar](docs/API.md#cvar) | `C_CVar.AreCVarsLoaded`, `C_CVar.DoesCVarExist`, `C_CVar.GetCVarBitfield`, `C_CVar.GetCVarBool`, `C_CVar.GetCVarInfo`, `C_CVar.SetCVarBitfield` | | [Cursor](docs/API.md#cursor) | `GetCursorInfo` | | [Container](docs/API.md#container) | `C_Container.CalculateTotalNumberOfFreeBagSlots`, `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemInfo`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetItemCooldown`, `C_Container.HasContainerItem`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown` | diff --git a/docs/API.md b/docs/API.md index 543d8073..88ab0cb9 100644 --- a/docs/API.md +++ b/docs/API.md @@ -60,6 +60,14 @@ build instructions. - [`StopAttack()`](#stopattack) - [Console](#console) + - [`ConsoleExec(command)`](#consoleexeccommand) + - [`ConsoleEcho(message [, colorType])`](#consoleechomessage--colortype) + - [`ConsolePrintAllMatchingCommands(prefix)`](#consoleprintallmatchingcommandsprefix) + - [`ConsoleIsActive()`](#consoleisactive) + - [`ConsoleGetColorFromType(colorType)`](#consolegetcolorfromtypecolortype) + - [`ConsoleGetFontHeight()`](#consolegetfontheight) + - [`SetConsoleKey(keyCode)`](#setconsolekeykeycode) + - [`CalculateStringEditDistance(a, b)`](#calculatestringeditdistancea-b) - [`ConsoleGetAllCommands()`](#consolegetallcommands) - [`ExportInterfaceFiles art|code` (console command)](#exportinterfacefiles-artcode-console-command) - [`ExportDBCFiles` (console command)](#exportdbcfiles-console-command) @@ -1593,6 +1601,101 @@ Stops your melee auto-attack. If you are not attacking, the call does nothing. ## Console +The developer console is the overlay you open with `~` when the client is +started with `-console`. These functions run commands in it, write to it, and +read its state. + +### `ConsoleExec(command)` + +Runs a console command line, the same way typing it into the console does. + +```lua +ConsoleExec("ExportDBCFiles") +ConsoleExec("gxRestart") +``` + +Every command [`ConsoleGetAllCommands`](#consolegetallcommands) lists can be run +this way, so anything the console can do is now reachable from Lua. The command +is added to the console's history, and an unknown command writes +`Unknown command` to the console rather than raising. + +The console's own `set` command is **not** the same as `SetCVar`. It writes any +cvar, including one `SetCVar` refuses as read-only and one no Lua function can +read. `ConsoleExec("set …")` is therefore a way around the limits every other +cvar function keeps, and it changes settings that persist. Prefer `SetCVar` +unless you specifically want the console's behaviour. + +Works whether or not the console is open, and whether or not `-console` was +used. + +### `ConsoleEcho(message [, colorType])` + +Writes one line to the console. `colorType` is 0 to 8 and picks the colour, as +[`ConsoleGetColorFromType`](#consolegetcolorfromtypecolortype) describes; +it defaults to 0, white. + +```lua +ConsoleEcho("something happened") +ConsoleEcho("something went wrong", 3) -- red +``` + +The line is kept whether or not the console is open, so it is there when you +next open it. + +### `ConsolePrintAllMatchingCommands(prefix)` + +Writes every command whose name begins with `prefix` to the console, the way its +own completion lists candidates. The match ignores case. An empty prefix prints +nothing; use [`ConsoleGetAllCommands`](#consolegetallcommands) to get everything. + +### `ConsoleIsActive()` + +Returns whether the console is open right now. Always `false` when the client +was started without `-console`, because the key that opens it does nothing then. + +### `ConsoleGetColorFromType(colorType)` + +Returns `r, g, b, a` for one of the console's nine line colours, each 0 to 1, or +`nil` outside that range. + +| Type | Colour | | Type | Colour | +|---|---|---|---|---| +| 0 | white | | 5 | white | +| 1 | white | | 6 | white | +| 2 | grey | | 7 | white, half alpha | +| 3 | red | | 8 | black | +| 4 | yellow | | | | + +### `ConsoleGetFontHeight()` + +Returns the console's text height as a fraction of the screen height. The +default is `0.02`. + +There is no matching setter. The font is built once while the client starts, and +rebuilding it afterwards leaves every line already in the console pointing at a +font that no longer exists. + +### `SetConsoleKey(keyCode)` + +Sets the key that opens and closes the console. + +`keyCode` is the client's own numeric key code, not a key name — the console +compares raw key codes and nothing in it reads names. The key still only works +when the client was started with `-console`. + +### `CalculateStringEditDistance(a, b)` + +Returns how many single-character insertions, deletions or substitutions turn +one string into the other. The console uses it to suggest a command when one is +mistyped. + +```lua +CalculateStringEditDistance("kitten", "sitting") -- 3 +CalculateStringEditDistance("help", "hepl") -- 2 +``` + +Returns `nil` if the shorter string is 256 characters or longer. + ### `ConsoleGetAllCommands()` Returns a list of every console command and console variable the client has, diff --git a/src/Offsets.h b/src/Offsets.h index 1c920faf..980d299e 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -5651,6 +5651,49 @@ enum Offsets { CONSOLE_CATEGORY_COUNT = 9, SIZEOF_CONSOLE_CATEGORY_ENTRY = 0x18, + // --- The rest of the console surface -------------------------------------- + // Run a command line: `__fastcall(const char *line, int addToHistory)`. Skips + // leading spaces, resolves the name, and calls the node's +0x18 handler — + // the same field ConsoleGetAllCommands reports. Prints "Unknown command" + // when nothing matches. This is what replays each `SET` line of Config.wtf. + FUN_CONSOLE_EXEC = 0x0063CE00, + // `__fastcall(int keyCode)`, the whole body being a store to + // VAR_CONSOLE_TOGGLE_KEY. + FUN_CONSOLE_SET_KEY = 0x0063CB00, + // Console font init: reads VAR_CONSOLE_FONT_HEIGHT, releases the old font + // handle, creates `Fonts\ARIALN.ttf` at that size, and re-seeds + // VAR_CONSOLE_COLORS to its defaults. + // + // DO NOT CALL IT. It has no code callers — its single reference is one + // table entry at 0x0080E170 — so it runs exactly once at startup, before a + // console line exists. The null-check-and-free of the previous handle looks + // like re-entrancy but is not: every existing line holds a cached, + // font-dependent draw object at +0x20, and this frees the font without + // touching them, so the NEXT console render walks freed data and faults in + // the texture manager. The console's own shutdown frees the font and those + // per-line objects together, which is what the pairing is for. Verified by + // crashing this way; see console/Shell.cpp for why there is no font-height + // setter. + FUN_CONSOLE_FONT_INIT = 0x00639100, + // Toggled by the console key in the key handler FUN_0063C860, which acts + // only when VAR_CONSOLE_ENABLED is set: `visible = (visible == 0)`. + VAR_CONSOLE_VISIBLE = 0x00C4EAC8, + // Set at startup from the `-console` command-line switch (FUN_00419C10(0x22) + // in ConsoleDeviceInitialize). Without it the toggle key does nothing, so + // the console can never open. + VAR_CONSOLE_ENABLED = 0x00C4EC20, + VAR_CONSOLE_TOGGLE_KEY = 0x00864554, + // Nine ARGB uint32 colours indexed by a line's colour type — the second + // argument to FUN_CONSOLE_WRITE, stored per line at +0x1C and used to pick + // the colour at draw time. Seeded by FUN_00638A60 / FUN_CONSOLE_FONT_INIT + // (white, white, grey, red, yellow, white, white, half-alpha white, black), + // and the engine's own setter bounds the index with `< 9`. `help` writes + // type 4, "Unknown command" type 0. + VAR_CONSOLE_COLORS = 0x00C4EAD8, + CONSOLE_COLOR_COUNT = 9, + // Console font height as a fraction of screen height, 0.02 by default. + VAR_CONSOLE_FONT_HEIGHT = 0x0086455C, + // `ConsoleWrite(const char *line /*ecx*/, int colorFlag /*edx*/)` — // appends a line to the developer console's output buffer. No-ops // cleanly when the console isn't active (gated on the console-init diff --git a/src/console/Commands.cpp b/src/console/Commands.cpp index bf91bbce..a37b7a66 100644 --- a/src/console/Commands.cpp +++ b/src/console/Commands.cpp @@ -57,10 +57,22 @@ namespace { constexpr int kCommandTypeCvar = 0; constexpr int kCommandTypeCommand = 1; +using ConsoleWrite_t = void(__fastcall *)(const char *line, int colorType); + // A list node, or 0 once the walk reaches the end. The low bit tags the // sentinel, the same convention the addon registry and the parser lists use. bool IsNode(uintptr_t node) { return node != 0 && (node & 1) == 0; } +char Lower(char c) { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; } + +bool StartsWithIgnoreCase(const char *name, const char *prefix) { + for (size_t i = 0; prefix[i] != '\0'; ++i) { + if (name[i] == '\0' || Lower(name[i]) != Lower(prefix[i])) + return false; + } + return true; +} + void SetStringField(void *L, const char *key, const char *value) { Game::Lua::PushString(L, key); Game::Lua::PushString(L, value != nullptr ? value : ""); @@ -122,6 +134,34 @@ int __fastcall Script_GetAllCommands(void *L) { // return still deserves the number instead of a nil. `Macro` and `Script` have // no registration path here, and `Reveal` / `None` are not among the engine's // nine categories -- everything else lines up, which is the point. +// `ConsolePrintAllMatchingCommands(prefix)` — write every command whose name +// starts with `prefix` to the console, the way its own tab completion lists +// candidates. Case-insensitive, matching how the engine resolves a command +// name. +// +// Prints nothing for an empty prefix rather than dumping all 500-odd entries; +// ConsoleGetAllCommands is the way to ask for everything. +int __fastcall Script_ConsolePrintAllMatchingCommands(void *L) { + if (!Game::Lua::IsString(L, 1)) + return 0; + const char *prefix = Game::Lua::ToString(L, 1); + if (prefix == nullptr || prefix[0] == '\0') + return 0; + + auto write = reinterpret_cast(Offsets::FUN_CONSOLE_WRITE); + const uintptr_t linkOffset = + Game::Read(Offsets::VAR_CONSOLE_COMMAND_LINK_OFFSET); + uintptr_t node = Game::Read(Offsets::VAR_CONSOLE_COMMAND_LIST_HEAD); + while (IsNode(node)) { + const auto *name = + Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_NAME); + node = Game::Read(node + linkOffset + 4); + if (name != nullptr && StartsWithIgnoreCase(name, prefix)) + write(name, 0); + } + return 0; +} + const Game::Lua::EnumIntegerEntry kCommandTypeEntries[] = { {"Cvar", kCommandTypeCvar}, {"Command", kCommandTypeCommand}, @@ -140,6 +180,8 @@ const Game::Lua::EnumIntegerEntry kCategoryEntries[] = { void RegisterLuaFunctions() { Game::Lua::RegisterGlobalFunction("ConsoleGetAllCommands", &Script_GetAllCommands); + Game::Lua::RegisterGlobalFunction("ConsolePrintAllMatchingCommands", + &Script_ConsolePrintAllMatchingCommands); Game::Lua::RegisterIntegerEnum("Enum", "ConsoleCommandType", kCommandTypeEntries, sizeof(kCommandTypeEntries) / sizeof(kCommandTypeEntries[0])); diff --git a/src/console/Shell.cpp b/src/console/Shell.cpp new file mode 100644 index 00000000..7d740046 --- /dev/null +++ b/src/console/Shell.cpp @@ -0,0 +1,240 @@ +// 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 . + +// The developer console, as Lua functions: running commands, writing lines, +// and reading the console's own state and appearance. +// +// `ConsoleExec` is the one with real reach. Nothing in this client's Lua could +// run a console command before, so every entry ConsoleGetAllCommands returns +// was visible and unreachable at once. It is the engine's own executor, the +// same one that replays each `SET` line of Config.wtf at boot. +// +// THAT INCLUDES `set`, AND `set` IS NOT SetCVar. The console's set handler +// looks a cvar up with the unfiltered lookup and performs no read-only check, +// while Script_SetCVar tests flag bit 0x4 first and refuses. So +// `ConsoleExec("set ")` can write a cvar that +// `SetCVar` rejects, and can reach cvars no Lua getter can see (Offsets.h at +// CVAR_FLAG_READ_ONLY has the mechanism). That is inherent to exposing the +// console rather than something added here -- an addon already runs arbitrary +// Lua -- but it does mean the read-only guarantee C_CVar.GetCVarInfo reports +// stops being absolute once this exists. Deliberate: a console you cannot run +// commands through is not a console. +// +// Everything else is state the console module already keeps. The colours are +// its own nine-entry table, the font height its own global, and the toggle key +// its own byte, so each is read or written where the engine reads or writes it +// rather than being modelled again here. + +#include "Game.h" +#include "Offsets.h" + +#include + +namespace Console::Shell { + +namespace { + +using ConsoleExec_t = void(__fastcall *)(const char *line, int addToHistory); +using ConsoleWrite_t = void(__fastcall *)(const char *line, int colorType); +using ConsoleSetKey_t = void(__fastcall *)(int keyCode); + +// `ConsoleExec(command)` — run a console command line. +// +// Passes addToHistory = 1 so a command run from Lua appears in the console's +// own history, which is what someone stepping through the console afterwards +// expects to find. +int __fastcall Script_ConsoleExec(void *L) { + if (!Game::Lua::IsString(L, 1)) + return 0; + reinterpret_cast(Offsets::FUN_CONSOLE_EXEC)(Game::Lua::ToString(L, 1), 1); + return 0; +} + +// `ConsoleEcho(message [, colorType])` — write one line to the console. +// +// The engine no-ops cleanly when the graphics device is not up, so this is safe +// to call at any time, and the line is kept whether or not the console is +// currently open. +int __fastcall Script_ConsoleEcho(void *L) { + if (!Game::Lua::IsString(L, 1)) + return 0; + int colorType = 0; + if (Game::Lua::IsNumber(L, 2)) { + colorType = static_cast(Game::Lua::ToNumber(L, 2)); + if (colorType < 0 || colorType >= Offsets::CONSOLE_COLOR_COUNT) + colorType = 0; + } + reinterpret_cast(Offsets::FUN_CONSOLE_WRITE)(Game::Lua::ToString(L, 1), + colorType); + return 0; +} + +// `ConsoleIsActive()` — whether the console is open right now. +// +// False when the client was started without `-console`, since the toggle key +// is gated on that and the console can then never open. +int __fastcall Script_ConsoleIsActive(void *L) { + const uint32_t enabled = Game::Read(Offsets::VAR_CONSOLE_ENABLED); + const uint32_t visible = Game::Read(Offsets::VAR_CONSOLE_VISIBLE); + Game::Lua::PushBool(L, enabled != 0 && visible != 0); + return 1; +} + +// `ConsoleGetColorFromType(colorType)` -> r, g, b, a +// +// The colour the console draws that type of line in, as four 0..1 components to +// match every other colour in this API. Nil for a type outside the table. +int __fastcall Script_ConsoleGetColorFromType(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Game::Lua::PushNil(L); + return 1; + } + const int type = static_cast(Game::Lua::ToNumber(L, 1)); + if (type < 0 || type >= Offsets::CONSOLE_COLOR_COUNT) { + Game::Lua::PushNil(L); + return 1; + } + const uint32_t argb = *reinterpret_cast( + Offsets::VAR_CONSOLE_COLORS + static_cast(type) * sizeof(uint32_t)); + Game::Lua::PushNumber(L, ((argb >> 16) & 0xFF) / 255.0); + Game::Lua::PushNumber(L, ((argb >> 8) & 0xFF) / 255.0); + Game::Lua::PushNumber(L, (argb & 0xFF) / 255.0); + Game::Lua::PushNumber(L, ((argb >> 24) & 0xFF) / 255.0); + return 4; +} + +// `ConsoleGetFontHeight()` — the console's text height, as a fraction of the +// screen height. +int __fastcall Script_ConsoleGetFontHeight(void *L) { + Game::Lua::PushNumber(L, *reinterpret_cast(Offsets::VAR_CONSOLE_FONT_HEIGHT)); + return 1; +} + +// There is deliberately no ConsoleSetFontHeight. Writing the height global +// alone changes nothing, since the font was already built at the old size, and +// the only thing that rebuilds it is the console's font init — which has no +// code callers at all, just one entry in a table at 0x0080E170. It runs once, +// during startup, before a single console line exists. +// +// Re-running it crashes, on a later frame rather than in the call: it frees the +// old font handle out from under the cached, font-dependent draw object every +// existing line holds at +0x20, and the next console render walks those. The +// console's own shutdown frees both together, which is what that pairing is +// for. Making a setter safe would mean replaying that teardown across every +// line, to change a text size nothing asks to change. + +// `SetConsoleKey(keyCode)` — the key that opens and closes the console. +// +// Takes the engine's own key code, the value its key events carry, rather than +// a key name: the console module stores and compares exactly that, and nothing +// in it translates names. +int __fastcall Script_SetConsoleKey(void *L) { + if (!Game::Lua::IsNumber(L, 1)) + return 0; + reinterpret_cast(Offsets::FUN_CONSOLE_SET_KEY)( + static_cast(Game::Lua::ToNumber(L, 1))); + return 0; +} + +// `CalculateStringEditDistance(a, b)` — Levenshtein distance, the number of +// single-character insertions, deletions or substitutions between two strings. +// The console uses it to suggest a command when one is mistyped. +// +// Two rolling rows rather than a full matrix, so the cost is bounded by the +// shorter string; the longer one only ever drives the loop. +int __fastcall Script_CalculateStringEditDistance(void *L) { + if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsString(L, 2)) { + Game::Lua::PushNil(L); + return 1; + } + const char *a = Game::Lua::ToString(L, 1); + const char *b = Game::Lua::ToString(L, 2); + + size_t lenA = 0, lenB = 0; + while (a[lenA] != '\0') + ++lenA; + while (b[lenB] != '\0') + ++lenB; + if (lenA == 0 || lenB == 0) { + Game::Lua::PushNumber(L, static_cast(lenA + lenB)); + return 1; + } + // Index the rows by the shorter string so the buffers stay small whichever + // way round the arguments came in. + if (lenB > lenA) { + const char *t = a; + a = b; + b = t; + const size_t n = lenA; + lenA = lenB; + lenB = n; + } + constexpr size_t kMaxRow = 256; // beyond this the answer is of no practical use + if (lenB >= kMaxRow) { + Game::Lua::PushNil(L); + return 1; + } + + size_t prev[kMaxRow], curr[kMaxRow]; + for (size_t j = 0; j <= lenB; ++j) + prev[j] = j; + for (size_t i = 1; i <= lenA; ++i) { + curr[0] = i; + for (size_t j = 1; j <= lenB; ++j) { + const size_t cost = (a[i - 1] == b[j - 1]) ? 0u : 1u; + size_t best = prev[j] + 1; // deletion + if (curr[j - 1] + 1 < best) + best = curr[j - 1] + 1; // insertion + if (prev[j - 1] + cost < best) + best = prev[j - 1] + cost; // substitution + curr[j] = best; + } + for (size_t j = 0; j <= lenB; ++j) + prev[j] = curr[j]; + } + Game::Lua::PushNumber(L, static_cast(prev[lenB])); + return 1; +} + +void Register() { + Game::Lua::RegisterGlobalFunction("ConsoleExec", &Script_ConsoleExec); + Game::Lua::RegisterGlobalFunction("ConsoleEcho", &Script_ConsoleEcho); + Game::Lua::RegisterGlobalFunction("ConsoleIsActive", &Script_ConsoleIsActive); + Game::Lua::RegisterGlobalFunction("ConsoleGetColorFromType", + &Script_ConsoleGetColorFromType); + Game::Lua::RegisterGlobalFunction("ConsoleGetFontHeight", &Script_ConsoleGetFontHeight); + Game::Lua::RegisterGlobalFunction("SetConsoleKey", &Script_SetConsoleKey); + Game::Lua::RegisterGlobalFunction("CalculateStringEditDistance", + &Script_CalculateStringEditDistance); +} + +// The console exists before login, so the same surface is registered on the +// glue state. +void RegisterGlue() { + Game::Lua::RegisterGlueFunction("ConsoleExec", &Script_ConsoleExec); + Game::Lua::RegisterGlueFunction("ConsoleEcho", &Script_ConsoleEcho); + Game::Lua::RegisterGlueFunction("ConsoleIsActive", &Script_ConsoleIsActive); + Game::Lua::RegisterGlueFunction("ConsoleGetColorFromType", + &Script_ConsoleGetColorFromType); + Game::Lua::RegisterGlueFunction("ConsoleGetFontHeight", &Script_ConsoleGetFontHeight); + Game::Lua::RegisterGlueFunction("SetConsoleKey", &Script_SetConsoleKey); + Game::Lua::RegisterGlueFunction("CalculateStringEditDistance", + &Script_CalculateStringEditDistance); +} + +const Game::ModuleAutoRegister _autoreg{&Register}; +const Game::GlueModuleAutoRegister _glueAutoreg{&RegisterGlue}; + +} // namespace + +} // namespace Console::Shell