mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-11 12:27:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6245d72694 | ||
|
|
bd14228ad7 | ||
|
|
5b15172894 | ||
|
|
b5470e8d3d | ||
|
|
c601967fdb | ||
|
|
5c063ade73 |
@@ -45,7 +45,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**.
|
||||
| [Loot](docs/API.md#loot) | `C_Loot.GetNearbyLootableUnits`, `C_Loot.GetLastScanResults`, `C_Loot.IsScanInProgress`, `C_Loot.LootUnit`, `C_Loot.LootUnitItem`, `C_Loot.ScanNearbyLoot` |
|
||||
| [LootHistory](docs/API.md#loothistory) | `C_LootHistory.GetNumItems`, `C_LootHistory.GetItem`, `C_LootHistory.GetPlayerInfo`, `C_LootHistory.Clear` |
|
||||
| [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount` |
|
||||
| [Lua](docs/API.md#lua) | `coroutine.create`, `coroutine.resume`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `math.fmod`, `select`, `string.gmatch`, `string.match`, `table.wipe` |
|
||||
| [Lua](docs/API.md#lua) | `coroutine.create`, `coroutine.resume`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `math.fmod`, `math.huge`, `math.modf`, `select`, `string.gmatch`, `string.match`, `string.reverse`, `strjoin`, `strreplace`, `strrev`, `strsplit`, `strtrim`, `table.wipe` |
|
||||
| [Macros](docs/API.md#macros) | `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroIcons`, `GetMacroItemIcons`, `GetMacroSpell` |
|
||||
| [Mail](docs/API.md#mail) | `GetInboxItemLink`, `GetSendMailItemLink` |
|
||||
| [Map](docs/API.md#map) | `C_Map.GetAreaInfo`, `C_Map.GetAreas`, `C_Map.GetAreaTriggerInfo`, `C_Map.GetAreaTriggers`, `C_Map.GetBestMapForUnit`, `C_Map.GetMapAreaIDs`, `C_Map.GetMapOverlays`, `C_Map.GetMapWorldSize` |
|
||||
|
||||
+157
-3
@@ -95,6 +95,7 @@ build instructions.
|
||||
|
||||
- [Events](#events)
|
||||
- [`C_EventUtils.IsEventValid(eventName)`](#c_eventutilsiseventvalideventname)
|
||||
- [`PLAYER_ENTERING_WORLD` payload (`isInitialLogin`, `isReloadingUi`)](#player_entering_world-payload-isinitiallogin-isreloadingui)
|
||||
- [`BAG_UPDATE_DELAYED` event](#bag_update_delayed-event)
|
||||
- [`PLAYER_EQUIPMENT_CHANGED` event](#player_equipment_changed-event)
|
||||
- [`UPDATE_INVENTORY_DURABILITY` event](#update_inventory_durability-event)
|
||||
@@ -282,7 +283,14 @@ build instructions.
|
||||
- [`select(index, ...)`](#selectindex-)
|
||||
- [`table.wipe(t)`](#tablewipet)
|
||||
- [`string.match` / `string.gmatch`](#stringmatch--stringgmatch)
|
||||
- [`strsplit(sep, str [, pieces])`](#strsplitsep-str--pieces)
|
||||
- [`strjoin(delimiter, ...)`](#strjoindelimiter-)
|
||||
- [`strtrim(str [, chars])`](#strtrimstr--chars)
|
||||
- [`strreplace(str, find, replace)`](#strreplacestr-find-replace)
|
||||
- [`string.reverse(s)` / `strrev(s)`](#stringreverses--strrevs)
|
||||
- [`math.fmod(x, y)`](#mathfmodx-y)
|
||||
- [`math.modf(x)`](#mathmodfx)
|
||||
- [`math.huge`](#mathhuge)
|
||||
- [`coroutine.create(fn)`](#coroutinecreatefn)
|
||||
- [`coroutine.resume(co, ...)`](#coroutineresumeco-)
|
||||
- [`coroutine.yield(...)`](#coroutineyield)
|
||||
@@ -2213,6 +2221,41 @@ SuperWoWhook patches the binary's event names with its own. This matches
|
||||
what `frame:RegisterEvent` will actually accept, which is what addon code
|
||||
needs to know.
|
||||
|
||||
### `PLAYER_ENTERING_WORLD` payload (`isInitialLogin`, `isReloadingUi`)
|
||||
|
||||
Backports the 8.0.1 payload onto vanilla's (natively arg-less)
|
||||
`PLAYER_ENTERING_WORLD`:
|
||||
|
||||
```lua
|
||||
local f = CreateFrame("Frame")
|
||||
f:RegisterEvent("PLAYER_ENTERING_WORLD")
|
||||
f:SetScript("OnEvent", function()
|
||||
local isInitialLogin, isReloadingUi = arg1, arg2
|
||||
if isInitialLogin then -- fresh character login (from char-select)
|
||||
elseif isReloadingUi then -- /reload
|
||||
else -- zone / instance transition
|
||||
end
|
||||
end)
|
||||
```
|
||||
|
||||
- `isInitialLogin` — `true` on a fresh login (including logging out to
|
||||
char-select and back in), `nil` otherwise.
|
||||
- `isReloadingUi` — `true` when the fire is caused by a `/reload`, `nil`
|
||||
otherwise.
|
||||
- Both `nil` on an instance/zone transition — matching retail.
|
||||
|
||||
Delivered as real event args (`arg1`/`arg2`), so retail-style handlers work
|
||||
unchanged. Values are `true`→`1` / false→`nil` (the engine dispatcher has no
|
||||
boolean), so `if isInitialLogin then …` reads naturally. Existing handlers
|
||||
that ignore the args are unaffected.
|
||||
|
||||
PEW is a no-arg event, so the engine broadcasts it through the
|
||||
`FUN_FIRE_EVENT_NO_ARGS` dispatcher; we intercept that (via the shared
|
||||
`Event::SignalHook`) and re-broadcast through the variadic dispatcher with
|
||||
the payload. The flags are derived from whether the in-game Lua state was
|
||||
just (re)built (login/`reload`) and whether we just came through the
|
||||
glue/login screen — no `PLAYER_ENTERING_WORLD`-specific engine hook.
|
||||
|
||||
### `BAG_UPDATE_DELAYED` event
|
||||
|
||||
Fires (with no payload) once per frame in which any `BAG_UPDATE`
|
||||
@@ -6839,6 +6882,83 @@ for word in string.gmatch("a,bb,ccc", "[^,]+") do print(word) end -- a / bb / cc
|
||||
> a hot VM-core function. This is the long-standing vanilla 1.12 constraint —
|
||||
> always write `string.match(s, p)`, never `s:match(p)`.
|
||||
|
||||
### `strsplit(sep, str [, pieces])`
|
||||
|
||||
The WoW global (backported from 3.3.5), splits `str` on **any** character in
|
||||
`sep` and returns the pieces as multiple values.
|
||||
|
||||
- `sep` — a set of delimiter *characters* (not a pattern); each character is
|
||||
a delimiter. `","` splits on commas; `" -"` splits on spaces and dashes.
|
||||
- `pieces` (optional) — caps the number of results. After `pieces - 1`
|
||||
splits the rest of the string (delimiters and all) is returned as the final
|
||||
piece. `0` or omitted = unlimited. `1` returns the whole string unsplit.
|
||||
|
||||
Consecutive/trailing delimiters produce empty pieces, matching retail.
|
||||
|
||||
```lua
|
||||
strsplit(",", "a,b,c") -- "a", "b", "c"
|
||||
strsplit(",", "a,b,c,d", 2) -- "a", "b,c,d" (capped at 2)
|
||||
strsplit(" -", "a b-c") -- "a", "b", "c" (space OR dash)
|
||||
strsplit(",", "a,,b") -- "a", "", "b" (empty middle piece)
|
||||
local zone, x, y = strsplit(":", "Durotar:52:38")
|
||||
```
|
||||
|
||||
Errors `strsplit(): Stack overflow` if a string splits into more pieces than
|
||||
the Lua stack can grow to hold (`lua_checkstack` guards every push) — the
|
||||
same guard and message 3.3.5 uses.
|
||||
|
||||
### `strjoin(delimiter, ...)`
|
||||
|
||||
The inverse of `strsplit`: concatenate the vararg pieces with `delimiter`
|
||||
between each.
|
||||
|
||||
```lua
|
||||
strjoin(",", "a", "b", "c") -- "a,b,c"
|
||||
strjoin("", "a", "b", "c") -- "abc"
|
||||
strjoin(",") -- "" (no pieces)
|
||||
```
|
||||
|
||||
A `nil` / non-string-coercible piece is treated as an empty string (so the
|
||||
delimiters still line up) rather than erroring.
|
||||
|
||||
### `strtrim(str [, chars])`
|
||||
|
||||
Remove any of the characters in `chars` from both ends of `str`. `chars` is a
|
||||
literal **set of characters** (not a Lua pattern); it defaults to whitespace
|
||||
(space, tab, `\n`, `\v`, `\f`, `\r`).
|
||||
|
||||
```lua
|
||||
strtrim(" hello ") -- "hello"
|
||||
strtrim("xxhelloxx", "x") -- "hello"
|
||||
strtrim("[a]", "[]") -- "a"
|
||||
```
|
||||
|
||||
### `strreplace(str, find, replace)`
|
||||
|
||||
Replace every occurrence of the literal substring `find` with `replace`,
|
||||
returning `(result, count)`. This is a **plain-text** replace — no pattern
|
||||
magic-character escaping, unlike `string.gsub`. An empty `find` returns `str`
|
||||
unchanged with count `0`.
|
||||
|
||||
```lua
|
||||
strreplace("a.b.c", ".", "-") -- "a-b-c", 2 (no pattern escaping)
|
||||
strreplace("hello world", "o", "0") -- "hell0 w0rld", 2
|
||||
```
|
||||
|
||||
> Not a stock WoW global — a ClassicAPI convenience. For pattern-based
|
||||
> replacement use `string.gsub`.
|
||||
|
||||
### `string.reverse(s)` / `strrev(s)`
|
||||
|
||||
Returns `s` with its bytes reversed. Lua 5.1 added `string.reverse`; 5.0's
|
||||
string library lacks it. Byte-wise (not UTF-8 aware), matching stock Lua.
|
||||
Registered both on the `string` table and as the `strrev` global.
|
||||
|
||||
```lua
|
||||
string.reverse("abc") -- "cba"
|
||||
strrev("hello") -- "olleh"
|
||||
```
|
||||
|
||||
### `math.fmod(x, y)`
|
||||
|
||||
The floating-point remainder of `x / y` (the quotient truncated toward zero),
|
||||
@@ -6853,6 +6973,28 @@ math.fmod(-7, 3) -- -1 (result takes the sign of the dividend)
|
||||
math.fmod(5.5, 2) -- 1.5
|
||||
```
|
||||
|
||||
### `math.modf(x)`
|
||||
|
||||
Returns `(integral, fractional)` — the integral part truncated toward zero
|
||||
and the fractional part carrying `x`'s sign. Lua 5.1 function, genuinely
|
||||
missing from 1.12's math library (not just renamed like `fmod`).
|
||||
|
||||
```lua
|
||||
math.modf(3.7) -- 3, 0.7
|
||||
math.modf(-3.7) -- -3, -0.7
|
||||
math.modf(5) -- 5, 0
|
||||
```
|
||||
|
||||
### `math.huge`
|
||||
|
||||
Positive infinity, as the numeric constant `math.huge` (Lua 5.1). Handy as a
|
||||
"larger than anything" sentinel in min/max scans.
|
||||
|
||||
```lua
|
||||
local best = math.huge
|
||||
for _, v in ipairs(costs) do best = math.min(best, v) end
|
||||
```
|
||||
|
||||
### `coroutine.*`
|
||||
|
||||
Restores Lua 5.0's stripped `coroutine.*` library. The C-level
|
||||
@@ -11467,13 +11609,25 @@ end
|
||||
|
||||
| Return | Meaning |
|
||||
|--------|---------|
|
||||
| `inRange` | `true` if the unit's world position is within 40 yards of the player's. `false` if out of range OR if `checkedRange` is `false`. |
|
||||
| `inRange` | `true` if the unit is within a 40-yard heal's reach of the player. `false` if out of range OR if `checkedRange` is `false`. |
|
||||
| `checkedRange` | `true` when a position-based range check was performed. `false` when the unit's position isn't available — either the token didn't resolve (empty `partyN` slot, no target, raid member in a different zone, etc.) or `unit == "player"` (see below). |
|
||||
|
||||
Reads the world position via the `CGObject::GetPosition` vtable
|
||||
virtual (slot 5, offset `+0x14`) — same path
|
||||
`CheckInteractDistance` uses. Squared-distance compare against
|
||||
`40 * 40 = 1600`.
|
||||
`CheckInteractDistance` uses.
|
||||
|
||||
**Reach-aware.** The threshold is not a flat 40 yards on the raw
|
||||
center-to-center distance — it's `40 + playerReach + targetReach`,
|
||||
mirroring the engine's own spell-range formula (`FUN_006e3480`), where
|
||||
each unit's reach is the bounding-radius float at `[m_objectFields +
|
||||
0x1F0]` (the same size factor the interact-distance and loot-range
|
||||
checks add). A 40-yard heal lands on a target whose *center* is up to
|
||||
`40 + reach` yards away, so a bare center-distance cap of 40 wrongly
|
||||
reports out-of-range for a target the client can actually heal (on a
|
||||
large target the reach gap is 2–3 yards). If a unit's descriptor isn't
|
||||
populated yet the reach term is 0 and the check degrades to a plain
|
||||
40-yard cap. Note this is the one difference from `UnitDistanceSquared`,
|
||||
which stays raw center-to-center (matching retail).
|
||||
|
||||
> **`UnitInRange("player")` returns `(false, false)`** by design,
|
||||
> matching modern WoW's behavior. The function is meant for healing-
|
||||
|
||||
+2
-1
@@ -57,7 +57,8 @@ namespace Lua {
|
||||
F(Resume, lua_resume, LUA_RESUME) \
|
||||
F(Yield, lua_yield, LUA_YIELD) \
|
||||
F(ArgError, luaL_argerror, LUAL_ARG_ERROR) \
|
||||
F(SetN, luaL_setn, LUAL_SETN)
|
||||
F(SetN, luaL_setn, LUAL_SETN) \
|
||||
F(CheckStack, lua_checkstack, LUA_CHECK_STACK)
|
||||
|
||||
#define CLASSICAPI_BIND_LUA(Name, Typedef, Offset) \
|
||||
const Typedef##_t Name = reinterpret_cast<Typedef##_t>(Offsets::Offset);
|
||||
|
||||
@@ -100,6 +100,7 @@ using lua_resume_t = int(__fastcall *)(void *L, int nargs);
|
||||
using lua_yield_t = int(__fastcall *)(void *L, int nresults);
|
||||
using luaL_argerror_t = void(__fastcall *)(void *L, int narg, const char *msg);
|
||||
using luaL_setn_t = void(__fastcall *)(void *L, int t, int n);
|
||||
using lua_checkstack_t = int(__fastcall *)(void *L, int size);
|
||||
|
||||
extern const lua_isnumber_t IsNumber;
|
||||
extern const lua_isstring_t IsString;
|
||||
@@ -142,6 +143,7 @@ extern const lua_resume_t Resume;
|
||||
extern const lua_yield_t Yield;
|
||||
extern const luaL_argerror_t ArgError;
|
||||
extern const luaL_setn_t SetN;
|
||||
extern const lua_checkstack_t CheckStack;
|
||||
|
||||
// Returns the global `lua_State *` (read on demand from the engine's global).
|
||||
// Callable outside a Lua callback, e.g. during LoadScriptFunctions setup.
|
||||
|
||||
@@ -3796,6 +3796,14 @@ enum Offsets {
|
||||
// `rawset(nil)` clear leaves it stale and subsequent `table.insert`
|
||||
// appends past the wiped slots.
|
||||
LUAL_SETN = 0x6F4EA0,
|
||||
// `lua_checkstack(L, n)` — `int __fastcall(L /*ecx*/, n /*edx*/)`.
|
||||
// Ensures room for `n` more stack values, growing if needed; returns 0
|
||||
// (without growing) when `(top-base)/16 + n` would exceed LUA_MAXCSTACK
|
||||
// (0x800 = 2048), 1 otherwise. Verified by the `cmp reg, 0x800` overflow
|
||||
// test at 0x006F2F43. Needed by any C function that pushes an unbounded
|
||||
// number of results (e.g. `strsplit`) — pushing past the ~20-slot
|
||||
// C-call guarantee without growing corrupts the stack.
|
||||
LUA_CHECK_STACK = 0x006F2F30,
|
||||
// `str_find` — the Lua 5.0 string-library `string.find` C function
|
||||
// (`int __fastcall(void *L)`), entry in the strlib luaL_reg table at
|
||||
// `0x00822dd0`. Returns `1` (nil pushed, no match), `2` (start, end),
|
||||
|
||||
+40
-5
@@ -14,16 +14,21 @@
|
||||
// Lua 5.1 math-library additions that 1.12's Lua 5.0 is missing:
|
||||
//
|
||||
// - `math.fmod(x, y)` — floating-point remainder of `x / y`.
|
||||
// - `math.modf(x)` — split into integral + fractional parts.
|
||||
// - `math.huge` — positive infinity constant.
|
||||
//
|
||||
// This is a pure rename: Lua 5.0 ships the exact same C function under the
|
||||
// name `math.mod`; 5.1 renamed the Lua-facing entry to `math.fmod`. We
|
||||
// register `math.fmod` as a direct alias of the engine's `math.mod` C
|
||||
// function (`FUN_LUA_MATH_FMOD`) — no wrapper. `math.mod` stays available too
|
||||
// (we don't touch it), so code written for either name works.
|
||||
// `math.fmod` is a pure rename: Lua 5.0 ships the exact same C function under
|
||||
// the name `math.mod`; 5.1 renamed the Lua-facing entry to `math.fmod`. We
|
||||
// register it as a direct alias of the engine's `math.mod` C function
|
||||
// (`FUN_LUA_MATH_FMOD`) — no wrapper. `math.mod` stays available too, so code
|
||||
// written for either name works. `modf` and `huge` are genuinely new in 5.1
|
||||
// (not in 1.12's mathlib table), so we implement/define them here.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace BaseLib::MathLib {
|
||||
|
||||
namespace {
|
||||
@@ -33,8 +38,38 @@ namespace {
|
||||
const auto Script_math_fmod =
|
||||
reinterpret_cast<Game::Lua::CFunction>(Offsets::FUN_LUA_MATH_FMOD);
|
||||
|
||||
// `math.modf(x)` — returns `(integral, fractional)`, the integral part
|
||||
// truncated toward zero and the fractional part carrying `x`'s sign
|
||||
// (`modf(3.7) → 3, 0.7`; `modf(-3.7) → -3, -0.7`). Matches C `modf` / Lua 5.1.
|
||||
int __fastcall Script_math_modf(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: math.modf(x)");
|
||||
return 0; // unreachable
|
||||
}
|
||||
double integral = 0.0;
|
||||
const double fractional = std::modf(Game::Lua::ToNumber(L, 1), &integral);
|
||||
Game::Lua::PushNumber(L, integral);
|
||||
Game::Lua::PushNumber(L, fractional);
|
||||
return 2;
|
||||
}
|
||||
|
||||
void RegisterFns() {
|
||||
Game::Lua::RegisterTableFunction("math", "fmod", Script_math_fmod);
|
||||
Game::Lua::RegisterTableFunction("math", "modf", &Script_math_modf);
|
||||
|
||||
// `math.huge` — a numeric constant, not a function. Fetch the (now
|
||||
// guaranteed-present) `math` table and set the field directly.
|
||||
void *L = Game::Lua::State();
|
||||
if (L != nullptr) {
|
||||
Game::Lua::PushString(L, "math");
|
||||
Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX); // [math]
|
||||
if (Game::Lua::Type(L, -1) == 5 /* LUA_TTABLE */) {
|
||||
Game::Lua::SetFieldNumber(L, "huge", HUGE_VAL); // math.huge = inf; [math]
|
||||
Game::Lua::SetTop(L, -2); // pop [math]
|
||||
} else {
|
||||
Game::Lua::SetTop(L, -2); // pop whatever GetTable returned
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Both states are Lua 5.0 and equally missing this; RegisterTableFunction
|
||||
|
||||
+188
-4
@@ -11,16 +11,22 @@
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// Lua 5.1 string-library additions that 1.12's Lua 5.0 is missing:
|
||||
// String helpers that 1.12's Lua 5.0 is missing:
|
||||
//
|
||||
// - `string.match(s, pattern [, init])` — first-match extraction.
|
||||
// - `string.gmatch(s, pattern)` — match iterator.
|
||||
// - `string.match(s, pattern [, init])` — first-match extraction (5.1).
|
||||
// - `string.gmatch(s, pattern)` — match iterator (5.1).
|
||||
// - `strsplit(sep, str [, pieces])` — WoW global; split on any char.
|
||||
// - `strjoin(delimiter, ...)` — WoW global; join varargs.
|
||||
// - `strtrim(str [, chars])` — WoW global; trim a char set.
|
||||
// - `strreplace(str, find, replace)` — plain-text replace (see below).
|
||||
// - `string.reverse(s)` / `strrev(s)` — 5.1 string function, missing in 5.0.
|
||||
//
|
||||
// Both are the same underlying pattern engine as functions 5.0 already ships:
|
||||
// The two pattern `string.*` ones reuse machinery 5.0 already ships:
|
||||
// - `match` is `find` returning captures / the whole match instead of the
|
||||
// start/end indices — so we call the engine's `str_find` and transform.
|
||||
// - `gmatch` is exactly 5.0's `string.gfind` (renamed in 5.1); we register
|
||||
// it as a direct alias of the engine's `gfind` C function.
|
||||
// `strsplit` is a hand-rolled port of 3.3.5's `strsplit` (see below).
|
||||
//
|
||||
// NOTE: only the `string.foo(s, ...)` call form works — NOT the
|
||||
// `("x"):foo(...)` method sugar. WoW's Lua VM strips type-metatables for
|
||||
@@ -33,6 +39,8 @@
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
namespace BaseLib::StringLib {
|
||||
|
||||
@@ -83,9 +91,185 @@ int __fastcall Script_string_match(void *L) {
|
||||
const auto Script_string_gmatch =
|
||||
reinterpret_cast<Game::Lua::CFunction>(Offsets::FUN_LUA_STR_GFIND);
|
||||
|
||||
// `strsplit(sep, str [, pieces])` — the WoW global (also aliased as
|
||||
// `string.split`), split `str` on ANY character in `sep` and return the
|
||||
// pieces as multiple values. `pieces > 0` caps the result count, with the
|
||||
// unsplit remainder as the final piece; `0` / omitted = unlimited. Ported
|
||||
// from 3.3.5's `strsplit` (FUN_00816a60) with one deliberate change: we do
|
||||
// NOT `lua_settop(L, 0)` up front. Popping the args would leave the source
|
||||
// string unreferenced, so a GC step triggered by a `pushlstring` could free
|
||||
// the very buffer we're still scanning. Keeping the args on the stack keeps
|
||||
// the source GC-rooted; Lua returns the top N values (our pieces) regardless
|
||||
// of the args sitting below them. Each push is guarded by `lua_checkstack`
|
||||
// (this pushes an unbounded number of results), erroring like 3.3.5 on
|
||||
// genuine stack exhaustion.
|
||||
int __fastcall Script_strsplit(void *L) {
|
||||
const char *sep = Game::Lua::ToString(L, 1);
|
||||
const char *str = Game::Lua::ToString(L, 2);
|
||||
if (sep == nullptr || str == nullptr) {
|
||||
Game::Lua::Error(L, "Usage: strsplit(\"separators\", str [, pieces])");
|
||||
return 0; // unreachable
|
||||
}
|
||||
const int pieces =
|
||||
Game::Lua::IsNumber(L, 3) ? static_cast<int>(Game::Lua::ToNumber(L, 3)) : 0;
|
||||
|
||||
const char *segStart = str;
|
||||
int count = 0;
|
||||
// Only scan for separators while unlimited (pieces == 0) or the cap
|
||||
// hasn't been reached (pieces > 1). pieces == 1 (or <= 0 but non-zero)
|
||||
// yields the whole string as a single piece — matches 3.3.5.
|
||||
if (pieces == 0 || pieces > 1) {
|
||||
for (const char *p = str; *p != '\0'; ++p) {
|
||||
bool isSep = false;
|
||||
for (const char *s = sep; *s != '\0'; ++s) {
|
||||
if (*p == *s) {
|
||||
isSep = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isSep)
|
||||
continue;
|
||||
++count;
|
||||
if (Game::Lua::CheckStack(L, count) == 0) {
|
||||
Game::Lua::Error(L, "strsplit(): Stack overflow");
|
||||
return 0; // unreachable
|
||||
}
|
||||
Game::Lua::PushLString(L, segStart,
|
||||
static_cast<unsigned int>(p - segStart));
|
||||
segStart = p + 1;
|
||||
if (count == pieces - 1)
|
||||
break; // cap hit; remainder becomes the final piece
|
||||
}
|
||||
}
|
||||
if (Game::Lua::CheckStack(L, count + 1) == 0) {
|
||||
Game::Lua::Error(L, "strsplit(): Stack overflow");
|
||||
return 0; // unreachable
|
||||
}
|
||||
Game::Lua::PushString(L, segStart); // final piece (remainder to end)
|
||||
return count + 1;
|
||||
}
|
||||
|
||||
// `strjoin(delimiter, ...)` — the inverse of `strsplit`: concatenate the
|
||||
// vararg pieces with `delimiter` between each. Standard WoW global (FrameXML
|
||||
// defines it in Lua; there's no C original to mirror). A nil / non-coercible
|
||||
// piece is treated as an empty string rather than erroring, so the delimiter
|
||||
// placement stays predictable. `strjoin(",")` with no pieces returns "".
|
||||
int __fastcall Script_strjoin(void *L) {
|
||||
const char *delim = Game::Lua::ToString(L, 1);
|
||||
if (delim == nullptr) {
|
||||
Game::Lua::Error(L, "Usage: strjoin(delimiter, ...)");
|
||||
return 0; // unreachable
|
||||
}
|
||||
const unsigned delimLen = Game::Lua::StrLen(L, 1);
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
|
||||
std::string out; // no Error() past this point — a longjmp would leak it
|
||||
for (int i = 2; i <= top; ++i) {
|
||||
if (i > 2)
|
||||
out.append(delim, delimLen);
|
||||
const char *piece = Game::Lua::ToString(L, i);
|
||||
if (piece != nullptr)
|
||||
out.append(piece, Game::Lua::StrLen(L, i));
|
||||
}
|
||||
Game::Lua::PushLString(L, out.data(), static_cast<unsigned int>(out.size()));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `strtrim(str [, chars])` — remove any of the characters in `chars` from
|
||||
// both ends of `str` (default: whitespace). `chars` is a literal set of
|
||||
// characters, not a pattern. Standard WoW global. Two-ended scan — no
|
||||
// allocation, embedded NULs preserved (bounds come from the Lua length).
|
||||
int __fastcall Script_strtrim(void *L) {
|
||||
const char *str = Game::Lua::ToString(L, 1);
|
||||
if (str == nullptr) {
|
||||
Game::Lua::Error(L, "Usage: strtrim(str [, chars])");
|
||||
return 0; // unreachable
|
||||
}
|
||||
const unsigned len = Game::Lua::StrLen(L, 1);
|
||||
const char *chars = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2)
|
||||
: " \t\n\v\f\r";
|
||||
|
||||
bool trim[256] = {false};
|
||||
for (const char *c = chars; *c != '\0'; ++c)
|
||||
trim[static_cast<unsigned char>(*c)] = true;
|
||||
|
||||
unsigned start = 0, end = len;
|
||||
while (start < end && trim[static_cast<unsigned char>(str[start])])
|
||||
++start;
|
||||
while (end > start && trim[static_cast<unsigned char>(str[end - 1])])
|
||||
--end;
|
||||
Game::Lua::PushLString(L, str + start, end - start);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `strreplace(str, find, replace)` — replace every occurrence of the literal
|
||||
// substring `find` with `replace`; returns `(result, count)`. NOT a stock WoW
|
||||
// global and NOT pattern-based (that's `gsub`) — a plain-text replace that
|
||||
// needs no magic-character escaping. Empty `find` returns `str` unchanged
|
||||
// (count 0) rather than looping forever.
|
||||
int __fastcall Script_strreplace(void *L) {
|
||||
const char *str = Game::Lua::ToString(L, 1);
|
||||
const char *find = Game::Lua::ToString(L, 2);
|
||||
const char *repl = Game::Lua::ToString(L, 3);
|
||||
if (str == nullptr || find == nullptr || repl == nullptr) {
|
||||
Game::Lua::Error(L, "Usage: strreplace(str, find, replace)");
|
||||
return 0; // unreachable
|
||||
}
|
||||
const unsigned strLen = Game::Lua::StrLen(L, 1);
|
||||
const unsigned findLen = Game::Lua::StrLen(L, 2);
|
||||
const unsigned replLen = Game::Lua::StrLen(L, 3);
|
||||
|
||||
if (findLen == 0) { // nothing to match — return input unchanged
|
||||
Game::Lua::PushLString(L, str, strLen);
|
||||
Game::Lua::PushNumber(L, 0.0);
|
||||
return 2;
|
||||
}
|
||||
|
||||
std::string out; // no Error() past this point
|
||||
int count = 0;
|
||||
unsigned i = 0;
|
||||
while (i < strLen) {
|
||||
if (i + findLen <= strLen && std::memcmp(str + i, find, findLen) == 0) {
|
||||
out.append(repl, replLen);
|
||||
i += findLen;
|
||||
++count;
|
||||
} else {
|
||||
out.push_back(str[i]);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
Game::Lua::PushLString(L, out.data(), static_cast<unsigned int>(out.size()));
|
||||
Game::Lua::PushNumber(L, static_cast<double>(count));
|
||||
return 2;
|
||||
}
|
||||
|
||||
// `string.reverse(s)` / `strrev(s)` — return `s` with its bytes reversed.
|
||||
// Lua 5.1 added `string.reverse`; 5.0's strlib lacks it. Byte-wise (not
|
||||
// UTF-8 aware), matching stock Lua; embedded NULs preserved (bounds from the
|
||||
// Lua length).
|
||||
int __fastcall Script_string_reverse(void *L) {
|
||||
const char *s = Game::Lua::ToString(L, 1);
|
||||
if (s == nullptr) {
|
||||
Game::Lua::Error(L, "Usage: string.reverse(s)");
|
||||
return 0; // unreachable
|
||||
}
|
||||
const unsigned len = Game::Lua::StrLen(L, 1);
|
||||
std::string out(len, '\0'); // no Error() past this point
|
||||
for (unsigned i = 0; i < len; ++i)
|
||||
out[i] = s[len - 1 - i];
|
||||
Game::Lua::PushLString(L, out.data(), len);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void RegisterFns() {
|
||||
Game::Lua::RegisterTableFunction("string", "match", &Script_string_match);
|
||||
Game::Lua::RegisterTableFunction("string", "gmatch", Script_string_gmatch);
|
||||
Game::Lua::RegisterTableFunction("string", "reverse", &Script_string_reverse);
|
||||
Game::Lua::RegisterGlobalFunction("strsplit", &Script_strsplit);
|
||||
Game::Lua::RegisterGlobalFunction("strjoin", &Script_strjoin);
|
||||
Game::Lua::RegisterGlobalFunction("strtrim", &Script_strtrim);
|
||||
Game::Lua::RegisterGlobalFunction("strreplace", &Script_strreplace);
|
||||
Game::Lua::RegisterGlobalFunction("strrev", &Script_string_reverse);
|
||||
}
|
||||
|
||||
// Both states are Lua 5.0 and equally missing these; RegisterTableFunction
|
||||
|
||||
@@ -107,11 +107,19 @@ static int AuxResume(void *L, void *co, int nargs) {
|
||||
: "cannot resume non-suspended coroutine");
|
||||
return -1;
|
||||
}
|
||||
if (Game::Lua::CheckStack(co, nargs) == 0) {
|
||||
Game::Lua::PushString(L, "too many arguments to resume coroutine");
|
||||
return -1;
|
||||
}
|
||||
Game::Lua::XMove(L, co, nargs);
|
||||
const int s = Game::Lua::Resume(co, nargs);
|
||||
const bool yielded = LuaCI(co) > LuaBaseCI(co);
|
||||
if (s == LUA_OK || yielded) {
|
||||
const int nres = Game::Lua::GetTop(co);
|
||||
if (Game::Lua::CheckStack(L, nres) == 0) {
|
||||
Game::Lua::PushString(L, "too many results to resume coroutine");
|
||||
return -1;
|
||||
}
|
||||
Game::Lua::XMove(co, L, nres);
|
||||
return nres;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// 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/>.
|
||||
|
||||
// `PLAYER_ENTERING_WORLD(isInitialLogin, isReloadingUi)` — the 8.0.1 payload,
|
||||
// backported. Vanilla fires PEW with no args; backported addons expect the
|
||||
// two booleans to distinguish a fresh login from a `/reload` from an
|
||||
// instance/zone transition.
|
||||
//
|
||||
// Delivery: PEW is a no-arg event, so the engine broadcasts it through
|
||||
// `FUN_FIRE_EVENT_NO_ARGS` (the `__fastcall(int)` dispatcher), NOT the
|
||||
// variadic `FUN_FIRE_EVENT`. We intercept that dispatcher (via the shared
|
||||
// `Event::SignalHook`) and, for the PEW event id, suppress the no-arg fire
|
||||
// and instead re-broadcast through the variadic `FUN_FIRE_EVENT` with a
|
||||
// two-boolean payload. Both fire paths read the same frame chain off the
|
||||
// event's table slot, so the frames registered for PEW receive the args
|
||||
// exactly once. Booleans use the `%d`/`%s`+nullptr trick (`1` / `nil`), so
|
||||
// `if isInitialLogin then …` reads naturally.
|
||||
//
|
||||
// Flags, from signals we already produce — no PEW-specific engine hook:
|
||||
// - isInitialLogin: our GlueModuleAutoRegister runs on every glue-screen
|
||||
// boot (initial launch + each logout return), so a set latch means "the
|
||||
// next enter-world is a fresh login". The first PEW consumes it.
|
||||
// - isReloadingUi: our ModuleAutoRegister runs whenever the in-game Lua
|
||||
// state is (re)built — login OR `/reload`, but NOT a zone transition. So
|
||||
// "script re-init happened and it wasn't the fresh login" == a reload.
|
||||
// - Instance/zone transition rebuilds neither, so both latches are clear →
|
||||
// both false, matching retail.
|
||||
|
||||
#include "Game.h"
|
||||
#include "event/Custom.h"
|
||||
#include "event/SignalHook.h"
|
||||
|
||||
namespace Event::EnteringWorld {
|
||||
|
||||
namespace {
|
||||
|
||||
// Set on glue-screen boot; a pending latch means the next enter-world is a
|
||||
// fresh character login (from the login/char-select screen).
|
||||
bool g_atGlue = false;
|
||||
// Set when the in-game Lua state is (re)built (login or /reload).
|
||||
bool g_scriptReloaded = false;
|
||||
// Cached PLAYER_ENTERING_WORLD event-table slot; -1 = unresolved. Reset per
|
||||
// in-game init (the table is rebuilt, though engine slots are stable) and
|
||||
// re-resolved lazily at fire time.
|
||||
int g_pewId = -1;
|
||||
|
||||
int PewId() {
|
||||
if (g_pewId < 0)
|
||||
g_pewId = Event::Custom::LookupByName("PLAYER_ENTERING_WORLD");
|
||||
return g_pewId;
|
||||
}
|
||||
|
||||
// Shared-hook interceptor. For PEW, re-broadcast with the payload and
|
||||
// suppress the engine's no-arg fire; everything else passes through.
|
||||
bool Intercept(int eventID) {
|
||||
const int pew = PewId();
|
||||
if (pew < 0 || eventID != pew)
|
||||
return false;
|
||||
|
||||
const bool isInitialLogin = g_atGlue;
|
||||
g_atGlue = false;
|
||||
const bool isReloadingUi = !isInitialLogin && g_scriptReloaded;
|
||||
g_scriptReloaded = false;
|
||||
|
||||
// Re-fire through the variadic dispatcher with the two booleans. true → 1
|
||||
// (%d), false → nil (%s + nullptr, which the dispatcher's pushstring
|
||||
// tail-jumps to pushnil).
|
||||
auto *const kNil = static_cast<const char *>(nullptr);
|
||||
if (isInitialLogin && isReloadingUi)
|
||||
Event::Custom::Fire(pew, "%d%d", 1, 1);
|
||||
else if (isInitialLogin)
|
||||
Event::Custom::Fire(pew, "%d%s", 1, kNil);
|
||||
else if (isReloadingUi)
|
||||
Event::Custom::Fire(pew, "%s%d", kNil, 1);
|
||||
else
|
||||
Event::Custom::Fire(pew, "%s%s", kNil, kNil);
|
||||
return true; // handled — suppress the original no-arg PEW fire
|
||||
}
|
||||
|
||||
const Event::SignalHook::AutoSubscribe _intercept{&Intercept};
|
||||
|
||||
// In-game Lua (re)init: login or /reload rebuilt the script state (never a
|
||||
// zone transition). Also re-arm the PEW slot lookup — the event table was
|
||||
// rebuilt.
|
||||
void OnInGameInit() {
|
||||
g_scriptReloaded = true;
|
||||
g_pewId = -1;
|
||||
}
|
||||
|
||||
// Glue-screen boot: we're at the login/char-select screen, so the next
|
||||
// enter-world will be a fresh login.
|
||||
void OnGlueInit() { g_atGlue = true; }
|
||||
|
||||
const Game::ModuleAutoRegister _inGame{&OnInGameInit};
|
||||
const Game::GlueModuleAutoRegister _glue{&OnGlueInit};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Event::EnteringWorld
|
||||
@@ -0,0 +1,49 @@
|
||||
// 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/>.
|
||||
|
||||
#include "SignalHook.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
namespace Event::SignalHook {
|
||||
|
||||
namespace {
|
||||
|
||||
// Chained at static-init time by each `AutoSubscribe` constructor, before
|
||||
// `DllMain`. Zero-initialized (namespace static) ahead of any dynamic init,
|
||||
// so the head is valid when subscribers link in.
|
||||
AutoSubscribe *g_head = nullptr;
|
||||
|
||||
// `FUN_FIRE_EVENT_NO_ARGS` is `__fastcall(int eventID)`; we mirror loot's
|
||||
// long-standing shape with a dummy EDX so the trampoline call matches the
|
||||
// register layout, and forward `0` for it (unused by the callee).
|
||||
using FireNoArgs_t = void(__fastcall *)(int eventID, int edx);
|
||||
FireNoArgs_t g_orig = nullptr;
|
||||
|
||||
void __fastcall Hook(int eventID, int /*edx*/) {
|
||||
for (AutoSubscribe *s = g_head; s != nullptr; s = s->next)
|
||||
if (s->fn(eventID))
|
||||
return; // a subscriber handled it — suppress the original fire
|
||||
g_orig(eventID, 0);
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _hook{
|
||||
Offsets::FUN_FIRE_EVENT_NO_ARGS, reinterpret_cast<void *>(&Hook),
|
||||
reinterpret_cast<void **>(&g_orig)};
|
||||
|
||||
} // namespace
|
||||
|
||||
AutoSubscribe::AutoSubscribe(Interceptor f) : fn(f), next(g_head) { g_head = this; }
|
||||
|
||||
} // namespace Event::SignalHook
|
||||
@@ -0,0 +1,47 @@
|
||||
// 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/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
// Shared interceptor for the engine's no-arg event dispatcher
|
||||
// `FUN_FIRE_EVENT_NO_ARGS` (`0x00703E50`) — the `__fastcall(int eventID)`
|
||||
// path every no-arg event broadcast goes through (PLAYER_ENTERING_WORLD,
|
||||
// LOOT_OPENED/CLOSED, zone changes, …), as opposed to the variadic
|
||||
// `FUN_FIRE_EVENT` used by events that carry a printf-style payload.
|
||||
//
|
||||
// MinHook allows only ONE hook per target address, and more than one feature
|
||||
// needs to intercept this dispatcher (loot silent-scan suppression, the
|
||||
// PLAYER_ENTERING_WORLD payload). So — exactly like `Tick::WorldTick` for the
|
||||
// per-frame tick — this module owns the single hook and fans out to
|
||||
// subscribers. Declare a file-scope `static const
|
||||
// Event::SignalHook::AutoSubscribe` in your module.
|
||||
//
|
||||
// An interceptor returns `true` when it has fully handled `eventID` and the
|
||||
// engine's original no-arg fire must be SUPPRESSED — either because it
|
||||
// swallowed the event (loot) or re-fired it a different way (the PEW payload
|
||||
// re-broadcasts through the variadic `FUN_FIRE_EVENT` with args). Returning
|
||||
// `false` lets the event fall through to the next subscriber and ultimately
|
||||
// the original. The FIRST subscriber to return `true` wins and the original
|
||||
// is skipped, so subscribers must claim disjoint event ids.
|
||||
|
||||
namespace Event::SignalHook {
|
||||
|
||||
using Interceptor = bool (*)(int eventID);
|
||||
|
||||
struct AutoSubscribe {
|
||||
explicit AutoSubscribe(Interceptor fn);
|
||||
Interceptor fn;
|
||||
AutoSubscribe *next;
|
||||
};
|
||||
|
||||
} // namespace Event::SignalHook
|
||||
+10
-14
@@ -27,6 +27,7 @@
|
||||
#include "../Game.h"
|
||||
#include "../Offsets.h"
|
||||
#include "../event/Custom.h"
|
||||
#include "../event/SignalHook.h"
|
||||
#include "../guid/Guid.h"
|
||||
#include "../tick/WorldTick.h"
|
||||
|
||||
@@ -115,9 +116,6 @@ using LootSlotLinkBuilder_t = const char *(__fastcall *)(uint32_t userFacingSlot
|
||||
using LootController_t = void(__fastcall *)(int lootStructPtr,
|
||||
int coin,
|
||||
int unk);
|
||||
using FireEventNoArgs_t = void(__fastcall *)(int eventID,
|
||||
int /*edx unused*/);
|
||||
|
||||
struct C3Vector {
|
||||
float x, y, z;
|
||||
};
|
||||
@@ -256,7 +254,6 @@ void StartLoot(uint64_t guid) {
|
||||
// === Hooks ===
|
||||
|
||||
LootController_t s_lootController_o = nullptr;
|
||||
FireEventNoArgs_t s_fireEventNoArgs_o = nullptr;
|
||||
|
||||
// `LOOT_OPENED` / `LOOT_CLOSED` get suppressed only while a scan is
|
||||
// actively interleaving open/close cycles, signaled by
|
||||
@@ -265,12 +262,14 @@ FireEventNoArgs_t s_fireEventNoArgs_o = nullptr;
|
||||
// `SendCloseLoot` that follows, then dropped before
|
||||
// `TryStartNext`-initiated CMSG_LOOTs go out. Every other engine
|
||||
// event fire — and normal play's loot events — pass through.
|
||||
void __fastcall FireEventNoArgs_h(int eventID, int /*unusedEdx*/) {
|
||||
if (s_scan.suppressEvents &&
|
||||
(eventID == EVENT_LOOT_OPENED || eventID == EVENT_LOOT_CLOSED)) {
|
||||
return;
|
||||
}
|
||||
s_fireEventNoArgs_o(eventID, 0);
|
||||
//
|
||||
// Runs as an interceptor on the shared no-arg event hook
|
||||
// (`Event::SignalHook`) rather than owning the hook directly, so it can
|
||||
// coexist with other features that intercept the same dispatcher (e.g. the
|
||||
// PLAYER_ENTERING_WORLD payload). Return true to swallow.
|
||||
bool SuppressLootEvents(int eventID) {
|
||||
return s_scan.suppressEvents &&
|
||||
(eventID == EVENT_LOOT_OPENED || eventID == EVENT_LOOT_CLOSED);
|
||||
}
|
||||
|
||||
// Intercepts the engine's loot-window state controller. Two paths:
|
||||
@@ -336,10 +335,7 @@ const Game::HookAutoRegister _hookController{
|
||||
reinterpret_cast<void *>(&LootController_h),
|
||||
reinterpret_cast<void **>(&s_lootController_o)};
|
||||
|
||||
const Game::HookAutoRegister _hookFireEvent{
|
||||
Offsets::FUN_FIRE_EVENT_NO_ARGS,
|
||||
reinterpret_cast<void *>(&FireEventNoArgs_h),
|
||||
reinterpret_cast<void **>(&s_fireEventNoArgs_o)};
|
||||
const Event::SignalHook::AutoSubscribe _lootIntercept{&SuppressLootEvents};
|
||||
|
||||
// === Tick (timeout only) ===
|
||||
|
||||
|
||||
+69
-16
@@ -13,20 +13,33 @@
|
||||
// `GetPosition` virtual (vtable slot 5) `CheckInteractDistance` uses:
|
||||
//
|
||||
// `UnitInRange(unit) → (inRange, checkedRange)` — 40-yard healing-
|
||||
// range check (fixed threshold on the squared distance).
|
||||
// range check. Reach-aware: matches the engine's own spell-range
|
||||
// formula (see below), so a 40-yard heal registers in-range against
|
||||
// a target whose *center* is slightly past 40 yards but whose body
|
||||
// is within reach.
|
||||
// `UnitDistanceSquared(unit) → (distanceSquared, checkedPosition)` —
|
||||
// the raw squared world distance player→unit. Squared because
|
||||
// nearly every consumer compares against a threshold (`distSq <=
|
||||
// range*range`) or ranks by nearest, neither of which needs the
|
||||
// sqrt; that's why retail exposes only the squared form (added
|
||||
// 5.0.4). Center-to-center — NOT reach-aware (that's UnitXP_SP3's
|
||||
// niche); equivalent to computing it from SuperWoW `UnitPosition`,
|
||||
// but self-contained (reads the position in C, no sibling-DLL
|
||||
// dependency, no clash with SuperWoW's own `UnitPosition`).
|
||||
// 5.0.4). Center-to-center — this one is NOT reach-adjusted (retail's
|
||||
// `UnitDistanceSquared` is also raw center distance); the reach
|
||||
// correction lives only in `UnitInRange`.
|
||||
//
|
||||
// Reach-awareness: the engine's spell-range helper `FUN_006e3480` compares
|
||||
// center distance against `baseRange + reachCaster + reachTarget`, where
|
||||
// each unit's reach is the bounding-radius float at `[m_objectFields +
|
||||
// 0x1F0]` (the same size factor the interact-distance and loot-range
|
||||
// checks add). So the effective in-range distance for a 40-yard heal is
|
||||
// `40 + playerReach + targetReach`. On big targets that's easily 2–3
|
||||
// yards past the raw 40, which is why a pure center-to-center 40-yard cap
|
||||
// reported out-of-range for a target the client could actually heal.
|
||||
|
||||
#include "Game.h"
|
||||
#include "unit/Position.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace Unit::Range {
|
||||
@@ -34,18 +47,44 @@ namespace Unit::Range {
|
||||
namespace {
|
||||
|
||||
constexpr float kRangeYards = 40.0f;
|
||||
constexpr float kRangeYardsSq = kRangeYards * kRangeYards;
|
||||
|
||||
// Squared world distance from the player to `token`'s unit. Returns true
|
||||
// and writes *outSq on success; false when either position is unavailable
|
||||
// (unresolved / absent token, or an object with no known position yet —
|
||||
// e.g. a party member outside the client's sync range). This false is
|
||||
// exactly the `checkedPosition = false` case retail flags.
|
||||
// Reads a unit's bounding radius (the engine's per-unit range "size
|
||||
// factor") from `[m_objectFields + 0x1F0]`. Returns 0 for a null object
|
||||
// or a unit whose descriptor isn't populated yet — a safe fallback that
|
||||
// degrades to the plain base-range check. Same field the loot/interact
|
||||
// range checks (loot/Nearby.cpp) read.
|
||||
float BoundingRadius(void *obj) {
|
||||
if (obj == nullptr)
|
||||
return 0.0f;
|
||||
auto *fields = *reinterpret_cast<const uint8_t *const *>(
|
||||
static_cast<const uint8_t *>(obj) + Offsets::OFF_UNIT_DESCRIPTOR);
|
||||
if (fields == nullptr)
|
||||
return 0.0f;
|
||||
return *reinterpret_cast<const float *>(
|
||||
fields + Offsets::OFF_UNIT_FIELD_BOUNDING_RADIUS);
|
||||
}
|
||||
|
||||
// Resolves `token` once and reads both its world position and bounding
|
||||
// radius. Returns false when the position is unavailable (unresolved /
|
||||
// absent token, or an object with no known position yet — e.g. a party
|
||||
// member outside the client's sync range). This false is exactly the
|
||||
// `checkedPosition = false` case retail flags.
|
||||
bool ReadPosAndReach(const char *token, float pos[3], float *reach) {
|
||||
void *obj = Unit::Position::ResolveToken(token);
|
||||
if (!Unit::Position::Read(obj, pos))
|
||||
return false;
|
||||
*reach = BoundingRadius(obj);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Squared world distance from the player to `token`'s unit (raw,
|
||||
// center-to-center; reach is applied by the caller when needed).
|
||||
bool PlayerToUnitDistSq(const char *token, float *outSq) {
|
||||
float unitPos[3] = {};
|
||||
float playerPos[3] = {};
|
||||
if (!Unit::Position::ReadToken(token, unitPos) ||
|
||||
!Unit::Position::ReadToken("player", playerPos))
|
||||
float reach = 0.0f;
|
||||
if (!ReadPosAndReach(token, unitPos, &reach) ||
|
||||
!ReadPosAndReach("player", playerPos, &reach))
|
||||
return false;
|
||||
const float dx = unitPos[0] - playerPos[0];
|
||||
const float dy = unitPos[1] - playerPos[1];
|
||||
@@ -72,14 +111,28 @@ int __fastcall Script_UnitInRange(void *L) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
float distSq = 0.0f;
|
||||
if (!PlayerToUnitDistSq(token, &distSq)) {
|
||||
float unitPos[3] = {};
|
||||
float playerPos[3] = {};
|
||||
float unitReach = 0.0f;
|
||||
float playerReach = 0.0f;
|
||||
if (!ReadPosAndReach(token, unitPos, &unitReach) ||
|
||||
!ReadPosAndReach("player", playerPos, &playerReach)) {
|
||||
Game::Lua::PushBool(L, false);
|
||||
Game::Lua::PushBool(L, false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
Game::Lua::PushBool(L, distSq <= kRangeYardsSq);
|
||||
const float dx = unitPos[0] - playerPos[0];
|
||||
const float dy = unitPos[1] - playerPos[1];
|
||||
const float dz = unitPos[2] - playerPos[2];
|
||||
const float distSq = dx * dx + dy * dy + dz * dz;
|
||||
|
||||
// Effective range = base + both units' reach, mirroring the engine's
|
||||
// spell-range formula (FUN_006e3480). Without the reach terms a target
|
||||
// whose center sits just past 40 yards but whose body is within reach
|
||||
// reports out-of-range even though a 40-yard heal would land.
|
||||
const float effRange = kRangeYards + playerReach + unitReach;
|
||||
Game::Lua::PushBool(L, distSq <= effRange * effRange);
|
||||
Game::Lua::PushBool(L, true);
|
||||
return 2;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user