RynthCore as of 2026-10-05 evening (internal 0a2043e): release 2026.10.5.20 - own dat reader, plugin manifests, UI/login hooks with Loot Editor drag-and-drop, server-message stream (API v78), raise attributes and skills (API v79), nameplate sizing and overlay opacity, engine reload held while a plugin is fighting, StatusAgent character sheet, world map and travel for DrakRemote
This commit is contained in:
parent
c3e15480e5
commit
913a2a00b6
110 changed files with 12560 additions and 1151 deletions
|
|
@ -419,6 +419,9 @@ internal static class AcMainThreadQueue
|
|||
// writes its own lines, so the chat window keeps the order lines arrived in.
|
||||
try { ChatCallbackHooks.OnMainThreadDrain(disarmed: false); } catch { }
|
||||
|
||||
// Keep the off-thread combat-mode cache true to the client (stale after a hot reload).
|
||||
CombatModeHooks.MainThreadRefresh();
|
||||
|
||||
// Deep-audit finding #22 (2026-06-18): these three queues are
|
||||
// documented as deliberately separate from the gesture-gated action
|
||||
// ring below specifically so appraisals/chat "can never get
|
||||
|
|
|
|||
|
|
@ -144,6 +144,8 @@ internal static class CharacterManagementHooks
|
|||
{
|
||||
Volatile.Write(ref _publishedMode, mode);
|
||||
Volatile.Write(ref _modePublished, 1);
|
||||
// Seeds UiFlowHooks' mode; drives its screen events when the UseNewMode hook isn't live.
|
||||
UiFlowHooks.OnModePolled(mode);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
|||
|
|
@ -106,19 +106,30 @@ internal static class ClientActionHooks
|
|||
return CombatActionHooks.CastSpell(targetId, spellId);
|
||||
}
|
||||
|
||||
// Movement calls below are the plugin API's only way in (PluginManager's callbacks), so each
|
||||
// one is traced here with the calling plugin: RynthLog.Move, behind RynthLog.MoveTraceEnabled.
|
||||
private static string MoveArg(System.FormattableString s) =>
|
||||
RynthLog.MoveTraceEnabled ? System.FormattableString.Invariant(s) : "";
|
||||
|
||||
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = MovementActionHooks.HoldKeyRun)
|
||||
{
|
||||
return MovementActionHooks.DoMovement(motion, speed, holdKey);
|
||||
bool ok = MovementActionHooks.DoMovement(motion, speed, holdKey);
|
||||
RynthLog.Move("DoMovement", MoveArg($"0x{motion:X8}, {speed:0.##}, {holdKey}"), ok, a: motion, b: (uint)holdKey);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool StopMovement(uint motion, int holdKey = MovementActionHooks.HoldKeyRun)
|
||||
{
|
||||
return MovementActionHooks.StopMovement(motion, holdKey);
|
||||
bool ok = MovementActionHooks.StopMovement(motion, holdKey);
|
||||
RynthLog.Move("StopMovement", MoveArg($"0x{motion:X8}, {holdKey}"), ok, a: motion, b: (uint)holdKey);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool JumpNonAutonomous(float extent)
|
||||
{
|
||||
return MovementActionHooks.JumpNonAutonomous(extent);
|
||||
bool ok = MovementActionHooks.JumpNonAutonomous(extent);
|
||||
RynthLog.Move("JumpNonAutonomous", MoveArg($"{extent:0.##}"), ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool SetAutonomyLevel(uint level)
|
||||
|
|
@ -128,37 +139,51 @@ internal static class ClientActionHooks
|
|||
|
||||
public static bool SetAutoRun(bool enabled)
|
||||
{
|
||||
return CommandInterpreterHooks.SetAutoRun(enabled);
|
||||
bool ok = CommandInterpreterHooks.SetAutoRun(enabled);
|
||||
RynthLog.Move("SetAutoRun", enabled ? "True" : "False", ok, a: enabled ? 1u : 0u);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool TapJump()
|
||||
{
|
||||
return CommandInterpreterHooks.TapJump();
|
||||
bool ok = CommandInterpreterHooks.TapJump();
|
||||
RynthLog.Move("TapJump", "", ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool CommenceJump()
|
||||
{
|
||||
return CommandInterpreterHooks.CommenceJump();
|
||||
bool ok = CommandInterpreterHooks.CommenceJump();
|
||||
RynthLog.Move("CommenceJump", "", ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool DoJump(bool autonomous)
|
||||
{
|
||||
return CommandInterpreterHooks.DoJump(autonomous);
|
||||
bool ok = CommandInterpreterHooks.DoJump(autonomous);
|
||||
RynthLog.Move("DoJump", autonomous ? "True" : "False", ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
|
||||
{
|
||||
return PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
|
||||
bool ok = PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
|
||||
RynthLog.Move("LaunchJumpWithMotion", MoveArg($"shift={shift}, w={holdW}, x={holdX}, z={holdZ}, c={holdC}"), ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool SetMotion(uint motion, bool enabled)
|
||||
{
|
||||
return CommandInterpreterHooks.SetMotion(motion, enabled);
|
||||
bool ok = CommandInterpreterHooks.SetMotion(motion, enabled);
|
||||
RynthLog.Move("SetMotion", MoveArg($"0x{motion:X8}, {enabled}"), ok, a: motion, b: enabled ? 1u : 0u);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool StopCompletely()
|
||||
{
|
||||
return CommandInterpreterHooks.StopCompletely();
|
||||
bool ok = CommandInterpreterHooks.StopCompletely();
|
||||
RynthLog.Move("StopCompletely", "", ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool TurnToHeading(float headingDegrees)
|
||||
|
|
@ -168,11 +193,12 @@ internal static class ClientActionHooks
|
|||
// Off AC's main thread (plugin pump) SetPlayerHeadingDirect only parks the
|
||||
// heading in AcMainThreadQueue's coalesced slot and returns true; the snap
|
||||
// (and the no-player CommandInterpreter fallback below) run in Drain.
|
||||
if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees))
|
||||
return true;
|
||||
|
||||
// Fallback: command interpreter gradual turn
|
||||
return CommandInterpreterHooks.TurnToHeading(headingDegrees);
|
||||
bool ok = PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees)
|
||||
// Fallback: command interpreter gradual turn
|
||||
|| CommandInterpreterHooks.TurnToHeading(headingDegrees);
|
||||
// Successive turns from one caller collapse into one line whatever the angle (nav steers every tick).
|
||||
RynthLog.Move("TurnToHeading", MoveArg($"{headingDegrees:0.0}"), ok, collapseByKind: true);
|
||||
return ok;
|
||||
}
|
||||
|
||||
public static bool TryGetPlayerHeading(out float headingDegrees)
|
||||
|
|
|
|||
|
|
@ -301,6 +301,44 @@ internal static class CombatModeHooks
|
|||
PluginManager.QueueCombatModeChange(currentCombatMode, previousCombatMode);
|
||||
}
|
||||
|
||||
// Main-thread refresh of the off-thread cache (2026-10-05). After the engine hot reload at
|
||||
// 13:42:55 Drakkon was in Magic (he had just cast Heal Self), but _lastObservedCombatMode
|
||||
// starts at NonCombat in a new engine and only the SetCombatMode detour (a mode CHANGE) or a
|
||||
// main-thread ReadCurrentCombatMode moved it. The plugin pump reads off the main thread, so
|
||||
// the engine synced "combat mode 1" to the plugins at 13:43:03 and RynthAi's heal at 13:43:12
|
||||
// asked for a Magic stance the client already had (RequestCombatMode req=8 clientField=8),
|
||||
// then waited out the stance settle. Drain calls this every frame; it reads the client's field
|
||||
// at most every MainThreadRefreshMs and, when the cache was wrong, heals it and tells the
|
||||
// plugins the way the detour does.
|
||||
private static long _lastMainThreadRefreshMs;
|
||||
private const long MainThreadRefreshMs = 250;
|
||||
|
||||
/// <summary>AC's main thread only (AcMainThreadQueue.Drain).</summary>
|
||||
internal static unsafe void MainThreadRefresh()
|
||||
{
|
||||
if (!IsInstalled) return;
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _lastMainThreadRefreshMs < MainThreadRefreshMs) return;
|
||||
_lastMainThreadRefreshMs = now;
|
||||
try
|
||||
{
|
||||
IntPtr slot = (IntPtr)_combatSystemPtrAddr;
|
||||
if (!ClientObjectHooks.IsReadablePointer(slot)) return;
|
||||
IntPtr combatSystem = *(IntPtr*)slot;
|
||||
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset)) return;
|
||||
int raw = NormalizeCombatMode(*(int*)(combatSystem + CombatModeOffset));
|
||||
if (raw is not (CombatActionHooks.CombatModeNonCombat or CombatActionHooks.CombatModeMelee
|
||||
or CombatActionHooks.CombatModeMissile or CombatActionHooks.CombatModeMagic))
|
||||
return; // not a mode (a singleton being torn down): leave the cache alone
|
||||
int previous = Interlocked.Exchange(ref _lastObservedCombatMode, raw);
|
||||
if (raw == previous) return;
|
||||
RynthLog.Compat($"CombatModeHooks: the cached combat mode was {previous} but the client reads {raw} " +
|
||||
"(no SetCombatMode seen since this engine started, e.g. after a hot reload): cache healed, plugins told.");
|
||||
PluginManager.QueueCombatModeChange(raw, previous);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static int NormalizeCombatMode(int combatMode)
|
||||
{
|
||||
return combatMode switch
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@
|
|||
// Want / Current / RefreshSoon any thread (the panel: AC's render thread).
|
||||
//
|
||||
// Demand-driven: nothing is read unless a reader called Want in the last 2 s,
|
||||
// then at most every 500 ms. Reads go into one preallocated work buffer; a new
|
||||
// then at most every 500 ms (WantSlow, the plugin API's GetTrainingInfo: in the
|
||||
// last 5 s, then at most every 2 s). Reads go into one preallocated work buffer; a new
|
||||
// snapshot object is published (and allocated) only when something changed,
|
||||
// so an idle open panel costs a compare every half second.
|
||||
// ============================================================================
|
||||
|
|
@ -173,6 +174,8 @@ internal static class PlayerProgressHooks
|
|||
{
|
||||
private const int RefreshMs = 500;
|
||||
private const int WantWindowMs = 2000;
|
||||
private const int SlowRefreshMs = 2000;
|
||||
private const int SlowWantWindowMs = 5000;
|
||||
|
||||
// StatMod type flags (ACE EnchantmentTypeFlags) that mark a buff on a stat.
|
||||
internal const uint ModAttribute = 0x1, ModSecondAttribute = 0x2, ModSkill = 0x10;
|
||||
|
|
@ -180,7 +183,9 @@ internal static class PlayerProgressHooks
|
|||
private const uint ModAnyStat = ModAttribute | ModSecondAttribute | ModSkill;
|
||||
|
||||
private static long _wantedUntilMs;
|
||||
private static long _slowWantedUntilMs;
|
||||
private static long _nextReadMs;
|
||||
private static long _lastReadMs;
|
||||
private static int _version;
|
||||
private static PlayerProgress? _published;
|
||||
|
||||
|
|
@ -198,9 +203,23 @@ internal static class PlayerProgressHooks
|
|||
public static void Want() =>
|
||||
Volatile.Write(ref _wantedUntilMs, Environment.TickCount64 + WantWindowMs);
|
||||
|
||||
/// <summary>
|
||||
/// A background reader (the plugin API, TrainingApi) wants data for the next 5 s, read at
|
||||
/// most every 2 s, so a plugin polling every few seconds doesn't keep the 2 Hz panel rate up.
|
||||
/// Any thread.
|
||||
/// </summary>
|
||||
public static void WantSlow() =>
|
||||
Volatile.Write(ref _slowWantedUntilMs, Environment.TickCount64 + SlowWantWindowMs);
|
||||
|
||||
/// <summary>Read again at the next main-thread tick (after a raise). Any thread.</summary>
|
||||
public static void RefreshSoon() => Volatile.Write(ref _nextReadMs, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Environment.TickCount64 of the last successful read, changed or not (0 = never), so a
|
||||
/// reader can tell how old <see cref="Current"/>'s numbers are. Any thread.
|
||||
/// </summary>
|
||||
public static long LastReadMs => Volatile.Read(ref _lastReadMs);
|
||||
|
||||
/// <summary>The last published read, or null. Never written again once published. Any thread.</summary>
|
||||
public static PlayerProgress? Current => Volatile.Read(ref _published);
|
||||
|
||||
|
|
@ -213,21 +232,25 @@ internal static class PlayerProgressHooks
|
|||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return;
|
||||
long now = Environment.TickCount64;
|
||||
if (now > Volatile.Read(ref _wantedUntilMs) || now < Volatile.Read(ref _nextReadMs))
|
||||
bool panel = now <= Volatile.Read(ref _wantedUntilMs);
|
||||
if ((!panel && now > Volatile.Read(ref _slowWantedUntilMs)) || now < Volatile.Read(ref _nextReadMs))
|
||||
return;
|
||||
Volatile.Write(ref _nextReadMs, now + RefreshMs);
|
||||
Volatile.Write(ref _nextReadMs, now + (panel ? RefreshMs : SlowRefreshMs));
|
||||
|
||||
if (!ClientObjectHooks.ReadPlayerProgressLive(Work))
|
||||
return;
|
||||
CopyStatBuffs(Work);
|
||||
|
||||
PlayerProgress? current = Volatile.Read(ref _published);
|
||||
if (current != null && current.SameAs(Work))
|
||||
return;
|
||||
var snapshot = new PlayerProgress();
|
||||
snapshot.CopyFrom(Work);
|
||||
snapshot.Version = ++_version;
|
||||
Volatile.Write(ref _published, snapshot);
|
||||
if (current == null || !current.SameAs(Work))
|
||||
{
|
||||
var snapshot = new PlayerProgress();
|
||||
snapshot.CopyFrom(Work);
|
||||
snapshot.Version = ++_version;
|
||||
Volatile.Write(ref _published, snapshot);
|
||||
}
|
||||
// After publishing: a reader that sees this time sees this read's numbers.
|
||||
Volatile.Write(ref _lastReadMs, Environment.TickCount64);
|
||||
}
|
||||
|
||||
/// <summary>The player's enchantments that change a skill, attribute or vital (not vitae).</summary>
|
||||
|
|
|
|||
|
|
@ -31,6 +31,10 @@
|
|||
//
|
||||
// Every call runs on AC's main thread: off it (or with defer) the request goes
|
||||
// through AcMainThreadQueue (ActionKind.Train) and the drain calls back in.
|
||||
// Only in the world (TrainingApi.InWorld), checked again when the drain sends:
|
||||
// a raise queued just before a logout is dropped, not sent to the next screen.
|
||||
// The plugin API (v79) reaches these through TrainingApi, which also works the
|
||||
// XP out and checks it (TrainingCosts).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -112,6 +116,11 @@ internal static unsafe class PlayerTraining
|
|||
{
|
||||
if (!Bound(kind) || !ValidTarget(kind, stype) || xp == 0)
|
||||
return false;
|
||||
if (!TrainingApi.InWorld)
|
||||
{
|
||||
RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world");
|
||||
return false;
|
||||
}
|
||||
if (defer || !MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp);
|
||||
|
||||
|
|
|
|||
|
|
@ -320,6 +320,9 @@ internal static class RadarHooks
|
|||
IntPtr inst = _gmRadarUIInstance;
|
||||
if (inst == IntPtr.Zero)
|
||||
return false;
|
||||
// Outside the world AC has freed the radar panel this points at (UiFlowHooks).
|
||||
if (!UiFlowHooks.InWorldOrUnknown || UiFlowHooks.ClientCleanupStarted)
|
||||
return false;
|
||||
if (_uiElementGetSurfaceBoxAddress == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// We read the function address, install a MinHook detour, call through to the
|
||||
/// original on every receive, then hand the buffer to RawPacketParser for
|
||||
/// opcode extraction. The hook is purely read-only and never modifies traffic.
|
||||
/// It also feeds Net.ServerMessageStream (API v78), which copies fragment datagrams
|
||||
/// for reassembly on the plugin pump while a plugin wants server messages.
|
||||
/// </summary>
|
||||
internal static class RawPacketHooks
|
||||
{
|
||||
|
|
@ -82,6 +84,11 @@ internal static class RawPacketHooks
|
|||
// This guard prevents any parser bug from crashing the client.
|
||||
try
|
||||
{
|
||||
// v78 server-message stream: a volatile check, and while a plugin wants
|
||||
// messages, one copy into a ring for the pump (never blocks, never allocates).
|
||||
// A MSG_PEEK (0x2) read leaves the datagram queued; the real read copies it.
|
||||
if ((flags & 0x2) == 0)
|
||||
Net.ServerMessageStream.OnDatagram((byte*)buf, bytesRead);
|
||||
RawPacketParser.Parse((byte*)buf, bytesRead);
|
||||
}
|
||||
catch
|
||||
|
|
|
|||
|
|
@ -43,12 +43,20 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// never sees it; every other "/rv" line still goes to the plugin.</item>
|
||||
/// <item><c>/rc server [auto|aelrynth|other]</c> — which server the engine detects
|
||||
/// (<see cref="ServerInfo"/>) and why; aelrynth/other force it for this session.</item>
|
||||
/// <item><c>/rc hooks [on|off <name>]</c> (alias <c>/rc uihooks</c>) — the UI hooks
|
||||
/// (screen mode, client cleanup, tooltip, drag/drop; <see cref="UiHookRegistry"/>):
|
||||
/// status, or switch one off/on (now and in engine.json).</item>
|
||||
/// <item><c>/rc mastery</c> — the Aelrynth mastery feed's state (<see cref="MasteryFeed"/>),
|
||||
/// and ask the server for /mastery-data again.</item>
|
||||
/// <item><c>/rc worldlayer [auto|uipass|transition|endscene]</c> — where the world overlays
|
||||
/// (nameplates, combat text, Nav3D markers) draw in AC's frame
|
||||
/// (<see cref="D3D9.Nav3DRenderInjector"/>): alone it reports the path and counters;
|
||||
/// a mode forces it for this session (A/B checks). Auto at every start; not saved.</item>
|
||||
/// <item><c>/rc netmsg [status|on|off|log on|off|capture on|off]</c> - the reassembled
|
||||
/// server-message stream for plugins (<see cref="Net.ServerMessageStream"/>, API v78):
|
||||
/// counters; on/off for this session (engine.json "ServerMessageStream": false is the
|
||||
/// kill switch); log = the SDK parsers run on live messages, results to the log;
|
||||
/// capture = raw datagrams to a .rnc file for tools/NetMessageTests.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class RynthCoreChatCommands
|
||||
|
|
@ -153,6 +161,26 @@ internal static class RynthCoreChatCommands
|
|||
return true;
|
||||
}
|
||||
|
||||
// /rc hooks [on|off <name>] : the UI hooks (screen mode, client cleanup, tooltip, drag/drop)
|
||||
if (IsVerb(sub, "hooks", out string hooksArgs) || IsVerb(sub, "uihooks", out hooksArgs))
|
||||
{
|
||||
try { HandleHooksCommand(hooksArgs); }
|
||||
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hooks failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream
|
||||
if (IsVerb(sub, "netmsg", out string netArgs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (string l in Net.ServerMessageStream.HandleCommand(netArgs))
|
||||
Reply(l);
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc netmsg failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc vtank [clear] : what the engine knows about VTank's macro (Decal bridge only);
|
||||
// clear = VTank was stopped with its own button, which the engine can't see.
|
||||
if (IsVerb(sub, "vtank", out string vtankArgs))
|
||||
|
|
@ -660,6 +688,30 @@ internal static class RynthCoreChatCommands
|
|||
return s != null && float.TryParse(s, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /rc hooks: one line per UI hook (UiHookRegistry: UseNewMode, ClientCleanup,
|
||||
/// StartTooltip, ResetTooltip, CheckTooltip, StartDragandDrop, CatchDroppedItem) with
|
||||
/// its address, how it was found, on/off and how often it fired, then the screen and
|
||||
/// tooltip/drag state. "/rc hooks off <name>" makes that hook pass straight to AC
|
||||
/// now and leaves it out at the next start (engine.json DisabledUiHooks); "on" undoes it.
|
||||
/// </summary>
|
||||
private static void HandleHooksCommand(string args)
|
||||
{
|
||||
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (parts.Length == 2 && (parts[0].Equals("on", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("off", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Reply(UiHookRegistry.SetEnabled(parts[1], parts[0].Equals("on", StringComparison.OrdinalIgnoreCase)));
|
||||
return;
|
||||
}
|
||||
if (parts.Length != 0 && !(parts.Length == 1 && parts[0].Equals("status", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Reply("Usage: /rc hooks [status] | /rc hooks on|off <name>");
|
||||
return;
|
||||
}
|
||||
foreach (string line in UiHookRegistry.DescribeLines())
|
||||
Reply(line);
|
||||
}
|
||||
|
||||
/// <summary>"on"/"off" sets; anything else (or nothing) toggles.</summary>
|
||||
private static bool Flag(string? value, bool current) =>
|
||||
value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current };
|
||||
|
|
|
|||
|
|
@ -347,10 +347,12 @@ internal static class SmartBoxHooks
|
|||
// v70: the sequence and its error code as one 64-bit value, so a reader
|
||||
// on the plugin pump never pairs one UseDone's number with another's code.
|
||||
System.Threading.Interlocked.Exchange(ref _useDoneLast, ((long)(uint)seq << 32) | err);
|
||||
if (_useDoneLogCount < 25)
|
||||
// Every one while RynthLog.ActionDoneTraceEnabled (the default; 2026-10-05: the
|
||||
// first 25 of a session couldn't show which completion a held cast was waiting on).
|
||||
if (RynthLog.ActionDoneTraceEnabled || _useDoneLogCount < 25)
|
||||
{
|
||||
_useDoneLogCount++;
|
||||
RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}");
|
||||
RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}{(err == 0x1D ? " (too busy)" : err == 0 ? " (done)" : "")}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
278
src/RynthCore.Engine/Compatibility/TrainingApi.cs
Normal file
278
src/RynthCore.Engine/Compatibility/TrainingApi.cs
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/TrainingApi.cs
|
||||
//
|
||||
// Plugin API v79: spending experience the way the retail character window's
|
||||
// "+" does (docs/IMGUI_SKILLS.md "Raising"), for plugins (the RynthRemote
|
||||
// plugin, so the DrakRemote phone app can raise from the Skills tab).
|
||||
//
|
||||
// GetTrainingInfo the numbers a raise needs and what it costs: unassigned XP,
|
||||
// skill credits, and per attribute / vital / skill the ranks,
|
||||
// XP spent, base and buffed value, the XP for +1 and +10, how
|
||||
// many ranks the unassigned XP buys, the credits to train.
|
||||
// Raise n ranks of one attribute, vital or trained skill. The engine
|
||||
// works the XP out from the same numbers (portal XpTable) and
|
||||
// refuses unless it equals what the caller confirmed.
|
||||
// TrainSkill an untrained skill -> trained, for exactly the SkillTable's
|
||||
// credit price.
|
||||
//
|
||||
// Sources: PlayerProgressHooks (the player's qualities, read on AC's main thread;
|
||||
// WantSlow keeps them coming every 2 s while a plugin asks) and SkillDat (the
|
||||
// portal SkillTable and XpTable, read once in the background). The sends are
|
||||
// PlayerTraining's: the client's own CM_Train senders, on AC's main thread
|
||||
// (queued in AcMainThreadQueue from any other thread).
|
||||
//
|
||||
// Guards: in the world only (login complete, the world screen, no logout, no
|
||||
// teardown, the snapshot is this character's); numbers at most 3 s old (else
|
||||
// a read is asked for and Stale comes back: try again a moment later); one
|
||||
// raise at a time (Busy until the unassigned XP or the credits change, or 5 s).
|
||||
// Any thread.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using RynthCore.Engine.ImGuiBackend.Panels;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static unsafe class TrainingApi
|
||||
{
|
||||
/// <summary>Numbers older than this are not raised against.</summary>
|
||||
internal const int StaleAfterMs = 3000;
|
||||
private const int BusyMs = 5000;
|
||||
|
||||
public const uint KindAttribute = 1, KindVital = 2, KindSkill = 3;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static long _busyUntilMs;
|
||||
private static long _busyUnassigned;
|
||||
private static int _busyCredits;
|
||||
|
||||
/// <summary>The player is in the world and its objects are live (same test as the
|
||||
/// main-thread snapshots, plus the world screen and no client cleanup). Any thread.</summary>
|
||||
public static bool InWorld =>
|
||||
LoginLifecycleHooks.HasObservedLoginComplete
|
||||
&& UiFlowHooks.InWorldOrUnknown
|
||||
&& !UiFlowHooks.ClientCleanupStarted
|
||||
&& !LogoutLifecycleHooks.HasObservedLogout
|
||||
&& !DbCacheTeardownHooks.TeardownActive
|
||||
&& ClientHelperHooks.GetPlayerId() != 0;
|
||||
|
||||
/// <summary>v79 GetTrainingInfo. Returns the number of entries there are (entries may be null to
|
||||
/// ask; at most maxEntries are written). 0 while there is nothing to report.</summary>
|
||||
public static int GetInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries)
|
||||
{
|
||||
PlayerProgressHooks.WantSlow();
|
||||
SkillDat.EnsureLoadQueued();
|
||||
|
||||
bool inWorld = InWorld;
|
||||
uint playerId = inWorld ? ClientHelperHooks.GetPlayerId() : 0;
|
||||
PlayerProgress? s = PlayerProgressHooks.Current;
|
||||
if (s != null && (s.PlayerId != playerId || !inWorld)) s = null;
|
||||
SkillDatTables? dat = SkillDat.Tables;
|
||||
long now = Environment.TickCount64;
|
||||
long readAt = PlayerProgressHooks.LastReadMs;
|
||||
|
||||
int count = 0;
|
||||
if (s != null && dat != null)
|
||||
{
|
||||
count = 6 + 3;
|
||||
for (uint id = 1; id <= PlayerProgress.MaxSkill; id++)
|
||||
if (dat.Skills.ContainsKey(id)) count++;
|
||||
}
|
||||
|
||||
if (info != null && info->Size >= 8)
|
||||
{
|
||||
TrainingInfoNative o = default;
|
||||
uint flags = 0;
|
||||
if (inWorld) flags |= TrainingInfoFlags.InWorld;
|
||||
if (PlayerTraining.Available) flags |= TrainingInfoFlags.RaiseBound;
|
||||
if (PlayerTraining.TrainAvailable) flags |= TrainingInfoFlags.TrainBound;
|
||||
if (s != null) flags |= TrainingInfoFlags.HaveNumbers;
|
||||
if (dat != null) flags |= TrainingInfoFlags.HaveTables;
|
||||
if (IsBusy(s, now)) flags |= TrainingInfoFlags.Busy;
|
||||
o.Flags = flags;
|
||||
o.SnapshotVersion = s != null ? (uint)s.Version : 0;
|
||||
o.AgeMs = s != null && readAt > 0 ? (uint)Math.Clamp(now - readAt, 0, uint.MaxValue - 1) : uint.MaxValue;
|
||||
o.UnassignedXp = s?.UnassignedXp ?? -1;
|
||||
o.TotalXp = s?.TotalXp ?? -1;
|
||||
o.Level = s?.Level ?? 0;
|
||||
o.SkillCredits = s?.SkillCredits ?? -1;
|
||||
o.EntryCount = count;
|
||||
o.StaleAfterMs = StaleAfterMs;
|
||||
uint n = Math.Min(info->Size, (uint)sizeof(TrainingInfoNative));
|
||||
Buffer.MemoryCopy(&o, info, n, n);
|
||||
info->Size = n;
|
||||
}
|
||||
|
||||
if (entries == null || maxEntries <= 0 || s == null || dat == null)
|
||||
return count;
|
||||
|
||||
int w = 0;
|
||||
for (uint a = 1; a <= 6 && w < maxEntries; a++)
|
||||
entries[w++] = Entry(KindAttribute, a, 0, s.AttrRanks[a], s.AttrXpSpent[a], s.AttrInit[a],
|
||||
(int)s.AttrBase[a], (int)s.AttrBuffed[a], dat.Xp.AttributeXp, s.UnassignedXp);
|
||||
for (uint v = 1; v <= 3 && w < maxEntries; v++)
|
||||
entries[w++] = Entry(KindVital, v * 2 - 1, 0, s.VitalRanks[v], s.VitalXpSpent[v], s.VitalInit[v],
|
||||
(int)s.VitalBase[v], (int)s.VitalBuffed[v], dat.Xp.VitalXp, s.UnassignedXp);
|
||||
for (uint id = 1; id <= PlayerProgress.MaxSkill && w < maxEntries; id++)
|
||||
{
|
||||
if (!dat.Skills.TryGetValue(id, out SkillDatEntry? e)) continue;
|
||||
uint cls = s.SkillClass[id];
|
||||
TrainingEntryNative x = Entry(KindSkill, id, cls, s.SkillRanks[id], s.SkillXpSpent[id], s.SkillInit[id],
|
||||
s.SkillBase[id], s.SkillBuffed[id], TrainingCosts.TableFor(dat.Xp, KindSkill, cls), s.UnassignedXp);
|
||||
if (e.UsableUntrained) x.Flags |= TrainingEntryFlags.UsableUntrained;
|
||||
if (cls < 2)
|
||||
{
|
||||
x.TrainCredits = Math.Max(0, e.TrainedCost);
|
||||
if (x.TrainCredits > 0) x.Flags |= TrainingEntryFlags.Trainable;
|
||||
}
|
||||
entries[w++] = x;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static TrainingEntryNative Entry(uint kind, uint stype, uint cls, uint ranks, uint spent, uint init,
|
||||
int baseValue, int buffed, uint[]? table, long unassigned)
|
||||
{
|
||||
var x = new TrainingEntryNative
|
||||
{
|
||||
Kind = kind, Stype = stype, Class = cls, Ranks = ranks, XpSpent = spent, Innate = init,
|
||||
Base = baseValue, Buffed = buffed, CostOne = -1, CostTen = -1,
|
||||
};
|
||||
if (table != null && table.Length > 0)
|
||||
{
|
||||
x.RanksLeft = TrainingCosts.RanksLeft(table, ranks);
|
||||
if (x.RanksLeft == 0) x.Flags |= TrainingEntryFlags.AtTop;
|
||||
else x.Flags |= TrainingEntryFlags.Raisable;
|
||||
x.CostOne = TrainingCosts.CostOf(table, ranks, spent, 1);
|
||||
x.CostTen = TrainingCosts.CostOf(table, ranks, spent, 10);
|
||||
x.Affordable = TrainingCosts.Affordable(table, ranks, spent, Math.Max(0, unassigned));
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
private static bool IsBusy(PlayerProgress? s, long now)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (now >= _busyUntilMs) return false;
|
||||
// The server answered: the unassigned XP or the credits moved.
|
||||
if (s != null && (s.UnassignedXp != _busyUnassigned || s.SkillCredits != _busyCredits))
|
||||
{
|
||||
_busyUntilMs = 0;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The snapshot to act on, or why not.</summary>
|
||||
private static RaiseStatus Ready(out PlayerProgress? s, out SkillDatTables? dat)
|
||||
{
|
||||
PlayerProgressHooks.WantSlow();
|
||||
SkillDat.EnsureLoadQueued();
|
||||
s = null;
|
||||
dat = SkillDat.Tables;
|
||||
if (!InWorld) return RaiseStatus.NotInWorld;
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
s = PlayerProgressHooks.Current;
|
||||
if (s == null || s.PlayerId != playerId || dat == null || !s.AttributeCacheRead || !s.SkillTableRead)
|
||||
{
|
||||
PlayerProgressHooks.RefreshSoon();
|
||||
return RaiseStatus.NotReady;
|
||||
}
|
||||
long read = PlayerProgressHooks.LastReadMs;
|
||||
if (read <= 0 || Environment.TickCount64 - read > StaleAfterMs)
|
||||
{
|
||||
PlayerProgressHooks.RefreshSoon();
|
||||
return RaiseStatus.Stale;
|
||||
}
|
||||
if (IsBusy(s, Environment.TickCount64)) return RaiseStatus.Busy;
|
||||
return RaiseStatus.Sent;
|
||||
}
|
||||
|
||||
/// <summary>v79 Raise: <paramref name="ranks"/> ranks of one attribute (1..6), vital (1 health,
|
||||
/// 3 stamina, 5 mana) or trained/specialized skill. <paramref name="xpSent"/> = the XP sent.</summary>
|
||||
public static RaiseStatus Raise(uint kind, uint stype, uint ranks, long expectedXp, out long xpSent)
|
||||
{
|
||||
xpSent = 0;
|
||||
if (kind is < KindAttribute or > KindSkill || ranks < 1 || ranks > TrainingCosts.MaxRanksPerRaise || expectedXp < 0
|
||||
|| !ValidTarget(kind, stype))
|
||||
return RaiseStatus.BadArguments;
|
||||
if (!PlayerTraining.Available) return RaiseStatus.Unavailable;
|
||||
|
||||
RaiseStatus ready = Ready(out PlayerProgress? s, out SkillDatTables? dat);
|
||||
if (ready != RaiseStatus.Sent) return ready;
|
||||
|
||||
uint[]? table;
|
||||
uint have, spent;
|
||||
switch (kind)
|
||||
{
|
||||
case KindAttribute:
|
||||
table = dat!.Xp.AttributeXp; have = s!.AttrRanks[stype]; spent = s.AttrXpSpent[stype];
|
||||
break;
|
||||
case KindVital:
|
||||
uint v = (stype + 1) / 2;
|
||||
table = dat!.Xp.VitalXp; have = s!.VitalRanks[v]; spent = s.VitalXpSpent[v];
|
||||
break;
|
||||
default:
|
||||
table = TrainingCosts.TableFor(dat!.Xp, KindSkill, s!.SkillClass[stype]); have = s.SkillRanks[stype]; spent = s.SkillXpSpent[stype];
|
||||
break;
|
||||
}
|
||||
|
||||
RaiseStatus check = TrainingCosts.CheckRaise(table, have, spent, s.UnassignedXp, (int)ranks, expectedXp, out long cost);
|
||||
if (check != RaiseStatus.Sent) return check;
|
||||
|
||||
var trainKind = kind switch
|
||||
{
|
||||
KindAttribute => PlayerTraining.TrainKind.Attribute,
|
||||
KindVital => PlayerTraining.TrainKind.Vital,
|
||||
_ => PlayerTraining.TrainKind.Skill,
|
||||
};
|
||||
AcActionTrace.Record("Raise", kind << 16 | stype, (uint)cost);
|
||||
if (!PlayerTraining.Raise(trainKind, stype, (uint)cost)) return RaiseStatus.SendFailed;
|
||||
MarkBusy(s);
|
||||
xpSent = cost;
|
||||
RynthLog.Compat($"TrainingApi: raise {trainKind} {stype} +{ranks} for {cost:N0} XP (plugin)");
|
||||
return RaiseStatus.Sent;
|
||||
}
|
||||
|
||||
/// <summary>v79 TrainSkill: untrained -> trained for exactly the SkillTable's credit price.</summary>
|
||||
public static RaiseStatus TrainSkill(uint stype, int expectedCredits)
|
||||
{
|
||||
if (stype < 1 || stype > PlayerProgress.MaxSkill || expectedCredits < 0) return RaiseStatus.BadArguments;
|
||||
if (!PlayerTraining.TrainAvailable) return RaiseStatus.Unavailable;
|
||||
|
||||
RaiseStatus ready = Ready(out PlayerProgress? s, out SkillDatTables? dat);
|
||||
if (ready != RaiseStatus.Sent) return ready;
|
||||
if (!dat!.Skills.TryGetValue(stype, out SkillDatEntry? e)) return RaiseStatus.NotRaisable;
|
||||
|
||||
RaiseStatus check = TrainingCosts.CheckTrain(s!.SkillClass[stype], e.TrainedCost, s.SkillCredits, expectedCredits);
|
||||
if (check != RaiseStatus.Sent) return check;
|
||||
|
||||
AcActionTrace.Record("TrainSkill", stype, (uint)e.TrainedCost);
|
||||
if (!PlayerTraining.TrainSkill(stype, (uint)e.TrainedCost)) return RaiseStatus.SendFailed;
|
||||
MarkBusy(s);
|
||||
RynthLog.Compat($"TrainingApi: train skill {stype} for {e.TrainedCost} credits (plugin)");
|
||||
return RaiseStatus.Sent;
|
||||
}
|
||||
|
||||
private static bool ValidTarget(uint kind, uint stype) => kind switch
|
||||
{
|
||||
KindAttribute => stype >= 1 && stype <= 6,
|
||||
KindVital => stype is 1 or 3 or 5,
|
||||
KindSkill => stype >= 1 && stype <= PlayerProgress.MaxSkill,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static void MarkBusy(PlayerProgress s)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_busyUntilMs = Environment.TickCount64 + BusyMs;
|
||||
_busyUnassigned = s.UnassignedXp;
|
||||
_busyCredits = s.SkillCredits;
|
||||
}
|
||||
PlayerProgressHooks.RefreshSoon();
|
||||
}
|
||||
}
|
||||
191
src/RynthCore.Engine/Compatibility/TrainingCosts.cs
Normal file
191
src/RynthCore.Engine/Compatibility/TrainingCosts.cs
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/TrainingCosts.cs
|
||||
//
|
||||
// The XP arithmetic behind raising an attribute, a vital or a skill, and the
|
||||
// checks a raise from the plugin API passes before anything is sent. Pure code
|
||||
// (no AC memory, no engine state), so tools/TrainingCostTests compiles it in and
|
||||
// runs it against the XpTable of a real client_portal.dat.
|
||||
//
|
||||
// XpTable 0x0E000018 (ACE.DatLoader XpTable; the server raises against the same
|
||||
// table): file id u32; counts i32 for attributes, vitals, trained skills,
|
||||
// specialized skills, then the level count u32; then count+1 u32 each for
|
||||
// attributes, vitals, trained and specialized skills, count+1 u64 levels and
|
||||
// count+1 u32 skill credits per level. Entry n is the total XP spent at rank n.
|
||||
//
|
||||
// Cost of n raises: table[ranks + n] - xpSpent (ACE Player.SpendAttributeXp /
|
||||
// SpendSkillXp take an XP amount and raise as many ranks as it covers; the retail
|
||||
// character window sends exactly this for "+1" and "+10": gmAttributeUI /
|
||||
// gmSkillUI GetCostToRaise / GetCostToRaise10 -> CM_Train::Event_Train*).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>The four raise tables of the portal XpTable (index = rank, value = total XP at that rank).</summary>
|
||||
internal sealed class XpTableData
|
||||
{
|
||||
public uint[] AttributeXp = Array.Empty<uint>();
|
||||
public uint[] VitalXp = Array.Empty<uint>();
|
||||
public uint[] TrainedXp = Array.Empty<uint>();
|
||||
public uint[] SpecializedXp = Array.Empty<uint>();
|
||||
public ulong[] LevelXp = Array.Empty<ulong>();
|
||||
}
|
||||
|
||||
/// <summary>The plugin API's raise and train results (RynthCoreAPI.RaiseFn / TrainSkillFn, v79).</summary>
|
||||
internal enum RaiseStatus
|
||||
{
|
||||
Sent = 1,
|
||||
/// <summary>The client's raise senders aren't bound on this build.</summary>
|
||||
Unavailable = 0,
|
||||
NotInWorld = -1,
|
||||
BadArguments = -2,
|
||||
/// <summary>No player snapshot or no XP table yet (both are being fetched; try again in a second).</summary>
|
||||
NotReady = -3,
|
||||
/// <summary>The numbers are older than the freshness limit; a new read was asked for. Try again in a second.</summary>
|
||||
Stale = -4,
|
||||
/// <summary>The cost the caller expected isn't the cost now (something changed: refresh and ask again).</summary>
|
||||
CostChanged = -5,
|
||||
/// <summary>Not enough unassigned XP (or skill credits for a train).</summary>
|
||||
NotEnough = -6,
|
||||
/// <summary>Can't be raised: at or past the top rank, an untrained skill, or a skill that can't be trained.</summary>
|
||||
NotRaisable = -7,
|
||||
/// <summary>An earlier raise or train hasn't shown up in the numbers yet (5 s at most).</summary>
|
||||
Busy = -8,
|
||||
/// <summary>The send failed or the action queue was full.</summary>
|
||||
SendFailed = -9,
|
||||
}
|
||||
|
||||
internal static class TrainingCosts
|
||||
{
|
||||
/// <summary>Most ranks one API raise may buy (the retail window offers 1 and 10).</summary>
|
||||
public const int MaxRanksPerRaise = 100;
|
||||
|
||||
// ── the XpTable ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Reads the portal XpTable file (0x0E000018). False when it is short or the counts are absurd.</summary>
|
||||
public static bool TryParseXpTable(ReadOnlySpan<byte> raw, out XpTableData table)
|
||||
{
|
||||
table = new XpTableData();
|
||||
int p = 0;
|
||||
if (!U32(raw, ref p, out _)) return false; // file id
|
||||
if (!U32(raw, ref p, out uint attrs) || !U32(raw, ref p, out uint vitals)
|
||||
|| !U32(raw, ref p, out uint trained) || !U32(raw, ref p, out uint spec)
|
||||
|| !U32(raw, ref p, out uint levels))
|
||||
return false;
|
||||
if (attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000)
|
||||
return false;
|
||||
if (!U32s(raw, ref p, (int)attrs + 1, out table.AttributeXp)
|
||||
|| !U32s(raw, ref p, (int)vitals + 1, out table.VitalXp)
|
||||
|| !U32s(raw, ref p, (int)trained + 1, out table.TrainedXp)
|
||||
|| !U32s(raw, ref p, (int)spec + 1, out table.SpecializedXp))
|
||||
return false;
|
||||
var lv = new ulong[levels + 1];
|
||||
for (int i = 0; i <= levels; i++)
|
||||
{
|
||||
if (p + 8 > raw.Length) return false;
|
||||
lv[i] = BinaryPrimitives.ReadUInt64LittleEndian(raw.Slice(p, 8));
|
||||
p += 8;
|
||||
}
|
||||
table.LevelXp = lv;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool U32(ReadOnlySpan<byte> b, ref int p, out uint v)
|
||||
{
|
||||
v = 0;
|
||||
if (p + 4 > b.Length) return false;
|
||||
v = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(p, 4));
|
||||
p += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool U32s(ReadOnlySpan<byte> b, ref int p, int n, out uint[] a)
|
||||
{
|
||||
a = Array.Empty<uint>();
|
||||
if (n < 0 || p + (long)n * 4 > b.Length) return false;
|
||||
a = new uint[n];
|
||||
for (int i = 0; i < n; i++) { a[i] = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(p, 4)); p += 4; }
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ──
|
||||
|
||||
/// <summary>The table a stat raises against: attributes, vitals, trained (2) or specialized (3+) skills;
|
||||
/// null for an untrained or unknown skill (those aren't raised with XP).</summary>
|
||||
public static uint[]? TableFor(XpTableData t, uint kind, uint skillClass) => kind switch
|
||||
{
|
||||
1 => t.AttributeXp,
|
||||
2 => t.VitalXp,
|
||||
3 => skillClass >= 3 ? t.SpecializedXp : skillClass == 2 ? t.TrainedXp : null,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
|
||||
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1L >= table.Length;
|
||||
|
||||
/// <summary>Ranks left to the top of the table.</summary>
|
||||
public static int RanksLeft(uint[] table, uint ranks) => (int)Math.Max(0L, table.Length - 1L - ranks);
|
||||
|
||||
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with
|
||||
/// <paramref name="spent"/> already spent; -1 past the top; 0 for n < 1.</summary>
|
||||
public static long CostOf(uint[] table, uint ranks, uint spent, int n)
|
||||
{
|
||||
if (n < 1) return 0;
|
||||
long target = (long)ranks + n;
|
||||
if (target >= table.Length) return -1;
|
||||
return Math.Max(0L, (long)table[target] - spent);
|
||||
}
|
||||
|
||||
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top.</summary>
|
||||
public static int Affordable(uint[] table, uint ranks, uint spent, long available)
|
||||
{
|
||||
int lo = 0, hi = RanksLeft(table, ranks);
|
||||
while (lo < hi)
|
||||
{
|
||||
int mid = (lo + hi + 1) / 2;
|
||||
long c = CostOf(table, ranks, spent, mid);
|
||||
if (c >= 0 && c <= available) lo = mid; else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
// ── the checks before a raise is sent ──────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Everything a raise of <paramref name="count"/> ranks must pass, given the numbers now:
|
||||
/// a table (null = untrained/unknown skill), not past the top, a cost that equals what the
|
||||
/// caller confirmed (<paramref name="expectedXp"/> > 0; 0 = don't compare), enough
|
||||
/// unassigned XP, and an amount the 32-bit game action can carry.
|
||||
/// <paramref name="cost"/> is the XP to send when the result is <see cref="RaiseStatus.Sent"/>.
|
||||
/// </summary>
|
||||
public static RaiseStatus CheckRaise(uint[]? table, uint ranks, uint spent, long unassignedXp,
|
||||
int count, long expectedXp, out long cost)
|
||||
{
|
||||
cost = -1;
|
||||
if (count < 1 || count > MaxRanksPerRaise || expectedXp < 0) return RaiseStatus.BadArguments;
|
||||
if (table == null || table.Length == 0) return RaiseStatus.NotRaisable;
|
||||
cost = CostOf(table, ranks, spent, count);
|
||||
if (cost <= 0) return RaiseStatus.NotRaisable; // past the top (-1) or nothing to buy (0)
|
||||
if (expectedXp != 0 && expectedXp != cost) return RaiseStatus.CostChanged;
|
||||
if (cost > unassignedXp) return RaiseStatus.NotEnough;
|
||||
if (cost > uint.MaxValue) return RaiseStatus.NotRaisable; // more than one game action can carry
|
||||
return RaiseStatus.Sent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The checks for training an untrained skill with credits: the skill must be untrained
|
||||
/// (class 1, or 0 = not in the table), the dat must price it (> 0), the price must be what
|
||||
/// the caller confirmed (<paramref name="expectedCredits"/> > 0; 0 = don't compare) and
|
||||
/// the player must have the credits.
|
||||
/// </summary>
|
||||
public static RaiseStatus CheckTrain(uint skillClass, int trainedCost, int credits, int expectedCredits)
|
||||
{
|
||||
if (expectedCredits < 0) return RaiseStatus.BadArguments;
|
||||
if (skillClass >= 2 || trainedCost <= 0) return RaiseStatus.NotRaisable;
|
||||
if (expectedCredits != 0 && expectedCredits != trainedCost) return RaiseStatus.CostChanged;
|
||||
if (trainedCost > credits) return RaiseStatus.NotEnough;
|
||||
return RaiseStatus.Sent;
|
||||
}
|
||||
}
|
||||
480
src/RynthCore.Engine/Compatibility/UiElementHooks.cs
Normal file
480
src/RynthCore.Engine/Compatibility/UiElementHooks.cs
Normal file
|
|
@ -0,0 +1,480 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/UiElementHooks.cs
|
||||
//
|
||||
// Tooltip and drag/drop hooks on AC's own UI (Chorizite comparison gap #5,
|
||||
// 2026-10-05). Every address and offset below was checked offline against our
|
||||
// client (tools/ui_hooks_check.py; report in ops/overnight/2026-10-05-ui-hooks.md):
|
||||
//
|
||||
// UIElementManager (the UI singleton; `this` of the first four):
|
||||
// StartTooltip(StringInfo*, UIElement* owner, uint, uint, uint) 0x0045DF70, ret 14h
|
||||
// stores the owner at +0x2F4, builds the tooltip element into +0x2F8.
|
||||
// ResetTooltip() 0x0045C440 frees +0x2F8, then tail-jumps into CheckTooltip.
|
||||
// CheckTooltip() 0x0045B7C0 per-frame tooltip timer (+0x325, +0x2D4, +0x24C).
|
||||
// StartDragandDrop(UIElement*, int x, int y) -> bool 0x0045E120, ret 0Ch
|
||||
// on success the drag icon is at +0x31C and its owner at +0x320; it calls
|
||||
// itself once for a drag proxy (we report only the outermost call).
|
||||
// UIElement::CatchDroppedItem(DragDropInfo*) -> bool 0x00461860, ret 4
|
||||
// the catcher's virtual (vtable +0xD8), called from StopDragandDrop
|
||||
// (0x00459880). All 113 UIElement vtables in the client route it here:
|
||||
// 36 directly, 77 through UIElement_Field::CatchDroppedItem, which calls
|
||||
// it. It broadcasts element message 0x15 (drop release) to the catcher;
|
||||
// that message is what drops an item on the ground (SmartBoxWrapper),
|
||||
// moves it into a pack (ItemList) and so on. DragDropInfo: +0x08 the
|
||||
// drag icon, +0x0C its owner, +0x10 the catcher, +0x14 success.
|
||||
// Not hooked, called: UIElement_ItemList::InqDropIconInfo(UIElement*, uint* item,
|
||||
// uint* spell, uint* flags), cdecl, 0x004E3380: AC's own "which object or
|
||||
// spell is this icon" (13 callers in the client; reads element properties
|
||||
// only, null-safe).
|
||||
// UIElement offsets: +0x2E4 element id (GetAncestorByID compares it), vtable
|
||||
// +0xA0 GetParent, +0x98 GetUIElementType (UIElement_ItemList: 0x10000031).
|
||||
//
|
||||
// Events, on AC's main thread, queued to plugins (API v77):
|
||||
// tooltip shown (object id or spell id of the hovered icon), tooltip hidden,
|
||||
// drag started (object/spell id, icon), item dropped (object/spell id, the
|
||||
// catcher's element id).
|
||||
// Drop claims: an item dragged out of an AC item list and let go over an engine
|
||||
// panel that takes drops (ImGui/UiDropTargets: the Loot Editor) never reaches
|
||||
// AC: CatchDroppedItem answers false without running, which is AC's own
|
||||
// "not caught" path (StopDragandDrop then tells the source list the drop
|
||||
// failed; ItemList::HandleDropRelease ignores a failed drop whose catcher isn't
|
||||
// inside it). Not claimed when the catcher is inside the source list itself.
|
||||
//
|
||||
// Not done (needs in-game checks): adding lines to AC's own tooltip text. That
|
||||
// means building an AC StringInfo/PStringBase and editing the tooltip element
|
||||
// AC just made, inside its allocator - see the report.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static unsafe class UiElementHooks
|
||||
{
|
||||
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
|
||||
private const int StartTooltipFallbackVa = 0x0045DF70;
|
||||
private const int ResetTooltipFallbackVa = 0x0045C440;
|
||||
private const int CheckTooltipFallbackVa = 0x0045B7C0;
|
||||
private const int StartDragandDropFallbackVa = 0x0045E120;
|
||||
private const int CatchDroppedItemFallbackVa = 0x00461860;
|
||||
private const int InqDropIconInfoFallbackVa = 0x004E3380;
|
||||
|
||||
private const int MgrTooltipOwner = 0x2F4;
|
||||
private const int MgrTooltipElement = 0x2F8;
|
||||
private const int MgrDragIcon = 0x31C;
|
||||
private const int MgrDragOwner = 0x320;
|
||||
private const int ElementId = 0x2E4;
|
||||
private const int VtGetUIElementType = 0x98;
|
||||
private const int VtGetParent = 0xA0;
|
||||
private const int DdiElement = 0x08;
|
||||
private const int DdiOwner = 0x0C;
|
||||
private const int UIElementTypeItemList = 0x10000031;
|
||||
|
||||
// StartTooltip: sub esp,10h / push ebp / push esi / mov esi,ecx / mov ecx,[esi+2F8h] /
|
||||
// xor ebp,ebp / cmp ecx,ebp / push edi / mov [esp+18h],esi / jz +0Bh / call rel32 /
|
||||
// mov [esi+2F8h],ebp - frees an old tooltip element first. Unique, lands at 0x0045DF70.
|
||||
private static readonly byte?[] StartTooltipPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x10, 0x55, 0x56, 0x8B, 0xF1, 0x8B, 0x8E, 0xF8, 0x02, 0x00, 0x00,
|
||||
0x33, 0xED, 0x3B, 0xCD, 0x57, 0x89, 0x74, 0x24, 0x18, 0x74, 0x0B,
|
||||
0xE8, null, null, null, null, 0x89, 0xAE, 0xF8, 0x02, 0x00, 0x00
|
||||
];
|
||||
|
||||
// ResetTooltip: push esi / mov esi,ecx / mov ecx,[esi+2F8h] / test ecx,ecx / jz +0Fh /
|
||||
// call rel32 / mov dword [esi+2F8h],0 / mov al,[esi+325h]. Unique, lands at 0x0045C440.
|
||||
private static readonly byte?[] ResetTooltipPattern =
|
||||
[
|
||||
0x56, 0x8B, 0xF1, 0x8B, 0x8E, 0xF8, 0x02, 0x00, 0x00, 0x85, 0xC9, 0x74, 0x0F,
|
||||
0xE8, null, null, null, null, 0xC7, 0x86, 0xF8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x8A, 0x86, 0x25, 0x03, 0x00, 0x00
|
||||
];
|
||||
|
||||
// CheckTooltip: sub esp,0Ch / mov eax,[imm32] / push esi / mov esi,ecx / mov ecx,[imm32] /
|
||||
// mov [esp+8],eax / mov al,[esi+325h] / test al,al / mov [esp+0Ch],ecx / jnz +79h /
|
||||
// mov al,[esi+2D4h]. The two timer globals wildcarded. Unique, lands at 0x0045B7C0.
|
||||
private static readonly byte?[] CheckTooltipPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x0C, 0xA1, null, null, null, null, 0x56, 0x8B, 0xF1, 0x8B, 0x0D, null, null, null, null,
|
||||
0x89, 0x44, 0x24, 0x08, 0x8A, 0x86, 0x25, 0x03, 0x00, 0x00, 0x84, 0xC0, 0x89, 0x4C, 0x24, 0x0C,
|
||||
0x75, 0x79, 0x8A, 0x86, 0xD4, 0x02, 0x00, 0x00
|
||||
];
|
||||
|
||||
// StartDragandDrop: sub esp,34h / push ebx,ebp,esi,edi / mov edi,[esp+48h] / test edi,edi /
|
||||
// mov esi,ecx / jz rel32 / mov eax,[imm32] / test eax,eax / jz rel32 / mov ebx,[imm32] /
|
||||
// test ebx,ebx. Unique, lands at 0x0045E120.
|
||||
private static readonly byte?[] StartDragandDropPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1,
|
||||
0x0F, 0x84, null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0,
|
||||
0x0F, 0x84, null, null, null, null, 0x8B, 0x1D, null, null, null, null, 0x85, 0xDB
|
||||
];
|
||||
|
||||
// UIElement::CatchDroppedItem, the whole function: mov eax,[esp+4] / push 0 / push eax /
|
||||
// push 15h / call BroadcastElementMessage / mov al,1 / ret 4. Unique, lands at 0x00461860.
|
||||
private static readonly byte?[] CatchDroppedItemPattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x04, 0x6A, 0x00, 0x50, 0x6A, 0x15, 0xE8, null, null, null, null,
|
||||
0xB0, 0x01, 0xC2, 0x04, 0x00
|
||||
];
|
||||
|
||||
// UIElement_ItemList::InqDropIconInfo: mov eax,[esp+10h] / sub esp,3Ch / push ebx / push ebp /
|
||||
// mov ebp,[esp+50h] / push esi / mov esi,[esp+4Ch] / xor ebx,ebx / cmp esi,ebx / push edi /
|
||||
// mov edi,[esp+54h] / mov [edi],ebx / mov [ebp],ebx / mov [eax],ebx. Unique, lands at 0x004E3380.
|
||||
private static readonly byte?[] InqDropIconInfoPattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56,
|
||||
0x8B, 0x74, 0x24, 0x4C, 0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54,
|
||||
0x89, 0x1F, 0x89, 0x5D, 0x00, 0x89, 0x18
|
||||
];
|
||||
|
||||
private static readonly UiHookSlot StartTooltipSlot =
|
||||
UiHookRegistry.Register("StartTooltip", "UIElementManager::StartTooltip - tooltip shown", StartTooltipFallbackVa);
|
||||
private static readonly UiHookSlot ResetTooltipSlot =
|
||||
UiHookRegistry.Register("ResetTooltip", "UIElementManager::ResetTooltip - tooltip reset", ResetTooltipFallbackVa);
|
||||
private static readonly UiHookSlot CheckTooltipSlot =
|
||||
UiHookRegistry.Register("CheckTooltip", "UIElementManager::CheckTooltip - tooltip expired", CheckTooltipFallbackVa);
|
||||
private static readonly UiHookSlot StartDragSlot =
|
||||
UiHookRegistry.Register("StartDragandDrop", "UIElementManager::StartDragandDrop - drag started", StartDragandDropFallbackVa);
|
||||
private static readonly UiHookSlot CatchDropSlot =
|
||||
UiHookRegistry.Register("CatchDroppedItem", "UIElement::CatchDroppedItem - item dropped", CatchDroppedItemFallbackVa);
|
||||
|
||||
private static IntPtr _origStartTooltip, _origResetTooltip, _origCheckTooltip, _origStartDrag, _origCatchDrop;
|
||||
private static IntPtr _inqDropIconInfo;
|
||||
private static int _initialized;
|
||||
|
||||
// AC's main thread only (every detour runs there; faces draw there).
|
||||
private static IntPtr _mgr;
|
||||
private static bool _dead; // Client::Cleanup started: touch nothing of AC's UI
|
||||
private static bool _tooltipShown;
|
||||
private static IntPtr _tooltipOwner;
|
||||
private static uint _tooltipObject, _tooltipSpell;
|
||||
private static int _dragDepth;
|
||||
private static uint _dragObject, _dragSpell;
|
||||
private static int _claimed;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
foreach (UiHookSlot s in new[] { StartTooltipSlot, ResetTooltipSlot, CheckTooltipSlot, StartDragSlot, CatchDropSlot })
|
||||
s.Reason = "acclient.exe not available";
|
||||
RynthLog.Compat("UiElementHooks: acclient.exe not available - tooltip and drag/drop hooks left out.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Every event names its object through InqDropIconInfo: without it, none goes in.
|
||||
HookResolver.ResolveResult inq = HookResolver.Resolve(text, "UiElement.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoFallbackVa);
|
||||
if (!inq.Success)
|
||||
{
|
||||
foreach (UiHookSlot s in new[] { StartTooltipSlot, ResetTooltipSlot, CheckTooltipSlot, StartDragSlot, CatchDropSlot })
|
||||
s.Reason = "UIElement_ItemList::InqDropIconInfo not found (names the objects)";
|
||||
RynthLog.Compat("UiElementHooks: InqDropIconInfo not found - tooltip and drag/drop hooks left out.");
|
||||
return;
|
||||
}
|
||||
_inqDropIconInfo = inq.Address;
|
||||
|
||||
if (UiHookRegistry.SwitchedOn(StartTooltipSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.StartTooltip", StartTooltipPattern, StartTooltipFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, uint, uint, uint, void> d = &StartTooltipDetour;
|
||||
if (UiHookRegistry.TryInstall(StartTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origStartTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(StartTooltipSlot); }
|
||||
}
|
||||
if (UiHookRegistry.SwitchedOn(ResetTooltipSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.ResetTooltip", ResetTooltipPattern, ResetTooltipFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> d = &ResetTooltipDetour;
|
||||
if (UiHookRegistry.TryInstall(ResetTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origResetTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(ResetTooltipSlot); }
|
||||
}
|
||||
if (UiHookRegistry.SwitchedOn(CheckTooltipSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.CheckTooltip", CheckTooltipPattern, CheckTooltipFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> d = &CheckTooltipDetour;
|
||||
if (UiHookRegistry.TryInstall(CheckTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origCheckTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(CheckTooltipSlot); }
|
||||
}
|
||||
if (UiHookRegistry.SwitchedOn(StartDragSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.StartDragandDrop", StartDragandDropPattern, StartDragandDropFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> d = &StartDragandDropDetour;
|
||||
if (UiHookRegistry.TryInstall(StartDragSlot, r, (IntPtr)d, out IntPtr t)) { _origStartDrag = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(StartDragSlot); }
|
||||
}
|
||||
if (UiHookRegistry.SwitchedOn(CatchDropSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.CatchDroppedItem", CatchDroppedItemPattern, CatchDroppedItemFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, byte> d = &CatchDroppedItemDetour;
|
||||
if (UiHookRegistry.TryInstall(CatchDropSlot, r, (IntPtr)d, out IntPtr t)) { _origCatchDrop = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(CatchDropSlot); }
|
||||
}
|
||||
|
||||
RynthLog.Compat($"UiElementHooks: tooltip {On(StartTooltipSlot)}/{On(ResetTooltipSlot)}/{On(CheckTooltipSlot)}, " +
|
||||
$"drag {On(StartDragSlot)}, drop {On(CatchDropSlot)} (InqDropIconInfo @ 0x{_inqDropIconInfo.ToInt32():X8}).");
|
||||
}
|
||||
|
||||
private static string On(UiHookSlot s) => s.Installed ? "hooked" : "out";
|
||||
|
||||
// ── What plugins and faces read ─────────────────────────────────────
|
||||
|
||||
/// <summary>Tooltip/drag/drop hooks a plugin can rely on (GetUiHookFlags bits 3-6).</summary>
|
||||
public static bool TooltipShowLive => StartTooltipSlot.Live;
|
||||
public static bool TooltipHideLive => ResetTooltipSlot.Live || CheckTooltipSlot.Live;
|
||||
public static bool DragStartLive => StartDragSlot.Live;
|
||||
public static bool DropLive => CatchDropSlot.Live;
|
||||
|
||||
/// <summary>
|
||||
/// AC's main thread: the object being dragged out of AC's UI right now, or 0. Checks
|
||||
/// the UI manager's drag icon (+0x31C) so a drag that ended without a catch (let go
|
||||
/// outside every element) clears too.
|
||||
/// </summary>
|
||||
public static uint CurrentDragObject
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_dragObject == 0)
|
||||
return 0;
|
||||
if (_dead || _mgr == IntPtr.Zero || !MainThreadGuard.IsOnMainThread())
|
||||
return _dead ? 0 : _dragObject;
|
||||
if (*(IntPtr*)(_mgr + MgrDragIcon) == IntPtr.Zero)
|
||||
{
|
||||
_dragObject = _dragSpell = 0;
|
||||
return 0;
|
||||
}
|
||||
return _dragObject;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The object whose tooltip AC shows, or 0 (any thread; a plain field).</summary>
|
||||
public static uint CurrentTooltipObject => _tooltipShown ? _tooltipObject : 0;
|
||||
|
||||
/// <summary>UiFlowHooks, leaving the world (main thread): forget tooltip/drag state; no events.</summary>
|
||||
public static void OnScreenLeaving()
|
||||
{
|
||||
_tooltipShown = false;
|
||||
_tooltipOwner = IntPtr.Zero;
|
||||
_tooltipObject = _tooltipSpell = 0;
|
||||
_dragObject = _dragSpell = 0;
|
||||
}
|
||||
|
||||
/// <summary>UiFlowHooks, Client::Cleanup (main thread): AC's UI is about to go; never touch it again.</summary>
|
||||
public static void OnClientCleanup()
|
||||
{
|
||||
_dead = true;
|
||||
_mgr = IntPtr.Zero;
|
||||
OnScreenLeaving();
|
||||
}
|
||||
|
||||
// ── Detours ──────────────────────────────────────────────────────────
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static void StartTooltipDetour(IntPtr mgr, IntPtr stringInfo, IntPtr owner, uint idTooltip, uint idLayout, uint idText)
|
||||
{
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, uint, uint, uint, void>)_origStartTooltip)(mgr, stringInfo, owner, idTooltip, idLayout, idText);
|
||||
if (!StartTooltipSlot.Enabled || _dead || mgr == IntPtr.Zero)
|
||||
return;
|
||||
try
|
||||
{
|
||||
_mgr = mgr;
|
||||
if (*(IntPtr*)(mgr + MgrTooltipElement) == IntPtr.Zero)
|
||||
return; // AC decided not to show one
|
||||
IntPtr shownOwner = *(IntPtr*)(mgr + MgrTooltipOwner);
|
||||
if (shownOwner == IntPtr.Zero) shownOwner = owner;
|
||||
Identify(shownOwner, 2, out uint obj, out uint spell);
|
||||
bool same = _tooltipShown && shownOwner == _tooltipOwner && obj == _tooltipObject && spell == _tooltipSpell;
|
||||
_tooltipShown = true;
|
||||
_tooltipOwner = shownOwner;
|
||||
_tooltipObject = obj;
|
||||
_tooltipSpell = spell;
|
||||
if (same)
|
||||
return;
|
||||
StartTooltipSlot.Note(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "a non-item element");
|
||||
Plugins.PluginManager.QueueTooltipShown(obj, spell);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogOnce("StartTooltip", ex);
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static void ResetTooltipDetour(IntPtr mgr)
|
||||
{
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origResetTooltip)(mgr);
|
||||
if (ResetTooltipSlot.Enabled)
|
||||
AfterTooltipCheck(mgr, ResetTooltipSlot);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static void CheckTooltipDetour(IntPtr mgr)
|
||||
{
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origCheckTooltip)(mgr);
|
||||
if (CheckTooltipSlot.Enabled)
|
||||
AfterTooltipCheck(mgr, CheckTooltipSlot);
|
||||
}
|
||||
|
||||
// A tooltip we reported is gone when AC's tooltip element pointer is clear again.
|
||||
private static void AfterTooltipCheck(IntPtr mgr, UiHookSlot slot)
|
||||
{
|
||||
if (!_tooltipShown || _dead || mgr == IntPtr.Zero)
|
||||
return;
|
||||
try
|
||||
{
|
||||
if (*(IntPtr*)(mgr + MgrTooltipElement) != IntPtr.Zero)
|
||||
return;
|
||||
uint obj = _tooltipObject;
|
||||
_tooltipShown = false;
|
||||
_tooltipOwner = IntPtr.Zero;
|
||||
_tooltipObject = _tooltipSpell = 0;
|
||||
slot.Note(obj != 0 ? $"hid object 0x{obj:X8}" : "hid");
|
||||
Plugins.PluginManager.QueueTooltipHidden();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogOnce(slot.Name, ex);
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static byte StartDragandDropDetour(IntPtr mgr, IntPtr element, int x, int y)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_origStartDrag;
|
||||
byte result;
|
||||
_dragDepth++;
|
||||
try { result = original(mgr, element, x, y); }
|
||||
finally { _dragDepth--; }
|
||||
|
||||
// The original calls itself once for a drag proxy: report the outermost call only.
|
||||
if (result == 0 || _dragDepth > 0 || !StartDragSlot.Enabled || _dead || mgr == IntPtr.Zero)
|
||||
return result;
|
||||
try
|
||||
{
|
||||
_mgr = mgr;
|
||||
IntPtr icon = *(IntPtr*)(mgr + MgrDragIcon);
|
||||
if (icon == IntPtr.Zero)
|
||||
return result;
|
||||
Identify(icon, 0, out uint obj, out uint spell);
|
||||
if (obj == 0 && spell == 0)
|
||||
Identify(element, 2, out obj, out spell);
|
||||
_dragObject = obj;
|
||||
_dragSpell = spell;
|
||||
uint iconId = 0;
|
||||
if (obj != 0)
|
||||
ClientObjectHooks.TryGetObjectDataIdProperty(obj, 8 /* Icon */, out iconId);
|
||||
StartDragSlot.Note(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "a non-item element");
|
||||
Plugins.PluginManager.QueueDragStarted(obj, spell, iconId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogOnce("StartDragandDrop", ex);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static byte CatchDroppedItemDetour(IntPtr catcher, IntPtr dragDropInfo)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, byte>)_origCatchDrop;
|
||||
if (!CatchDropSlot.Enabled || _dead || dragDropInfo == IntPtr.Zero)
|
||||
return original(catcher, dragDropInfo);
|
||||
|
||||
uint obj = 0, spell = 0;
|
||||
try
|
||||
{
|
||||
IntPtr dragged = *(IntPtr*)(dragDropInfo + DdiElement);
|
||||
IntPtr owner = *(IntPtr*)(dragDropInfo + DdiOwner);
|
||||
if (dragged != IntPtr.Zero)
|
||||
Identify(dragged, 0, out obj, out spell);
|
||||
|
||||
// An item out of an AC item list, let go over an engine panel that takes it.
|
||||
if (obj != 0 && IsItemList(owner) && !IsWithin(catcher, owner)
|
||||
&& ImGuiBackend.UiDropTargets.TryClaim(obj, spell, out string target))
|
||||
{
|
||||
Interlocked.Increment(ref _claimed);
|
||||
_dragObject = _dragSpell = 0;
|
||||
CatchDropSlot.Note($"object 0x{obj:X8} -> RynthCore {target} (kept from AC)");
|
||||
RynthLog.Compat($"UiElementHooks: object 0x{obj:X8} dropped on RynthCore {target}; AC's drop skipped (not caught).");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogOnce("CatchDroppedItem", ex);
|
||||
}
|
||||
|
||||
byte result = original(catcher, dragDropInfo);
|
||||
try
|
||||
{
|
||||
_dragObject = _dragSpell = 0;
|
||||
uint targetId = catcher != IntPtr.Zero ? *(uint*)(catcher + ElementId) : 0;
|
||||
CatchDropSlot.Note($"{(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "no object")} on element 0x{targetId:X8}");
|
||||
if (obj != 0 || spell != 0)
|
||||
Plugins.PluginManager.QueueItemDropped(obj, spell, targetId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogOnce("CatchDroppedItem", ex);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── AC UI helpers (main thread) ──────────────────────────────────────
|
||||
|
||||
/// <summary>AC's InqDropIconInfo on <paramref name="element"/>, then up to <paramref name="parents"/> parents.</summary>
|
||||
private static void Identify(IntPtr element, int parents, out uint objectId, out uint spellId)
|
||||
{
|
||||
objectId = spellId = 0;
|
||||
var inq = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)_inqDropIconInfo;
|
||||
for (int i = 0; i <= parents && element != IntPtr.Zero; i++)
|
||||
{
|
||||
uint item = 0, spell = 0, flags = 0;
|
||||
inq(element, &item, &spell, &flags);
|
||||
if (item != 0 || spell != 0)
|
||||
{
|
||||
objectId = item;
|
||||
spellId = spell;
|
||||
return;
|
||||
}
|
||||
element = Parent(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr Parent(IntPtr element)
|
||||
{
|
||||
IntPtr vtable = *(IntPtr*)element;
|
||||
var getParent = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr>)(*(IntPtr*)(vtable + VtGetParent));
|
||||
return getParent(element);
|
||||
}
|
||||
|
||||
private static bool IsItemList(IntPtr element)
|
||||
{
|
||||
if (element == IntPtr.Zero)
|
||||
return false;
|
||||
IntPtr vtable = *(IntPtr*)element;
|
||||
var getType = (delegate* unmanaged[Thiscall]<IntPtr, int>)(*(IntPtr*)(vtable + VtGetUIElementType));
|
||||
return getType(element) == UIElementTypeItemList;
|
||||
}
|
||||
|
||||
private static bool IsWithin(IntPtr element, IntPtr ancestor)
|
||||
{
|
||||
for (int i = 0; i < 32 && element != IntPtr.Zero; i++)
|
||||
{
|
||||
if (element == ancestor)
|
||||
return true;
|
||||
element = Parent(element);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int _loggedErrors;
|
||||
|
||||
private static void LogOnce(string where, Exception ex)
|
||||
{
|
||||
if (Interlocked.Increment(ref _loggedErrors) <= 5)
|
||||
try { RynthLog.Compat($"UiElementHooks: {where} threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
|
||||
public static string DescribeState()
|
||||
=> $"UI elements: tooltip {(_tooltipShown ? (_tooltipObject != 0 ? $"on object 0x{_tooltipObject:X8}" : "shown") : "none")}, " +
|
||||
$"drag {(_dragObject != 0 ? $"object 0x{_dragObject:X8}" : "none")}, {Volatile.Read(ref _claimed)} drop(s) kept for RynthCore. " +
|
||||
ImGuiBackend.UiDropTargets.Describe();
|
||||
}
|
||||
334
src/RynthCore.Engine/Compatibility/UiFlowHooks.cs
Normal file
334
src/RynthCore.Engine/Compatibility/UiFlowHooks.cs
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/UiFlowHooks.cs
|
||||
//
|
||||
// Screen-mode and teardown hooks (Chorizite comparison gap #4, 2026-10-05):
|
||||
//
|
||||
// UIFlow::UseNewMode (fallback 0x00479AA0) void __thiscall(UIFlow*)
|
||||
// AC switches screens here: intro, character select, the world, char gen,
|
||||
// disconnected... It copies the pending mode (+0x90) into the current mode
|
||||
// (+0x8C), destroys the old screen's UI object (+0x94) and builds the new
|
||||
// one. Read offline from our client: 0x00479B13..0x00479B35 (mov [esi+8C],ecx
|
||||
// from [esi+90]; old UI at +94 released with vfunc +0x24/+0x00).
|
||||
// Client::Cleanup (fallback 0x004118D0) void __thiscall(Client*)
|
||||
// The client's shutdown: tears down UI, net, database and preferences
|
||||
// (virtual calls at its top). Called once, from gmClient::Cleanup.
|
||||
//
|
||||
// Events (all raised on AC's main thread):
|
||||
// ScreenLeaving(old, new) - inside UseNewMode, BEFORE AC destroys the old
|
||||
// screen's UI. Leaving the world, the engine drops
|
||||
// every cached gameplay-UI pointer right here.
|
||||
// ScreenChanged(old, new) - after AC built the new screen (plugins get
|
||||
// RynthPluginOnScreenChanged on the next pump frame).
|
||||
// ClientCleanup - before AC tears anything down; plugins get
|
||||
// RynthPluginOnClientCleanup (bounded wait), then the
|
||||
// plugin pump stops ticking and the panels stop drawing.
|
||||
//
|
||||
// Fallback: until the hook is live (failed to resolve, switched off), the UIFlow
|
||||
// mode the engine already polls at +0x8C (CharacterManagementHooks.MainThreadTick)
|
||||
// drives the same events, one tick late and without the "before" guarantee.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static unsafe class UiFlowHooks
|
||||
{
|
||||
// UIFlow modes (UIFlow+0x8C), the client's own data ids.
|
||||
public const int ModeNone = 0;
|
||||
public const int ModeIntro = 0x10000001;
|
||||
public const int ModeDisconnected = 0x10000002;
|
||||
public const int ModeDataPatch = 0x10000003;
|
||||
public const int ModeCredits = 0x10000005;
|
||||
public const int ModeGamePlay = 0x10000008;
|
||||
public const int ModeEpilogue = 0x10000009;
|
||||
public const int ModeCharacterManagement = 0x1000000A;
|
||||
public const int ModeCharGen = 0x1000000B;
|
||||
|
||||
private const int UIFlowCurModeOffset = 0x8C;
|
||||
private const int UIFlowNewModeOffset = 0x90;
|
||||
|
||||
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
|
||||
private const int UseNewModeFallbackVa = 0x00479AA0;
|
||||
private const int ClientCleanupFallbackVa = 0x004118D0;
|
||||
|
||||
// UIFlow::UseNewMode: sub esp,0x90 / push esi / mov esi,ecx / mov eax,[esi+0x90] /
|
||||
// test eax,eax / jz rel32 / mov ecx,eax / xor edx,edx / div [imm32] / mov eax,[imm32].
|
||||
// The +0x90 pending-mode read and the hash-bucket div are the anchor. Unique, lands
|
||||
// at 0x00479AA0 (tools/pe_pattern.py CHECK, tools/ui_hooks_check.py).
|
||||
private static readonly byte?[] UseNewModePattern =
|
||||
[
|
||||
0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B, 0xF1, 0x8B, 0x86, 0x90, 0x00, 0x00, 0x00,
|
||||
0x85, 0xC0, 0x0F, 0x84, null, null, null, null,
|
||||
0x8B, 0xC8, 0x33, 0xD2, 0xF7, 0x35, null, null, null, null,
|
||||
0xA1, null, null, null, null
|
||||
];
|
||||
|
||||
// Client::Cleanup: push esi / mov esi,ecx / mov eax,[esi] / call [eax+0x28] / call rel32 /
|
||||
// mov edx,[esi] / mov ecx,esi / call [edx+0x8C] / call rel32 / mov eax,[esi] / mov ecx,esi /
|
||||
// call [eax+0x84]: its run of virtual cleanups. Unique, lands at 0x004118D0.
|
||||
private static readonly byte?[] ClientCleanupPattern =
|
||||
[
|
||||
0x56, 0x8B, 0xF1, 0x8B, 0x06, 0xFF, 0x50, 0x28, 0xE8, null, null, null, null,
|
||||
0x8B, 0x16, 0x8B, 0xCE, 0xFF, 0x92, 0x8C, 0x00, 0x00, 0x00, 0xE8, null, null, null, null,
|
||||
0x8B, 0x06, 0x8B, 0xCE, 0xFF, 0x90, 0x84, 0x00, 0x00, 0x00
|
||||
];
|
||||
|
||||
private static readonly UiHookSlot UseNewModeSlot =
|
||||
UiHookRegistry.Register("UseNewMode", "UIFlow::UseNewMode - screen changes", UseNewModeFallbackVa);
|
||||
private static readonly UiHookSlot CleanupSlot =
|
||||
UiHookRegistry.Register("ClientCleanup", "Client::Cleanup - client teardown", ClientCleanupFallbackVa);
|
||||
|
||||
private static IntPtr _originalUseNewMode;
|
||||
private static IntPtr _originalCleanup;
|
||||
private static int _initialized;
|
||||
|
||||
private static int _mode; // current UIFlow mode as last observed (0 = not known yet)
|
||||
private static int _previousMode;
|
||||
private static int _changes;
|
||||
private static string _lastSource = "none";
|
||||
private static int _cleanupStarted;
|
||||
private static int _useNewModeDepth;
|
||||
|
||||
/// <summary>AC's main thread, inside UseNewMode before the old screen's UI is destroyed (hook only).</summary>
|
||||
public static event Action<int, int>? ScreenLeaving;
|
||||
/// <summary>AC's main thread, after the new screen was built (hook) or on the next tick (poll fallback).</summary>
|
||||
public static event Action<int, int>? ScreenChanged;
|
||||
/// <summary>AC's main thread, before Client::Cleanup runs. Once.</summary>
|
||||
public static event Action? ClientCleanup;
|
||||
|
||||
/// <summary>The UIFlow mode as last observed; 0 until the first observation.</summary>
|
||||
public static int CurrentMode => Volatile.Read(ref _mode);
|
||||
public static int PreviousMode => Volatile.Read(ref _previousMode);
|
||||
|
||||
/// <summary>True while AC shows the world, or while the mode isn't known yet (no change
|
||||
/// from the old behaviour then). Gate cached-AC-UI-pointer use on this.</summary>
|
||||
public static bool InWorldOrUnknown
|
||||
{
|
||||
get
|
||||
{
|
||||
int m = Volatile.Read(ref _mode);
|
||||
return m == ModeNone || m == ModeGamePlay;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Client::Cleanup has started: AC is tearing its UI down. Never cleared.</summary>
|
||||
public static bool ClientCleanupStarted => Volatile.Read(ref _cleanupStarted) != 0;
|
||||
|
||||
/// <summary>The UseNewMode detour is installed and switched on (else the poll drives the events).</summary>
|
||||
public static bool ScreenHookLive => UseNewModeSlot.Live;
|
||||
public static bool CleanupHookLive => CleanupSlot.Live;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
UseNewModeSlot.Reason = CleanupSlot.Reason = "acclient.exe not available";
|
||||
RynthLog.Compat("UiFlowHooks: acclient.exe not available - screen-mode and cleanup hooks left out (the mode poll stays).");
|
||||
return;
|
||||
}
|
||||
|
||||
if (UiHookRegistry.SwitchedOn(UseNewModeSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiFlow.UseNewMode", UseNewModePattern, UseNewModeFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> detour = &UseNewModeDetour;
|
||||
if (UiHookRegistry.TryInstall(UseNewModeSlot, r, (IntPtr)detour, out IntPtr tramp))
|
||||
{
|
||||
_originalUseNewMode = tramp;
|
||||
Thread.MemoryBarrier();
|
||||
UiHookRegistry.Enable(UseNewModeSlot);
|
||||
}
|
||||
}
|
||||
|
||||
if (UiHookRegistry.SwitchedOn(CleanupSlot))
|
||||
{
|
||||
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiFlow.ClientCleanup", ClientCleanupPattern, ClientCleanupFallbackVa);
|
||||
delegate* unmanaged[Thiscall]<IntPtr, void> detour = &ClientCleanupDetour;
|
||||
if (UiHookRegistry.TryInstall(CleanupSlot, r, (IntPtr)detour, out IntPtr tramp))
|
||||
{
|
||||
_originalCleanup = tramp;
|
||||
Thread.MemoryBarrier();
|
||||
UiHookRegistry.Enable(CleanupSlot);
|
||||
}
|
||||
}
|
||||
|
||||
RynthLog.Compat($"UiFlowHooks: UseNewMode {(UseNewModeSlot.Installed ? "hooked" : "not hooked (" + UseNewModeSlot.Reason + ") - the +0x8C poll drives screen events")}, " +
|
||||
$"Client::Cleanup {(CleanupSlot.Installed ? "hooked" : "not hooked (" + CleanupSlot.Reason + ")")}.");
|
||||
}
|
||||
|
||||
// ── Detours ──────────────────────────────────────────────────────────
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static void UseNewModeDetour(IntPtr uiFlow)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, void>)_originalUseNewMode;
|
||||
if (!UseNewModeSlot.Enabled || uiFlow == IntPtr.Zero || _useNewModeDepth > 0)
|
||||
{
|
||||
original(uiFlow);
|
||||
return;
|
||||
}
|
||||
|
||||
int oldMode = 0, pending = 0;
|
||||
bool read = false;
|
||||
try
|
||||
{
|
||||
MainThreadGuard.RecordIfFirst();
|
||||
oldMode = *(int*)(uiFlow + UIFlowCurModeOffset);
|
||||
pending = *(int*)(uiFlow + UIFlowNewModeOffset);
|
||||
read = true;
|
||||
// AC destroys the old screen's UI inside the original: drop what points into it first.
|
||||
if (pending != 0 && pending != oldMode)
|
||||
RaiseLeaving(oldMode, pending, "hook");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"UiFlowHooks: UseNewMode pre-step threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
|
||||
_useNewModeDepth++;
|
||||
try { original(uiFlow); }
|
||||
finally { _useNewModeDepth--; }
|
||||
|
||||
if (!read)
|
||||
return;
|
||||
try
|
||||
{
|
||||
int newMode = *(int*)(uiFlow + UIFlowCurModeOffset);
|
||||
if (newMode != oldMode)
|
||||
Observe(oldMode, newMode, "hook");
|
||||
else if (Volatile.Read(ref _mode) == ModeNone && newMode != ModeNone)
|
||||
Volatile.Write(ref _mode, newMode);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"UiFlowHooks: UseNewMode post-step threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static void ClientCleanupDetour(IntPtr client)
|
||||
{
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, void>)_originalCleanup;
|
||||
if (CleanupSlot.Enabled)
|
||||
{
|
||||
try { RaiseCleanup(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"UiFlowHooks: Client::Cleanup pre-step threw {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
}
|
||||
original(client);
|
||||
}
|
||||
|
||||
// ── Poll fallback ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// AC's main thread (CharacterManagementHooks.MainThreadTick): the UIFlow mode it just
|
||||
/// read at +0x8C. Seeds the mode; when the UseNewMode hook isn't live, a change here
|
||||
/// raises the screen events instead (after the fact: the old screen is already gone).
|
||||
/// </summary>
|
||||
public static void OnModePolled(int mode)
|
||||
{
|
||||
int known = Volatile.Read(ref _mode);
|
||||
if (mode == known)
|
||||
return;
|
||||
if (known == ModeNone || UseNewModeSlot.Live)
|
||||
{
|
||||
// Seed (late attach, hot reload). With the hook live a difference here means the
|
||||
// hook missed a change (it was switched off for a while): correct it quietly.
|
||||
Volatile.Write(ref _mode, mode);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
RaiseLeaving(known, mode, "poll");
|
||||
Observe(known, mode, "poll");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"UiFlowHooks: poll fallback threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Raising ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void RaiseLeaving(int oldMode, int newMode, string source)
|
||||
{
|
||||
if (oldMode == ModeGamePlay)
|
||||
OnLeavingWorld();
|
||||
try { ScreenLeaving?.Invoke(oldMode, newMode); }
|
||||
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ScreenLeaving handler threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaving the world: AC is about to free gmGamePlayUI and every panel in it. The
|
||||
/// engine's per-frame users of cached panel pointers (EndScene TickHide for chat,
|
||||
/// radar, powerbar, retail vitals) run on this same thread, so clearing them here
|
||||
/// closes the window the pump-thread logout dispatch left open (it clears them a
|
||||
/// frame or more later). Idempotent: the logout dispatch clears them again.
|
||||
/// </summary>
|
||||
private static void OnLeavingWorld()
|
||||
{
|
||||
try { ChatHooks.ResetCachedInstance(); } catch { }
|
||||
try { RadarHooks.ResetCachedInstance(); } catch { }
|
||||
try { PowerbarHooks.ResetCachedInstance(); } catch { }
|
||||
try { RetailVitalsHooks.ResetCachedInstance(); } catch { }
|
||||
try { UiElementHooks.OnScreenLeaving(); } catch { }
|
||||
}
|
||||
|
||||
private static void Observe(int oldMode, int newMode, string source)
|
||||
{
|
||||
Volatile.Write(ref _previousMode, oldMode);
|
||||
Volatile.Write(ref _mode, newMode);
|
||||
Interlocked.Increment(ref _changes);
|
||||
_lastSource = source;
|
||||
string note = $"{ModeName(oldMode)} -> {ModeName(newMode)} ({source})";
|
||||
UseNewModeSlot.LastNote = note;
|
||||
if (source == "hook") Interlocked.Increment(ref UseNewModeSlot.Fired);
|
||||
RynthLog.Compat($"UiFlowHooks: screen {note}.");
|
||||
|
||||
try { ScreenChanged?.Invoke(oldMode, newMode); }
|
||||
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ScreenChanged handler threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
try { Plugins.PluginManager.QueueScreenChanged(oldMode, newMode); }
|
||||
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: queueing OnScreenChanged threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
private static void RaiseCleanup()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _cleanupStarted, 1) != 0)
|
||||
return;
|
||||
CleanupSlot.Note("Client::Cleanup entered");
|
||||
RynthLog.Compat("UiFlowHooks: Client::Cleanup - the client is tearing down; telling plugins, then stopping plugin ticks and panels.");
|
||||
try { UiElementHooks.OnClientCleanup(); } catch { }
|
||||
try { ClientCleanup?.Invoke(); }
|
||||
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ClientCleanup handler threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
try { Plugins.PluginManager.DispatchClientCleanup(500); }
|
||||
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: plugin cleanup dispatch threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
// ── Status ───────────────────────────────────────────────────────────
|
||||
|
||||
public static string ModeName(int mode) => mode switch
|
||||
{
|
||||
ModeNone => "unknown",
|
||||
ModeIntro => "Intro",
|
||||
ModeDisconnected => "Disconnected",
|
||||
ModeDataPatch => "DataPatch",
|
||||
ModeCredits => "Credits",
|
||||
ModeGamePlay => "World",
|
||||
ModeEpilogue => "Epilogue",
|
||||
ModeCharacterManagement => "CharacterSelect",
|
||||
ModeCharGen => "CharGen",
|
||||
_ => $"0x{mode:X8}",
|
||||
};
|
||||
|
||||
public static string DescribeState()
|
||||
=> $"Screen: {ModeName(CurrentMode)} (before: {ModeName(PreviousMode)}), {Volatile.Read(ref _changes)} change(s), last via {_lastSource}; " +
|
||||
$"driven by {(UseNewModeSlot.Live ? "the UseNewMode hook" : "the +0x8C poll (fallback)")}; " +
|
||||
$"client cleanup {(ClientCleanupStarted ? "STARTED" : "not started")}.";
|
||||
}
|
||||
215
src/RynthCore.Engine/Compatibility/UiHookRegistry.cs
Normal file
215
src/RynthCore.Engine/Compatibility/UiHookRegistry.cs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/UiHookRegistry.cs
|
||||
//
|
||||
// Status and kill switches for the UI hooks of 2026-10-05 (Chorizite gaps #4
|
||||
// and #5): UiFlowHooks (UIFlow::UseNewMode, Client::Cleanup) and UiElementHooks
|
||||
// (tooltip start/reset/check, drag start, item drop).
|
||||
//
|
||||
// Every hook has its own switch, two ways:
|
||||
// - engine.json "DisabledUiHooks": ["StartTooltip", ...] - not installed at
|
||||
// the next start (EngineSettings.IsUiHookEnabled);
|
||||
// - /rc hooks off <name> - the detour turns into a plain pass-through at
|
||||
// once (it still calls AC's original), and the name is saved to
|
||||
// engine.json for the next start. /rc hooks on <name> undoes both.
|
||||
// /rc hooks (alone) lists every hook: address, how it was found, on/off,
|
||||
// how many times it fired and the last thing it saw.
|
||||
//
|
||||
// A hook that fails to resolve or install logs once (HookResolver /
|
||||
// TryInstall) and stays out: its slot says why, and nothing else changes.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class UiHookSlot
|
||||
{
|
||||
public UiHookSlot(string name, string what, int fallbackVa)
|
||||
{
|
||||
Name = name;
|
||||
What = what;
|
||||
FallbackVa = fallbackVa;
|
||||
}
|
||||
|
||||
/// <summary>The switch name (engine.json DisabledUiHooks, /rc hooks on|off).</summary>
|
||||
public string Name { get; }
|
||||
/// <summary>The AC function, for people.</summary>
|
||||
public string What { get; }
|
||||
public int FallbackVa { get; }
|
||||
|
||||
public IntPtr Address;
|
||||
/// <summary>"pattern", "fallback", or empty when not installed.</summary>
|
||||
public string Source = string.Empty;
|
||||
public bool Installed;
|
||||
/// <summary>Why it isn't installed ("off in engine.json", "pattern and fallback both failed", ...).</summary>
|
||||
public string Reason = "not probed yet";
|
||||
public int Fired;
|
||||
public string LastNote = string.Empty;
|
||||
|
||||
private int _enabled = 1;
|
||||
/// <summary>Runtime switch: false = the detour only calls AC's original.</summary>
|
||||
public bool Enabled
|
||||
{
|
||||
get => Volatile.Read(ref _enabled) != 0;
|
||||
set => Volatile.Write(ref _enabled, value ? 1 : 0);
|
||||
}
|
||||
|
||||
/// <summary>Installed and switched on: the detour does its work.</summary>
|
||||
public bool Live => Installed && Enabled;
|
||||
|
||||
public void Note(string note)
|
||||
{
|
||||
Interlocked.Increment(ref Fired);
|
||||
LastNote = note;
|
||||
}
|
||||
|
||||
public string Describe()
|
||||
{
|
||||
string state = Installed
|
||||
? (Enabled ? "on" : "OFF (pass-through)")
|
||||
: "not installed: " + Reason;
|
||||
string addr = Installed ? $"0x{Address.ToInt32():X8} via {Source}" : $"(fallback 0x{FallbackVa:X8})";
|
||||
string last = LastNote.Length > 0 ? $" last: {LastNote}" : string.Empty;
|
||||
return $"{Name} [{What}] {addr} - {state}; fired {Fired}x.{last}";
|
||||
}
|
||||
}
|
||||
|
||||
internal static class UiHookRegistry
|
||||
{
|
||||
private static readonly List<UiHookSlot> Slots = new();
|
||||
private static readonly object Sync = new();
|
||||
|
||||
public static UiHookSlot Register(string name, string what, int fallbackVa)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
foreach (UiHookSlot s in Slots)
|
||||
if (string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase))
|
||||
return s;
|
||||
var slot = new UiHookSlot(name, what, fallbackVa);
|
||||
Slots.Add(slot);
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
|
||||
public static UiHookSlot? Find(string name)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
foreach (UiHookSlot s in Slots)
|
||||
if (string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase))
|
||||
return s;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static List<UiHookSlot> All()
|
||||
{
|
||||
lock (Sync) return new List<UiHookSlot>(Slots);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The engine.json switch, checked before resolving (so a switched-off hook leaves
|
||||
/// no HookResolver line): false = leave the hook out; the slot says why.
|
||||
/// </summary>
|
||||
public static bool SwitchedOn(UiHookSlot slot)
|
||||
{
|
||||
if (EngineSettings.IsUiHookEnabled(slot.Name))
|
||||
return true;
|
||||
slot.Reason = "off in engine.json (DisabledUiHooks)";
|
||||
slot.Enabled = false;
|
||||
RynthLog.Compat($"UiHooks: {slot.Name} switched off in engine.json - not installed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs one UI hook from its HookResolver result: the Decal guard, then MinHook
|
||||
/// (created, not yet enabled: the caller stores the trampoline, then calls Enable).
|
||||
/// Never throws; on any failure the slot says why and the caller leaves the hook out.
|
||||
/// <paramref name="trampoline"/> is AC's original.
|
||||
/// </summary>
|
||||
public static bool TryInstall(UiHookSlot slot, HookResolver.ResolveResult resolved, IntPtr detour, out IntPtr trampoline)
|
||||
{
|
||||
trampoline = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
if (!resolved.Success)
|
||||
{
|
||||
slot.Reason = "pattern and fallback address both failed (see the HookResolver line)";
|
||||
return false;
|
||||
}
|
||||
|
||||
// A Decal client on its first engine load: a pattern miss there means someone
|
||||
// else (Decal, a Decal plugin) already patched the prologue. Don't stack on it.
|
||||
// (A hot reload misses the pattern too, on our own stub, and installs as usual.)
|
||||
if (resolved.Source == HookResolver.ResolveSource.FallbackVa
|
||||
&& DecalBridgeHost.Active && EntryPoint.InitCount < 2)
|
||||
{
|
||||
slot.Reason = "pattern missed in a Decal client (prologue already patched?) - left out";
|
||||
RynthLog.Compat($"UiHooks: {slot.Name} - pattern missed with Decal in the process; not hooking over someone else's patch.");
|
||||
return false;
|
||||
}
|
||||
|
||||
trampoline = Hooking.MinHook.HookCreate(resolved.Address, detour);
|
||||
Thread.MemoryBarrier();
|
||||
slot.Address = resolved.Address;
|
||||
slot.Source = resolved.Source == HookResolver.ResolveSource.PatternScan ? "pattern" : "fallback";
|
||||
slot.Installed = true;
|
||||
slot.Reason = string.Empty;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
trampoline = IntPtr.Zero;
|
||||
slot.Installed = false;
|
||||
slot.Reason = $"install threw {ex.GetType().Name}: {ex.Message}";
|
||||
RynthLog.Compat($"UiHooks: {slot.Name} install threw {ex.GetType().Name}: {ex.Message} - left out.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Enables a hook TryInstall created (after the caller stored the trampoline).</summary>
|
||||
public static bool Enable(UiHookSlot slot)
|
||||
{
|
||||
try
|
||||
{
|
||||
Hooking.MinHook.Enable(slot.Address);
|
||||
RynthLog.Compat($"UiHooks: {slot.Name} ready @ 0x{slot.Address.ToInt32():X8} ({slot.Source}).");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
slot.Installed = false;
|
||||
slot.Reason = $"enable threw {ex.GetType().Name}: {ex.Message}";
|
||||
RynthLog.Compat($"UiHooks: {slot.Name} enable threw {ex.GetType().Name}: {ex.Message} - left out.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>/rc hooks on|off <name>: runtime pass-through plus engine.json for the next start.</summary>
|
||||
public static string SetEnabled(string name, bool enabled)
|
||||
{
|
||||
UiHookSlot? slot = Find(name);
|
||||
if (slot == null)
|
||||
return $"No UI hook called '{name}'. Names: {string.Join(", ", All().ConvertAll(s => s.Name))}.";
|
||||
EngineSettings.SetUiHookEnabled(slot.Name, enabled);
|
||||
slot.Enabled = enabled;
|
||||
if (enabled && !slot.Installed)
|
||||
return $"{slot.Name}: switched on in engine.json; it installs at the next client start.";
|
||||
return enabled
|
||||
? $"{slot.Name}: on (now, and at the next start)."
|
||||
: $"{slot.Name}: off - passes straight to AC now, and isn't installed at the next start.";
|
||||
}
|
||||
|
||||
public static List<string> DescribeLines()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
foreach (UiHookSlot s in All())
|
||||
lines.Add(s.Describe());
|
||||
lines.Add(UiFlowHooks.DescribeState());
|
||||
lines.Add(UiElementHooks.DescribeState());
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
|
@ -327,14 +327,21 @@ internal static class EndSceneHook
|
|||
_renderCount++;
|
||||
_frameCount++;
|
||||
|
||||
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
|
||||
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals").
|
||||
try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// These four call into gameplay-UI panels they cached (gmMainChatUI, the radar, the
|
||||
// powerbar, the vitals bars). AC frees those when it leaves the world; outside the
|
||||
// world (UiFlowHooks: a screen change seen by the UseNewMode hook or the mode poll)
|
||||
// they don't run. Mode not known yet = as before.
|
||||
if (UiFlowHooks.InWorldOrUnknown && !UiFlowHooks.ClientCleanupStarted)
|
||||
{
|
||||
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
|
||||
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals").
|
||||
try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
}
|
||||
|
||||
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -172,6 +172,7 @@ internal static class EngineLifecycle
|
|||
// The chat log is written on the tick pump (UiDataHub), now stopped. Left open,
|
||||
// it outlived this generation and locked the next one out of the file.
|
||||
Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog());
|
||||
Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown());
|
||||
|
||||
Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll());
|
||||
|
||||
|
|
|
|||
|
|
@ -87,6 +87,10 @@ public static class EntryPoint
|
|||
[UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")]
|
||||
public static uint Shutdown(IntPtr lpParam)
|
||||
{
|
||||
// Only the loader's hot reload calls this export (process exit and the engine's own
|
||||
// teardowns call EngineLifecycle.Shutdown directly), on its reload thread: wait here,
|
||||
// with the game running on this engine, while a plugin says a reload now would hurt.
|
||||
try { DeferReloadWhilePluginsObject(); } catch { }
|
||||
try
|
||||
{
|
||||
EngineLifecycle.Shutdown();
|
||||
|
|
@ -102,6 +106,39 @@ public static class EntryPoint
|
|||
}
|
||||
}
|
||||
|
||||
// The shell's ERl button: a reload asked for by hand isn't held for the plugins. Only the
|
||||
// reload that follows within ManualReloadWindowMs counts (a refused or coalesced signal
|
||||
// must not exempt the next file-watcher reload).
|
||||
private static long _manualReloadAtMs;
|
||||
private const long ManualReloadWindowMs = 10_000;
|
||||
internal static void NoteManualReload() => Interlocked.Exchange(ref _manualReloadAtMs, Environment.TickCount64);
|
||||
|
||||
/// <summary>
|
||||
/// Reload deferral (2026-10-05, see ReloadDeferral.cs): asks the plugins
|
||||
/// (RynthPluginReloadBlocker) and waits up to ReloadDeferral.DefaultCap while one objects,
|
||||
/// e.g. "engine reload waiting: RynthAi in combat (a monster engaged, ...)". Says so in chat
|
||||
/// once. Never throws; a query that fails counts as "nothing objects".
|
||||
/// </summary>
|
||||
private static void DeferReloadWhilePluginsObject()
|
||||
{
|
||||
long manualAt = Interlocked.Exchange(ref _manualReloadAtMs, 0);
|
||||
if (manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs)
|
||||
{
|
||||
RynthLog.Info("engine reload: asked for by hand (ERl), so it isn't deferred for the plugins.");
|
||||
return;
|
||||
}
|
||||
var deferral = new ReloadDeferral
|
||||
{
|
||||
Query = PluginManager.QueryReloadBlockers,
|
||||
Log = msg => RynthLog.Info(msg),
|
||||
Notify = why => Compatibility.AcMainThreadQueue.EnqueueWriteToChat(
|
||||
$"[RynthCore] A new RynthCore build is ready. It loads when this is clear: {why} (at most {ReloadDeferral.DefaultCap.TotalMinutes:0} minutes).", 1),
|
||||
};
|
||||
ReloadDeferral.Outcome outcome = deferral.Run(out TimeSpan waited);
|
||||
if (outcome != ReloadDeferral.Outcome.Clear)
|
||||
RynthLog.Info($"engine reload: deferral {outcome} after {waited.TotalSeconds:0.0} s.");
|
||||
}
|
||||
|
||||
private static uint InitializeCore(IntPtr lpParam)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
|
||||
|
|
@ -666,6 +703,12 @@ public static class EntryPoint
|
|||
Step("raw packet hooks", RawPacketHooks.Initialize);
|
||||
Step("property-update hooks", PropertyUpdateHooks.Initialize);
|
||||
Step("auto-id service", AutoIdService.Start);
|
||||
// Screen-mode + client-teardown hooks (UIFlow::UseNewMode, Client::Cleanup) and
|
||||
// AC's tooltip / drag / drop (2026-10-05, Chorizite gaps #4-#5). Each hook has its
|
||||
// own switch (engine.json DisabledUiHooks, /rc hooks); one that doesn't resolve
|
||||
// stays out and says why in /rc hooks.
|
||||
Step("UI flow hooks", UiFlowHooks.Initialize);
|
||||
Step("UI element hooks", UiElementHooks.Initialize);
|
||||
// Bridge mode: wait (bounded) for the bridge's hello. In Auto mode a bridge that
|
||||
// never shows up means the old coexistence mode: install what was skipped.
|
||||
if (bridgeSkipped != null && !DecalBridgeHost.WaitForBridge(InitAborted))
|
||||
|
|
|
|||
|
|
@ -459,6 +459,10 @@ internal static class EngineFrameController
|
|||
if (Compatibility.DecalBridgeHost.Active)
|
||||
Compatibility.DecalBridgeHost.Drain();
|
||||
PluginManager.ProcessPendingActions(pluginContext, device, _gameHwnd);
|
||||
// Client::Cleanup started (UiFlowHooks): the call above told the plugins; from
|
||||
// here on no plugin tick and no plugin export for the panels' data.
|
||||
if (Compatibility.UiFlowHooks.ClientCleanupStarted)
|
||||
return;
|
||||
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
|
||||
PluginManager.TickAll();
|
||||
// Panel data: plugin exports for the UI are called here, on the same
|
||||
|
|
@ -475,6 +479,21 @@ internal static class EngineFrameController
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="action"/> on the calling thread while no plugin pump frame runs,
|
||||
/// holding the pump's frame guard so it can't start one meanwhile. False (not run) when a
|
||||
/// frame is running. For Client::Cleanup (UiFlowHooks): AC's main thread tells the
|
||||
/// plugins itself when the pump is idle or no longer running frames.
|
||||
/// </summary>
|
||||
internal static bool TryRunOutsidePumpFrame(Action action)
|
||||
{
|
||||
if (System.Threading.Interlocked.CompareExchange(ref _pluginPumpInFrame, 1, 0) != 0)
|
||||
return false;
|
||||
try { action(); }
|
||||
finally { System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 0); }
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True when anything ImGui should be drawn this frame.</summary>
|
||||
private static bool HasImGuiContent()
|
||||
{
|
||||
|
|
@ -486,9 +505,13 @@ internal static class EngineFrameController
|
|||
|
||||
/// <summary>
|
||||
/// Panel faces show only in the world, like the Avalonia overlay (hidden
|
||||
/// between characters, not closed).
|
||||
/// between characters, not closed). Also off as soon as AC leaves the world screen
|
||||
/// (UiFlowHooks, before the logout dispatch catches up) and for good once
|
||||
/// Client::Cleanup starts.
|
||||
/// </summary>
|
||||
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
|
||||
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete
|
||||
&& Compatibility.UiFlowHooks.InWorldOrUnknown
|
||||
&& !Compatibility.UiFlowHooks.ClientCleanupStarted;
|
||||
|
||||
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
|
||||
private static float _uiScale = 1f;
|
||||
|
|
|
|||
|
|
@ -123,6 +123,17 @@ internal static unsafe class ImGuiPopOuts
|
|||
/// <summary>The pop-out typing into a text box, or null (for the input log). AC thread.</summary>
|
||||
public static string? TextFocusTitle => _keyboard is { WantTextInput: true } k ? k.Title : null;
|
||||
|
||||
/// <summary>
|
||||
/// True when the cursor is over <paramref name="title"/>'s pop-out window right now
|
||||
/// (UiDropTargets: an AC item released over a popped-out panel). AC thread.
|
||||
/// </summary>
|
||||
public static bool IsCursorOver(string title)
|
||||
{
|
||||
if (!Pops.TryGetValue(title, out PopOut? pop) || pop.Window == null || pop.Window.Hwnd == IntPtr.Zero)
|
||||
return false;
|
||||
return GetCursorPos(out POINT cursor) && WindowFromPoint(cursor) == pop.Window.Hwnd;
|
||||
}
|
||||
|
||||
/// <summary>The screen position of the game window's client origin (to place a pop-out where the docked panel was).</summary>
|
||||
public static Vector2 ClientOriginOnScreen()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -858,9 +858,12 @@ internal static class MonsterHud
|
|||
const float margin = 60f;
|
||||
if (MonsterHudSettings.KeepOnScreen)
|
||||
{
|
||||
// Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name).
|
||||
Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale,
|
||||
(label ? 22f : 56f) * f.UiScale * userScale);
|
||||
// Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name),
|
||||
// grown with the plate type's bar / text size.
|
||||
float sideMul = label ? LabelTextSize(p.Kind) : MathF.Max(MonsterHudSettings.MonsterBarWidth, MonsterHudSettings.MonsterTextSize);
|
||||
float topMul = label ? LabelTextSize(p.Kind) : MathF.Max(MonsterHudSettings.MonsterBarHeight, MonsterHudSettings.MonsterTextSize);
|
||||
Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale * sideMul,
|
||||
(label ? 22f : 56f) * f.UiScale * userScale * topMul);
|
||||
p.Anchor = new Vector2(MathF.Round(c.X), MathF.Round(c.Y));
|
||||
p.OnScreen = true;
|
||||
}
|
||||
|
|
@ -1004,7 +1007,7 @@ internal static class MonsterHud
|
|||
if (p.IsLabel)
|
||||
{
|
||||
// Name only: the same bold bake as a monster's name, no bar, badge or icons.
|
||||
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s);
|
||||
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s * LabelTextSize(p.Kind));
|
||||
p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true);
|
||||
p.NameW = TextWidth(p.NameFont, p.NameSize, p.Name);
|
||||
p.BadgeW = 0f;
|
||||
|
|
@ -1016,14 +1019,17 @@ internal static class MonsterHud
|
|||
return;
|
||||
}
|
||||
|
||||
p.BarW = MathF.Round(112f * k);
|
||||
p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k);
|
||||
// Bar width / height and text size each have their own multiplier (1 = the default look).
|
||||
float text = MonsterHudSettings.MonsterTextSize;
|
||||
p.BarW = MathF.Round(112f * k * MonsterHudSettings.MonsterBarWidth);
|
||||
p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k * MonsterHudSettings.MonsterBarHeight);
|
||||
|
||||
// Sizes follow the 11 px bold / 9 px regular bakes; the font drawn is the smallest bake at
|
||||
// least that big, so a scaled-up plate shrinks a bigger bake instead of stretching (blur).
|
||||
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s);
|
||||
// Picking a baked font per size: nothing is re-baked when a text size changes.
|
||||
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s * text);
|
||||
p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true);
|
||||
p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s);
|
||||
p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s * text);
|
||||
p.SmallFont = ImGuiFonts.Sharp(p.SmallSize, bold: false);
|
||||
|
||||
p.NameW = MonsterHudSettings.ShowNames && p.Name.Length > 0 ? TextWidth(p.NameFont, p.NameSize, p.Name) : 0f;
|
||||
|
|
@ -1039,11 +1045,15 @@ internal static class MonsterHud
|
|||
float nameH = (p.NameW > 0 || p.BadgeW > 0) ? p.NameSize + 2f * k : 0f;
|
||||
// The weak pill (left) and distance (right) hang off the bar's ends: keep them
|
||||
// inside the crowd-avoidance box, symmetric so the plate stays centred.
|
||||
float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k : 0f;
|
||||
float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k * text : 0f;
|
||||
p.Width = MathF.Max(p.BarW + side, nameLine) + 8f * k;
|
||||
p.Height = nameH + p.BarH + p.BelowBar;
|
||||
}
|
||||
|
||||
/// <summary>A name label's text size: players' or NPCs' (vendors count as NPCs).</summary>
|
||||
private static float LabelTextSize(byte kind) =>
|
||||
kind == RadarKind.Player ? MonsterHudSettings.PlayerTextSize : MonsterHudSettings.NpcTextSize;
|
||||
|
||||
/// <summary>Screen rect of a plate at a given upward nudge: (x0, y0, x1, y1).</summary>
|
||||
private static Vector4 RectAt(Plate p, float nudge, float uiScale)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -102,6 +102,21 @@ internal static class MonsterHudSettings
|
|||
public static bool GainLum = true;
|
||||
public static bool GainRadiance = true;
|
||||
|
||||
// Per-plate-type sizing (2026-10-05), multipliers on today's look (1 = unchanged), applied on
|
||||
// top of Scale. Bar width / height and the text drawn in or over the plate, each on its own.
|
||||
// NPC and player names are name-only labels (no bar), so they only have a text size.
|
||||
/// <summary>Monster plates: the health bar's width and height, and their text (name, level, HP, weak-to, distance).</summary>
|
||||
public static float MonsterBarWidth = 1.0f, MonsterBarHeight = 1.0f, MonsterTextSize = 1.0f;
|
||||
/// <summary>Name labels over NPCs and vendors.</summary>
|
||||
public static float NpcTextSize = 1.0f;
|
||||
/// <summary>Name labels over other players.</summary>
|
||||
public static float PlayerTextSize = 1.0f;
|
||||
/// <summary>Your own plate: the three bars' width and height, and their text (cur / max numbers, your name).</summary>
|
||||
public static float SelfBarWidth = 1.0f, SelfBarHeight = 1.0f, SelfTextSize = 1.0f;
|
||||
public const float MinBarWidth = 0.5f, MaxBarWidth = 2.5f;
|
||||
public const float MinBarHeight = 0.5f, MaxBarHeight = 3.0f;
|
||||
public const float MinTextSize = 0.5f, MaxTextSize = 2.0f;
|
||||
|
||||
// ── Ranges (shared by the Settings face, the command and Load) ──────
|
||||
public const float MinDistance = 5f, MaxDistanceLimit = 120f;
|
||||
public const int MinPlates = 1, MaxPlatesLimit = 60;
|
||||
|
|
@ -137,74 +152,88 @@ internal static class MonsterHudSettings
|
|||
{
|
||||
string path = FilePath;
|
||||
if (!File.Exists(path)) return;
|
||||
foreach (string raw in File.ReadAllLines(path))
|
||||
{
|
||||
string line = raw.Trim();
|
||||
if (line.Length == 0 || line.StartsWith('#')) continue;
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
string key = line[..eq].Trim();
|
||||
string val = line[(eq + 1)..].Trim();
|
||||
switch (key)
|
||||
{
|
||||
case "enabled": Enabled = val == "1"; break;
|
||||
case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break;
|
||||
case "maxPlates":
|
||||
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
|
||||
MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit);
|
||||
break;
|
||||
case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break;
|
||||
case "showNames": ShowNames = val == "1"; break;
|
||||
case "showHp": ShowHpNumbers = val == "1"; break;
|
||||
case "showDistance": ShowDistance = val == "1"; break;
|
||||
case "showLevel": ShowLevel = val == "1"; break;
|
||||
case "showWeakness": ShowWeakness = val == "1"; break;
|
||||
case "fade": FadeWithDistance = val == "1"; break;
|
||||
case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break;
|
||||
case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break;
|
||||
case "clickSelect": ClickToSelect = val == "1"; break;
|
||||
case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break;
|
||||
case "npcNames": NpcNames = val == "1"; break;
|
||||
case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break;
|
||||
case "npcMax":
|
||||
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm))
|
||||
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
|
||||
break;
|
||||
case "playerNames": PlayerNames = val == "1"; break;
|
||||
case "showDebuffs": ShowDebuffs = val == "1"; break;
|
||||
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
|
||||
case "selfPlate": SelfPlate = val == "1"; break;
|
||||
case "selfNumbers": SelfNumbers = val == "1"; break;
|
||||
case "selfName": SelfName = val == "1"; break;
|
||||
case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break;
|
||||
case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break;
|
||||
case "selfLocked": SelfLocked = val == "1"; break;
|
||||
case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break;
|
||||
case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break;
|
||||
case "numbers": Numbers = val == "1"; break;
|
||||
case "numDealt": NumDealt = val == "1"; break;
|
||||
case "numTaken": NumTaken = val == "1"; break;
|
||||
case "numHeals": NumHeals = val == "1"; break;
|
||||
case "numKills": NumKills = val == "1"; break;
|
||||
case "keepOnScreen": KeepOnScreen = val == "1"; break;
|
||||
case "numRestores": NumRestores = val == "1"; break;
|
||||
case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break;
|
||||
case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break;
|
||||
case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break;
|
||||
case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break;
|
||||
case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break;
|
||||
case "gains": Gains = val == "1"; break;
|
||||
case "gainXp": GainXp = val == "1"; break;
|
||||
case "gainLum": GainLum = val == "1"; break;
|
||||
case "gainRadiance": GainRadiance = val == "1"; break;
|
||||
}
|
||||
}
|
||||
ApplyLines(File.ReadAllLines(path));
|
||||
}
|
||||
catch { /* best-effort: defaults stay */ }
|
||||
finally { _loaded = true; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies the file's key=value lines (unknown keys and bad values are skipped). Also the tests' entry.</summary>
|
||||
internal static void ApplyLines(string[] lines)
|
||||
{
|
||||
foreach (string raw in lines)
|
||||
{
|
||||
string line = raw.Trim();
|
||||
if (line.Length == 0 || line.StartsWith('#')) continue;
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
string key = line[..eq].Trim();
|
||||
string val = line[(eq + 1)..].Trim();
|
||||
switch (key)
|
||||
{
|
||||
case "enabled": Enabled = val == "1"; break;
|
||||
case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break;
|
||||
case "maxPlates":
|
||||
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
|
||||
MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit);
|
||||
break;
|
||||
case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break;
|
||||
case "showNames": ShowNames = val == "1"; break;
|
||||
case "showHp": ShowHpNumbers = val == "1"; break;
|
||||
case "showDistance": ShowDistance = val == "1"; break;
|
||||
case "showLevel": ShowLevel = val == "1"; break;
|
||||
case "showWeakness": ShowWeakness = val == "1"; break;
|
||||
case "fade": FadeWithDistance = val == "1"; break;
|
||||
case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break;
|
||||
case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break;
|
||||
case "clickSelect": ClickToSelect = val == "1"; break;
|
||||
case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break;
|
||||
case "npcNames": NpcNames = val == "1"; break;
|
||||
case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break;
|
||||
case "npcMax":
|
||||
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm))
|
||||
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
|
||||
break;
|
||||
case "playerNames": PlayerNames = val == "1"; break;
|
||||
case "showDebuffs": ShowDebuffs = val == "1"; break;
|
||||
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
|
||||
case "selfPlate": SelfPlate = val == "1"; break;
|
||||
case "selfNumbers": SelfNumbers = val == "1"; break;
|
||||
case "selfName": SelfName = val == "1"; break;
|
||||
case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break;
|
||||
case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break;
|
||||
case "selfLocked": SelfLocked = val == "1"; break;
|
||||
case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break;
|
||||
case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break;
|
||||
case "numbers": Numbers = val == "1"; break;
|
||||
case "numDealt": NumDealt = val == "1"; break;
|
||||
case "numTaken": NumTaken = val == "1"; break;
|
||||
case "numHeals": NumHeals = val == "1"; break;
|
||||
case "numKills": NumKills = val == "1"; break;
|
||||
case "keepOnScreen": KeepOnScreen = val == "1"; break;
|
||||
case "numRestores": NumRestores = val == "1"; break;
|
||||
case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break;
|
||||
case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break;
|
||||
case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break;
|
||||
case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break;
|
||||
case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break;
|
||||
case "gains": Gains = val == "1"; break;
|
||||
case "gainXp": GainXp = val == "1"; break;
|
||||
case "gainLum": GainLum = val == "1"; break;
|
||||
case "gainRadiance": GainRadiance = val == "1"; break;
|
||||
case "monsterBarWidth": if (TryF(val, out float mbw)) MonsterBarWidth = Math.Clamp(mbw, MinBarWidth, MaxBarWidth); break;
|
||||
case "monsterBarHeight": if (TryF(val, out float mbh)) MonsterBarHeight = Math.Clamp(mbh, MinBarHeight, MaxBarHeight); break;
|
||||
case "monsterTextSize": if (TryF(val, out float mts)) MonsterTextSize = Math.Clamp(mts, MinTextSize, MaxTextSize); break;
|
||||
case "npcTextSize": if (TryF(val, out float nts)) NpcTextSize = Math.Clamp(nts, MinTextSize, MaxTextSize); break;
|
||||
case "playerTextSize": if (TryF(val, out float pts)) PlayerTextSize = Math.Clamp(pts, MinTextSize, MaxTextSize); break;
|
||||
case "selfBarWidth": if (TryF(val, out float sbw)) SelfBarWidth = Math.Clamp(sbw, MinBarWidth, MaxBarWidth); break;
|
||||
case "selfBarHeight": if (TryF(val, out float sbh)) SelfBarHeight = Math.Clamp(sbh, MinBarHeight, MaxBarHeight); break;
|
||||
case "selfTextSize": if (TryF(val, out float sts)) SelfTextSize = Math.Clamp(sts, MinTextSize, MaxTextSize); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryF(string s, out float v) => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out v);
|
||||
|
||||
/// <summary>Writes the settings in the background. Any thread.</summary>
|
||||
|
|
@ -220,56 +249,70 @@ internal static class MonsterHudSettings
|
|||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
using var sw = new StreamWriter(path, append: false);
|
||||
sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.");
|
||||
sw.WriteLine($"enabled={B(Enabled)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}"));
|
||||
sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}");
|
||||
sw.WriteLine($"showNames={B(ShowNames)}");
|
||||
sw.WriteLine($"showHp={B(ShowHpNumbers)}");
|
||||
sw.WriteLine($"showDistance={B(ShowDistance)}");
|
||||
sw.WriteLine($"showLevel={B(ShowLevel)}");
|
||||
sw.WriteLine($"showWeakness={B(ShowWeakness)}");
|
||||
sw.WriteLine($"fade={B(FadeWithDistance)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
|
||||
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
|
||||
sw.WriteLine($"npcNames={B(NpcNames)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
|
||||
sw.WriteLine($"playerNames={B(PlayerNames)}");
|
||||
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
|
||||
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
|
||||
sw.WriteLine($"selfPlate={B(SelfPlate)}");
|
||||
sw.WriteLine($"selfNumbers={B(SelfNumbers)}");
|
||||
sw.WriteLine($"selfName={B(SelfName)}");
|
||||
sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}");
|
||||
sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}");
|
||||
sw.WriteLine($"selfLocked={B(SelfLocked)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}"));
|
||||
sw.WriteLine($"numbers={B(Numbers)}");
|
||||
sw.WriteLine($"numDealt={B(NumDealt)}");
|
||||
sw.WriteLine($"numTaken={B(NumTaken)}");
|
||||
sw.WriteLine($"numHeals={B(NumHeals)}");
|
||||
sw.WriteLine($"numKills={B(NumKills)}");
|
||||
sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}");
|
||||
sw.WriteLine($"numRestores={B(NumRestores)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}"));
|
||||
sw.WriteLine($"selfPosition={SelfPosition}");
|
||||
sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}"));
|
||||
sw.WriteLine($"gains={B(Gains)}");
|
||||
sw.WriteLine($"gainXp={B(GainXp)}");
|
||||
sw.WriteLine($"gainLum={B(GainLum)}");
|
||||
sw.WriteLine($"gainRadiance={B(GainRadiance)}");
|
||||
WriteAll(sw);
|
||||
}
|
||||
catch { /* non-fatal */ }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every setting as the file's key=value lines. Also the tests' entry.</summary>
|
||||
internal static void WriteAll(TextWriter sw)
|
||||
{
|
||||
sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.");
|
||||
sw.WriteLine($"enabled={B(Enabled)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}"));
|
||||
sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}");
|
||||
sw.WriteLine($"showNames={B(ShowNames)}");
|
||||
sw.WriteLine($"showHp={B(ShowHpNumbers)}");
|
||||
sw.WriteLine($"showDistance={B(ShowDistance)}");
|
||||
sw.WriteLine($"showLevel={B(ShowLevel)}");
|
||||
sw.WriteLine($"showWeakness={B(ShowWeakness)}");
|
||||
sw.WriteLine($"fade={B(FadeWithDistance)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
|
||||
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
|
||||
sw.WriteLine($"npcNames={B(NpcNames)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
|
||||
sw.WriteLine($"playerNames={B(PlayerNames)}");
|
||||
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
|
||||
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
|
||||
sw.WriteLine($"selfPlate={B(SelfPlate)}");
|
||||
sw.WriteLine($"selfNumbers={B(SelfNumbers)}");
|
||||
sw.WriteLine($"selfName={B(SelfName)}");
|
||||
sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}");
|
||||
sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}");
|
||||
sw.WriteLine($"selfLocked={B(SelfLocked)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}"));
|
||||
sw.WriteLine($"numbers={B(Numbers)}");
|
||||
sw.WriteLine($"numDealt={B(NumDealt)}");
|
||||
sw.WriteLine($"numTaken={B(NumTaken)}");
|
||||
sw.WriteLine($"numHeals={B(NumHeals)}");
|
||||
sw.WriteLine($"numKills={B(NumKills)}");
|
||||
sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}");
|
||||
sw.WriteLine($"numRestores={B(NumRestores)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}"));
|
||||
sw.WriteLine($"selfPosition={SelfPosition}");
|
||||
sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}"));
|
||||
sw.WriteLine($"gains={B(Gains)}");
|
||||
sw.WriteLine($"gainXp={B(GainXp)}");
|
||||
sw.WriteLine($"gainLum={B(GainLum)}");
|
||||
sw.WriteLine($"gainRadiance={B(GainRadiance)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"monsterBarWidth={MonsterBarWidth:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"monsterBarHeight={MonsterBarHeight:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"monsterTextSize={MonsterTextSize:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"npcTextSize={NpcTextSize:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"playerTextSize={PlayerTextSize:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"selfBarWidth={SelfBarWidth:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"selfBarHeight={SelfBarHeight:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"selfTextSize={SelfTextSize:0.##}"));
|
||||
}
|
||||
|
||||
private static string B(bool v) => v ? "1" : "0";
|
||||
|
||||
/// <summary>Back to the defaults (and saved). Render / chat thread.</summary>
|
||||
|
|
@ -286,9 +329,24 @@ internal static class MonsterHudSettings
|
|||
NumSize = 1.0f; NumTime = 1.0f; NumRestores = true; KeepOnScreen = true;
|
||||
GainSize = 1.0f; GainTime = 1.0f; SelfPosition = SelfPlatePosition.Above;
|
||||
Gains = true; GainXp = true; GainLum = true; GainRadiance = true;
|
||||
ResetSizesNoSave();
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Every plate type's bar and text size back to 1 (and saved). Render / chat thread.</summary>
|
||||
public static void ResetSizes()
|
||||
{
|
||||
ResetSizesNoSave();
|
||||
Save();
|
||||
}
|
||||
|
||||
private static void ResetSizesNoSave()
|
||||
{
|
||||
MonsterBarWidth = 1.0f; MonsterBarHeight = 1.0f; MonsterTextSize = 1.0f;
|
||||
NpcTextSize = 1.0f; PlayerTextSize = 1.0f;
|
||||
SelfBarWidth = 1.0f; SelfBarHeight = 1.0f; SelfTextSize = 1.0f;
|
||||
}
|
||||
|
||||
/// <summary>The fixed plate back to its default spot (and saved). Render / chat thread.</summary>
|
||||
public static void ResetSelfPosition()
|
||||
{
|
||||
|
|
@ -314,7 +372,10 @@ internal static class MonsterHudSettings
|
|||
$"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " +
|
||||
$"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " +
|
||||
$"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " +
|
||||
$"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)}).");
|
||||
$"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)}); " +
|
||||
$"sizes: monster bar {MonsterBarWidth:0.##}x{MonsterBarHeight:0.##} text {MonsterTextSize:0.##}, " +
|
||||
$"NPC text {NpcTextSize:0.##}, player text {PlayerTextSize:0.##}, " +
|
||||
$"your bars {SelfBarWidth:0.##}x{SelfBarHeight:0.##} text {SelfTextSize:0.##}.");
|
||||
|
||||
private static string OnOff(bool v) => v ? "on" : "off";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -68,6 +68,12 @@ internal static class MonsterHudSettingsUi
|
|||
changed |= Toggle("Weak-to element", ref MonsterHudSettings.ShowWeakness,
|
||||
"What the monster takes most damage from, from RynthAi's Damage data (needs RynthAi).");
|
||||
changed |= Toggle("Distance", ref MonsterHudSettings.ShowDistance, null);
|
||||
changed |= SizeSlider("Bar width", ref MonsterHudSettings.MonsterBarWidth, MonsterHudSettings.MinBarWidth, MonsterHudSettings.MaxBarWidth, w,
|
||||
"How wide a monster's health bar is (1.00x = the default). On top of Look > Scale.");
|
||||
changed |= SizeSlider("Bar height", ref MonsterHudSettings.MonsterBarHeight, MonsterHudSettings.MinBarHeight, MonsterHudSettings.MaxBarHeight, w,
|
||||
"How tall (thick) a monster's health bar is (1.00x = the default). HP numbers need a bar at least 9 px tall.");
|
||||
changed |= SizeSlider("Text size", ref MonsterHudSettings.MonsterTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
|
||||
"The monster plate's text: name, level badge, HP numbers, weak-to pill and distance (1.00x = the default).");
|
||||
|
||||
Section("Names over NPCs and players", w);
|
||||
changed |= Toggle("NPC names", ref MonsterHudSettings.NpcNames,
|
||||
|
|
@ -77,8 +83,12 @@ internal static class MonsterHudSettingsUi
|
|||
MonsterHudSettings.MinNpcDistance, MonsterHudSettings.MaxNpcDistanceLimit, "%.0f", w);
|
||||
changed |= SliderI("Max names", ref MonsterHudSettings.MaxNpcLabels,
|
||||
MonsterHudSettings.MinNpcLabels, MonsterHudSettings.MaxNpcLabelsLimit, w);
|
||||
changed |= SizeSlider("NPC name size", ref MonsterHudSettings.NpcTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
|
||||
"Text size of the names over NPCs and vendors (1.00x = the default). Names have no bar.");
|
||||
changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames,
|
||||
"The name over other players too (blue), within the same distance and count. Chat: /rv plates players.");
|
||||
changed |= SizeSlider("Player name size", ref MonsterHudSettings.PlayerTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
|
||||
"Text size of the names over other players (1.00x = the default). Names have no bar.");
|
||||
Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w);
|
||||
|
||||
Section("Debuffs", w);
|
||||
|
|
@ -94,6 +104,12 @@ internal static class MonsterHudSettingsUi
|
|||
"Your own health, stamina and mana bars: fixed on screen, or following your character. Chat: /rv plates self.");
|
||||
changed |= Toggle("Numbers on your bars", ref MonsterHudSettings.SelfNumbers, "\"cur / max\" inside each bar (taller bars).", sub: true);
|
||||
changed |= Toggle("Your name", ref MonsterHudSettings.SelfName, null, sub: true);
|
||||
changed |= SizeSlider("Your bar width", ref MonsterHudSettings.SelfBarWidth, MonsterHudSettings.MinBarWidth, MonsterHudSettings.MaxBarWidth, w,
|
||||
"How wide your health, stamina and mana bars are (1.00x = the default).");
|
||||
changed |= SizeSlider("Your bar height", ref MonsterHudSettings.SelfBarHeight, MonsterHudSettings.MinBarHeight, MonsterHudSettings.MaxBarHeight, w,
|
||||
"How tall (thick) each of your bars is (1.00x = the default). The numbers need a bar at least 8 px tall.");
|
||||
changed |= SizeSlider("Your text size", ref MonsterHudSettings.SelfTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
|
||||
"Your plate's text: the cur / max numbers and your name (1.00x = the default).");
|
||||
|
||||
bool fixedOn = MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed;
|
||||
if (Toggle("Fixed on screen", ref fixedOn,
|
||||
|
|
@ -151,6 +167,14 @@ internal static class MonsterHudSettingsUi
|
|||
changed |= Toggle("Fade and shrink with distance", ref MonsterHudSettings.FadeWithDistance, null);
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
|
||||
if (SmallButton("Reset bar and text sizes"))
|
||||
{
|
||||
MonsterHudSettings.ResetSizes(); // saves
|
||||
changed = false;
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("Every plate type's bar width, bar height and text size back to 1.00x.");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
if (SmallButton("Reset all to defaults"))
|
||||
{
|
||||
MonsterHudSettings.ResetToDefaults();
|
||||
|
|
@ -238,6 +262,15 @@ internal static class MonsterHudSettingsUi
|
|||
return EndSliderRow(changed);
|
||||
}
|
||||
|
||||
/// <summary>A size multiplier slider ("1.00x" = the default look) with a tooltip. Labels are the ids: keep them unique.</summary>
|
||||
private static bool SizeSlider(string label, ref float value, float min, float max, float w, string tip)
|
||||
{
|
||||
BeginSliderRow(label, w);
|
||||
bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, "%.2fx", ImGuiSliderFlags.AlwaysClamp);
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tip);
|
||||
return EndSliderRow(changed);
|
||||
}
|
||||
|
||||
private static bool SliderI(string label, ref int value, int min, int max, float w)
|
||||
{
|
||||
BeginSliderRow(label, w);
|
||||
|
|
|
|||
|
|
@ -280,15 +280,18 @@ internal static class PlayerPlate
|
|||
float k = l.K = MonsterHudSettings.Scale * uiScale;
|
||||
bool numbers = l.Numbers = MonsterHudSettings.SelfNumbers;
|
||||
// With numbers on, the bars grow to fit bold, outlined text that reads over any fill.
|
||||
l.BarW = MathF.Round((numbers ? 124f : 96f) * k);
|
||||
l.BarH = MathF.Round((numbers ? 15f : 5f) * k);
|
||||
// Width, height and text each have their own multiplier on top (1 = the default look).
|
||||
l.BarW = MathF.Round((numbers ? 124f : 96f) * k * MonsterHudSettings.SelfBarWidth);
|
||||
l.BarH = MathF.Round((numbers ? 15f : 5f) * k * MonsterHudSettings.SelfBarHeight);
|
||||
l.Gap = MathF.Max(2f, MathF.Round(2f * k));
|
||||
l.Round = MathF.Max(1f, 1.5f * k);
|
||||
// Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up).
|
||||
l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale);
|
||||
// Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up;
|
||||
// nothing is re-baked when the text size changes).
|
||||
float text = MonsterHudSettings.Scale * MonsterHudSettings.SelfTextSize;
|
||||
l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * text);
|
||||
l.Small = ImGuiFonts.Sharp(l.SmallSize, bold: true);
|
||||
l.BlockH = 3 * l.BarH + 2 * l.Gap;
|
||||
l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale);
|
||||
l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * text);
|
||||
l.NameFont = ImGuiFonts.Sharp(l.NameSize, bold: true);
|
||||
l.NameH = MonsterHudSettings.SelfName ? l.NameSize + 3f * k : 0f;
|
||||
return l;
|
||||
|
|
@ -358,7 +361,9 @@ internal static class PlayerPlate
|
|||
float tw = MonsterHud.TextWidth(font, size, text);
|
||||
var pos = new Vector2(MathF.Round(left + (w - tw) * 0.5f), MathF.Round(top + (h - size) * 0.5f));
|
||||
// A dark band behind the text, then an outline, so it reads over bright and dark fills alike.
|
||||
dl.AddRectFilled(new Vector2(pos.X - 3f, top + 1f), new Vector2(pos.X + tw + 3f, top + h - 1f), MonsterHud.Mul(0x70000000u, a), 2f);
|
||||
// (Text sized bigger than the bar: the band grows to the text.)
|
||||
dl.AddRectFilled(new Vector2(pos.X - 3f, MathF.Min(top + 1f, pos.Y)), new Vector2(pos.X + tw + 3f, MathF.Max(top + h - 1f, pos.Y + size)),
|
||||
MonsterHud.Mul(0x70000000u, a), 2f);
|
||||
MonsterHud.OutlinedText(dl, font, size, pos, a, text);
|
||||
dl.AddText(font, size, pos, MonsterHud.Mul(NumCol, a), text);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -205,6 +205,7 @@ internal sealed class LootEditorFace : IImGuiPanel
|
|||
else RuleView(origin, size, w);
|
||||
}
|
||||
End(origin, size);
|
||||
AcceptAcDrops(origin, size);
|
||||
_lootAdd.Draw();
|
||||
// An item rule added to the open profile: show it (the state already carries it and its Focus).
|
||||
if (_lootAdd.TakeAdded() && _mode == Mode.List && _state != null && _state.Focus >= 0 && _state.Focus < _state.Rules.Count)
|
||||
|
|
@ -212,6 +213,39 @@ internal sealed class LootEditorFace : IImGuiPanel
|
|||
_picker.Draw();
|
||||
}
|
||||
|
||||
// ── Drop an item from AC's own inventory on the editor (2026-10-05) ──
|
||||
// Compatibility/UiElementHooks keeps a drop over this body from AC (AC's own
|
||||
// "not caught" path, the item stays put) and hands the item here; it opens the
|
||||
// same "Add to loot profile" popup as "Add selected item", for that item.
|
||||
|
||||
private const string DropKey = "LootEditor";
|
||||
|
||||
private void AcceptAcDrops(Vector2 origin, Vector2 size)
|
||||
{
|
||||
LootEditStateDto? s = _state;
|
||||
bool can = !_unavailable && s != null && s.Path.Length > 0 && !s.Dirty
|
||||
&& (!s.ReadOnly || s.Format == "json") && !_lootAdd.IsOpen;
|
||||
UiDropTargets.Publish(DropKey, Title, origin, origin + size, can);
|
||||
|
||||
if (UiDropTargets.TryTake(DropKey, out uint itemId) && can)
|
||||
{
|
||||
Compatibility.ClientObjectHooks.TryGetObjectName(itemId, out string name);
|
||||
_lootAdd.Open(itemId, name ?? string.Empty, toOpenProfile: true);
|
||||
}
|
||||
|
||||
// While AC drags an item: show that letting go here adds a rule.
|
||||
if (!can || Compatibility.UiElementHooks.CurrentDragObject == 0)
|
||||
return;
|
||||
bool over = UiDropTargets.IsCursorOver(DropKey);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRect(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), over ? Green : Teal, 4, ImDrawFlags.None, over ? 3f : 1.5f);
|
||||
string hint = over ? "Let go: add a loot rule for this item" : "Drop an item here to add a loot rule";
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(hint);
|
||||
Vector2 at = new(origin.X + (size.X - ts.X) * 0.5f, origin.Y + size.Y - ts.Y - 10);
|
||||
dl.AddRectFilled(at - new Vector2(6, 3), at + ts + new Vector2(6, 3), ShellBg, 4);
|
||||
dl.AddText(at, over ? Green : Teal, hint);
|
||||
}
|
||||
|
||||
private void RequestOpen(string path)
|
||||
{
|
||||
if (_state != null && _state.Dirty && path.Length > 0 && !SamePath(path, _state.Path))
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ using System.Globalization;
|
|||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
|
||||
|
|
@ -53,6 +54,8 @@ internal sealed class SkillDatTables
|
|||
public uint[] TrainedXp = Array.Empty<uint>();
|
||||
public uint[] SpecializedXp = Array.Empty<uint>();
|
||||
public ulong[] LevelXp = Array.Empty<ulong>();
|
||||
/// <summary>The same arrays as one object (Compatibility/TrainingCosts).</summary>
|
||||
public XpTableData Xp = new();
|
||||
}
|
||||
|
||||
internal static class SkillDat
|
||||
|
|
@ -137,51 +140,31 @@ internal static class SkillDat
|
|||
return r.Ok && t.Skills.Count > 0;
|
||||
}
|
||||
|
||||
// The XpTable layout and the cost arithmetic live in Compatibility/TrainingCosts.cs (shared
|
||||
// with the plugin API's raise calls and tested against a real portal.dat).
|
||||
private static bool ParseXp(byte[] raw, SkillDatTables t)
|
||||
{
|
||||
var r = new Reader(raw);
|
||||
r.U32(); // file id
|
||||
int attrs = (int)r.U32(), vitals = (int)r.U32(), trained = (int)r.U32(), spec = (int)r.U32();
|
||||
int levels = (int)r.U32();
|
||||
if (!r.Ok || attrs < 0 || vitals < 0 || trained < 0 || spec < 0 || levels < 0
|
||||
|| attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000)
|
||||
return false;
|
||||
t.AttributeXp = r.U32s(attrs + 1);
|
||||
t.VitalXp = r.U32s(vitals + 1);
|
||||
t.TrainedXp = r.U32s(trained + 1);
|
||||
t.SpecializedXp = r.U32s(spec + 1);
|
||||
var lv = new ulong[levels + 1];
|
||||
for (int i = 0; i <= levels; i++) lv[i] = r.U64();
|
||||
t.LevelXp = lv;
|
||||
return r.Ok;
|
||||
if (!TrainingCosts.TryParseXpTable(raw, out XpTableData xp)) return false;
|
||||
t.Xp = xp;
|
||||
t.AttributeXp = xp.AttributeXp;
|
||||
t.VitalXp = xp.VitalXp;
|
||||
t.TrainedXp = xp.TrainedXp;
|
||||
t.SpecializedXp = xp.SpecializedXp;
|
||||
t.LevelXp = xp.LevelXp;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── XP arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ──
|
||||
|
||||
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
|
||||
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1 >= (uint)table.Length;
|
||||
public static bool IsMax(uint[] table, uint ranks) => TrainingCosts.IsMax(table, ranks);
|
||||
|
||||
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with <paramref name="spent"/> already spent; -1 past the top.</summary>
|
||||
public static long CostOf(uint[] table, uint ranks, uint spent, int n)
|
||||
{
|
||||
if (n < 1) return 0;
|
||||
long target = (long)ranks + n;
|
||||
if (target >= table.Length) return -1;
|
||||
return Math.Max(0L, (long)table[target] - spent);
|
||||
}
|
||||
public static long CostOf(uint[] table, uint ranks, uint spent, int n) => TrainingCosts.CostOf(table, ranks, spent, n);
|
||||
|
||||
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top rank.</summary>
|
||||
public static int Affordable(uint[] table, uint ranks, uint spent, long available)
|
||||
{
|
||||
int lo = 0, hi = Math.Max(0, table.Length - 1 - (int)Math.Min(ranks, (uint)int.MaxValue));
|
||||
while (lo < hi)
|
||||
{
|
||||
int mid = (lo + hi + 1) / 2;
|
||||
long c = CostOf(table, ranks, spent, mid);
|
||||
if (c >= 0 && c <= available) lo = mid; else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
public static int Affordable(uint[] table, uint ranks, uint spent, long available) =>
|
||||
TrainingCosts.Affordable(table, ranks, spent, available);
|
||||
|
||||
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
|
||||
private ref struct Reader
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
// ImGui face of the RynthVision settings (UI/Panels/RynthVisionPanel.cs),
|
||||
// in three tabs:
|
||||
// Terrain the plugin's overlays (radar ring, unclimbable slopes,
|
||||
// impassable water), colours (AARRGGBB hex + swatch), tuning
|
||||
// impassable water), colours (AARRGGBB hex + swatch) each
|
||||
// with an opacity slider (the colour's alpha byte), tuning
|
||||
// sliders (Ctrl+click to type a value), water terrain types,
|
||||
// and "Log terrain types here";
|
||||
// Nameplates the RynthVision nameplates (monster plates, debuff icons,
|
||||
|
|
@ -115,10 +116,15 @@ internal sealed class VisionFace : IImGuiPanel
|
|||
if (ImGuiNET.ImGui.Checkbox("Unclimbable slopes", ref s.Slopes)) Save(VisionKeys.Slopes);
|
||||
if (ImGuiNET.ImGui.Checkbox("Impassable water", ref s.Water)) Save(VisionKeys.Water);
|
||||
|
||||
Header("Colors (hex AARRGGBB)");
|
||||
Header("Colors (hex AARRGGBB) and opacity");
|
||||
ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8));
|
||||
busy |= ColorRow(SlopeColorF, _slopeHex, ref s.SlopeColor);
|
||||
busy |= OpacitySlider(SlopeOpacityF, _slopeHex, ref s.SlopeColor);
|
||||
busy |= ColorRow(WaterColorF, _waterHex, ref s.WaterColor);
|
||||
busy |= OpacitySlider(WaterOpacityF, _waterHex, ref s.WaterColor);
|
||||
busy |= ColorRow(RadarColorF, _radarHex, ref s.RadarColor);
|
||||
busy |= OpacitySlider(RadarOpacityF, _radarHex, ref s.RadarColor);
|
||||
ImGuiNET.ImGui.PopItemWidth();
|
||||
|
||||
Header("Tuning");
|
||||
ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8));
|
||||
|
|
@ -188,6 +194,10 @@ internal sealed class VisionFace : IImGuiPanel
|
|||
private static readonly Field SlopeColorF = Field.Color("Slope", VisionKeys.SlopeColor);
|
||||
private static readonly Field WaterColorF = Field.Color("Water", VisionKeys.WaterColor);
|
||||
private static readonly Field RadarColorF = Field.Color("Radar", VisionKeys.RadarColor);
|
||||
// Opacity is the colour's alpha byte: the slider saves the colour field.
|
||||
private static readonly Field SlopeOpacityF = Field.Slider("Slope opacity", VisionKeys.SlopeColor);
|
||||
private static readonly Field WaterOpacityF = Field.Slider("Water opacity", VisionKeys.WaterColor);
|
||||
private static readonly Field RadarOpacityF = Field.Slider("Radar ring opacity", VisionKeys.RadarColor);
|
||||
private static readonly Field RadarRangeF = Field.Slider("Radar range", VisionKeys.RadarRange);
|
||||
private static readonly Field RingThickF = Field.Slider("Ring thickness", VisionKeys.RingThick);
|
||||
private static readonly Field RingHeightF = Field.Slider("Ring height (m)", VisionKeys.RingHeight);
|
||||
|
|
@ -227,6 +237,24 @@ internal sealed class VisionFace : IImGuiPanel
|
|||
return typing;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The colour's alpha as 0-100 %: label, then the slider. Rewrites the alpha byte (RGB kept) and the hex
|
||||
/// box as it moves, saves the colour on release. Untouched, the colour is never rewritten. True while in use.
|
||||
/// </summary>
|
||||
private bool OpacitySlider(Field f, byte[] hex, ref uint argb)
|
||||
{
|
||||
ImGuiNET.ImGui.TextUnformatted(f.Label);
|
||||
float pct = ArgbOpacity.Percent(argb);
|
||||
if (ImGuiNET.ImGui.SliderFloat(f.Id, ref pct, 0f, 100f, "%.0f%%", ImGuiSliderFlags.AlwaysClamp))
|
||||
{
|
||||
argb = ArgbOpacity.WithPercent(argb, pct);
|
||||
WriteUtf8(hex, argb.ToString("X8"));
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key);
|
||||
ImGuiNET.ImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value");
|
||||
return ImGuiNET.ImGui.IsItemActive();
|
||||
}
|
||||
|
||||
/// <summary>Label, then the slider; saves on release (or after Ctrl+click typing). True while in use.</summary>
|
||||
private bool Slider(Field f, ref double value, double min, double max, string format)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -369,6 +369,8 @@ internal static class RynthCoreShell
|
|||
new System.Threading.Thread(() =>
|
||||
{
|
||||
System.Threading.Thread.Sleep(120);
|
||||
// Asked for by hand: the reload deferral (EntryPoint.Shutdown) doesn't hold it.
|
||||
EntryPoint.NoteManualReload();
|
||||
bool ok = EngineLifecycle.SignalReload();
|
||||
RynthLog.Info($"ERl: SignalReload returned {ok}.");
|
||||
})
|
||||
|
|
|
|||
135
src/RynthCore.Engine/ImGui/UiDropTargets.cs
Normal file
135
src/RynthCore.Engine/ImGui/UiDropTargets.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/UiDropTargets.cs
|
||||
//
|
||||
// AC items dropped on the engine's ImGui panels (2026-10-05). A face that takes
|
||||
// drops publishes its body rect every frame it draws (Publish); when the player
|
||||
// drags an item out of an AC item list (a pack, the main inventory) and lets go
|
||||
// over that rect, Compatibility/UiElementHooks' UIElement::CatchDroppedItem
|
||||
// detour asks TryClaim. A claimed drop never reaches AC: the detour answers
|
||||
// "not caught" (false), which is AC's own drop-rejected path, so the item stays
|
||||
// where it was. The face picks the item up with TryTake on its next draw.
|
||||
//
|
||||
// All on AC's main thread: faces draw in EndScene, the detour runs inside AC's
|
||||
// StopDragandDrop. A target not published for StaleMs (panel closed, hidden,
|
||||
// between characters) never claims.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class UiDropTargets
|
||||
{
|
||||
private const long StaleMs = 500;
|
||||
|
||||
private sealed class Target
|
||||
{
|
||||
public required string Key;
|
||||
public required string PanelTitle;
|
||||
public bool Popped;
|
||||
public Vector2 Min, Max; // ImGui coordinates of the game window's client area (docked)
|
||||
public long SeenMs;
|
||||
public bool Accepting;
|
||||
public bool HasDrop;
|
||||
public uint ItemId, SpellId;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
|
||||
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p);
|
||||
|
||||
private static readonly Dictionary<string, Target> Targets = new(StringComparer.Ordinal);
|
||||
private static readonly object Sync = new();
|
||||
|
||||
/// <summary>
|
||||
/// Once per frame from a face's Draw: <paramref name="min"/>..<paramref name="max"/> is the
|
||||
/// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size).
|
||||
/// <paramref name="accepting"/> false: drawn, but a drop now wouldn't be used (it then
|
||||
/// goes to AC as usual). Popped-out faces hit-test against their own window.
|
||||
/// </summary>
|
||||
public static void Publish(string key, string panelTitle, Vector2 min, Vector2 max, bool accepting)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (!Targets.TryGetValue(key, out Target? t))
|
||||
Targets[key] = t = new Target { Key = key, PanelTitle = panelTitle };
|
||||
t.Popped = ImGuiPopOuts.InPopOutFrame;
|
||||
t.Min = min;
|
||||
t.Max = max;
|
||||
t.Accepting = accepting;
|
||||
t.SeenMs = Environment.TickCount64;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UIElement::CatchDroppedItem detour, AC's main thread: is the cursor over a live,
|
||||
/// accepting target? Then that target takes the item and the caller keeps it from AC.
|
||||
/// </summary>
|
||||
public static bool TryClaim(uint itemId, uint spellId, out string key)
|
||||
{
|
||||
key = string.Empty;
|
||||
if (itemId == 0)
|
||||
return false;
|
||||
long now = Environment.TickCount64;
|
||||
lock (Sync)
|
||||
{
|
||||
foreach (Target t in Targets.Values)
|
||||
{
|
||||
if (!t.Accepting || now - t.SeenMs > StaleMs || !IsCursorOver(t))
|
||||
continue;
|
||||
t.HasDrop = true;
|
||||
t.ItemId = itemId;
|
||||
t.SpellId = spellId;
|
||||
key = t.Key;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The face's draw: an item dropped on it since the last call.</summary>
|
||||
public static bool TryTake(string key, out uint itemId)
|
||||
{
|
||||
itemId = 0;
|
||||
lock (Sync)
|
||||
{
|
||||
if (!Targets.TryGetValue(key, out Target? t) || !t.HasDrop)
|
||||
return false;
|
||||
t.HasDrop = false;
|
||||
itemId = t.ItemId;
|
||||
return itemId != 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cursor is over the target now (the face's "drop here" highlight).</summary>
|
||||
public static bool IsCursorOver(string key)
|
||||
{
|
||||
lock (Sync)
|
||||
return Targets.TryGetValue(key, out Target? t) && IsCursorOver(t);
|
||||
}
|
||||
|
||||
private static bool IsCursorOver(Target t)
|
||||
{
|
||||
if (t.Popped)
|
||||
return ImGuiPopOuts.IsCursorOver(t.PanelTitle);
|
||||
if (!GetCursorPos(out POINT p))
|
||||
return false;
|
||||
Vector2 local = new Vector2(p.X, p.Y) - ImGuiPopOuts.ClientOriginOnScreen();
|
||||
return local.X >= t.Min.X && local.Y >= t.Min.Y && local.X < t.Max.X && local.Y < t.Max.Y;
|
||||
}
|
||||
|
||||
public static string Describe()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
lock (Sync)
|
||||
{
|
||||
if (Targets.Count == 0)
|
||||
return "Drop targets: none drawn yet.";
|
||||
var parts = new List<string>();
|
||||
foreach (Target t in Targets.Values)
|
||||
parts.Add($"{t.Key} ({(now - t.SeenMs <= StaleMs ? (t.Accepting ? "live" : "drawn, not accepting") : "not drawn")}{(t.Popped ? ", popped out" : string.Empty)})");
|
||||
return "Drop targets: " + string.Join(", ", parts) + ".";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -898,6 +898,15 @@ internal static unsafe class Win32Backend
|
|||
}
|
||||
}
|
||||
|
||||
// ── Remote tap-to-click (the phone, via the StatusAgent's PostMessage) ──
|
||||
// A posted mouse message whose point is not where the cursor was when it was queued did not come
|
||||
// from the mouse: it is the StatusAgent clicking where the phone tapped. Without this, the ImGui
|
||||
// capture below judged it by the REAL cursor (NewFrame's GetCursorPos): on the focused client,
|
||||
// with the PC's mouse parked over a RynthCore panel, every remote click was eaten, and the
|
||||
// phone's tap still fed ImGui a fake cursor. Hand it straight to AC instead.
|
||||
if (IsRemoteClientMouse(hWnd, msg, lParam))
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
|
||||
|
||||
// ── Chat capture: consume all key input for the chat TextBox ────
|
||||
// Game HWND keeps Win32 focus throughout; callbacks dispatch Text
|
||||
// updates to the panel on Avalonia's UI thread — no Avalonia focus needed.
|
||||
|
|
@ -1486,6 +1495,29 @@ internal static unsafe class Win32Backend
|
|||
};
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetMessagePos();
|
||||
|
||||
/// <summary>
|
||||
/// True for a client-area mouse message another process posted (the StatusAgent's remote click):
|
||||
/// Windows stamps every queued message with the cursor position at the time it was queued
|
||||
/// (GetMessagePos). Mouse input carries that same point in lParam; a PostMessage from elsewhere
|
||||
/// carries its own point while the stamp is wherever the real cursor sat. A 2 px slack covers
|
||||
/// rounding. Only the move/click messages whose lParam is client coordinates are tested (the wheel's
|
||||
/// lParam is screen coordinates).
|
||||
/// </summary>
|
||||
private static bool IsRemoteClientMouse(IntPtr hWnd, uint msg, IntPtr lParam)
|
||||
{
|
||||
if (msg != WM_MOUSEMOVE && msg != WM_LBUTTONDOWN && msg != WM_LBUTTONUP && msg != WM_RBUTTONDOWN && msg != WM_RBUTTONUP)
|
||||
return false;
|
||||
uint pos = GetMessagePos();
|
||||
var stamp = new POINT { X = (short)(pos & 0xFFFF), Y = (short)((pos >> 16) & 0xFFFF) };
|
||||
if (!ScreenToClient(hWnd, ref stamp))
|
||||
return false;
|
||||
int x = (short)((long)lParam & 0xFFFF), y = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
return Math.Abs(stamp.X - x) > 2 || Math.Abs(stamp.Y - y) > 2;
|
||||
}
|
||||
|
||||
private static bool IsMouseMessage(uint msg)
|
||||
{
|
||||
return msg >= WM_MOUSEMOVE && msg <= WM_MBUTTONUP
|
||||
|
|
|
|||
157
src/RynthCore.Engine/Net/AcPacketWire.cs
Normal file
157
src/RynthCore.Engine/Net/AcPacketWire.cs
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/AcPacketWire.cs
|
||||
// Where the message fragments sit in one server-to-client UDP datagram.
|
||||
//
|
||||
// Written from the AC wire format as the engine already reads it (RawPacketParser's
|
||||
// 20-byte header + 16-byte fragment headers) and general knowledge of the protocol;
|
||||
// no generated definitions. Pure code: no engine state, compiled into the
|
||||
// NetMessageTests replay runner as is.
|
||||
//
|
||||
// Datagram:
|
||||
// header (20 bytes)
|
||||
// +0 u32 sequence
|
||||
// +4 u32 flags (PacketFlags below)
|
||||
// +8 u32 checksum (not checked: we only read)
|
||||
// +12 u16 recipient id
|
||||
// +14 u16 time
|
||||
// +16 u16 size bytes after the header (optional headers + fragments)
|
||||
// +18 u16 iteration
|
||||
// optional headers, one per flag bit set, in ascending bit order
|
||||
// fragments, back to back, when flags has BlobFragments
|
||||
//
|
||||
// Fragment (16-byte header, then its share of the message):
|
||||
// +0 u32 sequence the message's id: every fragment of one message shares it
|
||||
// +4 u32 id
|
||||
// +8 u16 count fragments in the message
|
||||
// +10 u16 size this fragment INCLUDING its 16-byte header
|
||||
// +12 u16 index 0..count-1
|
||||
// +14 u16 queue the client's dispatch queue (not the opcode)
|
||||
//
|
||||
// The walk is self-checking: the optional headers and the fragments must end exactly at
|
||||
// 20 + header.size. A datagram that doesn't is counted as malformed and skipped whole,
|
||||
// so a wrong guess about an optional header shows up as a counter, never as garbage.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
/// <summary>Packet header flag bits the reader needs.</summary>
|
||||
internal static class PacketFlags
|
||||
{
|
||||
public const uint Retransmission = 0x00000001;
|
||||
public const uint EncryptedChecksum = 0x00000002;
|
||||
public const uint BlobFragments = 0x00000004;
|
||||
public const uint ServerSwitch = 0x00000100; // 8 bytes
|
||||
public const uint LogonServerAddr = 0x00000200; // size unknown here: skip the datagram
|
||||
public const uint EmptyHeader1 = 0x00000400; // 0 bytes
|
||||
public const uint Referral = 0x00000800; // size unknown here: skip the datagram
|
||||
public const uint RequestRetransmit = 0x00001000; // u32 count + count * u32
|
||||
public const uint RejectRetransmit = 0x00002000; // u32 count + count * u32
|
||||
public const uint AckSequence = 0x00004000; // 4 bytes
|
||||
public const uint Disconnect = 0x00008000; // 0 bytes
|
||||
public const uint LoginRequest = 0x00010000; // client to server only: skip
|
||||
public const uint WorldLoginRequest = 0x00020000; // 8 bytes
|
||||
public const uint ConnectRequest = 0x00040000; // 32 bytes; starts a new session
|
||||
public const uint ConnectResponse = 0x00080000; // 8 bytes
|
||||
public const uint NetError = 0x00100000; // 8 bytes
|
||||
public const uint NetErrorDisconnect = 0x00200000; // 8 bytes
|
||||
public const uint CICMDCommand = 0x00400000; // 8 bytes
|
||||
public const uint TimeSync = 0x01000000; // 8 bytes
|
||||
public const uint EchoRequest = 0x02000000; // 4 bytes
|
||||
public const uint EchoResponse = 0x04000000; // 8 bytes
|
||||
public const uint Flow = 0x08000000; // 6 bytes
|
||||
|
||||
/// <summary>Flags whose optional header this reader can't size; a fragment datagram carrying one is skipped.</summary>
|
||||
public const uint Unsized = LogonServerAddr | Referral | LoginRequest | 0x00800000u | 0xF0000000u | 0x000000F8u;
|
||||
}
|
||||
|
||||
internal enum PacketWalk : byte
|
||||
{
|
||||
/// <summary>Fragments located.</summary>
|
||||
Ok,
|
||||
/// <summary>No BlobFragments flag: nothing to reassemble (acks, pings, time sync...).</summary>
|
||||
NoFragments,
|
||||
/// <summary>Shorter than a header, or the sizes don't add up.</summary>
|
||||
Malformed,
|
||||
/// <summary>Carries an optional header this reader can't size.</summary>
|
||||
UnknownOptional,
|
||||
}
|
||||
|
||||
internal static unsafe class AcPacketWire
|
||||
{
|
||||
public const int HeaderSize = 20;
|
||||
public const int FragmentHeaderSize = 16;
|
||||
|
||||
public static uint ReadU32(byte* p) => (uint)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
|
||||
public static ushort ReadU16(byte* p) => (ushort)(p[0] | (p[1] << 8));
|
||||
|
||||
/// <summary>The datagram's flags, or 0 when it is shorter than a header.</summary>
|
||||
public static uint Flags(byte* data, int length) => length >= HeaderSize ? ReadU32(data + 4) : 0;
|
||||
|
||||
/// <summary>
|
||||
/// Finds the fragment area of one datagram: [fragStart, fragEnd). Never reads past
|
||||
/// <paramref name="length"/>. Ok only when the optional headers sized and fragEnd is
|
||||
/// exactly where the header's size says the datagram ends.
|
||||
/// </summary>
|
||||
public static PacketWalk LocateFragments(byte* data, int length, out int fragStart, out int fragEnd)
|
||||
{
|
||||
fragStart = fragEnd = 0;
|
||||
if (data == null || length < HeaderSize)
|
||||
return PacketWalk.Malformed;
|
||||
|
||||
uint flags = ReadU32(data + 4);
|
||||
if ((flags & PacketFlags.BlobFragments) == 0)
|
||||
return PacketWalk.NoFragments;
|
||||
if ((flags & PacketFlags.Unsized) != 0)
|
||||
return PacketWalk.UnknownOptional;
|
||||
|
||||
int end = HeaderSize + ReadU16(data + 16);
|
||||
if (end > length)
|
||||
return PacketWalk.Malformed;
|
||||
|
||||
int pos = HeaderSize;
|
||||
if ((flags & PacketFlags.ServerSwitch) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.RequestRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed;
|
||||
if ((flags & PacketFlags.RejectRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed;
|
||||
if ((flags & PacketFlags.AckSequence) != 0) pos += 4;
|
||||
if ((flags & PacketFlags.WorldLoginRequest) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.ConnectRequest) != 0) pos += 32;
|
||||
if ((flags & PacketFlags.ConnectResponse) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.NetError) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.NetErrorDisconnect) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.CICMDCommand) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.TimeSync) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.EchoRequest) != 0) pos += 4;
|
||||
if ((flags & PacketFlags.EchoResponse) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.Flow) != 0) pos += 6;
|
||||
if (pos > end)
|
||||
return PacketWalk.Malformed;
|
||||
|
||||
// The fragments must tile [pos, end) exactly.
|
||||
int walk = pos;
|
||||
int guard = 0;
|
||||
while (walk < end)
|
||||
{
|
||||
if (walk + FragmentHeaderSize > end || ++guard > 64)
|
||||
return PacketWalk.Malformed;
|
||||
int size = ReadU16(data + walk + 10);
|
||||
if (size < FragmentHeaderSize || walk + size > end)
|
||||
return PacketWalk.Malformed;
|
||||
walk += size;
|
||||
}
|
||||
if (walk == pos)
|
||||
return PacketWalk.Malformed; // the flag promised fragments
|
||||
|
||||
fragStart = pos;
|
||||
fragEnd = end;
|
||||
return PacketWalk.Ok;
|
||||
}
|
||||
|
||||
private static bool SkipU32List(byte* data, int end, ref int pos)
|
||||
{
|
||||
if (pos + 4 > end) return false;
|
||||
uint n = ReadU32(data + pos);
|
||||
if (n > 256) return false;
|
||||
pos += 4 + (int)n * 4;
|
||||
return pos <= end;
|
||||
}
|
||||
}
|
||||
307
src/RynthCore.Engine/Net/FragmentReassembler.cs
Normal file
307
src/RynthCore.Engine/Net/FragmentReassembler.cs
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/FragmentReassembler.cs
|
||||
// Turns server-to-client datagrams into whole messages (u32 opcode + body).
|
||||
//
|
||||
// Runs on the consumer side of PacketRing (the plugin pump), never in the RecvFrom
|
||||
// detour. Read-only: it sees copies of the client's datagrams.
|
||||
//
|
||||
// Bounded:
|
||||
// - at most MaxPartials messages in progress; the least recently touched one is
|
||||
// dropped when another starts, and any untouched for StaleMs is dropped (either
|
||||
// way its sequence counts as done, so its late fragments are ignored);
|
||||
// - at most MaxFragments fragments (MaxFragments * FragmentStride bytes) per message;
|
||||
// a bigger one is dropped and its sequence remembered as done;
|
||||
// - a window of the last DoneWindow completed sequences rejects retransmitted copies.
|
||||
// Slot buffers are pinned arrays reused from one message to the next, so a steady
|
||||
// stream allocates nothing; a one-fragment message is handed over straight from the
|
||||
// datagram without a copy.
|
||||
//
|
||||
// Messages are delivered in the order they complete (a long message completes after
|
||||
// shorter ones that started later). The client applies them in its own order.
|
||||
//
|
||||
// Pure code; compiled into the NetMessageTests replay runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
/// <summary>Receives each completed message. <paramref name="message"/> starts with the u32 opcode and is valid only during the call.</summary>
|
||||
internal unsafe interface IServerMessageSink
|
||||
{
|
||||
void OnServerMessage(uint fragmentSequence, byte* message, int length);
|
||||
}
|
||||
|
||||
internal sealed unsafe class FragmentReassembler
|
||||
{
|
||||
public const int FragmentStride = 512; // > the largest fragment body a 484-byte datagram can carry
|
||||
public const int MaxFragments = 256; // 256 * 448 = ~112 KB of message
|
||||
public const int MaxPartials = 16;
|
||||
public const int DoneWindow = 4096; // power of two
|
||||
public const long StaleMs = 30_000;
|
||||
|
||||
private sealed class Slot
|
||||
{
|
||||
public bool InUse;
|
||||
public uint Sequence;
|
||||
public int Count;
|
||||
public int Received;
|
||||
public int Bytes;
|
||||
public long TouchedMs;
|
||||
public byte[]? Buffer; // pinned; Count * FragmentStride
|
||||
public readonly ushort[] Lengths = new ushort[MaxFragments];
|
||||
public readonly ulong[] Have = new ulong[MaxFragments / 64];
|
||||
}
|
||||
|
||||
private readonly Slot[] _slots = new Slot[MaxPartials];
|
||||
private readonly ulong[] _done = new ulong[DoneWindow / 64];
|
||||
private uint _maxDone;
|
||||
private bool _anyDone;
|
||||
|
||||
// ── counters (read by /rc netmsg; written on the consumer thread only) ──
|
||||
public long Packets, PacketsNoFragments, PacketsMalformed, PacketsUnknownOptional;
|
||||
public long Fragments, Messages, MultiFragmentMessages, DuplicateFragments, DuplicateMessages;
|
||||
public long BadFragments, Oversized, EvictedStale, EvictedFull, SessionResets;
|
||||
public uint LastUnknownFlags;
|
||||
|
||||
public FragmentReassembler()
|
||||
{
|
||||
for (int i = 0; i < _slots.Length; i++)
|
||||
_slots[i] = new Slot();
|
||||
}
|
||||
|
||||
public int PartialCount
|
||||
{
|
||||
get
|
||||
{
|
||||
int n = 0;
|
||||
foreach (Slot s in _slots) if (s.InUse) n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget everything in progress and the done window (a new session, or the stream switched on).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
s.InUse = false;
|
||||
Array.Clear(_done);
|
||||
_maxDone = 0;
|
||||
_anyDone = false;
|
||||
}
|
||||
|
||||
/// <summary>One received datagram. <paramref name="nowMs"/> is any monotonic millisecond clock.</summary>
|
||||
public void ProcessDatagram(byte* data, int length, long nowMs, IServerMessageSink sink)
|
||||
{
|
||||
Packets++;
|
||||
uint flags = AcPacketWire.Flags(data, length);
|
||||
if ((flags & PacketFlags.ConnectRequest) != 0)
|
||||
{
|
||||
// The server's half of a new connection: fragment sequences start over.
|
||||
Reset();
|
||||
SessionResets++;
|
||||
}
|
||||
|
||||
PacketWalk walk = AcPacketWire.LocateFragments(data, length, out int pos, out int end);
|
||||
switch (walk)
|
||||
{
|
||||
case PacketWalk.NoFragments: PacketsNoFragments++; return;
|
||||
case PacketWalk.Malformed: PacketsMalformed++; return;
|
||||
case PacketWalk.UnknownOptional: PacketsUnknownOptional++; LastUnknownFlags = flags; return;
|
||||
}
|
||||
|
||||
while (pos < end)
|
||||
{
|
||||
byte* f = data + pos;
|
||||
int size = AcPacketWire.ReadU16(f + 10);
|
||||
Fragments++;
|
||||
Fragment(AcPacketWire.ReadU32(f), AcPacketWire.ReadU16(f + 8), AcPacketWire.ReadU16(f + 12),
|
||||
f + AcPacketWire.FragmentHeaderSize, size - AcPacketWire.FragmentHeaderSize, nowMs, sink);
|
||||
pos += size;
|
||||
}
|
||||
|
||||
EvictStale(nowMs);
|
||||
}
|
||||
|
||||
private void Fragment(uint seq, int count, int index, byte* body, int bodyLen, long nowMs, IServerMessageSink sink)
|
||||
{
|
||||
if (count == 0 || index >= count)
|
||||
{
|
||||
BadFragments++;
|
||||
return;
|
||||
}
|
||||
if (IsDone(seq))
|
||||
{
|
||||
DuplicateFragments++;
|
||||
if (count == 1) DuplicateMessages++;
|
||||
return;
|
||||
}
|
||||
|
||||
if (count == 1)
|
||||
{
|
||||
if (bodyLen < 4)
|
||||
{
|
||||
BadFragments++;
|
||||
MarkDone(seq);
|
||||
return;
|
||||
}
|
||||
MarkDone(seq);
|
||||
Messages++;
|
||||
sink.OnServerMessage(seq, body, bodyLen);
|
||||
return;
|
||||
}
|
||||
|
||||
if (count > MaxFragments || bodyLen > FragmentStride)
|
||||
{
|
||||
Oversized++;
|
||||
DropSequence(seq);
|
||||
return;
|
||||
}
|
||||
|
||||
Slot? slot = FindSlot(seq) ?? StartSlot(seq, count, nowMs);
|
||||
if (slot.Count != count)
|
||||
{
|
||||
BadFragments++;
|
||||
return;
|
||||
}
|
||||
int word = index >> 6;
|
||||
ulong bit = 1UL << (index & 63);
|
||||
if ((slot.Have[word] & bit) != 0)
|
||||
{
|
||||
DuplicateFragments++;
|
||||
return;
|
||||
}
|
||||
|
||||
slot.Have[word] |= bit;
|
||||
slot.Lengths[index] = (ushort)bodyLen;
|
||||
slot.Received++;
|
||||
slot.Bytes += bodyLen;
|
||||
slot.TouchedMs = nowMs;
|
||||
fixed (byte* dst = slot.Buffer)
|
||||
Buffer.MemoryCopy(body, dst + index * FragmentStride, bodyLen, bodyLen);
|
||||
|
||||
if (slot.Received < slot.Count)
|
||||
return;
|
||||
|
||||
// Complete: pack the fragments together in place (fragment i moves down, never up).
|
||||
fixed (byte* buf = slot.Buffer)
|
||||
{
|
||||
int at = 0;
|
||||
for (int i = 0; i < slot.Count; i++)
|
||||
{
|
||||
int len = slot.Lengths[i];
|
||||
if (at != i * FragmentStride)
|
||||
Buffer.MemoryCopy(buf + i * FragmentStride, buf + at, len, len);
|
||||
at += len;
|
||||
}
|
||||
slot.InUse = false;
|
||||
MarkDone(seq);
|
||||
if (at < 4)
|
||||
{
|
||||
BadFragments++;
|
||||
return;
|
||||
}
|
||||
Messages++;
|
||||
MultiFragmentMessages++;
|
||||
sink.OnServerMessage(seq, buf, at);
|
||||
}
|
||||
}
|
||||
|
||||
private Slot? FindSlot(uint seq)
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
if (s.InUse && s.Sequence == seq)
|
||||
return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
private Slot StartSlot(uint seq, int count, long nowMs)
|
||||
{
|
||||
Slot? pick = null;
|
||||
foreach (Slot s in _slots)
|
||||
{
|
||||
if (!s.InUse) { pick = s; break; }
|
||||
}
|
||||
if (pick == null)
|
||||
{
|
||||
// All busy: drop the one touched longest ago.
|
||||
pick = _slots[0];
|
||||
foreach (Slot s in _slots)
|
||||
if (s.TouchedMs < pick.TouchedMs) pick = s;
|
||||
EvictedFull++;
|
||||
MarkDone(pick.Sequence); // its stragglers are ignored, not given a new slot
|
||||
}
|
||||
|
||||
int need = count * FragmentStride;
|
||||
if (pick.Buffer == null || pick.Buffer.Length < need)
|
||||
{
|
||||
// Rounded up so a slot settles at the size it needs; at most MaxFragments * 512.
|
||||
int cap = 4096;
|
||||
while (cap < need) cap <<= 1;
|
||||
pick.Buffer = GC.AllocateUninitializedArray<byte>(cap, pinned: true);
|
||||
}
|
||||
pick.InUse = true;
|
||||
pick.Sequence = seq;
|
||||
pick.Count = count;
|
||||
pick.Received = 0;
|
||||
pick.Bytes = 0;
|
||||
pick.TouchedMs = nowMs;
|
||||
Array.Clear(pick.Have);
|
||||
return pick;
|
||||
}
|
||||
|
||||
private void DropSequence(uint seq)
|
||||
{
|
||||
Slot? s = FindSlot(seq);
|
||||
if (s != null) s.InUse = false;
|
||||
MarkDone(seq);
|
||||
}
|
||||
|
||||
private void EvictStale(long nowMs)
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
{
|
||||
if (s.InUse && nowMs - s.TouchedMs > StaleMs)
|
||||
{
|
||||
s.InUse = false;
|
||||
MarkDone(s.Sequence); // a straggler can't start it again
|
||||
EvictedStale++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── done window: the last DoneWindow sequences, by bit ──────────────────
|
||||
|
||||
private bool IsDone(uint seq)
|
||||
{
|
||||
if (!_anyDone) return false;
|
||||
if (seq > _maxDone) return false;
|
||||
if (_maxDone - seq >= DoneWindow) return true; // too old to still be in flight
|
||||
return (_done[(seq & (DoneWindow - 1)) >> 6] & (1UL << (int)(seq & 63))) != 0;
|
||||
}
|
||||
|
||||
private void MarkDone(uint seq)
|
||||
{
|
||||
if (!_anyDone)
|
||||
{
|
||||
_anyDone = true;
|
||||
_maxDone = seq;
|
||||
}
|
||||
else if (seq > _maxDone)
|
||||
{
|
||||
// Clear the bits of the sequences the window slides over.
|
||||
uint advance = seq - _maxDone;
|
||||
if (advance >= DoneWindow)
|
||||
Array.Clear(_done);
|
||||
else
|
||||
for (uint s = _maxDone + 1; s != seq; s++)
|
||||
_done[(s & (DoneWindow - 1)) >> 6] &= ~(1UL << (int)(s & 63));
|
||||
_maxDone = seq;
|
||||
}
|
||||
else if (_maxDone - seq >= DoneWindow)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_done[(seq & (DoneWindow - 1)) >> 6] |= 1UL << (int)(seq & 63);
|
||||
}
|
||||
}
|
||||
139
src/RynthCore.Engine/Net/PacketRing.cs
Normal file
139
src/RynthCore.Engine/Net/PacketRing.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/PacketRing.cs
|
||||
// Hand-off of received datagrams from the RecvFrom detour to the plugin pump.
|
||||
//
|
||||
// The producer (the detour) only copies the datagram: no allocation, no lock, no
|
||||
// wait. A full ring, or a second producer arriving while one is writing, drops the
|
||||
// datagram and counts it; the client's own copy is never touched either way. The
|
||||
// consumer (the single TickAll driver) reads records in place and releases them.
|
||||
//
|
||||
// Records are 8-byte aligned: [i32 length][u32 stamp ms][bytes][pad]. A length of -1
|
||||
// means "the rest of the buffer is unused, continue at 0". Capacity is a power of two
|
||||
// and a multiple of 8, so a wrap marker always fits.
|
||||
//
|
||||
// Pure code (native memory, no engine state); compiled into the NetMessageTests runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
internal sealed unsafe class PacketRing
|
||||
{
|
||||
private const int RecordHeader = 8;
|
||||
private const int WrapMarker = -1;
|
||||
|
||||
private readonly byte* _buf;
|
||||
private readonly int _capacity;
|
||||
private readonly int _mask;
|
||||
// Byte counters that wrap (int, so reads and writes are single instructions on x86);
|
||||
// only their difference and their low bits are used.
|
||||
private int _head; // bytes written (producer)
|
||||
private int _tail; // bytes released (consumer)
|
||||
private int _writing; // producer claim
|
||||
|
||||
/// <summary>Largest datagram accepted; anything longer is dropped (AC's are under 500 bytes).</summary>
|
||||
public const int MaxDatagram = 2048;
|
||||
|
||||
public long Written;
|
||||
public long DroppedFull;
|
||||
public long DroppedContended;
|
||||
public long DroppedTooLong;
|
||||
|
||||
/// <summary>The ring's memory is never freed: the detour may still be running at teardown.</summary>
|
||||
/// <param name="startCounter">Where the wrapping byte counters start (tests start them near int.MaxValue).</param>
|
||||
public PacketRing(int capacityPow2, int startCounter = 0)
|
||||
{
|
||||
_head = _tail = startCounter & ~7;
|
||||
if (capacityPow2 < 4096 || (capacityPow2 & (capacityPow2 - 1)) != 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(capacityPow2));
|
||||
_capacity = capacityPow2;
|
||||
_mask = capacityPow2 - 1;
|
||||
_buf = (byte*)NativeMemory.AllocZeroed((nuint)capacityPow2);
|
||||
}
|
||||
|
||||
public int Capacity => _capacity;
|
||||
|
||||
/// <summary>Bytes in use (approximate when read from another thread).</summary>
|
||||
public int Used => unchecked(Volatile.Read(ref _head) - Volatile.Read(ref _tail));
|
||||
|
||||
/// <summary>Producer: copy one datagram in. Never blocks; false = dropped (counted).</summary>
|
||||
public bool TryWrite(byte* data, int length, uint stampMs)
|
||||
{
|
||||
if (length <= 0 || length > MaxDatagram)
|
||||
{
|
||||
DroppedTooLong++;
|
||||
return false;
|
||||
}
|
||||
if (Interlocked.CompareExchange(ref _writing, 1, 0) != 0)
|
||||
{
|
||||
Interlocked.Increment(ref DroppedContended);
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
int need = RecordHeader + ((length + 7) & ~7);
|
||||
int head = _head;
|
||||
int used = unchecked(head - Volatile.Read(ref _tail));
|
||||
int pos = head & _mask;
|
||||
int toEnd = _capacity - pos;
|
||||
int skip = need > toEnd ? toEnd : 0;
|
||||
if (used + skip + need > _capacity)
|
||||
{
|
||||
DroppedFull++;
|
||||
return false;
|
||||
}
|
||||
if (skip != 0)
|
||||
{
|
||||
*(int*)(_buf + pos) = WrapMarker;
|
||||
pos = 0;
|
||||
}
|
||||
*(int*)(_buf + pos) = length;
|
||||
*(uint*)(_buf + pos + 4) = stampMs;
|
||||
Buffer.MemoryCopy(data, _buf + pos + RecordHeader, length, length);
|
||||
Written++;
|
||||
Volatile.Write(ref _head, unchecked(head + skip + need)); // publish after the bytes
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _writing, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Consumer: the oldest record, in place. Call <see cref="Release"/> with the returned
|
||||
/// token when done with it (the bytes stay valid until then).
|
||||
/// </summary>
|
||||
public bool TryPeek(out byte* data, out int length, out uint stampMs, out int releaseTo)
|
||||
{
|
||||
data = null;
|
||||
length = 0;
|
||||
stampMs = 0;
|
||||
releaseTo = 0;
|
||||
int tail = _tail;
|
||||
int head = Volatile.Read(ref _head);
|
||||
if (tail == head)
|
||||
return false;
|
||||
int pos = tail & _mask;
|
||||
int len = *(int*)(_buf + pos);
|
||||
if (len == WrapMarker)
|
||||
{
|
||||
tail = unchecked(tail + _capacity - pos);
|
||||
pos = 0;
|
||||
len = *(int*)_buf;
|
||||
}
|
||||
data = _buf + pos + RecordHeader;
|
||||
length = len;
|
||||
stampMs = *(uint*)(_buf + pos + 4);
|
||||
releaseTo = unchecked(tail + RecordHeader + ((len + 7) & ~7));
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Release(int releaseTo) => Volatile.Write(ref _tail, releaseTo);
|
||||
|
||||
/// <summary>Consumer: drop everything queued (used when the stream is switched on again).</summary>
|
||||
public void Clear() => Volatile.Write(ref _tail, Volatile.Read(ref _head));
|
||||
}
|
||||
84
src/RynthCore.Engine/Net/ServerMessageInterest.cs
Normal file
84
src/RynthCore.Engine/Net/ServerMessageInterest.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/ServerMessageInterest.cs
|
||||
// Which server messages one plugin asked for (PluginContract.SetServerMessageInterestFn).
|
||||
//
|
||||
// Opcodes and game event types are 16-bit on the wire in practice; each set is a
|
||||
// 65536-bit map (8 KB), so a check is one load. Special entries:
|
||||
// opcode 0xFFFFFFFF every message;
|
||||
// opcode 0xF7B0 every game event (otherwise only the listed event types).
|
||||
// Pure code; compiled into the NetMessageTests runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
internal sealed class ServerMessageInterest
|
||||
{
|
||||
public const uint GameEventOpcode = 0xF7B0;
|
||||
public const uint AllMessages = 0xFFFFFFFF;
|
||||
public const int MaxEntries = 4096;
|
||||
|
||||
private readonly ulong[] _opcodes = new ulong[65536 / 64];
|
||||
private readonly ulong[] _events = new ulong[65536 / 64];
|
||||
|
||||
public bool All { get; private set; }
|
||||
public bool AllGameEvents { get; private set; }
|
||||
public int OpcodeCount { get; private set; }
|
||||
public int EventCount { get; private set; }
|
||||
public bool IsEmpty => !All && OpcodeCount == 0 && EventCount == 0;
|
||||
|
||||
/// <summary>Replaces the set. False (set left empty) for an entry out of range or too many entries.</summary>
|
||||
public unsafe bool Set(uint* opcodes, int opcodeCount, uint* events, int eventCount)
|
||||
{
|
||||
Clear();
|
||||
if (opcodeCount < 0 || eventCount < 0 || opcodeCount > MaxEntries || eventCount > MaxEntries)
|
||||
return false;
|
||||
if ((opcodeCount > 0 && opcodes == null) || (eventCount > 0 && events == null))
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < opcodeCount; i++)
|
||||
{
|
||||
uint op = opcodes[i];
|
||||
if (op == AllMessages) { All = true; continue; }
|
||||
if (op > 0xFFFF) { Clear(); return false; }
|
||||
if (op == GameEventOpcode) AllGameEvents = true;
|
||||
if (Add(_opcodes, op)) OpcodeCount++;
|
||||
}
|
||||
for (int i = 0; i < eventCount; i++)
|
||||
{
|
||||
uint ev = events[i];
|
||||
if (ev > 0xFFFF) { Clear(); return false; }
|
||||
if (Add(_events, ev)) EventCount++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
Array.Clear(_opcodes);
|
||||
Array.Clear(_events);
|
||||
All = AllGameEvents = false;
|
||||
OpcodeCount = EventCount = 0;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="eventType"/> is only looked at for opcode 0xF7B0.</summary>
|
||||
public bool Wants(uint opcode, uint eventType)
|
||||
{
|
||||
if (All) return true;
|
||||
if (opcode > 0xFFFF) return false;
|
||||
if (opcode == GameEventOpcode)
|
||||
return AllGameEvents || (eventType <= 0xFFFF && Has(_events, eventType));
|
||||
return Has(_opcodes, opcode);
|
||||
}
|
||||
|
||||
private static bool Has(ulong[] map, uint v) => (map[v >> 6] & (1UL << (int)(v & 63))) != 0;
|
||||
|
||||
private static bool Add(ulong[] map, uint v)
|
||||
{
|
||||
ulong bit = 1UL << (int)(v & 63);
|
||||
if ((map[v >> 6] & bit) != 0) return false;
|
||||
map[v >> 6] |= bit;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
336
src/RynthCore.Engine/Net/ServerMessageStream.cs
Normal file
336
src/RynthCore.Engine/Net/ServerMessageStream.cs
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/ServerMessageStream.cs
|
||||
// The reassembled server-message stream for plugins (API v78).
|
||||
//
|
||||
// RecvFrom detour (RawPacketHooks) plugin pump (PluginManager.ProcessPendingActions)
|
||||
// OnDatagram: one volatile check; while Pump: drains the ring through the
|
||||
// capturing, copies fragment datagrams -> FragmentReassembler; each whole message goes
|
||||
// into PacketRing (no alloc, no lock, to the plugins that asked for it (and to the
|
||||
// never waits; full = dropped + counted) /rc netmsg log tap and capture file).
|
||||
//
|
||||
// Strictly read-only: the detour copies the client's bytes after the real recvfrom
|
||||
// returned them; it never alters, delays or drops anything the client gets.
|
||||
//
|
||||
// Capturing runs only while it is wanted: a plugin with a non-empty interest, or
|
||||
// /rc netmsg log / capture. engine.json "ServerMessageStream": false (or /rc netmsg off)
|
||||
// keeps it off whatever is wanted, and the detour is then exactly what it was before.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.PluginSdk.Net;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
internal static unsafe class ServerMessageStream
|
||||
{
|
||||
private const int RingBytes = 512 * 1024;
|
||||
private const int MaxPacketsPerPump = 8192;
|
||||
private const long MaxCaptureBytes = 32L * 1024 * 1024;
|
||||
private const int MaxLogLinesPerKind = 5;
|
||||
private const int MaxLogLines = 300;
|
||||
|
||||
private static PacketRing? _ring; // created on first use, never freed (see PacketRing)
|
||||
private static readonly FragmentReassembler Reassembler = new();
|
||||
private static readonly Sink MessageSink = new();
|
||||
private static volatile bool _capturing;
|
||||
private static bool _sessionOff;
|
||||
private static bool _pluginsWant;
|
||||
|
||||
// Delivery counters (pump thread).
|
||||
private static long _delivered, _dispatchedToPlugins;
|
||||
private static long _pumpTicksTotal, _pumpTicksMax, _pumps;
|
||||
|
||||
// /rc netmsg log: check the SDK parsers against the live server.
|
||||
private static bool _logOn;
|
||||
private static int _logLines;
|
||||
private static readonly Dictionary<string, KindStats> Kinds = new();
|
||||
private static readonly Dictionary<uint, long> Opcodes = new();
|
||||
private static readonly object LogLock = new(); // Kinds/Opcodes: pump writes, chat commands read
|
||||
|
||||
// /rc netmsg capture: raw fragment datagrams for tools\NetMessageTests.
|
||||
private static volatile FileStream? _capture; // opened by the command, written and closed by the pump
|
||||
private static volatile bool _captureStopRequested;
|
||||
private static string _capturePath = "";
|
||||
private static long _captureBytes;
|
||||
|
||||
private sealed class KindStats
|
||||
{
|
||||
public long Ok, Failed, Leftover;
|
||||
public int Logged;
|
||||
}
|
||||
|
||||
/// <summary>True while the detour copies datagrams.</summary>
|
||||
public static bool Capturing => _capturing;
|
||||
|
||||
// ── receive hook side ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Called by the RecvFrom detour after the real recvfrom, with the bytes it returned.</summary>
|
||||
public static void OnDatagram(byte* data, int length)
|
||||
{
|
||||
if (!_capturing)
|
||||
return;
|
||||
PacketRing? ring = _ring;
|
||||
if (ring == null || length < AcPacketWire.HeaderSize)
|
||||
return;
|
||||
uint flags = AcPacketWire.ReadU32(data + 4);
|
||||
if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) == 0)
|
||||
return; // acks, pings, time sync: nothing to reassemble
|
||||
ring.TryWrite(data, length, (uint)Environment.TickCount);
|
||||
}
|
||||
|
||||
// ── pump side ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Once per ProcessPendingActions (the single TickAll driver). <paramref name="pluginsWant"/>:
|
||||
/// some initialized plugin has a non-empty interest.
|
||||
/// </summary>
|
||||
public static void Pump(bool pluginsWant)
|
||||
{
|
||||
_pluginsWant = pluginsWant;
|
||||
if (_captureStopRequested)
|
||||
{
|
||||
_captureStopRequested = false;
|
||||
StopCapture("stopped");
|
||||
}
|
||||
bool want = EngineSettings.ServerMessageStream && !_sessionOff && (pluginsWant || _logOn || _capture != null);
|
||||
if (want != _capturing)
|
||||
{
|
||||
if (want)
|
||||
{
|
||||
_ring ??= new PacketRing(RingBytes);
|
||||
_ring.Clear();
|
||||
Reassembler.Reset();
|
||||
}
|
||||
_capturing = want;
|
||||
RynthLog.Compat($"ServerMessageStream: capture {(want ? "on" : "off")} (plugins={pluginsWant} log={_logOn} file={_capture != null})");
|
||||
}
|
||||
|
||||
PacketRing? ring = _ring;
|
||||
if (ring == null)
|
||||
return;
|
||||
if (!_capturing)
|
||||
{
|
||||
if (ring.Used != 0) ring.Clear();
|
||||
return;
|
||||
}
|
||||
|
||||
long start = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
long now = Environment.TickCount64;
|
||||
int n = 0;
|
||||
while (n < MaxPacketsPerPump && ring.TryPeek(out byte* data, out int len, out uint stamp, out int releaseTo))
|
||||
{
|
||||
n++;
|
||||
try
|
||||
{
|
||||
if (_capture != null) WriteCapture(data, len, stamp);
|
||||
Reassembler.ProcessDatagram(data, len, now, MessageSink);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ServerMessageStream: datagram failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
ring.Release(releaseTo);
|
||||
}
|
||||
if (n > 0)
|
||||
{
|
||||
long ticks = System.Diagnostics.Stopwatch.GetTimestamp() - start;
|
||||
_pumps++;
|
||||
_pumpTicksTotal += ticks;
|
||||
if (ticks > _pumpTicksMax) _pumpTicksMax = ticks;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Sink : IServerMessageSink
|
||||
{
|
||||
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
|
||||
{
|
||||
_delivered++;
|
||||
uint opcode = AcPacketWire.ReadU32(message);
|
||||
uint eventType = opcode == ServerMessage.GameEventOpcode && length >= 16 ? AcPacketWire.ReadU32(message + 12) : 0;
|
||||
if (_logOn)
|
||||
{
|
||||
try { LogTap(opcode, eventType, message, length); }
|
||||
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: log tap failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
if (_pluginsWant)
|
||||
_dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4);
|
||||
}
|
||||
}
|
||||
|
||||
// ── /rc netmsg ──────────────────────────────────────────────────────────
|
||||
|
||||
public static string[] HandleCommand(string args)
|
||||
{
|
||||
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status";
|
||||
string arg = parts.Length > 1 ? parts[1].ToLowerInvariant() : "";
|
||||
switch (verb)
|
||||
{
|
||||
case "on":
|
||||
_sessionOff = false;
|
||||
return new[] { EngineSettings.ServerMessageStream
|
||||
? "Server message stream allowed for this session (it runs while a plugin, the log or a capture wants it)."
|
||||
: "engine.json has \"ServerMessageStream\": false - the stream stays off. Remove it (or set true) and restart." };
|
||||
case "off":
|
||||
_sessionOff = true;
|
||||
return new[] { "Server message stream off for this session (plugins get nothing until /rc netmsg on)." };
|
||||
case "log":
|
||||
if (arg is "on" or "")
|
||||
{
|
||||
lock (LogLock) { _logLines = 0; Kinds.Clear(); Opcodes.Clear(); }
|
||||
_logOn = true;
|
||||
return new[] { "Server message log on: parsed messages go to the RynthCore log (NetMsg:), counts to /rc netmsg." };
|
||||
}
|
||||
if (arg == "off") { _logOn = false; return new[] { "Server message log off." }; }
|
||||
return new[] { "Usage: /rc netmsg log on|off" };
|
||||
case "capture":
|
||||
if (arg is "on" or "") return new[] { StartCapture() };
|
||||
if (arg == "off")
|
||||
{
|
||||
if (_capture == null) return new[] { "Not capturing." };
|
||||
_captureStopRequested = true; // the pump closes it after its current write
|
||||
return new[] { $"Capture stopping: {_capturePath}." };
|
||||
}
|
||||
return new[] { "Usage: /rc netmsg capture on|off" };
|
||||
case "status":
|
||||
return StatusLines();
|
||||
default:
|
||||
return new[] { "Usage: /rc netmsg [status|on|off|log on|off|capture on|off]" };
|
||||
}
|
||||
}
|
||||
|
||||
public static string[] StatusLines()
|
||||
{
|
||||
var r = Reassembler;
|
||||
var lines = new List<string>
|
||||
{
|
||||
$"Server messages: setting {(EngineSettings.ServerMessageStream ? "on" : "OFF (engine.json)")}, session {(_sessionOff ? "off" : "on")}, " +
|
||||
$"capturing {(_capturing ? "yes" : "no")}, hook {(Compatibility.RawPacketHooks.IsInstalled ? "installed" : "NOT installed")}; " +
|
||||
$"plugins {PluginManager.ServerMessageSubscriberCount()} subscribed",
|
||||
};
|
||||
if (_ring != null)
|
||||
lines.Add($"Ring: {_ring.Written} datagrams copied, dropped {_ring.DroppedFull} full / {_ring.DroppedContended} contended / {_ring.DroppedTooLong} too long, {_ring.Used / 1024} KB queued");
|
||||
lines.Add($"Reassembly: {r.Packets} packets ({r.PacketsNoFragments} no fragments, {r.PacketsMalformed} malformed, {r.PacketsUnknownOptional} unknown header" +
|
||||
(r.PacketsUnknownOptional > 0 ? $" last flags 0x{r.LastUnknownFlags:X8}" : "") + $"), {r.Fragments} fragments, " +
|
||||
$"{r.Messages} messages ({r.MultiFragmentMessages} multi-fragment), dup {r.DuplicateFragments} fragments / {r.DuplicateMessages} messages, " +
|
||||
$"bad {r.BadFragments}, oversized {r.Oversized}, evicted {r.EvictedStale} stale / {r.EvictedFull} full, {r.PartialCount} partial, {r.SessionResets} session resets");
|
||||
double tickUs = 1_000_000.0 / System.Diagnostics.Stopwatch.Frequency;
|
||||
lines.Add($"Delivered {_delivered}, plugin calls {_dispatchedToPlugins}; drain (incl. plugin calls) avg {(_pumps > 0 ? _pumpTicksTotal * tickUs / _pumps : 0):0.0} us, max {_pumpTicksMax * tickUs:0} us over {_pumps} drains");
|
||||
lock (LogLock)
|
||||
if (_logOn || Kinds.Count > 0)
|
||||
{
|
||||
string kinds = string.Join(", ", Kinds.OrderBy(k => k.Key).Select(k => $"{k.Key} {k.Value.Ok} ok" +
|
||||
(k.Value.Failed > 0 ? $"/{k.Value.Failed} FAILED" : "") + (k.Value.Leftover > 0 ? $"/{k.Value.Leftover} leftover" : "")));
|
||||
lines.Add($"Parsed ({(_logOn ? "log on" : "log off")}): {(kinds.Length > 0 ? kinds : "none yet")}");
|
||||
string top = string.Join(" ", Opcodes.OrderByDescending(o => o.Value).Take(12).Select(o => $"{FormatKey(o.Key)}x{o.Value}"));
|
||||
if (top.Length > 0) lines.Add($"Top opcodes: {top}");
|
||||
}
|
||||
if (_capture != null)
|
||||
lines.Add($"Capturing to {_capturePath} ({_captureBytes / 1024} KB)");
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
private static string FormatKey(uint key) => key >= 0x10000 ? $"F7B0/{key & 0xFFFF:X4}" : $"{key:X4}";
|
||||
|
||||
// ── log tap ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void LogTap(uint opcode, uint eventType, byte* message, int length)
|
||||
{
|
||||
uint key = opcode == ServerMessage.GameEventOpcode ? 0x10000u | (eventType & 0xFFFF) : opcode & 0xFFFF;
|
||||
var msg = new ServerMessage(opcode, new ReadOnlySpan<byte>(message + 4, length - 4));
|
||||
NetMessageInfo info = NetMessages.Inspect(msg);
|
||||
bool interesting = !info.Parsed || info.Leftover != 0;
|
||||
bool log;
|
||||
lock (LogLock)
|
||||
{
|
||||
Opcodes[key] = Opcodes.TryGetValue(key, out long c) ? c + 1 : 1;
|
||||
if (!info.Known)
|
||||
return;
|
||||
if (!Kinds.TryGetValue(info.Kind, out KindStats? k))
|
||||
Kinds[info.Kind] = k = new KindStats();
|
||||
if (info.Parsed) k.Ok++; else k.Failed++;
|
||||
if (info.Parsed && info.Leftover != 0) k.Leftover++;
|
||||
log = _logLines < MaxLogLines && (k.Logged < MaxLogLinesPerKind || interesting);
|
||||
if (log)
|
||||
{
|
||||
_logLines++;
|
||||
k.Logged++;
|
||||
}
|
||||
}
|
||||
if (log)
|
||||
{
|
||||
string hex = interesting ? " bytes=" + Convert.ToHexString(new ReadOnlySpan<byte>(message, Math.Min(length, 96))) : "";
|
||||
RynthLog.Compat($"NetMsg: {info.Kind} len={length} {(info.Parsed ? "ok" : "FAILED")}" +
|
||||
(info.Leftover != 0 ? $" leftover={info.Leftover}" : "") + $" {info.Summary}{hex}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── capture file ────────────────────────────────────────────────────────
|
||||
// Format "RNC1": the 4 magic bytes, then per datagram [u32 stamp ms][u16 length][bytes].
|
||||
|
||||
private static string StartCapture()
|
||||
{
|
||||
if (_capture != null)
|
||||
return $"Already capturing to {_capturePath}.";
|
||||
if (!EngineSettings.ServerMessageStream || _sessionOff)
|
||||
return "The server message stream is off; /rc netmsg on first (engine.json must allow it).";
|
||||
try
|
||||
{
|
||||
LogPaths.EnsureLogDirectory();
|
||||
_capturePath = Path.Combine(LogPaths.LogDirectory, $"netcapture-{Environment.ProcessId}-{DateTime.Now:yyyyMMdd-HHmmss}.rnc");
|
||||
_capture = new FileStream(_capturePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, 64 * 1024);
|
||||
_capture.Write("RNC1"u8);
|
||||
_captureBytes = 4;
|
||||
return $"Capturing server datagrams to {_capturePath} (stops at {MaxCaptureBytes / (1024 * 1024)} MB; holds chat text, keep it local).";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_capture = null;
|
||||
return $"Capture failed: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private static string StopCapture(string why)
|
||||
{
|
||||
if (_capture == null)
|
||||
return "Not capturing.";
|
||||
try { _capture.Dispose(); } catch { }
|
||||
_capture = null;
|
||||
string msg = $"Capture {why}: {_capturePath} ({_captureBytes / 1024} KB).";
|
||||
RynthLog.Compat("ServerMessageStream: " + msg);
|
||||
return msg;
|
||||
}
|
||||
|
||||
private static void WriteCapture(byte* data, int len, uint stamp)
|
||||
{
|
||||
FileStream? f = _capture;
|
||||
if (f == null) return;
|
||||
Span<byte> head = stackalloc byte[6];
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(head, stamp);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(head.Slice(4), (ushort)len);
|
||||
try
|
||||
{
|
||||
f.Write(head);
|
||||
f.Write(new ReadOnlySpan<byte>(data, len));
|
||||
_captureBytes += 6 + len;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StopCapture($"failed ({ex.Message})");
|
||||
return;
|
||||
}
|
||||
if (_captureBytes >= MaxCaptureBytes)
|
||||
StopCapture("reached its size cap");
|
||||
}
|
||||
|
||||
/// <summary>Engine shutdown: close a capture file. The ring stays allocated (see PacketRing).</summary>
|
||||
public static void Shutdown()
|
||||
{
|
||||
_capturing = false;
|
||||
if (_capture != null) StopCapture("closed at shutdown");
|
||||
}
|
||||
}
|
||||
|
|
@ -31,6 +31,9 @@ internal static class EngineSettings
|
|||
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
|
||||
private static bool _decalInGameImGui = true;
|
||||
private static bool _decalStandDown = true;
|
||||
// "DisabledUiHooks": the UI hooks (Compatibility/UiHookRegistry) switched off by name.
|
||||
private static readonly HashSet<string> _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static bool _serverMessageStream = true;
|
||||
private static bool _loaded;
|
||||
|
||||
public static IReadOnlyList<string> PluginPaths
|
||||
|
|
@ -252,6 +255,39 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>"DisabledUiHooks" in engine.json: an array of UI hook names
|
||||
/// (Compatibility/UiHookRegistry: UseNewMode, ClientCleanup, StartTooltip, ResetTooltip,
|
||||
/// CheckTooltip, StartDragandDrop, CatchDroppedItem). A listed hook is not installed at
|
||||
/// the next start. Missing = every hook on. /rc hooks on|off <name> edits it.</summary>
|
||||
public static bool IsUiHookEnabled(string name)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return !_disabledUiHooks.Contains(name);
|
||||
}
|
||||
|
||||
/// <summary>Switches a UI hook on or off for the next start, and saves engine.json.</summary>
|
||||
public static void SetUiHookEnabled(string name, bool enabled)
|
||||
{
|
||||
EnsureLoaded();
|
||||
bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name);
|
||||
if (changed)
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>"ServerMessageStream" in engine.json (default true): the kill switch for the
|
||||
/// reassembled server-message stream (Net/ServerMessageStream.cs, plugin API v78). Even when
|
||||
/// true, nothing is copied off the receive hook until a plugin asks for messages (or
|
||||
/// /rc netmsg log|capture is on). false = the RecvFrom detour does exactly what it did
|
||||
/// before the stream existed; /rc netmsg on can't override it.</summary>
|
||||
public static bool ServerMessageStream
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _serverMessageStream;
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddPluginPath(string path)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
|
@ -374,11 +410,25 @@ internal static class EngineSettings
|
|||
(dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False))
|
||||
_decalStandDown = dsdEl.GetBoolean();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("ServerMessageStream", out var smsEl) &&
|
||||
(smsEl.ValueKind == JsonValueKind.True || smsEl.ValueKind == JsonValueKind.False))
|
||||
_serverMessageStream = smsEl.GetBoolean();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
|
||||
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
|
||||
{
|
||||
_preventIdleLogoff = pilEl.GetBoolean();
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) &&
|
||||
duhEl.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var el in duhEl.EnumerateArray())
|
||||
{
|
||||
if (el.ValueKind == JsonValueKind.String && el.GetString() is { Length: > 0 } hookName)
|
||||
_disabledUiHooks.Add(hookName.Trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -417,6 +467,15 @@ internal static class EngineSettings
|
|||
w.WriteBoolean("DecalInGameImGui", false);
|
||||
if (!_decalStandDown) // default true: leave the file as it was
|
||||
w.WriteBoolean("DecalStandDown", false);
|
||||
if (_disabledUiHooks.Count > 0) // default none: leave the file as it was
|
||||
{
|
||||
w.WriteStartArray("DisabledUiHooks");
|
||||
foreach (string hookName in _disabledUiHooks)
|
||||
w.WriteStringValue(hookName);
|
||||
w.WriteEndArray();
|
||||
}
|
||||
if (!_serverMessageStream) // default true: leave the file as it was
|
||||
w.WriteBoolean("ServerMessageStream", false);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
File.WriteAllBytes(SettingsPath, ms.ToArray());
|
||||
|
|
|
|||
|
|
@ -55,6 +55,21 @@ internal sealed class LoadedPlugin
|
|||
public PluginTickDelegate? Tick { get; set; }
|
||||
public PluginRenderDelegate? Render { get; set; }
|
||||
|
||||
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
|
||||
public bool UiExportsResolved { get; set; }
|
||||
public IntPtr OnScreenChangedPtr { get; set; }
|
||||
public IntPtr OnClientCleanupPtr { get; set; }
|
||||
public IntPtr OnTooltipShowPtr { get; set; }
|
||||
public IntPtr OnTooltipHidePtr { get; set; }
|
||||
public IntPtr OnDragStartPtr { get; set; }
|
||||
public IntPtr OnItemDroppedPtr { get; set; }
|
||||
|
||||
// ─── v78 server messages (resolved when the plugin calls SetServerMessageInterest) ──
|
||||
/// <summary><c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c>, Cdecl.</summary>
|
||||
public IntPtr OnServerMessagePtr { get; set; }
|
||||
/// <summary>What the plugin asked for; null or empty = nothing.</summary>
|
||||
public Net.ServerMessageInterest? ServerMessageInterest { get; set; }
|
||||
|
||||
// ─── Runtime state ───────────────────────────────────────────────
|
||||
public bool Initialized { get; set; }
|
||||
public bool LoginCompleteDispatched { get; set; }
|
||||
|
|
@ -62,4 +77,12 @@ internal sealed class LoadedPlugin
|
|||
public bool Failed { get; set; }
|
||||
public string DisplayName { get; set; } = "";
|
||||
public string VersionString { get; set; } = "";
|
||||
|
||||
/// <summary>
|
||||
/// The manifest embedded in the DLL (read before loading it; see PluginManifestGate), or null
|
||||
/// for a plugin without one. Set by PluginManager after PluginLoader loads the plugin.
|
||||
/// </summary>
|
||||
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
|
||||
/// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary>
|
||||
public string NotStartedReason { get; set; } = "";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,9 @@
|
|||
// const char* RynthPluginVersion() — version string (e.g. "1.0.0")
|
||||
// void RynthPluginTick() — per-frame logic (before render)
|
||||
// void RynthPluginRender() — per-frame ImGui drawing
|
||||
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
|
||||
// — v78, reassembled server messages the plugin
|
||||
// asked for with SetServerMessageInterestFn
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -780,6 +783,156 @@ internal struct RynthCoreAPI
|
|||
/// AC's main thread (queued in the action ring from other threads, ahead of anything queued
|
||||
/// after it). Returns 1 if sent or queued. Requires API v76+.</summary>
|
||||
public IntPtr CloseContainerFn;
|
||||
|
||||
/// <summary>v77: <c>int GetScreenMode(int* previousMode)</c>: the client's screen (UIFlow mode,
|
||||
/// Compatibility/UiFlowHooks.cs): 0x10000001 intro, 0x10000002 disconnected, 0x10000008 the
|
||||
/// world, 0x10000009 epilogue, 0x1000000A character select, 0x1000000B character creation;
|
||||
/// 0 = not known yet. *previousMode (may be null) = the screen before. Any thread.
|
||||
/// Requires API v77+.</summary>
|
||||
public IntPtr GetScreenModeFn;
|
||||
|
||||
/// <summary>v77: <c>uint GetUiHookFlags(void)</c>: which UI hooks are live, so a plugin knows
|
||||
/// which v77 callbacks can arrive. bit0 RynthPluginOnScreenChanged from the UseNewMode hook,
|
||||
/// bit1 ... from the +0x8C mode poll instead (one tick late), bit2 RynthPluginOnClientCleanup,
|
||||
/// bit3 RynthPluginOnTooltipShow, bit4 RynthPluginOnTooltipHide, bit5 RynthPluginOnDragStart,
|
||||
/// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started. Any thread.
|
||||
/// Requires API v77+.</summary>
|
||||
public IntPtr GetUiHookFlagsFn;
|
||||
|
||||
/// <summary>v78: <c>int SetServerMessageInterest(uint* opcodes, int opcodeCount, uint* gameEvents,
|
||||
/// int eventCount)</c>: which reassembled server messages the calling plugin wants on its
|
||||
/// <c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
|
||||
/// data = the message after its u32 opcode, valid only during the call; for 0xF7B0 it starts
|
||||
/// with object id, sequence, event type). Replaces the plugin's previous set; both counts 0 =
|
||||
/// none. Opcodes are 16-bit; 0xF7B0 = every game event, 0xFFFFFFFF = every message;
|
||||
/// gameEvents lists single event types. Read-only: the client's packets are never changed.
|
||||
/// Call from the plugin's Init, Tick or an event (the engine finds the caller that way).
|
||||
/// Returns 1 = streaming, 2 = accepted but the stream is off (engine.json
|
||||
/// "ServerMessageStream": false or /rc netmsg off), 0 = the plugin has no
|
||||
/// RynthPluginOnServerMessage export, -1 = caller unknown (another thread), -3 = bad
|
||||
/// arguments. Requires API v78+.</summary>
|
||||
public IntPtr SetServerMessageInterestFn;
|
||||
|
||||
/// <summary>v79: <c>int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries,
|
||||
/// int maxEntries)</c>: what spending experience would do (Compatibility/TrainingApi.cs): the
|
||||
/// unassigned XP, skill credits and level, and one entry per attribute (1..6), vital maximum
|
||||
/// (1 health, 3 stamina, 5 mana) and portal-SkillTable skill with ranks, XP spent, base and
|
||||
/// buffed value and the XP for +1 / +10 from the portal XpTable. Set info->Size to sizeof
|
||||
/// before the call (info may be null; entries may be null to ask for the count). Returns the
|
||||
/// number of entries there are (at most maxEntries written), 0 when there are no numbers yet
|
||||
/// (not in the world, or the first read hasn't happened: it is asked for by this call and
|
||||
/// comes within a couple of seconds). Asking keeps the numbers coming every 2 s for 5 s.
|
||||
/// Any thread. Requires API v79+.</summary>
|
||||
public IntPtr GetTrainingInfoFn;
|
||||
|
||||
/// <summary>v79: <c>int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)</c>:
|
||||
/// spend unassigned XP like the character window's "+": kind 1 attribute (stype 1..6), 2 vital
|
||||
/// (1 health, 3 stamina, 5 mana), 3 trained or specialized skill; ranks 1..100. The engine works
|
||||
/// the XP out from the numbers GetTrainingInfo reports and sends it with the client's own
|
||||
/// CM_Train sender (0x0045 / 0x0044 / 0x0046) on AC's main thread. expectedXp > 0 must equal
|
||||
/// that XP (the cost the user confirmed), else nothing is sent; 0 skips the comparison.
|
||||
/// *xpSent (may be null) = the XP sent. Returns 1 sent or queued, 0 the senders aren't bound,
|
||||
/// -1 not in the world, -2 bad arguments, -3 no numbers yet, -4 the numbers are over 3 s old
|
||||
/// (a read was asked for: call again shortly), -5 the cost changed, -6 not enough XP, -7 not
|
||||
/// raisable (top rank, untrained skill), -8 an earlier raise hasn't landed yet, -9 the send
|
||||
/// failed. Any thread. Requires API v79+.</summary>
|
||||
public IntPtr RaiseFn;
|
||||
|
||||
/// <summary>v79: <c>int TrainSkill(uint stype, int expectedCredits)</c>: train an untrained
|
||||
/// skill with skill credits, as the skills window's train dialog does (0x0047, exactly the
|
||||
/// portal SkillTable's TrainedCost; the server refuses anything else). expectedCredits > 0
|
||||
/// must equal that price; 0 skips the comparison. Same results and threading as Raise.
|
||||
/// Requires API v79+.</summary>
|
||||
public IntPtr TrainSkillFn;
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
|
||||
internal static class TrainingInfoFlags
|
||||
{
|
||||
public const uint InWorld = 1u << 0;
|
||||
/// <summary>The attribute, vital and skill raise senders are bound on this client.</summary>
|
||||
public const uint RaiseBound = 1u << 1;
|
||||
/// <summary>The train-with-credits sender is bound.</summary>
|
||||
public const uint TrainBound = 1u << 2;
|
||||
/// <summary>The player's numbers have been read (entries follow).</summary>
|
||||
public const uint HaveNumbers = 1u << 3;
|
||||
/// <summary>The portal SkillTable and XpTable are loaded.</summary>
|
||||
public const uint HaveTables = 1u << 4;
|
||||
/// <summary>A raise or train from the API hasn't shown up in the numbers yet.</summary>
|
||||
public const uint Busy = 1u << 5;
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingEntryNative.Flags"/> bits.</summary>
|
||||
internal static class TrainingEntryFlags
|
||||
{
|
||||
/// <summary>Can be raised with XP (an attribute, a vital, a trained or specialized skill below the top rank).</summary>
|
||||
public const uint Raisable = 1u << 0;
|
||||
public const uint AtTop = 1u << 1;
|
||||
/// <summary>Skills: usable untrained (the SkillTable's min level 1).</summary>
|
||||
public const uint UsableUntrained = 1u << 2;
|
||||
/// <summary>Skills: untrained, and the SkillTable prices training it (TrainCredits).</summary>
|
||||
public const uint Trainable = 1u << 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 <c>GetTrainingInfo</c> header. Pack 4, 64 bytes; later versions only append.
|
||||
/// Mirrored by RynthCore.PluginSdk (TrainingInfoNative in RynthCoreApiNative.cs).
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct TrainingInfoNative
|
||||
{
|
||||
/// <summary>In: the caller's sizeof. Out: bytes written.</summary>
|
||||
public uint Size;
|
||||
/// <summary><see cref="TrainingInfoFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>Changes whenever any number changes.</summary>
|
||||
public uint SnapshotVersion;
|
||||
/// <summary>Milliseconds since the numbers were read; 0xFFFFFFFF = never.</summary>
|
||||
public uint AgeMs;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long UnassignedXp;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long TotalXp;
|
||||
public int Level;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public int SkillCredits;
|
||||
public int EntryCount;
|
||||
/// <summary>Raise refuses numbers older than this (Stale).</summary>
|
||||
public int StaleAfterMs;
|
||||
public fixed uint Reserved[4];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 <c>GetTrainingInfo</c> entry: one attribute, vital or skill. Pack 4, 64 bytes; later
|
||||
/// versions only append. Mirrored by RynthCore.PluginSdk (TrainingEntryNative).
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal struct TrainingEntryNative
|
||||
{
|
||||
/// <summary>1 attribute, 2 vital, 3 skill.</summary>
|
||||
public uint Kind;
|
||||
/// <summary>Attribute 1..6, vital maximum 1 / 3 / 5, skill id.</summary>
|
||||
public uint Stype;
|
||||
/// <summary>Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise.</summary>
|
||||
public uint Class;
|
||||
public uint Ranks;
|
||||
public uint XpSpent;
|
||||
/// <summary>The innate (starting) level.</summary>
|
||||
public uint Innate;
|
||||
/// <summary>Without enchantments (a vital's maximum).</summary>
|
||||
public int Base;
|
||||
public int Buffed;
|
||||
/// <summary>XP for one more rank; -1 at the top or not raisable.</summary>
|
||||
public long CostOne;
|
||||
/// <summary>XP for ten more ranks; -1 when fewer than ten are left or not raisable.</summary>
|
||||
public long CostTen;
|
||||
public int RanksLeft;
|
||||
/// <summary>Ranks in a row the unassigned XP buys now.</summary>
|
||||
public int Affordable;
|
||||
/// <summary>Untrained skills: the credits to train it (0 = can't be trained from the client).</summary>
|
||||
public int TrainCredits;
|
||||
/// <summary><see cref="TrainingEntryFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
}
|
||||
|
||||
/// <summary>v72 <see cref="TradeStateNative.Flags"/> bits.</summary>
|
||||
|
|
@ -964,11 +1117,8 @@ internal unsafe struct VendorTradeStatusNative
|
|||
|
||||
|
||||
|
||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
||||
internal static class PluginContractVersion
|
||||
{
|
||||
public const uint Current = 76;
|
||||
}
|
||||
// PluginContractVersion (the current API version) lives in PluginContractVersion.cs, which
|
||||
// the SDK and the launcher compile in too, so their copies can't drift from the engine's.
|
||||
|
||||
internal static class ClientActionHookFlags
|
||||
{
|
||||
|
|
@ -1077,6 +1227,17 @@ internal delegate void PluginTickDelegate();
|
|||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void PluginRenderDelegate();
|
||||
|
||||
// v77 callbacks (exports resolved by PluginManager.ResolveUiExports, not PluginLoader):
|
||||
// void RynthPluginOnScreenChanged(int oldMode, int newMode) - UIFlow mode change (GetScreenModeFn values)
|
||||
// void RynthPluginOnClientCleanup(void) - Client::Cleanup starting; no ticks after it
|
||||
// void RynthPluginOnTooltipShow(uint objectId, uint spellId) - AC shows a tooltip (0/0: not an item or spell)
|
||||
// void RynthPluginOnTooltipHide(void) - that tooltip is gone
|
||||
// void RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId) - a drag out of AC's UI began
|
||||
// void RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId) - AC caught a drop
|
||||
// All cdecl, all on the plugin pump like the other events, except OnClientCleanup (see
|
||||
// PluginManager.DispatchClientCleanup).
|
||||
|
||||
|
||||
// ─── Log callback that plugins can call ─────────────────────────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
|
|
@ -1485,3 +1646,21 @@ internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int
|
|||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int CloseContainerCallbackDelegate(uint containerId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetScreenModeCallbackDelegate(int* previousMode);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate uint GetUiHookFlagsCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int SetServerMessageInterestCallbackDelegate(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetTrainingInfoCallbackDelegate(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits);
|
||||
|
|
|
|||
19
src/RynthCore.Engine/Plugins/PluginContractVersion.cs
Normal file
19
src/RynthCore.Engine/Plugins/PluginContractVersion.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/PluginContractVersion.cs
|
||||
// The plugin API's version: the number of the last table (RynthCoreAPI) layout.
|
||||
//
|
||||
// One file, compiled into three assemblies so they can't disagree:
|
||||
// - the engine (this folder), which hands it to plugins in RynthCoreAPI.Version;
|
||||
// - the SDK (RynthCore.PluginSdk), as RynthCoreHost.CurrentApiVersion;
|
||||
// - the launcher (RynthCore.App.Avalonia), as the API of the engine it installed,
|
||||
// to hold back feed plugins whose minEngineApi is newer.
|
||||
// tools\PluginManifestTests also checks the SDK's table covers this version.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
|
||||
internal static class PluginContractVersion
|
||||
{
|
||||
public const uint Current = 79;
|
||||
}
|
||||
282
src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs
Normal file
282
src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/PluginManager.UiHooks.cs
|
||||
//
|
||||
// API v77 (2026-10-05): the plugin side of Compatibility/UiFlowHooks and
|
||||
// Compatibility/UiElementHooks.
|
||||
//
|
||||
// Callbacks (optional plugin exports, cdecl; looked up here on first use, not by
|
||||
// PluginLoader):
|
||||
// RynthPluginOnScreenChanged(int oldMode, int newMode)
|
||||
// RynthPluginOnClientCleanup()
|
||||
// RynthPluginOnTooltipShow(uint objectId, uint spellId)
|
||||
// RynthPluginOnTooltipHide()
|
||||
// RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId)
|
||||
// RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId)
|
||||
// The hooks queue them from AC's main thread; ProcessPendingActions delivers them
|
||||
// on the plugin pump in the order they happened (one queue), like every other
|
||||
// event. OnClientCleanup is the exception: it must arrive while AC's UI still
|
||||
// stands, so the Client::Cleanup detour (AC's main thread) waits, bounded, for the
|
||||
// pump to deliver it, and delivers it itself (under the pump's frame guard) if the
|
||||
// pump doesn't come. After it the pump delivers no more events and TickAll stops
|
||||
// ticking. Plugins: keep OnClientCleanup short and never wait on AC's main thread
|
||||
// inside it (it may be running on it, or waiting for you).
|
||||
//
|
||||
// Table functions: GetScreenModeFn, GetUiHookFlagsFn (PluginContract.cs).
|
||||
// Older engines have neither the table fields nor the callbacks: a plugin checks
|
||||
// RynthCoreAPI.Version >= 77 before reading the fields (RynthCoreHost.HasUiHooks).
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
internal static partial class PluginManager
|
||||
{
|
||||
private static GetScreenModeCallbackDelegate? _getScreenModeCallback; // v77
|
||||
private static GetUiHookFlagsCallbackDelegate? _getUiHookFlagsCallback; // v77
|
||||
|
||||
/// <summary>The thread that ran TickAll last (the plugin pump).</summary>
|
||||
private static int _tickThread;
|
||||
|
||||
private enum UiEventKind : byte { ScreenChanged, TooltipShow, TooltipHide, DragStart, ItemDropped }
|
||||
private readonly record struct PendingUiEvent(UiEventKind Kind, uint A, uint B, uint C);
|
||||
|
||||
private const int MaxPendingUiEvents = 256;
|
||||
private static readonly Queue<PendingUiEvent> _pendingUiEvents = new();
|
||||
private static readonly object PendingUiEventsLock = new();
|
||||
|
||||
// Client::Cleanup: 0 nothing, 1 waiting for the pump, 2 delivered (or nobody to tell).
|
||||
private static int _cleanupState;
|
||||
|
||||
// ── Queueing (AC's main thread) ──────────────────────────────────────
|
||||
|
||||
public static void QueueScreenChanged(int oldMode, int newMode) => QueueUiEvent(UiEventKind.ScreenChanged, (uint)oldMode, (uint)newMode, 0);
|
||||
public static void QueueTooltipShown(uint objectId, uint spellId) => QueueUiEvent(UiEventKind.TooltipShow, objectId, spellId, 0);
|
||||
public static void QueueTooltipHidden() => QueueUiEvent(UiEventKind.TooltipHide, 0, 0, 0);
|
||||
public static void QueueDragStarted(uint objectId, uint spellId, uint iconId) => QueueUiEvent(UiEventKind.DragStart, objectId, spellId, iconId);
|
||||
public static void QueueItemDropped(uint objectId, uint spellId, uint targetElementId) => QueueUiEvent(UiEventKind.ItemDropped, objectId, spellId, targetElementId);
|
||||
|
||||
private static void QueueUiEvent(UiEventKind kind, uint a, uint b, uint c)
|
||||
{
|
||||
if (!_initialized || _plugins.Count == 0 || Volatile.Read(ref _cleanupState) != 0)
|
||||
return;
|
||||
lock (PendingUiEventsLock)
|
||||
{
|
||||
if (_pendingUiEvents.Count >= MaxPendingUiEvents)
|
||||
_pendingUiEvents.Dequeue();
|
||||
_pendingUiEvents.Enqueue(new PendingUiEvent(kind, a, b, c));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Delivery (plugin pump) ───────────────────────────────────────────
|
||||
|
||||
private static void ResolveUiExports(LoadedPlugin plugin)
|
||||
{
|
||||
if (plugin.UiExportsResolved || plugin.ModuleHandle == IntPtr.Zero)
|
||||
return;
|
||||
plugin.UiExportsResolved = true;
|
||||
plugin.OnScreenChangedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnScreenChanged");
|
||||
plugin.OnClientCleanupPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnClientCleanup");
|
||||
plugin.OnTooltipShowPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipShow");
|
||||
plugin.OnTooltipHidePtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipHide");
|
||||
plugin.OnDragStartPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnDragStart");
|
||||
plugin.OnItemDroppedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnItemDropped");
|
||||
int count = (plugin.OnScreenChangedPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnClientCleanupPtr != IntPtr.Zero ? 1 : 0)
|
||||
+ (plugin.OnTooltipShowPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnTooltipHidePtr != IntPtr.Zero ? 1 : 0)
|
||||
+ (plugin.OnDragStartPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnItemDroppedPtr != IntPtr.Zero ? 1 : 0);
|
||||
if (count > 0)
|
||||
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} takes {count} v77 UI callback(s).");
|
||||
}
|
||||
|
||||
private static unsafe void DispatchQueuedUiEvents()
|
||||
{
|
||||
if (!_initialized || _plugins.Count == 0)
|
||||
return;
|
||||
|
||||
PendingUiEvent[] pending;
|
||||
lock (PendingUiEventsLock)
|
||||
{
|
||||
if (_pendingUiEvents.Count == 0)
|
||||
return;
|
||||
pending = _pendingUiEvents.ToArray();
|
||||
_pendingUiEvents.Clear();
|
||||
}
|
||||
|
||||
foreach (PendingUiEvent evt in pending)
|
||||
{
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
var plugin = _plugins[i];
|
||||
if (!plugin.Initialized || plugin.Failed)
|
||||
continue;
|
||||
ResolveUiExports(plugin);
|
||||
IntPtr fn = evt.Kind switch
|
||||
{
|
||||
UiEventKind.ScreenChanged => plugin.OnScreenChangedPtr,
|
||||
UiEventKind.TooltipShow => plugin.OnTooltipShowPtr,
|
||||
UiEventKind.TooltipHide => plugin.OnTooltipHidePtr,
|
||||
UiEventKind.DragStart => plugin.OnDragStartPtr,
|
||||
_ => plugin.OnItemDroppedPtr,
|
||||
};
|
||||
if (fn == IntPtr.Zero)
|
||||
continue;
|
||||
|
||||
LoadedPlugin? outer = EnterDispatch(plugin);
|
||||
try
|
||||
{
|
||||
switch (evt.Kind)
|
||||
{
|
||||
case UiEventKind.ScreenChanged:
|
||||
((delegate* unmanaged[Cdecl]<int, int, void>)fn)((int)evt.A, (int)evt.B);
|
||||
break;
|
||||
case UiEventKind.TooltipShow:
|
||||
((delegate* unmanaged[Cdecl]<uint, uint, void>)fn)(evt.A, evt.B);
|
||||
break;
|
||||
case UiEventKind.TooltipHide:
|
||||
((delegate* unmanaged[Cdecl]<void>)fn)();
|
||||
break;
|
||||
case UiEventKind.DragStart:
|
||||
case UiEventKind.ItemDropped:
|
||||
((delegate* unmanaged[Cdecl]<uint, uint, uint, void>)fn)(evt.A, evt.B, evt.C);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
plugin.Failed = true;
|
||||
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} On{evt.Kind} threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
LeaveDispatch(outer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Client::Cleanup ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// AC's main thread, inside the Client::Cleanup detour before AC tears anything down.
|
||||
/// Plugins are called from the plugin pump (a managed thread: a NativeAOT engine must not
|
||||
/// run plugin code on AC's threads, the 2026-05-16 fail-fast), never from two threads at
|
||||
/// once. So: the pump delivers RynthPluginOnClientCleanup at the top of its next frame
|
||||
/// (ProcessClientCleanup, every ~16 ms) while this waits for up to half of
|
||||
/// <paramref name="timeoutMs"/>. A pump that doesn't come (no frames: the device is
|
||||
/// gone) leaves it to this thread, which delivers it holding the pump's frame guard
|
||||
/// (EngineFrameController.TryRunOutsidePumpFrame). Exactly once either way; after the
|
||||
/// full timeout AC's cleanup goes ahead regardless.
|
||||
/// </summary>
|
||||
public static void DispatchClientCleanup(int timeoutMs)
|
||||
{
|
||||
if (!_initialized || _plugins.Count == 0)
|
||||
{
|
||||
Volatile.Write(ref _cleanupState, 2);
|
||||
return;
|
||||
}
|
||||
if (Interlocked.CompareExchange(ref _cleanupState, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
int pump = Volatile.Read(ref _tickThread);
|
||||
if (pump == 0 || pump == Environment.CurrentManagedThreadId)
|
||||
{
|
||||
TakeAndDeliverClientCleanup("the calling thread (no separate pump)");
|
||||
return;
|
||||
}
|
||||
|
||||
long start = Environment.TickCount64;
|
||||
long pumpUntil = start + timeoutMs / 2, until = start + timeoutMs;
|
||||
while (Volatile.Read(ref _cleanupState) != 2)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (now >= pumpUntil
|
||||
&& ImGuiBackend.EngineFrameController.TryRunOutsidePumpFrame(() => TakeAndDeliverClientCleanup("AC's main thread (the pump didn't come)")))
|
||||
return;
|
||||
if (now >= until)
|
||||
{
|
||||
RynthLog.Plugin($"PluginManager: OnClientCleanup not delivered within {timeoutMs} ms (a pump frame is running); AC's cleanup goes ahead, the pump delivers it at its next frame.");
|
||||
return;
|
||||
}
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plugin pump, top of ProcessPendingActions. True once Client::Cleanup started: the
|
||||
/// rest of the frame's events are dropped (AC is tearing down what they describe).
|
||||
/// </summary>
|
||||
private static bool ProcessClientCleanup()
|
||||
{
|
||||
if (Volatile.Read(ref _cleanupState) == 0)
|
||||
return UiFlowHooks.ClientCleanupStarted;
|
||||
TakeAndDeliverClientCleanup("the plugin pump");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1 -> 2 exactly once, whoever gets there first.
|
||||
private static void TakeAndDeliverClientCleanup(string where)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _cleanupState, 2, 1) != 1)
|
||||
return;
|
||||
DeliverClientCleanup(where);
|
||||
}
|
||||
|
||||
private static unsafe void DeliverClientCleanup(string where)
|
||||
{
|
||||
lock (PendingUiEventsLock)
|
||||
_pendingUiEvents.Clear();
|
||||
int told = 0;
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
var plugin = _plugins[i];
|
||||
if (!plugin.Initialized || plugin.Failed)
|
||||
continue;
|
||||
ResolveUiExports(plugin);
|
||||
if (plugin.OnClientCleanupPtr == IntPtr.Zero)
|
||||
continue;
|
||||
LoadedPlugin? outer = EnterDispatch(plugin);
|
||||
try
|
||||
{
|
||||
((delegate* unmanaged[Cdecl]<void>)plugin.OnClientCleanupPtr)();
|
||||
told++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
plugin.Failed = true;
|
||||
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnClientCleanup threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
LeaveDispatch(outer);
|
||||
}
|
||||
}
|
||||
RynthLog.Plugin($"PluginManager: OnClientCleanup delivered to {told} plugin(s) from {where}; no more plugin ticks or events.");
|
||||
}
|
||||
|
||||
// ── Table functions ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>v77: see PluginContract.GetScreenModeFn.</summary>
|
||||
private static unsafe int GetScreenModeAction(int* previousMode)
|
||||
{
|
||||
if (previousMode != null)
|
||||
*previousMode = UiFlowHooks.PreviousMode;
|
||||
return UiFlowHooks.CurrentMode;
|
||||
}
|
||||
|
||||
/// <summary>v77: see PluginContract.GetUiHookFlagsFn.</summary>
|
||||
private static uint GetUiHookFlagsAction()
|
||||
{
|
||||
uint flags = 0;
|
||||
if (UiFlowHooks.ScreenHookLive) flags |= 1u << 0;
|
||||
else flags |= 1u << 1; // the +0x8C poll drives OnScreenChanged
|
||||
if (UiFlowHooks.CleanupHookLive) flags |= 1u << 2;
|
||||
if (UiElementHooks.TooltipShowLive) flags |= 1u << 3;
|
||||
if (UiElementHooks.TooltipHideLive) flags |= 1u << 4;
|
||||
if (UiElementHooks.DragStartLive) flags |= 1u << 5;
|
||||
if (UiElementHooks.DropLive) flags |= 1u << 6;
|
||||
if (UiFlowHooks.ClientCleanupStarted) flags |= 1u << 7;
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
|
|
@ -12,10 +12,11 @@ using System.Threading;
|
|||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.PluginSdk.Manifest;
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
internal static class PluginManager
|
||||
internal static partial class PluginManager
|
||||
{
|
||||
// Held: set when AC hasn't printed the line yet (ChatCallbackHooks holds it until the
|
||||
// plugins' verdict is in; see IncomingChatHold.cs). Null for lines AC already printed.
|
||||
|
|
@ -259,6 +260,10 @@ internal static class PluginManager
|
|||
private static GetCharacterTitlesCallbackDelegate? _getCharacterTitlesCallback; // v75
|
||||
private static GetServerInfoCallbackDelegate? _getServerInfoCallback; // v75
|
||||
private static CloseContainerCallbackDelegate? _closeContainerCallback; // v76
|
||||
private static SetServerMessageInterestCallbackDelegate? _setServerMessageInterestCallback; // v78
|
||||
private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79
|
||||
private static RaiseCallbackDelegate? _raiseCallback; // v79
|
||||
private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79
|
||||
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
|
||||
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
|
||||
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
|
||||
|
|
@ -521,6 +526,10 @@ internal static class PluginManager
|
|||
|
||||
public static void ProcessPendingActions(IntPtr imguiContext, IntPtr d3dDevice, IntPtr gameHwnd)
|
||||
{
|
||||
// v77: Client::Cleanup started (UiFlowHooks): tell the plugins once, then no more events.
|
||||
if (ProcessClientCleanup())
|
||||
return;
|
||||
|
||||
UiLifecycleHooks.Poll();
|
||||
LoginLifecycleHooks.Poll();
|
||||
SessionStateRegistry.Poll();
|
||||
|
|
@ -539,6 +548,11 @@ internal static class PluginManager
|
|||
// • View BEFORE Stop — a container open-then-close in one frame must
|
||||
// end "closed"; draining Stop-then-View left the plugin believing the
|
||||
// container was still open.
|
||||
// v78 server messages first: the wire comes before the client's handling of it,
|
||||
// which is what the queued events below report. Cheap when nobody asked for any.
|
||||
try { Net.ServerMessageStream.Pump(_initialized && ServerMessageSubscriberCount() > 0); }
|
||||
catch (Exception ex) { RynthLog.Compat($"PluginManager: server message pump failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
DispatchQueuedBusyCountIncremented();
|
||||
DispatchQueuedBusyCountDecremented();
|
||||
DispatchQueuedCombatModeChange();
|
||||
|
|
@ -558,6 +572,7 @@ internal static class PluginManager
|
|||
DispatchQueuedEnchantmentAdded();
|
||||
DispatchQueuedEnchantmentRemoved();
|
||||
DispatchQueuedChatWindowText();
|
||||
DispatchQueuedUiEvents(); // v77 screen / tooltip / drag / drop (PluginManager.UiHooks.cs)
|
||||
|
||||
if (_rescanRequested)
|
||||
{
|
||||
|
|
@ -1004,6 +1019,10 @@ internal static class PluginManager
|
|||
public static void TickAll()
|
||||
{
|
||||
TickCount++;
|
||||
Volatile.Write(ref _tickThread, Environment.CurrentManagedThreadId);
|
||||
// v77: after Client::Cleanup no plugin ticks (AC is tearing its UI down); Shutdown still comes.
|
||||
if (UiFlowHooks.ClientCleanupStarted)
|
||||
return;
|
||||
|
||||
// Fire the delayed login self-identify once AC's vitals UI has settled
|
||||
// (armed in DispatchLoginCompleteToLoadedPlugins; deferred past the
|
||||
|
|
@ -1219,6 +1238,35 @@ internal static class PluginManager
|
|||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional
|
||||
/// <c>const char* RynthPluginReloadBlocker(void)</c> export whether a hot reload now would
|
||||
/// hurt. Null or "" = safe; a plugin without the export never objects. Fixed signature, so no
|
||||
/// mismatch can reach the stack; the plugin owns the buffer and it is copied at once. Called
|
||||
/// on the loader's reload thread before the engine tears down, while every plugin is loaded.
|
||||
/// </summary>
|
||||
internal static unsafe IReadOnlyList<(string Plugin, string Reason)> QueryReloadBlockers()
|
||||
{
|
||||
var result = new List<(string, string)>();
|
||||
LoadedPlugin[] plugins;
|
||||
try { plugins = _plugins.ToArray(); }
|
||||
catch { return result; } // the list changed under us (a plugin loading): don't hold the reload on it
|
||||
foreach (var p in plugins)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) continue;
|
||||
IntPtr fn = GetProcAddress(p.ModuleHandle, "RynthPluginReloadBlocker");
|
||||
if (fn == IntPtr.Zero) continue;
|
||||
IntPtr text = ((delegate* unmanaged[Cdecl]<IntPtr>)fn)();
|
||||
string? reason = text != IntPtr.Zero ? Marshal.PtrToStringAnsi(text) : null;
|
||||
if (!string.IsNullOrWhiteSpace(reason)) result.Add((p.DisplayName, reason.Trim()));
|
||||
}
|
||||
catch { /* a plugin that can't answer doesn't hold the reload */ }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void LogFromPlugin(IntPtr messageUtf8)
|
||||
{
|
||||
string? msg = Marshal.PtrToStringAnsi(messageUtf8);
|
||||
|
|
@ -2286,6 +2334,7 @@ internal static class PluginManager
|
|||
// bundled Plugins\ folder — that historically caused stray DLLs to
|
||||
// load on next start (or after hot-reload) without the user knowing.
|
||||
var extraPaths = EngineSettings.PluginPaths;
|
||||
var candidates = new List<string>(extraPaths.Count);
|
||||
for (int i = 0; i < extraPaths.Count; i++)
|
||||
{
|
||||
string dllPath = extraPaths[i];
|
||||
|
|
@ -2308,21 +2357,109 @@ internal static class PluginManager
|
|||
break;
|
||||
}
|
||||
}
|
||||
for (int j = 0; j < candidates.Count && !alreadyLoaded; j++)
|
||||
{
|
||||
if (string.Equals(Path.GetFileName(candidates[j]), extraFileName, StringComparison.OrdinalIgnoreCase))
|
||||
alreadyLoaded = true;
|
||||
}
|
||||
if (alreadyLoaded)
|
||||
{
|
||||
RynthLog.Plugin($"PluginManager: Extra plugin {extraFileName} already loaded from default directory — skipping.");
|
||||
continue;
|
||||
}
|
||||
candidates.Add(dllPath);
|
||||
}
|
||||
|
||||
// Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs
|
||||
// a newer engine API or a missing plugin, and put required plugins first. Without
|
||||
// manifests the list loads exactly as before.
|
||||
PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion);
|
||||
foreach (string line in plan.Log)
|
||||
RynthLog.Plugin($"PluginManager: {line}");
|
||||
foreach (PluginRefusal refusal in plan.Refused)
|
||||
RefusePlugin(Path.GetFileName(refusal.Plugin.Key), refusal.Reason);
|
||||
|
||||
foreach ((string dllPath, RynthPluginManifest? manifest) in plan.Load)
|
||||
{
|
||||
// A required plugin that failed to load (PluginLoader said no) takes its dependents with it.
|
||||
string? missing = PluginManifestGate.CheckRequiredStarted(manifest, name => FindPlugin(name) != null ? true : null);
|
||||
if (missing != null)
|
||||
{
|
||||
RefusePlugin(Path.GetFileName(dllPath), missing);
|
||||
continue;
|
||||
}
|
||||
|
||||
RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath}");
|
||||
var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration);
|
||||
if (plugin != null)
|
||||
{
|
||||
plugin.Manifest = manifest;
|
||||
if (manifest != null && !string.Equals(manifest.Name, plugin.DisplayName, StringComparison.OrdinalIgnoreCase))
|
||||
RynthLog.Plugin($"PluginManager: {plugin.FileName}: manifest name '{manifest.Name}' differs from RynthPluginName '{plugin.DisplayName}'; dependencies use the manifest's.");
|
||||
_plugins.Add(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
PublishPluginsRenderSnapshot();
|
||||
}
|
||||
|
||||
// ── Plugin manifests ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Refusals not yet said in chat; said once each, at login (see AnnouncePluginRefusals).</summary>
|
||||
private static readonly List<string> _pendingRefusalNotices = new();
|
||||
private static readonly HashSet<string> _announcedRefusals = new(StringComparer.Ordinal);
|
||||
|
||||
private static void RefusePlugin(string fileName, string reason)
|
||||
{
|
||||
RynthLog.Plugin($"PluginManager: NOT starting {fileName}: {reason} (this RynthCore is plugin API {PluginContractVersion.Current}).");
|
||||
lock (_pendingRefusalNotices)
|
||||
{
|
||||
if (!_announcedRefusals.Contains(reason) && !_pendingRefusalNotices.Contains(reason))
|
||||
_pendingRefusalNotices.Add(reason);
|
||||
}
|
||||
if (_loginCompleteObserved)
|
||||
AnnouncePluginRefusals();
|
||||
}
|
||||
|
||||
/// <summary>Says each refusal once in chat ("[RynthCore] RynthOracle needs a newer RynthCore (API 77) - not started."). Pump thread.</summary>
|
||||
private static void AnnouncePluginRefusals()
|
||||
{
|
||||
List<string> lines;
|
||||
lock (_pendingRefusalNotices)
|
||||
{
|
||||
if (_pendingRefusalNotices.Count == 0) return;
|
||||
lines = new List<string>(_pendingRefusalNotices);
|
||||
_pendingRefusalNotices.Clear();
|
||||
foreach (string l in lines) _announcedRefusals.Add(l);
|
||||
}
|
||||
foreach (string line in lines)
|
||||
AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {line} - not started.", 1);
|
||||
}
|
||||
|
||||
/// <summary>The loaded plugin going by <paramref name="name"/>: manifest name, else its file's name, else RynthPluginName.</summary>
|
||||
private static LoadedPlugin? FindPlugin(string name)
|
||||
{
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
LoadedPlugin p = _plugins[i];
|
||||
if (p.Manifest != null && string.Equals(p.Manifest.Name, name, StringComparison.OrdinalIgnoreCase)) return p;
|
||||
}
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
LoadedPlugin p = _plugins[i];
|
||||
if (string.Equals(RynthPluginManifest.NameFromFile(p.SourceFilePath), name, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(p.DisplayName, name, StringComparison.OrdinalIgnoreCase))
|
||||
return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string RawFileVersion(string path)
|
||||
{
|
||||
try { return System.Diagnostics.FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; }
|
||||
catch { return ""; }
|
||||
}
|
||||
|
||||
private static void InitializeLoadedPlugins()
|
||||
{
|
||||
if (_plugins.Count == 0)
|
||||
|
|
@ -2337,6 +2474,20 @@ internal static class PluginManager
|
|||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
var plugin = _plugins[i];
|
||||
|
||||
// Manifest: a plugin whose required plugin didn't start isn't started either (they
|
||||
// come first: LoadPluginsFromDisk ordered them). No manifest, no check.
|
||||
string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name =>
|
||||
FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null);
|
||||
if (blocked != null)
|
||||
{
|
||||
plugin.Failed = true;
|
||||
plugin.NotStartedReason = blocked;
|
||||
RefusePlugin(plugin.FileName, blocked);
|
||||
continue;
|
||||
}
|
||||
plugin.NotStartedReason = "";
|
||||
|
||||
LoadedPlugin? outer = EnterDispatch(plugin);
|
||||
try
|
||||
{
|
||||
|
|
@ -2451,6 +2602,7 @@ internal static class PluginManager
|
|||
return;
|
||||
|
||||
_loginDispatchPending = false;
|
||||
AnnouncePluginRefusals(); // plugins the manifests kept out, once each, now that chat is up
|
||||
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
|
|
@ -2633,6 +2785,12 @@ internal static class PluginManager
|
|||
unsafe { _getCharacterTitlesCallback ??= GetCharacterTitlesAction; }
|
||||
unsafe { _getServerInfoCallback ??= GetServerInfoAction; }
|
||||
_closeContainerCallback ??= CloseContainerAction;
|
||||
unsafe { _getScreenModeCallback ??= GetScreenModeAction; } // v77 (PluginManager.UiHooks.cs)
|
||||
_getUiHookFlagsCallback ??= GetUiHookFlagsAction;
|
||||
unsafe { _setServerMessageInterestCallback ??= SetServerMessageInterestAction; }
|
||||
unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79
|
||||
unsafe { _raiseCallback ??= RaiseAction; }
|
||||
_trainSkillCallback ??= TrainSkillAction;
|
||||
_getVendorInfoCallback ??= GetVendorInfoAction;
|
||||
_getVendorItemsCallback ??= GetVendorItemsAction;
|
||||
_vendorBuyCallback ??= VendorBuyAction;
|
||||
|
|
@ -2770,6 +2928,12 @@ internal static class PluginManager
|
|||
_api.GetCharacterTitlesFn = Marshal.GetFunctionPointerForDelegate(_getCharacterTitlesCallback);
|
||||
_api.GetServerInfoFn = Marshal.GetFunctionPointerForDelegate(_getServerInfoCallback);
|
||||
_api.CloseContainerFn = Marshal.GetFunctionPointerForDelegate(_closeContainerCallback);
|
||||
_api.GetScreenModeFn = Marshal.GetFunctionPointerForDelegate(_getScreenModeCallback);
|
||||
_api.GetUiHookFlagsFn = Marshal.GetFunctionPointerForDelegate(_getUiHookFlagsCallback);
|
||||
_api.SetServerMessageInterestFn = Marshal.GetFunctionPointerForDelegate(_setServerMessageInterestCallback);
|
||||
_api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback);
|
||||
_api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback);
|
||||
_api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback);
|
||||
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
|
||||
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
|
||||
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
|
||||
|
|
@ -3828,6 +3992,133 @@ internal static class PluginManager
|
|||
/// <summary>v72: see PluginContract.TradeCloseFn.</summary>
|
||||
private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close());
|
||||
|
||||
// ── v79: spending experience (Compatibility/TrainingApi.cs) ─────────
|
||||
|
||||
/// <summary>v79: see PluginContract.GetTrainingInfoFn.</summary>
|
||||
private static unsafe int GetTrainingInfoAction(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries)
|
||||
{
|
||||
try
|
||||
{
|
||||
return TrainingApi.GetInfo(info, entries, maxEntries);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v79: see PluginContract.RaiseFn.</summary>
|
||||
private static unsafe int RaiseAction(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)
|
||||
{
|
||||
try
|
||||
{
|
||||
RaiseStatus r = TrainingApi.Raise(kind, stype, ranks, expectedXp, out long sent);
|
||||
if (xpSent != null) *xpSent = sent;
|
||||
return (int)r;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Raise failed - {ex.GetType().Name}: {ex.Message}");
|
||||
return (int)RaiseStatus.SendFailed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v79: see PluginContract.TrainSkillFn.</summary>
|
||||
private static int TrainSkillAction(uint stype, int expectedCredits)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (int)TrainingApi.TrainSkill(stype, expectedCredits);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"TrainSkill failed - {ex.GetType().Name}: {ex.Message}");
|
||||
return (int)RaiseStatus.SendFailed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
|
||||
private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount)
|
||||
{
|
||||
try
|
||||
{
|
||||
LoadedPlugin? owner = CurrentDispatch;
|
||||
if (owner == null)
|
||||
return -1;
|
||||
if (opcodeCount == 0 && eventCount == 0)
|
||||
{
|
||||
owner.ServerMessageInterest?.Clear();
|
||||
RynthLog.Plugin($"PluginManager: {owner.DisplayName} stopped server messages.");
|
||||
return 1;
|
||||
}
|
||||
if (owner.OnServerMessagePtr == IntPtr.Zero)
|
||||
owner.OnServerMessagePtr = GetProcAddress(owner.ModuleHandle, "RynthPluginOnServerMessage");
|
||||
if (owner.OnServerMessagePtr == IntPtr.Zero)
|
||||
return 0;
|
||||
var interest = owner.ServerMessageInterest ??= new Net.ServerMessageInterest();
|
||||
if (!interest.Set(opcodes, opcodeCount, gameEvents, eventCount))
|
||||
return -3;
|
||||
RynthLog.Plugin($"PluginManager: {owner.DisplayName} wants server messages: " +
|
||||
(interest.All ? "all" : $"{interest.OpcodeCount} opcode(s), {interest.EventCount} game event(s){(interest.AllGameEvents ? " + all game events" : "")}"));
|
||||
return EngineSettings.ServerMessageStream ? 1 : 2;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"PluginManager: SetServerMessageInterest failed - {ex.GetType().Name}: {ex.Message}");
|
||||
return -3;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v78: initialized, healthy plugins with a non-empty server-message interest.</summary>
|
||||
internal static int ServerMessageSubscriberCount()
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
var p = _plugins[i];
|
||||
if (p.Initialized && !p.Failed && p.OnServerMessagePtr != IntPtr.Zero &&
|
||||
p.ServerMessageInterest is { IsEmpty: false })
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v78: one reassembled server message to the plugins that asked for it (called from
|
||||
/// ServerMessageStream.Pump, on this pump). <paramref name="body"/> is the message after
|
||||
/// its opcode, valid only during the call. Returns how many plugins were called.
|
||||
/// </summary>
|
||||
internal static unsafe int DispatchServerMessage(uint opcode, uint eventType, byte* body, int length)
|
||||
{
|
||||
int called = 0;
|
||||
for (int i = 0; i < _plugins.Count; i++)
|
||||
{
|
||||
var plugin = _plugins[i];
|
||||
if (!plugin.Initialized || plugin.Failed || plugin.OnServerMessagePtr == IntPtr.Zero)
|
||||
continue;
|
||||
var interest = plugin.ServerMessageInterest;
|
||||
if (interest == null || !interest.Wants(opcode, eventType))
|
||||
continue;
|
||||
|
||||
LoadedPlugin? outer = EnterDispatch(plugin);
|
||||
try
|
||||
{
|
||||
((delegate* unmanaged[Cdecl]<uint, byte*, int, void>)plugin.OnServerMessagePtr)(opcode, body, length);
|
||||
called++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
plugin.Failed = true;
|
||||
RynthLog.Error($"PluginManager: {plugin.DisplayName} OnServerMessage threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
LeaveDispatch(outer);
|
||||
}
|
||||
}
|
||||
return called;
|
||||
}
|
||||
|
||||
/// <summary>v76: close an external container (see PluginContract.CloseContainerFn).</summary>
|
||||
private static int CloseContainerAction(uint containerId)
|
||||
{
|
||||
|
|
|
|||
119
src/RynthCore.Engine/Plugins/PluginManifestGate.cs
Normal file
119
src/RynthCore.Engine/Plugins/PluginManifestGate.cs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/PluginManifestGate.cs
|
||||
// The engine's use of plugin manifests (RynthCore.PluginSdk.Manifest, compiled in):
|
||||
// - before any plugin DLL is loaded, read each one's embedded manifest from the
|
||||
// file (no LoadLibrary: a refused NativeAOT plugin would otherwise keep a whole
|
||||
// runtime in acclient's 4 GB for good) and decide which may load, in what order;
|
||||
// - before a plugin's Init, check the plugins it requires started.
|
||||
// A plugin without a manifest is never refused and keeps its place in the list,
|
||||
// so a plugin list with no manifests loads exactly as before.
|
||||
//
|
||||
// BCL + the manifest files only, so tools\PluginManifestTests compiles it too.
|
||||
// PluginManager owns the logging and the chat notice.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.PluginSdk.Manifest;
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
internal static class PluginManifestGate
|
||||
{
|
||||
internal sealed class LoadPlan
|
||||
{
|
||||
/// <summary>Paths to load, in order, with their manifests (null for a plugin without one).</summary>
|
||||
public List<(string Path, RynthPluginManifest? Manifest)> Load { get; } = new();
|
||||
/// <summary>Plugins not loaded, with the reason (one sentence, fit for chat).</summary>
|
||||
public List<PluginRefusal> Refused { get; } = new();
|
||||
/// <summary>Log lines: manifests found, broken manifests, notes.</summary>
|
||||
public List<string> Log { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the manifests of <paramref name="paths"/> and resolves them against
|
||||
/// <paramref name="engineApi"/>. <paramref name="fileVersion"/> gives a DLL's version resource
|
||||
/// (for dependency versions of plugins whose manifest has none); null skips it.
|
||||
/// </summary>
|
||||
public static LoadPlan Plan(IReadOnlyList<string> paths, uint engineApi, Func<string, string>? fileVersion = null)
|
||||
{
|
||||
var plan = new LoadPlan();
|
||||
var candidates = new List<PluginCandidate>(paths.Count);
|
||||
int withManifest = 0;
|
||||
foreach (string path in paths)
|
||||
{
|
||||
RynthPluginManifest? manifest = null;
|
||||
try
|
||||
{
|
||||
manifest = PluginManifestReader.Read(path);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
// A broken manifest is a build problem, not the player's: load it the old way.
|
||||
plan.Log.Add($"{Path.GetFileName(path)}: manifest unreadable ({ex.Message}) - loading it as a plugin without one.");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
plan.Log.Add($"{Path.GetFileName(path)}: could not read its manifest ({ex.Message}) - loading it as a plugin without one.");
|
||||
}
|
||||
|
||||
string fv = "";
|
||||
if (fileVersion != null && string.IsNullOrEmpty(manifest?.Version))
|
||||
{
|
||||
try { fv = fileVersion(path) ?? ""; } catch { fv = ""; }
|
||||
}
|
||||
if (manifest != null)
|
||||
{
|
||||
withManifest++;
|
||||
plan.Log.Add($"{Path.GetFileName(path)}: manifest {Describe(manifest)}.");
|
||||
}
|
||||
candidates.Add(new PluginCandidate(path, manifest, fv));
|
||||
}
|
||||
|
||||
PluginResolution res = PluginManifestResolver.Resolve(candidates, engineApi);
|
||||
foreach (PluginCandidate c in res.Order)
|
||||
plan.Load.Add((c.Key, c.Manifest));
|
||||
plan.Refused.AddRange(res.Refused);
|
||||
foreach (string note in res.Notes)
|
||||
plan.Log.Add(note);
|
||||
if (withManifest == 0 && paths.Count > 0)
|
||||
plan.Log.Add("no plugin has a manifest; loading them as listed.");
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when every plugin <paramref name="manifest"/> requires has started; otherwise why not.
|
||||
/// <paramref name="started"/> answers by plugin name: true started, false loaded but not
|
||||
/// started (failed or refused at Init), null not loaded at all.
|
||||
/// </summary>
|
||||
public static string? CheckRequiredStarted(RynthPluginManifest? manifest, Func<string, bool?> started)
|
||||
{
|
||||
if (manifest == null) return null;
|
||||
foreach (RynthPluginDependency d in manifest.Dependencies)
|
||||
{
|
||||
if (d.Optional) continue;
|
||||
bool? s = started(d.Name);
|
||||
if (s == true) continue;
|
||||
return s == false
|
||||
? $"{manifest.Name} needs {d.Name}, which failed to start"
|
||||
: $"{manifest.Name} needs {d.Name}, which is not loaded";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>"RynthOracle 2026.10.5.1, API 71+, needs RynthAi (optional)".</summary>
|
||||
public static string Describe(RynthPluginManifest m)
|
||||
{
|
||||
string api = m.MaxEngineApi != 0 ? $"API {m.MinEngineApi}-{m.MaxEngineApi}" : $"API {m.MinEngineApi}+";
|
||||
string s = $"{m.Name}{(m.Version.Length > 0 ? " " + m.Version : "")}, {api}";
|
||||
if (m.Dependencies.Count > 0)
|
||||
{
|
||||
var parts = new List<string>(m.Dependencies.Count);
|
||||
foreach (RynthPluginDependency d in m.Dependencies)
|
||||
parts.Add(d.Name + (d.MinVersion.Length > 0 ? " " + d.MinVersion + "+" : "") + (d.Optional ? " (optional)" : ""));
|
||||
s += ", needs " + string.Join(", ", parts);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
113
src/RynthCore.Engine/ReloadDeferral.cs
Normal file
113
src/RynthCore.Engine/ReloadDeferral.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ReloadDeferral.cs
|
||||
// Holds a hot reload while a plugin says one now would hurt (2026-10-05).
|
||||
//
|
||||
// Drakkon died on DreamWeave at 13:43:20 after the loader's file watcher saw a
|
||||
// new RynthCore.Engine.dll at 13:42:54 and reloaded the engine mid-fight: every
|
||||
// plugin was down for about 8 s, then RynthAi came back as if it had just logged
|
||||
// in. The loader (native\Loader, off-limits here) decides to reload and calls
|
||||
// RynthCoreShutdown on its own reload thread; nothing in the game waits on that
|
||||
// thread. So the engine's side of the handshake is: before tearing down, ask
|
||||
// every plugin's optional RynthPluginReloadBlocker export, and while one answers
|
||||
// with a reason, wait and ask again, up to Cap. The game keeps running on the
|
||||
// old engine meanwhile; the loader stages the new one after Shutdown returns, so
|
||||
// the newest file on disk is what loads.
|
||||
//
|
||||
// Pure: the plugin query, the clock, the sleep and the log are injected, so the
|
||||
// loop is tested offline (tools\ReloadDeferralTests). EntryPoint wires it.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
internal sealed class ReloadDeferral
|
||||
{
|
||||
/// <summary>Longest a reload waits for the plugins (then it goes ahead, and says so).</summary>
|
||||
public static readonly TimeSpan DefaultCap = TimeSpan.FromMinutes(2);
|
||||
/// <summary>How often the plugins are asked again while one blocks.</summary>
|
||||
public static readonly TimeSpan DefaultPoll = TimeSpan.FromMilliseconds(500);
|
||||
/// <summary>While waiting, the "still waiting" line repeats this often (the first line is at once).</summary>
|
||||
public static readonly TimeSpan DefaultLogEvery = TimeSpan.FromSeconds(15);
|
||||
|
||||
public enum Outcome
|
||||
{
|
||||
/// <summary>No plugin objected: reload at once.</summary>
|
||||
Clear,
|
||||
/// <summary>A plugin objected, then cleared within the cap.</summary>
|
||||
ClearedAfterWait,
|
||||
/// <summary>Still objecting at the cap: reload anyway.</summary>
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
/// <summary>The plugins that object now, each with its reason (empty = safe).</summary>
|
||||
public required Func<IReadOnlyList<(string Plugin, string Reason)>> Query { get; init; }
|
||||
public required Action<string> Log { get; init; }
|
||||
/// <summary>Told once, when the wait starts (the engine puts it in chat).</summary>
|
||||
public Action<string>? Notify { get; init; }
|
||||
public Func<DateTime> Clock { get; init; } = () => DateTime.UtcNow;
|
||||
public Action<TimeSpan> Sleep { get; init; } = t => Thread.Sleep(t);
|
||||
public TimeSpan Cap { get; init; } = DefaultCap;
|
||||
public TimeSpan Poll { get; init; } = DefaultPoll;
|
||||
public TimeSpan LogEvery { get; init; } = DefaultLogEvery;
|
||||
|
||||
/// <summary>Asks the plugins until none objects or <see cref="Cap"/> has passed.</summary>
|
||||
public Outcome Run(out TimeSpan waited)
|
||||
{
|
||||
DateTime start = Clock();
|
||||
waited = TimeSpan.Zero;
|
||||
var blockers = SafeQuery();
|
||||
if (blockers.Count == 0) return Outcome.Clear;
|
||||
|
||||
string first = Describe(blockers);
|
||||
Log($"engine reload waiting: {first} (asking again every {Poll.TotalSeconds:0.#} s, at most {Cap.TotalSeconds:0} s).");
|
||||
try { Notify?.Invoke(first); } catch { }
|
||||
DateTime lastLog = start;
|
||||
|
||||
while (true)
|
||||
{
|
||||
DateTime now = Clock();
|
||||
waited = now - start;
|
||||
if (waited >= Cap)
|
||||
{
|
||||
Log($"engine reload: waited {waited.TotalSeconds:0} s and {Describe(blockers)} still; reloading anyway.");
|
||||
return Outcome.TimedOut;
|
||||
}
|
||||
Sleep(Poll);
|
||||
blockers = SafeQuery();
|
||||
now = Clock();
|
||||
waited = now - start;
|
||||
if (blockers.Count == 0)
|
||||
{
|
||||
Log($"engine reload: the plugins are clear after {waited.TotalSeconds:0.0} s; reloading now.");
|
||||
return Outcome.ClearedAfterWait;
|
||||
}
|
||||
if (now - lastLog >= LogEvery)
|
||||
{
|
||||
lastLog = now;
|
||||
Log($"engine reload waiting: {Describe(blockers)} ({waited.TotalSeconds:0} s of at most {Cap.TotalSeconds:0} s).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"RynthAi in combat (a monster engaged)", several joined with "; ".</summary>
|
||||
public static string Describe(IReadOnlyList<(string Plugin, string Reason)> blockers)
|
||||
{
|
||||
var parts = new List<string>(blockers.Count);
|
||||
foreach (var (plugin, reason) in blockers) parts.Add($"{plugin} {reason}");
|
||||
return string.Join("; ", parts);
|
||||
}
|
||||
|
||||
// A plugin query that throws must never hold a reload: count it as "nothing objects".
|
||||
private IReadOnlyList<(string Plugin, string Reason)> SafeQuery()
|
||||
{
|
||||
try { return Query() ?? Array.Empty<(string, string)>(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { Log($"engine reload: asking the plugins failed ({ex.GetType().Name}: {ex.Message}); not waiting."); } catch { }
|
||||
return Array.Empty<(string, string)>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -73,10 +73,14 @@
|
|||
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Shared\SessionStateStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
|
||||
<!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's copy (MonoGame, Ms-PL). -->
|
||||
<!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's decoder (RynthCore's own, MIT). -->
|
||||
<Compile Include="..\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="Shared\DxtUtil.cs" />
|
||||
<!-- The byte-ring protocol shared with the Decal bridge plugin (docs/DECAL_BRIDGE_PLAN.md). -->
|
||||
<Compile Include="..\RynthCore.DecalBridge\BridgeProtocol.cs" Link="Shared\BridgeProtocol.cs" />
|
||||
<!-- Plugin manifests: read from each plugin DLL before loading it (Plugins/PluginManifestGate.cs). -->
|
||||
<Compile Include="..\RynthCore.PluginSdk\Manifest\*.cs" Link="Shared\Manifest\%(Filename)%(Extension)" />
|
||||
<!-- The SDK's server-message parsers: /rc netmsg log checks them against the live server (Net/ServerMessageStream.cs). -->
|
||||
<Compile Include="..\RynthCore.PluginSdk\Net\*.cs" Link="Shared\Net\%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Prevent trimmer from removing ImGui.NET's DllImport methods -->
|
||||
|
|
|
|||
|
|
@ -77,6 +77,83 @@ internal static class RynthLog
|
|||
EntryPoint.LogTagged("engine", msg, "ERR");
|
||||
}
|
||||
|
||||
// ── Diagnostic traces (2026-10-05, Drakkon's held casts on DreamWeave) ──
|
||||
// A movement packet sent while a cast winds up can cancel the cast or leave the server
|
||||
// holding it open, and the old movement lines were 1 in 8 with no caller. Both switches
|
||||
// are on by default; each costs one bool test when off.
|
||||
|
||||
/// <summary>Every plugin movement call (SetAutoRun, SetMotion, DoMovement/StopMovement,
|
||||
/// StopCompletely, TurnToHeading, jumps), one "Move:" line each with the calling plugin.
|
||||
/// Identical calls in a row from one caller (turns: any angle) are counted, not written,
|
||||
/// for up to MoveRepeatWindowMs; the count rides on the next line written.</summary>
|
||||
internal static bool MoveTraceEnabled = true;
|
||||
|
||||
/// <summary>Every server UseDone (0x01C7) with its sequence number and error code
|
||||
/// (before: the first 25 of a session).</summary>
|
||||
internal static bool ActionDoneTraceEnabled = true;
|
||||
|
||||
private const long MoveRepeatWindowMs = 1000;
|
||||
private static readonly object _moveGate = new();
|
||||
private static string _moveLastKey = "";
|
||||
private static long _moveLastWrittenMs = long.MinValue;
|
||||
private static int _moveRepeats;
|
||||
private static long _moveRepeatFirstMs;
|
||||
private static string _moveRepeatLastArg = "";
|
||||
|
||||
/// <summary>
|
||||
/// One plugin movement call (see <see cref="MoveTraceEnabled"/>). <paramref name="name"/>
|
||||
/// must be a string literal (it also goes into AcActionTrace, which keeps the last 256
|
||||
/// actions for crash dumps); <paramref name="a"/>/<paramref name="b"/> are its trace args.
|
||||
/// </summary>
|
||||
internal static void Move(string name, string arg, bool ok, bool collapseByKind = false, uint a = 0, uint b = 0)
|
||||
{
|
||||
Compatibility.AcActionTrace.Record(name, a, b);
|
||||
if (!MoveTraceEnabled) return;
|
||||
string? line = null;
|
||||
try
|
||||
{
|
||||
string caller = MoveCaller();
|
||||
lock (_moveGate)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
string key = collapseByKind ? $"{caller}|{name}" : $"{caller}|{name}({arg})|{ok}";
|
||||
if (key == _moveLastKey && now - _moveLastWrittenMs < MoveRepeatWindowMs)
|
||||
{
|
||||
if (_moveRepeats == 0) _moveRepeatFirstMs = now;
|
||||
_moveRepeats++;
|
||||
_moveRepeatLastArg = arg;
|
||||
return;
|
||||
}
|
||||
string more = "";
|
||||
if (_moveRepeats > 0)
|
||||
{
|
||||
string[] parts = _moveLastKey.Split('|');
|
||||
string what = parts.Length > 1 ? parts[1] : "?";
|
||||
string last = parts.Length > 2 ? "" : $", last {_moveRepeatLastArg}";
|
||||
more = $" (+{_moveRepeats} more {what}{last} by {parts[0]} before this, over {now - _moveRepeatFirstMs} ms)";
|
||||
}
|
||||
line = $"Move: {name}({arg}) by {caller} -> {(ok ? "ok" : "FAILED")}{more}";
|
||||
_moveLastKey = key;
|
||||
_moveLastWrittenMs = now;
|
||||
_moveRepeats = 0;
|
||||
_moveRepeatLastArg = "";
|
||||
}
|
||||
}
|
||||
catch { return; }
|
||||
Write(line);
|
||||
}
|
||||
|
||||
/// <summary>The plugin whose tick or event is calling, else the thread.</summary>
|
||||
private static string MoveCaller()
|
||||
{
|
||||
var plugin = Plugins.PluginManager.CurrentDispatch;
|
||||
if (plugin != null)
|
||||
return string.IsNullOrEmpty(plugin.DisplayName) ? plugin.FileName : plugin.DisplayName;
|
||||
return Compatibility.MainThreadGuard.IsOnMainThread()
|
||||
? "AC main thread"
|
||||
: $"thread {Environment.CurrentManagedThreadId}";
|
||||
}
|
||||
|
||||
// ── Sink ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void Write(string message) => EntryPoint.Log(message);
|
||||
|
|
|
|||
28
src/RynthCore.Engine/UI/Data/ArgbOpacity.cs
Normal file
28
src/RynthCore.Engine/UI/Data/ArgbOpacity.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/ArgbOpacity.cs
|
||||
// An AARRGGBB colour's alpha as an opacity percentage, for the Vision face's
|
||||
// overlay opacity sliders (slopes, water, radar ring). The opacity lives in the
|
||||
// colour the RynthVision plugin already saves, so the slider needs no new
|
||||
// setting and no plugin change: moving it rewrites the colour's alpha byte.
|
||||
//
|
||||
// Percent is a float so an untouched value round-trips exactly
|
||||
// (0x60 -> 37.65 % -> 0x60); only a slider move changes the byte.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal static class ArgbOpacity
|
||||
{
|
||||
/// <summary>The colour's alpha as 0..100 %.</summary>
|
||||
public static float Percent(uint argb) => (argb >> 24) * 100f / 255f;
|
||||
|
||||
/// <summary>The colour with its alpha set from <paramref name="percent"/> (clamped to 0..100); RGB kept.</summary>
|
||||
public static uint WithPercent(uint argb, float percent)
|
||||
{
|
||||
float p = float.IsNaN(percent) ? 0f : Math.Clamp(percent, 0f, 100f);
|
||||
uint a = (uint)Math.Clamp((int)MathF.Round(p * 255f / 100f), 0, 255);
|
||||
return (argb & 0x00FFFFFFu) | (a << 24);
|
||||
}
|
||||
}
|
||||
|
|
@ -156,6 +156,9 @@ internal sealed class RynthAiSettings
|
|||
public bool RebuffWhenIdle { get; set; }
|
||||
public int RebuffSecondsRemaining { get; set; } = 300;
|
||||
public int RebuffTopOffSecondsRemaining { get; set; } = 1200;
|
||||
// Cast our own buff even when gear already gives it (servers with buff augments). Default
|
||||
// on; a RynthAi that predates it doesn't send it, and must not read as off.
|
||||
public bool CastBuffsOverItemBuffs { get; set; } = true;
|
||||
public int BuffMinSkillLevelTier1 { get; set; } = 35;
|
||||
public int BuffMinSkillLevelTier2 { get; set; } = 85;
|
||||
public int BuffMinSkillLevelTier3 { get; set; } = 135;
|
||||
|
|
@ -176,6 +179,10 @@ internal sealed class RynthAiSettings
|
|||
public bool LootJumpEnabled { get; set; }
|
||||
public int LootJumpHeight { get; set; } = 10;
|
||||
public int LootOwnership { get; set; }
|
||||
// Recover your own death corpse whole (default on), and travel back to it after a death
|
||||
// (default off). A RynthAi that predates them doesn't send them; on must not read as off.
|
||||
public bool LootOwnCorpse { get; set; } = true;
|
||||
public bool TravelToOwnCorpse { get; set; }
|
||||
public bool EnableAutostack { get; set; } = true;
|
||||
public bool ReadUnknownScrolls { get; set; } = true; // VTank's default
|
||||
public bool EnableCombineSalvage { get; set; } = true;
|
||||
|
|
@ -646,6 +653,8 @@ internal static class SettingsSchema
|
|||
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."),
|
||||
Int("Also Refresh Under (seconds left)", s => s.RebuffTopOffSecondsRemaining, (s, v) => s.RebuffTopOffSecondsRemaining = v, 30, 3600, 60,
|
||||
"When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."),
|
||||
Bool("Cast buffs even when an item gives them", s => s.CastBuffsOverItemBuffs, (s, v) => s.CastBuffsOverItemBuffs = v,
|
||||
"Cast your own buff even when worn gear already gives that buff.\nFor servers with buff augments, where your own cast is stronger or lasts longer.\nOn by default: on retail it costs a few extra casts."),
|
||||
Spacer(),
|
||||
Section("Buff Difficulty (Min Buffed Skill)"),
|
||||
Tiers(
|
||||
|
|
@ -678,6 +687,10 @@ internal static class SettingsSchema
|
|||
Spacer(),
|
||||
Section("Corpse Ownership"),
|
||||
Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v),
|
||||
Bool("Recover My Corpse", s => s.LootOwnCorpse, (s, v) => s.LootOwnCorpse = v,
|
||||
"When your own corpse (\"Corpse of <you>\") is within loot range, open it and take every\nitem on it, whatever the loot profile and Loot From say. Needs Enable Looting.\n/ra owncorpse says where your last corpse is."),
|
||||
Bool("Travel Back To My Corpse", s => s.TravelToOwnCorpse, (s, v) => s.TravelToOwnCorpse = v,
|
||||
"After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."),
|
||||
Spacer(),
|
||||
Section("Inventory Management"),
|
||||
Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v),
|
||||
|
|
|
|||
|
|
@ -5,13 +5,20 @@
|
|||
// into one picture. Pure code: no AC memory, no D3D, no engine state, so the
|
||||
// RynthSuite offline tests compile it in and decode real icons.
|
||||
//
|
||||
// The texture formats and their byte layouts are the ones RynthCore.StatusAgent
|
||||
// (Dat/IconDecoder.cs, the phone remote's icons) decodes, ported from
|
||||
// ACEmulator's DatLoader; DXT1/3/5 use the StatusAgent's DxtUtil.cs (MonoGame,
|
||||
// Ms-PL), linked into the engine project. The dat reader is the on-demand
|
||||
// B-tree walk of ImGui/MonsterHud/PortalSpellTable.cs over one open stream:
|
||||
// header at 0x140, a B-tree searched by file id, block chains whose first
|
||||
// dword is the next block's offset.
|
||||
// Written for RynthCore (MIT); the dat reader and the texture decoding were
|
||||
// rewritten on 2026-10-05 from the public dat container layout and the
|
||||
// Texture / Palette layouts as Chorizite's DatReaderWriter (MIT) describes
|
||||
// them (its notice is in RynthCore.StatusAgent/Dat/DatDatabase.cs):
|
||||
// - header at 0x140: magic, block size, file size, ..., root node offset
|
||||
// (uint32 at 0x160); a block starts with the next block's offset (0 =
|
||||
// last); the directory is a B-tree of nodes (62 child offsets, an entry
|
||||
// count, entries of 24 bytes: flags, id, offset, size, date, iteration);
|
||||
// - Texture: id u32, data category u32, width i32, height i32, format u32,
|
||||
// length i32, data[length], and for P8 / INDEX16 a palette id u32;
|
||||
// Palette: id u32, count i32, count x u32 A8R8G8B8.
|
||||
// DXT1/3/5 use the StatusAgent's DxtUtil.cs, linked into the engine project.
|
||||
// The pixels are the same as the StatusAgent's Dat/IconDecoder.cs (the phone
|
||||
// remote's icons) produces.
|
||||
//
|
||||
// Threads: whatever thread owns the AcDatFile (the icon worker). Every read is
|
||||
// bounds-checked; a bad file returns null, never throws out of Decode/Compose.
|
||||
|
|
@ -21,26 +28,30 @@ using System;
|
|||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using ACE.DatLoader;
|
||||
using RynthCore.Imaging;
|
||||
|
||||
namespace RynthCore.Engine.UI.ScriptWindows;
|
||||
|
||||
/// <summary>A read-only portal.dat opened for a batch of reads. Not thread-safe.</summary>
|
||||
internal sealed class AcDatFile : IDisposable
|
||||
{
|
||||
private const int HeaderOffset = 0x140;
|
||||
private const int Branches = 62, MaxEntries = 61, EntrySize = 24;
|
||||
private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716
|
||||
private const int MaxDepth = 16;
|
||||
private const long HeaderOffset = 0x140;
|
||||
private const int ChildSlots = 62, MaxEntries = 61, EntryBytes = 24;
|
||||
private const int EntriesOffset = ChildSlots * 4 + 4; // 252
|
||||
private const int NodeBytes = EntriesOffset + MaxEntries * EntryBytes; // 1716
|
||||
private const int DepthLimit = 16;
|
||||
|
||||
private readonly FileStream _fs;
|
||||
private readonly uint _blockSize;
|
||||
private readonly long _length;
|
||||
private readonly int _payload; // block size - 4
|
||||
private readonly uint _root;
|
||||
private readonly byte[] _node = new byte[NodeBytes];
|
||||
|
||||
private AcDatFile(FileStream fs, uint blockSize, uint root)
|
||||
{
|
||||
_fs = fs;
|
||||
_blockSize = blockSize;
|
||||
_length = fs.Length;
|
||||
_payload = (int)blockSize - 4;
|
||||
_root = root;
|
||||
}
|
||||
|
||||
|
|
@ -52,24 +63,24 @@ internal sealed class AcDatFile : IDisposable
|
|||
{
|
||||
fs = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
|
||||
Span<byte> hdr = stackalloc byte[36];
|
||||
fs.Seek(HeaderOffset, SeekOrigin.Begin);
|
||||
if (!ReadFully(fs, hdr)) { why = "short header"; fs.Dispose(); return null; }
|
||||
uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
|
||||
uint root = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(32, 4));
|
||||
Span<byte> header = stackalloc byte[36];
|
||||
fs.Position = HeaderOffset;
|
||||
if (!ReadFully(fs, header)) { why = "short header"; fs.Dispose(); return null; }
|
||||
uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(4));
|
||||
uint root = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(32));
|
||||
if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length)
|
||||
{
|
||||
why = "bad header";
|
||||
why = $"not a dat file (block size {blockSize}, root 0x{root:X8})";
|
||||
fs.Dispose();
|
||||
return null;
|
||||
}
|
||||
why = string.Empty;
|
||||
why = "";
|
||||
return new AcDatFile(fs, blockSize, root);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
fs?.Dispose();
|
||||
why = $"{ex.GetType().Name}: {ex.Message}";
|
||||
why = ex.Message;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -104,26 +115,34 @@ internal sealed class AcDatFile : IDisposable
|
|||
{
|
||||
try
|
||||
{
|
||||
uint offset = _root;
|
||||
for (int depth = 0; depth < MaxDepth && offset != 0; depth++)
|
||||
uint at = _root;
|
||||
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
|
||||
{
|
||||
byte[]? node = ReadChain(offset, NodeSize);
|
||||
if (node == null) return null;
|
||||
uint count = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches));
|
||||
if (count > MaxEntries) return null;
|
||||
int i = 0;
|
||||
while (i < count && EntryId(node, i) < fileId) i++;
|
||||
if (i < count && EntryId(node, i) == fileId)
|
||||
int got = ReadChain(at, _node);
|
||||
if (got < EntriesOffset) return null;
|
||||
int count = BinaryPrimitives.ReadInt32LittleEndian(_node.AsSpan(EntriesOffset - 4));
|
||||
if (count < 0 || count > MaxEntries || got < EntriesOffset + count * EntryBytes) return null;
|
||||
|
||||
// Entries are sorted by id: binary search for the first id >= fileId.
|
||||
int lo = 0, hi = count;
|
||||
while (lo < hi)
|
||||
{
|
||||
int e = 4 * Branches + 4 + i * EntrySize;
|
||||
uint fileOffset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 8));
|
||||
uint fileSize = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 12));
|
||||
if (fileSize == 0 || fileSize > (uint)maxSize) return null;
|
||||
return ReadChain(fileOffset, (int)fileSize);
|
||||
int mid = (lo + hi) >> 1;
|
||||
if (IdAt(mid) < fileId) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
bool leaf = BinaryPrimitives.ReadUInt32LittleEndian(node) == 0;
|
||||
if (leaf || i >= Branches) return null;
|
||||
offset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(i * 4));
|
||||
if (lo < count && IdAt(lo) == fileId)
|
||||
{
|
||||
var e = _node.AsSpan(EntriesOffset + lo * EntryBytes);
|
||||
uint offset = BinaryPrimitives.ReadUInt32LittleEndian(e.Slice(8));
|
||||
uint size = BinaryPrimitives.ReadUInt32LittleEndian(e.Slice(12));
|
||||
if (size == 0 || size > (uint)maxSize || size > _length) return null;
|
||||
var data = new byte[size];
|
||||
return ReadChain(offset, data) == data.Length ? data : null;
|
||||
}
|
||||
// Not in this node: a leaf (first child offset 0) ends the search; otherwise
|
||||
// child `lo` holds the ids between entries lo-1 and lo.
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(_node) == 0) return null;
|
||||
at = BinaryPrimitives.ReadUInt32LittleEndian(_node.AsSpan(lo * 4));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -133,41 +152,36 @@ internal sealed class AcDatFile : IDisposable
|
|||
}
|
||||
}
|
||||
|
||||
private static uint EntryId(byte[] node, int i) =>
|
||||
BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches + 4 + i * EntrySize + 4));
|
||||
private uint IdAt(int i) => BinaryPrimitives.ReadUInt32LittleEndian(_node.AsSpan(EntriesOffset + i * EntryBytes + 4));
|
||||
|
||||
/// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary>
|
||||
private byte[]? ReadChain(uint offset, int size)
|
||||
// Copies the block chain at byte offset `first` into `dest`; returns the bytes
|
||||
// filled (fewer than dest.Length when the chain ends first), -1 on a bad link.
|
||||
private int ReadChain(uint first, Span<byte> dest)
|
||||
{
|
||||
if ((long)offset + 4 > _fs.Length) return null;
|
||||
var buffer = new byte[size];
|
||||
Span<byte> next = stackalloc byte[4];
|
||||
_fs.Seek(offset, SeekOrigin.Begin);
|
||||
if (!ReadFully(_fs, next)) return null;
|
||||
uint nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next);
|
||||
long block = first;
|
||||
int done = 0;
|
||||
int guard = 0;
|
||||
while (done < size)
|
||||
Span<byte> link = stackalloc byte[4];
|
||||
while (done < dest.Length)
|
||||
{
|
||||
int take = Math.Min((int)_blockSize - 4, size - done);
|
||||
if (!ReadFully(_fs, buffer.AsSpan(done, take))) return null;
|
||||
if (block == 0) return done;
|
||||
if (block + 4 > _length) return -1;
|
||||
int take = Math.Min(_payload, dest.Length - done);
|
||||
_fs.Position = block;
|
||||
if (!ReadFully(_fs, link) || !ReadFully(_fs, dest.Slice(done, take))) return -1;
|
||||
done += take;
|
||||
if (done >= size) break;
|
||||
if (nextAddr == 0 || nextAddr >= _fs.Length || ++guard > 1_000_000) return null;
|
||||
_fs.Seek(nextAddr, SeekOrigin.Begin);
|
||||
if (!ReadFully(_fs, next)) return null;
|
||||
nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next);
|
||||
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
|
||||
}
|
||||
return buffer;
|
||||
return done;
|
||||
}
|
||||
|
||||
private static bool ReadFully(FileStream fs, Span<byte> dest)
|
||||
{
|
||||
while (dest.Length > 0)
|
||||
int got = 0;
|
||||
while (got < dest.Length)
|
||||
{
|
||||
int n = fs.Read(dest);
|
||||
int n = fs.Read(dest.Slice(got));
|
||||
if (n <= 0) return false;
|
||||
dest = dest.Slice(n);
|
||||
got += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
|
@ -251,7 +265,7 @@ internal static class AcIconDecoder
|
|||
|
||||
/// <summary>
|
||||
/// A 0x06 Texture as RGBA, or null (not a texture id, missing, an unsupported format, larger
|
||||
/// than <see cref="MaxSide"/>, or short data). Layout: id u32, unknown i32, width i32,
|
||||
/// than <see cref="MaxSide"/>, or short data). Layout: id u32, data category u32, width i32,
|
||||
/// height i32, format u32, length i32, data[length], then for INDEX16/P8 a palette id u32.
|
||||
/// </summary>
|
||||
public static AcIconImage? Decode(AcDatFile dat, uint textureId) => Decode(dat, textureId, MaxSide);
|
||||
|
|
@ -274,106 +288,109 @@ internal static class AcIconDecoder
|
|||
}
|
||||
}
|
||||
|
||||
private const uint FmtR8G8B8 = 0x14, FmtA8R8G8B8 = 0x15, FmtR5G6B5 = 0x17, FmtA4R4G4B4 = 0x1A, FmtA8 = 0x1C,
|
||||
FmtP8 = 0x29, FmtIndex16 = 0x65, FmtLscapeR8G8B8 = 0xF3, FmtLscapeAlpha = 0xF4,
|
||||
FmtDxt1 = 0x31545844, FmtDxt3 = 0x33545844, FmtDxt5 = 0x35545844;
|
||||
|
||||
/// <summary>A Texture file's bytes as RGBA (see <see cref="Decode(AcDatFile, uint)"/>); <paramref name="readPalette"/> loads a 0x04 palette.</summary>
|
||||
internal static AcIconImage? DecodeTextureFile(byte[] data, Func<uint, byte[]?> readPalette, int maxSide = MaxSide)
|
||||
{
|
||||
if (data.Length < 24) return null;
|
||||
maxSide = Math.Clamp(maxSide, 1, MaxUiSide);
|
||||
ReadOnlySpan<byte> d = data;
|
||||
int w = BinaryPrimitives.ReadInt32LittleEndian(d[8..]);
|
||||
int h = BinaryPrimitives.ReadInt32LittleEndian(d[12..]);
|
||||
uint fmt = BinaryPrimitives.ReadUInt32LittleEndian(d[16..]);
|
||||
int len = BinaryPrimitives.ReadInt32LittleEndian(d[20..]);
|
||||
if (w <= 0 || h <= 0 || w > maxSide || h > maxSide || len < 0 || len > data.Length - 24) return null;
|
||||
byte[] src = d.Slice(24, len).ToArray();
|
||||
var file = new ReadOnlySpan<byte>(data);
|
||||
int w = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(8));
|
||||
int h = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(12));
|
||||
uint format = BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(16));
|
||||
int length = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(20));
|
||||
int limit = Math.Min(maxSide, MaxUiSide);
|
||||
if (w <= 0 || h <= 0 || w > limit || h > limit) return null;
|
||||
if (length < 0 || 24L + length > data.Length) return null;
|
||||
var src = file.Slice(24, length);
|
||||
int n = w * h;
|
||||
|
||||
switch (fmt)
|
||||
switch (format)
|
||||
{
|
||||
case 827611204: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1); // DXT1
|
||||
case 861165636: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3); // DXT3
|
||||
case 894720068: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5); // DXT5
|
||||
case FmtDxt1: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1);
|
||||
case FmtDxt3: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3);
|
||||
case FmtDxt5: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5);
|
||||
}
|
||||
|
||||
var rgba = new byte[n * 4];
|
||||
void Px(int i, int r, int g, int b, int a)
|
||||
var px = new byte[n * 4];
|
||||
switch (format)
|
||||
{
|
||||
int o = i * 4;
|
||||
rgba[o] = (byte)r; rgba[o + 1] = (byte)g; rgba[o + 2] = (byte)b; rgba[o + 3] = (byte)a;
|
||||
}
|
||||
|
||||
switch (fmt)
|
||||
{
|
||||
case 20: // R8G8B8, stored B, G, R
|
||||
for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
|
||||
case FmtA8R8G8B8: // memory order B, G, R, A
|
||||
if (length < n * 4) return null;
|
||||
for (int i = 0; i < n; i++) Set(px, i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], src[i * 4 + 3]);
|
||||
break;
|
||||
case 243: // CUSTOM_LSCAPE_R8G8B8, stored R, G, B
|
||||
for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
|
||||
case FmtR8G8B8: // B, G, R
|
||||
if (length < n * 3) return null;
|
||||
for (int i = 0; i < n; i++) Set(px, i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
|
||||
break;
|
||||
case 21: // A8R8G8B8, stored B, G, R, A
|
||||
case 22: // X8R8G8B8
|
||||
for (int i = 0; i < n && i * 4 + 3 < src.Length; i++)
|
||||
Px(i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], fmt == 22 ? 255 : src[i * 4 + 3]);
|
||||
case FmtLscapeR8G8B8: // R, G, B
|
||||
if (length < n * 3) return null;
|
||||
for (int i = 0; i < n; i++) Set(px, i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
|
||||
break;
|
||||
case 23: // R5G6B5
|
||||
for (int i = 0; i < n && i * 2 + 1 < src.Length; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255);
|
||||
}
|
||||
break;
|
||||
case 26: // A4R4G4B4
|
||||
for (int i = 0; i < n && i * 2 + 1 < src.Length; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17);
|
||||
}
|
||||
break;
|
||||
case 28: // A8 (greyscale)
|
||||
case 244: // LSCAPE_ALPHA
|
||||
for (int i = 0; i < n && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255);
|
||||
break;
|
||||
case 101: // INDEX16
|
||||
case 41: // P8
|
||||
{
|
||||
if (data.Length < 24 + len + 4) return null;
|
||||
uint paletteId = BinaryPrimitives.ReadUInt32LittleEndian(d[(24 + len)..]);
|
||||
uint[]? pal = Palette(readPalette(paletteId));
|
||||
if (pal == null || pal.Length == 0) return null;
|
||||
bool p8 = fmt == 41;
|
||||
case FmtR5G6B5: // top bits only, as the StatusAgent's decoder
|
||||
if (length < n * 2) return null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int idx;
|
||||
if (p8) { if (i >= src.Length) break; idx = src[i]; }
|
||||
else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); }
|
||||
uint c = pal[idx % pal.Length];
|
||||
Px(i, (int)((c >> 16) & 0xFF), (int)((c >> 8) & 0xFF), (int)(c & 0xFF), (int)((c >> 24) & 0xFF));
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Set(px, i, (byte)(((v >> 11) & 0x1F) << 3), (byte)(((v >> 5) & 0x3F) << 2), (byte)((v & 0x1F) << 3), 255);
|
||||
}
|
||||
break;
|
||||
case FmtA4R4G4B4:
|
||||
if (length < n * 2) return null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Set(px, i, (byte)(((v >> 8) & 0xF) * 17), (byte)(((v >> 4) & 0xF) * 17), (byte)((v & 0xF) * 17), (byte)(((v >> 12) & 0xF) * 17));
|
||||
}
|
||||
break;
|
||||
case FmtA8: // one byte a pixel: an opaque grey level
|
||||
case FmtLscapeAlpha:
|
||||
if (length < n) return null;
|
||||
for (int i = 0; i < n; i++) Set(px, i, src[i], src[i], src[i], 255);
|
||||
break;
|
||||
case FmtP8:
|
||||
case FmtIndex16:
|
||||
{
|
||||
int bytesPer = format == FmtP8 ? 1 : 2;
|
||||
if (length < n * bytesPer || 24L + length + 4 > data.Length) return null;
|
||||
uint[]? palette = Palette(readPalette(BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(24 + length))));
|
||||
if (palette == null) return null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int idx = bytesPer == 1 ? src[i] : src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
uint argb = idx < palette.Length ? palette[idx] : 0;
|
||||
Set(px, i, (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb, (byte)(argb >> 24));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return null; // a format icons don't use
|
||||
return null; // raw JPEG, anything else
|
||||
}
|
||||
return new AcIconImage { Width = w, Height = h, Pixels = rgba };
|
||||
return new AcIconImage { Width = w, Height = h, Pixels = px };
|
||||
}
|
||||
|
||||
private static AcIconImage? Dxt(byte[] src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> decompress)
|
||||
private static void Set(byte[] px, int i, byte r, byte g, byte b, byte a)
|
||||
{
|
||||
px[i * 4] = r; px[i * 4 + 1] = g; px[i * 4 + 2] = b; px[i * 4 + 3] = a;
|
||||
}
|
||||
|
||||
private static AcIconImage? Dxt(ReadOnlySpan<byte> src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> decompress)
|
||||
{
|
||||
long need = (long)((w + 3) / 4) * ((h + 3) / 4) * blockBytes;
|
||||
if (src.Length < need) return null; // DxtUtil would read past the end
|
||||
byte[] rgba = decompress(src, w, h);
|
||||
return rgba.Length == w * h * 4 ? new AcIconImage { Width = w, Height = h, Pixels = rgba } : null;
|
||||
if (src.Length < need) return null;
|
||||
return new AcIconImage { Width = w, Height = h, Pixels = decompress(src.Slice(0, (int)need).ToArray(), w, h) };
|
||||
}
|
||||
|
||||
/// <summary>Palette (0x04): id u32, count i32, count x u32 ARGB.</summary>
|
||||
private static uint[]? Palette(byte[]? data)
|
||||
{
|
||||
if (data == null || data.Length < 8) return null;
|
||||
int n = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
|
||||
if (n <= 0 || n > 65536) return null;
|
||||
n = Math.Min(n, (data.Length - 8) / 4);
|
||||
var pal = new uint[n];
|
||||
for (int i = 0; i < n; i++) pal[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4));
|
||||
return pal;
|
||||
int count = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
|
||||
if (count < 0 || 8L + count * 4L > data.Length) return null;
|
||||
var colours = new uint[count];
|
||||
for (int i = 0; i < count; i++) colours[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4));
|
||||
return colours;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue