feat(engine): SK engine and UI work through 2026-10-10 on 2026.10.12.1

See Changelog/2026-10-11-sk-engine-work-through-10-10.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-12 01:06:53 -04:00
commit c9743a2612
80 changed files with 6312 additions and 366 deletions

View file

@ -656,12 +656,21 @@ internal static class ClientHelperHooks
/// </summary>
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
{
// Every exit records its outcome in MergeStackResults so the plugin can poll
// GetMergeStackResult instead of guessing from a later inventory snapshot.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
{
bool queued = AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
MergeStackResults.Record(sourceObjectId, targetObjectId,
queued ? MergeStackResults.Queued : MergeStackResults.QueueFull);
return queued;
}
if (_eventStackableMerge == null) return false;
if (!IsValidObjectId(sourceObjectId)) return false;
if (!IsValidObjectId(targetObjectId)) return false;
if (_eventStackableMerge == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
{
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
// Read counts via the PWD fast path (stypes 11/12 are served from
// PublicWeenieDesc directly — no broken InqInt for inventory items).
@ -680,6 +689,7 @@ internal static class ClientHelperHooks
if (room <= 0)
{
RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})");
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.TargetFull);
return false;
}
amount = Math.Min(sourceCount, room);
@ -690,17 +700,24 @@ internal static class ClientHelperHooks
amount = sourceCount;
}
if (amount <= 0) return false;
if (amount <= 0)
{
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
try
{
byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount);
RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}");
MergeStackResults.Record(sourceObjectId, targetObjectId,
rv != 0 ? MergeStackResults.Sent : MergeStackResults.Failed, rv != 0 ? amount : 0);
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}");
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
}

View file

@ -241,6 +241,24 @@ internal static class ClientObjectHooks
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
private static bool _loggedObjectIdentityServe;
private const int ObjectIdentityPrefetchThrottleMs = 500;
// Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's
// PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before
// qualities/appraisal exist. The main-thread snapshot above can't resolve names for
// ~10 s after login (qualities not populated yet), so off-thread readers fall back to
// these seeds when the snapshot has no entry (or reports type 0). Entries live from
// create until delete; the cap only guards against a missed delete hook.
private static readonly object _createSeedLock = new();
private static readonly Dictionary<uint, string> _createSeedNames = new(1024);
private static readonly Dictionary<uint, uint> _createSeedTypes = new(1024);
private const int CreateSeedCap = 16384;
// PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct
// fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy).
// PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down.
private const int PwdNameOffset = 4;
private static int _createSeedCount;
private static bool _loggedCreateSeedServe;
// Every id the same walk visited, swapped whole (readers never see a half-built array).
private static volatile uint[] _liveObjectIds = Array.Empty<uint>();
@ -393,6 +411,7 @@ internal static class ClientObjectHooks
private static readonly object _weeniePtrSwapLock = new();
private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512);
private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512);
// Diagnostic (temporary): periodic snapshot-size log + live-read probe of
// objects with a position but no cached name. Remove once the missing-
// monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc.
@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks
value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
return false;
// Off-thread: served from the main-thread PWD byte snapshot, never from AC memory.
if (!MainThreadGuard.IsOnMainThread())
return false;
return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value);
if (_getWeenieObject == null)
{
if (!Probe() || _getWeenieObject == null)
@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks
// Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity().
if (!MainThreadGuard.IsOnMainThread())
{
lock (_objectIdentityCacheLock)
{
// A zero snapshot value means qualities weren't populated when the walk
// ran; prefer the create-time descriptor type in that case.
if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0)
return true;
}
if (TryGetCreateSeedType(objectId, out uint seeded))
{
typeFlags = seeded;
return true;
}
// Snapshot hit with flags=0 is still an answer (static scenery often has no type).
lock (_objectIdentityCacheLock)
{
if (_objectTypeCache.TryGetValue(objectId, out typeFlags))
@ -2592,36 +2625,7 @@ internal static class ClientObjectHooks
return TryGetPwdSnapshotInt(objectId, stype, out value);
}
if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0)
{
try
{
IntPtr weeniePtr = _getWeenieObject(objectId);
if (weeniePtr == IntPtr.Zero)
return false;
int pwdBase = _weeniePhysicsObjOffset + 4;
IntPtr fieldAddr = weeniePtr + pwdBase + pwdFieldOffset;
// Page-probe BOTH ends of the 4-byte read span (mirrors
// TryGetObjectOwnershipInfo's dual-end probe): a freed-but-decommitted
// weenie whose field straddles a committed/decommitted page boundary is
// an uncatchable AV under NativeAOT; the catch below only covers
// null-page faults. All stypes served here are Marshal.ReadInt32
// (4 bytes), so the span is [fieldAddr, fieldAddr+3].
if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3))
return false;
value = Marshal.ReadInt32(fieldAddr);
return true;
}
catch
{
return false;
}
}
// Fall through to CBaseQualities::InqInt for stypes not in PWD.
// (IsOnMainThread already checked above, before the PWD fast path.)
// CBaseQualities::InqInt for stypes not in PWD.
if (_inqInt == null)
{
if (!Probe() || _inqInt == null)
@ -3341,6 +3345,101 @@ internal static class ClientObjectHooks
}
}
/// <summary>
/// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed
/// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread,
/// after the original returns. The descriptor is server data that exists before the
/// object's qualities do, so this makes names/types readable off-thread immediately
/// instead of after the first successful identity snapshot (~10 s at login).
/// Every read is pointer-validated; a bad descriptor simply records nothing.
/// </summary>
internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc)
{
if (objectId == 0 || weenieDesc == IntPtr.Zero)
return;
try
{
// PublicWeenieDesc derives from PackObj, so a real descriptor starts with an
// acclient.exe vtable; reject anything else before reading fields.
if (!LooksLikeAcHeapObject(weenieDesc))
return;
bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name);
uint typeFlags = 0;
IntPtr typeAddr = weenieDesc + PwdTypeOffset;
bool gotType = IsReadablePointer(typeAddr);
if (gotType)
typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr));
if (!gotName && (!gotType || typeFlags == 0))
return;
lock (_createSeedLock)
{
// Safety valve for a missed delete: drop everything rather than grow forever.
// The live snapshot covers anything still in the world.
if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap)
{
_createSeedNames.Clear();
_createSeedTypes.Clear();
}
if (gotName)
_createSeedNames[objectId] = name;
if (gotType && typeFlags != 0)
_createSeedTypes[objectId] = typeFlags;
}
int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount);
// First few samples let a log reader confirm the descriptor offsets resolve
// to sensible names/types on this client build.
if (seedNo <= 5)
RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}");
if (!_loggedCreateSeedServe && seedNo >= 50)
{
_loggedCreateSeedServe = true;
int names, types;
lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; }
RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject.");
}
}
catch
{
// Descriptor read failures are non-fatal; the periodic snapshot still runs.
}
}
/// <summary>Drops create-time seeds for a deleted object (called from the delete hook).</summary>
internal static void ForgetCreateSeed(uint objectId)
{
lock (_createSeedLock)
{
_createSeedNames.Remove(objectId);
_createSeedTypes.Remove(objectId);
}
}
private static bool TryGetCreateSeedName(uint objectId, out string name)
{
lock (_createSeedLock)
{
if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0)
{
name = seeded;
return true;
}
}
name = string.Empty;
return false;
}
private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags)
{
lock (_createSeedLock)
return _createSeedTypes.TryGetValue(objectId, out typeFlags);
}
public static bool TryGetObjectName(uint objectId, out string name)
{
name = string.Empty;
@ -3356,6 +3455,10 @@ internal static class ClientObjectHooks
return true;
}
}
// Snapshot miss (login burst / object newer than the last walk): serve the
// name captured from the create descriptor.
if (TryGetCreateSeedName(objectId, out name))
return true;
name = string.Empty;
return false;
}
@ -3809,6 +3912,21 @@ internal static class ClientObjectHooks
&& PwdLayout.TryGetInt(e.Bytes, stype, out value);
}
/// <summary>
/// Off-thread read of one 4-byte PWD field by raw offset (the <see cref="TryReadPwdInt32"/>
/// contract) from the main-thread snapshot. False for objects the last walk didn't see.
/// </summary>
private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value)
{
value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size)
return false;
if (!TryGetPwdSnapshot(objectId, out PwdEntry e))
return false;
value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan<byte>)e.Bytes).Slice(pwdFieldOffset));
return true;
}
private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value)
{
value = 0;

View file

@ -81,6 +81,9 @@ internal static class CreateObjectHooks
if (count <= 0)
RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
// Capture name/type from the create descriptor BEFORE the plugin is told about the
// object, so its off-thread classifier can read them on the very first attempt.
ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc);
PluginManager.QueueCreateObject(objectId);
AutoIdService.Enqueue(objectId);
return result;

View file

@ -71,6 +71,7 @@ internal static class DeleteObjectHooks
if (objectId != 0)
{
PaletteCache.Remove(objectId);
ClientObjectHooks.ForgetCreateSeed(objectId);
PluginManager.QueueDeleteObject(objectId);
AutoIdService.Evict(objectId);
}

View file

@ -0,0 +1,110 @@
// ============================================================================
// RynthCore.Engine - Compatibility/DragDropHooks.cs
// Hooks UIElementManager::StartDragandDrop so the engine knows which item AC
// is actually dragging. AC does not change the selected object when a drag
// starts, so the selection is the previously clicked item, not the dragged one.
//
// The dragged UI element is resolved to an object id with AC's own
// UIElement_ItemList::InqDropIconInfo (the same call AC makes when the drop
// lands), then handed to ItemDragBridge, which republishes it to ImGui.
//
// Threads: AC's main thread (AC's input / UI processing).
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class DragDropHooks
{
// bool __thiscall UIElementManager::StartDragandDrop(UIElementManager*, UIElement* elem, int clickX, int clickY)
private const int StartDragandDropVa = 0x0045E120;
// void __cdecl UIElement_ItemList::InqDropIconInfo(const UIElement* icon, uint& itemId, uint& spellId, DropItemFlags& flags)
private const int InqDropIconInfoVa = 0x004E3380;
// Both verified unique in the shipped client (sub esp,34h / mov edi,[esp+48h] / mov esi,ecx prologue;
// InqDropIconInfo zeroes its out-params up front).
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
];
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
];
private static IntPtr _originalStartDrag;
private static delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void> _inqDropIconInfo;
private static int _logCount;
/// <summary>The drag-start hook is live, so ItemDragBridge gets the real dragged item.</summary>
public static bool IsInstalled { get; private set; }
public static string StatusMessage { get; private set; } = "Not probed yet.";
public static void Initialize()
{
if (IsInstalled) return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
StatusMessage = "acclient.exe not available.";
return;
}
var inq = HookResolver.Resolve(text, "DragDrop.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoVa);
var start = HookResolver.Resolve(text, "DragDrop.StartDragandDrop", StartDragandDropPattern, StartDragandDropVa);
// A guessed address for either would mean calling or patching the wrong code: pattern hits only.
if (inq.Source != HookResolver.ResolveSource.PatternScan || start.Source != HookResolver.ResolveSource.PatternScan)
{
StatusMessage = $"drag-start hook skipped (InqDropIconInfo {inq.Detail}, StartDragandDrop {start.Detail}).";
RynthLog.Compat($"Compat: {StatusMessage}");
return;
}
try
{
_inqDropIconInfo = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)inq.Address;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> detour = &StartDragandDropDetour;
MinHook.Hook(start.Address, (IntPtr)detour, out _originalStartDrag);
IsInstalled = true;
StatusMessage = $"Hooked UIElementManager::StartDragandDrop @ 0x{start.Address.ToInt32():X8}.";
RynthLog.Info($"Compat: drag-start hook ready - StartDragandDrop=0x{start.Address.ToInt32():X8}, InqDropIconInfo=0x{inq.Address.ToInt32():X8}");
}
catch (Exception ex)
{
StatusMessage = ex.Message;
RynthLog.Compat($"Compat: drag-start hook failed - {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static byte StartDragandDropDetour(IntPtr manager, IntPtr element, int clickX, int clickY)
{
try
{
if (element != IntPtr.Zero && _inqDropIconInfo != null)
{
uint itemId = 0, spellId = 0, flags = 0;
_inqDropIconInfo(element, &itemId, &spellId, &flags);
// Spell-bar drags carry a spell id and no item.
if (itemId != 0)
{
if (_logCount < 20) { _logCount++; RynthLog.UI($"DragDropHooks: AC drag start item=0x{itemId:X8} flags=0x{flags:X}"); }
ItemDragBridge.OnNativeDragStart(itemId);
}
}
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: drag-start detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_originalStartDrag;
return original(manager, element, clickX, clickY);
}
}

View file

@ -168,7 +168,8 @@ internal static class HeartbeatLogger
string vpField = "";
try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); }
catch { }
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
// Unfiltered on purpose: it is the launcher's liveness signal (see RynthLog.Heartbeat).
RynthLog.Heartbeat($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
// Every 60 s: garbage collections and the time they paused the process.
// Under the CoreCLR host the engine and managed plugins share one GC, so a

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Outcome of the most recent <see cref="ClientHelperHooks.MergeStackInternal"/> request per
/// (source, target) pair, so a plugin can learn what happened on AC's main thread instead of
/// only "queued". Before this, a merge the engine skipped (target already full) or that AC
/// rejected looked identical to one in flight, and RynthAi's AutoStack waited 10 s per pair
/// and logged a "confirmed failure". Thread-safe; bounded.
/// </summary>
internal static class MergeStackResults
{
// ABI status codes (GetMergeStackResult return value). Never renumber.
public const int None = 0; // no request recorded for this pair (or it aged out)
public const int Queued = 1; // accepted onto the main-thread queue, not executed yet
public const int Sent = 2; // Event_StackableMerge sent for 'amount' units
public const int TargetFull = 3; // skipped: target stack already at max stack size
public const int Failed = 4; // invalid ids, merge API unavailable, AC returned 0, or threw
public const int QueueFull = 5; // main-thread queue full; request dropped before execution
private struct Entry { public int Status; public int Amount; public long TickMs; }
private const int MaxEntries = 512; // prune threshold
private const long PruneAgeMs = 120_000; // results older than this are dropped on prune
private static readonly object _lock = new();
private static readonly Dictionary<ulong, Entry> _results = new();
private static ulong Key(uint source, uint target) => ((ulong)source << 32) | target;
/// <summary>Records the latest outcome for a pair (replaces any earlier one).</summary>
public static void Record(uint source, uint target, int status, int amount = 0)
{
long now = Environment.TickCount64;
lock (_lock)
{
if (_results.Count >= MaxEntries)
Prune(now);
_results[Key(source, target)] = new Entry { Status = status, Amount = amount, TickMs = now };
}
}
/// <summary>Latest outcome for the pair, or <see cref="None"/>. <paramref name="amount"/>
/// is the unit count sent (Sent only) and <paramref name="ageMs"/> how long ago it was recorded.</summary>
public static int Get(uint source, uint target, out int amount, out int ageMs)
{
amount = 0;
ageMs = 0;
lock (_lock)
{
if (!_results.TryGetValue(Key(source, target), out Entry e))
return None;
amount = e.Amount;
long age = Environment.TickCount64 - e.TickMs;
ageMs = age > int.MaxValue ? int.MaxValue : (int)age;
return e.Status;
}
}
// Drops aged results; if everything is recent, clears the map (callers re-request anyway).
private static void Prune(long now)
{
List<ulong>? old = null;
foreach (var kv in _results)
if (now - kv.Value.TickMs > PruneAgeMs)
(old ??= new List<ulong>()).Add(kv.Key);
if (old == null)
{
_results.Clear();
return;
}
foreach (ulong k in old)
_results.Remove(k);
}
}

View file

@ -43,12 +43,24 @@ internal static class SehTrampoline
/// no managed callback / reverse-P/Invoke transition — so unlike the removed
/// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an
/// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack
/// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602
/// (RaiseFailFast) classes that bypass managed handlers. Observes only.
/// sweep (bounded by the thread's StackBase) to <paramref name="logPath"/> for FATAL
/// crashes only: unhandled exceptions (chained unhandled-exception filter), AVs in
/// NativeAOT code (which the runtime fail-fasts past every filter), and other
/// first-chance AVs only if the process dies shortly after. AVs caught by the SEH_*
/// wrappers and the logger's own faults are never written. Observes only.
/// </summary>
public static void InstallCrashLogger(string logPath)
{
try { _InstallCrashLogger(logPath); }
try
{
_InstallCrashLogger(logPath);
// v2+ logs fatal crashes only (unhandled-exception filter + NativeAOT-module AVs);
// v1 (no version export) logged every first-chance AV.
uint version = 1;
try { version = _SehTrampolineVersion(); }
catch (EntryPointNotFoundException) { }
RynthLog.Compat($"SehTrampoline: native crash logger installed (v{version}{(version >= 2 ? ", fatal-only" : ", logs every first-chance AV")}) -> {logPath}");
}
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
}
@ -104,6 +116,10 @@ internal static class SehTrampoline
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SehTrampolineVersion",
CallingConvention = CallingConvention.Cdecl)]
private static extern uint _SehTrampolineVersion();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _GetTagParserGuardAddress();

View file

@ -458,6 +458,11 @@ internal static class EndSceneHook
if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
}
// ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub)
// is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene;
// guarded internally, so an ImGui draw failure can't skip the original EndScene.
EngineFrameController.RenderDeferredImGui();
}
catch (Exception ex)
{

View file

@ -169,6 +169,7 @@ internal static class EngineLifecycle
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.

View file

@ -12,6 +12,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using System.Collections.Generic;
using ImGuiNET;
using RynthCore;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
@ -45,7 +46,21 @@ public static class EntryPoint
private static readonly Queue<string> RecentLogLines = new();
private static long _recentLogSeq;
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary>
internal enum EngineLogLevel
{
/// <summary>As a global threshold: nothing but errors. As a category level: never written.</summary>
Off = -1,
Error = 0,
Warning = 1,
Info = 2,
Debug = 3,
Trace = 4
}
/// <summary>Active engine logging threshold loaded from engine settings.</summary>
internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info;
/// <summary>Legacy convenience flag used by existing verbose call sites.</summary>
internal static bool VerboseLogging = false;
/// <summary>Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.</summary>
@ -190,8 +205,14 @@ public static class EntryPoint
}
catch { }
// engine.json "LoggingLevel" + "LogCategories" (launcher Logging card) set the threshold
// and per-category levels first so every line written below honours them. The watcher
// started later re-reads them whenever the launcher edits the file.
string logSummary = LogSettings.Reload();
// Set up the unified log sink BEFORE anything else so all
// subsequent failures are captured in C:\Games\RynthCore\Logs.
// subsequent failures are captured in <CoreDir>\Logs (installer-chosen;
// resolved here on the init worker, never under the loader lock).
LogPaths.EnsureLogDirectory();
if (_initCount <= 1)
{
@ -206,10 +227,18 @@ public static class EntryPoint
InstallManagedExceptionHandlers();
RynthLog.Info("================================================================");
RynthLog.Info($"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}");
RynthLog.Info($" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}");
RynthLog.Info("================================================================");
// The banner bypasses the category levels: it must be in every log, whatever engine.json says.
LogTagged("engine", "================================================================", "INF");
LogTagged("engine", $"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}", "INF");
LogTagged("engine", $" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}", "INF");
LogTagged("engine", $" logging {logSummary}", "INF");
LogTagged("engine", "================================================================", "INF");
string hiddenCategories = LogSettings.HiddenCategoriesWarning();
if (hiddenCategories.Length > 0) RynthLog.Warn(hiddenCategories);
// Live logging config: launcher edits to engine.json apply without a client restart.
// Stopped in EngineLifecycle.Shutdown before the module can be unloaded.
LogSettings.StartWatcher();
CrashLogger.Install();
@ -217,18 +246,10 @@ public static class EntryPoint
// logging AC's main-thread native stack when its EndScene beat stalls.
MainThreadHangWatchdog.Start();
// MultiClientHooks.Initialize installs MinHook detours synchronously
// here, BEFORE InitWorker spawns and runs the main PreloadNativeDll
// pass. If we don't preload minhook.x86.dll first, the P/Invoke
// into minhook fails with DllNotFoundException and the multi-
// client hook silently skips — which means AC's
// Client::IsAlreadyRunning check fires unpatched on the second-
// and-later concurrent acclient.exe processes.
string? earlyEngineDir = GetEngineDirectory();
if (!string.IsNullOrEmpty(earlyEngineDir))
PreloadNativeDll(earlyEngineDir, "minhook.x86.dll");
else
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
// MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves
// minhook.x86.dll before InitWorker runs, so preload it from the engine directory;
// otherwise Client::IsAlreadyRunning fires unpatched on second-and-later clients.
TryPreloadMinHookForEarlyInit();
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// Before AC's main thread resumes, so no dat or network unpack runs the stock
@ -339,6 +360,33 @@ public static class EntryPoint
return new string(buffer, 0, (int)length);
}
/// <summary>
/// Loads MinHook on the RynthCoreInit thread so <see cref="MultiClientHooks.Initialize"/> can
/// call <see cref="Hooking.MinHook"/> P/Invokes without relying on the default DLL search path
/// (which often resolves against the AC client directory, not <c>Runtime\</c>).
/// </summary>
private static void TryPreloadMinHookForEarlyInit()
{
try
{
string? engineDir = GetEngineDirectory();
if (string.IsNullOrEmpty(engineDir))
{
RynthLog.Info("Early MinHook preload skipped: could not resolve engine directory.");
return;
}
if (PreloadNativeDll(engineDir, "minhook.x86.dll"))
RynthLog.Verbose($"Early MinHook preload OK (engine dir: {engineDir})");
else
RynthLog.Info($"Early MinHook preload failed: minhook.x86.dll not found beside engine ({engineDir}).");
}
catch (Exception ex)
{
RynthLog.Info($"Early MinHook preload exception: {ex.Message}");
}
}
/// <summary>
/// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a
/// stable pointer inside the engine's own module image — used by
@ -695,6 +743,8 @@ public static class EntryPoint
Step("account hooks", AccountHooks.Initialize);
Step("client combat hooks", () => ClientCombatHooks.Probe());
Step("selected-target hooks", SelectedTargetHooks.Initialize);
// Which item AC is dragging (AC keeps the old selection during a drag).
Step("drag-start hook", DragDropHooks.Initialize);
Step("smartbox hooks", SmartBoxHooks.Initialize);
Step("player vitals hooks", PlayerVitalsHooks.Initialize);
Step("enchantment hooks", () => EnchantmentHooks.Initialize());
@ -1686,10 +1736,34 @@ public static class EntryPoint
internal static void LogVerbose(string message)
{
if (VerboseLogging)
if (ShouldLog(EngineLogLevel.Debug))
Log(message);
}
/// <summary>
/// True when a line at <paramref name="level"/> passes the global threshold. Off-level lines
/// never pass; an Off threshold blocks everything (errors bypass this gate).
/// </summary>
internal static bool ShouldLog(EngineLogLevel level)
=> level != EngineLogLevel.Off && level <= LoggingLevel;
/// <summary>Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.</summary>
internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
{
if (string.IsNullOrWhiteSpace(configuredLevel))
return EngineLogLevel.Info;
string normalized = configuredLevel.Trim();
if (string.Equals(normalized, "Verbose", StringComparison.OrdinalIgnoreCase))
return EngineLogLevel.Debug;
if (string.Equals(normalized, "Warn", StringComparison.OrdinalIgnoreCase))
return EngineLogLevel.Warning;
return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed)
? parsed
: EngineLogLevel.Info;
}
internal static string[] GetRecentLogLines()
{
lock (LogLock)

View file

@ -23,6 +23,7 @@ using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
using RynthCore.Install;
namespace RynthCore.Engine.ImGuiBackend;
@ -48,6 +49,9 @@ internal static class EngineFrameController
private static bool _imguiInitFailed;
private static bool _coreResolved;
private static bool _pluginsInitialized;
// Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each).
private static int _pluginInitContextWaits;
private const int PluginInitContextMaxWaits = 300;
private static IntPtr _context;
private static IntPtr _gameHwnd;
@ -61,6 +65,25 @@ internal static class EngineFrameController
/// </summary>
internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
// ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a
// log shows whether frames start, which branch runs and whether draw data is submitted.
private const long HeartbeatIntervalMs = 30_000;
private static long _engineErrorCount;
private static long _nextEngineErrorLogAt;
private static bool _loggedFirstSubmit;
private static int _loggedBranch = -1;
private static string _initFailStep = "unknown";
private static long _drawSubmits;
private static long _nextHeartbeatAt;
// Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the
// Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until
// the next NewFrame on the main context.
private static IntPtr _deferredSubmitDevice;
// Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit).
private static long _deferredUiTicks;
private static long _lastFrameTicks;
private static int _frameCount;
@ -103,7 +126,10 @@ internal static class EngineFrameController
return true;
if (!EnsureCore(pDevice))
{
_initFailStep = "EnsureCore (game window not found)";
return false;
}
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
@ -131,7 +157,7 @@ internal static class EngineFrameController
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
}
catch (Exception ex)
{
@ -155,10 +181,16 @@ internal static class EngineFrameController
ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd))
{
_initFailStep = "Win32Backend.Init";
return false;
}
if (!DX9Backend.InitImGui(pDevice))
{
_initFailStep = "DX9Backend.InitImGui";
return false;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
@ -229,6 +261,8 @@ internal static class EngineFrameController
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
// marker rendering, and plugin lifecycle stay alive when the ImGui
// surface is disabled.
// A frame that throws before its build must not resubmit last frame's draw data.
_deferredSubmitDevice = IntPtr.Zero;
try
{
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
@ -344,10 +378,10 @@ internal static class EngineFrameController
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and
// the vital HUD, so ImGui windows sit above both. The Avalonia quad
// (EndSceneHook, after this returns) stays topmost while both stacks
// run, matching input order: Avalonia gets the first hit test.
// The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which
// EndSceneHook calls after the Avalonia quad, so ImGui windows sit above
// the Nav3D fallback, the vital HUD and the Avalonia panels. Input order
// matches: Win32Backend gives ImGui the mouse while it wants it.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
@ -370,17 +404,33 @@ internal static class EngineFrameController
if (imguiEnabled)
{
long t0 = Stopwatch.GetTimestamp();
if (imguiBuilt)
SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
if (imguiBuilt)
{
_deferredUiTicks = ticks;
_deferredSubmitDevice = pDevice;
}
else
{
UiFrameStats.Record(ticks);
}
}
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
// An exception here skips everything after it this frame (including RunImGuiFrame), so
// the first one gets a stack trace; repeats are summarised every 30 s instead of per frame.
_engineErrorCount++;
long errNow = Environment.TickCount64;
if (_engineErrorCount == 1)
RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}");
else if (errNow >= _nextEngineErrorLogAt)
RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}");
if (errNow >= _nextEngineErrorLogAt)
_nextEngineErrorLogAt = errNow + HeartbeatIntervalMs;
}
finally
{
@ -442,14 +492,26 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks
try
{
// Plugins only get the ImGui context when they may draw with it
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
// don't need plugins to see it, and handing it over switched
// RynthAi into its legacy-ImGui setup (first ImGui-on test,
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
// Plugins only get the ImGui context when they may draw with it: the
// ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay
// windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item
// Info; RynthPluginRenderOverlay). RynthAi only reads the context for
// those windows, so this does not switch it into a legacy-ImGui setup.
bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell
|| (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend);
// _context is written by the render thread (Init); this is the pump thread.
IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero;
if (!_pluginsInitialized)
{
// The plugin host copies the context once at init, so wait for the
// render path's ImGui init (first ImGui frame) rather than hand over
// zero for the whole session. Bounded: a failed or stalled ImGui init
// must not hold plugins (and the bot) back.
if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed
&& ++_pluginInitContextWaits <= PluginInitContextMaxWaits)
return;
if (pluginsDraw && pluginContext == IntPtr.Zero)
RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session.");
_pluginsInitialized = true;
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
}
@ -501,9 +563,16 @@ internal static class EngineFrameController
if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
|| D3D9.VideoPatch.WantsBanner;
|| D3D9.VideoPatch.WantsBanner || PluginOverlayWindowsLive;
}
/// <summary>
/// In the world, with the shell off, and some loaded plugin exports
/// RynthPluginRenderOverlay: its windows need a frame every frame.
/// </summary>
private static bool PluginOverlayWindowsLive =>
PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins;
/// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed). Also off as soon as AC leaves the world screen
@ -544,7 +613,8 @@ internal static class EngineFrameController
}
private static bool HasImGuiContentNoRestore() =>
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner));
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner))
|| PluginOverlayWindowsLive;
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard.
@ -573,6 +643,7 @@ internal static class EngineFrameController
if (!Init(pDevice))
{
_imguiInitFailed = true;
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
return false;
}
}
@ -596,7 +667,6 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
bool frameEnded = false;
try
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
@ -644,6 +714,9 @@ internal static class EngineFrameController
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
// a payload the client's drop targets (Mini Remote slots) see this frame.
ItemDragBridge.SubmitMainFrame(io);
ImGuiTextFocus.BeginFrame();
if (_dropImGuiTextFocus)
{
@ -653,11 +726,29 @@ internal static class EngineFrameController
}
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
int branch;
if (Plugins.EngineSettings.EnableImGuiShell)
{
branch = 1;
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
else if (PluginOverlayWindowsLive)
{
branch = 2;
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
// plugins' full ImGui UIs.
PluginManager.RenderOverlayAll();
}
else
{
branch = 0;
}
if (branch != _loggedBranch)
{
_loggedBranch = branch;
RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}.");
}
if (PanelsLive)
{
// World overlays: built into UnderUiLayer's list, drawn next frame at
@ -744,6 +835,24 @@ internal static class EngineFrameController
_prevAvaloniaText = avaloniaText;
}
/// <summary>
/// Submits this frame's ImGui draw data. EndSceneHook calls it after
/// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer.
/// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is
/// a no-op when <see cref="OnEndScene"/> built nothing this frame. Never throws.
/// </summary>
public static void RenderDeferredImGui()
{
IntPtr device = _deferredSubmitDevice;
if (device == IntPtr.Zero)
return;
_deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws
long t0 = Stopwatch.GetTimestamp();
SubmitImGuiFrame(device);
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
private static void SubmitImGuiFrame(IntPtr pDevice)
{
@ -751,7 +860,15 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
_drawSubmits++;
if (!_loggedFirstSubmit)
{
_loggedFirstSubmit = true;
RynthLog.Info("EngineFrameController: first ImGui draw submitted.");
}
LogHeartbeatIfDue(drawData);
}
catch (Exception ex)
{
@ -763,6 +880,29 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the
/// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no
/// ImGui window was drawn that frame. One string per interval; no per-frame allocation.
/// </summary>
private static void LogHeartbeatIfDue(ImDrawDataPtr drawData)
{
long now = Environment.TickCount64;
if (now < _nextHeartbeatAt) return;
bool first = _nextHeartbeatAt == 0;
_nextHeartbeatAt = now + HeartbeatIntervalMs;
if (first) return; // first interval starts now; the first-frame line already covers t=0
int lists = 0, vertices = 0;
unsafe
{
// ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets).
byte* p = (byte*)drawData.NativePtr;
if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); }
}
RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}.");
}
internal static IntPtr FindGameWindow()
{
uint pid = GetCurrentProcessId();

View file

@ -67,6 +67,10 @@ internal sealed record PanelSpec(
// Where the panel first opens (logical units) when nothing is saved for its
// key; null = the cascade. (Script windows: a FirstUseEver position.)
Vector2? DefaultPos = null,
// With nothing saved and no DefaultPos: open centred in the game view rather
// than in the top-left cascade, where popped-out panels (separate windows
// above the game frame) usually sit and would hide it.
bool OpenCentered = false,
// No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow
// fits its height to what it shows). Chromeless and GripInBody panels only.
bool NoResize = false);
@ -651,6 +655,10 @@ internal static class ImGuiPanelHost
{
pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position)
}
else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered)
{
pos = centered;
}
else
{
int shown = 0;
@ -670,6 +678,104 @@ internal static class ImGuiPanelHost
entry.NeedsPlacement = true;
entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null;
entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize;
// Popped-out windows sit above the game frame, so a docked panel opening under
// one would be invisible. The new spot is saved by the open's Persist, so the
// panel comes back where it could be seen.
if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear)
{
RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " +
$"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0}).");
entry.Pos = clear;
entry.PersistedPos = clear;
entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows
}
}
/// <summary>Above this share of a docked panel hidden by popped-out windows, it opens elsewhere.</summary>
private const float MaxCoveredFraction = 0.5f;
/// <summary>Candidate spots per axis when looking for a clear place (a grid over the game view).</summary>
private const int ClearSpotSteps = 8;
/// <summary>
/// A spot (client px) for a docked window of <paramref name="size"/> at <paramref name="pos"/>
/// that popped-out windows hide less, nearest the original among the least-covered; null when
/// at most half of it is covered or no spot is better.
/// </summary>
private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size)
{
float area = size.X * size.Y;
if (area <= 0) return null;
List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient();
if (covers.Count == 0) return null;
float covered = CoveredArea(pos, size, covers);
if (covered <= area * MaxCoveredFraction) return null;
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1) return null;
Vector2 room = Vector2.Max(Vector2.Zero, display - size);
// Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within
// 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one.
float least = float.MaxValue;
for (int i = 0; i <= ClearSpotSteps; i++)
for (int j = 0; j <= ClearSpotSteps; j++)
least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers));
if (least >= covered) return null;
float tolerance = least + area * 0.02f;
Vector2? best = null;
float bestDist = float.MaxValue;
for (int i = 0; i <= ClearSpotSteps; i++)
for (int j = 0; j <= ClearSpotSteps; j++)
{
Vector2 spot = GridSpot(room, i, j);
if (CoveredArea(spot, size, covers) > tolerance) continue;
float dist = Vector2.DistanceSquared(spot, pos);
if (dist < bestDist) { bestDist = dist; best = spot; }
}
return best;
}
private static Vector2 GridSpot(Vector2 room, int i, int j) =>
new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps));
/// <summary>Visible popped-out windows' rects in the game window's client px (ImGui coordinates).</summary>
private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient()
{
Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen();
var rects = new List<(Vector2, Vector2)>();
foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects())
{
var min = new Vector2(left, top) - origin;
rects.Add((min, min + new Vector2(width, height)));
}
return rects;
}
/// <summary>Area of the window hidden by <paramref name="covers"/> (overlaps between covers count twice).</summary>
private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers)
{
Vector2 max = pos + size;
float total = 0;
foreach (var (cMin, cMax) in covers)
{
float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X);
float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y);
if (w > 0 && h > 0) total += w * h;
}
return total;
}
/// <summary>
/// Top-left (logical units) that centres a window of logical <paramref name="size"/> in the
/// game view; null while the display size isn't known yet.
/// </summary>
private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale)
{
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null;
return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f);
}
private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size)

View file

@ -0,0 +1,251 @@
// ============================================================================
// RynthCore.Engine - ImGui/ItemDragBridge.cs
// Carries an item drag into the MAIN ImGui context when it didn't start there,
// so drop targets in the client (RynthAi's Mini Remote slots) can take it:
//
// • A popped-out Inventory: the pop-out has its own ImGui context and holds
// mouse capture for the whole drag, so the main context never sees it.
// The pop-out face reports the dragged item (NotePopOutDrag); the main
// frame republishes it as an extern payload. The main context sees no
// button press, so the payload uses PayloadAutoExpire: it is delivered to
// the hovered target on the first frame it is no longer submitted.
// • AC's own inventory: a press that began on the game belongs to the game,
// and ImGui ignores hovering for it. DragDropHooks reports the item AC
// starts dragging (OnNativeDragStart); a carried one is republished the
// same way, under PayloadType, and delivered when ImGui sees the button go
// up. AC does not select the dragged item, so without that hook the bridge
// can only guess from the selection: the guess goes out under
// NativePayloadType, which targets treat as unreliable.
//
// A native drag released over an ImGui window would otherwise complete in AC
// as a drop on the 3D view (the item lands on the ground). TryRedirectNativeDrop
// moves that button-up back to where the drag began, which AC treats as
// putting the item back.
//
// Threads: AC's main thread only (game WndProc, EndScene, pop-out frames).
// ============================================================================
using System;
using System.Diagnostics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ItemDragBridge
{
/// <summary>Payload type for one item (uint object id). Must match RynthAi's MiniRemoteHud.ItemPayloadType.</summary>
public const string PayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Payload type for a game drag whose item was guessed from the selection (DragDropHooks not
/// installed). Any game left-drag with a carried item selected looks like this (moving an AC
/// panel too), so targets should take it only where a wrong item does no harm (RynthAi: empty
/// slots). Must match MiniRemoteHud.GameItemPayloadType.
/// </summary>
public const string NativePayloadType = "RYNTH_GAME_ITEM";
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
private const int MK_LBUTTON = 0x0001, MK_OTHER = 0x0002 | 0x0010 | 0x0020 | 0x0040;
/// <summary>Movement (px, squared) before a game press counts as a drag.</summary>
private const int DragThresholdSq = 5 * 5;
/// <summary>AC may select the pressed item a few messages after the press: keep re-reading it this long.</summary>
private static readonly long SelectionSettleTicks = Stopwatch.Frequency / 2;
/// <summary>A pop-out drag with no report for this long is over (the pop-out closed mid-drag).</summary>
private static readonly long PopOutStaleTicks = Stopwatch.Frequency;
// Popped-out Inventory drag.
private static uint _popOutItem;
private static long _popOutSeenAt;
// Native (AC inventory) drag.
private static bool _pressPending;
private static IntPtr _pressLParam;
private static int _pressX, _pressY;
private static long _pressAt;
private static uint _nativeItem;
/// <summary>_nativeItem came from AC's drag start (DragDropHooks), not from the selection.</summary>
private static bool _nativeFromHook;
/// <summary>The left button is down on a press that belongs to the game.</summary>
private static bool _gamePressHeld;
private static bool _nativeReleased;
/// <summary>The cursor was over an ImGui window in the last main frame (only tracked during a native drag).</summary>
private static bool _overImGui;
// ── Popped-out Inventory ────────────────────────────────────────────────
/// <summary>A popped-out Inventory is dragging <paramref name="itemId"/> (call every pop-out frame of the drag).</summary>
public static void NotePopOutDrag(uint itemId)
{
if (itemId == 0) return;
if (_popOutItem != itemId)
RynthLog.UI($"ItemDragBridge: pop-out drag 0x{itemId:X8} published to the client.");
_popOutItem = itemId;
_popOutSeenAt = Stopwatch.GetTimestamp();
}
/// <summary>The popped-out Inventory's drag ended (dropped or cancelled).</summary>
public static void EndPopOutDrag() => _popOutItem = 0;
// ── Native drag (game WndProc) ──────────────────────────────────────────
/// <summary>
/// Every game-window mouse message, after the backend decided who owns the held buttons.
/// <paramref name="gameOwned"/>: the current press began on the game, not on ImGui.
/// </summary>
public static void OnGameMouse(uint msg, IntPtr wParam, IntPtr lParam, bool gameOwned)
{
int keys = (int)((long)wParam & 0xFFFF);
switch (msg)
{
case WM_LBUTTONDOWN:
// Only a plain left press that belongs to the game can be an inventory drag.
_pressPending = gameOwned && (keys & MK_OTHER) == 0;
_pressLParam = lParam;
_pressX = LoWord(lParam);
_pressY = HiWord(lParam);
_pressAt = Stopwatch.GetTimestamp();
_gamePressHeld = _pressPending;
if (_pressPending) { _nativeItem = 0; _nativeFromHook = false; _nativeReleased = false; }
break;
case WM_MOUSEMOVE:
if ((keys & MK_LBUTTON) == 0)
{
// A release we never saw (outside the window): finish the drag.
_pressPending = false;
_gamePressHeld = false;
if (_nativeItem != 0) _nativeReleased = true;
break;
}
if (_pressPending)
{
int dx = LoWord(lParam) - _pressX, dy = HiWord(lParam) - _pressY;
if (dx * dx + dy * dy >= DragThresholdSq)
{
_pressPending = false;
// With the drag-start hook the real item arrives through OnNativeDragStart.
if (_nativeItem == 0 && !DragDropHooks.IsInstalled)
{
_nativeItem = CarriedSelection();
if (_nativeItem != 0)
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{_nativeItem:X8} (from the selection) published to ImGui.");
}
}
}
else if (_nativeItem != 0 && !_nativeFromHook && !_nativeReleased && Stopwatch.GetTimestamp() - _pressAt < SelectionSettleTicks)
{
// The selection can trail the press by a few messages: follow it while it settles.
uint sel = CarriedSelection();
if (sel != 0) _nativeItem = sel;
}
break;
case WM_LBUTTONUP:
_pressPending = false;
_gamePressHeld = false;
if (_nativeItem != 0) _nativeReleased = true;
break;
}
}
/// <summary>
/// AC started dragging <paramref name="itemId"/> (DragDropHooks, AC's main thread). Taken while
/// a game-owned left press is held and only for items the player carries.
/// </summary>
public static void OnNativeDragStart(uint itemId)
{
if (!_gamePressHeld || itemId == 0 || !IsCarried(itemId)) return;
_pressPending = false;
_nativeItem = itemId;
_nativeFromHook = true;
_nativeReleased = false;
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{itemId:X8} published to ImGui.");
}
/// <summary>
/// A native item drag is being released over an ImGui window: returns the press position
/// to send AC instead, so AC puts the item back rather than dropping it on the ground.
/// </summary>
public static bool TryRedirectNativeDrop(uint msg, out IntPtr pressLParam)
{
pressLParam = _pressLParam;
if (msg != WM_LBUTTONUP || _nativeItem == 0 || !_overImGui) return false;
RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window; AC gets the drop back at its start ({_pressX},{_pressY}).");
return true;
}
// ── Main frame (after ImGui.NewFrame, before any window) ────────────────
/// <summary>Republishes a pop-out or native drag in the main context for this frame.</summary>
public static void SubmitMainFrame(ImGuiIOPtr io)
{
uint id = 0;
string type = PayloadType;
if (_popOutItem != 0)
{
if (Stopwatch.GetTimestamp() - _popOutSeenAt > PopOutStaleTicks) _popOutItem = 0;
else id = _popOutItem;
}
if (id == 0 && _nativeItem != 0)
{
type = _nativeFromHook ? PayloadType : NativePayloadType;
// After the button-up, stop once ImGui itself sees the button up: that frame
// delivers the drop (the payload outlives its last submission by one frame).
if (_nativeReleased && !io.MouseDown[0])
{
_nativeItem = 0;
_nativeFromHook = false;
_nativeReleased = false;
_overImGui = false;
return;
}
id = _nativeItem;
_overImGui = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
}
if (id == 0) return;
const ImGuiDragDropFlags flags = ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip
| ImGuiDragDropFlags.PayloadAutoExpire;
if (ImGuiNET.ImGui.BeginDragDropSource(flags))
{
ImGuiNET.ImGui.SetDragDropPayload(type, (IntPtr)(&id), sizeof(uint));
ImGuiNET.ImGui.EndDragDropSource();
}
}
/// <summary>Forget every drag (focus lost, logout, engine shutdown).</summary>
public static void Reset()
{
_popOutItem = 0;
_pressPending = false;
_gamePressHeld = false;
_nativeItem = 0;
_nativeFromHook = false;
_nativeReleased = false;
_overImGui = false;
}
/// <summary>The game's selected object when the player carries it, else 0.</summary>
private static uint CarriedSelection()
{
uint id = ClientHelperHooks.GetSelectedItemId();
return IsCarried(id) ? id : 0;
}
/// <summary><paramref name="id"/> is in the player's pack, a side pack, or worn.</summary>
private static bool IsCarried(uint id)
{
if (id == 0 || !ClientHelperHooks.HasGetPlayerId) return false;
uint player = ClientHelperHooks.GetPlayerId();
if (player == 0 || id == player) return false;
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false;
if (wielder == player || container == player) return true;
// Side pack in the main pack.
return container != 0 && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == player;
}
private static int LoWord(IntPtr l) => unchecked((short)((long)l & 0xFFFF));
private static int HiWord(IntPtr l) => unchecked((short)(((long)l >> 16) & 0xFFFF));
}

View file

@ -138,6 +138,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute);
Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute);
}
DrawStandardFilters(rowW);
ImGuiNET.ImGui.PopStyleColor(2);
ImGuiNET.ImGui.EndChild();
@ -181,6 +182,58 @@ internal sealed class ChatFiltersFace : IImGuiPanel
edit?.Invoke(); // after drawing: the rows above drew from the old list
}
// ── Standard filters (RynthChatPresets) ──────────────────────────────
/// <summary>
/// The canned filters, by group: tick to hide, or pick a tab to move the lines there.
/// The router checks them after the rules, for lines no rule moved or hid.
/// </summary>
private void DrawStandardFilters(float rowW)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (!ImGuiNET.ImGui.CollapsingHeader("Standard filters##std")) return;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Label("Checked after the rules above, only for lines no rule moved or hid.", Mute);
Label("Tick to hide the lines; pick a tab to move them there instead.", Mute);
ImGuiNET.ImGui.PopFont();
foreach (string group in UI.Panels.RynthChatPresets.Groups)
{
int on = 0, total = 0;
foreach (var p in UI.Panels.RynthChatPresets.All)
if (p.Group == group) { total++; if (p.Enabled) on++; }
if (!ImGuiNET.ImGui.TreeNode($"{group} ({on}/{total})###grp_{group}")) continue;
foreach (var p in UI.Panels.RynthChatPresets.All)
{
if (p.Group != group) continue;
ImGuiNET.ImGui.PushID(p.Id);
bool enabled = p.Enabled;
if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); }
ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example);
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f));
string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret;
if (ImGuiNET.ImGui.SmallButton(tabText))
OpenPresetTabPicker(p, new Vector2(ImGuiNET.ImGui.GetItemRectMin().X, ImGuiNET.ImGui.GetItemRectMax().Y + 2));
ImGuiNET.ImGui.SetItemTooltip("Where its lines go: hidden, or moved to a tab");
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.TreePop();
}
}
private void OpenPresetTabPicker(UI.Panels.RynthChatPresets.Preset preset, Vector2 below)
{
string[] tabs = ChatModel.TargetTabs();
var items = new string[tabs.Length + 1];
items[0] = "Hide";
Array.Copy(tabs, 0, items, 1, tabs.Length);
int selected = preset.Tab.Length == 0 ? 0 : Math.Max(0, Array.FindIndex(tabs, t => string.Equals(t, preset.Tab, StringComparison.OrdinalIgnoreCase)) + 1);
_picker.Open(below, items, selected, k =>
{
preset.Tab = k <= 0 ? "" : items[k];
ChatModel.FiltersChanged();
}, 160);
}
private void Flash(string message)
{
_flash = message;
@ -548,7 +601,12 @@ internal sealed class ChatFiltersFace : IImGuiPanel
var trace = new List<ChatRouter.Step>();
ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace);
foreach (ChatRouter.Step step in trace)
_testResult.Add(((step.Rule < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text));
_testResult.Add((step.Rule switch
{
ChatRouter.StandardFilterStep => "Standard",
< 0 => "Your name",
_ => $"Rule {step.Rule + 1}",
} + ": " + step.What, Text));
if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute)));
string where;

View file

@ -10,8 +10,8 @@
//
// The mechanics live here (tabs, slide, side, placement, the one window);
// each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files and
// Patrol (RynthAiFace.Drawers.cs).
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files,
// Patrol and Mini Remote (RynthAiFace.Drawers.cs).
//
// A top-level ImGui window of its own, begun from inside the dashboard's Draw
// and placed against the dashboard's window every frame, so it follows the

View file

@ -44,7 +44,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
{
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true),
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true),
() => new DungeonMapFace());
}

View file

@ -813,7 +813,7 @@ internal sealed partial class InventoryFace
_hover = it;
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_selected = it.Id;
SelectItem(it);
_pressItem = it;
_pressAt = ImGuiNET.ImGui.GetMousePos();
}

View file

@ -130,6 +130,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventoryModel.Hover(0);
InventoryModel.Unsubscribe();
_dragItem = _pressItem = null;
ItemDragBridge.EndPopOutDrag();
UiDropTargets.EngineDragObject = 0;
_lootAdd.Cancel();
}
@ -538,7 +539,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_selected = hot.Id;
SelectItem(hot);
_pressItem = hot;
_pressAt = mouse;
}
@ -838,6 +839,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
_dragItem = null;
_pressItem = null;
if (item == null) return;
ItemDragBridge.EndPopOutDrag();
Vector2 m = ImGuiNET.ImGui.GetMousePos();
foreach (Target t in _targets)
{
@ -852,13 +854,50 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
private void DrawDragGhost()
/// <summary>
/// ImGui drag-and-drop payload type for one item (uint object id), published while an item is
/// dragged so other ImGui windows (RynthAi's Mini Remote slots) can accept the drop. Must
/// match MiniRemoteHud.ItemPayloadType in RynthAi.
/// </summary>
public const string ItemPayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Selects <paramref name="it"/> here and in the game, like a click in the retail inventory, so
/// "selected item" features (Mini Remote slots, item info, loot rules) see it too.
/// </summary>
private void SelectItem(InventoryItem it)
{
_selected = it.Id;
// Queued, not called inline: Draw runs inside EndScene, and AC's SetSelectedObject rebuilds
// UI elements, so it runs at the main-thread queue's drain point instead.
if (ClientHelperHooks.GetSelectedItemId() != it.Id)
AcMainThreadQueue.EnqueueSetSelectedObject(it.Id);
}
private unsafe void DrawDragGhost()
{
if (_dragItem == null) return;
var fg = ImGuiNET.ImGui.GetForegroundDrawList();
Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f);
DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF);
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
// A popped-out Inventory draws in its own ImGui context: the client's drop targets
// only see the drag through the bridge, which republishes it in the main context.
if (ImGuiPopOuts.InPopOutFrame)
{
ItemDragBridge.NotePopOutDrag(_dragItem.Id);
return;
}
// Re-submitted every frame of the drag (an extern source expires when it isn't); the
// ghost above is the preview, so no ImGui tooltip.
if (ImGuiNET.ImGui.BeginDragDropSource(ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip))
{
uint id = _dragItem.Id;
ImGuiNET.ImGui.SetDragDropPayload(ItemPayloadType, (IntPtr)(&id), sizeof(uint));
ImGuiNET.ImGui.EndDragDropSource();
}
}
// ── Tooltip ─────────────────────────────────────────────────────────
@ -985,6 +1024,11 @@ internal sealed partial class InventoryFace : IImGuiPanel
_lootAdd.Open(it.Id, it.Name, toOpenProfile: false);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)");
if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD"))
UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)");
if (!it.IsPack) MiniRemoteMenu(it);
if (!idle)
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
}
@ -995,6 +1039,36 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
/// <summary>RynthAi Mini Remote quick-use grid size (HudState.MiniRemoteSlotCount, 6 rows of 5).</summary>
private const int MiniRemoteSlots = 30, MiniRemoteColumns = 5;
/// <summary>
/// "Add to Mini Remote" submenu: first empty slot, or a numbered grid laid out like the
/// remote's own slots. RynthAi validates the item and reports the result in chat.
/// </summary>
private static void MiniRemoteMenu(InventoryItem it)
{
if (!ImGuiNET.ImGui.BeginMenu("Add to Mini Remote")) return;
if (ImGuiNET.ImGui.MenuItem("First empty slot"))
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", "first " + it.Id.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextDisabled("Or pick a slot (replaces what's there):");
for (int i = 0; i < MiniRemoteSlots; i++)
{
if (i % MiniRemoteColumns != 0) ImGuiNET.ImGui.SameLine();
string label = (i + 1).ToString("00", CultureInfo.InvariantCulture);
if (ImGuiNET.ImGui.Button(label, new Vector2(28, 0)))
{
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot",
(i + 1).ToString(CultureInfo.InvariantCulture) + " " + it.Id.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.CloseCurrentPopup();
}
}
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextDisabled("Tip: you can also drag the item onto a slot.");
ImGuiNET.ImGui.EndMenu();
}
// ── Split dialog ────────────────────────────────────────────────────
private void SplitDialog(InventoryView view)

View file

@ -1,21 +1,28 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/NavFace.cs
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) /
// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav
// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as
// Settings > Navigation), and the waypoint list (click selects the insert
// point, X deletes, => marks the active one).
// Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay
// toggles, Add Waypoint / Portal (selected object) /
// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
// delete / set active / move here on the selection; nearest, reverse, snap to
// path, point at selection, pause, simplify; recording and trail -> route),
// a chat waypoint, Save As, the nav file picker, the nav point reach
// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
// sets active, right-click edits, X or Delete deletes, => marks the active one).
//
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
// copy at once; the plugin applies commands immediately, so the next
// snapshot (requested right after) replaces the copy. The reach row reads
// UiSources.Settings and saves through SettingsCommands, like the Settings face.
// snapshot (requested right after) replaces the copy. Edits send indices into
// the route this face shows, so the selection is remapped locally as the copy
// changes. The reach row reads UiSources.Settings and saves through
// SettingsCommands, like the Settings face.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
@ -28,7 +35,7 @@ internal sealed class NavFace : IImGuiPanel
public const string Title = "Nav";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true),
new PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true),
() => new NavFace());
private static readonly string[] Actions =
@ -38,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel
};
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
// Route editor rows. Edit acts on the selected waypoints; Tools on the route.
private static readonly string[] EditActions =
{
PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate",
PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here",
};
private static readonly string[] ToolActions =
{
PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
};
private static readonly string[] RowMenu =
{ "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail...";
private readonly bool[] _editEnabled = new bool[6];
private NavPayload _data = new();
private long _seenVersion = -1;
private readonly List<string> _pointText = new();
private int _selected = -1, _addMode;
// _selected is the focus row (insert point, chat editing); _multi is every selected row,
// always containing _selected when it is set. _anchor starts Shift-click ranges.
private int _selected = -1, _anchor = -1, _addMode;
private readonly HashSet<int> _multi = new();
private bool _typing;
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
private string _fileLabel = "Select nav file...";
@ -130,13 +155,32 @@ internal sealed class NavFace : IImGuiPanel
});
NextLine(p, 26);
// Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character)
p = ImGuiNET.ImGui.GetCursorScreenPos();
if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half,
"Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it."))
{
bool on = !_data.TrackBreadcrumbs;
NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on });
_data.TrackBreadcrumbs = on;
}
if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half,
"Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."))
{
bool on = !_data.ShowRouteOverlay;
NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on });
_data.ShowRouteOverlay = on;
}
NextLine(p, 26);
typing |= ReachRow(w);
// Actions
int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled);
int action = WrapButtons("nav_act", Actions, w, 24);
switch (action)
{
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", AddMode = _addMode, InsertAt = _selected }); break;
case 2:
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
@ -144,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel
case 3:
NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
_data.Points.Clear();
_selected = -1;
ClearSelection();
RebuildPointText();
break;
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
}
RouteEditor(w);
// Chat waypoint: sent as if typed when the route reaches it. Selecting an
// existing chat waypoint loads its command here; Update saves the edit.
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
@ -230,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false)
&& (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused()))
DeleteSelected();
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
@ -239,6 +288,18 @@ internal sealed class NavFace : IImGuiPanel
_picker.Draw();
}
/// <summary>
/// A checkbox-style toggle button: ticked box and teal text when on, empty box and muted
/// text when off. Returns true when clicked (the caller flips the value).
/// </summary>
private static bool OverlayToggle(string id, string label, bool on, Vector2 pos, float width, string tooltip)
{
string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label;
bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip);
return clicked;
}
/// <summary>
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
@ -303,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22;
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
bool active = i == _data.ActiveNavIndex, selected = i == _selected;
bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i);
ImGuiNET.ImGui.PushID(i);
// Row click selects (drawn first so the X button on top wins).
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i;
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i);
if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
SetActive(i);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
if (!selected) SelectOnly(i);
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140);
}
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
{
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
if (_selected == i) _selected = -1;
else if (_selected > i) _selected--;
_data.Points.RemoveAt(i);
RebuildPointText();
RemoveLocal(new HashSet<int> { i });
ImGuiNET.ImGui.PopID();
return;
}
@ -331,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel
}
}
/// <summary>
/// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle
/// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause,
/// simplify, trail) double as the confirmation for edits that can't be undone.
/// </summary>
private void RouteEditor(float w)
{
int n = _multi.Count, count = _data.Points.Count;
bool one = n == 1 && _selected >= 0;
_editEnabled[0] = n > 0 && _multi.Min() > 0;
_editEnabled[1] = n > 0 && _multi.Max() < count - 1;
_editEnabled[2] = _editEnabled[3] = n > 0;
_editEnabled[4] = _editEnabled[5] = one;
Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute);
switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled))
{
case 0: MoveSelected(-1); break;
case 1: MoveSelected(+1); break;
case 2: DuplicateSelected(); break;
case 3: DeleteSelected(); break;
case 4: SetActive(_selected); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
}
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
switch (WrapButtons("nav_tools", ToolActions, w, 22))
{
case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break;
case 1:
if (count < 2) break;
NavCommands.Send(new NavCmd { Cmd = "reverseRoute" });
ReverseLocal();
break;
case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break;
case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break;
case 4:
_picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd
{ Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140);
break;
case 5:
_picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
break;
}
// Record | Route from Trail...
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) / 2;
if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half,
"Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route."))
{
bool on = !_data.IsRecording;
NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on });
_data.IsRecording = on;
}
Vector2 tp = new(p.X + half + 4, p.Y);
if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
_picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2
? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."
: "Turn on Breadcrumbs and walk a while to build a trail.");
NextLine(p, 26);
if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber);
}
/// <summary>Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.</summary>
private void ClickRow(int i)
{
var io = ImGuiNET.ImGui.GetIO();
if (io.KeyShift && _anchor >= 0)
{
if (!io.KeyCtrl) _multi.Clear();
for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k);
_selected = i;
}
else if (io.KeyCtrl)
{
if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; }
else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1;
_anchor = i;
}
else SelectOnly(i);
}
private void SelectOnly(int i)
{
_multi.Clear();
_multi.Add(i);
_selected = _anchor = i;
}
private void ClearSelection()
{
_multi.Clear();
_selected = _anchor = -1;
}
private List<int> SelectedIndices()
{
var list = new List<int>(_multi);
list.Sort();
return list;
}
private void RowMenuPick(int item)
{
switch (item)
{
case 0: if (_selected >= 0) SetActive(_selected); break;
case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
case 2: MoveSelected(-1); break;
case 3: MoveSelected(+1); break;
case 4: DuplicateSelected(); break;
case 5: DeleteSelected(); break;
}
}
private void SetActive(int i)
{
if (i < 0 || i >= _data.Points.Count) return;
NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
_data.ActiveNavIndex = i;
}
/// <summary>Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).</summary>
private void MoveSelected(int delta)
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta });
var pts = _data.Points;
var sel = new HashSet<NavPoint>();
foreach (int i in _multi) sel.Add(pts[i]);
NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null;
if (delta < 0)
{
for (int i = 1; i < pts.Count; i++)
if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]);
}
else
{
for (int i = pts.Count - 2; i >= 0; i--)
if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]);
}
_multi.Clear();
for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i);
_selected = focus != null ? pts.IndexOf(focus) : -1;
_anchor = anchor != null ? pts.IndexOf(anchor) : _selected;
RebuildPointText();
}
/// <summary>Each selected row gets a copy right after it (as the plugin does); the copies end up selected.</summary>
private void DuplicateSelected()
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() });
var result = new List<NavPoint>(_data.Points.Count + _multi.Count);
var copies = new HashSet<int>();
for (int i = 0; i < _data.Points.Count; i++)
{
NavPoint pt = _data.Points[i];
result.Add(pt);
if (!_multi.Contains(i)) continue;
copies.Add(result.Count);
result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z });
}
_data.Points = result;
_multi.Clear();
_multi.UnionWith(copies);
_selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1;
RebuildPointText();
}
private void DeleteSelected()
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() });
RemoveLocal(new HashSet<int>(_multi));
}
/// <summary>Drops rows from the local copy and shifts the selection past them.</summary>
private void RemoveLocal(HashSet<int> removed)
{
int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; }
var keep = new List<int>();
foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i));
_selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1;
_anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected;
_multi.Clear();
_multi.UnionWith(keep);
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i);
RebuildPointText();
}
private void ReverseLocal()
{
int last = _data.Points.Count - 1;
_data.Points.Reverse();
var flipped = new List<int>();
foreach (int i in _multi) flipped.Add(last - i);
_multi.Clear();
_multi.UnionWith(flipped);
if (_selected >= 0) _selected = last - _selected;
if (_anchor >= 0) _anchor = last - _anchor;
RebuildPointText();
}
private void TakeSnapshot()
{
var snap = UiSources.Nav.Current;
@ -338,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel
_seenVersion = snap.Version;
_data = snap.Value.Clone();
_navFiles = _data.NavFiles.ToArray();
if (_selected >= _data.Points.Count) _selected = -1;
int count = _data.Points.Count;
_multi.RemoveWhere(i => i >= count);
if (_selected >= count) _selected = -1;
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
if (_anchor >= count) _anchor = _selected;
RebuildPointText();
UpdateLabels();
}

View file

@ -12,12 +12,19 @@
// recorded hazards and the saved routes. Was the Patrol
// launcher's right-click popup; right-click now opens this
// drawer (popped out: still the popup).
// Mini Remote RynthAi's Mini Remote (session rates, target, summon,
// item slots, toggles, bank, rebuff, Translate, Guardian)
// with its Options menu. The plugin draws it here through
// RynthPluginRenderEmbed("miniremote") and says how big it
// wants the panel; the Hub launcher's right-click opens it
// (popped out: the floating Mini Remote instead).
// AC thread only (inside the dashboard's Draw).
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
@ -25,7 +32,7 @@ namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class RynthAiFace
{
/// <summary>Meta state, bot activity and the four file pickers.</summary>
/// <summary>Meta state, bot activity and the five file pickers.</summary>
private sealed class FilesDrawer : DashboardDrawer
{
private readonly RynthAiFace _face;
@ -40,9 +47,10 @@ internal sealed partial class RynthAiFace
public override string TabTooltip(bool right)
{
RynthAiView? v = _face._view;
return "Loaded files: the Profile, Nav, Loot and Meta pickers, meta state and bot activity.\n" +
return "Loaded files: the Profile, Nav, Loot, Meta and Buffs pickers, meta state and bot activity.\n" +
"Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") +
"\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") +
"\nBuffs: " + (v?.BuffText ?? "Built-in") +
(right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out.");
}
@ -50,7 +58,7 @@ internal sealed partial class RynthAiFace
public override float Width(float k) => 230 * k;
public override float Height(float k) =>
(Pad + TitleH + 4 + 2 * LineH + 6) * k + 4 * SelRow + 3 * SelGap + Pad * k;
(Pad + TitleH + 4 + 2 * LineH + 6) * k + 5 * SelRow + 4 * SelGap + Pad * k;
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{
@ -76,6 +84,8 @@ internal sealed partial class RynthAiFace
_face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw);
y += SelRow + SelGap;
_face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null);
y += SelRow + SelGap;
_face.Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, x, y, w, null, spellsButton: true);
}
private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value)
@ -136,4 +146,81 @@ internal sealed partial class RynthAiFace
finally { ImGuiNET.ImGui.EndChild(); }
}
}
/// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click).</summary>
private sealed class RemoteDrawer : DashboardDrawer
{
/// <summary>The plugin surface name, NUL-terminated for the export.</summary>
private static ReadOnlySpan<byte> Surface => "miniremote\0"u8;
// Content bounds in unscaled pixels; the plugin's wish is clamped to them.
private const float MinW = 200, MaxW = 760, MinH = 60, DefaultH = 120;
/// <summary>The content size the plugin last asked for (pixels); zero until it has drawn here.</summary>
private Vector2 _want;
public override string Key => "remote";
public override string Icon => PhosphorIcons.SquaresFour;
public override string Name => "Mini Remote drawer";
public override bool SavedOpen => RynthAiDashboardState.RemoteOpen;
public override void SaveOpen(bool open) => RynthAiDashboardState.SetRemoteOpen(open);
public override string TabTooltip(bool right) =>
"Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" +
"Its Options button picks the sections and opens the ILT Hub windows (also: right-click Hub).\n" +
(right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out.");
public override float Width(float k) =>
Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k;
public override float Height(float k)
{
float frame = (Pad + TitleH + 4 + Pad) * k;
// Never taller than the screen: the body scrolls instead.
float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y;
float maxBody = screen > 1 ? MathF.Max(MinH * k, screen - frame - 8 * k) : 900 * k;
return frame + Math.Clamp(_want.Y > 0 ? _want.Y : DefaultH * k, MinH * k, maxBody);
}
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{
float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SquaresFour, "MINI REMOTE", null, "Hide the Mini Remote drawer");
float x = origin.X + Pad * k;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y));
Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = ImGuiNET.ImGui.BeginChild("##remote_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
ImGuiNET.ImGui.PopStyleVar();
try
{
if (!open) return;
// The plugin's widgets use the default UI font, as in its floating Mini Remote.
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
int result = PluginManager.RenderEmbed("RynthAi", Surface, size, out Vector2 want);
if (result == PluginManager.EmbedDrawn)
{
if (want.X > 0 && want.Y > 0) _want = want;
}
else
{
_want = Vector2.Zero;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute);
ImGuiNET.ImGui.TextWrapped(result switch
{
PluginManager.EmbedNoPlugin =>
"This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.",
PluginManager.EmbedFailed =>
"The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.",
_ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).",
});
ImGuiNET.ImGui.PopStyleColor();
}
}
finally { ImGuiNET.ImGui.PopFont(); }
}
finally { ImGuiNET.ImGui.EndChild(); }
}
}
}

View file

@ -18,7 +18,7 @@
// the buttons above it.
// drawers tabs on the left edge (DashboardDrawers.cs), one open at a
// time, a window of their own beside the dashboard: Ranges
// (RangesSlideOut.cs), Loaded files and Patrol
// (RangesSlideOut.cs), Loaded files, Patrol and Mini Remote
// (RynthAiFace.Drawers.cs). Everything that slides out goes
// left; only the bars stay at the bottom (Tom 2026-10-05).
// Minimized keeps the title row, the control row and the bars. The window's
@ -76,13 +76,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel
// The drawers on the dashboard's left edge (their own window, placed against this one).
private readonly DashboardDrawers _drawers;
private readonly PatrolDrawer _patrol = new();
private readonly RemoteDrawer _remote = new();
// This frame's data, for the drawers.
private RynthAiView? _view;
private RynthAiSnapshot _raw = Empty;
// Picker toggle: ImGui closes a popup on the press outside it, so remember
// whether it was showing when the selector press began (a second click closes).
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 };
private readonly bool[] _pressedWhileOpen = new bool[4];
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10, -10 };
private readonly bool[] _pressedWhileOpen = new bool[5];
// The content's height (logical units, body padding included), measured each
// frame: the window's minimum height. _fit: resize the window to it once.
private float _contentHeight;
@ -92,7 +93,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
public RynthAiFace()
{
// Tab order top to bottom; the first one saved open wins at load.
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol);
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote);
}
public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight
@ -145,6 +146,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
}
Bars(view, raw, x0, width, boxBg);
PatrolPopup();
CharMenu();
MeasureAndFit(start.Y);
// Last: a window of its own, placed against this one's rect (hidden popped out).
_drawers.Draw();
@ -248,7 +250,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH));
}
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ──
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta/Buffs pickers (60%) ──
private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width)
{
@ -266,7 +268,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle");
float leftBottom = ly + 2 * (f10.FontSize + 1);
// Right: four selector rows (label 36 px, picker fills, spacing 3).
// Right: five selector rows (label 36 px, picker fills, spacing 3).
float rx = x0 + leftW, rw = width - leftW, ry = y0;
// The fold arrow sits at the end of the Profile row, where it always fits.
const float foldW = 18f;
@ -280,23 +282,39 @@ internal sealed partial class RynthAiFace : IImGuiPanel
Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw);
ry += 16 + 3;
Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null);
ry += 16 + 3;
Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, rx, ry, rw, null, spellsButton: true);
ry += 16;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4));
}
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" };
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" };
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta", "##sel_buff" };
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta", "##pick_buff" };
private static readonly string[] NoneItems = { "None" };
/// <summary>
/// One file picker row. <paramref name="kind"/> is RynthPluginSelectProfile's list (0 nav,
/// 1 loot, 2 meta, 3 settings profile, 4 buff profile). <paramref name="lootEdit"/> adds the
/// Loot Editor button, <paramref name="spellsButton"/> the RynthAi Spells window button.
/// </summary>
private void Selector(int slot, string label, string text, string[] items, int selected, int kind,
float x, float y, float w, RynthAiSnapshot? lootEdit)
float x, float y, float w, RynthAiSnapshot? lootEdit, bool spellsButton = false)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9);
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label);
float editW = 0;
if (spellsButton)
{
editW = 18;
var ep = new Vector2(x + w - editW, y);
if (IconButton("##buff_spells", ep, new Vector2(editW, 16), PhosphorIcons.Sparkle, UiFont.Dash11, SelectorBg, Mute, 0, 2))
RynthAiCommands.ApplyRemoteCommand("spells", "toggle");
ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: browse the spell list and build buff profiles.");
editW += 3;
}
if (lootEdit != null)
{
editW = 18;
@ -431,7 +449,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel
RynthAiDashboardState.SetFilesOpen(true);
ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") +
"\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") +
"\n\nClick to show the Profile, Nav, Loot and Meta pickers.");
"\nBuffs: " + (view?.BuffText ?? "Built-in") +
"\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers.");
}
// What the bot is doing, always in view (every mode, minimized too): between the toggles and FR.
@ -477,7 +496,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private void Launchers(float x0, float width)
{
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
const int buttons = 8;
const int buttons = 10;
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
// Short labels only when every button has room for its icon and label.
bool labels = bw >= 68;
@ -516,6 +535,32 @@ internal sealed partial class RynthAiFace : IImGuiPanel
}
else _drawers.Toggle(_patrol);
}
x += bw + LauncherGap;
// Char and Hub open RynthAi's own ImGui overlay windows (Mini Remote, which is the ILT
// Hub, its section windows, Inventory HUDs). They draw only when the engine hands plugins
// its ImGui context.
Launcher("##l_char", PhosphorIcons.User, "Char",
"Char. Left-click: ILT Hub / Mini Remote (/ra hub show). Right-click: Hub windows, Progression (Skills panel).",
x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("hub", "show"));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
ImGuiNET.ImGui.OpenPopup("##charmenu");
}
x += bw + LauncherGap;
// Right-click is the Mini Remote drawer, as Patrol's is its drawer; popped out there are
// no drawers, so it shows the floating Mini Remote. Inventory HUDs setup is in the
// Mini Remote's Options menu.
Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub",
popped ? "Hub. Left-click: floating Mini Remote (/ra remote). Right-click: show the floating Mini Remote."
: "Hub. Left-click: floating Mini Remote (/ra remote). Right-click: the Mini Remote drawer (left), with its Options.",
x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("remote", "toggle"));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
if (popped) RynthAiCommands.ApplyRemoteCommand("remote", "show");
else _drawers.Toggle(_remote);
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
}
@ -708,6 +753,46 @@ internal sealed partial class RynthAiFace : IImGuiPanel
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
}
// ── Char menu (right-click Char): RynthAi's character windows ──────────
/// <summary>ILT Hub section windows: menu label and the "/ra hub open" section name RynthAi parses.</summary>
private static readonly (string Label, string Section)[] HubSections =
{
("Character", "character"), ("Quests", "quests"), ("Pets", "pets"),
("Banking", "banking"), ("Gear", "gear"), ("Games", "games"), ("Guardian", "guardian"),
};
private static void CharMenu()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
bool open = ImGuiNET.ImGui.BeginPopup("##charmenu");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
// The Mini Remote is the ILT Hub; each former Hub tab is its own window (toggled).
if (ImGuiNET.ImGui.MenuItem("Mini Remote (ILT Hub)", "/ra hub"))
RynthAiCommands.ApplyRemoteCommand("hub", "toggle");
ImGuiNET.ImGui.Separator();
foreach ((string label, string section) in HubSections)
{
if (ImGuiNET.ImGui.MenuItem(label, "/ra hub open " + section))
RynthAiCommands.ApplyRemoteCommand("hub", "open " + section + " toggle");
}
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Progression (Skills panel)"))
SkillsFace.ShowProgression();
ImGuiNET.ImGui.SetItemTooltip("XP planner, augmentations and enlightenment (ILT worlds)");
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
// ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ──
private void PatrolPopup()

View file

@ -53,14 +53,27 @@ internal sealed class SettingsFace : IImGuiPanel
public bool Active; // the box had keyboard focus last frame
}
private readonly Dictionary<SettingRow, NumberEdit> _edits = new();
// Text rows being typed in (the saved value shows again once the box loses focus).
private readonly Dictionary<SettingRow, string> _textEdits = new();
/// <summary>Extra sidebar tab after the schema tabs; drawn from UiSources.Charms, not settings rows.</summary>
private const string CharmsTabName = "Charms Tracking";
private static int CharmsTab => SettingsSchema.Tabs.Length;
private const string CharmsHeader = "Advanced Settings > " + CharmsTabName;
public void OnShown()
{
UiSources.Settings.Subscribe();
UiSources.Settings.RequestRefresh();
UiSources.Charms.Subscribe();
UiSources.Charms.RequestRefresh();
}
public void OnHidden() => UiSources.Settings.Unsubscribe();
public void OnHidden()
{
UiSources.Settings.Unsubscribe();
UiSources.Charms.Unsubscribe();
}
public void Draw()
{
@ -100,9 +113,9 @@ internal sealed class SettingsFace : IImGuiPanel
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
SettingsTab[] tabs = SettingsSchema.Tabs;
for (int i = 0; i < tabs.Length; i++)
for (int i = 0; i <= tabs.Length; i++)
{
string tabName = tabs[i].Name;
string tabName = i < tabs.Length ? tabs[i].Name : CharmsTabName;
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushID(i);
@ -154,14 +167,23 @@ internal sealed class SettingsFace : IImGuiPanel
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
if (_tab >= SettingsSchema.Tabs.Length) _tab = 0;
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]);
if (_tab > CharmsTab) _tab = 0;
bool charms = _tab == CharmsTab;
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), charms ? CharmsHeader : Headers[_tab]);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (charms)
{
CharmsTabContent(w);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.EndChild();
return;
}
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
for (int i = 0; i < rows.Length; i++)
{
@ -189,9 +211,132 @@ internal sealed class SettingsFace : IImGuiPanel
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
case SettingKind.Note: Note(row.Label, w); break;
case SettingKind.CraftingStatus: CraftingStatus(row); break;
case SettingKind.Button: ButtonRow(row, w); break;
case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break;
case SettingKind.Text: TextRow(row, w); break;
case SettingKind.Status: StatusRow(row, w); break;
}
}
// [All on] [All off] [ILT Hub on], then a 3-column grid of square toggles, one per
// RynthAi trace category. Edits the copy's DiagCategories and saves like any other row.
private void TraceCategoriesRow(SettingRow row, float w)
{
var cats = TraceCategoryLevels.Parse(_data.DiagCategories);
if (cats.Count == 0)
{
Note("Waiting for RynthAi...", w);
return;
}
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true));
ImGuiNET.ImGui.SameLine(0, 6);
if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false));
ImGuiNET.ImGui.SameLine(0, 6);
if (ImGuiNET.ImGui.Button("ILT Hub on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt"));
Tooltip(row);
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float colW = Math.Max(80f, w / 3f);
int perRow = Math.Max(1, (int)(w / colW));
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
for (int i = 0; i < cats.Count; i++)
{
var (name, level) = cats[i];
bool on = level != TraceCategoryLevels.Off;
string label = TraceCategoryLevels.Label(name, level);
var p = start + new Vector2(i % perRow * colW, i / perRow * 18f);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(name);
if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16)))
SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on));
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.PopID();
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true);
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
dl.PopClipRect();
}
int rowsUsed = (cats.Count + perRow - 1) / perRow;
ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f));
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
}
private void SaveCategories(string levels)
{
_data.DiagCategories = levels;
SettingsCommands.Save(_data.Clone());
}
// Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes).
private void TextRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
Tooltip(row);
string saved = row.GetText?.Invoke(_data) ?? string.Empty;
string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(3);
Tooltip(row);
_editing |= active;
if (committed)
{
_textEdits.Remove(row);
if (!string.Equals(text, saved, StringComparison.Ordinal))
{
row.SetText?.Invoke(_data, text);
SettingsCommands.Save(_data.Clone());
}
}
else if (active) _textEdits[row] = text;
else _textEdits.Remove(row);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// RynthAi's one-line status (teal), wrapped to the column.
private void StatusRow(SettingRow row, float w)
{
string text = row.GetText?.Invoke(_data) ?? string.Empty;
if (text.Length == 0) return;
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
// Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
private static void ButtonRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
row.Click?.Invoke();
Tooltip(row);
}
private void Changed(SettingRow row, double value)
{
row.Set!(_data, value);
@ -403,6 +548,130 @@ internal sealed class SettingsFace : IImGuiPanel
}
}
// ── Charms Tracking tab ───────────────────────────────────────────────
private static readonly uint CharmOn = C(0xFF33FF33), CharmDisabled = C(0xFFFF5555);
/// <summary>Summary line, one table row per ACECustom registry charm, then how each column is known.</summary>
private static void CharmsTabContent(float w)
{
var snap = UiSources.Charms.Current;
if (snap == null)
{
Note("Waiting for RynthAi...", w);
return;
}
CharmsInfo info = snap.Value;
if (!info.Available)
{
Note("Charm tracking is for ILT (Infinite Leaftide / ACECustom) worlds."
+ (info.World.Length > 0 ? " Current world: " + info.World + "." : ""), w);
Note("Use /ra hub force on to treat this world as ILT.", w);
return;
}
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333),
$"{info.AcquiredCount} of {info.Total} acquired | {info.ActiveCount} active");
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(4, 3));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBgAlt, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableHeaderBg, TabActive);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableBorderLight, BtnBord);
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit;
if (ImGuiNET.ImGui.BeginTable("##charms", 5, flags, new Vector2(w, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch);
ImGuiNET.ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 70);
ImGuiNET.ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44);
ImGuiNET.ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 32);
ImGuiNET.ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableHeadersRow();
CharmRow[] rows = info.Charms;
for (int i = 0; i < rows.Length; i++)
{
CharmRow r = rows[i];
ImGuiNET.ImGui.PushID(i);
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn();
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), r.Name);
if (r.Effect.Length > 0) ImGuiNET.ImGui.SetItemTooltip(r.Effect);
ImGuiNET.ImGui.TableNextColumn();
switch (r.Acquired)
{
case "carried":
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
ImGuiNET.ImGui.SetItemTooltip("In your pack or equipped.");
break;
case "seen":
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "Stored");
ImGuiNET.ImGui.SetItemTooltip("Owned but not carried"
+ (r.LastSeen.Length > 0 ? " (last carried " + r.LastSeen + ")" : "")
+ ". The client only sees items you carry.");
break;
default:
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not yet");
break;
}
ImGuiNET.ImGui.TableNextColumn();
if (r.Acquired != "carried")
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-");
else if (r.Active == "on")
ColoredText(CharmOn, "ON");
else if (r.Active == "off")
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "OFF");
else
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "?");
ImGuiNET.ImGui.SetItemTooltip("Waiting for the charm's appraisal (requested automatically).");
}
ImGuiNET.ImGui.TableNextColumn();
string tier = r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString(CultureInfo.InvariantCulture);
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), tier);
ImGuiNET.ImGui.TableNextColumn();
if (r.Server == "off")
{
ColoredText(CharmDisabled, "Disabled");
ImGuiNET.ImGui.SetItemTooltip("The server refused or reported this charm as disabled.");
}
else if (r.Server == "on")
ColoredText(CharmOn, "Enabled");
else
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-");
ImGuiNET.ImGui.SetItemTooltip("Not reported. The server only tells players when a charm is refused.");
}
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndTable();
}
ImGuiNET.ImGui.PopStyleColor(4);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
Note("Double-click a carried charm in your pack to toggle it. Status comes from the charm's appraisal "
+ "(Status: ON/OFF) or your character's ability flag. Charms not carried are inactive.", w);
Note("Stored = carried by this character before; RynthAi remembers it per character.", w);
}
/// <summary>TextUnformatted in a packed ImGui colour.</summary>
private static void ColoredText(uint abgr, string text)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, abgr);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
}
private static bool StepButton(string id, Vector2 pos, string glyph)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
@ -430,6 +699,8 @@ internal sealed class SettingsFace : IImGuiPanel
["Crafting"] = PhosphorIcons.Hammer,
["Looting"] = PhosphorIcons.Bag,
["Vendoring"] = PhosphorIcons.Storefront,
["Diagnostics"] = PhosphorIcons.Wrench,
[CharmsTabName] = PhosphorIcons.Gift,
};
private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new();

View file

@ -0,0 +1,693 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs
// The Skills panel's Progression tab, shown on ILT-like worlds only:
// - XP planner: exact XP for the next N raises of every attribute and vital,
// from the client's XP tables (raising stays on the Attributes & Vitals tab).
// - Attribute raiser: infinite attributes past the retail cap. RynthAi reads the
// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from
// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP
// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost.
// - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc /
// Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game.
// - Augmentations / Enlightenment: RynthAi's ILT Hub planners. RynthAi owns the
// math and the saved inputs (UiSources.Progression snapshot); edits and
// actions go back as "prog ..." remote commands. /enl and arming
// auto-enlighten ask here first; the server still shows its own dialog.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class SkillsFace
{
private const string ProgConfirmId = "##skills_prog_confirm";
private int _planLevels = 10; // XP planner: raises to price per row
private bool _progSubscribed;
// The confirm the Progression tab asked for; the command is sent only on its Yes button.
private string _progConfirmTitle = "", _progConfirmText = "", _progConfirmYes = "", _progConfirmCommand = "";
private bool _progConfirmOpenRequested;
// Set by ShowProgression (any panel, AC thread); the tab is selected once RynthAi's snapshot
// says it exists (the first poll lands a step after the panel opens).
private static bool _progressionRequested;
/// <summary>RynthAi reports an ILT-like world (its ILT Hub exists and the server has ILT features).</summary>
private static bool ProgressionTabVisible => UiSources.Progression.Current?.Value.Available == true;
/// <summary>Opens the Skills panel (if closed) on the Progression tab. AC thread.</summary>
public static void ShowProgression()
{
_progressionRequested = true;
if (!ImGuiPanelHost.IsOpen(Title)) PanelRouter.Toggle(Title);
}
/// <summary>Draw: applies a pending ShowProgression once the tab exists.</summary>
private void ApplyProgressionRequest()
{
if (!_progressionRequested || !ProgressionTabVisible) return;
_progressionRequested = false;
_tab = 2;
}
private void ProgressionShown()
{
if (_progSubscribed) return;
_progSubscribed = true;
UiSources.Progression.Subscribe();
UiSources.Progression.RequestRefresh();
}
private void ProgressionHidden()
{
_progressionRequested = false;
if (!_progSubscribed) return;
_progSubscribed = false;
UiSources.Progression.Unsubscribe();
}
/// <summary>Sends "prog &lt;value&gt;" to RynthAi; the snapshot re-polls after its next tick applies it.</summary>
private static void SendProg(string value)
{
RynthAiCommands.ApplyRemoteCommand("prog", value);
UiSources.Progression.RequestRefreshAfterPluginTick();
}
private void AskProgConfirm(string title, string text, string yes, string command)
{
_progConfirmTitle = title;
_progConfirmText = text;
_progConfirmYes = yes;
_progConfirmCommand = command;
_progConfirmOpenRequested = true;
}
// ── Body ────────────────────────────────────────────────────────────
private void DrawProgression(float w)
{
ProgressionInfo? info = UiSources.Progression.Current?.Value;
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
try
{
DrawXpPlanner(w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (info == null || !info.Available)
{
Message("Augmentations and Enlightenment need RynthAi's ILT Hub on an ILT world.", w);
return;
}
DrawAttrRaiser(info.Attr, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
DrawAugPlanner(info.Aug, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
DrawEnlPlanner(info.Enl, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
}
finally
{
ImGuiNET.ImGui.PopStyleVar();
}
}
private void DrawXpPlanner(float w)
{
Section("XP planner", w);
if (_snap == null || _dat == null || _attributes.Count == 0)
{
Message("Waiting for your character's data...", w);
return;
}
ImGuiNET.ImGui.Indent(8);
long have = _snap.UnassignedXp;
Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute);
ImGuiNET.ImGui.SetNextItemWidth(160);
ImGuiNET.ImGui.SliderInt("Raises to plan##prog_lv", ref _planLevels, 1, 100);
if (ImGuiNET.ImGui.BeginTable("##prog_xp", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Stat");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 50);
ImGuiNET.ImGui.TableSetupColumn("Next raise", ImGuiTableColumnFlags.WidthFixed, 100);
ImGuiNET.ImGui.TableSetupColumn($"Next {_planLevels}", ImGuiTableColumnFlags.WidthFixed, 120);
ImGuiNET.ImGui.TableHeadersRow();
foreach (Row r in _attributes) PlannerRow(r, have);
foreach (Row r in _vitals) PlannerRow(r, have);
ImGuiNET.ImGui.EndTable();
}
Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab"
+ (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim);
ImGuiNET.ImGui.Unindent(8);
}
private void PlannerRow(Row r, long have)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Name);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Base.ToString(CultureInfo.InvariantCulture));
uint[]? table = r.Table;
int left = table == null ? 0 : Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue));
ImGuiNET.ImGui.TableNextColumn();
if (table == null || left == 0) { Label(table == null ? "-" : "max", Dim); ImGuiNET.ImGui.TableNextColumn(); Label("-", Dim); return; }
long one = SkillDat.CostOf(table, r.Ranks, r.Spent, 1);
Label(one >= 0 ? one.ToString("N0", CultureInfo.InvariantCulture) : "-", one >= 0 && one <= have ? Teal : Dim);
ImGuiNET.ImGui.TableNextColumn();
int n = Math.Min(_planLevels, left);
long many = SkillDat.CostOf(table, r.Ranks, r.Spent, n);
string text = many >= 0 ? many.ToString("N0", CultureInfo.InvariantCulture) : "-";
if (n < _planLevels) text += $" ({n} to max)";
Label(text, many >= 0 && many <= have ? Teal : Dim);
}
private static readonly string[] AttrModes =
{
"Priority - top of the order first",
"Round robin - one level each, in order",
"Cheapest next level first",
};
private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value)
private int? _attrEveryEdit; // interval box being typed in
private void DrawAttrRaiser(AttrRaiser? a, float w)
{
Section("Attribute raiser (infinite attributes)", w);
ImGuiNET.ImGui.Indent(8);
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24;
ImGuiNET.ImGui.PushTextWrapPos(wrap);
try
{
if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; }
if (a.Off) { Label(a.Reason, Mute); return; }
Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal);
if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (a.Running)
{
if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop");
}
else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal))
SendProg("attrrun");
if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running))
SendProg("attrcosts");
ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all.");
if (a.Updated.Length > 0)
{
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4));
Label("Last updated: " + a.Updated, Dim);
}
NextLine(p, 28);
if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status);
if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim);
ImGuiNET.ImGui.Separator();
bool auto = a.Auto;
if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto))
SendProg("attrauto " + (auto ? "on" : "off"));
ImGuiNET.ImGui.SameLine();
// Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send
// restarts the auto-raise timer).
int every = _attrEveryEdit ?? a.Every;
ImGuiNET.ImGui.SetNextItemWidth(90);
bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue);
bool everyActive = ImGuiNET.ImGui.IsItemActive();
if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_attrEveryEdit = null;
if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture));
}
else _attrEveryEdit = everyActive ? every : null;
if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim);
int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1);
ImGuiNET.ImGui.SetNextItemWidth(260);
if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length))
SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture));
// The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an
// Enter on an untouched box can't round the reserve.
string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep;
string keep = _attrKeepEdit ?? shownKeep;
ImGuiNET.ImGui.SetNextItemWidth(140);
bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool keepActive = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_attrKeepEdit = null;
if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal))
SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal));
}
else _attrKeepEdit = keepActive ? keep : null;
ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes.");
DrawAttrTable(a, w);
Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. "
+ "+1 / +10 raise by hand (red = not enough unassigned XP). "
+ "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim);
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Unindent(8);
}
}
/// <summary>
/// UB Leaftide XP tab layout: Auto tick, stat, base, then "+1 Level" / "+10 Levels" buttons
/// labelled with what they cost, then the priority arrows.
/// </summary>
private void DrawAttrTable(AttrRaiser a, float w)
{
if (!ImGuiNET.ImGui.BeginTable("##prog_attr", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
return;
ImGuiNET.ImGui.TableSetupColumn("Auto", ImGuiTableColumnFlags.WidthFixed, 34);
ImGuiNET.ImGui.TableSetupColumn("Stat");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableSetupColumn("+1 Level", ImGuiTableColumnFlags.WidthFixed, 84);
ImGuiNET.ImGui.TableSetupColumn("+10 Levels", ImGuiTableColumnFlags.WidthFixed, 84);
ImGuiNET.ImGui.TableSetupColumn("Order", ImGuiTableColumnFlags.WidthFixed, 48);
ImGuiNET.ImGui.TableHeadersRow();
for (int i = 0; i < a.Rows.Length; i++)
{
AttrRow r = a.Rows[i];
ImGuiNET.ImGui.PushID("attr_" + r.Key);
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn();
bool on = r.On;
if (ImGuiNET.ImGui.Checkbox("##on", ref on)) SendProg($"attron {r.Key} {(on ? "on" : "off")}");
ImGuiNET.ImGui.TableNextColumn();
Label($"{i + 1}. {r.Label}", r.On ? Text : Mute);
ImGuiNET.ImGui.TableNextColumn();
int clientBase = ClientBase(r);
Label(clientBase > 0 ? clientBase.ToString("N0", CultureInfo.InvariantCulture)
: r.Base >= 0 ? r.Base.ToString("N0", CultureInfo.InvariantCulture) : "-", Text);
// Older RynthAi sends no cost10 / afford1: plain buttons, the server decides.
bool rich = r.Cost10.Length > 0;
ImGuiNET.ImGui.TableNextColumn();
RaiseButton(a, r, 1, rich ? r.Cost : "+1", rich ? r.Afford1 : true, r.CostFull, rich);
ImGuiNET.ImGui.TableNextColumn();
RaiseButton(a, r, 10, rich ? r.Cost10 : "+10", rich ? r.Afford10 : true, r.Cost10Full, rich);
ImGuiNET.ImGui.TableNextColumn();
ImGuiNET.ImGui.BeginDisabled(i == 0);
if (ImGuiNET.ImGui.ArrowButton("##up", ImGuiDir.Up)) SendProg($"attrmove {r.Key} up");
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SameLine(0, 2);
ImGuiNET.ImGui.BeginDisabled(i == a.Rows.Length - 1);
if (ImGuiNET.ImGui.ArrowButton("##down", ImGuiDir.Down)) SendProg($"attrmove {r.Key} down");
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndTable();
}
/// <summary>
/// One by-hand raise button filling its cell. Unknown cost ("?") stays clickable (the server
/// checks); a known cost over the unassigned XP is red and disabled.
/// </summary>
private static void RaiseButton(AttrRaiser a, AttrRow r, int levels, string label, bool afford, string exact, bool rich)
{
bool known = rich && r.Known;
bool enabled = !a.Running && (!known || afford);
uint fg = !known ? Text : afford ? Teal : Red;
Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos();
float width = Math.Max(40f, ImGuiNET.ImGui.GetContentRegionAvail().X);
if (Button("##raise" + levels, label, pos, new Vector2(width, 20), fg, BtnFill, enabled, border: known && afford ? Teal : 0))
SendProg($"attrraise {r.Key} {levels}");
string what = $"{r.Label} +{levels} level{(levels > 1 ? "s" : "")}";
string tip = !known ? $"{what}: cost not read yet (Refresh XP)."
: levels > 1 ? $"{what}: about {exact} XP (estimate)."
: $"{what}: {exact} XP.";
if (known && !afford) tip += " Not enough unassigned XP.";
if (a.Running) tip += " Wait for the raise run to finish.";
ImGuiNET.ImGui.SetItemTooltip(tip);
}
/// <summary>The client's own base value for a raiser row (0 when the snapshot has none).</summary>
private int ClientBase(AttrRow r)
{
List<Row> rows = r.Vital ? _vitals : _attributes;
foreach (Row row in rows)
if (row.Name.Equals(r.Label, StringComparison.OrdinalIgnoreCase)) return row.Base;
return 0;
}
private void DrawAugPlanner(AugPlanner a, float w)
{
Section("Augmentations", w);
ImGuiNET.ImGui.Indent(8);
try
{
if (a.Off) { Label("/aug is not available on this server.", Mute); return; }
// UB Augs tab buttons: Refresh Current, Reset Target, Copy Discord, Copy In-Game.
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float x = p.X;
if (Button("##aug_refresh", "Refresh current", new Vector2(x, p.Y), new Vector2(120, 22), Text, StartBg, border: Teal))
SendProg("augload");
ImGuiNET.ImGui.SetItemTooltip("Reads your augmentation levels with /aug (also done once when this tab first opens).");
x += 124;
if (Button("##aug_reset", "Reset targets", new Vector2(x, p.Y), new Vector2(104, 22), Text, BtnFill))
SendProg("augreset");
ImGuiNET.ImGui.SetItemTooltip("Sets every target back to the current level.");
x += 108;
if (Button("##aug_discord", "Copy Discord", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyDiscord.Length > 0))
ImGuiNET.ImGui.SetClipboardText(a.CopyDiscord);
ImGuiNET.ImGui.SetItemTooltip("Copies the plan as a Discord code-block table.");
x += 104;
if (Button("##aug_ingame", "Copy in-game", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyIngame.Length > 0))
ImGuiNET.ImGui.SetClipboardText(a.CopyIngame);
ImGuiNET.ImGui.SetItemTooltip("Copies your current levels as one chat line.");
NextLine(p, 26);
Label("Status: " + a.Status, Dim);
if (ImGuiNET.ImGui.BeginTable("##prog_augs", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Aug");
ImGuiNET.ImGui.TableSetupColumn("Current", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableSetupColumn("Target", ImGuiTableColumnFlags.WidthFixed, 124);
ImGuiNET.ImGui.TableSetupColumn("Inc", ImGuiTableColumnFlags.WidthFixed, 44);
ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 76);
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableHeadersRow();
foreach (AugRow row in a.Rows)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Current.ToString("N0", CultureInfo.InvariantCulture));
ImGuiNET.ImGui.TableNextColumn();
DrawAugTarget(row);
int inc = row.Increase > 0 ? row.Increase : Math.Max(0, row.Target - row.Current);
ImGuiNET.ImGui.TableNextColumn(); Label(inc > 0 ? inc.ToString("N0", CultureInfo.InvariantCulture) : "-", inc > 0 ? Teal : Dim);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString("N0", CultureInfo.InvariantCulture) : "-");
}
if (a.TotalLum.Length > 0)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); Label("TOTALS", Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCurrent.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalTarget.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalIncrease.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalLum, Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCoins.ToString("N0", CultureInfo.InvariantCulture), Amber);
}
ImGuiNET.ImGui.EndTable();
}
// Lum per coin commits on Enter / focus loss, not per keystroke.
string shownLpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture);
string lpc = _augLpcEdit ?? shownLpc;
ImGuiNET.ImGui.SetNextItemWidth(140);
bool lpcEnter = ImGuiNET.ImGui.InputTextWithHint("Lum per e-coin##prog_lpc", "0 = don't price coins", ref lpc, 24u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool lpcActive = ImGuiNET.ImGui.IsItemActive();
if (lpcEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augLpcEdit = null;
string clean = lpc.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal);
if (!string.Equals(clean, shownLpc, StringComparison.Ordinal)) SendProg("lumpercoin " + clean);
}
else _augLpcEdit = lpcActive ? lpc : null;
ImGuiNET.ImGui.SetItemTooltip("Luminance one Enlightened Coin costs you. Accepts k / m / b / t suffixes.");
if (a.CoinsLine.Length > 0)
{
Label(a.CoinsLine, Text);
Label(a.LumToBuy, Text);
}
else
{
Label(a.Total, Amber);
if (a.Short.Length > 0) Label(a.Short, Text);
}
Label(a.Banked, Dim);
if (a.Config != null) DrawAugCostSettings(a.Config, w);
}
finally
{
ImGuiNET.ImGui.Unindent(8);
}
}
private static readonly string[] AugTierNames = { "Below S1", "From S1", "From S2", "From S3", "From S4" };
// Cost-settings boxes being typed in, by box id (committed on Enter / focus loss).
private readonly Dictionary<string, int> _augCfgIntEdit = new(StringComparer.Ordinal);
private readonly Dictionary<string, double> _augCfgDblEdit = new(StringComparer.Ordinal);
/// <summary>
/// Collapsible editor for this world's aug cost rules (RynthAi saves them per world). The
/// defaults are UB's InfiniteLeaftide model; Reset puts a changed world back on them.
/// </summary>
private void DrawAugCostSettings(AugCostConfig cfg, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
string head = $"Cost settings for {cfg.World}" + (cfg.Custom ? " (custom)" : " (InfiniteLeaftide defaults)");
if (!ImGuiNET.ImGui.CollapsingHeader(head + "##aug_cfg")) return;
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24);
Label("Level i costs (Base + (i - 1) x Base x Growth% / 100) x the multiplier of its tier. "
+ "A tier starts at its S level (UB's InfiniteLeaftide model). Changes apply to this world only.", Dim);
ImGuiNET.ImGui.PopTextWrapPos();
// Tier multipliers, one box each.
Label("Tier multipliers", Text);
for (int t = 0; t < AugTierNames.Length && t < cfg.Multipliers.Length; t++)
{
if (t > 0) ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.BeginGroup();
Label(AugTierNames[t], Mute);
ImGuiNET.ImGui.SetNextItemWidth(62);
CfgDouble($"mult{t}", cfg.Multipliers[t], v => $"augmult {t} {v.ToString("R", CultureInfo.InvariantCulture)}");
ImGuiNET.ImGui.EndGroup();
}
// Per-aug rules.
if (ImGuiNET.ImGui.BeginTable("##aug_cfg_rows", 9, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Aug");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 74);
ImGuiNET.ImGui.TableSetupColumn("Growth%", ImGuiTableColumnFlags.WidthFixed, 54);
ImGuiNET.ImGui.TableSetupColumn("S1", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S2", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S3", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S4", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("Cap", ImGuiTableColumnFlags.WidthFixed, 50);
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 42);
ImGuiNET.ImGui.TableHeadersRow();
foreach (AugCostRule r in cfg.Rows)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Label);
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.base", (int)Math.Min(r.Base, int.MaxValue), $"augcfg {r.Key} base");
ImGuiNET.ImGui.TableNextColumn(); CfgDouble($"{r.Key}.pct", r.Percent, v => $"augcfg {r.Key} pct {v.ToString("R", CultureInfo.InvariantCulture)}");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s1", r.S1, $"augcfg {r.Key} s1");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s2", r.S2, $"augcfg {r.Key} s2");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s3", r.S3, $"augcfg {r.Key} s3");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s4", r.S4, $"augcfg {r.Key} s4");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.cap", r.Cap, $"augcfg {r.Key} cap");
ImGuiNET.ImGui.SetItemTooltip("Highest target level; 0 = no limit.");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.coins", r.Coins, $"augcfg {r.Key} coins");
ImGuiNET.ImGui.SetItemTooltip("Enlightened Coins per level.");
}
ImGuiNET.ImGui.EndTable();
}
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##aug_cfg_reset", "Reset to InfiniteLeaftide defaults", p, new Vector2(230, 22), Text, BtnFill, enabled: cfg.Custom))
SendProg("augcfgreset");
ImGuiNET.ImGui.SetItemTooltip("Drops this world's changes; it goes back to UB's InfiniteLeaftide rules.");
NextLine(p, 26);
}
/// <summary>Integer box that sends "<paramref name="verb"/> value" on Enter or focus loss.</summary>
private void CfgInt(string id, int value, string verb)
{
int v = _augCfgIntEdit.TryGetValue(id, out int typing) ? typing : value;
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool enter = ImGuiNET.ImGui.InputInt("##cfg_" + id, ref v, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augCfgIntEdit.Remove(id);
if (v != value) SendProg($"{verb} {Math.Max(0, v).ToString(CultureInfo.InvariantCulture)}");
}
else if (active) _augCfgIntEdit[id] = v;
else _augCfgIntEdit.Remove(id);
}
/// <summary>Decimal box (the caller sets its width) that sends <paramref name="command"/>(value) on Enter or focus loss.</summary>
private void CfgDouble(string id, double value, Func<double, string> command)
{
double v = _augCfgDblEdit.TryGetValue(id, out double typing) ? typing : value;
if (!id.StartsWith("mult", StringComparison.Ordinal)) ImGuiNET.ImGui.SetNextItemWidth(-1);
bool enter = ImGuiNET.ImGui.InputDouble("##cfg_" + id, ref v, 0, 0, "%.6g", ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augCfgDblEdit.Remove(id);
if (Math.Abs(v - value) > 1e-9 && double.IsFinite(v)) SendProg(command(Math.Max(0, v)));
}
else if (active) _augCfgDblEdit[id] = v;
else _augCfgDblEdit.Remove(id);
}
private string? _augLpcEdit; // Lum per coin box being typed in
private readonly Dictionary<string, int> _augTargetEdit = new(StringComparer.Ordinal); // target boxes being typed in
/// <summary>
/// Target cell: -/+ step one level (Ctrl: 100), typing commits on Enter or focus loss so a
/// half-typed number never reaches RynthAi. RynthAi clamps to current..cap.
/// </summary>
private void DrawAugTarget(AugRow row)
{
int tgt = _augTargetEdit.TryGetValue(row.Key, out int typing) ? typing : row.Target;
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool commit = ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 1, 100, ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (commit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augTargetEdit.Remove(row.Key);
int clamped = Math.Clamp(tgt, row.Current, Math.Max(row.Cap, row.Current));
if (clamped != row.Target) SendProg($"augtarget {row.Key} {clamped.ToString(CultureInfo.InvariantCulture)}");
}
else if (active) _augTargetEdit[row.Key] = tgt;
else _augTargetEdit.Remove(row.Key);
ImGuiNET.ImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)}).");
}
private void DrawEnlPlanner(EnlPlanner e, float w)
{
Section("Enlightenment", w);
ImGuiNET.ImGui.Indent(8);
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; // window-local x
ImGuiNET.ImGui.PushTextWrapPos(wrap);
try
{
if (e.Off) { Label("/enl is not available on this server.", Mute); return; }
Label(e.Header, Text);
Label(e.Next, Teal);
int target = e.Target;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target))
SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture));
foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line);
int coinsPerToken = e.CoinsPerToken;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken))
SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture));
if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim);
ImGuiNET.ImGui.Separator();
if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green);
foreach (string b in e.Blockers) Label(b, Amber);
Label(e.ServerChecks, Dim);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##prog_enl", "Enlighten now...", p, new Vector2(150, 24), Text, BtnFill, border: Teal))
AskProgConfirm("Enlighten",
"Send /enl now?\n\nEnlightening resets your level and wipes unassigned XP.\n"
+ "The server will show its own Yes/No dialog - you must click Yes there.",
"Send /enl", "enlighten");
NextLine(p, 28);
ImGuiNET.ImGui.Separator();
bool auto = e.Auto;
if (ImGuiNET.ImGui.Checkbox("Auto-enlighten when ready##prog_auto", ref auto))
{
if (auto)
AskProgConfirm("Arm auto-enlighten",
"Auto-enlighten will send /enl whenever the checks pass (peace mode, level, materials).\n"
+ "You still have to click Yes in the AC dialog each time.\n\nArm it for this session?",
"Arm", "autoenl on");
else
SendProg("autoenl off");
}
if (e.Auto && !e.Armed)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Arm for this session...##prog_arm"))
AskProgConfirm("Arm auto-enlighten", "Arm auto-enlighten for this session?", "Arm", "autoenl arm");
}
bool spend = e.SpendFirst;
if (ImGuiNET.ImGui.Checkbox("Spend unassigned XP on attributes first##prog_spend", ref spend))
SendProg("spendfirst " + (spend ? "on" : "off"));
int every = e.CheckEvery;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every))
SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture));
Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim);
if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status);
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Unindent(8);
}
}
// ── Confirm ─────────────────────────────────────────────────────────
/// <summary>The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).</summary>
private void DrawProgressionConfirm()
{
if (_progConfirmOpenRequested)
{
_progConfirmOpenRequested = false;
ImGuiNET.ImGui.OpenPopup(ProgConfirmId);
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
bool open = ImGuiNET.ImGui.BeginPopup(ProgConfirmId);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
Label(_progConfirmTitle, Amber);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 320);
Label(_progConfirmText, Text);
ImGuiNET.ImGui.PopTextWrapPos();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
if (Button("##prog_yes", _progConfirmYes, p, new Vector2(120, 24), Text, StartBg))
{
SendProg(_progConfirmCommand);
ImGuiNET.ImGui.CloseCurrentPopup();
}
if (Button("##prog_no", "Cancel", new Vector2(p.X + 126, p.Y), new Vector2(90, 24), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
NextLine(p, 28);
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
}

View file

@ -45,7 +45,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class SkillsFace : IImGuiPanel
internal sealed partial class SkillsFace : IImGuiPanel
{
public const string Title = "Skills";
@ -127,7 +127,7 @@ internal sealed class SkillsFace : IImGuiPanel
}
// ── State ───────────────────────────────────────────────────────────
private int _tab; // 0 skills, 1 attributes & vitals
private int _tab; // 0 skills, 1 attributes & vitals, 2 progression (ILT worlds)
private SortKey _sort = SortKey.Name;
private bool _descending;
private readonly bool[] _collapsed = { false, false, false, true };
@ -193,18 +193,23 @@ internal sealed class SkillsFace : IImGuiPanel
SkillDat.EnsureLoadQueued();
PortalSpellTable.EnsureLoadQueued();
MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale
ProgressionShown();
}
public void OnHidden() => ProgressionHidden();
public void Draw()
{
PlayerProgressHooks.Want();
Refresh();
ApplyProgressionRequest();
if (_tab == 2 && !ProgressionTabVisible) _tab = 0;
float w = Begin(out Vector2 origin, out Vector2 size);
DrawSummary(w);
DrawTabs(w);
if (_tab == 0) DrawToolbar(w);
DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
@ -212,7 +217,9 @@ internal sealed class SkillsFace : IImGuiPanel
ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
EnsureWidths();
if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
if (_tab == 2)
DrawProgression(bw);
else if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
Message("Waiting for your character's data...", bw);
else if (_dat == null)
Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw);
@ -228,6 +235,7 @@ internal sealed class SkillsFace : IImGuiPanel
_picker.Draw();
DrawMulti();
DrawConfirm();
DrawProgressionConfirm();
}
// ── Data ────────────────────────────────────────────────────────────
@ -691,13 +699,18 @@ internal sealed class SkillsFace : IImGuiPanel
private void DrawTabs(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) * 0.5f;
if (Button("##tab_skills", "Skills", p, new Vector2(half, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
// The Progression tab only exists on ILT-like worlds (RynthAi's snapshot says so).
int count = ProgressionTabVisible ? 3 : 2;
float tabW = (w - 4 * (count - 1)) / count;
if (Button("##tab_skills", "Skills", p, new Vector2(tabW, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
border: _tab == 0 ? Teal : 0))
_tab = 0;
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22),
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + tabW + 4, p.Y), new Vector2(tabW, 22),
_tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0))
_tab = 1;
if (count == 3 && Button("##tab_prog", "Progression", new Vector2(p.X + 2 * (tabW + 4), p.Y), new Vector2(tabW, 22),
_tab == 2 ? Teal : Text, _tab == 2 ? Selected : BtnFill, border: _tab == 2 ? Teal : 0))
_tab = 2;
NextLine(p, 26);
}

View file

@ -392,6 +392,14 @@ internal static unsafe class Win32Backend
RunOnGameThread<bool>(() => { action(); return true; });
}
/// <summary>
/// True once the game window is known AND its WndProc is subclassed, i.e.
/// <see cref="RunOnGameThread{T}"/> can actually deliver work to AC's main
/// thread. Knowing the HWND alone is not enough: without the subclass,
/// WM_RYNTH_RUN_ACTION reaches AC's own WndProc, which ignores it.
/// </summary>
public static bool CanRunOnGameThread => _initialized && _gameHwnd != IntPtr.Zero;
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
/// Win32 focus transfer is needed.</summary>
public static void ReturnFocusToGame() => ChatCaptureActive = false;
@ -572,10 +580,11 @@ internal static unsafe class Win32Backend
if (!_initialized) return;
// Destroy floating panels while our hook can still run on the game
// thread. LayeredWindow.Dispose only POSTS its destroy, and the game
// thread usually hasn't reached that post by the time we unhook below —
// AC's own WndProc then drops it and the panel outlives this engine
// load, frozen and unclickable (duplicate RynthAi dashboard after RL).
// thread. LayeredWindow.Dispose posts its destroy to the panel itself
// (handled by the panel's own WndProc, which survives this unhook), but
// any panel never disposed would outlive this engine load, frozen and
// unclickable (duplicate RynthAi dashboard after RL) — this sweep is the
// synchronous backstop for those.
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
SMTO_NORMAL, 2000, out _);
if (swept == IntPtr.Zero)
@ -991,11 +1000,15 @@ internal static unsafe class Win32Backend
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
// unless the HUD is drawn.
if (IsMouseMessage(msg))
{
TrackMouseButtons(msg, wParam);
ItemDragBridge.OnGameMouse(msg, wParam, lParam, _heldButtonsBelongToGame);
}
else if (msg == WM_KILLFOCUS)
{
_heldMouseButtons = 0;
_heldButtonsBelongToGame = false;
ItemDragBridge.Reset();
}
// ── Avalonia panel hit-test & input forwarding ────────────────
@ -1006,7 +1019,7 @@ internal static unsafe class Win32Backend
{
// fall through: AC gets the message
}
else if (IsMouseMessage(msg))
else if (IsMouseMessage(msg) && !ImGuiOwnsMouseOverAvalonia())
{
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
if (handled)
@ -1097,6 +1110,14 @@ internal static unsafe class Win32Backend
}
}
// An AC inventory item dragged onto an ImGui window: AC must not drop it on the
// ground behind the window. It gets the release where the drag began instead.
if (ItemDragBridge.TryRedirectNativeDrop(msg, out IntPtr pressLParam))
{
CallWindowProcA(_originalWndProc, hWnd, WM_MOUSEMOVE, (IntPtr)MK_LBUTTON, pressLParam);
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, pressLParam);
}
// Pass through to original WndProc
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
}
@ -1107,6 +1128,17 @@ internal static unsafe class Win32Backend
}
}
/// <summary>
/// ImGui windows are drawn on top of the Avalonia layer, so when the cursor is over
/// an ImGui window (or an ImGui widget is active) mouse input must go to ImGui
/// instead of the Avalonia panel underneath. An Avalonia drag/resize that is already
/// in progress keeps its capture so the release is never lost.
/// </summary>
private static bool ImGuiOwnsMouseOverAvalonia()
{
return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture;
}
/// <summary>
/// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to
/// the off-screen Avalonia HWND and return true (caller should suppress game delivery).

View file

@ -21,6 +21,7 @@
using System;
using System.IO;
using RynthCore.Install;
namespace RynthCore.Engine;

View file

@ -0,0 +1,245 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine;
/// <summary>
/// Engine log categories. Each one has a configurable emit level (see <see cref="LogSettings"/>).
/// Names are the keys of engine.json "LogCategories" and must stay stable.
/// </summary>
internal enum LogCategory
{
/// <summary>Uncategorised RynthLog.Info lines.</summary>
General = 0,
/// <summary>D3D9: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
D3D9,
/// <summary>Compatibility hooks: client objects, combat, movement, vitals, chat, ...</summary>
Compat,
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
Render,
/// <summary>Plugin system, including every line plugins write through the host Log API.</summary>
Plugin,
/// <summary>UI / Avalonia overlay.</summary>
UI,
/// <summary>Verbose detail lines (RynthLog.Verbose / RynthLog.Debug).</summary>
Verbose,
}
/// <summary>
/// Live engine logging configuration, read from %APPDATA%\RynthCore\engine.json:
/// <list type="bullet">
/// <item><c>"LoggingLevel"</c> — global threshold: Off, Error, Warning, Info, Debug, Trace.</item>
/// <item><c>"LogCategories"</c> — per-category emit level: <c>{ "Compat": "Info", "Verbose": "Debug", ... }</c>.
/// The emit level is the level a category's lines are written AT, so a line shows when
/// its emit level is within the global threshold. Setting a Trace/Debug category to
/// Info puts it in the normal (Info) log; Off silences the category entirely.</item>
/// </list>
/// A background thread polls the file's timestamp once a second, so launcher edits apply to a
/// running client without a restart. Errors are always written, even when the level is Off.
/// </summary>
internal static class LogSettings
{
/// <summary>engine.json property holding the per-category levels.</summary>
internal const string CategoriesProperty = "LogCategories";
private const int PollIntervalMs = 1000;
// Default emit level per LogCategory (index = enum value): categories at Info,
// Render off, verbose lines at Debug.
private static readonly EntryPoint.EngineLogLevel[] Defaults =
{
EntryPoint.EngineLogLevel.Info, // General
EntryPoint.EngineLogLevel.Info, // D3D9
EntryPoint.EngineLogLevel.Info, // Compat
EntryPoint.EngineLogLevel.Off, // Render
EntryPoint.EngineLogLevel.Info, // Plugin
EntryPoint.EngineLogLevel.Info, // UI
EntryPoint.EngineLogLevel.Debug, // Verbose
};
// Replaced wholesale on reload (never mutated after publish) so hot-path readers on any
// thread can index it without a lock.
private static EntryPoint.EngineLogLevel[] _levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
private static readonly object WatcherLock = new();
private static Thread? _watcherThread;
private static ManualResetEventSlim? _stopSignal;
private static DateTime _stampUtc = DateTime.MinValue;
private static string SettingsPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json");
/// <summary>Current emit level for a category (cheap; safe on hot paths).</summary>
internal static EntryPoint.EngineLogLevel LevelFor(LogCategory category)
{
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
int i = (int)category;
return (uint)i < (uint)levels.Length ? levels[i] : EntryPoint.EngineLogLevel.Info;
}
/// <summary>True when a line in this category would be written right now.</summary>
internal static bool IsEnabled(LogCategory category) => EntryPoint.ShouldLog(LevelFor(category));
/// <summary>3-char severity tag written into each log line.</summary>
internal static string Tag(EntryPoint.EngineLogLevel level) => level switch
{
EntryPoint.EngineLogLevel.Error => "ERR",
EntryPoint.EngineLogLevel.Warning => "WRN",
EntryPoint.EngineLogLevel.Debug => "DBG",
EntryPoint.EngineLogLevel.Trace => "TRC",
_ => "INF",
};
/// <summary>
/// Reads the global level and category levels from engine.json and publishes them.
/// Called once at init (before the first log line) and again by the watcher on change.
/// Missing or unreadable values fall back to their defaults. Returns a one-line summary.
/// </summary>
internal static string Reload()
{
string? globalText = null;
var levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
try
{
string path = SettingsPath;
if (File.Exists(path))
{
_stampUtc = File.GetLastWriteTimeUtc(path);
// ReadAllText strips a UTF-8/UTF-16 BOM that JsonDocument would choke on.
using var doc = JsonDocument.Parse(File.ReadAllText(path));
JsonElement root = doc.RootElement;
if (root.TryGetProperty("LoggingLevel", out JsonElement levelEl) && levelEl.ValueKind == JsonValueKind.String)
globalText = levelEl.GetString();
if (root.TryGetProperty(CategoriesProperty, out JsonElement catsEl) && catsEl.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty p in catsEl.EnumerateObject())
{
if (p.Value.ValueKind != JsonValueKind.String) continue;
if (!Enum.TryParse(p.Name, ignoreCase: true, out LogCategory cat) || !Enum.IsDefined(cat)) continue;
if (TryParseCategoryLevel(p.Value.GetString(), out EntryPoint.EngineLogLevel lvl))
levels[(int)cat] = lvl;
}
}
}
}
catch
{
// Half-written / corrupt file: keep defaults for this pass; the next timestamp change retries.
globalText ??= EngineSettings.LoggingLevel;
}
EntryPoint.LoggingLevel = EntryPoint.ParseLoggingLevel(globalText);
Volatile.Write(ref _levels, levels);
EntryPoint.VerboseLogging = IsEnabled(LogCategory.Verbose);
return Describe();
}
/// <summary>Human-readable "level=Info D3D9=Info Compat=Info ..." summary for the log.</summary>
internal static string Describe()
{
var sb = new StringBuilder();
sb.Append("level=").Append(EntryPoint.LoggingLevel);
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
for (int i = 0; i < levels.Length; i++)
sb.Append(' ').Append((LogCategory)i).Append('=').Append(levels[i]);
return sb.ToString();
}
/// <summary>
/// Categories whose emit level is more verbose than the global level, so none of their lines
/// are written (e.g. every category at Trace with LoggingLevel Info: an almost empty log).
/// Empty when nothing is hidden.
/// </summary>
internal static string HiddenCategoriesWarning()
{
EntryPoint.EngineLogLevel global = EntryPoint.LoggingLevel;
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
var hidden = new StringBuilder();
for (int i = 0; i < levels.Length; i++)
{
if (levels[i] == EntryPoint.EngineLogLevel.Off || levels[i] <= global) continue;
if (hidden.Length > 0) hidden.Append(", ");
hidden.Append((LogCategory)i).Append('=').Append(levels[i]);
}
return hidden.Length == 0 ? ""
: $"LogSettings: {hidden} write above the global LoggingLevel ({global}), so those lines are NOT logged. " +
"Raise LoggingLevel to the most verbose category level, or set the categories to Info.";
}
/// <summary>Starts the once-a-second engine.json poll. Idempotent.</summary>
internal static void StartWatcher()
{
lock (WatcherLock)
{
if (_watcherThread != null) return;
_stopSignal = new ManualResetEventSlim(false);
ManualResetEventSlim stop = _stopSignal;
_watcherThread = new Thread(() => WatchLoop(stop))
{
IsBackground = true,
Name = "RynthCore.LogSettingsWatcher",
};
_watcherThread.Start();
}
}
/// <summary>
/// Stops and joins the poll thread. Called from EngineLifecycle.Shutdown so the thread never
/// runs inside an old engine generation after a hot reload.
/// </summary>
internal static void StopWatcher()
{
Thread? thread;
lock (WatcherLock)
{
thread = _watcherThread;
_stopSignal?.Set();
_watcherThread = null;
}
thread?.Join(2000);
}
private static void WatchLoop(ManualResetEventSlim stop)
{
while (!stop.Wait(PollIntervalMs))
{
try
{
string path = SettingsPath;
if (!File.Exists(path) || File.GetLastWriteTimeUtc(path) == _stampUtc)
continue;
string summary = Reload();
// Bypasses the category levels so a change is visible whenever Info is in range.
if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info))
EntryPoint.LogTagged("engine", $"LogSettings: engine.json changed - logging reloaded ({summary}).", "INF");
string hidden = HiddenCategoriesWarning();
if (hidden.Length > 0) RynthLog.Warn(hidden);
}
catch
{
// Logging configuration must never take the client down; retry next poll.
}
}
}
/// <summary>
/// Parses a category emit level: Off, Trace, Debug (or Verbose), Info, Warning (or Warn), Error.
/// </summary>
private static bool TryParseCategoryLevel(string? text, out EntryPoint.EngineLogLevel level)
{
level = EntryPoint.EngineLogLevel.Info;
if (string.IsNullOrWhiteSpace(text)) return false;
string t = text.Trim();
if (t.Equals("Verbose", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Debug; return true; }
if (t.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Warning; return true; }
return Enum.TryParse(t, ignoreCase: true, out level) && Enum.IsDefined(level);
}
}

View file

@ -28,9 +28,11 @@ internal static class EngineSettings
private static bool _enableEngine = true;
private static int _engineHookCount = int.MaxValue;
private static bool _enableImGuiBackend = true;
private static bool _enablePluginOverlayWindows = true;
private static bool _enableHangMinidump = true;
private static bool _preventIdleLogoff = true;
private static bool _closeOnServerDisconnect = true;
private static string _loggingLevel = "Info";
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true;
@ -205,6 +207,19 @@ internal static class EngineSettings
}
}
/// <summary>When true (default) and the ImGui shell is off, plugins that export
/// RynthPluginRenderOverlay draw their extra ImGui windows (RynthAi: ILT Hub, Item Info)
/// beside the Avalonia UI. engine.json "EnablePluginOverlayWindows": false hides them.
/// Needs <see cref="EnableImGuiBackend"/>.</summary>
public static bool EnablePluginOverlayWindows
{
get
{
EnsureLoaded();
return _enablePluginOverlayWindows;
}
}
/// <summary>When true, MainThreadHangWatchdog writes a minidump to
/// Logs\dumps\ the first time AC's main thread is confirmed permanently
/// wedged — a targeted post-mortem to replace always-on procdump (which
@ -253,6 +268,18 @@ internal static class EngineSettings
}
}
/// <summary>Engine log threshold from engine.json "LoggingLevel", written by the launcher's
/// Logging level box: Error, Warning, Info (default), Debug/Verbose or Trace. Parsed by
/// EntryPoint.ParseLoggingLevel at init; unknown values fall back to Info.</summary>
public static string LoggingLevel
{
get
{
EnsureLoaded();
return _loggingLevel;
}
}
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
@ -522,6 +549,12 @@ internal static class EngineSettings
_enableImGuiBackend = ibEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnablePluginOverlayWindows", out var powEl) &&
(powEl.ValueKind == JsonValueKind.True || powEl.ValueKind == JsonValueKind.False))
{
_enablePluginOverlayWindows = powEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
{
@ -595,6 +628,14 @@ internal static class EngineSettings
_disabledUiHooks.Add(hookName.Trim());
}
}
if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) &&
logLevelEl.ValueKind == JsonValueKind.String)
{
string? configuredLevel = logLevelEl.GetString();
if (!string.IsNullOrWhiteSpace(configuredLevel))
_loggingLevel = configuredLevel;
}
}
catch (Exception ex)
{
@ -627,7 +668,7 @@ internal static class EngineSettings
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect",
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "EnablePluginOverlayWindows", "LoggingLevel",
};
private static void Save()
@ -653,8 +694,11 @@ internal static class EngineSettings
w.WriteBoolean("EnableEngine", _enableEngine);
w.WriteNumber("EngineHookCount", _engineHookCount);
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
w.WriteBoolean("EnablePluginOverlayWindows", _enablePluginOverlayWindows);
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
// Preserve the launcher-chosen level; dropping it here would reset logging to Info.
w.WriteString("LoggingLevel", _loggingLevel);
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
w.WriteString("DecalBridge", _decalBridgeMode.ToString());
if (!_decalInGameImGui) // default true: leave the file as it was

View file

@ -54,6 +54,18 @@ internal sealed class LoadedPlugin
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; }
/// <summary>Optional RynthPluginRenderOverlay: ImGui windows drawn while the ImGui shell is off.</summary>
public PluginRenderDelegate? RenderOverlay { get; set; }
/// <summary>Set after the first RenderOverlay call has been logged (render thread only).</summary>
public bool RenderOverlayLogged { get; set; }
/// <summary>
/// Optional <c>int RynthPluginRenderEmbed(const char* surface, float width, float height,
/// float* wantWidth, float* wantHeight)</c>, Cdecl: the plugin draws a named surface into the
/// engine's current ImGui window (PluginManager.RenderEmbed). Zeroed after it throws.
/// </summary>
public IntPtr RenderEmbedPtr { get; set; }
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
public bool UiExportsResolved { get; set; }
@ -85,4 +97,45 @@ internal sealed class LoadedPlugin
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; } = "";
/// <summary>
/// Drops managed delegates wrapping exports so the native module can fully unload after
/// the host calls FreeLibrary (hot-reload / rescan).
/// </summary>
internal void ClearResolvedDelegates()
{
Init = null;
Shutdown = null;
GetName = null;
GetVersion = null;
OnLoginComplete = null;
OnUIInitialized = null;
OnBusyCountIncremented = null;
OnBusyCountDecremented = null;
OnSelectedTargetChange = null;
OnCombatModeChange = null;
OnSmartBoxEventPtr = IntPtr.Zero;
OnSmartBoxEvent = null;
OnDeleteObject = null;
OnCreateObject = null;
OnUpdateObjectPtr = IntPtr.Zero;
OnUpdateObject = null;
OnUpdateObjectInventory = null;
OnViewObjectContents = null;
OnStopViewingObjectContents = null;
OnVendorOpen = null;
OnVendorClose = null;
OnUpdateHealthPtr = IntPtr.Zero;
OnUpdateHealth = null;
OnChatWindowTextPtr = IntPtr.Zero;
OnChatWindowText = null;
OnChatBarEnter = null;
OnBarAction = null;
OnEnchantmentAdded = null;
OnEnchantmentRemoved = null;
Tick = null;
Render = null;
RenderOverlay = null;
RenderEmbedPtr = IntPtr.Zero;
}
}

View file

@ -10,7 +10,18 @@
// const char* RynthPluginName() — human-readable name
// const char* RynthPluginVersion() — version string (e.g. "1.0.0")
// void RynthPluginTick() — per-frame logic (before render)
// void RynthPluginRender() — per-frame ImGui drawing
// void RynthPluginRender() — per-frame ImGui drawing (ImGui shell on)
// void RynthPluginRenderOverlay() — per-frame ImGui drawing while the ImGui shell is
// off (Avalonia mode): only windows that have no
// Avalonia panel. Gated by engine.json
// "EnablePluginOverlayWindows" (default true).
// int RynthPluginRenderEmbed(const char* surface, float width, float height,
// float* wantWidth, float* wantHeight)
// — draws a named surface (UTF-8, e.g. RynthAi's
// "miniremote") into the engine's current ImGui
// window on AC's render thread, inside a
// width x height child; reports the size it wants.
// 1 = drawn, 0 = not ready / unknown surface.
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn
@ -864,6 +875,15 @@ internal struct RynthCoreAPI
/// Returns 1 sent or queued, 0 refused before sending (bad ids, negative placement), -1 the
/// sender isn't bound on this client. Requires API v80+.</summary>
public IntPtr PutItemInContainerFn;
/// <summary>v81: <c>int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)</c>:
/// outcome of the latest MergeStackInternal(source, target) request: 0 none, 1 queued,
/// 2 sent (amount = units sent), 3 skipped because the target was already full,
/// 4 failed (invalid ids / AC rejected / threw), 5 dropped (main-thread queue full).
/// ageMs = how long ago the outcome was recorded. Either out pointer may be null.
/// The thunk is cdecl. Any thread. Requires API v81+ (it was v77 on QOL-items and v80 on sk
/// before upstream's v77-v80 landed; plugins built against those SDKs must be rebuilt).</summary>
public IntPtr GetMergeStackResultFn;
}
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
@ -1654,6 +1674,10 @@ internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* it
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status);
// Cdecl is mandatory on every API delegate: without it x86 marshals a stdcall thunk, the callee and
// the cdecl caller both pop the args, and the plugin's stack drifts on every call.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetMergeStackResultCallbackDelegate(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence);

View file

@ -15,5 +15,6 @@ 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 = 80;
// v81: GetMergeStackResult (was v77 on QOL-items, then v80; renumbered after upstream's v77-v80).
public const uint Current = 81;
}

View file

@ -89,6 +89,9 @@ internal static class PluginLoader
/// </summary>
public static void Unload(LoadedPlugin plugin)
{
// Release managed thunks first so the module ref-count can drop to zero on FreeLibrary.
plugin.ClearResolvedDelegates();
if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle))
{
ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away
@ -506,6 +509,13 @@ internal static class PluginLoader
if (renderPtr != IntPtr.Zero)
plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr);
IntPtr renderOverlayPtr = GetProcAddress(handle, "RynthPluginRenderOverlay");
if (renderOverlayPtr != IntPtr.Zero)
plugin.RenderOverlay = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderOverlayPtr);
// Called through a function pointer (PluginManager.RenderEmbed), so no delegate here.
plugin.RenderEmbedPtr = GetProcAddress(handle, "RynthPluginRenderEmbed");
// Read name/version from the plugin if available
if (plugin.GetName != null)
{

View file

@ -271,6 +271,7 @@ internal static partial class PluginManager
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
private static VendorSellCallbackDelegate? _vendorSellCallback;
private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback;
private static GetMergeStackResultCallbackDelegate? _getMergeStackResultCallback;
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
@ -1142,6 +1143,154 @@ internal static partial class PluginManager
}
}
/// <summary>
/// ImGui-shell-off counterpart of <see cref="RenderAll"/>: calls the optional
/// RynthPluginRenderOverlay export, where a plugin draws only the extra windows that have
/// no Avalonia panel (e.g. RynthAi's ILT Hub). They float beside the Avalonia UI and add to it.
/// A throw switches off just that plugin's overlay windows; the plugin is NOT marked Failed,
/// so its tick/automation and Avalonia panels keep running.
/// </summary>
public static void RenderOverlayAll()
{
_overlayCalls++;
if (!_loginCompleteObserved)
{
if (!_loggedOverlayWaitingForLogin)
{
_loggedOverlayWaitingForLogin = true;
RynthLog.Info("PluginManager: RenderOverlayAll called - waiting for login before drawing overlay windows.");
}
return; // same not-in-world crash zone guard as RenderAll
}
LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
// Count plugins that will actually be called; log whenever that set changes.
int bound = 0;
for (int i = 0; i < plugins.Length; i++)
{
var p = plugins[i];
if (p.Initialized && !p.Failed && p.RenderOverlay != null) bound++;
}
_overlayBound = bound;
if (bound != _loggedOverlayBound || plugins.Length != _loggedOverlayTotal)
{
_loggedOverlayBound = bound;
_loggedOverlayTotal = plugins.Length;
var sb = new System.Text.StringBuilder();
for (int i = 0; i < plugins.Length; i++)
{
var p = plugins[i];
if (sb.Length > 0) sb.Append(", ");
sb.Append(p.DisplayName).Append('(')
.Append(p.RenderOverlay != null ? "overlay" : "no-overlay")
.Append(p.Initialized ? "" : ",not-init")
.Append(p.Failed ? ",failed" : "")
.Append(')');
}
RynthLog.Info($"PluginManager: RenderOverlayAll login seen, {bound} of {plugins.Length} plugin(s) will draw overlay windows: {sb}.");
}
for (int i = 0; i < plugins.Length; i++)
{
var plugin = plugins[i];
var overlay = plugin.RenderOverlay;
if (!plugin.Initialized || plugin.Failed || overlay == null)
continue;
if (!plugin.RenderOverlayLogged)
{
// One line per plugin per session: proves the engine is actually driving the overlay export.
plugin.RenderOverlayLogged = true;
RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}.");
}
try
{
overlay();
}
catch (Exception ex)
{
plugin.RenderOverlay = null;
RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running).");
}
}
}
// RenderOverlayAll diagnostics (render thread only).
private static long _overlayCalls;
private static int _overlayBound;
private static bool _loggedOverlayWaitingForLogin;
private static int _loggedOverlayBound = -1;
private static int _loggedOverlayTotal = -1;
/// <summary>
/// True when an initialized, healthy plugin exports RynthPluginRenderOverlay. Reads the
/// render snapshot only (no lock, no allocation): safe every frame on the render thread.
/// </summary>
internal static bool HasOverlayPlugins
{
get
{
LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
for (int i = 0; i < plugins.Length; i++)
{
var p = plugins[i];
if (p.Initialized && !p.Failed && p.RenderOverlay != null) return true;
}
return false;
}
}
/// <summary>Overlay stats for the ImGui heartbeat line.</summary>
internal static string DescribeOverlayState()
=> $"overlayCalls={_overlayCalls} loginSeen={_loginCompleteObserved} overlayPlugins={_overlayBound}";
/// <summary>RenderEmbed results.</summary>
internal const int EmbedDrawn = 1, EmbedNotReady = 0, EmbedNoPlugin = -1, EmbedFailed = -2;
/// <summary>
/// Lets the plugin named <paramref name="pluginName"/> (display name contains it) draw the
/// surface <paramref name="surfaceUtf8"/> (NUL-terminated) into the current ImGui window,
/// through its optional RynthPluginRenderEmbed export. The caller has begun a child of
/// <paramref name="size"/> in the main ImGui context; the plugin draws only inside it and
/// reports the content size it wants in <paramref name="want"/> (zero when it didn't say).
/// Render thread only. Returns <see cref="EmbedDrawn"/>, <see cref="EmbedNotReady"/> (the
/// plugin isn't ready: before login, no ImGui context), <see cref="EmbedNoPlugin"/> (not
/// loaded, or too old to have the export) or <see cref="EmbedFailed"/> (it threw: the export
/// is switched off for this session; the plugin keeps running).
/// </summary>
internal static unsafe int RenderEmbed(string pluginName, ReadOnlySpan<byte> surfaceUtf8, System.Numerics.Vector2 size, out System.Numerics.Vector2 want)
{
want = System.Numerics.Vector2.Zero;
if (!_loginCompleteObserved) return EmbedNotReady; // same not-in-world guard as RenderAll
LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
for (int i = 0; i < plugins.Length; i++)
{
LoadedPlugin p = plugins[i];
if (!p.Initialized || p.Failed || !p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase))
continue;
IntPtr fn = p.RenderEmbedPtr;
if (fn == IntPtr.Zero) return EmbedNoPlugin;
float w = 0, h = 0;
try
{
int r;
fixed (byte* s = surfaceUtf8)
r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h);
want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0);
return r == 1 ? EmbedDrawn : EmbedNotReady;
}
catch (Exception ex)
{
p.RenderEmbedPtr = IntPtr.Zero;
RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running).");
return EmbedFailed;
}
}
return EmbedNoPlugin;
}
public static void ShutdownAll()
{
RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)...");
@ -2338,6 +2487,14 @@ internal static partial class PluginManager
// %APPDATA%\RynthCore\engine.json. The engine never auto-scans a
// bundled Plugins\ folder — that historically caused stray DLLs to
// load on next start (or after hot-reload) without the user knowing.
//
// Track DLL file names and canonical paths already staged this generation. engine.json can
// list the same plugin twice (e.g. a stale copy in another folder); a second File.Copy to the
// same shadow file name fails while the first copy is still mapped ("used by another process")
// and breaks hot-reload ordering for later DLLs.
var loadedBasenames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var loadedCanonicalPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var extraPaths = EngineSettings.PluginPaths;
var present = new List<string>(extraPaths.Count);
for (int i = 0; i < extraPaths.Count; i++)
@ -2398,7 +2555,29 @@ internal static partial class PluginManager
}
}
// RenderAll / RenderOverlayAll iterate only this snapshot; without it they see no plugins.
PublishPluginsRenderSnapshot();
RynthLog.Plugin($"PluginManager: render snapshot published ({_plugins.Count} plugin(s)).");
}
private static void TryAddCanonicalPath(HashSet<string> set, string path)
{
if (TryGetCanonicalPath(path, out string canon))
set.Add(canon);
}
private static bool TryGetCanonicalPath(string path, out string canonical)
{
try
{
canonical = Path.GetFullPath(path);
return true;
}
catch
{
canonical = string.Empty;
return false;
}
}
// ── Plugin manifests ─────────────────────────────────────────────────
@ -2796,6 +2975,7 @@ internal static partial class PluginManager
_vendorBuyCallback ??= VendorBuyAction;
_vendorSellCallback ??= VendorSellAction;
_getVendorTradeStatusCallback ??= GetVendorTradeStatusAction;
_getMergeStackResultCallback ??= GetMergeStackResultAction;
_api.Version = PluginContractVersion.Current;
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
@ -2941,6 +3121,7 @@ internal static partial class PluginManager
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
_api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback);
_api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback);
_api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback);
RouteApiThroughLoader();
}
@ -3665,6 +3846,22 @@ internal static partial class PluginManager
return ToAbiBool(ClientHelperHooks.MergeStackInternal(sourceObjectId, targetObjectId));
}
// v68: outcome of the latest MergeStackInternal(source, target) (MergeStackResults codes).
private static unsafe int GetMergeStackResultAction(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)
{
try
{
int status = MergeStackResults.Get(sourceObjectId, targetObjectId, out int sent, out int age);
if (amount != null) *amount = sent;
if (ageMs != null) *ageMs = age;
return status;
}
catch
{
return MergeStackResults.None;
}
}
private static int GiveObjectTo(uint objectId, uint targetId, int amount)
{
Compatibility.AcActionTrace.Record("GiveObjectTo", objectId, targetId);

View file

@ -6,6 +6,9 @@
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Unreachable code (CS0162) is always a bug here: a misplaced statement after a return
once left the plugin render snapshot unpublished and silently disabled every overlay window. -->
<WarningsAsErrors>$(WarningsAsErrors);CS0162</WarningsAsErrors>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
@ -66,9 +69,9 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Skia" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" />
<!-- Avalonia pulls Tmds.DBus.Protocol 0.20.0 (GHSA-xrw6-gwf8-vvr9; D-Bus is Linux-only, but pin the fixed version). -->
<!-- Overrides Avalonia.FreeDesktop transitive Tmds.DBus.Protocol (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" />
</ItemGroup>
<ItemGroup>

View file

@ -4,73 +4,67 @@ namespace RynthCore.Engine;
/// <summary>
/// Centralised logging — every log call in the Engine routes through here.
/// Toggle categories on/off at runtime to suppress entire subsystems.
/// Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
/// Each category method writes at that category's emit level (engine.json "LogCategories",
/// editable live from the launcher; see <see cref="LogSettings"/>), gated by the global
/// "LoggingLevel". Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
/// </summary>
internal static class RynthLog
{
// ── Category toggles (flip to false to silence a subsystem) ──────────
internal static bool D3D9Enabled = true;
internal static bool CompatEnabled = true;
internal static bool RenderEnabled = false; // ImGui, DX9Backend, Win32Backend
internal static bool PluginEnabled = true;
internal static bool UIEnabled = true;
// ── Category methods ─────────────────────────────────────────────────
/// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
internal static void D3D9(string msg)
{
if (D3D9Enabled) Write(msg);
}
internal static void D3D9(string msg) => WriteCategory(LogCategory.D3D9, msg);
/// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary>
internal static void Compat(string msg)
{
if (CompatEnabled) Write(msg);
}
internal static void Compat(string msg) => WriteCategory(LogCategory.Compat, msg);
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
internal static void Render(string msg)
{
if (RenderEnabled) Write(msg);
}
internal static void Render(string msg) => WriteCategory(LogCategory.Render, msg);
/// <summary>Plugin system: loader, manager, lifecycle callbacks.</summary>
internal static void Plugin(string msg)
{
if (PluginEnabled) Write(msg);
}
/// <summary>Plugin system: loader, manager, lifecycle callbacks, plugin host Log lines.</summary>
internal static void Plugin(string msg) => WriteCategory(LogCategory.Plugin, msg);
/// <summary>UI / Avalonia overlay subsystem.</summary>
internal static void UI(string msg)
{
if (UIEnabled) Write(msg);
}
internal static void UI(string msg) => WriteCategory(LogCategory.UI, msg);
/// <summary>Verbose-only log (any category). Only written when VerboseLogging is on.</summary>
internal static void Verbose(string msg)
{
if (EntryPoint.VerboseLogging) Write(msg);
}
/// <summary>Verbose detail (any subsystem). Debug by default; set the Verbose category to Info to see it in the normal log.</summary>
internal static void Verbose(string msg) => WriteCategory(LogCategory.Verbose, msg);
/// <summary>Always-on log for critical / uncategorised messages (INFO).</summary>
internal static void Info(string msg) => Write(msg);
/// <summary>Same as <see cref="Verbose"/>.</summary>
internal static void Debug(string msg) => WriteCategory(LogCategory.Verbose, msg);
/// <summary>Trace-level line: written only when the global level is Trace.</summary>
internal static void Trace(string msg) => WriteAt(EntryPoint.EngineLogLevel.Trace, msg);
/// <summary>Uncategorised line (General category, Info by default).</summary>
internal static void Info(string msg) => WriteCategory(LogCategory.General, msg);
/// <summary>Same as <see cref="Warn"/>.</summary>
internal static void Warning(string msg) => Warn(msg);
// Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box
// can be diagnosed remotely without reading the PC log.
// can be diagnosed remotely without reading the PC log. Recorded even when the line is filtered.
internal static volatile string? LastIssue;
internal static DateTime LastIssueUtc;
/// <summary>Always-on WARN line — a recoverable problem worth grepping for.</summary>
/// <summary>WARN line — a recoverable problem worth grepping for. Hidden only at level Error/Off.</summary>
internal static void Warn(string msg)
{
LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
EntryPoint.LogTagged("engine", msg, "WRN");
if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Warning))
EntryPoint.LogTagged("engine", msg, "WRN");
}
/// <summary>Always-on ERROR line — a fault/crash/disable. Triage with grep "[ERR]".</summary>
/// <summary>
/// Always-on heartbeat line, written at every LoggingLevel (Off included). The launcher's
/// wedge watchdog reads RynthCore.&lt;pid&gt;.log going quiet for 120 s as a dead engine and
/// kills the client, so this line must never be filtered: on 2026-10-06 LoggingLevel=Info
/// with General=Trace dropped it and healthy in-world clients were killed and relaunched
/// every few minutes.
/// </summary>
internal static void Heartbeat(string msg) => EntryPoint.LogTagged("engine", msg, "INF");
/// <summary>Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]".</summary>
internal static void Error(string msg)
{
LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
@ -154,7 +148,24 @@ internal static class RynthLog
: $"thread {Environment.CurrentManagedThreadId}";
}
/// <summary>True when a line in <paramref name="category"/> would be written (guard expensive messages).</summary>
internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category);
// ── Sink ─────────────────────────────────────────────────────────────
private static void Write(string message) => EntryPoint.Log(message);
/// <summary>Uncategorised line (General category); used by the Move/UseDone traces.</summary>
private static void Write(string? message)
{
if (message != null)
WriteCategory(LogCategory.General, message);
}
private static void WriteCategory(LogCategory category, string message)
=> WriteAt(LogSettings.LevelFor(category), message);
private static void WriteAt(EntryPoint.EngineLogLevel level, string message)
{
if (EntryPoint.ShouldLog(level))
EntryPoint.LogTagged("engine", message, LogSettings.Tag(level));
}
}

View file

@ -0,0 +1,78 @@
// ============================================================================
// RynthCore.Engine - UI/Data/CharmsData.cs
// RynthAi's ACECustom charm tracker for the Settings panel's "Charms
// Tracking" tab. RynthAi owns the charm registry (WCIDs, ability flags) and
// the per-character "seen" memory; this side only shows the snapshot.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthPluginGetCharmsJson's payload.</summary>
internal sealed class CharmsInfo
{
/// <summary>False off ILT-like worlds (or before RynthAi's ILT Hub exists).</summary>
[JsonPropertyName("available")] public bool Available { get; set; }
[JsonPropertyName("world")] public string World { get; set; } = "";
[JsonPropertyName("total")] public int Total { get; set; }
[JsonPropertyName("acquiredCount")] public int AcquiredCount { get; set; }
[JsonPropertyName("activeCount")] public int ActiveCount { get; set; }
[JsonPropertyName("charms")] public CharmRow[] Charms { get; set; } = Array.Empty<CharmRow>();
}
internal sealed class CharmRow
{
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("effect")] public string Effect { get; set; } = "";
/// <summary>"carried" (in pack / equipped now), "seen" (carried before, now elsewhere) or "no".</summary>
[JsonPropertyName("acquired")] public string Acquired { get; set; } = "no";
/// <summary>Copies carried right now.</summary>
[JsonPropertyName("count")] public int Count { get; set; }
/// <summary>Best tier carried or last seen; 0 until an appraisal reports it.</summary>
[JsonPropertyName("tier")] public int Tier { get; set; }
[JsonPropertyName("maxTier")] public int MaxTier { get; set; }
/// <summary>Ability toggled on: "on", "off" or "unknown".</summary>
[JsonPropertyName("active")] public string Active { get; set; } = "unknown";
/// <summary>Server-side global switch as far as the client has learned it: "on", "off" or "unknown".</summary>
[JsonPropertyName("server")] public string Server { get; set; } = "unknown";
/// <summary>yyyy-MM-dd the charm was last carried (empty when never).</summary>
[JsonPropertyName("lastSeen")] public string LastSeen { get; set; } = "";
}
[JsonSerializable(typeof(CharmsInfo))]
internal sealed partial class CharmsJsonContext : JsonSerializerContext { }
/// <summary>
/// RynthPluginGetCharmsJson (single static buffer: one caller only) while the Settings panel
/// is open. Every 2 s is plenty: charm state only changes when one is picked up or toggled.
/// </summary>
internal sealed unsafe class CharmsSource : UiSource<CharmsInfo>
{
private delegate* unmanaged[Cdecl]<IntPtr> _getCharmsJson;
public CharmsSource() : base("Charms", periodMs: 2000) { }
protected internal override void Poll()
{
if (_getCharmsJson == null)
_getCharmsJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetCharmsJson");
if (_getCharmsJson == null) return;
IntPtr p = _getCharmsJson();
string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
CharmsInfo info;
try { info = JsonSerializer.Deserialize(json, CharmsJsonContext.Default.CharmsInfo) ?? new CharmsInfo(); }
catch (JsonException) { info = new CharmsInfo(); }
Publish(info);
}
protected internal override void Reset()
{
_getCharmsJson = null;
ClearSnapshot();
}
}

View file

@ -604,6 +604,8 @@ internal static class ChatModel
foreach (string t in Volatile.Read(ref _customTabs)) if (seen.Add(t)) tabs.Add(t);
foreach (ChatFilterRule rule in Filters)
if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 && seen.Add(rule.Tab)) tabs.Add(rule.Tab);
foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs())
if (seen.Add(t)) tabs.Add(t);
string[] result = tabs.ToArray();
_allTabs = (version, result);
return result;
@ -674,6 +676,9 @@ internal static class ChatModel
foreach (ChatFilterRule rule in Filters)
if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase))
rule.Tab = newName;
foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All)
if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase))
preset.Tab = newName;
if (string.Equals(ActiveChannel, tab, StringComparison.OrdinalIgnoreCase)) ActiveChannel = newName;
FiltersChanged();
return true;
@ -690,6 +695,9 @@ internal static class ChatModel
if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy
&& string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase))
rule.Enabled = false;
foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All)
if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase))
preset.Enabled = false;
FiltersChanged();
}
@ -1350,6 +1358,16 @@ internal static class ChatModel
&& !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase))
tabs.Add(rule.Tab);
}
foreach (RynthChatPresetDto p in dto.Presets ?? Array.Empty<RynthChatPresetDto>())
{
var preset = p.Id == null ? null : RynthCore.Engine.UI.Panels.RynthChatPresets.Get(p.Id);
if (preset == null) continue; // a preset a later build removed
preset.Enabled = p.Enabled;
preset.Tab = (p.Tab ?? "").Trim();
if (preset.Tab.Length > 0 && !IsBaseTab(preset.Tab)
&& !tabs.Contains(preset.Tab, StringComparer.OrdinalIgnoreCase))
tabs.Add(preset.Tab);
}
_customTabs = tabs.ToArray();
_filters = rules.ToArray();
Interlocked.Increment(ref _filtersVersion);
@ -1404,6 +1422,11 @@ internal static class ChatModel
LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set
CustomTabs = Volatile.Read(ref _customTabs),
Filters = Filters.Select(ToDto).ToArray(),
// Only presets the user touched: new presets in later builds start off.
Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All
.Where(p => p.Enabled || p.Tab.Length > 0)
.Select(p => new RynthChatPresetDto { Id = p.Id, Enabled = p.Enabled, Tab = p.Tab.Length > 0 ? p.Tab : null })
.ToArray(),
};
UiBackgroundWriter.Enqueue("persist chat settings", () =>
{

View file

@ -292,9 +292,12 @@ internal sealed class ChatRouter
foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0);
}
/// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary>
/// <summary>One step of the editor's test: rule index (-1 = mention, -2 = a standard filter) and what it did.</summary>
public readonly record struct Step(int Rule, string What);
/// <summary><see cref="Step.Rule"/> of a standard-filter (RynthChatPresets) step.</summary>
public const int StandardFilterStep = -2;
public ChatRoute Evaluate(ChatLine line, List<Step>? trace) =>
Evaluate(line.Text, line.Channel, line.ChatType, trace);
@ -383,6 +386,28 @@ internal sealed class ChatRouter
trace?.Add(new Step(i, what!.ToString()));
}
// Standard filters (RynthChatPresets) decide only what the custom rules left undecided.
if (!routed)
{
var preset = RynthCore.Engine.UI.Panels.RynthChatPresets.FirstMatch(text, channel);
if (preset != null)
{
string presetTab = preset.Tab;
routed = true;
if (presetTab.Length == 0)
{
hidden = true;
trace?.Add(new Step(StandardFilterStep, $"standard filter \"{preset.Label}\" hides it"));
}
else
{
inHome = false;
AddTab(ref tabs, presetTab);
trace?.Add(new Step(StandardFilterStep, $"standard filter \"{preset.Label}\" moves it to {presetTab}"));
}
}
}
bool mention = false;
if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType))
{

View file

@ -66,6 +66,16 @@ internal sealed class RynthChatSettingsDto
[JsonPropertyName("historyLines")] public int? HistoryLines { get; set; }
[JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; }
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
/// <summary>Standard filters' user state (RynthChatPresets); absent while none was changed.</summary>
[JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; }
}
/// <summary>A standard filter's user state (RynthChatPresets), by preset id.</summary>
internal sealed class RynthChatPresetDto
{
[JsonPropertyName("id")] public string? Id { get; set; }
[JsonPropertyName("enabled")] public bool Enabled { get; set; }
[JsonPropertyName("tab")] public string? Tab { get; set; }
}
/// <summary>Export / import on the clipboard (the rule editor's Export and Import).</summary>

View file

@ -63,11 +63,14 @@ internal sealed unsafe class ItemsSource : UiSource<ItemsSnapshot>
internal static unsafe class ItemsCommands
{
private static delegate* unmanaged[Cdecl]<IntPtr, void> _set;
private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addConsumable;
private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addShield, _addConsumable;
/// <summary>ItemRule.Action value the plugin uses for off-hand shields.</summary>
public const string ShieldAction = "Shield";
static ItemsCommands()
{
PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addConsumable = null; };
PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addShield = null; _addConsumable = null; };
}
public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
@ -94,6 +97,18 @@ internal static unsafe class ItemsCommands
UiSources.Items.RequestRefresh();
});
/// <summary>
/// Adds the item selected in the inventory as an off-hand shield. RynthAi older than
/// 0.6.20 has no such export: the click is logged and dropped.
/// </summary>
public static void AddSelectedShield() => UiDataHub.Post("Items add shield", () =>
{
if (_addShield == null) _addShield = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedShield");
if (_addShield != null) _addShield();
else RynthLog.UI("ItemsCommands: Add Selected Shield unavailable - RynthAi 0.6.20 or newer is required.");
UiSources.Items.RequestRefresh();
});
/// <summary>Adds the item selected in the inventory as a consumable.</summary>
public static void AddSelectedConsumable() => UiDataHub.Post("Items add consumable", () =>
{

View file

@ -40,6 +40,17 @@ internal sealed class NavPayload
public int ActiveNavIndex { get; set; }
public List<string> NavFiles { get; set; } = new();
public List<NavPoint> Points { get; set; } = new();
/// <summary>RynthAi records (and draws) the walked breadcrumb trail. Older plugins omit it (false).</summary>
public bool TrackBreadcrumbs { get; set; }
/// <summary>RynthAi draws the route overlay (rings / lines, waypoint labels, guide line).</summary>
public bool ShowRouteOverlay { get; set; }
/// <summary>Route recording is on (points are added as you walk). Older plugins omit it.</summary>
public bool IsRecording { get; set; }
/// <summary>Breadcrumb trail size, for "Trail to route" / "Backtrack".</summary>
public int TrailPoints { get; set; }
public double TrailYards { get; set; }
/// <summary>The last route edit's result, for a few seconds after it (empty otherwise).</summary>
public string EditStatus { get; set; } = string.Empty;
/// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary>
public NavPayload Clone()
@ -60,6 +71,12 @@ internal sealed class NavCmd
public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty; // addChat
public bool On { get; set; } // setBreadcrumbs / setRouteOverlay / setRecording
public List<int>? Indices { get; set; } // movePoints / duplicatePoints / deletePoints
public int Delta { get; set; } // movePoints: -1 up, +1 down
public double Seconds { get; set; } // addPause
public double Yards { get; set; } // simplifyRoute tolerance
public bool Reverse { get; set; } // trailToRoute: backtrack
}
[JsonSerializable(typeof(NavPayload))]
@ -105,6 +122,19 @@ internal static class NavCommands
public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" };
public static readonly string[] AddModes = { "End", "Above", "Below" };
public static readonly double[] PauseSeconds = { 1, 2, 3, 5, 10, 15, 30, 60 };
public static readonly string[] PauseLabels = Array.ConvertAll(PauseSeconds, s => $"Pause {s:0} s");
public static readonly double[] SimplifyYards = { 0.5, 1, 2, 3, 5 };
public static readonly string[] SimplifyLabels =
Array.ConvertAll(SimplifyYards, y => $"Drop points within {y:0.#} yd of a straight line");
public static readonly string[] TrailChoices =
{
"Replace route with the trail (walk it again)",
"Replace route with a backtrack (walk it back)",
};
/// <summary>Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).</summary>
public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };

View file

@ -0,0 +1,206 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ProgressionData.cs
// RynthAi's ILT progression planners (augmentations, enlightenment) and the
// infinite-attribute raiser for the Skills panel's Progression tab. RynthAi owns the math and the persisted
// inputs; this side only shows the snapshot and sends "prog ..." remote
// commands (RynthAiCommands.ApplyRemoteCommand) for edits and actions.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthPluginGetProgressionJson's payload. Display strings arrive preformatted.</summary>
internal sealed class ProgressionInfo
{
/// <summary>False off ILT-like worlds (or before the ILT Hub exists): the tab is hidden.</summary>
[JsonPropertyName("available")] public bool Available { get; set; }
[JsonPropertyName("world")] public string World { get; set; } = "";
[JsonPropertyName("aug")] public AugPlanner Aug { get; set; } = new();
[JsonPropertyName("enl")] public EnlPlanner Enl { get; set; } = new();
/// <summary>Absent from an older RynthAi: stays empty and the section shows "update RynthAi".</summary>
[JsonPropertyName("attr")] public AttrRaiser? Attr { get; set; }
}
/// <summary>RynthAi's IltAttributeRaiser: server costs ("/xp all") and the raise settings.</summary>
internal sealed class AttrRaiser
{
/// <summary>The raiser can't run here; <see cref="Reason"/> says why.</summary>
[JsonPropertyName("off")] public bool Off { get; set; }
[JsonPropertyName("reason")] public string Reason { get; set; } = "";
[JsonPropertyName("auto")] public bool Auto { get; set; }
/// <summary>Minutes between auto-raise runs.</summary>
[JsonPropertyName("every")] public int Every { get; set; } = 5;
/// <summary>0 priority, 1 round robin, 2 cheapest first.</summary>
[JsonPropertyName("mode")] public int Mode { get; set; }
[JsonPropertyName("running")] public bool Running { get; set; }
/// <summary>XP reserve, preformatted ("0", "1.50B").</summary>
[JsonPropertyName("keep")] public string Keep { get; set; } = "0";
/// <summary>XP reserve in full ("1,234,567"): what the reserve box edits.</summary>
[JsonPropertyName("keepFull")] public string KeepFull { get; set; } = "";
[JsonPropertyName("status")] public string Status { get; set; } = "";
[JsonPropertyName("lastRun")] public string LastRun { get; set; } = "";
[JsonPropertyName("unassigned")] public string Unassigned { get; set; } = "";
/// <summary>Time to the next auto run ("" when auto is off).</summary>
[JsonPropertyName("next")] public string Next { get; set; } = "";
[JsonPropertyName("costsAge")] public string CostsAge { get; set; } = "";
/// <summary>Local time the costs were last read ("-" before the first read; "" from older RynthAi).</summary>
[JsonPropertyName("updated")] public string Updated { get; set; } = "";
/// <summary>"Level N Total XP X Unassigned Y" ("" from older RynthAi).</summary>
[JsonPropertyName("xpHeader")] public string XpHeader { get; set; } = "";
/// <summary>In raise-priority order.</summary>
[JsonPropertyName("rows")] public AttrRow[] Rows { get; set; } = Array.Empty<AttrRow>();
}
internal sealed class AttrRow
{
/// <summary>/attr abbreviation: str end coo qui foc sel hea sta man.</summary>
[JsonPropertyName("key")] public string Key { get; set; } = "";
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("vital")] public bool Vital { get; set; }
/// <summary>Ticked: "Raise now" and auto-raise may spend on it.</summary>
[JsonPropertyName("on")] public bool On { get; set; }
/// <summary>Base value RynthAi last saw in a server reply (-1 = unknown; the panel prefers the client's).</summary>
[JsonPropertyName("base")] public int Base { get; set; } = -1;
/// <summary>Next-level cost from "/xp all", preformatted ("?" until read).</summary>
[JsonPropertyName("cost")] public string Cost { get; set; } = "?";
/// <summary>Next level fits the raiser's budget (unassigned minus the reserve).</summary>
[JsonPropertyName("afford")] public bool Afford { get; set; }
/// <summary>The next-level cost has been read (false from older RynthAi too).</summary>
[JsonPropertyName("known")] public bool Known { get; set; }
/// <summary>By hand: +1 fits the unassigned XP (no reserve).</summary>
[JsonPropertyName("afford1")] public bool Afford1 { get; set; }
/// <summary>By hand: the projected +10 fits the unassigned XP.</summary>
[JsonPropertyName("afford10")] public bool Afford10 { get; set; }
/// <summary>Projected cost of ten levels (7.7% growth per level), e.g. "~1.2T"; "" from older RynthAi.</summary>
[JsonPropertyName("cost10")] public string Cost10 { get; set; } = "";
/// <summary>Exact next-level cost with separators, for the tooltip.</summary>
[JsonPropertyName("costFull")] public string CostFull { get; set; } = "";
[JsonPropertyName("cost10Full")] public string Cost10Full { get; set; } = "";
}
internal sealed class AugPlanner
{
/// <summary>The server reports /aug off.</summary>
[JsonPropertyName("off")] public bool Off { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = "";
[JsonPropertyName("lumPerCoin")] public long LumPerCoin { get; set; }
[JsonPropertyName("rows")] public AugRow[] Rows { get; set; } = Array.Empty<AugRow>();
[JsonPropertyName("total")] public string Total { get; set; } = "";
/// <summary>Empty when the bank holds enough Enlightened Coins.</summary>
[JsonPropertyName("short")] public string Short { get; set; } = "";
[JsonPropertyName("banked")] public string Banked { get; set; } = "";
// Totals row and e-coin summary (all empty / zero from older RynthAi).
[JsonPropertyName("totCur")] public long TotalCurrent { get; set; }
[JsonPropertyName("totTgt")] public long TotalTarget { get; set; }
[JsonPropertyName("totInc")] public long TotalIncrease { get; set; }
[JsonPropertyName("totLum")] public string TotalLum { get; set; } = "";
[JsonPropertyName("totCoins")] public long TotalCoins { get; set; }
[JsonPropertyName("coinsLine")] public string CoinsLine { get; set; } = "";
[JsonPropertyName("lumToBuy")] public string LumToBuy { get; set; } = "";
/// <summary>Ready-made clipboard texts (UB's Copy Discord / Copy In-Game).</summary>
[JsonPropertyName("copyDiscord")] public string CopyDiscord { get; set; } = "";
[JsonPropertyName("copyIngame")] public string CopyIngame { get; set; } = "";
/// <summary>This world's cost rules for the Cost settings editor (null from older RynthAi).</summary>
[JsonPropertyName("cfg")] public AugCostConfig? Config { get; set; }
}
/// <summary>Per-server aug cost rules: level i costs (Base + (i-1)*Base*Pct/100) x the multiplier of its tier.</summary>
internal sealed class AugCostConfig
{
[JsonPropertyName("world")] public string World { get; set; } = "";
/// <summary>The world has its own saved rules (false = UB / InfiniteLeaftide defaults).</summary>
[JsonPropertyName("custom")] public bool Custom { get; set; }
/// <summary>Tier multipliers: below S1, from S1, from S2, from S3, from S4.</summary>
[JsonPropertyName("mults")] public double[] Multipliers { get; set; } = Array.Empty<double>();
[JsonPropertyName("rows")] public AugCostRule[] Rows { get; set; } = Array.Empty<AugCostRule>();
}
internal sealed class AugCostRule
{
[JsonPropertyName("key")] public string Key { get; set; } = "";
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("base")] public long Base { get; set; }
/// <summary>Percent of Base added per level.</summary>
[JsonPropertyName("pct")] public double Percent { get; set; }
[JsonPropertyName("coins")] public int Coins { get; set; }
[JsonPropertyName("s1")] public int S1 { get; set; }
[JsonPropertyName("s2")] public int S2 { get; set; }
[JsonPropertyName("s3")] public int S3 { get; set; }
[JsonPropertyName("s4")] public int S4 { get; set; }
/// <summary>Highest target (0 = no limit).</summary>
[JsonPropertyName("cap")] public int Cap { get; set; }
}
internal sealed class AugRow
{
[JsonPropertyName("key")] public string Key { get; set; } = "";
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("cur")] public int Current { get; set; }
[JsonPropertyName("tgt")] public int Target { get; set; }
/// <summary>Levels planned (target - current).</summary>
[JsonPropertyName("inc")] public int Increase { get; set; }
/// <summary>Highest target allowed (the aug's cap, or the current level when the server reports more).</summary>
[JsonPropertyName("cap")] public int Cap { get; set; }
[JsonPropertyName("lum")] public string Lum { get; set; } = "-";
[JsonPropertyName("coins")] public long Coins { get; set; }
}
internal sealed class EnlPlanner
{
/// <summary>The server reports /enl off.</summary>
[JsonPropertyName("off")] public bool Off { get; set; }
[JsonPropertyName("header")] public string Header { get; set; } = "";
[JsonPropertyName("next")] public string Next { get; set; } = "";
[JsonPropertyName("enl")] public int Level { get; set; }
[JsonPropertyName("target")] public int Target { get; set; }
[JsonPropertyName("plan")] public string[] Plan { get; set; } = Array.Empty<string>();
[JsonPropertyName("coinsPerToken")] public int CoinsPerToken { get; set; }
[JsonPropertyName("tokensShort")] public string TokensShort { get; set; } = "";
/// <summary>Client-side requirements not yet met; empty = the client checks pass.</summary>
[JsonPropertyName("blockers")] public string[] Blockers { get; set; } = Array.Empty<string>();
[JsonPropertyName("serverChecks")] public string ServerChecks { get; set; } = "";
[JsonPropertyName("auto")] public bool Auto { get; set; }
/// <summary>Auto-enlighten is disarmed every session until confirmed again.</summary>
[JsonPropertyName("armed")] public bool Armed { get; set; }
[JsonPropertyName("spendFirst")] public bool SpendFirst { get; set; }
[JsonPropertyName("checkEvery")] public int CheckEvery { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = "";
}
[JsonSerializable(typeof(ProgressionInfo))]
internal sealed partial class ProgressionJsonContext : JsonSerializerContext { }
/// <summary>
/// RynthPluginGetProgressionJson (single static buffer: one caller only) while the Skills
/// panel is open, and right after each Progression edit (RequestRefreshAfterPluginTick).
/// </summary>
internal sealed unsafe class ProgressionSource : UiSource<ProgressionInfo>
{
private delegate* unmanaged[Cdecl]<IntPtr> _getProgressionJson;
public ProgressionSource() : base("Progression", periodMs: 1000) { }
protected internal override void Poll()
{
if (_getProgressionJson == null)
_getProgressionJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetProgressionJson");
if (_getProgressionJson == null) return;
IntPtr p = _getProgressionJson();
string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
ProgressionInfo info;
try { info = JsonSerializer.Deserialize(json, ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); }
catch (JsonException) { info = new ProgressionInfo(); }
Publish(info);
}
protected internal override void Reset()
{
_getProgressionJson = null;
ClearSnapshot();
}
}

View file

@ -41,6 +41,11 @@ internal sealed class RynthAiSnapshot
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; }
[JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; }
[JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; }
// Buff profiles (RynthAi 0.5.31+): "Built-in" first, then BuffProfiles\*.json. Older plugins
// send none, and the Buffs picker then shows "Built-in" with nothing to pick.
[JsonPropertyName("buffProfiles")] public string[] BuffProfiles { get; set; } = Array.Empty<string>();
[JsonPropertyName("currentBuffName")] public string CurrentBuffName { get; set; } = string.Empty;
[JsonPropertyName("selectedBuffIdx")] public int SelectedBuffIdx { get; set; }
[JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; }
[JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; }
[JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; }
@ -85,6 +90,8 @@ internal sealed class RynthAiView
public required string NavText { get; init; }
public required string LootText { get; init; }
public required string MetaText { get; init; }
/// <summary>Buff profile buffing uses ("Built-in" without one).</summary>
public required string BuffText { get; init; }
public required string TargetHeadline { get; init; }
public required int TargetSegmentsLit { get; init; }
public required bool ShowTargetSubBars { get; init; }
@ -164,6 +171,7 @@ internal sealed unsafe class RynthAiSource : UiSource<RynthAiView>
NavText = Truncate(s.CurrentNavName, 16),
LootText = Truncate(s.CurrentLootName, 16),
MetaText = Truncate(s.CurrentMetaName, 16),
BuffText = Truncate(string.IsNullOrWhiteSpace(s.CurrentBuffName) ? "Built-in" : s.CurrentBuffName, 16),
TargetHeadline = Truncate(label, 32),
TargetSegmentsLit = lit,
ShowTargetSubBars = showSub,
@ -265,6 +273,7 @@ internal static unsafe class RynthAiCommands
private static delegate* unmanaged[Cdecl]<float, void> _adjustOpacity;
private static delegate* unmanaged[Cdecl]<void> _togglePanelLock;
private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendNavCommand;
private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _applyRemoteCommand;
static RynthAiCommands()
{
@ -272,6 +281,7 @@ internal static unsafe class RynthAiCommands
{
_toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null;
_cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null;
_applyRemoteCommand = null;
};
}
@ -341,6 +351,29 @@ internal static unsafe class RynthAiCommands
if (refreshPatrol) UiSources.Patrol.RequestRefresh();
UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll
});
/// <summary>
/// RynthPluginApplyRemoteCommand(action, value) - the same (action, value) pairs as the
/// plugin's /ra chat commands ("huds","show"; "remote","toggle"; "hub","show" ...).
/// Older RynthAi builds without the export drop the command (logged once per bind miss).
/// </summary>
public static void ApplyRemoteCommand(string action, string value) => Run("remote command " + action, () =>
{
if (_applyRemoteCommand == null) _applyRemoteCommand = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)Export("RynthPluginApplyRemoteCommand");
if (_applyRemoteCommand == null)
{
RynthLog.UI($"RynthAiCommands: RynthPluginApplyRemoteCommand not exported; dropped '{action} {value}'.");
return;
}
IntPtr a = Marshal.StringToHGlobalAnsi(action);
IntPtr b = Marshal.StringToHGlobalAnsi(value);
try { _applyRemoteCommand(a, b); }
finally
{
Marshal.FreeHGlobal(a);
Marshal.FreeHGlobal(b);
}
});
}
/// <summary>RynthPluginGetPatrolInfoJson's payload (patrol flyout).</summary>

View file

@ -11,6 +11,7 @@
// ============================================================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -47,6 +48,13 @@ internal sealed class RynthAiSettings
// Decal bridge: stop RynthAi's macro when VTank's starts (one bot per client). Default on;
// an older RynthAi doesn't send it, and a missing field must not read as "off".
public bool YieldToVTank { get; set; } = true;
// Server Features (RynthAi ServerFeatureGate): world names that turn on the ILT Hub, the
// Progression planners and the attribute raiser, plus a manual override. An older RynthAi
// doesn't send them; RynthAi lays a save over its current values, so these defaults are
// only ever shown, never applied. ServerFeaturesStatus is read-only (RynthAi ignores it).
public string FeatureServerNames { get; set; } = "InfiniteLeaftide, *Leaftide*";
public bool ForceServerFeatures { get; set; }
public string ServerFeaturesStatus { get; set; } = string.Empty;
public bool EnableRaycasting { get; set; }
public bool UseArcs { get; set; }
public float BowArcVelocity { get; set; } = 25f;
@ -219,6 +227,15 @@ internal sealed class RynthAiSettings
public int SalvageSalvageDelayMs { get; set; } = 50;
public int SalvageResultDelayFirstMs { get; set; } = 1000;
public int SalvageResultDelayFastMs { get; set; } = 250;
// Ground loot and item info
public bool EnableGroundLoot { get; set; }
// Diagnostics (RynthAi's RynthLog: per PC in Logs\Diagnostics\diagnostics.json, not the profile)
public bool DiagDebugToChat { get; set; }
public bool DiagFileLogAll { get; set; } = true;
/// <summary>"Name=Level" per trace category, ','-joined; Level 0 Off, 1 Trace, 2 Info. See <see cref="TraceCategoryLevels"/>.</summary>
public string DiagCategories { get; set; } = string.Empty;
/// <summary>Read-only (RynthAi ignores it on save): the diagnostics folder.</summary>
public string DiagFolder { get; set; } = string.Empty;
/// <summary>A private copy for a face to edit (all members are values or strings).</summary>
public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone();
@ -289,7 +306,60 @@ internal static unsafe class SettingsCommands
// ── Schema ─────────────────────────────────────────────────────────────────
internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus }
internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status }
/// <summary>
/// Reads and edits <see cref="RynthAiSettings.DiagCategories"/> ("Name=Level,..."). The category
/// list comes from RynthAi, so a category it adds shows up without an engine change.
/// </summary>
internal static class TraceCategoryLevels
{
public const int Off = 0, Trace = 1, Info = 2;
/// <summary>The categories in RynthAi's order; malformed entries are skipped.</summary>
public static List<(string Name, int Level)> Parse(string? levels)
{
var list = new List<(string, int)>();
if (string.IsNullOrWhiteSpace(levels)) return list;
foreach (string entry in levels.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
int eq = entry.IndexOf('=');
if (eq <= 0 || !int.TryParse(entry[(eq + 1)..], out int level)) continue;
list.Add((entry[..eq], Math.Clamp(level, Off, Info)));
}
return list;
}
private static string Format(List<(string Name, int Level)> list)
{
var parts = new string[list.Count];
for (int i = 0; i < list.Count; i++) parts[i] = list[i].Name + "=" + list[i].Level;
return string.Join(",", parts);
}
/// <summary>
/// Turns tracing on or off for one category (empty <paramref name="name"/> with a
/// <paramref name="prefix"/>: every category starting with it; both empty: all). On keeps
/// a category already at Info at Info, the same rule as /ra trace.
/// </summary>
public static string Set(string? levels, string name, bool on, string prefix = "")
{
List<(string Name, int Level)> list = Parse(levels);
for (int i = 0; i < list.Count; i++)
{
var (n, level) = list[i];
bool match = name.Length > 0
? string.Equals(n, name, StringComparison.OrdinalIgnoreCase)
: n.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
list[i] = (n, !on ? Off : level == Off ? Trace : level);
}
return Format(list);
}
/// <summary>Checkbox label: the name, plus " +log" at Info (trace lines also go to the normal log).</summary>
public static string Label(string name, int level) => level == Info ? name + " +log" : name;
}
/// <summary>
/// One row of a settings tab. Numeric values go through double (bools as
@ -307,7 +377,15 @@ internal sealed record SettingRow(
double Step = 1,
string[]? Items = null,
Func<RynthAiSettings, bool>? VisibleWhen = null,
bool Gates = false)
bool Gates = false,
// Button rows: the button's caption (Label is the row label) and its action. Any thread.
string? ButtonText = null,
Action? Click = null,
// Text rows: the string value (committed on Enter / focus loss); Status rows: GetText only.
Func<RynthAiSettings, string>? GetText = null,
Action<RynthAiSettings, string>? SetText = null,
// Text rows: greyed hint shown while the box is empty.
string? Hint = null)
{
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
}
@ -387,6 +465,17 @@ internal static class SettingsSchema
private static SettingRow Note(string text, Func<RynthAiSettings, bool>? when = null) =>
new(SettingKind.Note, text, VisibleWhen: when);
private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click);
private static SettingRow Text(string label, Func<RynthAiSettings, string> get, Action<RynthAiSettings, string> set,
string? tip = null, string? hint = null) =>
new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint);
// A one-line status RynthAi computes (read-only; empty = hidden).
private static SettingRow Status(Func<RynthAiSettings, string> get) =>
new(SettingKind.Status, "", GetText: get, VisibleWhen: s => !string.IsNullOrEmpty(get(s)));
private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set)
{
var rows = new SettingRow[get.Length];
@ -481,6 +570,12 @@ internal static class SettingsSchema
TextSize("Status", "Status"),
TextSize("Log", "Log"),
TextSize("Tracker", "Tracker"),
Spacer(),
Section("Item Info"),
Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v,
"Print a Mag-style description of an item in chat when you select it, identifying it\nfirst when needed. Items the bot selects while looting are skipped.\nAlso: /ra iteminfo on|off."),
Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"),
"Which fields the description shows and which item types are described on select (/ra iteminfo window)."),
}),
new("UI", new[]
@ -546,6 +641,17 @@ internal static class SettingsSchema
"With Decal: when VTank's macro starts (/vt start), RynthAi's macro stops, and it won't start while VTank runs.\nOne bot per client. Without Decal this does nothing. Also: /ra vtankyield on|off."),
Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v),
Spacer(),
Section("Server Features (ILT / infinite attributes)"),
Status(s => s.ServerFeaturesStatus),
Text("Servers", s => s.FeatureServerNames, (s, v) => s.FeatureServerNames = v,
"Comma-separated world names that turn on the ILT Hub, the Skills panel's Progression planners\n" +
"and the attribute raiser. * is a wildcard (*Leaftide* matches any name containing Leaftide).\n" +
"Case does not matter. Saved with the RynthAi profile.",
hint: "InfiniteLeaftide, *Leaftide*"),
Bool("Force enable on this server (manual override)", s => s.ForceServerFeatures, (s, v) => s.ForceServerFeatures = v,
"Turn the features on for whatever world you are on, even if it is not in the list.\n" +
"Each feature still follows what the server reports (for example /xp off keeps the attribute raiser off)."),
Spacer(),
Section("Missile Arc Velocities (m/s)"),
Bool("Use Arcs for Missile LoS", s => s.UseArcs, (s, v) => s.UseArcs = v,
"A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).", gates: true),
@ -748,6 +854,8 @@ internal static class SettingsSchema
new("Buffing", Concat(
Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v),
Button("Buff Profiles", "Spells...", () => RynthAiCommands.ApplyRemoteCommand("spells", "show"),
"Open the RynthAi Spells window: browse the spell list by school, level and target,\nand build the buff profile buffing uses (pick it under Loaded Files > Buffs).\nAlso: /ra spells, /ra buffprofile <name>|none."),
Bool("Rebuff When Idle", s => s.RebuffWhenIdle, (s, v) => s.RebuffWhenIdle = v),
Int("Rebuff With (seconds left)", s => s.RebuffSecondsRemaining, (s, v) => s.RebuffSecondsRemaining = v, 30, 1800, 30,
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."),
@ -790,6 +898,8 @@ internal static class SettingsSchema
"Don't start on another corpse when no pack has a free slot (says so once in chat)."),
Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true),
Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled),
Bool("Loot Items On Ground", s => s.EnableGroundLoot, (s, v) => s.EnableGroundLoot = v,
"Pick up loose items on the ground that match your loot profile, within Corpse Max range.\nCorpses always come first. Status and rescan: /ra groundloot."),
Spacer(),
Section("Corpse Ownership"),
Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v),
@ -799,8 +909,6 @@ internal static class SettingsSchema
"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("Item Info On Select", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v,
"Selecting an item prints its details to chat, Mag-Tools style (/ra iteminfo),\nidentifying it first when needed. Items the bot selects while looting are skipped."),
Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v),
Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v,
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."),
@ -808,6 +916,8 @@ internal static class SettingsSchema
"After the salvage queue empties, move same-name bags together so the server merges them."),
Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v,
"When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."),
Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"),
"Opens the item count HUD / Mini Remote setup window (/ra huds)."),
Spacer(),
Section("Loot Timers (ms)"),
Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25),
@ -850,5 +960,24 @@ internal static class SettingsSchema
Spacer(),
Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."),
}),
new("Diagnostics", new[]
{
Section("Logging & Debugging"),
Bool("Debug to chat", s => s.DiagDebugToChat, (s, v) => s.DiagDebugToChat = v,
"Echo trace lines and errors from the categories ticked below into the chat window.\nAlso: /ra debug on|off."),
Bool("Daily RynthAi log file", s => s.DiagFileLogAll, (s, v) => s.DiagFileLogAll = v,
"Mirror every RynthAi log line to rynthai_<date>.txt in the log folder (kept 7 days).\nAlso: /ra logs file on|off."),
Button("Log Folder", "Open", () => RynthAiCommands.ApplyRemoteCommand("logs", "open"),
"Open RynthAi's Logs\\Diagnostics folder in Explorer (/ra logs open)."),
Button("Old Log Files", "Prune", () => RynthAiCommands.ApplyRemoteCommand("logs", "prune"),
"Delete diagnostics files past the retention limit now (/ra logs prune)."),
Spacer(),
Section("Trace Per Category"),
new SettingRow(SettingKind.TraceCategories, "Categories",
"Ticked categories write their trace lines to Trace\\<Category>_<date>.txt (/ra trace <category> on|off)."),
Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."),
Note("Exceptions always go to exceptions_<date>.txt with full stack traces (throttled). Settings here are for this PC, not the profile."),
}),
};
}

View file

@ -16,6 +16,8 @@ internal static class UiSources
public static readonly TrackerSource Tracker = new();
public static readonly RynthAiSource RynthAi = new();
public static readonly PatrolSource Patrol = new();
public static readonly ProgressionSource Progression = new();
public static readonly CharmsSource Charms = new();
public static readonly RadarSource Radar = new();
public static readonly SettingsSource Settings = new();
public static readonly MetaSource Meta = new();
@ -54,6 +56,8 @@ internal static class UiSources
UiDataHub.Register(Radar);
UiDataHub.Register(RynthAi);
UiDataHub.Register(Patrol);
UiDataHub.Register(Progression);
UiDataHub.Register(Charms);
UiDataHub.Register(PluginStatus);
UiDataHub.Register(Log);
UiDataHub.Register(Tracker);

View file

@ -207,7 +207,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
[DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd);
private const uint GW_OWNER = 4;
[DllImport("user32.dll")] private static extern bool ReleaseCapture();
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint);
@ -275,15 +275,20 @@ internal sealed unsafe class LayeredWindow : IDisposable
/// DestroyWindow only works there. A window created on the overlay thread
/// (not the game thread) could not be destroyed by a destroy posted to the
/// game thread (ACCESS_DENIED) and stayed on screen: the double dashboard.
/// Must not collide with Win32Backend's game-window messages (0x8001-0x8005).
/// </summary>
private const uint WM_RYNTH_SELF_DESTROY = 0x8051;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam)
{
// Handled before the instance lookup: Dispose has already removed the
// instance by the time this posted message is dispatched.
if (msg == WM_RYNTH_SELF_DESTROY)
{
DestroyWindow(hwnd);
bool destroyed = DestroyWindow(hwnd);
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
RynthCore.Engine.RynthLog.Info($"LayeredWindow: self-destroy DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed} err={err} on thread=0x{GetCurrentThreadId():X}.");
return IntPtr.Zero;
}
@ -317,12 +322,11 @@ internal sealed unsafe class LayeredWindow : IDisposable
/// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on
/// the owning thread.
///
/// Dispose only posts the destroy, and Win32Backend.Shutdown unhooks the
/// game WndProc ~1 ms after the overlay stops — usually before the game
/// thread gets to the post. AC's own WndProc then drops it, and because
/// the engine module is never unloaded the panel lives on: frozen on its
/// last frame, deaf to input, and hidden under the next generation's copy
/// of it until that one is moved ("two RynthAi windows").
/// Synchronous backstop for panels that were never disposed: because the
/// engine module is never unloaded, such a panel lives on after shutdown,
/// frozen on its last frame, deaf to input, and hidden under the next
/// generation's copy of it until that one is moved ("two RynthAi windows").
/// (Disposed panels destroy themselves via WM_RYNTH_SELF_DESTROY.)
///
/// <paramref name="includeThisGeneration"/>=false spares this engine
/// load's own windows (class names carry a per-load Guid) and removes only
@ -367,6 +371,25 @@ internal sealed unsafe class LayeredWindow : IDisposable
}
}
/// <summary>
/// The content rects (screen px: left, top, width, height) of every visible panel window.
/// They sit above the game window, so nothing drawn in the game frame can show over them.
/// </summary>
internal static List<(int Left, int Top, int Width, int Height)> VisibleContentRects()
{
LayeredWindow[] windows;
lock (_instancesLock)
{
windows = new LayeredWindow[_instances.Count];
_instances.Values.CopyTo(windows, 0);
}
var rects = new List<(int, int, int, int)>(windows.Length);
foreach (LayeredWindow w in windows)
if (w.IsVisible && w.Width > 0 && w.Height > 0)
rects.Add((w.ScreenLeft, w.ScreenTop, w.Width, w.Height));
return rects;
}
private static readonly HashSet<IntPtr> _sweptLogged = new();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
@ -1526,4 +1549,43 @@ internal sealed unsafe class LayeredWindow : IDisposable
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: destroy fallback threw {ex.GetType().Name}: {ex.Message}.");
}
}
/// <summary>
/// Destroys <paramref name="hwnd"/> on the thread that actually owns it, never
/// blocking the caller. Inline when the caller is the owner; otherwise posts
/// WM_RYNTH_SELF_DESTROY to the window itself so its own WndProc destroys it.
/// Posting to the panel (not the game window) works for panels created on
/// any thread, and still works after Win32Backend has unhooked the game
/// WndProc at shutdown — a post to the game window would be dropped by AC.
/// </summary>
private static void DestroyOnOwnerThread(IntPtr hwnd)
{
uint ownerThread = GetWindowThreadProcessId(hwnd, out _);
uint currentThread = GetCurrentThreadId();
if (ownerThread == 0)
{
// Window already gone (e.g. its owning thread exited, which destroys it).
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: HWND=0x{hwnd.ToInt64():X} no longer exists — nothing to destroy.");
return;
}
if (ownerThread == currentThread)
{
bool destroyed = DestroyWindow(hwnd);
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: DestroyWindow(0x{hwnd.ToInt64():X}) inline on owner thread=0x{currentThread:X} = {destroyed} err={err}.");
return;
}
if (PostMessage(hwnd, WM_RYNTH_SELF_DESTROY, IntPtr.Zero, IntPtr.Zero))
{
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: posted self-destroy to HWND=0x{hwnd.ToInt64():X} (owner thread=0x{ownerThread:X}, caller thread=0x{currentThread:X}).");
return;
}
// Post failed (queue full or HWND destroyed in the meantime); a cross-thread
// DestroyWindow would only fail, so report it rather than attempt it.
RynthCore.Engine.RynthLog.Error($"LayeredWindow.Dispose: PostMessage(self-destroy) to HWND=0x{hwnd.ToInt64():X} failed err={Marshal.GetLastWin32Error()} (owner thread=0x{ownerThread:X}).");
}
}

View file

@ -0,0 +1,72 @@
// ============================================================================
// RynthCore.Engine - UI/OverlayFrameBuffer.cs
// Lock-minimised pixel handoff from the Avalonia UI thread to the D3D9
// render thread. Avalonia submits a captured BGRA frame; EndScene consumes
// it once, uploads to a D3D9 texture, then re-uses that texture until the
// next submit.
//
// Thread model:
// Writer: Avalonia STA thread (DispatcherTimer ~30 fps)
// Reader: D3D9 render thread (EndScene ~60 fps)
//
// The submitted buffer is replaced atomically (pointer swap). The reader
// holds a reference for the duration of the upload, preventing GC collection
// even if the writer has already posted a newer frame.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.UI;
internal static class OverlayFrameBuffer
{
private sealed class Frame
{
public readonly byte[] Pixels;
public readonly int Width;
public readonly int Height;
public Frame(byte[] pixels, int w, int h)
{
Pixels = pixels;
Width = w;
Height = h;
}
}
// Written by Avalonia thread, read by D3D9 thread.
// Interlocked.Exchange gives the sequential-consistency guarantee we need.
private static Frame? _pending;
/// <summary>
/// Submit a new BGRA frame from the Avalonia UI thread.
/// The pixel array is copied so the caller can reuse its bitmap lock buffer.
/// </summary>
public static void Submit(IntPtr pixelData, int byteCount, int w, int h)
{
var buf = new byte[byteCount];
System.Runtime.InteropServices.Marshal.Copy(pixelData, buf, 0, byteCount);
Interlocked.Exchange(ref _pending, new Frame(buf, w, h));
}
/// <summary>
/// Consume the latest pending frame from the D3D9 render thread.
/// Returns true if a new frame is available; the caller owns the byte array
/// until the next call (no further synchronisation required).
/// </summary>
public static bool TryConsume(out byte[]? pixels, out int w, out int h)
{
Frame? frame = Interlocked.Exchange(ref _pending, null);
if (frame == null)
{
pixels = null; w = 0; h = 0;
return false;
}
pixels = frame.Pixels;
w = frame.Width;
h = frame.Height;
return true;
}
}

View file

@ -2,8 +2,9 @@
// RynthCore.Engine — UI/Panels/ItemsPanel.cs
// Avalonia replica of the ImGui Items tab (LegacyWeaponsUi.cs).
//
// Three sections:
// Weapons — Name, Element picker, Delete
// Four sections:
// Weapons — Name, Element picker, Delete (ItemRules with Action != "Shield")
// Shields — Auto-equip toggle, Name, Delete (ItemRules with Action == "Shield")
// Consumables — Name, Type picker, Delete
// Mana Stones — Enable tapping toggle, keep count, min mana threshold
//
@ -67,6 +68,8 @@ internal static class ItemsPanel
/// it when the payload is saved back.
/// </summary>
[JsonPropertyName("missingIds")] public List<int> MissingIds { get; set; } = new();
// Null when the plugin predates shields (RynthAi < 0.6.20); the plugin then ignores it on write-back.
[JsonPropertyName("autoEquipShield")] public bool? AutoEquipShield { get; set; }
}
internal sealed class WeaponEntry
@ -74,6 +77,10 @@ internal static class ItemsPanel
[JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("name")] public string Name { get; set; } = string.Empty;
[JsonPropertyName("element")] public string Element { get; set; } = "Slash";
// "Weapon" or "Shield" (older settings may hold "Loot"). Round-tripped untouched.
[JsonPropertyName("action")] public string Action { get; set; } = "Weapon";
public bool IsShield => string.Equals(Action, ItemsCommands.ShieldAction, StringComparison.OrdinalIgnoreCase);
}
internal sealed class ConsumableEntry
@ -212,29 +219,33 @@ internal static class ItemsPanel
{
body.Children.Clear();
// Weapons and shields share the plugin's ItemRules list (state.Data.Weapons);
// rows are split by Action, so deletes remove by reference, not by index.
void DeleteItem(WeaponEntry entry)
{
state.Data.Weapons.Remove(entry);
state.Dirty = true;
PushChanges(state);
Refresh();
}
// ── Weapons ──────────────────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Weapons"));
if (state.Data.Weapons.Count == 0)
var weapons = state.Data.Weapons.Where(w => !w.IsShield).ToList();
if (weapons.Count == 0)
{
body.Children.Add(BuildEmptyRow("No weapons configured"));
}
else
{
body.Children.Add(BuildTableHeader(new[] { "Item Name", "Element", "" }, new[] { true, false, false }, new double[] { 0, 100, 46 }));
for (int i = 0; i < state.Data.Weapons.Count; i++)
for (int i = 0; i < weapons.Count; i++)
{
var w = state.Data.Weapons[i];
int wi = i;
body.Children.Add(BuildWeaponRow(w, wi % 2 == 0, ShowPicker,
var w = weapons[i];
body.Children.Add(BuildWeaponRow(w, i % 2 == 0, ShowPicker,
onChanged: () => { state.Dirty = true; PushChanges(state); },
onDelete: () =>
{
state.Data.Weapons.RemoveAt(wi);
state.Dirty = true;
PushChanges(state);
Refresh();
}));
onDelete: () => DeleteItem(w)));
}
}
@ -243,6 +254,45 @@ internal static class ItemsPanel
body.Children.Add(BuildDivider());
// ── Shields (off-hand) ───────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Shields (off-hand)"));
// Plugins older than RynthAi 0.6.20 don't report the setting — hide the toggle then.
if (state.Data.AutoEquipShield is bool autoEquip)
{
body.Children.Add(BuildToggleRow("Auto-equip with one-handed melee weapons", autoEquip,
"On: in melee with a one-handed weapon, combat wields the first shield below unless the monster has its own off-hand (Damage panel or Monsters 'Offhand').\n" +
"Off: only per-monster off-hand choices are equipped.\n" +
"Never used with two-handed weapons, bows, crossbows, atlatls or casters.",
on =>
{
state.Data.AutoEquipShield = on;
state.Dirty = true;
PushChanges(state);
Refresh();
}));
}
var shields = state.Data.Weapons.Where(w => w.IsShield).ToList();
if (shields.Count == 0)
{
body.Children.Add(BuildEmptyRow("No shields configured"));
}
else
{
body.Children.Add(BuildTableHeader(new[] { "Shield Name", "" }, new[] { true, false }, new double[] { 0, 46 }));
for (int i = 0; i < shields.Count; i++)
{
var s = shields[i];
body.Children.Add(BuildShieldRow(s, i % 2 == 0, onDelete: () => DeleteItem(s)));
}
}
body.Children.Add(BuildAddButton("Add Selected Shield", "(select a shield in inventory first)",
ItemsCommands.AddSelectedShield));
body.Children.Add(BuildDivider());
// ── Consumables ──────────────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Consumable Items"));
@ -296,7 +346,8 @@ internal static class ItemsPanel
bool consumablesChanged = ConsumablesChanged(state.Data.Consumables, fresh.Consumables);
bool manaChanged = state.Data.EnableManaTapping != fresh.EnableManaTapping
|| state.Data.ManaTapMinMana != fresh.ManaTapMinMana
|| state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount;
|| state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount
|| state.Data.AutoEquipShield != fresh.AutoEquipShield;
// UI deep-dive finding P0-4 (2026-07-02): state.Data = fresh used
// to run unconditionally, EVERY poll tick, even when the
@ -515,6 +566,80 @@ internal static class ItemsPanel
return grid;
}
// ── Shield table row (name + delete; shields have no element) ─────────────
private static Control BuildShieldRow(WeaponEntry s, bool alt, Action onDelete)
{
var grid = new Grid
{
Background = alt ? ColRowAlt : ColPanelBg,
Height = 24,
ColumnDefinitions = new ColumnDefinitions("*, 46"),
};
var nameTb = new TextBlock
{
Text = s.Name,
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(6, 0),
TextTrimming = TextTrimming.CharacterEllipsis,
};
Grid.SetColumn(nameTb, 0);
grid.Children.Add(nameTb);
var del = new Button
{
Content = "Del",
Background = ColBtnFill,
Foreground = ColRed,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 2),
FontSize = 10,
Margin = new Thickness(2, 2),
};
del.Click += (_, _) => onDelete();
Grid.SetColumn(del, 1);
grid.Children.Add(del);
return grid;
}
// ── Labelled ON/OFF toggle row (same look as the mana-tapping toggle) ─────
private static Control BuildToggleRow(string label, bool value, string tooltip, Action<bool> onToggled)
{
var row = new WrapPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4, 4, 4, 2) };
var btn = new Button
{
Content = value ? "ON" : "OFF",
Background = value ? new SolidColorBrush(Color.FromRgb(0x10, 0x40, 0x10)) : ColBtnFill,
Foreground = value ? new SolidColorBrush(Color.FromRgb(0x33, 0xFF, 0x33)) : ColMute,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(8, 2),
FontSize = 10,
Width = 50,
Margin = new Thickness(0, 0, 8, 0),
};
btn.Click += (_, _) => onToggled(!value);
ToolTip.SetTip(btn, tooltip);
row.Children.Add(btn);
var lbl = new TextBlock
{
Text = label,
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(lbl, tooltip);
row.Children.Add(lbl);
return row;
}
// ── Consumable table row ──────────────────────────────────────────────────
private static Control BuildConsumableRow(
ConsumableEntry c, bool alt,
@ -745,7 +870,8 @@ internal static class ItemsPanel
{
if (a.Count != b.Count) return true;
for (int i = 0; i < a.Count; i++)
if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element) return true;
if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element
|| !string.Equals(a[i].Action, b[i].Action, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}

View file

@ -171,9 +171,29 @@ internal static class NavPanel
{ e.Handled = true; picker.Close(); }
};
// Waypoint list controls live for the panel's lifetime. Rebuild() only refills
// waypointStack: a ScrollViewer recreated (or given a new Content) resets its
// offset to the top, which made the list jump back every poll and impossible to edit.
var waypointStack = new StackPanel { Spacing = 1 };
var waypointScroll = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = waypointStack,
};
var waypointHost = new Border { Height = 200, Child = waypointScroll };
// Last plugin JSON the panel was built from. A rebuild from a user action
// (optimistic local edit) clears it so the next poll always resyncs with the plugin.
string lastJson = string.Empty;
bool rebuildFromPoll = false;
void Rebuild()
{
if (!rebuildFromPoll) lastJson = string.Empty;
Vector keepOffset = waypointScroll.Offset;
content.Children.Clear();
waypointStack.Children.Clear();
var d = state.Data;
bool navActive = d.MacroRunning && d.NavigationEnabled;
@ -439,7 +459,6 @@ internal static class NavPanel
FontSize = 10,
});
var waypointStack = new StackPanel { Spacing = 1 };
for (int i = 0; i < d.Points.Count; i++)
{
int ci = i;
@ -516,16 +535,10 @@ internal static class NavPanel
waypointStack.Children.Add(row);
}
content.Children.Add(new Border
{
Height = 200,
Child = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = waypointStack,
},
});
content.Children.Add(waypointHost); // same instance every rebuild — keeps scroll offset
// Re-apply after layout too: the re-attach / new row extent can coerce it to 0.
waypointScroll.Offset = keepOffset;
Dispatcher.UIThread.Post(() => waypointScroll.Offset = keepOffset, DispatcherPriority.Loaded);
}
// ── Poll timer ────────────────────────────────────────────────────────
@ -536,6 +549,9 @@ internal static class NavPanel
timer.Tick += (_, _) =>
{
if (picker.ActivePicker != null || state.Typing) return;
// A rebuild between press and release eats the click on X / row select. seenVersion
// is left alone, so the change is picked up once the pointer leaves the list.
if (waypointHost.IsPointerOver) return;
var snap = UiSources.Nav.Current;
if (snap == null || snap.Version == seenVersion) return;
seenVersion = snap.Version;

View file

@ -558,7 +558,7 @@ internal static partial class RynthAiPanel
var launcherGrid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,*,*"),
RowDefinitions = new RowDefinitions("Auto,Auto"),
RowDefinitions = new RowDefinitions("Auto,Auto,Auto"),
Margin = new Thickness(0, 4, 0, 0)
};
AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>",
@ -567,8 +567,15 @@ internal static partial class RynthAiPanel
AddMonstersLauncher(launcherGrid, 0, 1);
AddLauncher(launcherGrid, 0, 2, "Settings", "⚒",
onClick: () => PanelRouter.Toggle("Settings"));
AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺",
onLeftClick: () => PanelRouter.Toggle("Nav"));
// Map: RynthAi's dungeon map is an ImGui overlay window; the right half toggles it like "/ra map".
var (_, mapBtn) = AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺",
onLeftClick: () => PanelRouter.Toggle("Nav"),
onRightClick: () =>
{
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("map", "toggle");
});
ToolTip.SetTip(mapBtn, "Show/hide the dungeon map (/ra map). It appears when you are indoors.");
AddLauncher(launcherGrid, 1, 1, "Items", "🛡",
onClick: () => PanelRouter.Toggle("Items"));
var patrolBtn = AddLauncher(launcherGrid, 1, 2, "Patrol", "⬡",
@ -583,6 +590,33 @@ internal static partial class RynthAiPanel
ShowPatrolFlyout(patrolBtn);
}
};
// Char: same as typing "/ra hub show". The ILT Hub is an ImGui overlay window with no
// Avalonia panel, so this is the panel's way to open it.
var charBtn = AddLauncher(launcherGrid, 2, 0, "Char", "♥",
onClick: () =>
{
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("hub", "show");
});
ToolTip.SetTip(charBtn, "Open the character hub (ILT Hub) window (/ra hub show).");
// Hub: the Mini Remote and the Inventory HUDs setup are ImGui windows inside RynthAi.
var hudBtn = AddLauncher(launcherGrid, 2, 1, "Hub", "▣",
onClick: () =>
{
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("remote", "toggle");
});
ToolTip.SetTip(hudBtn, "Left-click: show/hide the Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds).");
hudBtn.PointerPressed += (_, e) =>
{
if (e.GetCurrentPoint(hudBtn).Properties.IsRightButtonPressed)
{
e.Handled = true;
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("huds", "show");
}
};
dash.Children.Add(launcherGrid);
@ -1201,16 +1235,18 @@ internal static partial class RynthAiPanel
/// by side. Used for Nav | Map so the user can pop the navigation panel
/// or the dungeon map independently from the same row slot.
/// </summary>
private static void AddSplitLauncher(Grid grid, int row, int col,
/// <returns>The left and right half buttons (e.g. for tooltips).</returns>
private static (Button Left, Button Right) AddSplitLauncher(Grid grid, int row, int col,
string leftLabel, string leftIcon, string rightLabel, string rightIcon,
Action? onLeftClick = null, Action? onRightClick = null)
{
var splitGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*") };
AddLauncher(splitGrid, 0, 0, leftLabel, leftIcon, onLeftClick);
AddLauncher(splitGrid, 0, 1, rightLabel, rightIcon, onRightClick);
var left = AddLauncher(splitGrid, 0, 0, leftLabel, leftIcon, onLeftClick);
var right = AddLauncher(splitGrid, 0, 1, rightLabel, rightIcon, onRightClick);
grid.Children.Add(splitGrid);
Grid.SetRow(splitGrid, row);
Grid.SetColumn(splitGrid, col);
return (left, right);
}
private static Button AddLauncher(Grid grid, int row, int col, string label, string icon, Action? onClick = null)

View file

@ -6,7 +6,10 @@
//
// Rule semantics (the rules live in ChatModel, UI/Data/ChatData.cs; the ImGui
// face is ImGui/Panels/ChatFiltersFace.cs):
// • Regex, case-insensitive, matched against the formatted line.
// • Regex, or plain text Contains / Starts with / Ends with (the mode
// button), case-insensitive.
// • Standard filters (RynthChatPresets) below the rules apply only to
// lines no rule moved or hid.
// • FIRST matching rule wins — order matters, hence the ▲▼ buttons.
// • Tab name set → matching lines MOVE to that tab (and leave All).
// • Tab name empty → matching lines are hidden everywhere.
@ -95,10 +98,24 @@ internal static class RynthChatFiltersPanel
ChatModel.FiltersChanged();
};
// Click-to-cycle (no ComboBox: the overlay's popup hosting is unreliable).
var modeBtn = new Button
{
Content = ModeLabels[(int)r.Mode],
FontSize = 10,
Width = 62,
Padding = new Thickness(4, 2),
Background = ButtonBg,
Foreground = Brushes.White,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(modeBtn, "How the text is matched: Regex, or plain text Contains / Starts with / Ends with.");
var patternBox = new TextBox
{
Text = r.Pattern,
Watermark = "regex (e.g. AutoRun)",
Watermark = PatternWatermark(r.Mode),
FontSize = 10,
MinWidth = 220,
Height = 24,
@ -118,6 +135,15 @@ internal static class RynthChatFiltersPanel
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
ChatModel.FiltersChanged();
};
modeBtn.Click += (_, _) =>
{
r.Mode = (ChatMatchMode)(((int)r.Mode + 1) % ModeLabels.Length);
r.Recompile();
modeBtn.Content = ModeLabels[(int)r.Mode];
patternBox.Watermark = PatternWatermark(r.Mode);
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
ChatModel.FiltersChanged();
};
var tabBox = new TextBox
{
@ -180,7 +206,7 @@ internal static class RynthChatFiltersPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Children = { enabledCheck, patternBox, tabBox, upBtn, downBtn, delBtn },
Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn },
});
}
@ -194,6 +220,80 @@ internal static class RynthChatFiltersPanel
Margin = new Thickness(2, 6),
});
}
AddStandardFilters();
}
// Canned UB-IT-style filters (RynthChatPresets), checked after the rules above.
void AddStandardFilters()
{
rows.Children.Add(new TextBlock
{
Text = "Standard filters — tick to hide; type a tab to move the lines there instead.",
FontSize = 10,
FontWeight = FontWeight.Bold,
Foreground = Brushes.White,
Margin = new Thickness(2, 10, 2, 2),
});
foreach (string group in RynthChatPresets.Groups)
{
rows.Children.Add(new TextBlock
{
Text = group,
FontSize = 10,
Foreground = Brushes.LightSteelBlue,
Margin = new Thickness(2, 6, 2, 0),
});
foreach (var p in RynthChatPresets.All.Where(p => p.Group == group))
rows.Children.Add(PresetRow(p));
}
}
Control PresetRow(RynthChatPresets.Preset p)
{
var check = new CheckBox
{
IsChecked = p.Enabled,
Content = new TextBlock { Text = p.Label, FontSize = 10, Foreground = Brushes.White },
VerticalAlignment = VerticalAlignment.Center,
MinWidth = 220,
};
ToolTip.SetTip(check, $"{p.Description}\nExample: {p.Example}");
check.IsCheckedChanged += (_, _) =>
{
p.Enabled = check.IsChecked == true;
ChatModel.FiltersChanged();
};
var tabBox = new TextBox
{
Text = p.Tab,
Watermark = "tab (empty = hide)",
FontSize = 10,
Width = 120,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
tabBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tabBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
tabBox.TextChanged += (_, _) =>
{
p.Tab = (tabBox.Text ?? "").Trim();
ChatModel.FiltersChanged();
};
return new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Margin = new Thickness(8, 0, 0, 0),
Children = { check, tabBox },
};
}
addBtn.Click += (_, _) =>
@ -224,4 +324,15 @@ internal static class RynthChatFiltersPanel
RebuildRows();
return layout;
}
/// <summary>Button captions, indexed by <see cref="ChatMatchMode"/>.</summary>
private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts", "Ends" };
private static string PatternWatermark(ChatMatchMode mode) => mode switch
{
ChatMatchMode.Contains => "text anywhere in the line",
ChatMatchMode.StartsWith => "line starts with...",
ChatMatchMode.EndsWith => "line ends with...",
_ => "regex (e.g. AutoRun)",
};
}

View file

@ -0,0 +1,250 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthChatPresets.cs
// Canned ("standard") RynthChat filters, modelled on UtilityBelt-IT's
// ChatFilter / Mag ChatFilter categories. Each preset is a tick-box in the
// ChatFilters panel that hides its lines or moves them to a tab.
//
// Presets match the raw line text (no timestamp / sender prefix). Most are
// limited to non-chat channels so a player typing the same words in Local or
// a channel is never eaten. ChatRouter evaluates them on the plugin pump
// (after the custom rules); editors change Enabled / Tab from any thread and
// then call ChatModel.FiltersChanged so every kept line is routed again.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthChatPresets
{
/// <summary>Which RynthChat channels a preset may match.</summary>
internal enum Scope
{
/// <summary>Anything except Chat / Channels (player-typed text).</summary>
NotPlayerChat,
/// <summary>Only the Combat channel (spell incantations arrive as chat type 0x11 → Combat).</summary>
CombatOnly,
/// <summary>Only the Channels tab (General / Trade / LFG / Roleplay / Society).</summary>
ChannelsOnly,
/// <summary>Every channel.</summary>
Any,
}
internal sealed class Preset
{
internal string Id { get; }
internal string Group { get; }
internal string Label { get; }
internal string Description { get; }
internal string Example { get; }
internal Scope Where { get; }
internal Regex Pattern { get; }
// User state (persisted in rynthchat_settings.json "presets" by ChatModel).
// Volatile: written by an editor, read by the pump's router.
internal volatile bool Enabled;
internal volatile string Tab = ""; // "" = hide matching lines
internal Preset(string id, string group, string label, string description, string example, Scope where, string pattern)
{
Id = id;
Group = group;
Label = label;
Description = description;
Example = example;
Where = where;
Pattern = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50));
}
/// <summary>True when this preset applies to a line on <paramref name="channel"/> with raw <paramref name="text"/>.</summary>
internal bool Matches(string text, string channel)
{
bool inScope = Where switch
{
Scope.NotPlayerChat => channel is not ("Chat" or "Channels"),
Scope.CombatOnly => channel == "Combat",
Scope.ChannelsOnly => channel == "Channels",
_ => true,
};
if (!inScope) return false;
try { return Pattern.IsMatch(text); }
catch (RegexMatchTimeoutException) { return false; }
}
}
// Kill flavour text (retail/ACE death messages). Damage lines ("... for N points of ...")
// share some verbs, so they are excluded up front.
private const string KillPattern =
@"^(?!.* for \d+ points? of )(?:" +
@"You (?:flatten|knock|split|cleave|slay|bring|beat|run|suffocate|smite|killed) .+!" +
@"|.+ is (?:reduced to cinders|torn to ribbons by your assault|shattered by your assault|incinerated by your assault|liquified by your attack|dessicated by your attack)!" +
@"|.+ catches your attack, with dire consequences!" +
@"|.+'s (?:seared corpse smolders before you|last strength dissolves before you)!" +
@"|Electricity tears .+ apart!|Blistered by lightning, .+ falls!" +
@"|Your killing blow nearly turns .+ inside-out!|The thunder of crushing .+ is followed by the deafening silence of death!" +
@"|Your attack stops .+ cold!)";
// Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ".
private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*";
private static readonly Preset[] _all =
{
// ── Combat ────────────────────────────────────────────────────────
new("combat.attack_evades", "Combat", "Your attacks evaded",
"A monster evades your melee or missile attack.",
"Drudge Slinker evaded your attack.", Scope.NotPlayerChat, @" evaded your attack\.\s*$"),
new("combat.defense_evades", "Combat", "You evade attacks",
"You evade a monster's attack.",
"You evaded Drudge Slinker!", Scope.NotPlayerChat, @"^You evaded "),
new("combat.damage_dealt", "Combat", "Damage you deal",
"Your melee, missile and war-spell hits (including critical / sneak attack prefixes).",
"You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"You .+ for \d+ points? of "),
new("combat.damage_taken", "Combat", "Damage you take",
"Monster hits and spell damage landing on you.",
"Drudge Slinker slashes you for 12 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"(?!You ).+ you (?:with .+ )?for \d+ points? of "),
new("combat.attack_resists", "Combat", "Your spells resisted",
"A target resists one of your spells.",
"Drudge Slinker resists your spell", Scope.NotPlayerChat, @" resists your spell"),
new("combat.defense_resists", "Combat", "You resist spells",
"You resist a spell, or a caster was out of range / had no valid target.",
"You resist the spell cast by Drudge Sorcerer", Scope.NotPlayerChat,
@"^You resist the spell cast by |^You have no appropriate target.*spell|^You are an invalid target for the spell|tried to cast a spell on you, but was too far away!"),
new("combat.npk", "Combat", "Not-a-PK failures",
"\"You fail to affect X, you are not a player killer!\" and the mirror message.",
"You fail to affect Bob because you are not a player killer!", Scope.NotPlayerChat,
@"^You fail to affect .+ you are not a player killer!|fails to affect you.+ is not a player killer!"),
new("combat.dirty_fighting", "Combat", "Dirty Fighting procs",
"Dirty Fighting assault announcements.",
"Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!", Scope.NotPlayerChat, @"^Dirty Fighting! .+ delivers a "),
new("combat.monster_deaths", "Combat", "Monster death messages",
"Kill flavour text (\"You flatten…\", \"…is reduced to cinders!\").",
"Drudge Slinker is reduced to cinders!", Scope.NotPlayerChat, KillPattern),
// ── Casting ───────────────────────────────────────────────────────
new("cast.mine", "Casting", "Your spell words",
"Your own incantations (\"You say, \\\"Zojak…\\\"\"). Real Local chat is untouched.",
"You say, \"Zojak Equin\"", Scope.CombatOnly, @"^You say, """),
new("cast.others", "Casting", "Others' spell words",
"Incantations from other players and monsters.",
"Bob says, \"Cruath Quareth\"", Scope.CombatOnly, @"^(?!You say).+ says, """),
new("cast.fizzle", "Casting", "Spell fizzles",
"\"Your spell fizzled.\"",
"Your spell fizzled.", Scope.NotPlayerChat, @"^Your spell fizzled\."),
new("cast.components", "Casting", "Component usage",
"\"The spell consumed the following components: …\"",
"The spell consumed the following components: Lead Scarab", Scope.NotPlayerChat, @"^The spell consumed the following components"),
new("cast.self_buffs", "Casting", "Your buff casts",
"\"You cast X on yourself…\" confirmations.",
"You cast Strength Self VII on yourself", Scope.NotPlayerChat, @"^You cast .+ on yourself"),
new("cast.buffs_on_you", "Casting", "Buffs others cast on you",
"\"Bob cast X on you…\" lines from buff bots and fellows.",
"Bob cast Strength Other VII on you", Scope.NotPlayerChat, @"^(?!You ).+ cast .+ on you\b"),
new("cast.expires", "Casting", "Spell expiry",
"\"… has expired.\" — rares (Brilliance / Prodigal / Spectral) are kept.",
"Strength Self VII has expired.", Scope.NotPlayerChat, @"^(?!.*(?:Brilliance|Prodigal|Spectral)).*\b(?:has|have) expired\."),
// ── Items & utility ───────────────────────────────────────────────
new("item.heal_ok", "Items", "Healing kit success",
"\"You heal yourself for N Health points…\"",
"You heal yourself for 80 Health points.", Scope.NotPlayerChat, @"^You .*heal yourself for "),
new("item.heal_fail", "Items", "Healing kit failure",
"\"You fail to heal yourself.\"",
"You fail to heal yourself. ", Scope.NotPlayerChat, @"^You fail to heal yourself\."),
new("item.salvage", "Items", "Salvage results",
"\"You obtain … using your knowledge of …\"",
"You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", Scope.NotPlayerChat, @"^You obtain .+ using your knowledge of "),
new("item.salvage_fail", "Items", "Salvage failures",
"\"Salvaging Failed!\" and unsuitable-item notices.",
"Salvaging Failed!", Scope.NotPlayerChat, @"^Salvaging Failed!|The following were not suitable for salvaging: "),
new("item.craftsman", "Items", "Aura of the Craftsman",
"The +5 skill augmentation notice on every craft.",
"Your Aura of the Craftman augmentation increased your skill by 5!", Scope.NotPlayerChat, @"^Your Aura of the Craftman augmentation increased your skill"),
new("item.mana_stone", "Items", "Mana stone usage",
"Mana stone give / drain / destroyed lines.",
"The Mana Stone gives 4,500 points of mana to the following items:", Scope.NotPlayerChat,
@"^The Mana Stone (?:gives|drains) |^You need .+ more mana to fully charge your items\.\s*$|^The .+ is destroyed\.\s*$"),
new("item.regen", "Items", "Periodic healing ticks",
"\"You receive N points of periodic healing.\"",
"You receive 12 points of periodic healing.", Scope.NotPlayerChat, @"^You receive .+ points of periodic healing"),
// ── Social & trade ────────────────────────────────────────────────
new("social.bot_spam", "Social", "Trade / buff bot spam",
"Lines ending in the bot tags -t- or -b-.",
"BuffBot says, \"Buffs at the Holtburg lifestone -b-\"", Scope.Any, @"-[tb]-""?\s*$"),
new("social.failed_assess", "Social", "Failed assess on you",
"\"Someone tried and failed to assess you!\"",
"Bob tried and failed to assess you!", Scope.NotPlayerChat, @"tried and failed to assess you!\s*$"),
new("social.kill_task", "Social", "Kill task complete",
"\"You have killed N Xs! Your task is complete!\"",
"You have killed 50 Drudges! Your task is complete!", Scope.NotPlayerChat, @"^You have killed \d+ .+Your task is complete!\s*$"),
new("social.general", "Social", "General channel",
"Everything said on General.",
"[General] Bob says, \"hi\"", Scope.ChannelsOnly, @"^\[General\]|says on the General channel"),
new("social.trade", "Social", "Trade channel",
"Everything said on Trade.",
"[Trade] Bob says, \"WTS\"", Scope.ChannelsOnly, @"^\[Trade\]|says on the Trade channel"),
new("social.lfg", "Social", "LFG channel",
"Everything said on LFG.",
"[LFG] Bob says, \"LF fellow\"", Scope.ChannelsOnly, @"^\[LFG\]|says on the LFG channel"),
new("social.roleplay", "Social", "Roleplay channel",
"Everything said on Roleplay.",
"[Roleplay] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[Roleplay\]|says on the Roleplay channel"),
new("social.society", "Social", "Society channel",
"Everything said on your society channel.",
"[Society] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[(?:Society|Celestial Hand|Eldrytch Web|Radiant Blood)\]|says on the (?:Society|Celestial Hand|Eldrytch Web|Radiant Blood) channel"),
// ── NPCs ──────────────────────────────────────────────────────────
new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)",
"All Master Arbitrator speech and the fellowship-lock notice.",
"Master Arbitrator tells you, \"You shall be known…\"", Scope.Any,
@"^Master Arbitrator (?:says|tells you)|^Your fellowship is now locked\..*you have 15 minutes to be recruited"),
// ── Pets (ACE custom combat pets) ─────────────────────────────────
new("pet.hit", "Pets", "Pet hits",
"\"[Pet] … hit …\" outgoing damage.",
"[Pet] Fire Banshee hit Drudge for 40 damage.", Scope.NotPlayerChat, @"^\[Pet\] .+ hit "),
new("pet.evade", "Pets", "Pet attacks evaded",
"\"[Pet] … evaded by …\"",
"[Pet] Fire Banshee's attack was evaded by Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ evaded by "),
new("pet.damage_taken", "Pets", "Pet damage taken",
"\"[Pet] … took …\" incoming damage.",
"[Pet] Fire Banshee took 25 damage from Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ took "),
new("pet.death", "Pets", "Pet died",
"\"[Pet] Your combat pet … has died.\"",
"[Pet] Your combat pet Fire Banshee has died.", Scope.NotPlayerChat, @"^\[Pet\] Your combat pet .+ has died\.\s*$"),
new("pet.recall_block", "Pets", "Pet recall blocked",
"\"Your pet was in combat recently; you cannot recall it…\"",
"Your pet was in combat recently; you cannot recall it for about 10 seconds.", Scope.NotPlayerChat,
@"^Your pet was in combat recently; you cannot recall it"),
new("pet.overflow", "Pets", "Pet heal overflow",
"\"… receives N excess … from …\" boost overflow.",
"Fire Banshee receives 20 excess health from Heal Other.", Scope.NotPlayerChat, @" receives .+ excess .+ from "),
};
private static readonly Dictionary<string, Preset> _byId =
_all.ToDictionary(p => p.Id, StringComparer.OrdinalIgnoreCase);
/// <summary>Every preset in display order.</summary>
internal static IReadOnlyList<Preset> All => _all;
/// <summary>Group names in display order.</summary>
internal static IEnumerable<string> Groups => _all.Select(p => p.Group).Distinct();
internal static Preset? Get(string id) => _byId.TryGetValue(id, out var p) ? p : null;
/// <summary>First enabled preset that matches the line, or null.</summary>
internal static Preset? FirstMatch(string text, string channel)
{
foreach (var p in _all)
if (p.Enabled && p.Matches(text, channel))
return p;
return null;
}
/// <summary>Tabs named by enabled presets (tab names create tabs implicitly, like custom rules).</summary>
internal static IEnumerable<string> TargetTabs()
=> _all.Where(p => p.Enabled && p.Tab.Length > 0).Select(p => p.Tab);
}

View file

@ -333,6 +333,25 @@ internal static class SettingsPanel
return SectionHeader(row.Label);
case SettingKind.Spacer:
return Spacer();
case SettingKind.Button:
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip);
case SettingKind.TraceCategories:
return TraceCategoriesRow(state, row);
case SettingKind.Text:
return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v =>
{
row.SetText?.Invoke(state.Data, v);
Push(state);
}, row.Tooltip);
case SettingKind.Status:
{
string status = row.GetText?.Invoke(d) ?? string.Empty;
return status.Length == 0 ? null : new TextBlock
{
Text = status, Foreground = ColTeal, FontSize = 11,
TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 2),
};
}
case SettingKind.Note:
return new TextBlock
{
@ -416,6 +435,53 @@ internal static class SettingsPanel
return row;
}
/// <summary>Label above a full-width text box; commits on Enter or focus loss when the text changed.</summary>
private static Control TextRow(string label, string value, string? hint, Action<string> onChange, string? tooltip = null)
{
string committed = value;
var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) };
box.Children.Add(new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, Margin = new Thickness(0, 0, 0, 2) });
var tb = new TextBox
{
Text = value,
Watermark = hint,
FontSize = 11,
Height = 22,
Padding = new Thickness(4, 2),
Background = ColPanelBg,
Foreground = ColAmber,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
VerticalContentAlignment = VerticalAlignment.Center,
};
DisableInnerScroll(tb);
void Commit()
{
string text = tb.Text ?? string.Empty;
if (string.Equals(text, committed, StringComparison.Ordinal)) return;
committed = text;
onChange(text);
}
// Same keyboard gate as the number boxes: typed keys go to Avalonia, not the game.
tb.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tb.LostFocus += (_, _) =>
{
Win32Backend.AvaloniaTextInputActive = false;
Commit();
};
tb.KeyDown += (_, e) =>
{
if (e.Key == Avalonia.Input.Key.Enter) Commit();
};
box.Children.Add(tb);
if (tooltip != null)
{
ToolTip.SetTip(box, tooltip);
ToolTip.SetShowDelay(box, 400);
}
return box;
}
private static Control IntRow(string label, int value, int min, int max, int step, Action<int> onChange, string? tooltip = null)
{
int current = Math.Clamp(value, min, max);
@ -699,6 +765,96 @@ internal static class SettingsPanel
return row;
}
/// <summary>Label on the left, a single action button on the right.</summary>
private static Control ButtonRow(string label, string buttonText, Action onClick, string? tooltip = null)
{
var btn = new Button
{
Content = buttonText,
FontSize = 10,
Height = 20,
MinWidth = 160,
Padding = new Thickness(4, 1),
Background = ColBtnFill,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
HorizontalContentAlignment = HorizontalAlignment.Center,
};
btn.Click += (_, _) => onClick();
var row = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
Margin = new Thickness(0, 2, 0, 2),
Height = 22,
};
var lblBlock = new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, VerticalAlignment = VerticalAlignment.Center };
Grid.SetColumn(lblBlock, 0);
Grid.SetColumn(btn, 1);
row.Children.Add(lblBlock);
row.Children.Add(btn);
if (tooltip != null)
{
ToolTip.SetTip(row, tooltip);
ToolTip.SetShowDelay(row, 400);
}
return row;
}
/// <summary>
/// [All on] [All off] [ILT Hub on] over a 3-column grid of toggles, one per RynthAi trace
/// category. Each change edits DiagCategories, saves, and rebuilds the tab so the grid redraws.
/// </summary>
private static Control TraceCategoriesRow(PanelState state, SettingRow row)
{
var cats = TraceCategoryLevels.Parse(state.Data.DiagCategories);
if (cats.Count == 0)
return new TextBlock { Text = "Waiting for RynthAi...", Foreground = ColMute, FontSize = 10, Margin = new Thickness(0, 2, 0, 0) };
void Save(string levels)
{
state.Data.DiagCategories = levels;
Push(state);
state.Rebuild?.Invoke();
}
Button Bulk(string text, Func<string> next)
{
var b = new Button
{
Content = text, FontSize = 10, Height = 20, Padding = new Thickness(6, 1),
Background = ColBtnFill, Foreground = ColTextDim, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
};
b.Click += (_, _) => Save(next());
return b;
}
var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) };
var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 0, 0, 4) };
buttons.Children.Add(Bulk("All on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true)));
buttons.Children.Add(Bulk("All off", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", false)));
buttons.Children.Add(Bulk("ILT Hub on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true, "Ilt")));
if (row.Tooltip != null)
{
ToolTip.SetTip(buttons, row.Tooltip);
ToolTip.SetShowDelay(buttons, 400);
}
box.Children.Add(buttons);
var grid = new Avalonia.Controls.Primitives.UniformGrid { Columns = 3 };
foreach (var (name, level) in cats)
{
string catName = name;
bool on = level != TraceCategoryLevels.Off;
grid.Children.Add(BoolRow(TraceCategoryLevels.Label(name, level), on,
v => Save(TraceCategoryLevels.Set(state.Data.DiagCategories, catName, v))));
}
box.Children.Add(grid);
return box;
}
// SimpleTheme wraps TextBox content in a ScrollViewer, and its vertical
// scrollbar's up RepeatButton is a filled triangle Path. On these short
// (Height=20) single-line numeric fields that scrollbar shows and the

View file

@ -6,7 +6,8 @@
// minimized|expanded, line 2 unused, line 3 target|notarget, line 4
// vitals|novitals; line 5 filesopen|nofiles, the Loaded files drawer; line 9
// ranges|noranges, the Ranges drawer; line 10 patrol|nopatrol, the Patrol
// drawer: the left-edge drawers, ImGui/Panels/DashboardDrawers.cs). Line 2
// drawer; line 11 remote|noremote, the Mini Remote drawer: the left-edge
// drawers, ImGui/Panels/DashboardDrawers.cs). Line 2
// was the Monsters button's Simple/Advanced mode, retired 2026-10-01 with the
// basic Monsters panel: it is still written ("advanced") so the lines after
// it keep their places, and ignored on read. Lines 7 and 8 (the dashboard's
@ -37,6 +38,7 @@ internal static class RynthAiDashboardState
private static volatile bool _barCollapsed; // the RynthCore bar shows only its grip + expand
private static volatile bool _rangesOpen; // the Ranges drawer beside the dashboard is open
private static volatile bool _patrolOpen; // the Patrol drawer beside the dashboard is open
private static volatile bool _remoteOpen; // the Mini Remote drawer beside the dashboard is open
// Lines 7 and 8, unused since 2026-10-05: written back as read.
private static string _line7 = "-", _line8 = "-";
private static bool _loaded;
@ -140,6 +142,19 @@ internal static class RynthAiDashboardState
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
}
/// <summary>The Mini Remote drawer (RynthAi's Mini Remote drawn by the plugin) is open beside the dashboard. Any thread.</summary>
public static bool RemoteOpen
{
get { EnsureLoaded(); return _remoteOpen; }
}
public static void SetRemoteOpen(bool open)
{
EnsureLoaded();
_remoteOpen = open;
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
}
/// <summary>Reads the file if it hasn't been read yet. Engine init calls this so AC's thread never does.</summary>
public static void EnsureLoaded()
{
@ -163,6 +178,7 @@ internal static class RynthAiDashboardState
if (lines.Length >= 8 && lines[7].Trim().Length > 0) _line8 = lines[7].Trim();
_rangesOpen = lines.Length >= 9 && lines[8].Trim().Equals("ranges", StringComparison.OrdinalIgnoreCase);
_patrolOpen = lines.Length >= 10 && lines[9].Trim().Equals("patrol", StringComparison.OrdinalIgnoreCase);
_remoteOpen = lines.Length >= 11 && lines[10].Trim().Equals("remote", StringComparison.OrdinalIgnoreCase);
}
}
catch { /* corrupt cache: start expanded */ }
@ -180,7 +196,8 @@ internal static class RynthAiDashboardState
+ (_showTargetBar ? "target" : "notarget") + "\n" + (_showVitals ? "vitals" : "novitals") + "\n"
+ (_filesOpen ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n"
+ _line7 + "\n" + _line8 + "\n"
+ (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n");
+ (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n"
+ (_remoteOpen ? "remote" : "noremote") + "\n");
}
catch { /* best-effort */ }
}