RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9b5e2765b7
commit
a24ed6df7c
322 changed files with 83009 additions and 7504 deletions
|
|
@ -228,6 +228,9 @@ internal static class AvaloniaOverlay
|
|||
internal static volatile int SurfacePixelWidth;
|
||||
internal static volatile int SurfacePixelHeight;
|
||||
internal static volatile float InputScale = 1f;
|
||||
|
||||
/// <summary>True once the overlay window exists (Start ran and built it).</summary>
|
||||
internal static bool IsRunning => _window != null;
|
||||
internal static bool UseAnglePreferredBridge { get; private set; }
|
||||
internal static bool UseCustomSkiaBridge { get; private set; }
|
||||
internal static bool ShouldUseCustomSkiaProducer => UseCustomSkiaBridge;
|
||||
|
|
@ -321,6 +324,7 @@ internal static class AvaloniaOverlay
|
|||
|
||||
internal static void RequestCapture()
|
||||
{
|
||||
if (_window == null) return; // not started: nothing to capture, no dispatcher to wake
|
||||
Dispatcher.UIThread.Post(() => _window?.RequestCapture(), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
|
|
@ -331,27 +335,107 @@ internal static class AvaloniaOverlay
|
|||
{
|
||||
var dcomp = DcompActivateBarButton;
|
||||
if (dcomp != null) { dcomp(title); return; }
|
||||
// Not started (Avalonia off, e.g. the CoreCLR engine): no Avalonia panels, and
|
||||
// touching Dispatcher.UIThread would bring up a dispatcher for nothing.
|
||||
if (_window == null) return;
|
||||
Dispatcher.UIThread.Post(() => _window?.ActivateBarButton(title), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The ImGui face of <paramref name="title"/> just opened: take down any
|
||||
/// Avalonia copy of it (docked or popped out) without saving that as the
|
||||
/// panel's state, so one panel is never on screen twice. Any thread.
|
||||
/// </summary>
|
||||
internal static void CloseAvaloniaCopy(string title)
|
||||
{
|
||||
if (_window == null) return; // not started: there is no Avalonia copy (and no dispatcher to wake)
|
||||
Dispatcher.UIThread.Post(() => _window?.CloseAvaloniaCopyCore(title), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="action"/> on the Avalonia UI thread at Input
|
||||
/// priority (same queue as ActivateBarButton), so a sequence of UI steps
|
||||
/// stays in order. Any thread.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Takes keyboard focus off any Avalonia TextBox (an ImGui text field just
|
||||
/// took the keyboard; plan §3.2 d). Clearing Avalonia's focus makes the
|
||||
/// TextBox lose focus (which clears AvaloniaTextInputActive) without
|
||||
/// touching Win32 focus. Any thread.
|
||||
/// </summary>
|
||||
internal static void ClearTextFocus()
|
||||
{
|
||||
if (_window != null)
|
||||
Dispatcher.UIThread.Post(() => _window?.FocusManager?.ClearFocus(), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
internal static void PostToUi(Action action)
|
||||
{
|
||||
if (_window != null)
|
||||
Dispatcher.UIThread.Post(action, DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
/// <summary>Toggles a panel synchronously. Avalonia UI thread only (inside PostToUi).</summary>
|
||||
internal static void TogglePanelOnUiThread(string title) => _window?.ActivateBarButton(title);
|
||||
|
||||
/// <summary>
|
||||
/// True while the ImGui bar stands in for the docked Avalonia bar: the
|
||||
/// Avalonia bar is laid out but invisible (opacity 0, so pop-out can still
|
||||
/// measure it) and publishes no hit rects, so it takes no clicks.
|
||||
/// </summary>
|
||||
internal static volatile bool DockedBarSuppressed;
|
||||
|
||||
internal static void SetDockedBarSuppressed(bool suppressed)
|
||||
{
|
||||
DockedBarSuppressed = suppressed;
|
||||
// Before Start there is no window (and no UI thread to post to): BuildRoot reads the flag.
|
||||
if (_window != null)
|
||||
Dispatcher.UIThread.Post(() => _window?.ApplyDockedBarSuppression(), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The ImGui bar's ↗: move the (hidden) docked Avalonia bar to where the
|
||||
/// ImGui bar is, then pop it out, in one UI-thread step so PopOutBar
|
||||
/// snapshots the right docked position.
|
||||
/// </summary>
|
||||
internal static void PopOutBarFrom(double left, double top)
|
||||
{
|
||||
if (_window == null) return;
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
_window?.MoveDockedBar(left, top);
|
||||
_window?.PopOutBar();
|
||||
}, DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
/// <summary>Keeps the hidden docked Avalonia bar where the ImGui bar is. Any thread.</summary>
|
||||
internal static void SyncDockedBarPosition(double left, double top)
|
||||
{
|
||||
if (_window != null)
|
||||
Dispatcher.UIThread.Post(() => _window?.MoveDockedBar(left, top), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
internal static void CommitDrag(int x, int y)
|
||||
{
|
||||
if (_window == null) return;
|
||||
Dispatcher.UIThread.Post(() => _window?.CommitBarDrag(x, y), DispatcherPriority.Render);
|
||||
}
|
||||
|
||||
internal static void MoveBarByPhys(int x, int y)
|
||||
{
|
||||
if (_window == null) return;
|
||||
Dispatcher.UIThread.Post(() => _window?.MoveBarByPhys(x, y), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
internal static void ResizePanelByPhys(int w, int h)
|
||||
{
|
||||
if (_window == null) return;
|
||||
Dispatcher.UIThread.Post(() => _window?.ResizeShellByPhys(w, h), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
internal static void NotifyGameSurfaceMetricsChanged()
|
||||
{
|
||||
if (!UseCustomSkiaBridge)
|
||||
if (!UseCustomSkiaBridge || _window == null)
|
||||
return;
|
||||
|
||||
Dispatcher.UIThread.Post(() => _window?.OnGameSurfaceMetricsChanged(), DispatcherPriority.Render);
|
||||
|
|
@ -396,6 +480,7 @@ internal static class AvaloniaOverlay
|
|||
internal static void DismissLightDismissPopups()
|
||||
{
|
||||
HasOpenLightDismissPopup = false;
|
||||
if (_window == null) return;
|
||||
Dispatcher.UIThread.Post(() => _window?.CloseLightDismissPopups(), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
|
|
@ -1337,13 +1422,13 @@ internal class RynthOverlayWindow : Window
|
|||
ToolTip.SetTip(rcLabel, $"RynthCore {EntryPoint.BuildStamp}"); // plugins: Status panel
|
||||
stack.Children.Add(rcLabel);
|
||||
|
||||
var barSuppressed = new HashSet<string> { "Monsters", "Settings", "Nav", "Meta", "Items" };
|
||||
var barSuppressed = new HashSet<string> { "Monsters", "Damage", "Settings", "Nav", "Meta", "Items", "Lua" };
|
||||
foreach (var p in registeredPanels)
|
||||
{
|
||||
_registeredPanels[p.Title] = p.Factory;
|
||||
if (barSuppressed.Contains(p.Title)) continue;
|
||||
var btn = StyleBarButton(new Button { Content = p.Title });
|
||||
btn.Click += (_, _) => ActivateBarButton(p.Title);
|
||||
btn.Click += (_, _) => PanelRouter.Toggle(p.Title);
|
||||
stack.Children.Add(btn);
|
||||
_barButtons[p.Title] = btn;
|
||||
}
|
||||
|
|
@ -1389,6 +1474,11 @@ internal class RynthOverlayWindow : Window
|
|||
CornerRadius = new CornerRadius(4),
|
||||
Child = stack
|
||||
};
|
||||
if (AvaloniaOverlay.DockedBarSuppressed)
|
||||
{
|
||||
_barBorder.Opacity = 0;
|
||||
_barBorder.IsHitTestVisible = false;
|
||||
}
|
||||
|
||||
// Update physical bar bounds for dragging. Use the persisted position
|
||||
// if we have one so a reload (or AC restart) keeps the user's layout.
|
||||
|
|
@ -1432,7 +1522,8 @@ internal class RynthOverlayWindow : Window
|
|||
// its own comments. Poll briefly; give up after a few seconds so
|
||||
// a never-ready GameHwnd (Decal coexistence?) doesn't leave the
|
||||
// bar lost.
|
||||
if (PanelStateStore.BarFloating && _floatingBar == null)
|
||||
// An ImGui-faced bar pops out as an ImGui window (ImGuiBar.SyncPopOut).
|
||||
if (PanelStateStore.BarFloating && _floatingBar == null && ImGuiBar.ResolveFace() != PanelFace.ImGui)
|
||||
{
|
||||
TryRestoreFloatingBar(attemptsRemaining: 30);
|
||||
}
|
||||
|
|
@ -1454,9 +1545,18 @@ internal class RynthOverlayWindow : Window
|
|||
}
|
||||
if (kv.Value.Floating)
|
||||
{
|
||||
// Panels with an ImGui face pop out as ImGui windows now
|
||||
// (ImGuiPopOuts, Tom 2026-09-29): ImGuiPanelHost.RestoreOnce
|
||||
// reopens them popped out. Leave the saved entry alone.
|
||||
if (PanelRouter.ResolveDockedFace(kv.Key) == PanelFace.ImGui)
|
||||
continue;
|
||||
deferred.Add(kv.Key);
|
||||
continue;
|
||||
}
|
||||
// Docked panels whose docked face is ImGui are restored by
|
||||
// ImGuiPanelHost.RestoreOnce instead.
|
||||
if (PanelRouter.ResolveDockedFace(kv.Key) == PanelFace.ImGui)
|
||||
continue;
|
||||
if (_registeredPanels.TryGetValue(kv.Key, out Func<Control>? factory))
|
||||
TogglePanel(kv.Key, factory);
|
||||
}
|
||||
|
|
@ -1487,8 +1587,24 @@ internal class RynthOverlayWindow : Window
|
|||
}
|
||||
}
|
||||
|
||||
private void RestoreFloatingPanels(List<string> titles)
|
||||
private void RestoreFloatingPanels(List<string> titles) => RestoreFloatingPanels(titles, 0);
|
||||
|
||||
private void RestoreFloatingPanels(List<string> titles, int waited)
|
||||
{
|
||||
// A floating panel's window must be created on AC's thread (PopOut uses
|
||||
// RunOnGameThread). Login can complete before Win32Backend knows the game
|
||||
// window (it initialises with ImGui, a few seconds later); restoring then
|
||||
// created the window on this thread, the later close was posted to the
|
||||
// game thread, DestroyWindow failed with ACCESS_DENIED and the old window
|
||||
// stayed up beside every reopened one — the double dashboard
|
||||
// (2026-09-28). Wait for the game window, up to ~30 s.
|
||||
if (ImGuiBackend.Win32Backend.GameHwnd == IntPtr.Zero && waited < 120)
|
||||
{
|
||||
DispatcherTimer.RunOnce(() => RestoreFloatingPanels(titles, waited + 1), TimeSpan.FromMilliseconds(250));
|
||||
return;
|
||||
}
|
||||
if (waited > 0)
|
||||
try { RynthLog.UI($"AvaloniaOverlay: restoring floating panel(s) after waiting {waited * 250} ms for the game window."); } catch { }
|
||||
try
|
||||
{
|
||||
foreach (var title in titles)
|
||||
|
|
@ -1515,6 +1631,35 @@ internal class RynthOverlayWindow : Window
|
|||
QueueCapture();
|
||||
}
|
||||
|
||||
internal void CloseAvaloniaCopyCore(string title)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_floatingPanels.TryGetValue(title, out FloatingPanelHost? host))
|
||||
{
|
||||
RynthLog.Info($"Panel({title}): ImGui face opened; closing its popped-out Avalonia window.");
|
||||
_floatingPanels.Remove(title);
|
||||
RebuildFloatingLayeredSnapshot();
|
||||
_panelContents.Remove(title);
|
||||
try { _desktopCanvas.Children.Remove(host.RootControl); } catch { }
|
||||
host.Dispose();
|
||||
}
|
||||
if (_activePanels.TryGetValue(title, out Border? docked))
|
||||
{
|
||||
RynthLog.Info($"Panel({title}): ImGui face opened; closing its docked Avalonia copy.");
|
||||
_desktopCanvas.Children.Remove(docked);
|
||||
_activePanels.Remove(title);
|
||||
_panelContents.Remove(title);
|
||||
}
|
||||
RefreshHitTestSnapshot();
|
||||
RequestFrameRefresh();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"Panel({title}): CloseAvaloniaCopy threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
internal void ActivateBarButton(string title)
|
||||
{
|
||||
if (_registeredPanels.TryGetValue(title, out Func<Control>? factory))
|
||||
|
|
@ -1540,20 +1685,63 @@ internal class RynthOverlayWindow : Window
|
|||
}
|
||||
}
|
||||
|
||||
// Every docked frame carries this tag so a frame the dictionaries lost
|
||||
// track of can still be found (see RemoveStrayPanelFrames).
|
||||
private const string PanelFrameTagPrefix = "rc-panel:";
|
||||
|
||||
private static string PanelFrameTag(string title) => PanelFrameTagPrefix + title;
|
||||
|
||||
/// <summary>
|
||||
/// A panel has at most one frame. Before opening a new one, remove any
|
||||
/// frame for this title still sitting in the canvas that neither
|
||||
/// _activePanels nor a floating host owns: it would keep drawing under the
|
||||
/// new one and could never be clicked (hit-testing only covers tracked
|
||||
/// frames), i.e. the "frozen duplicate" players see.
|
||||
/// </summary>
|
||||
private int RemoveStrayPanelFrames(string title)
|
||||
{
|
||||
string tag = PanelFrameTag(title);
|
||||
_activePanels.TryGetValue(title, out Border? tracked);
|
||||
_floatingPanels.TryGetValue(title, out FloatingPanelHost? host);
|
||||
var strays = _desktopCanvas.Children
|
||||
.OfType<Control>()
|
||||
.Where(c => c.Tag is string t && t == tag
|
||||
&& !ReferenceEquals(c, tracked)
|
||||
&& !ReferenceEquals(c, host?.RootControl))
|
||||
.ToList();
|
||||
foreach (Control stray in strays)
|
||||
{
|
||||
try { _desktopCanvas.Children.Remove(stray); } catch { }
|
||||
}
|
||||
if (strays.Count > 0)
|
||||
RynthLog.Info($"Panel({title}): removed {strays.Count} untracked frame(s) from the overlay - a duplicate was about to show.");
|
||||
return strays.Count;
|
||||
}
|
||||
|
||||
private int CountPanelFrames(string title)
|
||||
{
|
||||
string tag = PanelFrameTag(title);
|
||||
return _desktopCanvas.Children.Count(c => c.Tag is string t && t == tag);
|
||||
}
|
||||
|
||||
private void TogglePanel(string title, Func<Control> factory)
|
||||
{
|
||||
if (_activePanels.TryGetValue(title, out var existing))
|
||||
{
|
||||
RynthLog.Info($"Panel({title}): toggle -> close docked (frames={CountPanelFrames(title)}, inWorld={LoginLifecycleHooks.HasObservedLoginComplete}).");
|
||||
ClosePanel(title, existing);
|
||||
}
|
||||
else if (_floatingPanels.TryGetValue(title, out var floating))
|
||||
{
|
||||
// Toggling a panel that's currently popped out closes the
|
||||
// floating window entirely (matches the docked-mode toggle).
|
||||
RynthLog.Info($"Panel({title}): toggle -> close floating (frames={CountPanelFrames(title)}, inWorld={LoginLifecycleHooks.HasObservedLoginComplete}).");
|
||||
CloseFloatingPanel(title, floating);
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveStrayPanelFrames(title);
|
||||
RynthLog.Info($"Panel({title}): toggle -> open (inWorld={LoginLifecycleHooks.HasObservedLoginComplete}, canvas={_desktopCanvas.Bounds.Width:0}x{_desktopCanvas.Bounds.Height:0}).");
|
||||
bool isRynthAi = string.Equals(title, "RynthAi", StringComparison.OrdinalIgnoreCase);
|
||||
bool isMonsters = string.Equals(title, "Monsters", StringComparison.OrdinalIgnoreCase);
|
||||
bool isRadar = string.Equals(title, "Radar", StringComparison.OrdinalIgnoreCase);
|
||||
|
|
@ -1572,7 +1760,7 @@ internal class RynthOverlayWindow : Window
|
|||
// clamps the effective render size regardless of how Height was
|
||||
// set, so a hardcoded large floor here would silently re-expand
|
||||
// it back to 260 on every reopen despite the smaller saved value.
|
||||
bool rynthAiMinimized = isRynthAi && Panels.RynthAiPanel.IsAvaloniaMinimized;
|
||||
bool rynthAiMinimized = isRynthAi && RynthAiDashboardState.Minimized;
|
||||
var windowFrame = new Border
|
||||
{
|
||||
Width = hasSaved && saved.Width > 0 ? saved.Width : defaultW,
|
||||
|
|
@ -2008,6 +2196,7 @@ internal class RynthOverlayWindow : Window
|
|||
|
||||
windowFrame.Child = grid;
|
||||
windowFrame.PointerPressed += (_, _) => BringPanelToFront(title, windowFrame);
|
||||
windowFrame.Tag = PanelFrameTag(title);
|
||||
_desktopCanvas.Children.Add(windowFrame);
|
||||
|
||||
double initialLeft = hasSaved ? saved.Left : 100 + (_activePanels.Count * 20);
|
||||
|
|
@ -2040,16 +2229,30 @@ internal class RynthOverlayWindow : Window
|
|||
|
||||
private void ClosePanel(string title, Border panel)
|
||||
{
|
||||
// Only forget the tracked frame if it is the one being closed. A close
|
||||
// from an older frame's handler must not untrack the live frame: that
|
||||
// left it drawing in the canvas, unclickable, and the next bar toggle
|
||||
// opened a second copy on top of it.
|
||||
bool isTracked = _activePanels.TryGetValue(title, out Border? tracked) && ReferenceEquals(tracked, panel);
|
||||
|
||||
// Save final pos/size before tearing the panel down so reopens
|
||||
// start where the user left it.
|
||||
PersistPanelState(title, panel, open: false);
|
||||
if (isTracked)
|
||||
PersistPanelState(title, panel, open: false);
|
||||
|
||||
_desktopCanvas.Children.Remove(panel);
|
||||
_activePanels.Remove(title);
|
||||
// Drop the content reference — closing the panel discards in-panel
|
||||
// state, matching the previous behavior where reopening called factory()
|
||||
// again. Popout/redock keeps the entry, full-close removes it.
|
||||
_panelContents.Remove(title);
|
||||
if (isTracked)
|
||||
{
|
||||
_activePanels.Remove(title);
|
||||
// Drop the content reference — closing the panel discards in-panel
|
||||
// state, matching the previous behavior where reopening called factory()
|
||||
// again. Popout/redock keeps the entry, full-close removes it.
|
||||
_panelContents.Remove(title);
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Info($"Panel({title}): close came from an untracked frame; the tracked frame stays open.");
|
||||
}
|
||||
// Tear down the radar's settings popup if this is the radar — the
|
||||
// popup lives in _desktopCanvas as a sibling and would otherwise
|
||||
// leak past the panel close.
|
||||
|
|
@ -2242,6 +2445,7 @@ internal class RynthOverlayWindow : Window
|
|||
|
||||
Canvas.SetLeft(renderWrapper, offBoundsX);
|
||||
Canvas.SetTop(renderWrapper, offBoundsY);
|
||||
renderWrapper.Tag = PanelFrameTag(title);
|
||||
_desktopCanvas.Children.Add(renderWrapper);
|
||||
|
||||
// The chrome's caption is 24px tall; reserve ~60px on the right for
|
||||
|
|
@ -2700,6 +2904,11 @@ internal class RynthOverlayWindow : Window
|
|||
// where the user popped out from. Canvas.GetLeft can return NaN if
|
||||
// the bar hasn't been positioned yet — defensive defaults match
|
||||
// BuildRoot's initial 50,5.
|
||||
// Popped out, the bar is always the Avalonia bar - even while the ImGui
|
||||
// bar stands in for it docked.
|
||||
_barBorder.Opacity = 1;
|
||||
_barBorder.IsHitTestVisible = true;
|
||||
|
||||
double dockedLeft = GetCanvasLeft(_barBorder);
|
||||
double dockedTop = GetCanvasTop(_barBorder);
|
||||
if (double.IsNaN(dockedLeft)) dockedLeft = 50;
|
||||
|
|
@ -2905,9 +3114,26 @@ internal class RynthOverlayWindow : Window
|
|||
ToolTip.SetTip(_barPopoutButton, "Pop the bar out into its own floating window.");
|
||||
}
|
||||
|
||||
ApplyDockedBarSuppression();
|
||||
RynthLog.Info($"RedockBar: redocked to canvas at ({dockedLeft:0.#},{dockedTop:0.#}).");
|
||||
}
|
||||
|
||||
internal void ApplyDockedBarSuppression()
|
||||
{
|
||||
if (_barBorder == null) return;
|
||||
bool hide = AvaloniaOverlay.DockedBarSuppressed && _floatingBar == null;
|
||||
_barBorder.Opacity = hide ? 0 : 1;
|
||||
_barBorder.IsHitTestVisible = !hide;
|
||||
RefreshHitTestSnapshot();
|
||||
RequestFrameRefresh();
|
||||
RynthLog.Info($"RedockBar: redocked to canvas at ({dockedLeft:0.#},{dockedTop:0.#}).");
|
||||
}
|
||||
|
||||
internal void MoveDockedBar(double left, double top)
|
||||
{
|
||||
if (_barBorder == null || _floatingBar != null) return;
|
||||
Canvas.SetLeft(_barBorder, left);
|
||||
Canvas.SetTop(_barBorder, top);
|
||||
RefreshHitTestSnapshot();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -2926,6 +3152,16 @@ internal class RynthOverlayWindow : Window
|
|||
return;
|
||||
}
|
||||
|
||||
// ImGui in game, Avalonia popped out: when this panel's docked face is
|
||||
// ImGui, redocking closes the floating window and opens the ImGui face.
|
||||
if (PanelRouter.RedockGoesToImGui(title))
|
||||
{
|
||||
RynthLog.Info($"RedockPanel({title}): docked face is ImGui - handing off.");
|
||||
CloseFloatingPanel(title, host);
|
||||
PanelRouter.CompleteRedockToImGui(title);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_registeredPanels.TryGetValue(title, out Func<Control>? factory) || factory == null)
|
||||
{
|
||||
RynthLog.Info($"RedockPanel({title}): bailing — no factory.");
|
||||
|
|
@ -3177,6 +3413,7 @@ internal class RynthOverlayWindow : Window
|
|||
Grid.SetRow(resizeGrip, 1);
|
||||
windowFrame.Child = grid;
|
||||
windowFrame.PointerPressed += (_, _) => BringPanelToFront(title, windowFrame);
|
||||
windowFrame.Tag = PanelFrameTag(title);
|
||||
_desktopCanvas.Children.Add(windowFrame);
|
||||
|
||||
double initialLeft = hasSaved ? saved.Left : 100 + (_activePanels.Count * 20);
|
||||
|
|
@ -3864,7 +4101,14 @@ internal class RynthOverlayWindow : Window
|
|||
float inputScale = (float)GetEffectiveRenderScale();
|
||||
AvaloniaOverlay.InputScale = inputScale;
|
||||
|
||||
if (_barBorder != null)
|
||||
bool barSuppressed = AvaloniaOverlay.DockedBarSuppressed && _floatingBar == null;
|
||||
if (barSuppressed)
|
||||
{
|
||||
// Off-screen, zero-size: IsOverPanel/bar drag never match it.
|
||||
AvaloniaOverlay.PanelPhysLeft = AvaloniaOverlay.PanelPhysRight = -10000;
|
||||
AvaloniaOverlay.PanelPhysTop = AvaloniaOverlay.PanelPhysBottom = -10000;
|
||||
}
|
||||
else if (_barBorder != null)
|
||||
{
|
||||
Point? barOrigin = _barBorder.TranslatePoint(default, _desktopCanvas);
|
||||
double barLeft = barOrigin?.X ?? Canvas.GetLeft(_barBorder);
|
||||
|
|
@ -3884,7 +4128,7 @@ internal class RynthOverlayWindow : Window
|
|||
}
|
||||
|
||||
var buttonRects = new Dictionary<string, (double Left, double Top, double Width, double Height)>(_barButtons.Count, StringComparer.OrdinalIgnoreCase);
|
||||
if (_barBorder != null)
|
||||
if (_barBorder != null && !barSuppressed)
|
||||
{
|
||||
foreach ((string title, Button button) in _barButtons)
|
||||
{
|
||||
|
|
@ -4423,6 +4667,8 @@ internal sealed unsafe class FloatingPanelHost : IDisposable
|
|||
_ownerApplied = true;
|
||||
}
|
||||
|
||||
// One popped-out window per panel: retire any earlier window for this title.
|
||||
LayeredWindow.ClaimTitle(title, _layered.Hwnd);
|
||||
_layered.CaptionHeight = captionHeight;
|
||||
_layered.CaptionRightInset = captionRightInset;
|
||||
// Each chrome button is 20×20 logical + ~4px margin = ~24
|
||||
|
|
@ -4448,8 +4694,14 @@ internal sealed unsafe class FloatingPanelHost : IDisposable
|
|||
// job and returns immediately, never blocking the game thread.
|
||||
_layered.OnInput = (uint msg, IntPtr wp, IntPtr lp, int cx, int cy) =>
|
||||
Dispatcher.UIThread.Post(() => ForwardInput(msg, wp, lp, cx, cy));
|
||||
// Post, not Invoke (2026-09-30): OnMoved fires on AC's game thread (the
|
||||
// LayeredWindow WndProc: WM_MOVE, EndDrag, capture loss) and only persists
|
||||
// the position, so nothing needs to wait for it. The blocking Invoke held
|
||||
// AC's frame on panel-state persistence at every drag end, and is the same
|
||||
// AB-BA deadlock class as OnInput above if the UI thread is inside
|
||||
// RunOnGameThread / UpdateLayeredWindow on this HWND at that moment.
|
||||
_layered.OnMoved = (x, y) =>
|
||||
Dispatcher.UIThread.Invoke(() => OnLayeredMoved(x, y));
|
||||
Dispatcher.UIThread.Post(() => OnLayeredMoved(x, y));
|
||||
// Invoke (synchronous), NOT Post. This is deliberate: the WndProc runs
|
||||
// on AC's game thread, and during an HTBOTTOMRIGHT drag it sits in the
|
||||
// OS modal resize loop. The synchronous Invoke blocks that loop until
|
||||
|
|
@ -4508,13 +4760,33 @@ internal sealed unsafe class FloatingPanelHost : IDisposable
|
|||
internal void SetShown(bool shown)
|
||||
{
|
||||
if (_disposed || _layered.Hwnd == IntPtr.Zero || _windowShown == shown) return;
|
||||
_windowShown = shown;
|
||||
ImGuiBackend.Win32Backend.RunOnGameThread(() =>
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _setShownRetryAtMs) return;
|
||||
|
||||
// Record the new state only once the game thread has actually run the
|
||||
// Show/Hide. RunOnGameThread gives up after 2 s and returns false - the
|
||||
// game thread is often that busy right at login - and recording the
|
||||
// state first left a popped-out panel hidden for the whole session
|
||||
// (the bar button then "closes" an invisible window). Retry after 1 s.
|
||||
bool ran = ImGuiBackend.Win32Backend.RunOnGameThread(() =>
|
||||
{
|
||||
if (shown) _layered.Show(); else _layered.Hide();
|
||||
return true;
|
||||
});
|
||||
if (ran)
|
||||
{
|
||||
_windowShown = shown;
|
||||
_setShownRetryAtMs = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
_setShownRetryAtMs = now + 1000;
|
||||
RynthLog.Info($"FloatingPanelHost({Title}): {(shown ? "Show" : "Hide")} didn't run on the game thread; retrying.");
|
||||
}
|
||||
}
|
||||
|
||||
private long _setShownRetryAtMs;
|
||||
|
||||
public void Tick()
|
||||
{
|
||||
if (_disposed || _layered.Hwnd == IntPtr.Zero) return;
|
||||
|
|
|
|||
72
src/RynthCore.Engine/UI/Data/ChatCoords.cs
Normal file
72
src/RynthCore.Engine/UI/Data/ChatCoords.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/ChatCoords.cs
|
||||
// Finds map coordinates in a chat line ("42.1N, 33.6E", "42.1N 33.6E",
|
||||
// "33.6E 42.1N", "0.5S, 101.2W"), for the chat window's right-click menu
|
||||
// ("Arrow to ..." / "Go to ..." send them to RynthNav).
|
||||
//
|
||||
// Runs when a line's menu opens, never per frame. No engine dependencies:
|
||||
// tools/ChatCoordTests compiles this file.
|
||||
//
|
||||
// To keep ordinary chat from turning into coordinates ("give me 5 s, 2 e"),
|
||||
// a pair counts when both letters are capitals, or both numbers have a decimal
|
||||
// point; and every number must be on the map (0 to 102).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal readonly record struct ChatCoord(int Start, int Length, double Ns, double Ew)
|
||||
{
|
||||
/// <summary>"42.1N, 33.6E".</summary>
|
||||
public string Text => Fmt(Ns, 'N', 'S') + ", " + Fmt(Ew, 'E', 'W');
|
||||
|
||||
private static string Fmt(double v, char pos, char neg) =>
|
||||
Math.Abs(v).ToString("0.0##", CultureInfo.InvariantCulture) + (v >= 0 ? pos : neg);
|
||||
}
|
||||
|
||||
internal static class ChatCoords
|
||||
{
|
||||
private const double MaxDegrees = 102.0;
|
||||
|
||||
// number, optional space, letter; then a separator; then the other axis.
|
||||
private static readonly Regex NsFirst = new(
|
||||
@"(?<![\w.])(\d{1,3}(?:\.\d+)?)\s?([NnSs])(?![A-Za-z])[\s,;/]*(\d{1,3}(?:\.\d+)?)\s?([EeWw])(?![\w])",
|
||||
RegexOptions.CultureInvariant);
|
||||
private static readonly Regex EwFirst = new(
|
||||
@"(?<![\w.])(\d{1,3}(?:\.\d+)?)\s?([EeWw])(?![A-Za-z])[\s,;/]*(\d{1,3}(?:\.\d+)?)\s?([NnSs])(?![\w])",
|
||||
RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>Every coordinate pair in <paramref name="text"/>, in order, without overlaps.</summary>
|
||||
public static List<ChatCoord> Find(string? text)
|
||||
{
|
||||
var found = new List<ChatCoord>();
|
||||
if (string.IsNullOrEmpty(text) || text.Length > 4000) return found;
|
||||
Collect(NsFirst, text, nsFirst: true, found);
|
||||
Collect(EwFirst, text, nsFirst: false, found);
|
||||
found.Sort((a, b) => a.Start.CompareTo(b.Start));
|
||||
for (int i = found.Count - 1; i > 0; i--)
|
||||
if (found[i].Start < found[i - 1].Start + found[i - 1].Length) found.RemoveAt(i);
|
||||
return found;
|
||||
}
|
||||
|
||||
private static void Collect(Regex rx, string text, bool nsFirst, List<ChatCoord> found)
|
||||
{
|
||||
foreach (Match m in rx.Matches(text))
|
||||
{
|
||||
string n1 = m.Groups[1].Value, l1 = m.Groups[2].Value, n2 = m.Groups[3].Value, l2 = m.Groups[4].Value;
|
||||
bool capitals = char.IsUpper(l1[0]) && char.IsUpper(l2[0]);
|
||||
bool decimals = n1.Contains('.') && n2.Contains('.');
|
||||
if (!capitals && !decimals) continue;
|
||||
if (!double.TryParse(n1, NumberStyles.Float, CultureInfo.InvariantCulture, out double a)) continue;
|
||||
if (!double.TryParse(n2, NumberStyles.Float, CultureInfo.InvariantCulture, out double b)) continue;
|
||||
if (a > MaxDegrees || b > MaxDegrees) continue;
|
||||
double v1 = "SsWw".IndexOf(l1[0]) >= 0 ? -a : a;
|
||||
double v2 = "SsWw".IndexOf(l2[0]) >= 0 ? -b : b;
|
||||
found.Add(nsFirst ? new ChatCoord(m.Index, m.Length, v1, v2) : new ChatCoord(m.Index, m.Length, v2, v1));
|
||||
}
|
||||
}
|
||||
}
|
||||
1717
src/RynthCore.Engine/UI/Data/ChatData.cs
Normal file
1717
src/RynthCore.Engine/UI/Data/ChatData.cs
Normal file
File diff suppressed because it is too large
Load diff
806
src/RynthCore.Engine/UI/Data/DamageData.cs
Normal file
806
src/RynthCore.Engine/UI/Data/DamageData.cs
Normal file
|
|
@ -0,0 +1,806 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/DamageData.cs
|
||||
// RynthAi's learned per-monster combat data (the Damage panel) and the
|
||||
// name-keyed monster rules (Monsters panel, Damage drawer), for both faces.
|
||||
//
|
||||
// Every getter here frees its previous return buffer on the next call, so
|
||||
// the hub is the only caller: DamageSource (damage rows, selectable weapons,
|
||||
// pet choices) and MonsterRulesSource (rules). Before this, the Avalonia
|
||||
// Monsters and Damage panels both polled RynthPluginGetMonstersJson from the
|
||||
// UI thread. Setters run on the pump too (DamageCommands), so they no longer
|
||||
// race the plugin tick.
|
||||
//
|
||||
// Aelrynth difficulty tiers (2026-10-03): RynthAi keeps a monster's HP, kills,
|
||||
// casts to kill, seconds per kill and hit rate per tier of Aelrynth's awakened
|
||||
// worlds and scaled copies (same monsters, +5% a tier). The rows describe the
|
||||
// tier RynthAi is showing; RynthPluginGetAwakenedTierJson says which, and the
|
||||
// panel's picker sets it (RynthPluginSetDamageViewTier). Shown only on
|
||||
// Aelrynth (ServerInfo.IsAelrynth) and once RynthAi has seen the server's tier;
|
||||
// an older RynthAi without the export shows nothing of it.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>One row of RynthPluginGetMonsterDamageJson (a monster, per weapon/element/tier key).</summary>
|
||||
internal sealed class DamageRow
|
||||
{
|
||||
public uint Wcid; public string Name = ""; public uint Wid; public string Weapon = "";
|
||||
public string Elem = ""; public int Tier; public int Hp; public bool HpManual;
|
||||
/// <summary>Hp is an estimate: real Dereth's +5% per Aelrynth difficulty tier (that tier not appraised yet).</summary>
|
||||
public bool HpEst;
|
||||
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
|
||||
public double Casts; public int Kills; public string Key = "";
|
||||
/// <summary>Per-monster (wcid) weapon state, the same on every row of a wcid.</summary>
|
||||
public uint AssignedWid; public string AssignedWeapon = "";
|
||||
public uint BestWid; public string BestWeapon = "";
|
||||
public uint AssignedOff; public string AssignedOffName = "";
|
||||
public string Pet = ""; public string PetLabel = "Auto";
|
||||
/// <summary>What the monster takes most damage from ("Bludgeon 1.0, Pierce 0.86") and where that came from.</summary>
|
||||
public string Weak = ""; public string WeakSrc = "";
|
||||
/// <summary>Seconds per kill and hit rate (0-1) over every weapon; -1 = not learned yet.</summary>
|
||||
public double SecKill = -1, HitRate = -1;
|
||||
/// <summary>The monster being fought (or selected) right now.</summary>
|
||||
public bool Targeted;
|
||||
/// <summary>One of these is on the player's landblock.</summary>
|
||||
public bool Nearby;
|
||||
public List<DamageTierStat> Tiers = new();
|
||||
/// <summary>The synthetic top "Default" line (wcid 0).</summary>
|
||||
public bool IsDefault;
|
||||
}
|
||||
|
||||
internal sealed class DamageTierStat
|
||||
{
|
||||
public int Tier; public string Elem = ""; public string Weapon = "";
|
||||
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
|
||||
public double Casts; public int Kills;
|
||||
}
|
||||
|
||||
internal sealed class DamageView
|
||||
{
|
||||
public List<DamageRow> Rows = new();
|
||||
/// <summary>Weapons with learned rows (the filter list), in first-seen order.</summary>
|
||||
public List<(uint Id, string Name)> LearnedWeapons = new();
|
||||
/// <summary>Configured weapons (ItemRules) plus learned ones, by name: the per-row pickers.</summary>
|
||||
public List<(uint Id, string Name)> WeaponChoices = new();
|
||||
/// <summary>("" = Auto, "E:<element>", "I:<essence id>", label).</summary>
|
||||
public List<(string Key, string Name)> PetChoices = new();
|
||||
public bool Bound;
|
||||
/// <summary>The Aelrynth difficulty tier the rows describe; Show false = say nothing of tiers.</summary>
|
||||
public AwakenedTierView Tier = AwakenedTierView.Hidden;
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginGetAwakenedTierJson, gated on ServerInfo.IsAelrynth.</summary>
|
||||
internal sealed class AwakenedTierView
|
||||
{
|
||||
public static readonly AwakenedTierView Hidden = new();
|
||||
|
||||
public bool Show;
|
||||
/// <summary>The tier where the player stands; the tier the rows describe; whether that follows Current.</summary>
|
||||
public int Current, View;
|
||||
public bool Following = true;
|
||||
public double Percent = 5;
|
||||
/// <summary>Tiers with something learned, plus 0 and the current one, ascending.</summary>
|
||||
public List<int> Tiers = new();
|
||||
|
||||
public static AwakenedTierView Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(json)) return Hidden;
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (!r.TryGetProperty("show", out var sh) || sh.ValueKind != JsonValueKind.True) return Hidden;
|
||||
var t = new AwakenedTierView { Show = true };
|
||||
if (r.TryGetProperty("current", out var c)) t.Current = c.GetInt32();
|
||||
if (r.TryGetProperty("view", out var v)) t.View = v.GetInt32();
|
||||
if (r.TryGetProperty("following", out var f)) t.Following = f.ValueKind == JsonValueKind.True;
|
||||
if (r.TryGetProperty("percent", out var pc)) t.Percent = pc.GetDouble();
|
||||
if (r.TryGetProperty("tiers", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement e in arr.EnumerateArray()) t.Tiers.Add(e.GetInt32());
|
||||
return t;
|
||||
}
|
||||
catch { return Hidden; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The monster rules (RynthPluginGetMonstersJson). Parsed is shared: copy before changing (ParseCopy).</summary>
|
||||
internal sealed class MonsterRulesSnapshot
|
||||
{
|
||||
public MonsterRulesSnapshot(string json, MonstersPanel.Payload parsed)
|
||||
{
|
||||
Json = json;
|
||||
Parsed = parsed;
|
||||
foreach (MonstersPanel.Rule r in parsed.Rules)
|
||||
if (!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase))
|
||||
_custom.Add(r.Name);
|
||||
}
|
||||
|
||||
public string Json { get; }
|
||||
public MonstersPanel.Payload Parsed { get; }
|
||||
private readonly HashSet<string> _custom = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>An exact-name rule exists for <paramref name="name"/> (it doesn't inherit Default).</summary>
|
||||
public bool HasCustomRule(string name) => _custom.Contains(name);
|
||||
|
||||
public MonstersPanel.Rule? FindRule(string name)
|
||||
{
|
||||
foreach (MonstersPanel.Rule r in Parsed.Rules)
|
||||
if (!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
|
||||
return r;
|
||||
return null;
|
||||
}
|
||||
|
||||
public MonstersPanel.Rule DefaultRule()
|
||||
{
|
||||
foreach (MonstersPanel.Rule r in Parsed.Rules)
|
||||
if (r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase))
|
||||
return r;
|
||||
return new MonstersPanel.Rule { Name = "Default", UseBolt = true };
|
||||
}
|
||||
|
||||
/// <summary>A private, editable copy of the payload.</summary>
|
||||
public MonstersPanel.Payload ParseCopy() =>
|
||||
JsonSerializer.Deserialize(Json, MonstersPanelJsonContext.Default.Payload) ?? new MonstersPanel.Payload();
|
||||
}
|
||||
|
||||
/// <summary>Damage rows + weapons (500 ms) and pet choices (2 s) while a Damage face is open.</summary>
|
||||
internal sealed unsafe class DamageSource : UiSource<DamageView>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getRows, _getWeapons, _getPets, _getTier;
|
||||
private string? _rowsJson, _weaponsJson, _petsJson, _tierJson;
|
||||
private AwakenedTierView _tier = AwakenedTierView.Hidden;
|
||||
private bool _tierAelrynth;
|
||||
private List<DamageRow> _rows = new();
|
||||
private List<(uint Id, string Name)> _items = new();
|
||||
private List<(string Key, string Name)> _pets = new();
|
||||
private long _nextPetTicks;
|
||||
|
||||
public DamageSource() : base("Damage", periodMs: 500) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getRows == null)
|
||||
{
|
||||
_getRows = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMonsterDamageJson");
|
||||
_getWeapons = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetCombatWeaponsJson");
|
||||
_getPets = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetPetChoicesJson");
|
||||
_getTier = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetAwakenedTierJson");
|
||||
if (_getRows == null)
|
||||
{
|
||||
if (Current == null) Publish(new DamageView { Bound = false });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
bool changed = Current == null || !Current.Value.Bound;
|
||||
string? json = Read(_getRows);
|
||||
if (json != null && json != _rowsJson) { _rowsJson = json; _rows = ParseRows(json); changed = true; }
|
||||
|
||||
if (_getWeapons != null && (json = Read(_getWeapons)) != null && json != _weaponsJson)
|
||||
{
|
||||
_weaponsJson = json;
|
||||
_items = ParseItems(json);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// The difficulty tier, only on Aelrynth: anywhere else the panel says nothing of tiers.
|
||||
bool aelrynth = ServerInfo.IsAelrynth;
|
||||
string? tierJson = aelrynth && _getTier != null ? Read(_getTier) : null;
|
||||
if (aelrynth != _tierAelrynth || tierJson != _tierJson)
|
||||
{
|
||||
_tierAelrynth = aelrynth;
|
||||
_tierJson = tierJson;
|
||||
_tier = aelrynth ? AwakenedTierView.Parse(tierJson) : AwakenedTierView.Hidden;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
if (_getPets != null && now >= _nextPetTicks)
|
||||
{
|
||||
_nextPetTicks = now + Stopwatch.Frequency * 2;
|
||||
if ((json = Read(_getPets)) != null && json != _petsJson)
|
||||
{
|
||||
_petsJson = json;
|
||||
_pets = ParsePets(json);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) Publish(BuildView());
|
||||
}
|
||||
|
||||
/// <summary>Re-read the pet choices on the next poll too (after a pet change).</summary>
|
||||
public void RefreshPetsSoon() => _nextPetTicks = 0;
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getRows = _getWeapons = _getPets = _getTier = null;
|
||||
_rowsJson = _weaponsJson = _petsJson = _tierJson = null;
|
||||
_tier = AwakenedTierView.Hidden;
|
||||
_tierAelrynth = false;
|
||||
ClearSnapshot();
|
||||
}
|
||||
|
||||
private static string? Read(delegate* unmanaged[Cdecl]<IntPtr> fn)
|
||||
{
|
||||
IntPtr p = fn();
|
||||
return p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p);
|
||||
}
|
||||
|
||||
private DamageView BuildView()
|
||||
{
|
||||
var view = new DamageView { Rows = _rows, Bound = true, Tier = _tier };
|
||||
var seen = new HashSet<uint>();
|
||||
foreach (DamageRow r in _rows)
|
||||
if (r.Wid != 0 && seen.Add(r.Wid)) view.LearnedWeapons.Add((r.Wid, r.Weapon));
|
||||
|
||||
var choiceSeen = new HashSet<uint>();
|
||||
foreach (var it in _items) if (it.Id != 0 && choiceSeen.Add(it.Id)) view.WeaponChoices.Add(it);
|
||||
foreach (var w in view.LearnedWeapons) if (choiceSeen.Add(w.Id)) view.WeaponChoices.Add(w);
|
||||
view.WeaponChoices.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
view.PetChoices = _pets.Count > 0 ? _pets : new List<(string, string)> { ("", "Auto (update RynthAi for pet choices)") };
|
||||
return view;
|
||||
}
|
||||
|
||||
private static List<DamageRow> ParseRows(string json)
|
||||
{
|
||||
var list = new List<DamageRow>();
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
foreach (JsonElement e in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
var row = new DamageRow
|
||||
{
|
||||
Wcid = (uint)e.GetProperty("wcid").GetInt64(),
|
||||
Name = e.GetProperty("name").GetString() ?? "",
|
||||
Wid = (uint)e.GetProperty("wid").GetInt64(),
|
||||
Weapon = e.GetProperty("weapon").GetString() ?? "",
|
||||
Elem = e.GetProperty("elem").GetString() ?? "",
|
||||
Tier = e.GetProperty("tier").GetInt32(),
|
||||
Hp = e.GetProperty("hp").GetInt32(),
|
||||
HpManual = e.GetProperty("hpManual").GetBoolean(),
|
||||
Crit = e.GetProperty("crit").GetDouble(),
|
||||
CritN = e.GetProperty("critN").GetInt32(),
|
||||
NonCrit = e.GetProperty("noncrit").GetDouble(),
|
||||
NonCritN = e.GetProperty("noncritN").GetInt32(),
|
||||
Casts = e.GetProperty("casts").GetDouble(),
|
||||
Kills = e.GetProperty("kills").GetInt32(),
|
||||
Key = e.GetProperty("key").GetString() ?? "",
|
||||
};
|
||||
// Optional fields: an older plugin omits them.
|
||||
if (e.TryGetProperty("assignedWid", out var aw)) row.AssignedWid = (uint)aw.GetInt64();
|
||||
if (e.TryGetProperty("assignedWeapon", out var awn)) row.AssignedWeapon = awn.GetString() ?? "";
|
||||
if (e.TryGetProperty("bestWid", out var bw)) row.BestWid = (uint)bw.GetInt64();
|
||||
if (e.TryGetProperty("bestWeapon", out var bwn)) row.BestWeapon = bwn.GetString() ?? "";
|
||||
if (e.TryGetProperty("assignedOff", out var ao)) row.AssignedOff = (uint)ao.GetInt64();
|
||||
if (e.TryGetProperty("assignedOffName", out var aon)) row.AssignedOffName = aon.GetString() ?? "";
|
||||
if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean();
|
||||
if (e.TryGetProperty("hpEst", out var he)) row.HpEst = he.ValueKind == JsonValueKind.True;
|
||||
if (e.TryGetProperty("pet", out var pc)) row.Pet = pc.GetString() ?? "";
|
||||
if (e.TryGetProperty("petLabel", out var pl)) row.PetLabel = pl.GetString() ?? "Auto";
|
||||
if (e.TryGetProperty("weak", out var wk)) row.Weak = wk.GetString() ?? "";
|
||||
if (e.TryGetProperty("weakSrc", out var ws)) row.WeakSrc = ws.GetString() ?? "";
|
||||
if (e.TryGetProperty("secKill", out var sk)) row.SecKill = sk.GetDouble();
|
||||
if (e.TryGetProperty("hitRate", out var hr)) row.HitRate = hr.GetDouble();
|
||||
if (e.TryGetProperty("targeted", out var tg)) row.Targeted = tg.GetBoolean();
|
||||
if (e.TryGetProperty("nearby", out var nb)) row.Nearby = nb.GetBoolean();
|
||||
if (e.TryGetProperty("tiers", out var tarr) && tarr.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement te in tarr.EnumerateArray())
|
||||
row.Tiers.Add(new DamageTierStat
|
||||
{
|
||||
Tier = te.GetProperty("tier").GetInt32(),
|
||||
Elem = te.GetProperty("elem").GetString() ?? "",
|
||||
Weapon = te.GetProperty("weapon").GetString() ?? "",
|
||||
Crit = te.GetProperty("crit").GetDouble(),
|
||||
CritN = te.GetProperty("critN").GetInt32(),
|
||||
NonCrit = te.GetProperty("noncrit").GetDouble(),
|
||||
NonCritN = te.GetProperty("noncritN").GetInt32(),
|
||||
Casts = te.GetProperty("casts").GetDouble(),
|
||||
Kills = te.GetProperty("kills").GetInt32(),
|
||||
});
|
||||
list.Add(row);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<(uint, string)> ParseItems(string json)
|
||||
{
|
||||
var list = new List<(uint, string)>();
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
foreach (JsonElement e in doc.RootElement.EnumerateArray())
|
||||
list.Add(((uint)e.GetProperty("id").GetInt64(), e.GetProperty("name").GetString() ?? ""));
|
||||
}
|
||||
catch { }
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<(string, string)> ParsePets(string json)
|
||||
{
|
||||
var list = new List<(string, string)>();
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
foreach (JsonElement e in doc.RootElement.EnumerateArray())
|
||||
list.Add((e.GetProperty("key").GetString() ?? "", e.GetProperty("name").GetString() ?? ""));
|
||||
}
|
||||
catch { }
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Tier display: 0 = none ("—"); negative = ring spell ("R<level>"); positive = spell level.</summary>
|
||||
public static string FormatTier(int t) =>
|
||||
t == 0 ? "—" : t < 0 ? "R" + (-t).ToString(CultureInfo.InvariantCulture) : t.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>One monster's breakdown (RynthPluginGetMonsterDetailJson), for the Monster Detail panel.</summary>
|
||||
internal sealed class MonsterDetail
|
||||
{
|
||||
public uint Wcid; public string Name = ""; public int Hp; public string HpSrc = "";
|
||||
public double SecKill = -1, HitRate = -1;
|
||||
public string WeakSrc = "";
|
||||
public List<(string Element, double Mult)> Weak = new(); // Mult -1 = order only
|
||||
public List<DetailCast> Casts = new();
|
||||
public List<(string Weapon, int Hits, int Misses, double Sec, int SecN)> Weapons = new();
|
||||
public List<(string Element, int Kills, double Sec)> Summons = new();
|
||||
public List<(string Element, int Hits, double Avg, double Max)> Taken = new();
|
||||
public bool Bound;
|
||||
}
|
||||
|
||||
internal sealed class DetailCast
|
||||
{
|
||||
public string Weapon = "", Elem = ""; public int Tier, Hits, CritN, NonCritN, Kills;
|
||||
public double Avg, Crit, NonCrit, Casts;
|
||||
}
|
||||
|
||||
/// <summary>The selected monster's detail (1 s) while the Monster Detail panel is open.</summary>
|
||||
internal sealed unsafe class MonsterDetailSource : UiSource<MonsterDetail>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<uint, IntPtr> _get;
|
||||
private string? _lastJson;
|
||||
private uint _lastWcid;
|
||||
|
||||
public MonsterDetailSource() : base("MonsterDetail", periodMs: 1000) { }
|
||||
|
||||
/// <summary>The monster to show (any thread); the next poll reads it.</summary>
|
||||
public static volatile uint SelectedWcid;
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
uint wcid = SelectedWcid;
|
||||
if (_get == null)
|
||||
{
|
||||
_get = (delegate* unmanaged[Cdecl]<uint, IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMonsterDetailJson");
|
||||
if (_get == null)
|
||||
{
|
||||
if (Current == null) Publish(new MonsterDetail { Bound = false });
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (wcid == 0) return;
|
||||
IntPtr p = _get(wcid);
|
||||
string? json = p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p);
|
||||
if (json == null || (json == _lastJson && wcid == _lastWcid)) return;
|
||||
_lastJson = json;
|
||||
_lastWcid = wcid;
|
||||
Publish(Parse(json, wcid));
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_get = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
|
||||
private static MonsterDetail Parse(string json, uint wcid)
|
||||
{
|
||||
var d = new MonsterDetail { Wcid = wcid, Bound = true };
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (!r.TryGetProperty("wcid", out _)) return d;
|
||||
d.Name = r.GetProperty("name").GetString() ?? "";
|
||||
d.Hp = r.GetProperty("hp").GetInt32();
|
||||
d.HpSrc = r.GetProperty("hpSrc").GetString() ?? "";
|
||||
d.SecKill = r.GetProperty("secKill").GetDouble();
|
||||
d.HitRate = r.GetProperty("hitRate").GetDouble();
|
||||
d.WeakSrc = r.GetProperty("weakSrc").GetString() ?? "";
|
||||
foreach (JsonElement e in r.GetProperty("weak").EnumerateArray())
|
||||
d.Weak.Add((e.GetProperty("e").GetString() ?? "", e.GetProperty("m").GetDouble()));
|
||||
foreach (JsonElement e in r.GetProperty("casts").EnumerateArray())
|
||||
d.Casts.Add(new DetailCast
|
||||
{
|
||||
Weapon = e.GetProperty("weapon").GetString() ?? "", Elem = e.GetProperty("elem").GetString() ?? "",
|
||||
Tier = e.GetProperty("tier").GetInt32(), Hits = e.GetProperty("hits").GetInt32(),
|
||||
Avg = e.GetProperty("avg").GetDouble(), Crit = e.GetProperty("crit").GetDouble(),
|
||||
CritN = e.GetProperty("critN").GetInt32(), NonCrit = e.GetProperty("noncrit").GetDouble(),
|
||||
NonCritN = e.GetProperty("noncritN").GetInt32(), Casts = e.GetProperty("casts").GetDouble(),
|
||||
Kills = e.GetProperty("kills").GetInt32(),
|
||||
});
|
||||
foreach (JsonElement e in r.GetProperty("weapons").EnumerateArray())
|
||||
d.Weapons.Add((e.GetProperty("weapon").GetString() ?? "", e.GetProperty("hits").GetInt32(),
|
||||
e.GetProperty("misses").GetInt32(), e.GetProperty("sec").GetDouble(), e.GetProperty("secN").GetInt32()));
|
||||
foreach (JsonElement e in r.GetProperty("summons").EnumerateArray())
|
||||
d.Summons.Add((e.GetProperty("elem").GetString() ?? "", e.GetProperty("kills").GetInt32(), e.GetProperty("sec").GetDouble()));
|
||||
foreach (JsonElement e in r.GetProperty("taken").EnumerateArray())
|
||||
d.Taken.Add((e.GetProperty("elem").GetString() ?? "", e.GetProperty("hits").GetInt32(),
|
||||
e.GetProperty("avg").GetDouble(), e.GetProperty("max").GetDouble()));
|
||||
}
|
||||
catch { }
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginGetMonstersJson while a Monsters or Damage face is open (1 s, and after each write).</summary>
|
||||
internal sealed unsafe class MonsterRulesSource : UiSource<MonsterRulesSnapshot>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _get;
|
||||
private string? _lastJson;
|
||||
|
||||
public MonsterRulesSource() : base("MonsterRules", periodMs: 1000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
string? json = FetchJson();
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
MonstersPanel.Payload? parsed;
|
||||
try { parsed = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload); }
|
||||
catch { return; }
|
||||
if (parsed == null) return;
|
||||
_lastJson = json;
|
||||
Publish(new MonsterRulesSnapshot(json, parsed));
|
||||
}
|
||||
|
||||
/// <summary>The plugin's current rules JSON. Pump thread only (hub commands use it to edit the latest rules).</summary>
|
||||
internal string? FetchJson()
|
||||
{
|
||||
if (_get == null)
|
||||
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMonstersJson");
|
||||
if (_get == null) return null;
|
||||
IntPtr p = _get();
|
||||
return p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p);
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_get = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Damage and Monsters panels' mutating exports, on the pump thread. Any thread may call these.</summary>
|
||||
internal static unsafe class DamageCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<uint, int, void> _setHp;
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, int> _deleteRow;
|
||||
private static delegate* unmanaged[Cdecl]<uint, uint, void> _setWeapon, _setOffhand;
|
||||
private static delegate* unmanaged[Cdecl]<uint, void> _setDefaultWeapon;
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _setMonsters;
|
||||
private static delegate* unmanaged[Cdecl]<void> _clearStats;
|
||||
private static delegate* unmanaged[Cdecl]<uint, IntPtr, void> _setPet;
|
||||
private static delegate* unmanaged[Cdecl]<int, void> _setViewTier;
|
||||
|
||||
static DamageCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_setHp = null; _deleteRow = null; _setWeapon = null; _setOffhand = null; _setDefaultWeapon = null;
|
||||
_setMonsters = null; _clearStats = null; _setPet = null; _setViewTier = null;
|
||||
};
|
||||
}
|
||||
|
||||
private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name);
|
||||
|
||||
private static void Run(string label, Action action, bool rules = false)
|
||||
{
|
||||
UiDataHub.Post("Damage " + label, () =>
|
||||
{
|
||||
action();
|
||||
UiSources.Damage.RequestRefreshAfterPluginTick();
|
||||
if (rules) UiSources.MonsterRules.RequestRefreshAfterPluginTick();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Manual max HP; 0 returns the monster to auto.</summary>
|
||||
public static void SetHp(uint wcid, int hp) => Run("hp", () =>
|
||||
{
|
||||
if (_setHp == null) _setHp = (delegate* unmanaged[Cdecl]<uint, int, void>)Export("RynthPluginSetMonsterHp");
|
||||
if (_setHp != null) _setHp(wcid, hp);
|
||||
});
|
||||
|
||||
public static void DeleteRow(string key) => Run("delete row", () =>
|
||||
{
|
||||
if (_deleteRow == null) _deleteRow = (delegate* unmanaged[Cdecl]<IntPtr, int>)Export("RynthPluginDeleteMonsterRow");
|
||||
if (_deleteRow == null || key.Length == 0) return;
|
||||
IntPtr k = Marshal.StringToHGlobalAnsi(key);
|
||||
try { _deleteRow(k); }
|
||||
finally { Marshal.FreeHGlobal(k); }
|
||||
});
|
||||
|
||||
/// <summary>Per-monster weapon (0 = Auto, the learned best).</summary>
|
||||
public static void SetWeapon(uint wcid, uint weaponId) => Run("weapon", () =>
|
||||
{
|
||||
if (_setWeapon == null) _setWeapon = (delegate* unmanaged[Cdecl]<uint, uint, void>)Export("RynthPluginSetMonsterWeapon");
|
||||
if (_setWeapon != null) _setWeapon(wcid, weaponId);
|
||||
});
|
||||
|
||||
/// <summary>Per-monster offhand item (0 = none: the monster's rule, else the DEFAULT line, decides).</summary>
|
||||
public static void SetOffhand(uint wcid, uint offhandId) => Run("offhand", () =>
|
||||
{
|
||||
if (_setOffhand == null) _setOffhand = (delegate* unmanaged[Cdecl]<uint, uint, void>)Export("RynthPluginSetMonsterOffhand");
|
||||
if (_setOffhand != null) _setOffhand(wcid, offhandId);
|
||||
});
|
||||
|
||||
/// <summary>The Default line's weapon: every monster set to Default uses it (0 = learned best).</summary>
|
||||
public static void SetDefaultWeapon(uint weaponId) => Run("default weapon", () =>
|
||||
{
|
||||
if (_setDefaultWeapon == null) _setDefaultWeapon = (delegate* unmanaged[Cdecl]<uint, void>)Export("RynthPluginSetDefaultWeapon");
|
||||
if (_setDefaultWeapon != null) _setDefaultWeapon(weaponId);
|
||||
});
|
||||
|
||||
/// <summary>Pet for this monster: "" = Auto, "E:<element>", "I:<essence id>".</summary>
|
||||
public static void SetPet(uint wcid, string choice) => Run("pet", () =>
|
||||
{
|
||||
if (_setPet == null) _setPet = (delegate* unmanaged[Cdecl]<uint, IntPtr, void>)Export("RynthPluginSetMonsterPet");
|
||||
if (_setPet == null) return;
|
||||
IntPtr a = Marshal.StringToHGlobalAnsi(choice);
|
||||
try { _setPet(wcid, a); }
|
||||
finally { Marshal.FreeHGlobal(a); }
|
||||
UiSources.Damage.RefreshPetsSoon();
|
||||
});
|
||||
|
||||
/// <summary>The Aelrynth difficulty tier the panel shows: -1 follows the one where the player stands.</summary>
|
||||
public static void SetViewTier(int tier) => Run("view tier", () =>
|
||||
{
|
||||
if (_setViewTier == null) _setViewTier = (delegate* unmanaged[Cdecl]<int, void>)Export("RynthPluginSetDamageViewTier");
|
||||
if (_setViewTier != null) _setViewTier(tier);
|
||||
UiSources.MonsterDetail.RequestRefresh();
|
||||
});
|
||||
|
||||
/// <summary>Removes one monster from the Damage tab: its learned data and its settings.</summary>
|
||||
public static void RemoveMonster(uint wcid) => DeleteRow(wcid.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
/// <summary>Clears all learned damage statistics (names and manual settings are kept).</summary>
|
||||
public static void ClearStats() => Run("clear stats", () =>
|
||||
{
|
||||
if (_clearStats == null) _clearStats = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginClearMonsterStats");
|
||||
if (_clearStats != null) _clearStats();
|
||||
});
|
||||
|
||||
/// <summary>Writes the whole rules array, already serialized (the Monsters panel's save).</summary>
|
||||
public static void SetRulesJson(string json) => Run("rules", () =>
|
||||
{
|
||||
if (_setMonsters == null) _setMonsters = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSetMonstersJson");
|
||||
if (_setMonsters == null) return;
|
||||
IntPtr ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _setMonsters(ansi); }
|
||||
finally { Marshal.FreeHGlobal(ansi); }
|
||||
}, rules: true);
|
||||
|
||||
/// <summary>
|
||||
/// Edits <paramref name="name"/>'s exact-name rule on the plugin's latest
|
||||
/// rules (read fresh here, so an edit can't clobber one made elsewhere).
|
||||
/// A monster that inherits Default gets a copy of Default first, inserted
|
||||
/// right after it so the specific rule wins. "Default" edits Default itself.
|
||||
/// <paramref name="copyFrom"/>: the rule to copy instead of Default when the monster has no
|
||||
/// rule of its own yet (the name rule that covers it, so an edit doesn't swap its spells).
|
||||
/// </summary>
|
||||
public static void EditRule(string name, Action<MonstersPanel.Rule> edit, string? copyFrom = null) => Run("edit rule", () =>
|
||||
{
|
||||
MonstersPanel.Payload? rules = FreshRules();
|
||||
if (rules == null) return;
|
||||
edit(EnsureRule(rules, name, copyFrom));
|
||||
PushRules(rules.Rules);
|
||||
}, rules: true);
|
||||
|
||||
/// <summary>
|
||||
/// The first rule other than Default whose name <paramref name="monsterName"/> contains, in list
|
||||
/// order, the way RynthAi's targeting priority finds it (CombatManager.ScoreCandidate, which
|
||||
/// goes by name only: a match expression doesn't limit the priority bonus).
|
||||
/// </summary>
|
||||
public static MonstersPanel.Rule? CoveringRule(List<MonstersPanel.Rule> rules, string monsterName)
|
||||
{
|
||||
foreach (MonstersPanel.Rule r in rules)
|
||||
{
|
||||
if (IsDefault(r) || string.IsNullOrWhiteSpace(r.Name)) continue;
|
||||
if (monsterName.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Makes <paramref name="name"/> follow Default again (drops its exact-name rule).</summary>
|
||||
public static void ResetRule(string name) => Run("reset rule", () =>
|
||||
{
|
||||
MonstersPanel.Payload? rules = FreshRules();
|
||||
if (rules == null) return;
|
||||
int i = rules.Rules.FindIndex(r => !IsDefault(r) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (i < 0) return;
|
||||
rules.Rules.RemoveAt(i);
|
||||
PushRules(rules.Rules);
|
||||
}, rules: true);
|
||||
|
||||
private static bool IsDefault(MonstersPanel.Rule r) => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static MonstersPanel.Payload? FreshRules()
|
||||
{
|
||||
string? json = UiSources.MonsterRules.FetchJson();
|
||||
if (string.IsNullOrEmpty(json)) return null;
|
||||
MonstersPanel.Payload? p;
|
||||
try { p = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload); }
|
||||
catch { return null; }
|
||||
// Never write back an empty or unloaded array: it would wipe the rules (Default included).
|
||||
return p?.Rules == null || p.Rules.Count == 0 ? null : p;
|
||||
}
|
||||
|
||||
private static MonstersPanel.Rule EnsureRule(MonstersPanel.Payload rules, string name, string? copyFrom = null)
|
||||
{
|
||||
int defIdx = rules.Rules.FindIndex(IsDefault);
|
||||
if (name.Equals("Default", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (defIdx >= 0) return rules.Rules[defIdx];
|
||||
var created = new MonstersPanel.Rule { Name = "Default", UseBolt = true };
|
||||
rules.Rules.Add(created);
|
||||
return created;
|
||||
}
|
||||
MonstersPanel.Rule? existing = rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (existing != null) return existing;
|
||||
MonstersPanel.Rule s = defIdx >= 0 ? rules.Rules[defIdx] : new MonstersPanel.Rule { Name = "Default", UseBolt = true };
|
||||
MonstersPanel.Rule? from = string.IsNullOrEmpty(copyFrom) ? null
|
||||
: rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(copyFrom, StringComparison.OrdinalIgnoreCase));
|
||||
MonstersPanel.Rule clone = CopyOfDefault(from ?? s, name);
|
||||
if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; } // a name rule's own choices, kept
|
||||
rules.Rules.Insert(defIdx >= 0 ? defIdx + 1 : 0, clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A new rule named <paramref name="name"/> with Default's settings. Off hand and pet are
|
||||
/// left on "follow Default" (0 / PAuto) rather than copied, so a later change on the
|
||||
/// DEFAULT line still reaches it.
|
||||
/// </summary>
|
||||
private static MonstersPanel.Rule CopyOfDefault(MonstersPanel.Rule s, string name) => new()
|
||||
{
|
||||
Name = name, Category = s.Category,
|
||||
MatchExpression = "", // an exact-name rule matches by name, not by a (possibly false) expression
|
||||
Priority = s.Priority, DamageType = s.DamageType, WeaponId = s.WeaponId, OffhandId = 0,
|
||||
ExVuln = s.ExVuln, PetDamage = "PAuto",
|
||||
Fester = s.Fester, Broadside = s.Broadside, GravityWell = s.GravityWell,
|
||||
Imperil = s.Imperil, Yield = s.Yield, Vuln = s.Vuln,
|
||||
UseArc = s.UseArc, UseBolt = s.UseBolt, UseRing = s.UseRing, UseStreak = s.UseStreak, UseBlast = s.UseBlast,
|
||||
CustomDebuffs = s.CustomDebuffs,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Adds a name rule (the Damage panel's Name rules): it covers every monster whose name
|
||||
/// contains <paramref name="name"/>, and the expression too when one is given. Starts as a
|
||||
/// copy of Default and goes at the end of the list, so a monster's own rule (inserted
|
||||
/// after Default) still wins over it. An existing rule of that name only takes the expression.
|
||||
/// </summary>
|
||||
public static void AddRule(string name, string expression) => Run("add rule", () =>
|
||||
{
|
||||
name = name.Trim();
|
||||
expression = expression.Trim();
|
||||
if (name.Length == 0 || name.Equals("Default", StringComparison.OrdinalIgnoreCase)) return;
|
||||
MonstersPanel.Payload? rules = FreshRules();
|
||||
if (rules == null) return;
|
||||
MonstersPanel.Rule? existing = rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (existing != null)
|
||||
{
|
||||
if (expression.Length == 0) return;
|
||||
existing.MatchExpression = expression;
|
||||
}
|
||||
else
|
||||
{
|
||||
MonstersPanel.Rule def = rules.Rules.Find(IsDefault) ?? new MonstersPanel.Rule { Name = "Default", UseBolt = true };
|
||||
MonstersPanel.Rule added = CopyOfDefault(def, name);
|
||||
added.MatchExpression = expression;
|
||||
rules.Rules.Add(added);
|
||||
}
|
||||
PushRules(rules.Rules);
|
||||
}, rules: true);
|
||||
|
||||
private static void PushRules(List<MonstersPanel.Rule> rules)
|
||||
{
|
||||
if (rules.Count == 0) return; // never wipe the plugin's rules
|
||||
if (_setMonsters == null) _setMonsters = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSetMonstersJson");
|
||||
if (_setMonsters == null) return;
|
||||
string json = JsonSerializer.Serialize(new MonstersPanel.Payload { Rules = rules }, MonstersPanelJsonContext.Default.Payload);
|
||||
IntPtr ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _setMonsters(ansi); }
|
||||
finally { Marshal.FreeHGlobal(ansi); }
|
||||
}
|
||||
|
||||
// ── Drawer vocabulary (shared by both faces) ─────────────────────────
|
||||
|
||||
public static readonly (string Field, string Label, string Tip)[] DebuffDefs =
|
||||
{
|
||||
("Imperil", "Imperil", "Imperil (Gossamer Flesh / Imperil Other)"),
|
||||
("Vuln", "Vuln", "Vulnerability (element-matched)"),
|
||||
("Fester", "Fester", "Fester (Decrepitude's Grasp / Fester Other)"),
|
||||
("Yield", "Yield", "Yield (Magic Yield Other)"),
|
||||
("Broadside", "Broadside","Broadside (Missile Weapons Ineptitude)"),
|
||||
("GravityWell", "Gravity", "Gravity Well (Vulnerability Other)"),
|
||||
};
|
||||
|
||||
/// <summary>The Damage panel's one-letter debuff marks, in DebuffDefs order.</summary>
|
||||
public static readonly (string Field, char Letter)[] DebuffLetters =
|
||||
{
|
||||
("Imperil", 'I'), ("Vuln", 'V'), ("Fester", 'F'), ("Yield", 'Y'), ("Broadside", 'B'), ("GravityWell", 'G'),
|
||||
};
|
||||
|
||||
/// <summary>"IVF" for the debuffs a rule has on; X = an extra vuln, + = typed-in ones.</summary>
|
||||
public static string DebuffMarks(MonstersPanel.Rule r)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder(8);
|
||||
foreach (var (field, letter) in DebuffLetters) if (r.GetToggle(field)) sb.Append(letter);
|
||||
if (!string.IsNullOrEmpty(r.ExVuln) && !r.ExVuln.Equals("None", StringComparison.OrdinalIgnoreCase)) sb.Append('X');
|
||||
if (!string.IsNullOrWhiteSpace(r.CustomDebuffs)) sb.Append('+');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static readonly (string Field, string Label, string Tip)[] ShapeDefs =
|
||||
{
|
||||
("UseArc", "Arc", "Arc spells"),
|
||||
("UseBolt", "Bolt", "Bolt spells (default)"),
|
||||
("UseRing", "Ring", "Ring spells"),
|
||||
("UseStreak", "Streak", "Streak spells"),
|
||||
("UseBlast", "Blast", "Blast spells (Flame Blast, Frost Blast...): a spread of projectiles, from level III.\n" +
|
||||
"Used instead of Bolt when both are on (Arc and Streak come first). A character who knows\n" +
|
||||
"no blast of the element casts its Bolt."),
|
||||
};
|
||||
|
||||
public static readonly string[] ExVulnTypes =
|
||||
{ "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
|
||||
/// <summary>Rule.DamageType choices (Auto = from the monster's weaknesses).</summary>
|
||||
public static readonly string[] DamageTypes =
|
||||
{ "Auto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
|
||||
/// <summary>Rule.OffhandId as RynthAi reads it: 0 = follow the DEFAULT line, 1-4 a mode, anything else an item id.</summary>
|
||||
public static readonly string[] OffhandModeNames = { "Default", "Auto", "Shield", "Dual wield", "None" };
|
||||
|
||||
/// <summary>Rule.PetDamage choices; "PAuto" is shown as Auto.</summary>
|
||||
public static readonly string[] PetDamageTypes =
|
||||
{ "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
|
||||
/// <summary>Flips a debuff/shape toggle; a monster is never left with no spell shape (combat would refuse to cast).</summary>
|
||||
public static void FlipToggle(MonstersPanel.Rule rule, string field)
|
||||
{
|
||||
bool on = !rule.GetToggle(field);
|
||||
rule.SetToggle(field, on);
|
||||
bool shape = field is "UseArc" or "UseBolt" or "UseRing" or "UseStreak" or "UseBlast";
|
||||
if (shape && !on && !HasAnyShape(rule))
|
||||
rule.UseBolt = true;
|
||||
}
|
||||
|
||||
/// <summary>At least one spell shape is on (RynthAi refuses to attack with magic otherwise).</summary>
|
||||
public static bool HasAnyShape(MonstersPanel.Rule r) => r.UseArc || r.UseBolt || r.UseRing || r.UseStreak || r.UseBlast;
|
||||
|
||||
/// <summary>The shape RynthAi casts when no ring is due (RynthAi CombatManager.PickBaseShape): Arc, Streak, Blast, then Bolt.</summary>
|
||||
public static string BaseShapeName(MonstersPanel.Rule r)
|
||||
{
|
||||
if (r.UseArc) return "Arc";
|
||||
if (r.UseStreak) return "Streak";
|
||||
if (r.UseBlast) return "Blast";
|
||||
if (r.UseBolt || r.UseRing) return "Bolt";
|
||||
return "";
|
||||
}
|
||||
}
|
||||
107
src/RynthCore.Engine/UI/Data/ItemsData.cs
Normal file
107
src/RynthCore.Engine/UI/Data/ItemsData.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/ItemsData.cs
|
||||
// RynthAi's item rules (weapons with their element, consumables with their
|
||||
// type, mana stone tapping) for both Items faces.
|
||||
//
|
||||
// RynthPluginGetItemsJson frees its previous buffer on each call, so the hub
|
||||
// is its only caller (ItemsSource, 1 s). RynthPluginSetItemsJson and the two
|
||||
// Add Selected exports apply on the spot; they run on the pump (they read
|
||||
// and change plugin state the tick also uses) and refresh the snapshot.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>The items JSON and its parse. Parsed is shared: copy before changing (ParseCopy).</summary>
|
||||
internal sealed class ItemsSnapshot
|
||||
{
|
||||
public ItemsSnapshot(string json, ItemsPanel.Payload parsed) { Json = json; Parsed = parsed; }
|
||||
public string Json { get; }
|
||||
public ItemsPanel.Payload Parsed { get; }
|
||||
|
||||
public ItemsPanel.Payload ParseCopy() =>
|
||||
JsonSerializer.Deserialize(Json, ItemsPanelJsonContext.Default.Payload) ?? new ItemsPanel.Payload();
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginGetItemsJson while an Items face is open (1 s, and after each change).</summary>
|
||||
internal sealed unsafe class ItemsSource : UiSource<ItemsSnapshot>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _get;
|
||||
private string? _lastJson;
|
||||
|
||||
public ItemsSource() : base("Items", periodMs: 1000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_get == null)
|
||||
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetItemsJson");
|
||||
if (_get == null) return;
|
||||
IntPtr ptr = _get();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
ItemsPanel.Payload? parsed;
|
||||
try { parsed = JsonSerializer.Deserialize(json, ItemsPanelJsonContext.Default.Payload); }
|
||||
catch { return; }
|
||||
if (parsed == null) return;
|
||||
_lastJson = json;
|
||||
Publish(new ItemsSnapshot(json, parsed));
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_get = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
internal static unsafe class ItemsCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _set;
|
||||
private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addConsumable;
|
||||
|
||||
static ItemsCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addConsumable = null; };
|
||||
}
|
||||
|
||||
public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
public static readonly string[] ConsumableTypes = { "General", "Lockpick", "HealthKit", "HealthPotion", "ManaPotion", "StaminaPotion", "ManaStone", "Stamina", "Pet" };
|
||||
|
||||
private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name);
|
||||
|
||||
/// <summary>Saves the whole items payload, already serialized (a copy the caller no longer changes).</summary>
|
||||
public static void SetJson(string json) => UiDataHub.Post("Items save", () =>
|
||||
{
|
||||
if (_set == null) _set = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSetItemsJson");
|
||||
if (_set == null) return;
|
||||
IntPtr ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _set(ansi); }
|
||||
finally { Marshal.FreeHGlobal(ansi); }
|
||||
UiSources.Items.RequestRefresh();
|
||||
});
|
||||
|
||||
/// <summary>Adds the item selected in the inventory as a weapon.</summary>
|
||||
public static void AddSelectedWeapon() => UiDataHub.Post("Items add weapon", () =>
|
||||
{
|
||||
if (_addWeapon == null) _addWeapon = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedWeapon");
|
||||
if (_addWeapon != null) _addWeapon();
|
||||
UiSources.Items.RequestRefresh();
|
||||
});
|
||||
|
||||
/// <summary>Adds the item selected in the inventory as a consumable.</summary>
|
||||
public static void AddSelectedConsumable() => UiDataHub.Post("Items add consumable", () =>
|
||||
{
|
||||
if (_addConsumable == null) _addConsumable = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedConsumable");
|
||||
if (_addConsumable != null) _addConsumable();
|
||||
UiSources.Items.RequestRefresh();
|
||||
});
|
||||
|
||||
public static string Serialize(ItemsPanel.Payload payload) =>
|
||||
JsonSerializer.Serialize(payload, ItemsPanelJsonContext.Default.Payload);
|
||||
}
|
||||
345
src/RynthCore.Engine/UI/Data/LootEditData.cs
Normal file
345
src/RynthCore.Engine/UI/Data/LootEditData.cs
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/LootEditData.cs
|
||||
// RynthAi's loot profile editor state for the ImGui Loot Editor face
|
||||
// (docs/IMGUI_LOOT_EDITOR.md). RynthAi owns the data (LootSdk's
|
||||
// LootEditSession); these DTOs mirror RynthSuite's Shared/RynthCore.LootSdk/
|
||||
// Editing/LootEditWire.cs - keep the two in step. The engine does not
|
||||
// reference LootSdk.
|
||||
//
|
||||
// LootEditSource (pump thread, after the plugin tick) asks for the cheap
|
||||
// revision every second and fetches the rule list only when it moved; the
|
||||
// full rule the face has open comes from a second export, the pickers' names
|
||||
// from a third (once per plugin load). Strings are UTF-8 both ways.
|
||||
// LootEditCommands posts edits through the hub; the plugin applies them at
|
||||
// once, so the same hub step's poll already shows the result.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal sealed class LootEditStateDto
|
||||
{
|
||||
public long Revision { get; set; }
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string Format { get; set; } = string.Empty;
|
||||
public bool Exists { get; set; }
|
||||
public bool ReadOnly { get; set; }
|
||||
public string ReadOnlyReason { get; set; } = string.Empty;
|
||||
public bool Dirty { get; set; }
|
||||
public bool ChangedOnDisk { get; set; }
|
||||
public string InUsePath { get; set; } = string.Empty;
|
||||
public bool InUse { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
public bool MessageOk { get; set; } = true;
|
||||
public long MessageSeq { get; set; }
|
||||
public int Focus { get; set; } = -1;
|
||||
public List<LootEditFileDto> Files { get; set; } = new();
|
||||
public List<LootEditRowDto> Rules { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class LootEditFileDto
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string Display { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class LootEditRowDto
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public bool Enabled { get; set; } = true;
|
||||
public int Action { get; set; }
|
||||
public int KeepCount { get; set; }
|
||||
public string Summary { get; set; } = string.Empty;
|
||||
public int Conditions { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class LootEditRuleDto
|
||||
{
|
||||
public int Index { get; set; } = -1;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public bool Enabled { get; set; } = true;
|
||||
public int Action { get; set; } = 1;
|
||||
public int KeepCount { get; set; }
|
||||
public int Priority { get; set; }
|
||||
public string? CustomExpression { get; set; }
|
||||
public List<LootEditConditionDto> Conditions { get; set; } = new();
|
||||
|
||||
public LootEditRuleDto Clone()
|
||||
{
|
||||
var r = (LootEditRuleDto)MemberwiseClone();
|
||||
r.Conditions = new List<LootEditConditionDto>(Conditions.Count);
|
||||
foreach (LootEditConditionDto c in Conditions) r.Conditions.Add(c.Clone());
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>Same content (the rule view's "edited?" test).</summary>
|
||||
public bool SameAs(LootEditRuleDto o)
|
||||
{
|
||||
if (Name != o.Name || Enabled != o.Enabled || Action != o.Action || Priority != o.Priority
|
||||
|| CustomExpression != o.CustomExpression || Conditions.Count != o.Conditions.Count)
|
||||
return false;
|
||||
if (Action == LootEditVocabulary.KeepUpTo && KeepCount != o.KeepCount) return false;
|
||||
for (int i = 0; i < Conditions.Count; i++)
|
||||
if (!Conditions[i].SameAs(o.Conditions[i])) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class LootEditConditionDto
|
||||
{
|
||||
public int NodeType { get; set; }
|
||||
public string LengthCode { get; set; } = "0";
|
||||
public List<string> Lines { get; set; } = new();
|
||||
|
||||
public LootEditConditionDto Clone() => new() { NodeType = NodeType, LengthCode = LengthCode, Lines = new List<string>(Lines) };
|
||||
|
||||
public bool SameAs(LootEditConditionDto o)
|
||||
{
|
||||
if (NodeType != o.NodeType || LengthCode != o.LengthCode || Lines.Count != o.Lines.Count) return false;
|
||||
for (int i = 0; i < Lines.Count; i++) if (Lines[i] != o.Lines[i]) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class LootEditCmd
|
||||
{
|
||||
public string Op { get; set; } = string.Empty;
|
||||
public int Index { get; set; } = -1;
|
||||
public int To { get; set; } = -1;
|
||||
public string Value { get; set; } = string.Empty;
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string? Expect { get; set; }
|
||||
public bool Force { get; set; }
|
||||
public LootEditRuleDto? Rule { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class LootEditVocabDto
|
||||
{
|
||||
public List<LootEditNameDto> Actions { get; set; } = new();
|
||||
public List<LootEditNodeTypeDto> NodeTypes { get; set; } = new();
|
||||
public List<LootEditNameDto> ObjectClasses { get; set; } = new();
|
||||
public List<LootEditNameDto> LongKeys { get; set; } = new();
|
||||
public List<LootEditNameDto> DoubleKeys { get; set; } = new();
|
||||
public List<LootEditNameDto> StringKeys { get; set; } = new();
|
||||
public List<LootEditNameDto> Skills { get; set; } = new();
|
||||
/// <summary>Names for long keys' values (added 2026-10); empty from an older RynthAi (the value stays a text box).</summary>
|
||||
public List<LootEditValueTableDto> LongValueTables { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class LootEditNameDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class LootEditValueTableDto
|
||||
{
|
||||
public int Key { get; set; }
|
||||
public bool Flags { get; set; }
|
||||
public List<LootEditNameDto> Values { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class LootEditNodeTypeDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public int Lines { get; set; }
|
||||
public List<string> Labels { get; set; } = new();
|
||||
public List<string> Defaults { get; set; } = new();
|
||||
public string Editor { get; set; } = "raw";
|
||||
public string KeyTable { get; set; } = string.Empty;
|
||||
/// <summary>keyval "long": pick the value by name when the key has a LongValueTables entry (added 2026-10).</summary>
|
||||
public bool NamedValues { get; set; }
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(LootEditStateDto))]
|
||||
[JsonSerializable(typeof(LootEditRuleDto))]
|
||||
[JsonSerializable(typeof(LootEditCmd))]
|
||||
[JsonSerializable(typeof(LootEditVocabDto))]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false)]
|
||||
internal partial class LootEditJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>What the face reads. Immutable once published (the face clones what it edits).</summary>
|
||||
internal sealed class LootEditView
|
||||
{
|
||||
/// <summary>RynthAi isn't loaded, or is too old to have the loot editor exports.</summary>
|
||||
public bool Unavailable { get; init; }
|
||||
public LootEditStateDto? State { get; init; }
|
||||
/// <summary>The rule asked for with LootEditSource.WantRule, fetched at State's revision; null if none.</summary>
|
||||
public LootEditRuleDto? Rule { get; init; }
|
||||
public LootEditVocabDto? Vocab { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The loot editor's state while the face is open (revision each second, the list when it changes).</summary>
|
||||
internal sealed unsafe class LootEditSource : UiSource<LootEditView>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<int> _revision;
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getState, _getVocab;
|
||||
private delegate* unmanaged[Cdecl]<int, IntPtr> _getRule;
|
||||
private bool _bound;
|
||||
private int _lastRevision;
|
||||
private bool _haveState;
|
||||
private LootEditStateDto? _state;
|
||||
private LootEditVocabDto? _vocab;
|
||||
private LootEditRuleDto? _rule;
|
||||
private int _ruleIndex = -1, _ruleRevision;
|
||||
private int _wantRule = -1;
|
||||
|
||||
public LootEditSource() : base("LootEdit", periodMs: 1000) { }
|
||||
|
||||
/// <summary>The rule the face has open (-1: none). Any thread.</summary>
|
||||
public void WantRule(int index)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _wantRule, index) != index) RequestRefresh();
|
||||
}
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (!_bound)
|
||||
{
|
||||
_revision = (delegate* unmanaged[Cdecl]<int>)PluginExportBinder.Resolve("RynthAi", "RynthPluginLootEditRevision");
|
||||
_getState = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetLootEditJson");
|
||||
_getRule = (delegate* unmanaged[Cdecl]<int, IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetLootEditRuleJson");
|
||||
_getVocab = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetLootEditVocabJson");
|
||||
_bound = _revision != null && _getState != null && _getRule != null && _getVocab != null;
|
||||
if (!_bound)
|
||||
{
|
||||
if (Current == null || !Current.Value.Unavailable) Publish(new LootEditView { Unavailable = true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
bool changed = false;
|
||||
if (_vocab == null)
|
||||
{
|
||||
_vocab = Parse(_getVocab(), LootEditJsonContext.Default.LootEditVocabDto);
|
||||
changed |= _vocab != null;
|
||||
}
|
||||
|
||||
int revision = _revision();
|
||||
if (!_haveState || revision != _lastRevision)
|
||||
{
|
||||
LootEditStateDto? state = Parse(_getState(), LootEditJsonContext.Default.LootEditStateDto);
|
||||
if (state != null)
|
||||
{
|
||||
_state = state;
|
||||
_haveState = true;
|
||||
// The list call may have opened the profile (first look): the state's own revision is current.
|
||||
_lastRevision = unchecked((int)state.Revision);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
int want = Volatile.Read(ref _wantRule);
|
||||
if (want != _ruleIndex || (want >= 0 && _ruleRevision != _lastRevision))
|
||||
{
|
||||
_rule = want < 0 ? null : Parse(_getRule(want), LootEditJsonContext.Default.LootEditRuleDto);
|
||||
if (_rule != null && _rule.Index < 0) _rule = null;
|
||||
_ruleIndex = want;
|
||||
_ruleRevision = _lastRevision;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) Publish(new LootEditView { State = _state, Rule = _rule, Vocab = _vocab });
|
||||
}
|
||||
|
||||
private static T? Parse<T>(IntPtr utf8, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info) where T : class
|
||||
{
|
||||
if (utf8 == IntPtr.Zero) return null;
|
||||
string? json = Marshal.PtrToStringUTF8(utf8);
|
||||
if (string.IsNullOrEmpty(json)) return null;
|
||||
try { return JsonSerializer.Deserialize(json, info); }
|
||||
catch (JsonException ex)
|
||||
{
|
||||
RynthLog.UI($"LootEditSource: bad JSON from RynthAi ({typeof(T).Name}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_bound = false;
|
||||
_revision = null;
|
||||
_getState = null;
|
||||
_getVocab = null;
|
||||
_getRule = null;
|
||||
_haveState = false;
|
||||
_state = null;
|
||||
_vocab = null;
|
||||
_rule = null;
|
||||
_ruleIndex = -1;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginSendLootEditCommand on the pump thread. Any thread may call Send.</summary>
|
||||
internal static unsafe class LootEditCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _send;
|
||||
|
||||
static LootEditCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () => _send = null;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="cmd"/> (and its Rule) must not be changed after this call.</summary>
|
||||
public static void Send(LootEditCmd cmd)
|
||||
{
|
||||
UiDataHub.Post("LootEdit " + cmd.Op, () =>
|
||||
{
|
||||
if (_send == null)
|
||||
_send = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSendLootEditCommand");
|
||||
if (_send == null) return;
|
||||
string json = JsonSerializer.Serialize(cmd, LootEditJsonContext.Default.LootEditCmd);
|
||||
IntPtr utf8 = Marshal.StringToCoTaskMemUTF8(json);
|
||||
try { _send(utf8); }
|
||||
finally { Marshal.FreeCoTaskMem(utf8); }
|
||||
UiSources.LootEdit.RequestRefresh();
|
||||
});
|
||||
}
|
||||
|
||||
public static void Simple(string op, int index = -1, string value = "", string path = "", string? expect = null,
|
||||
bool force = false, int to = -1)
|
||||
=> Send(new LootEditCmd { Op = op, Index = index, Value = value, Path = path, Expect = expect, Force = force, To = to });
|
||||
}
|
||||
|
||||
/// <summary>Action codes and badge text shared by the face.</summary>
|
||||
internal static class LootEditVocabulary
|
||||
{
|
||||
public const int Keep = 1, Salvage = 2, Sell = 3, Read = 4, KeepUpTo = 10;
|
||||
|
||||
/// <summary>The action filter's chips: 0 = all.</summary>
|
||||
public static readonly int[] FilterActions = { 0, Keep, KeepUpTo, Salvage, Sell, Read };
|
||||
public static readonly string[] FilterLabels = { "All", "Keep", "Keep #", "Salvage", "Sell", "Read" };
|
||||
|
||||
public static string Badge(int action, int keepCount) => action switch
|
||||
{
|
||||
Keep => "KEEP",
|
||||
KeepUpTo => "KEEP " + keepCount.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
Salvage => "SALVAGE",
|
||||
Sell => "SELL",
|
||||
Read => "READ",
|
||||
_ => "?",
|
||||
};
|
||||
|
||||
/// <summary>Badge fill, ARGB (the external editor's colours).</summary>
|
||||
public static uint BadgeArgb(int action) => action switch
|
||||
{
|
||||
Keep => 0xFF1F6F3A,
|
||||
KeepUpTo => 0xFF196E6E,
|
||||
Salvage => 0xFFA35C15,
|
||||
Sell => 0xFF7A1F1F,
|
||||
Read => 0xFF1F497D,
|
||||
_ => 0xFF444444,
|
||||
};
|
||||
|
||||
public const int DisabledRule = 9999;
|
||||
}
|
||||
143
src/RynthCore.Engine/UI/Data/LuaData.cs
Normal file
143
src/RynthCore.Engine/UI/Data/LuaData.cs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/LuaData.cs
|
||||
// Lua scripts (state, script list, console, last loaded script) for both Lua
|
||||
// faces, from RynthLua (v2: several scripts, ScriptInfos / Selected / ...)
|
||||
// or an older RynthAi that still exports the single-script payload.
|
||||
//
|
||||
// RynthPluginGetLuaJson frees its previous buffer on each call, so the hub is
|
||||
// its only caller. RynthPluginSendLuaCommand queues: the plugin runs the
|
||||
// command on its next tick, so the refresh waits for that tick. UTF-8 both
|
||||
// ways (scripts keep non-ASCII text).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal sealed class LuaPayload
|
||||
{
|
||||
public bool Running { get; set; }
|
||||
public string ScriptName { get; set; } = string.Empty;
|
||||
public string Status { get; set; } = string.Empty;
|
||||
public List<string> Scripts { get; set; } = new();
|
||||
public string Console { get; set; } = string.Empty;
|
||||
public int ConsoleSeq { get; set; }
|
||||
/// <summary>Text of the last script loaded; an editor takes it when LoadSeq changes.</summary>
|
||||
public string LoadedText { get; set; } = string.Empty;
|
||||
public string LoadedName { get; set; } = string.Empty;
|
||||
public int LoadSeq { get; set; }
|
||||
|
||||
// ── RynthLua v2 (several scripts at once). Null from the old RynthAi
|
||||
// exports, which the faces then show the single-script way. ─────────
|
||||
/// <summary>Every script (files, plus running ones that aren't saved). Null = old single-script payload.</summary>
|
||||
public List<LuaScriptInfo>? ScriptInfos { get; set; }
|
||||
/// <summary>The script the panel shows: Console / Running / ScriptName / Status are its.</summary>
|
||||
public string? Selected { get; set; }
|
||||
public int RunningCount { get; set; }
|
||||
/// <summary>RynthAi's "RynthAi.Script" interface is there (macro, nav, meta features for scripts).</summary>
|
||||
public bool? RynthAi { get; set; }
|
||||
/// <summary>A character is logged in (per-character autostart needs one). Null from older plugins.</summary>
|
||||
public bool? LoggedIn { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One script in the v2 list (RynthLua's LuaScriptInfo).</summary>
|
||||
internal sealed class LuaScriptInfo
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public bool Running { get; set; }
|
||||
/// <summary>"none", "global" or "character" (for the logged-in character).</summary>
|
||||
public string Autostart { get; set; } = "none";
|
||||
/// <summary>From script.json; "(not saved)" for a running script with no file (the editor, /lua exec).</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
/// <summary>A folder script (index.lua); false for a single Name.lua.</summary>
|
||||
public bool IsFolder { get; set; }
|
||||
/// <summary>No file behind it (the editor, /lua exec): no autostart, restart or open.</summary>
|
||||
public bool Transient { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class LuaCmd
|
||||
{
|
||||
public string Cmd { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Code { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(LuaPayload))]
|
||||
[JsonSerializable(typeof(LuaCmd))]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false)]
|
||||
internal partial class LuaJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>RynthPluginGetLuaJson while a Lua face is open (500 ms, and after each command).</summary>
|
||||
internal sealed unsafe class LuaSource : UiSource<LuaPayload>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getLuaJson;
|
||||
private string? _lastJson;
|
||||
|
||||
public LuaSource() : base("Lua", periodMs: 500) { }
|
||||
|
||||
/// <summary>
|
||||
/// Lua is the RynthLua plugin since 2026-09-29; before that the same exports were
|
||||
/// RynthAi's. Ask RynthLua first, then an older RynthAi that still has them.
|
||||
/// </summary>
|
||||
internal static IntPtr ResolveLua(string export)
|
||||
{
|
||||
IntPtr p = PluginExportBinder.Resolve("RynthLua", export);
|
||||
return p != IntPtr.Zero ? p : PluginExportBinder.Resolve("RynthAi", export);
|
||||
}
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getLuaJson == null)
|
||||
_getLuaJson = (delegate* unmanaged[Cdecl]<IntPtr>)ResolveLua("RynthPluginGetLuaJson");
|
||||
if (_getLuaJson == null) return;
|
||||
IntPtr ptr = _getLuaJson();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
LuaPayload? parsed = JsonSerializer.Deserialize(json, LuaJsonContext.Default.LuaPayload);
|
||||
if (parsed != null) Publish(parsed);
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getLuaJson = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginSendLuaCommand on the pump thread: run / stop / load / save / delete / clearConsole,
|
||||
/// and RynthLua's select / start / restart / stopScript (Name), autostart (Code = none|global|character),
|
||||
/// execin (Name, Code).
|
||||
/// </summary>
|
||||
internal static unsafe class LuaCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _send;
|
||||
|
||||
static LuaCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () => _send = null;
|
||||
}
|
||||
|
||||
public static void Send(string cmd, string name = "", string code = "")
|
||||
{
|
||||
var command = new LuaCmd { Cmd = cmd, Name = name, Code = code };
|
||||
UiDataHub.Post("Lua " + cmd, () =>
|
||||
{
|
||||
if (_send == null)
|
||||
_send = (delegate* unmanaged[Cdecl]<IntPtr, void>)LuaSource.ResolveLua("RynthPluginSendLuaCommand");
|
||||
if (_send == null) return;
|
||||
string json = JsonSerializer.Serialize(command, LuaJsonContext.Default.LuaCmd);
|
||||
IntPtr utf8 = Marshal.StringToCoTaskMemUTF8(json);
|
||||
try { _send(utf8); }
|
||||
finally { Marshal.FreeCoTaskMem(utf8); }
|
||||
UiSources.Lua.RequestRefreshAfterPluginTick();
|
||||
});
|
||||
}
|
||||
}
|
||||
455
src/RynthCore.Engine/UI/Data/MetaData.cs
Normal file
455
src/RynthCore.Engine/UI/Data/MetaData.cs
Normal file
|
|
@ -0,0 +1,455 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/MetaData.cs
|
||||
// RynthAi's meta (rules, files, states, .af source) for both Meta faces
|
||||
// (docs/IMGUI_PARITY_PLAN.md §2.13).
|
||||
//
|
||||
// RynthPluginGetMetaJson frees its previous buffer on each call, so the hub
|
||||
// is its only caller. RynthPluginSendMetaCommand only queues: the plugin
|
||||
// applies the command on its next tick, so a command defers the refresh to
|
||||
// after that tick (UiSource.RequestRefreshAfterPluginTick) and the next
|
||||
// snapshot already shows the result.
|
||||
//
|
||||
// The faces edit their own copies (Clone) for instant feedback; the next
|
||||
// snapshot replaces the copy.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal sealed class MetaRuleDto
|
||||
{
|
||||
public string State { get; set; } = "Default";
|
||||
public int Condition { get; set; }
|
||||
public string ConditionData { get; set; } = string.Empty;
|
||||
public int Action { get; set; }
|
||||
public string ActionData { get; set; } = string.Empty;
|
||||
public List<MetaRuleDto> Children { get; set; } = new();
|
||||
public List<MetaRuleDto> ActionChildren { get; set; } = new();
|
||||
public bool Enabled { get; set; } = true;
|
||||
public long LastFiredMs { get; set; } = 99999;
|
||||
|
||||
public MetaRuleDto Clone()
|
||||
{
|
||||
var r = new MetaRuleDto
|
||||
{
|
||||
State = State, Condition = Condition, ConditionData = ConditionData,
|
||||
Action = Action, ActionData = ActionData, Enabled = Enabled, LastFiredMs = LastFiredMs,
|
||||
};
|
||||
foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone());
|
||||
foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone());
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class MetaFile
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string Display { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The plugin's answer to the last Source "Apply" (set_source). Seq counts applies.</summary>
|
||||
internal sealed class MetaApplyResult
|
||||
{
|
||||
public long Seq { get; set; }
|
||||
public bool Ok { get; set; }
|
||||
public string Text { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One Meta Manager rule ("when TRIGGER, load META"): the settings the panel edits (also the
|
||||
/// mm_add / mm_update wire format) plus the plugin's read-only status.
|
||||
/// </summary>
|
||||
internal sealed class ScheduleRuleDto
|
||||
{
|
||||
public bool Enabled { get; set; } = true;
|
||||
/// <summary>0 quest ready, 1 after N minutes on the meta, 2 every N minutes, 3 countdown.</summary>
|
||||
public int Trigger { get; set; }
|
||||
public string Quest { get; set; } = string.Empty;
|
||||
public double Minutes { get; set; } = 30;
|
||||
public string Meta { get; set; } = string.Empty;
|
||||
public string OnlyOnMeta { get; set; } = string.Empty;
|
||||
public bool Repeat { get; set; } = true;
|
||||
|
||||
// Status (the plugin's; not sent back).
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool Fired { get; set; }
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public int FireCount { get; set; }
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public long LastFiredMs { get; set; }
|
||||
/// <summary>When it is due (unix ms): 0 = not known / not running, -1 = never.</summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public long DueAtMs { get; set; }
|
||||
/// <summary>A few words ("waiting: combat", "error: ...") or empty when the due time says it all.</summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? State { get; set; }
|
||||
|
||||
internal ScheduleRuleDto MemberwiseCloneRule() => (ScheduleRuleDto)MemberwiseClone();
|
||||
|
||||
public ScheduleRuleDto CloneSettings() => new()
|
||||
{
|
||||
Enabled = Enabled, Trigger = Trigger, Quest = Quest, Minutes = Minutes,
|
||||
Meta = Meta, OnlyOnMeta = OnlyOnMeta, Repeat = Repeat,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's Meta Manager: its settings, poll state and rules (the "schedule" object).</summary>
|
||||
internal sealed class SchedulePayload
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
public int PollMinutes { get; set; } = 5;
|
||||
public int MaxWaitSeconds { get; set; } = 60;
|
||||
public int MinGapSeconds { get; set; } = 30;
|
||||
public bool AllowWhileStopped { get; set; }
|
||||
public bool Polling { get; set; }
|
||||
public bool ServerDisabled { get; set; }
|
||||
public bool HaveQuestList { get; set; }
|
||||
public int QuestCount { get; set; }
|
||||
public long LastPollMs { get; set; }
|
||||
public string LastSwitch { get; set; } = string.Empty;
|
||||
public long LastSwitchMs { get; set; }
|
||||
/// <summary>The rule that fires next (first due rule, or the one waiting to switch); -1 none.</summary>
|
||||
public int FirstMatch { get; set; } = -1;
|
||||
public List<ScheduleRuleDto> Rules { get; set; } = new();
|
||||
|
||||
/// <summary>A copy the face may change for instant feedback (the snapshot stays as published).</summary>
|
||||
public SchedulePayload Clone()
|
||||
{
|
||||
var p = (SchedulePayload)MemberwiseClone();
|
||||
p.Rules = new List<ScheduleRuleDto>(Rules.Count);
|
||||
foreach (ScheduleRuleDto r in Rules) p.Rules.Add(r.MemberwiseCloneRule());
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class MetaPayload
|
||||
{
|
||||
public bool EnableMeta { get; set; }
|
||||
public bool MetaDebug { get; set; }
|
||||
public string CurrentState { get; set; } = "Default";
|
||||
public string CurrentMetaPath { get; set; } = string.Empty;
|
||||
public List<MetaRuleDto> Rules { get; set; } = new();
|
||||
public List<MetaFile> Files { get; set; } = new();
|
||||
public List<string> States { get; set; } = new();
|
||||
public List<string> NavFiles { get; set; } = new();
|
||||
public List<string> EmbeddedNavKeys { get; set; } = new();
|
||||
public string SourceText { get; set; } = string.Empty;
|
||||
/// <summary>Null from a plugin that doesn't report apply results yet (it reports to chat).</summary>
|
||||
public MetaApplyResult? ApplyResult { get; set; }
|
||||
/// <summary>The Meta Manager; null from a RynthAi without it.</summary>
|
||||
public SchedulePayload? Schedule { get; set; }
|
||||
|
||||
/// <summary>Deep copy of the rules; the rest is shared (faces never change it).</summary>
|
||||
public MetaPayload Clone()
|
||||
{
|
||||
var p = (MetaPayload)MemberwiseClone();
|
||||
p.Rules = new List<MetaRuleDto>(Rules.Count);
|
||||
foreach (MetaRuleDto r in Rules) p.Rules.Add(r.Clone());
|
||||
p.Schedule = Schedule?.Clone();
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class MetaCmd
|
||||
{
|
||||
public string Op { get; set; } = string.Empty;
|
||||
public int Index { get; set; } = -1;
|
||||
public string Value { get; set; } = string.Empty;
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string Text { get; set; } = string.Empty;
|
||||
public MetaRuleDto? Rule { get; set; }
|
||||
/// <summary>mm_add / mm_update: the Meta Manager rule (settings only).</summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ScheduleRuleDto? ScheduleRule { get; set; }
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(MetaPayload))]
|
||||
[JsonSerializable(typeof(MetaCmd))]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
|
||||
internal partial class MetaJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>RynthPluginGetMetaJson while a Meta face is open (2 s, and after each command).</summary>
|
||||
internal sealed unsafe class MetaSource : UiSource<MetaPayload>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getMetaJson;
|
||||
private string? _lastJson;
|
||||
|
||||
public MetaSource() : base("Meta", periodMs: 2000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getMetaJson == null)
|
||||
_getMetaJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetMetaJson");
|
||||
if (_getMetaJson == null) return;
|
||||
IntPtr ptr = _getMetaJson();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
MetaPayload? parsed = JsonSerializer.Deserialize(json, MetaJsonContext.Default.MetaPayload);
|
||||
if (parsed != null) Publish(parsed);
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getMetaJson = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginSendMetaCommand on the pump thread. Any thread may call Send.</summary>
|
||||
internal static unsafe class MetaCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendMetaCommand;
|
||||
|
||||
static MetaCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () => _sendMetaCommand = null;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="cmd"/> (and its Rule) must not be changed after this call.</summary>
|
||||
public static void Send(MetaCmd cmd)
|
||||
{
|
||||
UiDataHub.Post("Meta " + cmd.Op, () =>
|
||||
{
|
||||
if (_sendMetaCommand == null)
|
||||
_sendMetaCommand = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSendMetaCommand");
|
||||
if (_sendMetaCommand == null) return;
|
||||
string json = JsonSerializer.Serialize(cmd, MetaJsonContext.Default.MetaCmd);
|
||||
IntPtr ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _sendMetaCommand(ansi); }
|
||||
finally { Marshal.FreeHGlobal(ansi); }
|
||||
UiSources.Meta.RequestRefreshAfterPluginTick();
|
||||
});
|
||||
}
|
||||
|
||||
public static void Simple(string op, int index = -1, string value = "", string path = "")
|
||||
=> Send(new MetaCmd { Op = op, Index = index, Value = value, Path = path });
|
||||
}
|
||||
|
||||
/// <summary>Names, hints and .af keywords shared by the Meta faces (mirror RynthSuite's MetaSchema).</summary>
|
||||
internal static class MetaVocabulary
|
||||
{
|
||||
public const string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
|
||||
public static readonly string[] ConditionNames =
|
||||
{
|
||||
"Never", "Always", "All", "Any", "Chat Message", "Pack Slots <=",
|
||||
"Seconds in State >=", "Character Death", "Any Vendor Open",
|
||||
"Vendor Closed", "Inventory Item Count <=", "Inventory Item Count >=",
|
||||
"Monster Name Count Within Dist", "Monster Priority Count Within Dist",
|
||||
"Need To Buff", "No Monsters Within Dist", "Landblock ==",
|
||||
"Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not",
|
||||
"Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=",
|
||||
"Burden % >=", "Dist Any Route PT >=", "Expression",
|
||||
"Chat Message Capture", "Navroute Empty",
|
||||
"Main Health <=", "Main Health % >=", "Main Mana <=", "Main Mana % >=",
|
||||
"Main Stam <=", "Vitae % >=",
|
||||
};
|
||||
|
||||
public static readonly string[] ConditionHints =
|
||||
{
|
||||
"", "", "(sub-conditions)", "(sub-conditions)", "Regex pattern", "Min slots (e.g. 5)",
|
||||
"Seconds (e.g. 10)", "", "", "",
|
||||
"name,count (e.g. Mana Stone,5)", "name,count (e.g. Mana Stone,5)",
|
||||
"name regex,distance,count", "count,distance (e.g. 1,20)",
|
||||
"", "Distance (e.g. 20)", "Hex (e.g. A9B40000)", "Hex (e.g. A9B40000)",
|
||||
"", "", "(sub-conditions)", "Seconds (e.g. 10)",
|
||||
"spellId,seconds (e.g. 2293,30)", "spellId,seconds (e.g. 2293,30)",
|
||||
"Percentage (e.g. 250)", "Distance (e.g. 10)", "Expression",
|
||||
"Regex pattern", "",
|
||||
"", "", "", "", "", "Vitae % (e.g. 5)",
|
||||
};
|
||||
|
||||
public static readonly string[] ActionNames =
|
||||
{
|
||||
"None", "Chat Command", "Set Meta State", "Embedded Nav Route", "All",
|
||||
"Call Meta State", "Return From Call", "Expression Action", "Chat Expression",
|
||||
"Set Watchdog", "Clear Watchdog", "Get RA Option", "Set RA Option",
|
||||
"Create View", "Destroy View", "Destroy All Views",
|
||||
};
|
||||
|
||||
public static readonly string[] ActionHints =
|
||||
{
|
||||
"", "e.g. /say hello", "State name", "Route name", "(sub-actions)",
|
||||
"State name", "", "Expression", "Expression",
|
||||
"state;meters;seconds (e.g. Default;10;60)", "", "Option name", "OptionName;Value",
|
||||
"", "", "",
|
||||
};
|
||||
|
||||
// ── .af source keywords (keyword form, as written in the file) ──────────
|
||||
public static readonly string[] StructKeywords = { "STATE", "IF", "DO", "NAV" };
|
||||
|
||||
public static readonly string[] ConditionKeywords =
|
||||
{
|
||||
"Never", "Always", "All", "Any", "ChatMatch", "MainSlotsLE",
|
||||
"SecsInStateGE", "Death", "VendorOpen", "VendorClosed",
|
||||
"ItemCountLE", "ItemCountGE",
|
||||
"MobsInDist_Name", "MobsInDist_Priority",
|
||||
"NeedToBuff", "NoMobsInDist", "BlockE", "CellE",
|
||||
"IntoPortal", "ExitPortal", "Not",
|
||||
"PSecsInStateGE", "SecsOnSpellGE", "SecsOnSpellLE",
|
||||
"BuPercentGE", "DistToRteGE", "Expr",
|
||||
"ChatCapture", "NavEmpty",
|
||||
"MainHealthLE", "MainHealthPHE", "MainManaLE", "MainManaPHE",
|
||||
"MainStamLE", "VitaePHE",
|
||||
};
|
||||
|
||||
public static readonly string[] ActionKeywords =
|
||||
{
|
||||
"None", "Chat", "SetState", "EmbedNav", "DoAll",
|
||||
"CallState", "Return", "DoExpr", "ChatExpr",
|
||||
"SetWatchdog", "ClearWatchdog", "GetOpt", "SetOpt",
|
||||
"CreateView", "DestroyView", "DestroyAllViews",
|
||||
};
|
||||
|
||||
/// <summary>All=2, Any=3, Not=20 hold sub-conditions.</summary>
|
||||
public static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20;
|
||||
|
||||
/// <summary>All (DoAll) = 4 holds sub-actions.</summary>
|
||||
public static bool IsAllAction(int idx) => idx == 4;
|
||||
|
||||
/// <summary>Sub-conditions nest this deep (Not/All/Any under Not/All/Any).</summary>
|
||||
public const int MaxSubConditionDepth = 4;
|
||||
|
||||
public static string ConditionName(int idx) =>
|
||||
idx >= 0 && idx < ConditionNames.Length ? ConditionNames[idx] : $"Cond({idx})";
|
||||
|
||||
public static string ActionName(int idx) =>
|
||||
idx >= 0 && idx < ActionNames.Length ? ActionNames[idx] : $"Act({idx})";
|
||||
|
||||
public static string ConditionHint(int idx) =>
|
||||
idx >= 0 && idx < ConditionHints.Length ? ConditionHints[idx] : "";
|
||||
|
||||
public static string ActionHint(int idx) =>
|
||||
idx >= 0 && idx < ActionHints.Length ? ActionHints[idx] : "";
|
||||
|
||||
/// <summary>One condition as text, nested ones included: "Not No Monsters Within Dist: 5", "Any(Chat Message: …, Navroute Empty)".</summary>
|
||||
public static string CondText(MetaRuleDto c, int depth = 0)
|
||||
{
|
||||
string name = ConditionName(c.Condition);
|
||||
if (IsCompositeCondition(c.Condition) && c.Children.Count > 0 && depth < MaxSubConditionDepth)
|
||||
{
|
||||
if (c.Condition == 20) return $"Not {CondText(c.Children[0], depth + 1)}";
|
||||
var sb = new StringBuilder(name).Append('(');
|
||||
for (int i = 0; i < c.Children.Count; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(", ");
|
||||
sb.Append(CondText(c.Children[i], depth + 1));
|
||||
}
|
||||
return sb.Append(')').ToString();
|
||||
}
|
||||
return string.IsNullOrEmpty(c.ConditionData) ? name : $"{name}: {c.ConditionData}";
|
||||
}
|
||||
|
||||
public static string ActText(MetaRuleDto a)
|
||||
{
|
||||
string name = ActionName(a.Action);
|
||||
return string.IsNullOrEmpty(a.ActionData) ? name : $"{name}: {a.ActionData}";
|
||||
}
|
||||
|
||||
/// <summary>A rule row's condition column: composite ones show the first child and "(+N)".</summary>
|
||||
public static string RowConditionText(MetaRuleDto rule)
|
||||
{
|
||||
string name = ConditionName(rule.Condition);
|
||||
if (IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
|
||||
{
|
||||
string first = CondText(rule.Children[0]);
|
||||
return rule.Children.Count > 1 ? $"{name}: {first} (+{rule.Children.Count - 1})" : $"{name}: {first}";
|
||||
}
|
||||
return string.IsNullOrEmpty(rule.ConditionData) ? name : $"{name}: {rule.ConditionData}";
|
||||
}
|
||||
|
||||
/// <summary>A rule row's action column: DoAll shows the first sub-action and "(+N)".</summary>
|
||||
public static string RowActionText(MetaRuleDto rule)
|
||||
{
|
||||
string name = ActionName(rule.Action);
|
||||
if (IsAllAction(rule.Action) && rule.ActionChildren.Count > 0)
|
||||
{
|
||||
string first = ActText(rule.ActionChildren[0]);
|
||||
return rule.ActionChildren.Count > 1 ? $"{name}: {first} (+{rule.ActionChildren.Count - 1})" : $"{name}: {first}";
|
||||
}
|
||||
return string.IsNullOrEmpty(rule.ActionData) ? name : $"{name}: {rule.ActionData}";
|
||||
}
|
||||
|
||||
/// <summary>The state picker's list: the meta's states, with Default first if it is missing.</summary>
|
||||
public static string[] StatePicks(MetaPayload d)
|
||||
{
|
||||
var states = new List<string>(d.States);
|
||||
if (!states.Contains("Default")) states.Insert(0, "Default");
|
||||
return states.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Embedded Nav's route picker: nav files, then "[emb] key" for embedded routes.</summary>
|
||||
public static string[] RoutePicks(MetaPayload d)
|
||||
{
|
||||
var routes = new List<string>();
|
||||
foreach (string n in d.NavFiles) if (n != "None") routes.Add(n);
|
||||
foreach (string k in d.EmbeddedNavKeys) if (!routes.Contains(k)) routes.Add($"[emb] {k}");
|
||||
return routes.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Nav names for source completion (nav files and embedded keys, no duplicates).</summary>
|
||||
public static IReadOnlyList<string> CompletionNavs(MetaPayload d)
|
||||
{
|
||||
var combined = new List<string>(d.NavFiles.Count + d.EmbeddedNavKeys.Count);
|
||||
combined.AddRange(d.NavFiles);
|
||||
foreach (string n in d.EmbeddedNavKeys) if (!combined.Contains(n)) combined.Add(n);
|
||||
return combined;
|
||||
}
|
||||
|
||||
/// <summary>The file picker's current entry; "-- None --" without a loaded file.</summary>
|
||||
public static string CurrentFileDisplay(MetaPayload d)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(d.CurrentMetaPath) && d.Files.Count > 1)
|
||||
foreach (MetaFile f in d.Files)
|
||||
if (string.Equals(f.Path, d.CurrentMetaPath, StringComparison.OrdinalIgnoreCase))
|
||||
return f.Display;
|
||||
return "-- None --";
|
||||
}
|
||||
|
||||
public static int CurrentFileIndex(MetaPayload d)
|
||||
{
|
||||
if (string.IsNullOrEmpty(d.CurrentMetaPath)) return 0;
|
||||
return d.Files.FindIndex(f => string.Equals(f.Path, d.CurrentMetaPath, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rule list grouped by state (sorted by state name), each group's rules
|
||||
/// in list order: the order the plugin's move_up/move_down swap within.
|
||||
/// </summary>
|
||||
public static List<(string State, List<int> Rules)> GroupByState(List<MetaRuleDto> rules)
|
||||
{
|
||||
var byState = new Dictionary<string, List<int>>();
|
||||
var order = new List<string>();
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
{
|
||||
string s = rules[i].State;
|
||||
if (!byState.TryGetValue(s, out List<int>? list))
|
||||
{
|
||||
byState[s] = list = new List<int>();
|
||||
order.Add(s);
|
||||
}
|
||||
list.Add(i);
|
||||
}
|
||||
order.Sort(StringComparer.CurrentCulture);
|
||||
var groups = new List<(string, List<int>)>(order.Count);
|
||||
foreach (string s in order) groups.Add((s, byState[s]));
|
||||
return groups;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rule index move_up (-1) or move_down (+1) swaps <paramref name="index"/>
|
||||
/// with: the neighbour in the same state, or -1 at the group's end.
|
||||
/// </summary>
|
||||
public static int SwapPartner(List<MetaRuleDto> rules, int index, int direction)
|
||||
{
|
||||
if (index < 0 || index >= rules.Count) return -1;
|
||||
string state = rules[index].State;
|
||||
for (int j = index + direction; j >= 0 && j < rules.Count; j += direction)
|
||||
if (string.Equals(rules[j].State, state, StringComparison.Ordinal))
|
||||
return j;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
139
src/RynthCore.Engine/UI/Data/NavData.cs
Normal file
139
src/RynthCore.Engine/UI/Data/NavData.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/NavData.cs
|
||||
// RynthAi's nav route (active nav, status, route type, waypoints, nav files)
|
||||
// for both Nav faces.
|
||||
//
|
||||
// RynthPluginGetNavJson frees its previous buffer on each call, so the hub is
|
||||
// its only caller (NavSource, 1 s). Commands go through
|
||||
// RynthAiCommands.SendNavCommand on the pump; the plugin applies them on the
|
||||
// spot, so the next poll (requested right after) shows the result. ANSI JSON.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal sealed class NavPoint
|
||||
{
|
||||
public int Idx { get; set; }
|
||||
public string Type { get; set; } = string.Empty;
|
||||
public string Desc { get; set; } = string.Empty;
|
||||
public string Text { get; set; } = string.Empty; // Chat points: the command (editable)
|
||||
public double NS { get; set; }
|
||||
public double EW { get; set; }
|
||||
public double Z { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class NavPayload
|
||||
{
|
||||
public string ActiveNavName { get; set; } = string.Empty;
|
||||
public string NavStatusLine { get; set; } = string.Empty;
|
||||
public bool NavIsStuck { get; set; }
|
||||
public bool MacroRunning { get; set; }
|
||||
public bool NavigationEnabled { get; set; }
|
||||
public int RouteType { get; set; }
|
||||
public int ActiveNavIndex { get; set; }
|
||||
public List<string> NavFiles { get; set; } = new();
|
||||
public List<NavPoint> Points { get; set; } = new();
|
||||
|
||||
/// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary>
|
||||
public NavPayload Clone()
|
||||
{
|
||||
var c = (NavPayload)MemberwiseClone();
|
||||
c.Points = new List<NavPoint>(Points);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class NavCmd
|
||||
{
|
||||
public string Cmd { get; set; } = string.Empty;
|
||||
public int SpellId { get; set; }
|
||||
public int Index { get; set; }
|
||||
public int RouteType { get; set; }
|
||||
public int AddMode { get; set; }
|
||||
public int InsertAt { get; set; } = -1;
|
||||
public string NavName { get; set; } = string.Empty;
|
||||
public string Text { get; set; } = string.Empty; // addChat
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(NavPayload))]
|
||||
[JsonSerializable(typeof(NavCmd))]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
|
||||
internal partial class NavJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>RynthPluginGetNavJson while a Nav face is open (1 s, and after each command).</summary>
|
||||
internal sealed unsafe class NavSource : UiSource<NavPayload>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getNavJson;
|
||||
private string? _lastJson;
|
||||
|
||||
public NavSource() : base("Nav", periodMs: 1000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getNavJson == null)
|
||||
_getNavJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetNavJson");
|
||||
if (_getNavJson == null) return;
|
||||
IntPtr ptr = _getNavJson();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
NavPayload? parsed = JsonSerializer.Deserialize(json, NavJsonContext.Default.NavPayload);
|
||||
if (parsed != null) Publish(parsed);
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getNavJson = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Nav panel commands and vocabulary, shared by both faces.</summary>
|
||||
internal static class NavCommands
|
||||
{
|
||||
public static void Send(NavCmd cmd) =>
|
||||
RynthAiCommands.SendNavCommand(JsonSerializer.Serialize(cmd, NavJsonContext.Default.NavCmd));
|
||||
|
||||
public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" };
|
||||
public static readonly string[] AddModes = { "End", "Above", "Below" };
|
||||
|
||||
/// <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 };
|
||||
|
||||
/// <summary>The plugin's RouteType for a route picker index (Once = 4).</summary>
|
||||
public static int RouteTypeFor(int index) => index switch { 1 => 1, 2 => 2, 3 => 3, _ => 4 };
|
||||
|
||||
public static readonly int[] RecallIds =
|
||||
{
|
||||
48, 2645, 2647,
|
||||
1635, 1636,
|
||||
157, 158, 1637,
|
||||
2648, 2649, 2650,
|
||||
2931, 2023, 2041, 2358, 2813, 2941, 2943,
|
||||
3865, 3929, 3930, 4084, 4198, 4213,
|
||||
4907, 4908, 4909,
|
||||
5175, 5330, 5541, 6150, 6321, 6322,
|
||||
};
|
||||
|
||||
public static readonly string[] RecallLabels = BuildRecallLabels();
|
||||
|
||||
private static string[] BuildRecallLabels()
|
||||
{
|
||||
var labels = new string[RecallIds.Length];
|
||||
for (int i = 0; i < labels.Length; i++) labels[i] = $"Spell {RecallIds[i]} ({RecallIds[i]})";
|
||||
return labels;
|
||||
}
|
||||
|
||||
/// <summary>"[3] Recall ..." or "[3] Point (12.34N, 56.78E, 12.3)".</summary>
|
||||
public static string PointText(NavPoint pt, int i) =>
|
||||
!string.IsNullOrEmpty(pt.Desc)
|
||||
? $"[{i}] {pt.Desc}"
|
||||
: $"[{i}] {pt.Type} ({pt.NS:F2}N, {pt.EW:F2}E, {pt.Z:F1})";
|
||||
}
|
||||
135
src/RynthCore.Engine/UI/Data/PanelSources.cs
Normal file
135
src/RynthCore.Engine/UI/Data/PanelSources.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/PanelSources.cs
|
||||
// Hub sources for the P1 panels (Log, Tracker). Both faces of a panel read
|
||||
// the same snapshot; display strings are formatted here, on the pump thread,
|
||||
// so drawing allocates nothing.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>The engine's recent-log ring with the sequence number of its last line.</summary>
|
||||
internal sealed record LogSnapshot(string[] Lines, long LastSeq)
|
||||
{
|
||||
/// <summary>Sequence number of Lines[0].</summary>
|
||||
public long FirstSeq => LastSeq - Lines.Length + 1;
|
||||
}
|
||||
|
||||
internal sealed class LogSource : UiSource<LogSnapshot>
|
||||
{
|
||||
public LogSource() : base("Log", periodMs: 1000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (Current is { } cur && cur.Value.LastSeq == EntryPoint.RecentLogSeq) return;
|
||||
string[] lines = EntryPoint.GetRecentLogLines(out long lastSeq);
|
||||
Publish(new LogSnapshot(lines, lastSeq));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Tracker panel's rows, formatted: nine, plus two Radiance rows on Aelrynth once earned.</summary>
|
||||
internal sealed record TrackerSnapshot(string[] Labels, string[] Values)
|
||||
{
|
||||
public static readonly string[] DefaultLabels = { "Session", "XP/hr", "Lum/hr", "Kls/hr", "XP", "Lum", "Kills", "XP/kl", "Deaths" };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthTracker's RynthTrackerGetSnapshotJson (single consumer: it frees the
|
||||
/// previous buffer on each call, so only the hub may call it).
|
||||
/// </summary>
|
||||
internal sealed unsafe class TrackerSource : UiSource<TrackerSnapshot>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getSnapshotJson;
|
||||
private delegate* unmanaged[Cdecl]<void> _reset;
|
||||
private string? _lastJson;
|
||||
|
||||
public TrackerSource() : base("Tracker", periodMs: 500) { }
|
||||
|
||||
/// <summary>Resets the session counters (RynthTrackerReset). Any thread; runs on the pump.</summary>
|
||||
public void RequestReset()
|
||||
{
|
||||
UiDataHub.Post("Tracker reset", () =>
|
||||
{
|
||||
Bind();
|
||||
if (_reset != null) _reset();
|
||||
RequestRefresh();
|
||||
});
|
||||
}
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
Bind();
|
||||
if (_getSnapshotJson == null) return;
|
||||
|
||||
IntPtr ptr = _getSnapshotJson();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); // copy now: freed on the next call
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement r = doc.RootElement;
|
||||
double Num(string key) => r.TryGetProperty(key, out JsonElement v) && v.TryGetDouble(out double d) ? d : 0;
|
||||
|
||||
CultureInfo ic = CultureInfo.InvariantCulture;
|
||||
// At the level cap the server adds no experience, so the XP rows say so instead of 0.
|
||||
bool maxLevel = Num("ml") > 0;
|
||||
string Xp(long v) => maxLevel ? "max level" : FormatNum(v);
|
||||
var labels = new List<string> { "Session", "XP/hr", "Lum/hr" };
|
||||
var values = new List<string> { FormatTime(Num("ss")), Xp((long)Num("xh")), FormatNum((long)Num("lh")) };
|
||||
// Radiance (Aelrynth's Bank session total): rows only once some has been earned.
|
||||
long rad = (long)Num("rt");
|
||||
if (rad > 0) { labels.Add("Rad/hr"); values.Add(FormatNum((long)Num("rh"))); }
|
||||
labels.AddRange(new[] { "Kls/hr", "XP", "Lum" });
|
||||
values.AddRange(new[] { Num("kh").ToString("F1", ic), Xp((long)Num("xt")), FormatNum((long)Num("lt")) });
|
||||
if (rad > 0) { labels.Add("Rad"); values.Add(FormatNum(rad)); }
|
||||
labels.AddRange(new[] { "Kills", "XP/kl", "Deaths" });
|
||||
values.AddRange(new[] { ((long)Num("kt")).ToString(ic), Xp((long)Num("xk")), ((long)Num("dt")).ToString(ic) });
|
||||
Publish(new TrackerSnapshot(labels.ToArray(), values.ToArray()));
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getSnapshotJson = null;
|
||||
_reset = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
|
||||
private void Bind()
|
||||
{
|
||||
if (_getSnapshotJson == null)
|
||||
_getSnapshotJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthTracker", "RynthTrackerGetSnapshotJson");
|
||||
if (_reset == null)
|
||||
_reset = (delegate* unmanaged[Cdecl]<void>)PluginExportBinder.Resolve("RynthTracker", "RynthTrackerReset");
|
||||
}
|
||||
|
||||
// Same formatting as the Avalonia Tracker had.
|
||||
private static string FormatTime(double totalSeconds)
|
||||
{
|
||||
var ts = TimeSpan.FromSeconds(totalSeconds);
|
||||
return ts.TotalHours >= 1
|
||||
? $"{(int)ts.TotalHours}:{ts.Minutes:D2}:{ts.Seconds:D2}"
|
||||
: $"{ts.Minutes}:{ts.Seconds:D2}";
|
||||
}
|
||||
|
||||
private static string FormatNum(long value)
|
||||
{
|
||||
if (value == 0) return "0";
|
||||
bool neg = value < 0;
|
||||
string s = (neg ? -value : value).ToString(CultureInfo.InvariantCulture);
|
||||
var sb = new StringBuilder(s.Length + s.Length / 3);
|
||||
int offset = s.Length % 3;
|
||||
for (int i = 0; i < s.Length; i++)
|
||||
{
|
||||
if (i > 0 && (i - offset) % 3 == 0) sb.Append(',');
|
||||
sb.Append(s[i]);
|
||||
}
|
||||
return neg ? "-" + sb : sb.ToString();
|
||||
}
|
||||
}
|
||||
48
src/RynthCore.Engine/UI/Data/PluginExportBinder.cs
Normal file
48
src/RynthCore.Engine/UI/Data/PluginExportBinder.cs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/PluginExportBinder.cs
|
||||
// Resolves a plugin's C export for a UiSource. Pump thread only.
|
||||
//
|
||||
// Plugin exports are [UnmanagedCallersOnly] cdecl functions; sources call
|
||||
// them through `delegate* unmanaged[Cdecl]<...>` pointers (no delegate
|
||||
// marshalling). Resolving on AC's render thread is refused and logged: plugin
|
||||
// code on AC's thread is the fail-fast crash class (4b70ef1).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal static class PluginExportBinder
|
||||
{
|
||||
// Managed plugins (CoreCLR engine) answer from their export map; see ManagedPlugins.
|
||||
private static IntPtr GetProcAddress(IntPtr hModule, string procName) => Plugins.ManagedPlugins.GetProcAddress(hModule, procName);
|
||||
|
||||
private static int _acThreadRefusals;
|
||||
|
||||
/// <summary>
|
||||
/// The export <paramref name="exportName"/> of the first loaded plugin whose
|
||||
/// display name contains <paramref name="pluginNamePart"/>, or zero when the
|
||||
/// plugin isn't loaded (or doesn't have it).
|
||||
/// </summary>
|
||||
public static IntPtr Resolve(string pluginNamePart, string exportName)
|
||||
{
|
||||
if (MainThreadGuard.IsOnMainThread())
|
||||
{
|
||||
if (_acThreadRefusals++ < 5)
|
||||
RynthLog.UI($"PluginExportBinder: refused to bind {exportName} on AC's thread; plugin exports are called from UiDataHub only.");
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
// PluginManager mutates its list on this (pump) thread, so reading it here is race-free.
|
||||
foreach (LoadedPlugin plugin in PluginManager.Plugins)
|
||||
{
|
||||
if (plugin.ModuleHandle == IntPtr.Zero) continue;
|
||||
if (!plugin.DisplayName.Contains(pluginNamePart, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
return GetProcAddress(plugin.ModuleHandle, exportName);
|
||||
}
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
185
src/RynthCore.Engine/UI/Data/RadarData.cs
Normal file
185
src/RynthCore.Engine/UI/Data/RadarData.cs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/RadarData.cs
|
||||
// The radar's data (docs/IMGUI_PARITY_PLAN.md §2.2), shared by its Avalonia
|
||||
// face (UI/Panels/RadarPanel.cs) and ImGui face (ImGui/Panels/RadarFace.cs).
|
||||
//
|
||||
// RadarSource calls RynthPluginGetRadarSnapshot at 33 ms on the pump thread
|
||||
// while a radar face is open. Walls/fills only travel when the landblock
|
||||
// changes (the export skips them when told the cached MapVersion), so the
|
||||
// source keeps that cache - the logic moved here from the Avalonia panel's
|
||||
// timer - and publishes a RadarView with per-layer lookups and the current
|
||||
// layer's wall "visited" flags precomputed, so drawing does no dictionary
|
||||
// or point-in-strip work per frame.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
// The snapshot DTOs (RadarSnapshot, RadarMarker, ...) are in RadarSnapshotJson.cs.
|
||||
|
||||
/// <summary>What either radar face draws: the live snapshot plus cached geometry and lookups.</summary>
|
||||
internal sealed class RadarView
|
||||
{
|
||||
public required RadarSnapshot Live { get; init; }
|
||||
public required List<RadarWallLayer> Walls { get; init; }
|
||||
public required List<RadarFillLayer> Fills { get; init; }
|
||||
|
||||
/// <summary>Index into Live.LayerZs of the layer the player is on (-1: none).</summary>
|
||||
public required int CurrentLayer { get; init; }
|
||||
/// <summary>Per layer index (parallel to Live.LayerZs): its walls / fill strips / visited strips, or null.</summary>
|
||||
public required float[]?[] WallsByLayer { get; init; }
|
||||
public required float[]?[] FillsByLayer { get; init; }
|
||||
public required float[]?[] VisitedByLayer { get; init; }
|
||||
/// <summary>Per wall of the current layer: true when its midpoint is in a visited strip (drawn blue).</summary>
|
||||
public required bool[]? CurrentWallVisited { get; init; }
|
||||
/// <summary>"LB AABB Z 12.3" indoors, "33.1N 44.8E Z 12.3" outdoors.</summary>
|
||||
public required string CoordText { get; init; }
|
||||
}
|
||||
|
||||
internal sealed unsafe class RadarSource : UiSource<RadarView>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<uint, IntPtr> _getRadarSnapshot;
|
||||
private uint _cachedMapVersion;
|
||||
private List<RadarWallLayer> _cachedWalls = new();
|
||||
private List<RadarFillLayer> _cachedFills = new();
|
||||
private string? _lastJson;
|
||||
|
||||
// Wall "visited" flags depend only on the current layer's walls and visited
|
||||
// strips; recompute when either changes, not on every pose update.
|
||||
private float[]? _visitedKeyStrips;
|
||||
private float[]? _visitedKeyWalls;
|
||||
private bool[]? _visitedFlags;
|
||||
|
||||
public RadarSource() : base("Radar", periodMs: 33) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getRadarSnapshot == null)
|
||||
_getRadarSnapshot = (delegate* unmanaged[Cdecl]<uint, IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetRadarSnapshot");
|
||||
if (_getRadarSnapshot == null) return;
|
||||
|
||||
IntPtr ptr = _getRadarSnapshot(_cachedMapVersion);
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); // copy now: freed on the next call
|
||||
if (string.IsNullOrEmpty(json) || json == "{}" || json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
|
||||
RadarSnapshot? fresh = RadarSnapshot.Parse(json);
|
||||
if (fresh == null) return;
|
||||
|
||||
if (fresh.GeometryIncluded)
|
||||
{
|
||||
_cachedMapVersion = fresh.MapVersion;
|
||||
_cachedWalls = fresh.Walls;
|
||||
_cachedFills = fresh.Fills;
|
||||
}
|
||||
else if (fresh.MapVersion != _cachedMapVersion && fresh.MapVersion != 0 && !fresh.IsIndoor)
|
||||
{
|
||||
// Outdoor landblocks carry no geometry but still bump the version:
|
||||
// drop stale walls so they don't bleed through indoor -> outdoor.
|
||||
_cachedMapVersion = fresh.MapVersion;
|
||||
_cachedWalls = new List<RadarWallLayer>();
|
||||
_cachedFills = new List<RadarFillLayer>();
|
||||
}
|
||||
|
||||
// First polls after login can land before raycast is ready: an indoor
|
||||
// snapshot with no walls. Re-ask with version 0 until geometry arrives,
|
||||
// or the plugin keeps skipping it and the radar stays blank.
|
||||
if (fresh.IsIndoor && _cachedWalls.Count == 0)
|
||||
_cachedMapVersion = 0;
|
||||
|
||||
Publish(BuildView(fresh));
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getRadarSnapshot = null;
|
||||
_cachedMapVersion = 0;
|
||||
_cachedWalls = new List<RadarWallLayer>();
|
||||
_cachedFills = new List<RadarFillLayer>();
|
||||
_lastJson = null;
|
||||
_visitedKeyStrips = _visitedKeyWalls = null;
|
||||
_visitedFlags = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
|
||||
private RadarView BuildView(RadarSnapshot live)
|
||||
{
|
||||
List<float> layers = live.LayerZs;
|
||||
int cur = -1;
|
||||
if (layers.Count > 0)
|
||||
{
|
||||
cur = 0;
|
||||
float best = MathF.Abs(layers[0] - live.CurrentLayerZ);
|
||||
for (int i = 1; i < layers.Count; i++)
|
||||
{
|
||||
float d = MathF.Abs(layers[i] - live.CurrentLayerZ);
|
||||
if (d < best) { best = d; cur = i; }
|
||||
}
|
||||
}
|
||||
|
||||
var walls = new float[]?[layers.Count];
|
||||
var fills = new float[]?[layers.Count];
|
||||
var visited = new float[]?[layers.Count];
|
||||
for (int i = 0; i < layers.Count; i++)
|
||||
{
|
||||
float z = layers[i];
|
||||
foreach (RadarWallLayer w in _cachedWalls) if (w.Z == z) { walls[i] = w.Segments; break; }
|
||||
foreach (RadarFillLayer f in _cachedFills) if (f.Z == z) { fills[i] = f.Strips; break; }
|
||||
foreach (RadarVisitedLayer v in live.Visited) if (v.Z == z) { visited[i] = v.Strips; break; }
|
||||
}
|
||||
|
||||
bool[]? wallVisited = null;
|
||||
if (cur >= 0 && walls[cur] is float[] curWalls && visited[cur] is float[] curVisited)
|
||||
{
|
||||
if (!ReferenceEquals(curWalls, _visitedKeyWalls) || _visitedKeyStrips == null
|
||||
|| !curVisited.AsSpan().SequenceEqual(_visitedKeyStrips))
|
||||
{
|
||||
_visitedKeyWalls = curWalls;
|
||||
_visitedKeyStrips = curVisited;
|
||||
_visitedFlags = new bool[curWalls.Length / 6];
|
||||
for (int w = 0; w < _visitedFlags.Length; w++)
|
||||
{
|
||||
float mx = (curWalls[w * 6] + curWalls[w * 6 + 2]) * 0.5f;
|
||||
float my = (curWalls[w * 6 + 1] + curWalls[w * 6 + 3]) * 0.5f;
|
||||
_visitedFlags[w] = PointInStrips(mx, my, curVisited);
|
||||
}
|
||||
}
|
||||
wallVisited = _visitedFlags;
|
||||
}
|
||||
|
||||
return new RadarView
|
||||
{
|
||||
Live = live,
|
||||
Walls = _cachedWalls,
|
||||
Fills = _cachedFills,
|
||||
CurrentLayer = cur,
|
||||
WallsByLayer = walls,
|
||||
FillsByLayer = fills,
|
||||
VisitedByLayer = visited,
|
||||
CurrentWallVisited = wallVisited,
|
||||
CoordText = FormatCoords(live),
|
||||
};
|
||||
}
|
||||
|
||||
private static bool PointInStrips(float x, float y, float[] strips)
|
||||
{
|
||||
for (int i = 0; i + 3 < strips.Length; i += 4)
|
||||
if (x >= strips[i] && x <= strips[i + 2] && y >= strips[i + 1] && y <= strips[i + 3])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Same readout as the ImGui-era and Avalonia radars.
|
||||
private static string FormatCoords(RadarSnapshot s)
|
||||
{
|
||||
RadarPlayer p = s.Player;
|
||||
if (s.IsIndoor)
|
||||
return $"LB {p.Landblock:X4} Z {p.Z:0.0}";
|
||||
if (!double.IsNaN(s.Ns) && !double.IsNaN(s.Ew))
|
||||
return $"{Math.Abs(s.Ns):0.0}{(s.Ns >= 0 ? "N" : "S")} {Math.Abs(s.Ew):0.0}{(s.Ew >= 0 ? "E" : "W")} Z {p.Z:0.0}";
|
||||
return $"Z {p.Z:0.0}";
|
||||
}
|
||||
}
|
||||
136
src/RynthCore.Engine/UI/Data/RadarSnapshotJson.cs
Normal file
136
src/RynthCore.Engine/UI/Data/RadarSnapshotJson.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/RadarSnapshotJson.cs
|
||||
// The radar snapshot's JSON shape, as RynthAi's RynthPluginGetRadarSnapshot
|
||||
// writes it (mirrors RynthCore.Plugin.RynthAi.LegacyUi.RadarSnapshotPayload).
|
||||
// Split out of RadarData.cs so it stays self-contained: RynthSuite's
|
||||
// RynthAiHostTests links this file to check the plugin's output parses here.
|
||||
//
|
||||
// Compatibility: System.Text.Json skips properties it doesn't know (the
|
||||
// default, never set to Disallow here), and a missing property keeps its
|
||||
// default. So fields can be added on either side: an older engine ignores
|
||||
// a newer plugin's extra fields, and a newer engine reads an older plugin's
|
||||
// snapshot with the new fields at their defaults (marker Id = 0: unknown).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal sealed class RadarSnapshot
|
||||
{
|
||||
[JsonPropertyName("mapVersion")] public uint MapVersion { get; set; }
|
||||
[JsonPropertyName("geometryIncluded")] public bool GeometryIncluded { get; set; }
|
||||
[JsonPropertyName("isIndoor")] public bool IsIndoor { get; set; }
|
||||
[JsonPropertyName("player")] public RadarPlayer Player { get; set; } = new();
|
||||
[JsonPropertyName("ns")] public double Ns { get; set; } = double.NaN;
|
||||
[JsonPropertyName("ew")] public double Ew { get; set; } = double.NaN;
|
||||
[JsonPropertyName("layerZs")] public List<float> LayerZs { get; set; } = new();
|
||||
[JsonPropertyName("currentLayerZ")] public float CurrentLayerZ { get; set; }
|
||||
[JsonPropertyName("walls")] public List<RadarWallLayer> Walls { get; set; } = new();
|
||||
[JsonPropertyName("fills")] public List<RadarFillLayer> Fills { get; set; } = new();
|
||||
[JsonPropertyName("visited")] public List<RadarVisitedLayer> Visited { get; set; } = new();
|
||||
[JsonPropertyName("markers")] public List<RadarMarker> Markers { get; set; } = new();
|
||||
|
||||
/// <summary>Parses one RynthPluginGetRadarSnapshot reply; null for "null". Throws on malformed JSON.</summary>
|
||||
public static RadarSnapshot? Parse(string json) =>
|
||||
JsonSerializer.Deserialize(json, RadarJsonContext.Default.RadarSnapshot);
|
||||
}
|
||||
|
||||
internal sealed class RadarPlayer
|
||||
{
|
||||
[JsonPropertyName("cellId")] public uint CellId { get; set; }
|
||||
[JsonPropertyName("landblock")] public uint Landblock { get; set; }
|
||||
[JsonPropertyName("x")] public float X { get; set; }
|
||||
[JsonPropertyName("y")] public float Y { get; set; }
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("worldX")] public float WorldX { get; set; }
|
||||
[JsonPropertyName("worldY")] public float WorldY { get; set; }
|
||||
[JsonPropertyName("heading")] public float Heading { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class RadarWallLayer
|
||||
{
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
/// <summary>6 floats per wall: ax, ay, bx, by, cellX, cellY.</summary>
|
||||
[JsonPropertyName("segments")] public float[] Segments { get; set; } = Array.Empty<float>();
|
||||
}
|
||||
|
||||
internal sealed class RadarFillLayer
|
||||
{
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
/// <summary>5 floats per strip: x0, y0, x1, y1, type (0 flat, 1 slope up, 2 slope down).</summary>
|
||||
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
|
||||
}
|
||||
|
||||
internal sealed class RadarVisitedLayer
|
||||
{
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
/// <summary>4 floats per strip: x0, y0, x1, y1.</summary>
|
||||
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marker kinds (RadarMarker.Kind). 0-3 are the original four; 4 and up were added
|
||||
/// 2026-10-04 and are only sent by RynthAi builds from then on, so a newer engine
|
||||
/// reading an older RynthAi simply never sees them. An older engine drops kinds it
|
||||
/// doesn't know (its ShowKind returns false). Numbers never change meaning: new kinds
|
||||
/// are appended.
|
||||
/// </summary>
|
||||
internal static class RadarKind
|
||||
{
|
||||
public const byte Monster = 0;
|
||||
public const byte Npc = 1;
|
||||
public const byte Portal = 2;
|
||||
public const byte Door = 3;
|
||||
public const byte Player = 4; // another player
|
||||
public const byte Fellow = 5; // a player in your fellowship
|
||||
public const byte Pet = 6; // your own combat pet / summon
|
||||
public const byte Vendor = 7;
|
||||
public const byte Corpse = 8; // someone else's corpse (or not yet identified)
|
||||
public const byte OwnCorpse = 9; // a corpse you may loot: your kill, a fellow's kill, or your own
|
||||
public const byte Lifestone = 10;
|
||||
public const byte GroundItem = 11; // an item lying on the ground
|
||||
public const int Count = 12;
|
||||
|
||||
/// <summary>A creature (has health, can be hovered for a health reading).</summary>
|
||||
public static bool IsCreature(byte kind) =>
|
||||
kind is Monster or Npc or Player or Fellow or Pet or Vendor;
|
||||
|
||||
/// <summary>Singular name, for the hover tooltip when a marker has no label.</summary>
|
||||
public static string Name(byte kind) => kind switch
|
||||
{
|
||||
Monster => "Monster",
|
||||
Npc => "NPC",
|
||||
Portal => "Portal",
|
||||
Door => "Door",
|
||||
Player => "Player",
|
||||
Fellow => "Fellow",
|
||||
Pet => "Your pet",
|
||||
Vendor => "Vendor",
|
||||
Corpse => "Corpse",
|
||||
OwnCorpse => "Your corpse",
|
||||
Lifestone => "Lifestone",
|
||||
GroundItem => "Item",
|
||||
_ => "Object",
|
||||
};
|
||||
}
|
||||
|
||||
internal sealed class RadarMarker
|
||||
{
|
||||
/// <summary>A <see cref="RadarKind"/>: 0 monster, 1 NPC, 2 portal, 3 door, 4 player, 5 fellow,
|
||||
/// 6 your pet, 7 vendor, 8 corpse, 9 your corpse, 10 lifestone, 11 item on the ground.</summary>
|
||||
[JsonPropertyName("kind")] public byte Kind { get; set; }
|
||||
[JsonPropertyName("x")] public float X { get; set; }
|
||||
[JsonPropertyName("y")] public float Y { get; set; }
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("label")] public string? Label { get; set; }
|
||||
/// <summary>The object's id (RynthAi 2026-10-01 and later); 0 from older RynthAi builds.</summary>
|
||||
[JsonPropertyName("id")] public uint Id { get; set; }
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(RadarSnapshot))]
|
||||
[JsonSourceGenerationOptions(WriteIndented = false)]
|
||||
internal partial class RadarJsonContext : JsonSerializerContext { }
|
||||
391
src/RynthCore.Engine/UI/Data/RynthAiData.cs
Normal file
391
src/RynthCore.Engine/UI/Data/RynthAiData.cs
Normal file
|
|
@ -0,0 +1,391 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/RynthAiData.cs
|
||||
// The RynthAi dashboard's data (docs/IMGUI_PARITY_PLAN.md §2.1), shared by
|
||||
// its Avalonia face (UI/Panels/RynthAiPanel.cs) and ImGui face.
|
||||
//
|
||||
// RynthAiSource polls RynthPluginGetSnapshotJson at 33 ms on the pump thread
|
||||
// (the same thread as RynthAi's tick, so no race with the plugin) and
|
||||
// publishes a RynthAiView: the raw fields plus every display string, sticky
|
||||
// vitals applied. RynthAiCommands runs the dashboard's mutating exports on
|
||||
// the pump too. PatrolSource fetches the patrol flyout's data on demand.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>RynthPluginGetSnapshotJson's fields the dashboard uses.</summary>
|
||||
internal sealed class RynthAiSnapshot
|
||||
{
|
||||
[JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; }
|
||||
[JsonPropertyName("currentState")] public string CurrentState { get; set; } = string.Empty;
|
||||
[JsonPropertyName("botAction")] public string BotAction { get; set; } = string.Empty;
|
||||
[JsonPropertyName("selectedProfile")] public string SelectedProfile { get; set; } = "Default";
|
||||
[JsonPropertyName("profiles")] public string[] Profiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("navProfiles")] public string[] NavProfiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("lootProfiles")] public string[] LootProfiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("currentLootPath")] public string CurrentLootPath { get; set; } = string.Empty;
|
||||
// Set while a vendor is open: the AutoVendor profile it would use (may not exist yet).
|
||||
[JsonPropertyName("vendorProfilePath")] public string VendorProfilePath { get; set; } = string.Empty;
|
||||
[JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; }
|
||||
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; }
|
||||
[JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; }
|
||||
[JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; }
|
||||
[JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; }
|
||||
[JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; }
|
||||
[JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; }
|
||||
[JsonPropertyName("lootingEnabled")] public bool LootingEnabled { get; set; }
|
||||
[JsonPropertyName("metaEnabled")] public bool MetaEnabled { get; set; }
|
||||
[JsonPropertyName("currentTargetId")] public uint CurrentTargetId { get; set; }
|
||||
[JsonPropertyName("targetLabel")] public string TargetLabel { get; set; } = "NO TARGET";
|
||||
[JsonPropertyName("targetHealthPercent")] public float TargetHealthPercent { get; set; }
|
||||
[JsonPropertyName("targetHealthDisplay")] public string TargetHealthDisplay { get; set; } = "0";
|
||||
[JsonPropertyName("targetHealth")] public uint TargetHealth { get; set; }
|
||||
[JsonPropertyName("targetMaxHealth")] public uint TargetMaxHealth { get; set; }
|
||||
[JsonPropertyName("targetStamina")] public uint TargetStamina { get; set; }
|
||||
[JsonPropertyName("targetMaxStamina")] public uint TargetMaxStamina { get; set; }
|
||||
[JsonPropertyName("targetMana")] public uint TargetMana { get; set; }
|
||||
[JsonPropertyName("targetMaxMana")] public uint TargetMaxMana { get; set; }
|
||||
[JsonPropertyName("playerHealth")] public uint PlayerHealth { get; set; }
|
||||
[JsonPropertyName("playerMaxHealth")] public uint PlayerMaxHealth { get; set; }
|
||||
[JsonPropertyName("playerStamina")] public uint PlayerStamina { get; set; }
|
||||
[JsonPropertyName("playerMaxStamina")] public uint PlayerMaxStamina { get; set; }
|
||||
[JsonPropertyName("playerMana")] public uint PlayerMana { get; set; }
|
||||
[JsonPropertyName("playerMaxMana")] public uint PlayerMaxMana { get; set; }
|
||||
[JsonPropertyName("showTargetStaminaMana")] public bool ShowTargetStaminaMana { get; set; }
|
||||
[JsonPropertyName("isLocked")] public bool IsLocked { get; set; }
|
||||
[JsonPropertyName("isMinimized")] public bool IsMinimized { get; set; }
|
||||
[JsonPropertyName("bgOpacity")] public float BgOpacity { get; set; } = 0.95f;
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(RynthAiSnapshot))]
|
||||
internal sealed partial class RynthAiSnapshotJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>A vital bar: fill fraction and its text ("HP: 92% (314/341)").</summary>
|
||||
internal readonly record struct VitalView(float Fraction, string Text);
|
||||
|
||||
/// <summary>Everything either dashboard face draws, formatted on the pump thread.</summary>
|
||||
internal sealed class RynthAiView
|
||||
{
|
||||
public required RynthAiSnapshot Raw { get; init; }
|
||||
public required string Version { get; init; }
|
||||
public required string MetaStateText { get; init; }
|
||||
public required string BotActivityText { get; init; }
|
||||
public required string ProfileText { get; init; }
|
||||
public required string NavText { get; init; }
|
||||
public required string LootText { get; init; }
|
||||
public required string MetaText { get; init; }
|
||||
public required string TargetHeadline { get; init; }
|
||||
public required int TargetSegmentsLit { get; init; }
|
||||
public required bool ShowTargetSubBars { get; init; }
|
||||
public required VitalView TargetStamina { get; init; }
|
||||
public required VitalView TargetMana { get; init; }
|
||||
public required VitalView Health { get; init; }
|
||||
public required VitalView Stamina { get; init; }
|
||||
public required VitalView Mana { get; init; }
|
||||
/// <summary>Combat box background alpha 0-255 (the header +/- chips; floor 10%).</summary>
|
||||
public required byte PanelAlpha { get; init; }
|
||||
|
||||
public const int Segments = 15;
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginGetSnapshotJson at 33 ms while a dashboard face is open.</summary>
|
||||
internal sealed unsafe class RynthAiSource : UiSource<RynthAiView>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getSnapshotJson;
|
||||
private string? _lastJson;
|
||||
private string _version = "";
|
||||
private long _versionTicks;
|
||||
|
||||
public RynthAiSource() : base("RynthAi", periodMs: 33) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getSnapshotJson == null)
|
||||
_getSnapshotJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetSnapshotJson");
|
||||
if (_getSnapshotJson == null) return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
bool versionChanged = false;
|
||||
if (now - _versionTicks > 2000)
|
||||
{
|
||||
_versionTicks = now;
|
||||
string ver = "";
|
||||
foreach (LoadedPlugin p in PluginManager.Plugins)
|
||||
if (p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)) { ver = p.VersionString; break; }
|
||||
versionChanged = ver != _version;
|
||||
_version = ver;
|
||||
}
|
||||
|
||||
IntPtr ptr = _getSnapshotJson();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrWhiteSpace(json)) return;
|
||||
if (json == _lastJson && !versionChanged) return;
|
||||
_lastJson = json;
|
||||
|
||||
RynthAiSnapshot snap = JsonSerializer.Deserialize(json, RynthAiSnapshotJsonContext.Default.RynthAiSnapshot) ?? new RynthAiSnapshot();
|
||||
Publish(BuildView(snap, _version));
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getSnapshotJson = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
|
||||
private static RynthAiView BuildView(RynthAiSnapshot s, string version)
|
||||
{
|
||||
StickyVitals.Update(s);
|
||||
string label = string.IsNullOrWhiteSpace(s.TargetLabel) ? "NO TARGET" : s.TargetLabel.ToUpperInvariant();
|
||||
bool showSub = s.ShowTargetStaminaMana && s.TargetMaxStamina > 0;
|
||||
float pct = Math.Clamp(s.TargetHealthPercent, 0f, 1f);
|
||||
int lit = 0;
|
||||
for (int i = 0; i < RynthAiView.Segments; i++)
|
||||
if ((float)i / RynthAiView.Segments <= pct) lit++;
|
||||
|
||||
return new RynthAiView
|
||||
{
|
||||
Raw = s,
|
||||
Version = version,
|
||||
MetaStateText = string.IsNullOrWhiteSpace(s.CurrentState) ? "Default" : s.CurrentState,
|
||||
BotActivityText = string.IsNullOrWhiteSpace(s.BotAction) || s.BotAction == "Default" ? "Idle" : s.BotAction,
|
||||
ProfileText = Truncate(s.SelectedProfile, 16),
|
||||
NavText = Truncate(s.CurrentNavName, 16),
|
||||
LootText = Truncate(s.CurrentLootName, 16),
|
||||
MetaText = Truncate(s.CurrentMetaName, 16),
|
||||
TargetHeadline = Truncate(label, 32),
|
||||
TargetSegmentsLit = lit,
|
||||
ShowTargetSubBars = showSub,
|
||||
TargetStamina = showSub ? Compact("ST", s.TargetStamina, s.TargetMaxStamina) : default,
|
||||
TargetMana = showSub ? Compact("MN", s.TargetMana, s.TargetMaxMana) : default,
|
||||
Health = Vital("HP", StickyVitals.Hp, StickyVitals.MaxHp),
|
||||
Stamina = Vital("ST", StickyVitals.St, StickyVitals.MaxSt),
|
||||
Mana = Vital("MN", StickyVitals.Mn, StickyVitals.MaxMn),
|
||||
PanelAlpha = (byte)Math.Clamp(Math.Round(s.BgOpacity * 255f), 25.5, 255),
|
||||
};
|
||||
}
|
||||
|
||||
private static VitalView Vital(string label, uint v, uint max)
|
||||
{
|
||||
float pct = max == 0 ? 0 : Math.Clamp((float)v / max, 0, 1);
|
||||
string display = max == 0 ? (v == 0 ? "--/--" : $"{v}/--") : $"{v}/{max}";
|
||||
return new VitalView(pct, $"{label}: {(int)(pct * 100)}% ({display})");
|
||||
}
|
||||
|
||||
private static VitalView Compact(string prefix, uint v, uint max) =>
|
||||
new(max == 0 ? 0 : Math.Clamp((float)v / max, 0, 1), $"{prefix} {v}/{max}");
|
||||
|
||||
internal static string Truncate(string? value, int max)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value)) return "None";
|
||||
return value.Length > max ? value[..(max - 1)] + "…" : value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Last-known good vitals, so a hot reload (when the plugin's vital cache is
|
||||
/// cold for a tick or two) doesn't show 0/0. Persisted to vitals.cache, at
|
||||
/// most once a second, off the pump thread.
|
||||
/// </summary>
|
||||
internal static class StickyVitals
|
||||
{
|
||||
public static uint Hp, MaxHp, St, MaxSt, Mn, MaxMn;
|
||||
private static bool _loaded;
|
||||
private static long _lastSaved;
|
||||
|
||||
private static string CachePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "vitals.cache");
|
||||
|
||||
/// <summary>Pump thread (RynthAiSource.Poll).</summary>
|
||||
public static void Update(RynthAiSnapshot s)
|
||||
{
|
||||
if (!_loaded) Load();
|
||||
bool changed = false;
|
||||
if (s.PlayerMaxHealth != 0) { changed |= Hp != s.PlayerHealth || MaxHp != s.PlayerMaxHealth; Hp = s.PlayerHealth; MaxHp = s.PlayerMaxHealth; }
|
||||
if (s.PlayerMaxStamina != 0) { changed |= St != s.PlayerStamina || MaxSt != s.PlayerMaxStamina; St = s.PlayerStamina; MaxSt = s.PlayerMaxStamina; }
|
||||
if (s.PlayerMaxMana != 0) { changed |= Mn != s.PlayerMana || MaxMn != s.PlayerMaxMana; Mn = s.PlayerMana; MaxMn = s.PlayerMaxMana; }
|
||||
if (!changed) return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _lastSaved < 1000) return;
|
||||
_lastSaved = now;
|
||||
string text = $"{Hp},{MaxHp},{St},{MaxSt},{Mn},{MaxMn}";
|
||||
UiBackgroundWriter.Enqueue("vitals cache", () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = CachePath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, text);
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void Load()
|
||||
{
|
||||
_loaded = true;
|
||||
try
|
||||
{
|
||||
string path = CachePath;
|
||||
if (!File.Exists(path)) return;
|
||||
string[] p = File.ReadAllText(path).Split(',');
|
||||
if (p.Length < 6) return;
|
||||
CultureInfo ic = CultureInfo.InvariantCulture;
|
||||
Hp = uint.Parse(p[0], ic); MaxHp = uint.Parse(p[1], ic);
|
||||
St = uint.Parse(p[2], ic); MaxSt = uint.Parse(p[3], ic);
|
||||
Mn = uint.Parse(p[4], ic); MaxMn = uint.Parse(p[5], ic);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dashboard's mutating exports, run on the pump thread (UiDataHub.Post).
|
||||
/// Any thread may call these; each refreshes the snapshot afterwards.
|
||||
/// </summary>
|
||||
internal static unsafe class RynthAiCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<void> _toggleMacro;
|
||||
private static delegate* unmanaged[Cdecl]<int, int, void> _setSubsystemEnabled;
|
||||
private static delegate* unmanaged[Cdecl]<int, int, void> _selectProfile;
|
||||
private static delegate* unmanaged[Cdecl]<void> _forceRebuff;
|
||||
private static delegate* unmanaged[Cdecl]<void> _cancelForceRebuff;
|
||||
private static delegate* unmanaged[Cdecl]<float, void> _adjustOpacity;
|
||||
private static delegate* unmanaged[Cdecl]<void> _togglePanelLock;
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendNavCommand;
|
||||
|
||||
static RynthAiCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null;
|
||||
_cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null;
|
||||
};
|
||||
}
|
||||
|
||||
private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthAi", name);
|
||||
|
||||
private static void Run(string label, Action action)
|
||||
{
|
||||
UiDataHub.Post("RynthAi " + label, () =>
|
||||
{
|
||||
action();
|
||||
UiSources.RynthAi.RequestRefresh();
|
||||
});
|
||||
}
|
||||
|
||||
public static void ToggleMacro() => Run("toggle macro", () =>
|
||||
{
|
||||
if (_toggleMacro == null) _toggleMacro = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginToggleMacro");
|
||||
if (_toggleMacro != null) _toggleMacro();
|
||||
});
|
||||
|
||||
/// <summary>0 Combat, 1 Buff, 2 Nav, 3 Loot, 4 Meta.</summary>
|
||||
public static void SetSubsystemEnabled(int id, bool on) => Run("subsystem", () =>
|
||||
{
|
||||
if (_setSubsystemEnabled == null) _setSubsystemEnabled = (delegate* unmanaged[Cdecl]<int, int, void>)Export("RynthPluginSetSubsystemEnabled");
|
||||
if (_setSubsystemEnabled != null) _setSubsystemEnabled(id, on ? 1 : 0);
|
||||
});
|
||||
|
||||
/// <summary>kind: 0 nav, 1 loot, 2 meta, 3 profile.</summary>
|
||||
public static void SelectProfile(int kind, int index) => Run("select profile", () =>
|
||||
{
|
||||
if (_selectProfile == null) _selectProfile = (delegate* unmanaged[Cdecl]<int, int, void>)Export("RynthPluginSelectProfile");
|
||||
if (_selectProfile != null) _selectProfile(kind, index);
|
||||
});
|
||||
|
||||
public static void ForceRebuff() => Run("force rebuff", () =>
|
||||
{
|
||||
if (_forceRebuff == null) _forceRebuff = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginForceRebuff");
|
||||
if (_forceRebuff != null) _forceRebuff();
|
||||
});
|
||||
|
||||
public static void CancelForceRebuff() => Run("cancel force rebuff", () =>
|
||||
{
|
||||
if (_cancelForceRebuff == null) _cancelForceRebuff = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginCancelForceRebuff");
|
||||
if (_cancelForceRebuff != null) _cancelForceRebuff();
|
||||
});
|
||||
|
||||
public static void AdjustOpacity(float delta) => Run("opacity", () =>
|
||||
{
|
||||
if (_adjustOpacity == null) _adjustOpacity = (delegate* unmanaged[Cdecl]<float, void>)Export("RynthPluginAdjustOpacity");
|
||||
if (_adjustOpacity != null) _adjustOpacity(delta);
|
||||
});
|
||||
|
||||
public static void TogglePanelLock() => Run("lock", () =>
|
||||
{
|
||||
if (_togglePanelLock == null) _togglePanelLock = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginTogglePanelLock");
|
||||
if (_togglePanelLock != null) _togglePanelLock();
|
||||
});
|
||||
|
||||
/// <summary>RynthPluginSendNavCommand with a JSON command ({"Cmd":"dunPatrol"} ...).</summary>
|
||||
public static void SendNavCommand(string json, bool refreshPatrol = false) => Run("nav command", () =>
|
||||
{
|
||||
if (_sendNavCommand == null) _sendNavCommand = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthPluginSendNavCommand");
|
||||
if (_sendNavCommand == null) return;
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _sendNavCommand(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
if (refreshPatrol) UiSources.Patrol.RequestRefresh();
|
||||
UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginGetPatrolInfoJson's payload (patrol flyout).</summary>
|
||||
internal sealed class PatrolInfo
|
||||
{
|
||||
[JsonPropertyName("inDungeon")] public bool InDungeon { get; set; }
|
||||
[JsonPropertyName("currentLandblock")] public string CurrentLandblock { get; set; } = "0000";
|
||||
[JsonPropertyName("currentHazards")] public int CurrentHazards { get; set; }
|
||||
[JsonPropertyName("liveHazards")] public int LiveHazards { get; set; }
|
||||
[JsonPropertyName("dungeons")] public DungeonHazards[] Dungeons { get; set; } = Array.Empty<DungeonHazards>();
|
||||
[JsonPropertyName("routes")] public string[] Routes { get; set; } = Array.Empty<string>();
|
||||
}
|
||||
|
||||
internal sealed class DungeonHazards
|
||||
{
|
||||
[JsonPropertyName("landblock")] public string Landblock { get; set; } = "0000";
|
||||
[JsonPropertyName("cells")] public int Cells { get; set; }
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(PatrolInfo))]
|
||||
internal sealed partial class PatrolInfoJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginGetPatrolInfoJson (single static buffer: one caller only) while
|
||||
/// the patrol flyout is open, and right after each patrol action.
|
||||
/// </summary>
|
||||
internal sealed unsafe class PatrolSource : UiSource<PatrolInfo>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getPatrolInfoJson;
|
||||
|
||||
public PatrolSource() : base("Patrol", periodMs: 2000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getPatrolInfoJson == null)
|
||||
_getPatrolInfoJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetPatrolInfoJson");
|
||||
if (_getPatrolInfoJson == null) return;
|
||||
IntPtr p = _getPatrolInfoJson();
|
||||
string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
|
||||
Publish(JsonSerializer.Deserialize(json, PatrolInfoJsonContext.Default.PatrolInfo) ?? new PatrolInfo());
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getPatrolInfoJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
395
src/RynthCore.Engine/UI/Data/RynthNavAtlasData.cs
Normal file
395
src/RynthCore.Engine/UI/Data/RynthNavAtlasData.cs
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/RynthNavAtlasData.cs
|
||||
// The Go and Atlas tabs' data: RynthNav's location database (NavData\locations.json,
|
||||
// made by tools\navdata\gen_locations.py from the world database), read here
|
||||
// read-only so thousands of places don't travel through the status JSON
|
||||
// (RynthNav itself owns favorites, recent, the arrow and routing). The file's
|
||||
// path comes from RynthNav's status, so both read the same file.
|
||||
//
|
||||
// RynthNavAtlas the loaded places (a background load, UiBackgroundWriter),
|
||||
// and the player's map position from the pose snapshot.
|
||||
// RynthNavAtlasSource the rows the face shows for its query (search by name
|
||||
// and type, typed coordinates as the first row, Nearby,
|
||||
// Favorites, Recent; Saved = favorites then recent, the Go
|
||||
// tab's list while its box is empty), worked out on
|
||||
// the pump thread twice a second and only when the query,
|
||||
// the data or your position (by 3 yd) changed.
|
||||
//
|
||||
// Map coordinates are the /loc numbers (north and east positive); distances are
|
||||
// in yards (world units, 240 per degree).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>One place from locations.json, with its display strings.</summary>
|
||||
internal sealed class NavPlace
|
||||
{
|
||||
public int Id;
|
||||
public string Name = "", Type = "", Desc = "", Place = "", Lb = "", Cell = "";
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
public bool HasDest, DestOnMap;
|
||||
public double DestNs, DestEw;
|
||||
public string DestName = "";
|
||||
public int MinLevel, MaxLevel;
|
||||
public bool Quest, Closed;
|
||||
public string CoordText = "", DestText = "", LevelText = "";
|
||||
}
|
||||
|
||||
/// <summary>Saved: favorites, then recent places (the Go tab's list while its box is empty).</summary>
|
||||
internal enum AtlasMode { Search, Nearby, Favorites, Recent, Saved }
|
||||
|
||||
internal sealed record AtlasQuery(string Text, string Type, AtlasMode Mode);
|
||||
|
||||
internal sealed class AtlasRow
|
||||
{
|
||||
public required string Name, Type, Coord;
|
||||
public string Dist = "";
|
||||
/// <summary>"Town · 1.2k yd NE": the type and distance, for the Go tab's short list.</summary>
|
||||
public string Meta = "";
|
||||
public double Distance = double.PositiveInfinity;
|
||||
public bool OnMap, Favorite;
|
||||
public double Ns, Ew;
|
||||
/// <summary>The Atlas entry, when the row is one (a favorite or recent may not be).</summary>
|
||||
public NavPlace? Place;
|
||||
}
|
||||
|
||||
internal sealed class AtlasView
|
||||
{
|
||||
public static readonly AtlasView Empty = new(Array.Empty<AtlasRow>(), "");
|
||||
public AtlasView(AtlasRow[] rows, string summary) { Rows = rows; Summary = summary; }
|
||||
public AtlasRow[] Rows { get; }
|
||||
public string Summary { get; }
|
||||
}
|
||||
|
||||
internal static class RynthNavAtlas
|
||||
{
|
||||
public static readonly string[] Types =
|
||||
{ "All", "Town", "Dungeon", "Portal", "Lifestone", "Bindstone", "Vendor", "NPC", "Landmark" };
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static string _requested = "";
|
||||
private static volatile NavPlace[] _places = Array.Empty<NavPlace>();
|
||||
private static volatile HashSet<uint> _mapLandblocks = new();
|
||||
private static volatile string _status = "";
|
||||
private static long _version;
|
||||
|
||||
public static NavPlace[] Places => _places;
|
||||
public static string Status => _status;
|
||||
public static long Version => System.Threading.Interlocked.Read(ref _version);
|
||||
|
||||
/// <summary>Loads <paramref name="path"/> in the background unless it is already loaded or on its way. Any thread.</summary>
|
||||
public static void EnsureLoaded(string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path)) return;
|
||||
lock (Sync)
|
||||
{
|
||||
if (path == _requested) return;
|
||||
_requested = path;
|
||||
}
|
||||
_status = "loading the Atlas…";
|
||||
UiBackgroundWriter.Enqueue("RynthNav atlas (load)", () => Load(path));
|
||||
}
|
||||
|
||||
private static void Load(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) { _status = "No Atlas: " + path + " is missing."; return; }
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
var list = new List<NavPlace>();
|
||||
var lbs = new HashSet<uint>();
|
||||
if (doc.RootElement.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
var p = new NavPlace
|
||||
{
|
||||
Id = Int(e, "id"), Name = Str(e, "name"), Type = Str(e, "type"), Desc = Str(e, "desc"),
|
||||
Place = Str(e, "place"), Lb = Str(e, "lb"), Cell = Str(e, "cell"),
|
||||
MinLevel = Int(e, "minLevel"), MaxLevel = Int(e, "maxLevel"),
|
||||
Quest = e.TryGetProperty("quest", out var q) && q.ValueKind == JsonValueKind.True,
|
||||
Closed = e.TryGetProperty("closed", out var c) && c.ValueKind == JsonValueKind.True,
|
||||
};
|
||||
p.OnMap = TryNum(e, "ns", out p.Ns) & TryNum(e, "ew", out p.Ew);
|
||||
if (e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
p.HasDest = true;
|
||||
p.DestOnMap = TryNum(d, "ns", out p.DestNs) & TryNum(d, "ew", out p.DestEw);
|
||||
p.DestName = Str(d, "name");
|
||||
p.DestText = p.DestOnMap ? RynthNavStatus.Coord(p.DestNs, p.DestEw)
|
||||
: p.DestName.Length > 0 ? p.DestName + " (a dungeon)" : "a dungeon";
|
||||
}
|
||||
p.CoordText = p.OnMap ? RynthNavStatus.Coord(p.Ns, p.Ew) : "in a dungeon";
|
||||
p.LevelText = p.MinLevel > 0 && p.MaxLevel > 0 ? $"levels {p.MinLevel}–{p.MaxLevel}"
|
||||
: p.MinLevel > 0 ? $"level {p.MinLevel}+" : p.MaxLevel > 0 ? $"up to level {p.MaxLevel}" : "";
|
||||
if (p.OnMap && p.Cell.Length == 8 && uint.TryParse(p.Cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint lb))
|
||||
lbs.Add(lb);
|
||||
list.Add(p);
|
||||
}
|
||||
}
|
||||
_places = list.ToArray();
|
||||
_mapLandblocks = lbs;
|
||||
string generated = doc.RootElement.TryGetProperty("generated", out var g) ? g.GetString() ?? "" : "";
|
||||
_status = $"{list.Count} places" + (generated.Length >= 10 ? ", from " + generated.Substring(0, 10) : "");
|
||||
System.Threading.Interlocked.Increment(ref _version);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_status = "The Atlas didn't load: " + ex.Message;
|
||||
lock (Sync) _requested = ""; // try again on the next request
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Your map position from the pose snapshot (no AC call). <paramref name="onMap"/> is
|
||||
/// false in a dungeon, where the numbers aren't real map coordinates.
|
||||
/// </summary>
|
||||
public static bool TryPlayerPos(out double ns, out double ew, out bool onMap, out uint cell)
|
||||
{
|
||||
ns = ew = 0; onMap = false;
|
||||
if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out cell, out float x, out float y, out _, out _, out _, out _, out _)
|
||||
|| (cell >> 16) == 0)
|
||||
return false;
|
||||
int lbX = (int)((cell >> 24) & 0xFF), lbY = (int)((cell >> 16) & 0xFF);
|
||||
ew = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
|
||||
ns = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
|
||||
onMap = (cell & 0xFFFF) < 0x100 || _mapLandblocks.Contains(cell >> 16);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static double Distance(double ns1, double ew1, double ns2, double ew2)
|
||||
{
|
||||
double dn = (ns2 - ns1) * 240.0, de = (ew2 - ew1) * 240.0;
|
||||
return Math.Sqrt(dn * dn + de * de);
|
||||
}
|
||||
|
||||
/// <summary>Compass bearing: 0 = north, clockwise.</summary>
|
||||
public static double Bearing(double fromNs, double fromEw, double toNs, double toEw)
|
||||
{
|
||||
double b = Math.Atan2(toEw - fromEw, toNs - fromNs) * 180.0 / Math.PI;
|
||||
return b < 0 ? b + 360.0 : b;
|
||||
}
|
||||
|
||||
private static readonly string[] Compass16 =
|
||||
{ "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" };
|
||||
|
||||
public static string CompassPoint(double bearing) => Compass16[(int)Math.Round(((bearing % 360.0) + 360.0) % 360.0 / 22.5) & 15];
|
||||
|
||||
/// <summary>How well a name matches a search (RynthNav's Atlas.MatchScore): 0 = not at all.</summary>
|
||||
public static int MatchScore(string name, string q)
|
||||
{
|
||||
if (q.Length == 0) return 1;
|
||||
if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100;
|
||||
int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase);
|
||||
if (at == 0) return 80;
|
||||
if (at > 0) return char.IsLetterOrDigit(name[at - 1]) ? 40 : 60;
|
||||
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length < 2) return 0;
|
||||
foreach (string w in words)
|
||||
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0;
|
||||
return 30;
|
||||
}
|
||||
|
||||
public static int TypeRank(string type) => type switch
|
||||
{
|
||||
"Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 4,
|
||||
"Portal" => 5, "Vendor" => 6, "NPC" => 7, _ => 8,
|
||||
};
|
||||
|
||||
private static string Str(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
|
||||
|
||||
private static int Int(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0;
|
||||
|
||||
private static bool TryNum(JsonElement e, string name, out double d)
|
||||
{
|
||||
d = 0;
|
||||
return e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Go or Atlas tab's rows for <see cref="Query"/> (pump thread, 500 ms, while either tab is open).</summary>
|
||||
internal sealed class RynthNavAtlasSource : UiSource<AtlasView>
|
||||
{
|
||||
private const int MaxRows = 300;
|
||||
|
||||
/// <summary>What the Go or Atlas tab asks for (the one showing). Set by the face (AC's thread), read here.</summary>
|
||||
public static volatile AtlasQuery Query = new("", "All", AtlasMode.Search);
|
||||
|
||||
private AtlasQuery? _seenQuery;
|
||||
private long _seenAtlas = -1, _seenStatus = -1;
|
||||
private double _seenNs = double.NaN, _seenEw = double.NaN;
|
||||
|
||||
public RynthNavAtlasSource() : base("RynthNavAtlas", periodMs: 500) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
UiSnapshot<RynthNavStatus>? stSnap = UiSources.RynthNav.Current;
|
||||
RynthNavStatus? st = stSnap?.Value;
|
||||
if (st != null && st.AtlasPath.Length > 0) RynthNavAtlas.EnsureLoaded(st.AtlasPath);
|
||||
|
||||
AtlasQuery q = Query;
|
||||
bool hasPos = RynthNavAtlas.TryPlayerPos(out double pns, out double pew, out bool onMap, out _);
|
||||
hasPos &= onMap;
|
||||
long atlasV = RynthNavAtlas.Version, statusV = stSnap?.Version ?? -1;
|
||||
bool moved = hasPos != !double.IsNaN(_seenNs)
|
||||
|| (hasPos && RynthNavAtlas.Distance(pns, pew, _seenNs, _seenEw) > 3);
|
||||
// The status moves with favorites (the stars) and recent, so it counts for every mode.
|
||||
if (q == _seenQuery && atlasV == _seenAtlas && !moved && statusV == _seenStatus && Current != null)
|
||||
return;
|
||||
_seenQuery = q; _seenAtlas = atlasV; _seenStatus = statusV;
|
||||
_seenNs = hasPos ? pns : double.NaN; _seenEw = hasPos ? pew : double.NaN;
|
||||
|
||||
var favorites = st?.Favorites ?? Array.Empty<RynthNavPlace>();
|
||||
NavPlace[] places = RynthNavAtlas.Places;
|
||||
var rows = new List<AtlasRow>();
|
||||
string summary;
|
||||
switch (q.Mode)
|
||||
{
|
||||
case AtlasMode.Saved:
|
||||
{
|
||||
// Favorites first, then recent places that aren't favorites (each place once).
|
||||
foreach (RynthNavPlace s in favorites) rows.Add(SavedRow(places, s));
|
||||
foreach (RynthNavPlace s in st?.Recent ?? Array.Empty<RynthNavPlace>())
|
||||
{
|
||||
bool fav = false;
|
||||
foreach (RynthNavPlace f in favorites)
|
||||
if (SamePlace(f.Name, f.Ns, f.Ew, s.Name, s.Ns, s.Ew)) { fav = true; break; }
|
||||
if (!fav) rows.Add(SavedRow(places, s));
|
||||
}
|
||||
summary = st == null ? "RynthNav isn't answering."
|
||||
: rows.Count == 0 ? "Type a place, or coordinates like 42.1N, 33.6E. Favorites and recent places show here."
|
||||
: $"{favorites.Length} favorite{(favorites.Length == 1 ? "" : "s")}, {rows.Count - favorites.Length} recent";
|
||||
break;
|
||||
}
|
||||
case AtlasMode.Favorites:
|
||||
case AtlasMode.Recent:
|
||||
{
|
||||
RynthNavPlace[] saved = q.Mode == AtlasMode.Favorites ? favorites : st?.Recent ?? Array.Empty<RynthNavPlace>();
|
||||
foreach (RynthNavPlace s in saved)
|
||||
{
|
||||
if (!TypeMatches(q.Type, s.Type) || RynthNavAtlas.MatchScore(s.Name, q.Text.Trim()) == 0) continue;
|
||||
rows.Add(SavedRow(places, s));
|
||||
}
|
||||
summary = st == null ? "RynthNav isn't answering."
|
||||
: rows.Count == 0 ? (q.Mode == AtlasMode.Favorites ? "No favorites yet: the star on a place adds it." : "Nothing yet: places you point the arrow at show here.")
|
||||
: $"{rows.Count} {(q.Mode == AtlasMode.Favorites ? "favorite" : "recent place")}{(rows.Count == 1 ? "" : "s")}";
|
||||
break;
|
||||
}
|
||||
case AtlasMode.Nearby:
|
||||
{
|
||||
if (!hasPos) { summary = places.Length == 0 ? RynthNavAtlas.Status : "Nearby needs you on the map (not in a dungeon)."; break; }
|
||||
var hits = new List<(NavPlace P, double D)>();
|
||||
string text = q.Text.Trim();
|
||||
foreach (NavPlace p in places)
|
||||
{
|
||||
if (!p.OnMap || !TypeMatches(q.Type, p.Type) || RynthNavAtlas.MatchScore(p.Name, text) == 0) continue;
|
||||
hits.Add((p, RynthNavAtlas.Distance(pns, pew, p.Ns, p.Ew)));
|
||||
}
|
||||
hits.Sort((a, b) => a.D.CompareTo(b.D));
|
||||
for (int i = 0; i < hits.Count && rows.Count < MaxRows; i++) rows.Add(Row(hits[i].P));
|
||||
summary = places.Length == 0 ? RynthNavAtlas.Status : $"{hits.Count} on the map, nearest first";
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
string text = q.Text.Trim();
|
||||
var hits = new List<(NavPlace P, int S)>();
|
||||
foreach (NavPlace p in places)
|
||||
{
|
||||
if (!TypeMatches(q.Type, p.Type)) continue;
|
||||
int sc = RynthNavAtlas.MatchScore(p.Name, text);
|
||||
if (sc > 0) hits.Add((p, sc));
|
||||
}
|
||||
hits.Sort((a, b) =>
|
||||
{
|
||||
int c = b.S.CompareTo(a.S);
|
||||
if (c != 0) return c;
|
||||
c = RynthNavAtlas.TypeRank(a.P.Type).CompareTo(RynthNavAtlas.TypeRank(b.P.Type));
|
||||
if (c != 0) return c;
|
||||
c = b.P.OnMap.CompareTo(a.P.OnMap);
|
||||
return c != 0 ? c : string.Compare(a.P.Name, b.P.Name, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
for (int i = 0; i < hits.Count && rows.Count < MaxRows; i++) rows.Add(Row(hits[i].P));
|
||||
summary = places.Length == 0 ? RynthNavAtlas.Status
|
||||
: hits.Count > rows.Count ? $"{hits.Count} matches, the first {rows.Count} shown" : $"{hits.Count} of {places.Length} places";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Coordinates typed ("42.1N, 33.6E", a name after them is kept): the first row.
|
||||
if (q.Mode == AtlasMode.Search && CoordRow(q.Text) is AtlasRow coordRow)
|
||||
{
|
||||
rows.Insert(0, coordRow);
|
||||
if (rows.Count == 1) summary = "Coordinates: " + coordRow.Coord;
|
||||
}
|
||||
|
||||
foreach (AtlasRow r in rows)
|
||||
{
|
||||
if (hasPos && r.OnMap)
|
||||
{
|
||||
r.Distance = RynthNavAtlas.Distance(pns, pew, r.Ns, r.Ew);
|
||||
r.Dist = RynthNavStatus.Yards(r.Distance) + " " + RynthNavAtlas.CompassPoint(RynthNavAtlas.Bearing(pns, pew, r.Ns, r.Ew));
|
||||
}
|
||||
r.Meta = r.Dist.Length > 0 ? r.Type + " · " + r.Dist : r.OnMap ? r.Type : r.Type + " · in a dungeon";
|
||||
foreach (RynthNavPlace f in favorites)
|
||||
if (SamePlace(f.Name, f.Ns, f.Ew, r.Name, r.Ns, r.Ew)) { r.Favorite = true; break; }
|
||||
}
|
||||
Publish(new AtlasView(rows.ToArray(), summary));
|
||||
}
|
||||
|
||||
private static AtlasRow SavedRow(NavPlace[] places, RynthNavPlace s) => new()
|
||||
{
|
||||
Name = s.Name, Type = s.Type.Length > 0 ? s.Type : "Place", Coord = s.CoordText, OnMap = true, Ns = s.Ns, Ew = s.Ew,
|
||||
Place = Find(places, s.Name, s.Ns, s.Ew),
|
||||
};
|
||||
|
||||
private static bool SamePlace(string n1, double ns1, double ew1, string n2, double ns2, double ew2) =>
|
||||
n1.Equals(n2, StringComparison.OrdinalIgnoreCase) && Math.Abs(ns1 - ns2) < 0.05 && Math.Abs(ew1 - ew2) < 0.05;
|
||||
|
||||
/// <summary>A row for typed coordinates (the whole text, or coordinates then a name), else null.</summary>
|
||||
internal static AtlasRow? CoordRow(string text)
|
||||
{
|
||||
text = text.Trim();
|
||||
if (text.Length == 0) return null;
|
||||
var found = ChatCoords.Find(text);
|
||||
if (found.Count == 0 || found[0].Start != 0) return null;
|
||||
ChatCoord c = found[0];
|
||||
string name = text.Substring(c.Length).Trim().TrimStart(',', ';').Trim();
|
||||
return new AtlasRow
|
||||
{
|
||||
Name = name.Length > 0 ? name : c.Text, Type = "Coordinates", Coord = c.Text, OnMap = true, Ns = c.Ns, Ew = c.Ew,
|
||||
};
|
||||
}
|
||||
|
||||
private static AtlasRow Row(NavPlace p) => new()
|
||||
{
|
||||
Name = p.Name, Type = p.Type, Coord = p.CoordText, OnMap = p.OnMap, Ns = p.Ns, Ew = p.Ew, Place = p,
|
||||
};
|
||||
|
||||
private static bool TypeMatches(string filter, string type) =>
|
||||
filter.Length == 0 || filter == "All" || filter.Equals(type, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static NavPlace? Find(NavPlace[] places, string name, double ns, double ew)
|
||||
{
|
||||
foreach (NavPlace p in places)
|
||||
if (p.OnMap && p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && Math.Abs(p.Ns - ns) < 0.05 && Math.Abs(p.Ew - ew) < 0.05)
|
||||
return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_seenQuery = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
521
src/RynthCore.Engine/UI/Data/RynthNavData.cs
Normal file
521
src/RynthCore.Engine/UI/Data/RynthNavData.cs
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/RynthNavData.cs
|
||||
// The RynthNav plugin's status (pose, loaded navmesh tile, status line, last
|
||||
// path, run/turn state; and its travel side: the arrow, the last planned
|
||||
// route, the recalls this character can use, favorites and recent, where its
|
||||
// Atlas lives; and, from 0.6.1, the Go tab's status line, the current step's
|
||||
// distance left, portal ties and the Info section's NavData facts) for both
|
||||
// RynthNav faces, and its commands.
|
||||
//
|
||||
// RynthNavGetStatusJson (and RynthNavGetStatusJsonUtf8, 0.6.1+, tried first)
|
||||
// frees its previous buffer on each call, so the hub is its only caller
|
||||
// (RynthNavSource, 250 ms). Load tile / test / preview / go /
|
||||
// move / command run on the pump too. RynthNavArrowWatch reads one int (how
|
||||
// many times a command asked to show the arrow) twice a second, always, so
|
||||
// "/rnav arrow Holtburg" opens the arrow overlay with every RynthNav face shut.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>A place RynthNav keeps (favorites, recent) or can recall to.</summary>
|
||||
internal sealed record RynthNavPlace(string Name, string Type, double Ns, double Ew, string Detail = "")
|
||||
{
|
||||
/// <summary>"42.1N, 33.6E".</summary>
|
||||
public string CoordText { get; } = RynthNavStatus.Coord(Ns, Ew);
|
||||
}
|
||||
|
||||
/// <summary>One leg of the last planned route.</summary>
|
||||
internal sealed record RynthNavRouteStep(string Kind, string Label, double Ns, double Ew, bool HasLanding, double LandNs, double LandEw)
|
||||
{
|
||||
/// <summary>What to do, as the route view shows it.</summary>
|
||||
public string Text { get; } = Kind switch
|
||||
{
|
||||
"recall" => "Cast " + Label + (HasLanding ? " → " + RynthNavStatus.Coord(LandNs, LandEw) : ""),
|
||||
"portal" => "Take portal " + Label + " at " + RynthNavStatus.Coord(Ns, Ew) + (HasLanding ? " → " + RynthNavStatus.Coord(LandNs, LandEw) : ""),
|
||||
// Town Network legs (a later RynthNav): shown as they come; unknown kinds read as a leg to take.
|
||||
"town" => "Town Network: " + Label + (HasLanding ? " → " + RynthNavStatus.Coord(LandNs, LandEw) : ""),
|
||||
"walk" or "" => "Walk to " + RynthNavStatus.Coord(Ns, Ew),
|
||||
_ => (Label.Length > 0 ? Label : Kind) + " at " + RynthNavStatus.Coord(Ns, Ew),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A recall spot RynthNav learned for this character (portal ties, @lifestone, house...). RynthNav 0.6.1+.</summary>
|
||||
internal sealed record RynthNavRecallSpot(string Slot, string Name, bool OnMap, double Ns, double Ew, string At)
|
||||
{
|
||||
/// <summary>"Holtburg Lifestone, 42.1N, 33.6E" or "Matron Hive (a dungeon)".</summary>
|
||||
public string Where { get; } = OnMap
|
||||
? (At.Length > 0 ? At + ", " : "") + RynthNavStatus.Coord(Ns, Ew)
|
||||
: (At.Length > 0 ? At : "somewhere") + " (a dungeon)";
|
||||
}
|
||||
|
||||
/// <summary>What the arrow points at now (a place, a portal on the way, or a recall to cast).</summary>
|
||||
internal sealed class RynthNavArrow
|
||||
{
|
||||
public string Name = "", Type = "", Kind = "place", Hint = "", Final = "", FinalType = "";
|
||||
public bool OnMap;
|
||||
public double Ns, Ew, FinalNs, FinalEw, ArriveYards = 10;
|
||||
public int Step = 1, Steps = 1;
|
||||
public string StepText = "", CoordText = "", ThenText = "";
|
||||
}
|
||||
|
||||
internal sealed class RynthNavStatus
|
||||
{
|
||||
public bool HasPose, TileLoaded;
|
||||
public int PolyCount, RunState, TurnState;
|
||||
public string Landblock = "----", LoadedLb = "----", Status = "", LastPath = "";
|
||||
public double NS, EW;
|
||||
public bool Goto;
|
||||
|
||||
// Travel (RynthNav 0.6+; absent from older plugins: Travel stays false).
|
||||
public bool Travel;
|
||||
public string AtlasPath = "", AtlasStatus = "", AtlasGenerated = "";
|
||||
public int AtlasCount;
|
||||
public bool PortalsOn, RecallsOn = true;
|
||||
// Avoidance settings (RynthNav 0.6.4+; HasAvoid false on older plugins).
|
||||
public bool HasAvoid, AvoidPortals, AvoidWalls;
|
||||
public double AvoidPortalM, AvoidWallM, CornerM;
|
||||
public int OpenArrow;
|
||||
public RynthNavArrow? Arrow;
|
||||
public string RouteFor = "", RouteSummary = "";
|
||||
public bool RouteActive;
|
||||
public int RouteIdx = -1;
|
||||
public RynthNavRouteStep[] Route = Array.Empty<RynthNavRouteStep>();
|
||||
public RynthNavPlace[] Recalls = Array.Empty<RynthNavPlace>();
|
||||
public string[] RecallNotes = Array.Empty<string>();
|
||||
public RynthNavPlace[] Favorites = Array.Empty<RynthNavPlace>();
|
||||
public RynthNavPlace[] Recent = Array.Empty<RynthNavPlace>();
|
||||
// The route view's lines, built here (not per frame): the header, one per step, one per recall.
|
||||
public string RouteHeader = "", RecallHeader = "RECALLS FOR ROUTES (0)";
|
||||
public string[] RouteLines = Array.Empty<string>(), RecallLines = Array.Empty<string>();
|
||||
|
||||
// Panel (RynthNav 0.6.1+; absent from older plugins: Panel, HasInfo and HasTies stay false).
|
||||
public bool Panel;
|
||||
public string Version = "";
|
||||
public string GoLine = "", GoPhase = "";
|
||||
public double GoLeft = -1;
|
||||
public bool HasInfo, GraphLoaded, Indoors;
|
||||
public int TileHere = -1, OnDisk = -1;
|
||||
public string NavDir = "", NavSource = "", GraphStatus = "";
|
||||
// The Town Network (RynthNav 0.6.2+): townnet.json loaded or not, and why.
|
||||
public bool HasTownNet, TownNetLoaded;
|
||||
public string TownNetStatus = "";
|
||||
public bool HasTies;
|
||||
public int Tie1Known = -1, Tie2Known = -1;
|
||||
public string TiePending = "";
|
||||
public RynthNavRecallSpot[] Mine = Array.Empty<RynthNavRecallSpot>();
|
||||
// Built once per status for the Go tab.
|
||||
/// <summary>The status line: what RynthNav is doing, or how the last goto ended.</summary>
|
||||
public string StatusLine = "";
|
||||
/// <summary>The current route step's "340 yd left" (empty when not walking a step).</summary>
|
||||
public string StepLeft = "";
|
||||
public string Tie1Text = "", Tie2Text = "", TiePendingText = "";
|
||||
public string[] MineLines = Array.Empty<string>();
|
||||
public string InfoHere = "", InfoNavData = "", InfoTiles = "", InfoGraph = "", InfoTownNet = "", InfoAtlas = "", InfoStatus = "";
|
||||
|
||||
// Display strings, built once per status.
|
||||
public string PlayerText = "— no pose —", MeshText = "not loaded", PathText = "";
|
||||
public bool OnMap = true;
|
||||
|
||||
public static RynthNavStatus? Parse(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
JsonElement r = doc.RootElement;
|
||||
var s = new RynthNavStatus();
|
||||
if (r.TryGetProperty("hasPose", out var v)) s.HasPose = v.GetInt32() != 0;
|
||||
if (r.TryGetProperty("landblock", out v)) s.Landblock = v.GetString() ?? "----";
|
||||
if (r.TryGetProperty("ns", out v)) s.NS = v.GetDouble();
|
||||
if (r.TryGetProperty("ew", out v)) s.EW = v.GetDouble();
|
||||
if (r.TryGetProperty("tileLoaded", out v)) s.TileLoaded = v.GetInt32() != 0;
|
||||
if (r.TryGetProperty("loadedLb", out v)) s.LoadedLb = v.GetString() ?? "----";
|
||||
if (r.TryGetProperty("polyCount", out v)) s.PolyCount = v.GetInt32();
|
||||
if (r.TryGetProperty("status", out v)) s.Status = v.GetString() ?? "";
|
||||
if (r.TryGetProperty("lastPath", out v)) s.LastPath = v.GetString() ?? "";
|
||||
if (r.TryGetProperty("runState", out v)) s.RunState = v.GetInt32();
|
||||
if (r.TryGetProperty("turnState", out v)) s.TurnState = v.GetInt32();
|
||||
if (r.TryGetProperty("goto", out v)) s.Goto = v.GetInt32() != 0;
|
||||
// RynthNav 0.6.3+: "onMap" 0 in a dungeon, where ns/ew aren't map coordinates.
|
||||
s.OnMap = !r.TryGetProperty("onMap", out v) || v.ValueKind != JsonValueKind.Number || v.GetInt32() != 0;
|
||||
s.PlayerText = !s.HasPose ? "— no pose —"
|
||||
: s.OnMap ? $"0x{s.Landblock} {Loc(s.NS, 'N', 'S')} {Loc(s.EW, 'E', 'W')}"
|
||||
: $"0x{s.Landblock} in a dungeon (no map position: routes start with a recall)";
|
||||
// polyCount is RynthNav's loaded TILE count (a window of landblocks around
|
||||
// the player), not a polygon count; it was labelled "polys".
|
||||
s.MeshText = s.TileLoaded ? $"{s.PolyCount} tiles around 0x{s.LoadedLb}" : "not loaded";
|
||||
s.PathText = string.IsNullOrEmpty(s.LastPath) ? "" : "↳ " + s.LastPath;
|
||||
ParseTravel(r, s);
|
||||
ParsePanel(r, s);
|
||||
return s;
|
||||
}
|
||||
catch { return null; } // transient partial JSON
|
||||
}
|
||||
|
||||
private static void ParseTravel(JsonElement r, RynthNavStatus s)
|
||||
{
|
||||
if (!r.TryGetProperty("atlas", out var atlas) || atlas.ValueKind != JsonValueKind.Object) return;
|
||||
s.Travel = true;
|
||||
s.AtlasPath = Str(atlas, "path");
|
||||
s.AtlasStatus = Str(atlas, "status");
|
||||
s.AtlasGenerated = Str(atlas, "generated");
|
||||
s.AtlasCount = Int(atlas, "count");
|
||||
s.PortalsOn = Int(r, "portalsOn") != 0;
|
||||
s.RecallsOn = Int(r, "recallsOn") != 0;
|
||||
s.HasAvoid = r.TryGetProperty("avoidPortals", out _);
|
||||
s.AvoidPortals = Int(r, "avoidPortals") != 0;
|
||||
s.AvoidWalls = Int(r, "avoidWalls") != 0;
|
||||
s.AvoidPortalM = Num(r, "avoidPortalM");
|
||||
s.AvoidWallM = Num(r, "avoidWallM");
|
||||
s.CornerM = Num(r, "cornerM");
|
||||
s.OpenArrow = Int(r, "openArrow");
|
||||
|
||||
if (r.TryGetProperty("arrow", out var a) && a.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
var ar = new RynthNavArrow
|
||||
{
|
||||
Name = Str(a, "name"), Type = Str(a, "type"), Kind = Str(a, "kind"), Hint = Str(a, "hint"),
|
||||
Final = Str(a, "final"), FinalType = Str(a, "finalType"),
|
||||
OnMap = Int(a, "onMap") != 0, Ns = Num(a, "ns"), Ew = Num(a, "ew"),
|
||||
FinalNs = Num(a, "finalNs"), FinalEw = Num(a, "finalEw"),
|
||||
Step = Int(a, "step"), Steps = Int(a, "steps"), ArriveYards = Num(a, "arrive"),
|
||||
};
|
||||
ar.CoordText = ar.OnMap ? Coord(ar.Ns, ar.Ew) : "";
|
||||
ar.StepText = ar.Steps > 1 ? $"step {ar.Step} of {ar.Steps}, to {ar.Final}" : "";
|
||||
ar.ThenText = ar.Steps > 1 ? "then " + ar.Final + " " + Coord(ar.FinalNs, ar.FinalEw) : "";
|
||||
s.Arrow = ar;
|
||||
}
|
||||
|
||||
if (r.TryGetProperty("route", out var route) && route.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
s.RouteFor = Str(route, "for");
|
||||
s.RouteActive = Int(route, "active") != 0;
|
||||
s.RouteIdx = Int(route, "idx", -1);
|
||||
var steps = new List<RynthNavRouteStep>();
|
||||
int teleports = 0;
|
||||
if (route.TryGetProperty("steps", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
bool land = e.TryGetProperty("lns", out _);
|
||||
var step = new RynthNavRouteStep(Str(e, "k"), Str(e, "l"), Num(e, "ns"), Num(e, "ew"), land, Num(e, "lns"), Num(e, "lew"));
|
||||
if (step.Kind != "walk") teleports++;
|
||||
steps.Add(step);
|
||||
}
|
||||
s.Route = steps.ToArray();
|
||||
double est = Num(route, "est");
|
||||
s.RouteSummary = teleports == 0
|
||||
? $"walk, about {Yards(est)}"
|
||||
: $"{teleports} teleport{(teleports == 1 ? "" : "s")}, about {Yards(est)} of effort";
|
||||
s.RouteHeader = "To " + s.RouteFor + ": " + s.RouteSummary + (s.RouteActive ? " (walking)" : "");
|
||||
var lines = new string[s.Route.Length];
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
RynthNavRouteStep st = s.Route[i];
|
||||
string icon = st.Kind == "recall" ? StepIconRecall : st.Kind == "portal" ? StepIconPortal
|
||||
: st.Kind == "town" ? StepIconTown : StepIconWalk;
|
||||
lines[i] = icon + " " + (i + 1).ToString(CultureInfo.InvariantCulture) + ". " + st.Text;
|
||||
}
|
||||
s.RouteLines = lines;
|
||||
}
|
||||
|
||||
s.Recalls = Places(r, "recalls", recall: true);
|
||||
s.RecallHeader = "RECALLS FOR ROUTES (" + s.Recalls.Length.ToString(CultureInfo.InvariantCulture) + ")";
|
||||
var recallLines = new string[s.Recalls.Length];
|
||||
for (int i = 0; i < recallLines.Length; i++)
|
||||
recallLines[i] = StepIconRecall + " " + s.Recalls[i].Name + " → " + s.Recalls[i].CoordText + " (" + s.Recalls[i].Detail + ")";
|
||||
s.RecallLines = recallLines;
|
||||
if (r.TryGetProperty("recallNotes", out var notes) && notes.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (JsonElement n in notes.EnumerateArray()) list.Add(n.GetString() ?? "");
|
||||
s.RecallNotes = list.ToArray();
|
||||
}
|
||||
s.Favorites = Places(r, "favs", recall: false);
|
||||
s.Recent = Places(r, "recent", recall: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Go tab's fields (RynthNav 0.6.1+): the status line, the current step's distance
|
||||
/// left, the Info section (NavData, route graph, the tile here) and the Recalls section's
|
||||
/// portal ties and learned recall spots. Older RynthNavs: the status line falls back to
|
||||
/// the technical status, and the sections say what an update adds.
|
||||
/// </summary>
|
||||
private static void ParsePanel(JsonElement r, RynthNavStatus s)
|
||||
{
|
||||
s.Version = Str(r, "v");
|
||||
if (r.TryGetProperty("go", out var go) && go.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
s.Panel = true;
|
||||
s.GoLine = Str(go, "line");
|
||||
s.GoPhase = Str(go, "phase");
|
||||
s.GoLeft = go.TryGetProperty("left", out var l) && l.ValueKind == JsonValueKind.Number ? l.GetDouble() : -1;
|
||||
}
|
||||
s.StatusLine = s.Panel ? (s.GoLine.Length > 0 ? s.GoLine : s.Goto ? "walking" : "ready") : s.Status;
|
||||
// "town": walking inside the Town Network (RynthNav 0.6.2+).
|
||||
s.StepLeft = s.Goto && (s.GoPhase == "walk" || s.GoPhase == "town") && s.GoLeft >= 0 ? Yards(s.GoLeft) + " left" : "";
|
||||
|
||||
if (r.TryGetProperty("info", out var info) && info.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
s.HasInfo = true;
|
||||
s.NavDir = Str(info, "dir");
|
||||
s.NavSource = Str(info, "source");
|
||||
s.GraphLoaded = Int(info, "graph") != 0;
|
||||
s.GraphStatus = Str(info, "graphStatus");
|
||||
s.TileHere = Int(info, "tileHere", -1);
|
||||
s.Indoors = Int(info, "indoors") != 0;
|
||||
s.OnDisk = Int(info, "onDisk", -1);
|
||||
s.HasTownNet = info.TryGetProperty("townNet", out _);
|
||||
s.TownNetLoaded = Int(info, "townNet") != 0;
|
||||
s.TownNetStatus = Str(info, "townNetStatus");
|
||||
}
|
||||
string meshHere = !s.HasInfo ? (s.TileLoaded ? "loaded" : "not loaded")
|
||||
: s.TileHere == 1 ? "yes" : s.TileHere == 0 ? "no (no tile for this landblock)" : "not checked yet";
|
||||
s.InfoHere = s.HasPose
|
||||
? $"0x{s.Landblock}{(s.Indoors ? " (indoors)" : "")} \u00B7 navmesh here: {meshHere} \u00B7 {s.PolyCount} tile{(s.PolyCount == 1 ? "" : "s")} loaded"
|
||||
: "no position yet";
|
||||
s.InfoNavData = s.HasInfo ? s.NavDir + (s.NavSource.Length > 0 ? " (" + s.NavSource + ")" : "") : "update RynthNav for the NavData folder";
|
||||
s.InfoTiles = !s.HasInfo ? "" : s.OnDisk >= 0 ? $"{s.OnDisk} tile files in the folder" : "tile files: counting\u2026";
|
||||
s.InfoGraph = s.HasInfo ? (s.GraphLoaded ? "loaded: " : "not loaded: ") + s.GraphStatus : "update RynthNav for the route graph";
|
||||
s.InfoTownNet = s.HasTownNet ? (s.TownNetLoaded ? "loaded: " : "not loaded: ") + s.TownNetStatus : "update RynthNav (0.6.2) for Town Network routes";
|
||||
s.InfoAtlas = !s.Travel ? "update RynthNav for the Atlas"
|
||||
: $"{s.AtlasCount} places" + (s.AtlasStatus.Length > 0 && !s.AtlasStatus.EndsWith(" places", StringComparison.Ordinal) ? " (" + s.AtlasStatus + ")" : "")
|
||||
+ (s.AtlasGenerated.Length >= 10 ? ", from " + s.AtlasGenerated.Substring(0, 10) : "");
|
||||
s.InfoStatus = s.Status + (s.LastPath.Length > 0 ? " \u00B7 " + s.LastPath : "");
|
||||
|
||||
if (r.TryGetProperty("mine", out var mine) && mine.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
s.HasTies = true;
|
||||
var spots = new List<RynthNavRecallSpot>();
|
||||
foreach (JsonElement e in mine.EnumerateArray())
|
||||
spots.Add(new RynthNavRecallSpot(Str(e, "s"), Str(e, "n"), Int(e, "on") != 0, Num(e, "ns"), Num(e, "ew"), Str(e, "at")));
|
||||
s.Mine = spots.ToArray();
|
||||
if (r.TryGetProperty("ties", out var ties) && ties.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
s.Tie1Known = Int(ties, "t1", -1);
|
||||
s.Tie2Known = Int(ties, "t2", -1);
|
||||
}
|
||||
s.TiePending = Str(r, "tiePending");
|
||||
s.Tie1Text = TieText("Primary", "Tie1", s.Tie1Known, s.Mine);
|
||||
s.Tie2Text = TieText("Secondary", "Tie2", s.Tie2Known, s.Mine);
|
||||
s.TiePendingText = s.TiePending.Length > 0 ? "Portal tie noted: " + s.TiePending + ". Which tie was it?" : "";
|
||||
var lines = new List<string>();
|
||||
foreach (RynthNavRecallSpot m in s.Mine)
|
||||
if (m.Slot != "Tie1" && m.Slot != "Tie2") lines.Add(StepIconRecall + " " + m.Name + ": " + m.Where);
|
||||
s.MineLines = lines.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static string TieText(string which, string slot, int known, RynthNavRecallSpot[] mine)
|
||||
{
|
||||
foreach (RynthNavRecallSpot m in mine)
|
||||
if (m.Slot == slot) return which + " tie: " + m.Where;
|
||||
return which + " tie: " + (known == 0 ? "you don't know " + which + " Portal Tie" : "not tied yet (cast " + which + " Portal Tie on a portal)");
|
||||
}
|
||||
|
||||
// Phosphor glyphs (ImGui/PhosphorIcons.cs: MagicWand, Spiral, Footprints, CastleTurret), kept here
|
||||
// so this data class needs nothing from the ImGui layer.
|
||||
private const string StepIconRecall = "\uE6B6", StepIconPortal = "\uE9FA", StepIconWalk = "\uEA88", StepIconTown = "\uE9D0";
|
||||
|
||||
private static RynthNavPlace[] Places(JsonElement r, string key, bool recall)
|
||||
{
|
||||
if (!r.TryGetProperty(key, out var arr) || arr.ValueKind != JsonValueKind.Array) return Array.Empty<RynthNavPlace>();
|
||||
var list = new List<RynthNavPlace>();
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
list.Add(new RynthNavPlace(Str(e, "n"), recall ? "Recall" : Str(e, "t"), Num(e, "ns"), Num(e, "ew"),
|
||||
recall ? Str(e, "how") + (Int(e, "learned") != 0 ? ", learned" : "") : ""));
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
private static string Str(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
|
||||
|
||||
private static int Int(JsonElement e, string name, int fallback = 0) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback;
|
||||
|
||||
private static double Num(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : 0;
|
||||
|
||||
private static string Loc(double v, char pos, char neg) =>
|
||||
v.ToString("F1", CultureInfo.InvariantCulture).TrimStart('-') + (v >= 0 ? pos : neg);
|
||||
|
||||
/// <summary>"42.1N, 33.6E".</summary>
|
||||
public static string Coord(double ns, double ew) => Loc(ns, 'N', 'S') + ", " + Loc(ew, 'E', 'W');
|
||||
|
||||
/// <summary>What RynthNav's commands take: "42.08N, 33.60E" (two decimals, so a place's own spot).</summary>
|
||||
public static string CommandCoord(double ns, double ew) =>
|
||||
Math.Abs(ns).ToString("F2", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", "
|
||||
+ Math.Abs(ew).ToString("F2", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
|
||||
|
||||
public static string Yards(double units) =>
|
||||
units < 1000 ? units.ToString("0", CultureInfo.InvariantCulture) + " yd"
|
||||
: (units / 1000.0).ToString("0.0", CultureInfo.InvariantCulture) + "k yd";
|
||||
}
|
||||
|
||||
/// <summary>RynthNavGetStatusJson while a RynthNav face is open (250 ms).</summary>
|
||||
internal sealed unsafe class RynthNavSource : UiSource<RynthNavStatus>
|
||||
{
|
||||
// RynthNav 0.6.1+ also has a UTF-8 getter (names with characters the ANSI code page lacks);
|
||||
// older ones only the ANSI one. Each frees its own previous buffer; only one is called.
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _get;
|
||||
private bool _utf8;
|
||||
private string? _lastJson;
|
||||
|
||||
public RynthNavSource() : base("RynthNav", periodMs: 250) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_get == null)
|
||||
{
|
||||
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthNav", "RynthNavGetStatusJsonUtf8");
|
||||
_utf8 = _get != null;
|
||||
if (_get == null)
|
||||
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthNav", "RynthNavGetStatusJson");
|
||||
}
|
||||
if (_get == null) return;
|
||||
IntPtr ptr = _get();
|
||||
string? json = ptr == IntPtr.Zero ? null : _utf8 ? Marshal.PtrToStringUTF8(ptr) : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
RynthNavStatus? status = RynthNavStatus.Parse(json);
|
||||
if (status == null) return;
|
||||
_lastJson = json;
|
||||
Publish(status);
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_get = null;
|
||||
_utf8 = false;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
internal static unsafe class RynthNavCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<void> _loadTile, _testQuery;
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _preview, _goto, _command;
|
||||
private static delegate* unmanaged[Cdecl]<int, void> _move;
|
||||
|
||||
static RynthNavCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () => { _loadTile = null; _testQuery = null; _preview = null; _goto = null; _move = null; _command = null; };
|
||||
}
|
||||
|
||||
private static IntPtr Export(string name) => PluginExportBinder.Resolve("RynthNav", name);
|
||||
|
||||
private static void Run(string label, Action action) => UiDataHub.Post("RynthNav " + label, () =>
|
||||
{
|
||||
action();
|
||||
UiSources.RynthNav.RequestRefresh();
|
||||
});
|
||||
|
||||
public static void LoadTile() => Run("load tile", () =>
|
||||
{
|
||||
if (_loadTile == null) _loadTile = (delegate* unmanaged[Cdecl]<void>)Export("RynthNavLoadTile");
|
||||
if (_loadTile != null) _loadTile();
|
||||
});
|
||||
|
||||
public static void TestQuery() => Run("test", () =>
|
||||
{
|
||||
if (_testQuery == null) _testQuery = (delegate* unmanaged[Cdecl]<void>)Export("RynthNavTestQuery");
|
||||
if (_testQuery != null) _testQuery();
|
||||
});
|
||||
|
||||
/// <summary>Preview a route to a /loc coordinate ("42.5N, 33.6E").</summary>
|
||||
public static void Preview(string coord) => Run("preview", () =>
|
||||
{
|
||||
if (_preview == null) _preview = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthNavPreviewPath");
|
||||
if (_preview == null) return;
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(coord);
|
||||
try { _preview(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
});
|
||||
|
||||
/// <summary>Walk the navmesh path to a /loc coordinate.</summary>
|
||||
public static void Goto(string coord) => Run("go", () =>
|
||||
{
|
||||
if (_goto == null) _goto = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthNavGoto");
|
||||
if (_goto == null) return;
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(coord);
|
||||
try { _goto(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
});
|
||||
|
||||
/// <summary>1 forward, 2 back, 3 turn left, 4 turn right, 5 stop.</summary>
|
||||
public static void Move(int cmd) => Run("move", () =>
|
||||
{
|
||||
if (_move == null) _move = (delegate* unmanaged[Cdecl]<int, void>)Export("RynthNavMove");
|
||||
if (_move != null) _move(cmd);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A /rnav command without the "/rnav" ("arrow 42.08N, 33.60E Holtburg", "go Holtburg",
|
||||
/// "fav ...", "portals on"). RynthNav 0.6+ (RynthNavCommand); RynthNav queues it for its
|
||||
/// tick, so the status shows the result a poll or two later.
|
||||
/// </summary>
|
||||
public static void Command(string text) => Run("command", () =>
|
||||
{
|
||||
if (_command == null) _command = (delegate* unmanaged[Cdecl]<IntPtr, void>)Export("RynthNavCommand");
|
||||
if (_command == null) return;
|
||||
IntPtr p = Marshal.StringToCoTaskMemUTF8(text);
|
||||
try { _command(p); }
|
||||
finally { Marshal.FreeCoTaskMem(p); }
|
||||
});
|
||||
|
||||
public static void Arrow(string name, double ns, double ew) =>
|
||||
Command("arrow " + RynthNavStatus.CommandCoord(ns, ew) + " " + name);
|
||||
|
||||
public static void Go(string name, double ns, double ew) =>
|
||||
Command("go " + RynthNavStatus.CommandCoord(ns, ew) + " " + name);
|
||||
|
||||
public static void Route(string name, double ns, double ew) =>
|
||||
Command("route " + RynthNavStatus.CommandCoord(ns, ew) + " " + name);
|
||||
|
||||
public static void ToggleFavorite(string name, double ns, double ew) =>
|
||||
Command("fav " + RynthNavStatus.CommandCoord(ns, ew) + " " + name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the arrow overlay when a RynthNav command asks to show the arrow (any arrow
|
||||
/// set: /rnav arrow, go, the Atlas, the chat menu), even with every RynthNav face shut.
|
||||
/// RynthNavArrowSeq is one int; polled twice a second while RynthNav is loaded.
|
||||
/// </summary>
|
||||
internal sealed unsafe class RynthNavArrowWatch : UiSource<object>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<int> _get;
|
||||
private int _last = int.MinValue;
|
||||
private long _retryAtMs;
|
||||
|
||||
/// <summary>Set by the face registration: what to call when the arrow should show. Pump thread.</summary>
|
||||
public static Action? ShowArrow;
|
||||
|
||||
public RynthNavArrowWatch() : base("RynthNavArrowWatch", periodMs: 500) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_get == null)
|
||||
{
|
||||
// Not loaded yet, or an older RynthNav (no overlay auto-open): look again later.
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _retryAtMs) return;
|
||||
_get = (delegate* unmanaged[Cdecl]<int>)PluginExportBinder.Resolve("RynthNav", "RynthNavArrowSeq");
|
||||
if (_get == null) { _retryAtMs = now + 10000; return; }
|
||||
}
|
||||
int seq = _get();
|
||||
if (_last != int.MinValue && seq != _last) ShowArrow?.Invoke();
|
||||
_last = seq;
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_get = null;
|
||||
_retryAtMs = 0;
|
||||
_last = int.MinValue;
|
||||
}
|
||||
}
|
||||
679
src/RynthCore.Engine/UI/Data/SenseData.cs
Normal file
679
src/RynthCore.Engine/UI/Data/SenseData.cs
Normal file
|
|
@ -0,0 +1,679 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/SenseData.cs
|
||||
// Sense, our take on Virindi Sense: a watch list of names, and every object
|
||||
// the client knows about, anywhere, whose name matches one.
|
||||
//
|
||||
// SenseStore the watch list and the alert settings, in
|
||||
// %LocalAppData%\RynthCore\sense.txt (read and written on
|
||||
// UiBackgroundWriter, never on AC's render thread).
|
||||
// SensePattern one term, case-insensitive. Without wildcards the name only
|
||||
// has to contain it ("drake" finds "Dragon's Isle Drake");
|
||||
// with * or ? the whole name must match ("Drake*", "?ire Ant").
|
||||
// SenseSource the scan: on the plugin pump thread at 2 Hz, reading only the
|
||||
// engine's main-thread snapshots (LiveObjectIds, the identity,
|
||||
// position, PWD and attackable snapshots, the player pose),
|
||||
// never AC memory. Publishes an immutable SenseView and raises
|
||||
// the optional chat line / beep for a new match. Polled while
|
||||
// the Sense face is open, and while an alert is on with at least
|
||||
// one enabled term, so alerts work with the panel closed.
|
||||
//
|
||||
// How far it sees: the whole client object table, not a radar radius. The
|
||||
// client knows what the server has sent it, which is every object in the
|
||||
// landblocks it has loaded around you (outdoors on ACE: your 192 m landblock
|
||||
// and the eight around it, so a few hundred yards, far past the radar), or
|
||||
// the dungeon you are in.
|
||||
//
|
||||
// Distances: outdoors and in surface buildings the landblock grid is one
|
||||
// space (world = landblock x 192 m + cell-local origin). A dungeon has its own
|
||||
// space: a distance is shown only when you and the object are in the same
|
||||
// landblock, or both in the overworld; otherwise the row says "elsewhere" and
|
||||
// gives the landblock. A landblock counts as overworld when anything known in
|
||||
// it (or you) stands in an outdoor cell; indoor cells of a landblock with no
|
||||
// outdoor objects are taken for a dungeon.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>One watch-list term. Immutable.</summary>
|
||||
internal sealed class SensePattern
|
||||
{
|
||||
public SensePattern(string text, bool enabled)
|
||||
{
|
||||
Text = (text ?? string.Empty).Trim();
|
||||
Enabled = enabled;
|
||||
IsGlob = Text.IndexOfAny(Wildcards) >= 0;
|
||||
}
|
||||
|
||||
private static readonly char[] Wildcards = { '*', '?' };
|
||||
|
||||
public string Text { get; }
|
||||
public bool Enabled { get; }
|
||||
/// <summary>True when the term has * or ?: the whole name must match it.</summary>
|
||||
public bool IsGlob { get; }
|
||||
|
||||
public bool Matches(string name)
|
||||
{
|
||||
if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false;
|
||||
return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Case-insensitive whole-string match of <paramref name="s"/> against
|
||||
/// <paramref name="p"/> (* any run, ? one character). Iterative, backtracking
|
||||
/// only to the last *; no allocation.
|
||||
/// </summary>
|
||||
internal static bool Glob(string s, string p)
|
||||
{
|
||||
int si = 0, pi = 0, star = -1, mark = 0;
|
||||
while (si < s.Length)
|
||||
{
|
||||
if (pi < p.Length && p[pi] == '*') { star = pi++; mark = si; }
|
||||
else if (pi < p.Length && (p[pi] == '?' || Same(p[pi], s[si]))) { si++; pi++; }
|
||||
else if (star >= 0) { pi = star + 1; si = ++mark; }
|
||||
else return false;
|
||||
}
|
||||
while (pi < p.Length && p[pi] == '*') pi++;
|
||||
return pi == p.Length;
|
||||
}
|
||||
|
||||
private static bool Same(char a, char b) => a == b || char.ToUpperInvariant(a) == char.ToUpperInvariant(b);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The watch list and alert settings. Edited on AC's thread (the face, /rc sense),
|
||||
/// read by the scan on the pump thread: the term list is an immutable array
|
||||
/// swapped whole, with a version the scan compares. File I/O on UiBackgroundWriter.
|
||||
/// </summary>
|
||||
internal static class SenseStore
|
||||
{
|
||||
public const int MaxTerms = 40;
|
||||
public const int MaxTermLength = 64;
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static SensePattern[] _terms = Array.Empty<SensePattern>();
|
||||
private static long _version;
|
||||
private static volatile bool _loaded;
|
||||
private static bool _loadQueued;
|
||||
private static volatile bool _alertChat;
|
||||
private static volatile bool _alertBeep;
|
||||
private static bool _alertSubscribed;
|
||||
|
||||
/// <summary>The current terms (never null; do not modify). Any thread.</summary>
|
||||
public static SensePattern[] Terms => Volatile.Read(ref _terms);
|
||||
|
||||
/// <summary>Bumped on every change to the terms. Any thread.</summary>
|
||||
public static long Version => Interlocked.Read(ref _version);
|
||||
|
||||
public static bool Loaded => _loaded;
|
||||
|
||||
/// <summary>A chat line when a new match appears (off by default).</summary>
|
||||
public static bool AlertChat => _alertChat;
|
||||
|
||||
/// <summary>The system beep when a new match appears (off by default).</summary>
|
||||
public static bool AlertBeep => _alertBeep;
|
||||
|
||||
public static bool AnyEnabled
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (SensePattern t in Terms)
|
||||
if (t.Enabled && t.Text.Length > 0) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string FilePath =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "sense.txt");
|
||||
|
||||
/// <summary>Queues the one-time read off the calling thread. Any thread; cheap after the first call.</summary>
|
||||
public static void EnsureLoadQueued()
|
||||
{
|
||||
if (_loaded) return;
|
||||
lock (Sync)
|
||||
{
|
||||
if (_loadQueued) return;
|
||||
_loadQueued = true;
|
||||
}
|
||||
UiBackgroundWriter.Enqueue("sense list (load)", LoadNow);
|
||||
}
|
||||
|
||||
private static void LoadNow()
|
||||
{
|
||||
var list = new List<SensePattern>();
|
||||
bool chat = false, beep = false;
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
foreach (string raw in File.ReadAllLines(path))
|
||||
{
|
||||
string line = raw.Trim();
|
||||
if (line.Length == 0 || line.StartsWith('#')) continue;
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
string key = line[..eq].Trim();
|
||||
string val = line[(eq + 1)..];
|
||||
switch (key)
|
||||
{
|
||||
case "alertChat": chat = val.Trim() == "1"; break;
|
||||
case "alertBeep": beep = val.Trim() == "1"; break;
|
||||
case "term":
|
||||
{
|
||||
// term=1|pattern (1 on, 0 off); a bare term=pattern is on.
|
||||
bool on = true;
|
||||
string text = val;
|
||||
int bar = val.IndexOf('|');
|
||||
if (bar is 1 && (val[0] == '0' || val[0] == '1'))
|
||||
{
|
||||
on = val[0] == '1';
|
||||
text = val[2..];
|
||||
}
|
||||
text = Clean(text);
|
||||
if (text.Length > 0 && list.Count < MaxTerms && IndexOf(list, text) < 0)
|
||||
list.Add(new SensePattern(text, on));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.UI($"Sense: reading sense.txt failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
|
||||
lock (Sync)
|
||||
{
|
||||
Volatile.Write(ref _terms, list.ToArray());
|
||||
_alertChat = chat;
|
||||
_alertBeep = beep;
|
||||
Interlocked.Increment(ref _version);
|
||||
_loaded = true;
|
||||
}
|
||||
SyncAlertSubscription();
|
||||
}
|
||||
|
||||
private static string Clean(string text)
|
||||
{
|
||||
text = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim();
|
||||
return text.Length > MaxTermLength ? text[..MaxTermLength] : text;
|
||||
}
|
||||
|
||||
private static int IndexOf(IReadOnlyList<SensePattern> list, string text)
|
||||
{
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
if (string.Equals(list[i].Text, text, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a term (switched on). An existing term with the same text is switched
|
||||
/// on instead. False when the text is empty, the list is full or not loaded yet.
|
||||
/// </summary>
|
||||
public static bool Add(string text, out string message)
|
||||
{
|
||||
text = Clean(text);
|
||||
if (!_loaded) { message = "The watch list is still loading."; return false; }
|
||||
if (text.Length == 0) { message = "Type a name first."; return false; }
|
||||
lock (Sync)
|
||||
{
|
||||
SensePattern[] cur = _terms;
|
||||
int at = IndexOf(cur, text);
|
||||
if (at >= 0)
|
||||
{
|
||||
message = cur[at].Enabled ? $"\"{cur[at].Text}\" is already on the list." : $"\"{cur[at].Text}\" switched on.";
|
||||
if (!cur[at].Enabled) Replace(at, new SensePattern(cur[at].Text, true));
|
||||
return true;
|
||||
}
|
||||
if (cur.Length >= MaxTerms) { message = $"The list is full ({MaxTerms} terms)."; return false; }
|
||||
var next = new SensePattern[cur.Length + 1];
|
||||
Array.Copy(cur, next, cur.Length);
|
||||
next[^1] = new SensePattern(text, true);
|
||||
Publish(next);
|
||||
message = $"Watching for \"{text}\".";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetEnabled(int index, bool enabled)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
SensePattern[] cur = _terms;
|
||||
if ((uint)index >= (uint)cur.Length || cur[index].Enabled == enabled) return;
|
||||
Replace(index, new SensePattern(cur[index].Text, enabled));
|
||||
}
|
||||
}
|
||||
|
||||
public static void Remove(int index)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
SensePattern[] cur = _terms;
|
||||
if ((uint)index >= (uint)cur.Length) return;
|
||||
var next = new SensePattern[cur.Length - 1];
|
||||
Array.Copy(cur, 0, next, 0, index);
|
||||
Array.Copy(cur, index + 1, next, index, cur.Length - index - 1);
|
||||
Publish(next);
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetAlerts(bool chat, bool beep)
|
||||
{
|
||||
if (chat == _alertChat && beep == _alertBeep) return;
|
||||
_alertChat = chat;
|
||||
_alertBeep = beep;
|
||||
SyncAlertSubscription();
|
||||
Save();
|
||||
}
|
||||
|
||||
// Under Sync.
|
||||
private static void Replace(int index, SensePattern pattern)
|
||||
{
|
||||
var next = (SensePattern[])_terms.Clone();
|
||||
next[index] = pattern;
|
||||
Publish(next);
|
||||
}
|
||||
|
||||
// Under Sync.
|
||||
private static void Publish(SensePattern[] next)
|
||||
{
|
||||
Volatile.Write(ref _terms, next);
|
||||
Interlocked.Increment(ref _version);
|
||||
UiSources.Sense.RequestRefresh();
|
||||
SyncAlertSubscription();
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the scan running with the panel closed while an alert is on and a term
|
||||
/// is enabled (one subscription of its own). Any thread.
|
||||
/// </summary>
|
||||
public static void SyncAlertSubscription()
|
||||
{
|
||||
bool want = _loaded && (_alertChat || _alertBeep) && AnyEnabled;
|
||||
lock (Sync)
|
||||
{
|
||||
if (want == _alertSubscribed) return;
|
||||
_alertSubscribed = want;
|
||||
if (want) UiSources.Sense.Subscribe();
|
||||
else UiSources.Sense.Unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes the list in the background. Any thread.</summary>
|
||||
public static void Save()
|
||||
{
|
||||
if (!_loaded) return; // never overwrite the file with the empty pre-load list
|
||||
UiBackgroundWriter.Enqueue("sense list", SaveNow);
|
||||
}
|
||||
|
||||
private static void SaveNow()
|
||||
{
|
||||
try
|
||||
{
|
||||
SensePattern[] terms = Terms;
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game.");
|
||||
sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches.");
|
||||
sb.AppendLine(_alertChat ? "alertChat=1" : "alertChat=0");
|
||||
sb.AppendLine(_alertBeep ? "alertBeep=1" : "alertBeep=0");
|
||||
foreach (SensePattern t in terms)
|
||||
sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text);
|
||||
string path = FilePath;
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(path, sb.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.UI($"Sense: writing sense.txt failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal enum SenseKind : byte { Monster, Npc, Player, Item, Portal, Corpse }
|
||||
|
||||
/// <summary>One match, with its texts built by the scan. Immutable once published.</summary>
|
||||
internal sealed class SenseRow
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = "";
|
||||
public SenseKind Kind;
|
||||
/// <summary>True when a distance and bearing mean something (same space as you).</summary>
|
||||
public bool Measured;
|
||||
public float Distance; // yd (= m); +inf when not measured
|
||||
public float Bearing = float.NaN; // compass degrees from you, 0 = North, clockwise; NaN unknown / on top of you
|
||||
public string DistanceText = "";
|
||||
public string CompassText = "";
|
||||
public string LocationText = "";
|
||||
public string Tooltip = "";
|
||||
/// <summary>Environment.TickCount64 when the match first appeared (0 = was already there when the scan started).</summary>
|
||||
public long FirstSeenMs;
|
||||
}
|
||||
|
||||
/// <summary>A published scan.</summary>
|
||||
internal sealed class SenseView
|
||||
{
|
||||
public static readonly SenseView Empty = new(Array.Empty<SenseRow>(), "", 0);
|
||||
|
||||
public SenseView(SenseRow[] rows, string status, int known)
|
||||
{
|
||||
Rows = rows;
|
||||
Status = status;
|
||||
Known = known;
|
||||
}
|
||||
|
||||
public SenseRow[] Rows { get; }
|
||||
public string Status { get; }
|
||||
/// <summary>Objects in the client's table at the scan.</summary>
|
||||
public int Known { get; }
|
||||
}
|
||||
|
||||
/// <summary>The Sense scan (see the file header). Pump thread.</summary>
|
||||
internal sealed class SenseSource : UiSource<SenseView>
|
||||
{
|
||||
public SenseSource() : base("Sense", periodMs: 500) { }
|
||||
|
||||
private const uint TypeCreature = 0x10, TypePortal = 0x10000;
|
||||
private const uint BfPlayer = 0x8, BfCorpse = 0x2000, BfPortal = 0x40000;
|
||||
private const float LandblockSize = 192f;
|
||||
private const int MaxRows = 300;
|
||||
private const int MaxAlertLines = 3;
|
||||
private const long AlertCooldownMs = 120_000; // the same object again within this: no second alert
|
||||
private const long GapMs = 3000; // longer between polls: the scan was off, nothing is "new"
|
||||
private const int ChatType = 1; // the colour of RynthCore's own replies
|
||||
|
||||
private static readonly string[] Compass16 = { "N", "NE", "NE", "E", "E", "SE", "SE", "S", "S", "SW", "SW", "W", "W", "NW", "NW", "N" };
|
||||
|
||||
private long _lastPollMs;
|
||||
private long _seenVersion = -1;
|
||||
private Dictionary<uint, long> _firstSeen = new();
|
||||
private Dictionary<uint, long> _firstSeenNext = new();
|
||||
private readonly Dictionary<uint, long> _lastAlertMs = new();
|
||||
private long _nextAlertPruneMs;
|
||||
private long _lastBeepMs;
|
||||
private readonly List<(uint Id, string Name, SensePattern Term)> _hits = new();
|
||||
private readonly HashSet<uint> _overworldBlocks = new();
|
||||
private readonly List<SenseRow> _rows = new();
|
||||
private readonly List<SenseRow> _alerts = new();
|
||||
|
||||
[DllImport("user32.dll")] private static extern bool MessageBeep(uint uType);
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
bool gap = _lastPollMs == 0 || now - _lastPollMs > GapMs;
|
||||
_lastPollMs = now;
|
||||
|
||||
if (!SenseStore.Loaded) { PublishStatus("Loading the watch list...", 0); return; }
|
||||
|
||||
SensePattern[] terms = SenseStore.Terms;
|
||||
long version = SenseStore.Version;
|
||||
bool termsChanged = version != _seenVersion;
|
||||
_seenVersion = version;
|
||||
|
||||
int enabled = 0;
|
||||
foreach (SensePattern t in terms) if (t.Enabled && t.Text.Length > 0) enabled++;
|
||||
if (enabled == 0)
|
||||
{
|
||||
_firstSeen.Clear();
|
||||
PublishStatus(terms.Length == 0 ? "Add a name to watch for." : "Every term is switched off.", 0);
|
||||
return;
|
||||
}
|
||||
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (playerId == 0 || !LoginLifecycleHooks.HasObservedLoginComplete || LogoutLifecycleHooks.HasObservedLogout)
|
||||
{
|
||||
_firstSeen.Clear();
|
||||
PublishStatus("Not in the world.", 0);
|
||||
return;
|
||||
}
|
||||
if (TeleportStateHooks.IsPortaling)
|
||||
{
|
||||
PublishStatus("In portal space...", 0);
|
||||
return;
|
||||
}
|
||||
// Position only: the face turns the arrows with the heading of the frame it draws.
|
||||
if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out uint pCell, out float px, out float py, out float pz,
|
||||
out _, out _, out _, out _) || (pCell >> 16) == 0)
|
||||
{
|
||||
PublishStatus("Waiting for your position...", 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// Pass 1: names only (a dictionary lookup per id).
|
||||
uint[] ids = ClientObjectHooks.LiveObjectIds;
|
||||
_hits.Clear();
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
uint id = ids[i];
|
||||
if (id == 0 || id == playerId) continue;
|
||||
if (!ClientObjectHooks.TryGetSnapshotName(id, out string name) || name.Length == 0) continue;
|
||||
foreach (SensePattern t in terms)
|
||||
{
|
||||
if (!t.Enabled || !t.Matches(name)) continue;
|
||||
_hits.Add((id, name, t));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Which landblocks are overworld (only needed when someone stands indoors).
|
||||
_overworldBlocks.Clear();
|
||||
bool needBlocks = !IsOutdoorCell(pCell);
|
||||
if (!needBlocks)
|
||||
{
|
||||
foreach (var h in _hits)
|
||||
if (ClientObjectHooks.TryGetSnapshotPosition(h.Id, out uint c, out _, out _, out _) && !IsOutdoorCell(c)) { needBlocks = true; break; }
|
||||
}
|
||||
if (needBlocks)
|
||||
{
|
||||
if (IsOutdoorCell(pCell)) _overworldBlocks.Add(pCell >> 16);
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
if (ClientObjectHooks.TryGetSnapshotPosition(ids[i], out uint c, out _, out _, out _) && (c >> 16) != 0 && IsOutdoorCell(c))
|
||||
_overworldBlocks.Add(c >> 16);
|
||||
}
|
||||
bool playerOverworld = IsOverworld(pCell);
|
||||
|
||||
// Pass 2: rows for the hits that stand somewhere (not in a pack, not wielded).
|
||||
_rows.Clear();
|
||||
_alerts.Clear();
|
||||
_firstSeenNext.Clear();
|
||||
bool flashNew = !gap;
|
||||
bool alertNew = !gap && !termsChanged && (SenseStore.AlertChat || SenseStore.AlertBeep);
|
||||
foreach (var h in _hits)
|
||||
{
|
||||
if (_rows.Count >= MaxRows) break;
|
||||
if (!ClientObjectHooks.TryGetSnapshotPosition(h.Id, out uint cell, out float x, out float y, out float z) || (cell >> 16) == 0)
|
||||
continue;
|
||||
bool hasPwd = ClientObjectHooks.TryGetSnapshotPwdInfo(h.Id, out uint bf, out uint container, out uint wielder);
|
||||
if (hasPwd && (container != 0 || wielder != 0)) continue;
|
||||
|
||||
var row = new SenseRow { Id = h.Id, Name = h.Name, Kind = Classify(h.Id, hasPwd ? bf : 0) };
|
||||
bool objOverworld = IsOverworld(cell);
|
||||
row.Measured = (cell >> 16) == (pCell >> 16) || (playerOverworld && objOverworld);
|
||||
uint lb = cell >> 16;
|
||||
string coords = objOverworld ? Coords(cell, x, y) : "";
|
||||
if (row.Measured)
|
||||
{
|
||||
Offset(pCell, cell, out float ox, out float oy);
|
||||
float dx = x + ox - px, dy = y + oy - py, dz = z - pz;
|
||||
row.Distance = MathF.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||
float flat = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (flat >= 0.5f)
|
||||
{
|
||||
float b = MathF.Atan2(dx, dy) * (180f / MathF.PI);
|
||||
row.Bearing = b < 0 ? b + 360f : b;
|
||||
row.CompassText = Compass16[(int)(row.Bearing / 22.5f) & 15];
|
||||
}
|
||||
else
|
||||
{
|
||||
row.CompassText = "here";
|
||||
}
|
||||
row.DistanceText = row.Distance.ToString("0", CultureInfo.InvariantCulture) + " yd";
|
||||
row.LocationText = objOverworld ? coords : "LB " + lb.ToString("X4", CultureInfo.InvariantCulture);
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Distance = float.PositiveInfinity;
|
||||
row.DistanceText = "elsewhere";
|
||||
row.CompassText = "";
|
||||
row.LocationText = objOverworld
|
||||
? coords + " (LB " + lb.ToString("X4", CultureInfo.InvariantCulture) + ")"
|
||||
: "dungeon LB " + lb.ToString("X4", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
bool isNew;
|
||||
if (_firstSeen.TryGetValue(h.Id, out long first)) { isNew = false; }
|
||||
else { isNew = true; first = flashNew ? now : 0; }
|
||||
row.FirstSeenMs = first;
|
||||
_firstSeenNext[h.Id] = first;
|
||||
row.Tooltip = BuildTooltip(row, h.Term, cell, coords);
|
||||
_rows.Add(row);
|
||||
|
||||
if (isNew && alertNew && (!_lastAlertMs.TryGetValue(h.Id, out long last) || now - last > AlertCooldownMs))
|
||||
{
|
||||
_lastAlertMs[h.Id] = now;
|
||||
_alerts.Add(row);
|
||||
}
|
||||
}
|
||||
(_firstSeen, _firstSeenNext) = (_firstSeenNext, _firstSeen);
|
||||
|
||||
_rows.Sort(static (a, b) =>
|
||||
{
|
||||
int c = a.Distance.CompareTo(b.Distance);
|
||||
return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
|
||||
RaiseAlerts(now);
|
||||
|
||||
string status = _rows.Count switch
|
||||
{
|
||||
0 => $"No matches among {ids.Length:N0} objects the client knows.",
|
||||
1 => $"1 match among {ids.Length:N0} objects the client knows.",
|
||||
_ => $"{_rows.Count:N0} matches among {ids.Length:N0} objects the client knows.",
|
||||
};
|
||||
Publish(new SenseView(_rows.ToArray(), status, ids.Length));
|
||||
}
|
||||
|
||||
private void PublishStatus(string status, int known)
|
||||
{
|
||||
SenseView? cur = Current?.Value;
|
||||
if (cur != null && cur.Rows.Length == 0 && cur.Status == status) return;
|
||||
Publish(new SenseView(Array.Empty<SenseRow>(), status, known));
|
||||
}
|
||||
|
||||
private void RaiseAlerts(long now)
|
||||
{
|
||||
if (now >= _nextAlertPruneMs)
|
||||
{
|
||||
_nextAlertPruneMs = now + 60_000;
|
||||
List<uint>? stale = null;
|
||||
foreach (var kv in _lastAlertMs)
|
||||
if (now - kv.Value > AlertCooldownMs) (stale ??= new List<uint>()).Add(kv.Key);
|
||||
if (stale != null) foreach (uint id in stale) _lastAlertMs.Remove(id);
|
||||
}
|
||||
if (_alerts.Count == 0) return;
|
||||
|
||||
if (SenseStore.AlertChat)
|
||||
{
|
||||
_alerts.Sort(static (a, b) => a.Distance.CompareTo(b.Distance));
|
||||
int shown = Math.Min(MaxAlertLines, _alerts.Count);
|
||||
for (int i = 0; i < shown; i++)
|
||||
{
|
||||
SenseRow r = _alerts[i];
|
||||
string where = r.Measured
|
||||
? r.DistanceText + (r.CompassText.Length > 0 && r.CompassText != "here" ? " " + r.CompassText : "")
|
||||
: "elsewhere (" + r.LocationText + ")";
|
||||
AcMainThreadQueue.EnqueueWriteToChat("Sense: " + r.Name + " " + where, ChatType);
|
||||
}
|
||||
if (_alerts.Count > shown)
|
||||
AcMainThreadQueue.EnqueueWriteToChat($"Sense: and {_alerts.Count - shown} more (open the Sense panel).", ChatType);
|
||||
}
|
||||
if (SenseStore.AlertBeep && now - _lastBeepMs > 3000)
|
||||
{
|
||||
_lastBeepMs = now;
|
||||
try { MessageBeep(0x40); } catch { } // MB_ICONASTERISK; queued, returns at once
|
||||
}
|
||||
}
|
||||
|
||||
private static SenseKind Classify(uint id, uint bitfield)
|
||||
{
|
||||
if ((bitfield & BfPlayer) != 0) return SenseKind.Player;
|
||||
if ((bitfield & BfCorpse) != 0) return SenseKind.Corpse;
|
||||
ClientObjectHooks.TryGetSnapshotItemType(id, out uint type);
|
||||
if ((type & TypePortal) != 0 || (bitfield & BfPortal) != 0) return SenseKind.Portal;
|
||||
if ((type & TypeCreature) != 0)
|
||||
return ClientObjectHooks.TryGetSnapshotAttackable(id, out bool attackable) && attackable ? SenseKind.Monster : SenseKind.Npc;
|
||||
return SenseKind.Item;
|
||||
}
|
||||
|
||||
public static string KindName(SenseKind kind) => kind switch
|
||||
{
|
||||
SenseKind.Monster => "Monster",
|
||||
SenseKind.Npc => "NPC",
|
||||
SenseKind.Player => "Player",
|
||||
SenseKind.Portal => "Portal",
|
||||
SenseKind.Corpse => "Corpse",
|
||||
_ => "Item",
|
||||
};
|
||||
|
||||
private static bool IsOutdoorCell(uint cell) => (cell & 0xFFFF) < 0x100;
|
||||
|
||||
private bool IsOverworld(uint cell) => IsOutdoorCell(cell) || _overworldBlocks.Contains(cell >> 16);
|
||||
|
||||
/// <summary>Metres from the player's landblock origin to <paramref name="cell"/>'s (192 m per landblock step).</summary>
|
||||
private static void Offset(uint fromCell, uint cell, out float ox, out float oy)
|
||||
{
|
||||
int dxb = (int)((cell >> 24) & 0xFF) - (int)((fromCell >> 24) & 0xFF);
|
||||
int dyb = (int)((cell >> 16) & 0xFF) - (int)((fromCell >> 16) & 0xFF);
|
||||
ox = dxb * LandblockSize;
|
||||
oy = dyb * LandblockSize;
|
||||
}
|
||||
|
||||
/// <summary>"42.1N 33.6E" (PlayerPhysicsHooks.TryGetLiveCoords' basis).</summary>
|
||||
internal static string Coords(uint cell, float x, float y)
|
||||
{
|
||||
int lbX = (int)((cell >> 24) & 0xFF), lbY = (int)((cell >> 16) & 0xFF);
|
||||
double ew = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
|
||||
double ns = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
|
||||
return Math.Abs(ns).ToString("0.0", CultureInfo.InvariantCulture) + (ns >= 0 ? "N " : "S ")
|
||||
+ Math.Abs(ew).ToString("0.0", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
|
||||
}
|
||||
|
||||
private static string BuildTooltip(SenseRow r, SensePattern term, uint cell, string coords)
|
||||
{
|
||||
var sb = new StringBuilder(160);
|
||||
sb.Append(r.Name).Append('\n');
|
||||
sb.Append(KindName(r.Kind)).Append(" 0x").Append(r.Id.ToString("X8", CultureInfo.InvariantCulture)).Append('\n');
|
||||
if (r.Measured)
|
||||
{
|
||||
sb.Append(r.DistanceText);
|
||||
if (!float.IsNaN(r.Bearing))
|
||||
sb.Append(' ').Append(r.CompassText).Append(" (bearing ").Append(r.Bearing.ToString("0", CultureInfo.InvariantCulture)).Append("°)");
|
||||
else
|
||||
sb.Append(", right here");
|
||||
sb.Append('\n');
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append("Elsewhere: not in the same space as you (another dungeon or landblock), so no distance.\n");
|
||||
}
|
||||
if (coords.Length > 0) sb.Append(coords).Append(" ");
|
||||
sb.Append("landblock ").Append((cell >> 16).ToString("X4", CultureInfo.InvariantCulture))
|
||||
.Append(", cell 0x").Append(cell.ToString("X8", CultureInfo.InvariantCulture)).Append('\n');
|
||||
sb.Append("Matches \"").Append(term.Text).Append("\"\n");
|
||||
sb.Append("Click to select it.");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
709
src/RynthCore.Engine/UI/Data/SettingsData.cs
Normal file
709
src/RynthCore.Engine/UI/Data/SettingsData.cs
Normal file
|
|
@ -0,0 +1,709 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/SettingsData.cs
|
||||
// RynthAi's Advanced Settings (docs/IMGUI_PARITY_PLAN.md §2.4): the payload,
|
||||
// its hub source and save command, and the ONE schema both faces draw from
|
||||
// (UI/Panels/SettingsPanel.cs, ImGui/Panels/SettingsFace.cs).
|
||||
//
|
||||
// To add a setting: add the property to RynthAiSettings (it must match
|
||||
// RynthAi's SettingsBridgePayload) and a row to SettingsSchema.Tabs. Both
|
||||
// faces pick it up. The payload always carries every property, so a save
|
||||
// can't send a field missing (RynthAi applied missing fields as 0, 2026-09-27).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>Mirrors RynthAi's SettingsBridgePayload (RynthPluginGet/SetSettingsJson).</summary>
|
||||
internal sealed class RynthAiSettings
|
||||
{
|
||||
// Display
|
||||
public bool ShowTargetStaminaMana { get; set; }
|
||||
// UI
|
||||
public bool SuppressRetailRadar { get; set; }
|
||||
// No rows (RynthAi's plugin-drawn radar/chat windows are gone); kept so the payload
|
||||
// still carries them - a field missing from a save is applied as false.
|
||||
public bool ShowRynthRadar { get; set; }
|
||||
public bool RadarClickThrough { get; set; }
|
||||
// Retail-chatbox suppression is owned by the RynthChat plugin ("Hide retail chat"
|
||||
// in its gear menu); routing it through RynthAi's settings push fought that toggle.
|
||||
public bool ShowRynthChat { get; set; }
|
||||
public bool ChatClickThrough { get; set; }
|
||||
public bool SuppressRetailPowerbar { get; set; }
|
||||
// Misc
|
||||
public bool EnableFPSLimit { get; set; }
|
||||
public int TargetFPSFocused { get; set; } = 60;
|
||||
public int TargetFPSBackground { get; set; } = 30;
|
||||
public bool EnableAutocram { get; set; }
|
||||
public bool PeaceModeWhenIdle { get; set; }
|
||||
public bool StartMacroOnLogin { get; set; }
|
||||
public bool PatrolOnLogin { get; set; }
|
||||
// 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;
|
||||
public bool EnableRaycasting { get; set; }
|
||||
public bool UseArcs { get; set; }
|
||||
public float BowArcVelocity { get; set; } = 25f;
|
||||
public float MissileArcClearance { get; set; } = 0.5f;
|
||||
// Vendoring (RynthAi AutoVendor; defaults match LegacyUiSettings)
|
||||
public bool AutoVendorEnabled { get; set; }
|
||||
public bool AutoVendorEnableBuying { get; set; } = true;
|
||||
public bool AutoVendorEnableSelling { get; set; } = true;
|
||||
public bool AutoVendorTestMode { get; set; } = true;
|
||||
public bool AutoVendorThink { get; set; }
|
||||
public bool AutoVendorShowMerchantInfo { get; set; } = true;
|
||||
public bool AutoVendorOnlyFromMainPack { get; set; }
|
||||
public int AutoVendorTries { get; set; } = 4;
|
||||
public int AutoVendorTriesTime { get; set; } = 5000;
|
||||
public bool LosDebugLog { get; set; }
|
||||
public float CrossbowArcVelocity { get; set; } = 40f;
|
||||
public float AtlatlArcVelocity { get; set; } = 22f;
|
||||
// Arc spells' horizontal speed: ACE flies every player arc at 40 m/s across the ground.
|
||||
public float MagicArcVelocity { get; set; } = 40f;
|
||||
public int BlacklistAttempts { get; set; } = 3;
|
||||
public int BlacklistTimeoutSec { get; set; } = 30;
|
||||
// Not shown in the panel, but carried so a save doesn't send them missing.
|
||||
public int BlacklistCastSettleMs { get; set; } = 1500;
|
||||
public int MonsterDisengageRange { get; set; }
|
||||
public int TargetNoProgressTimeoutSec { get; set; }
|
||||
public int GiveQueueIntervalMs { get; set; } = 150;
|
||||
// Recharge
|
||||
public int HealAt { get; set; } = 60;
|
||||
public int RestamAt { get; set; } = 30;
|
||||
public int GetManaAt { get; set; } = 40;
|
||||
public int TopOffHP { get; set; } = 95;
|
||||
public int TopOffStam { get; set; } = 95;
|
||||
public int TopOffMana { get; set; } = 95;
|
||||
public int HealOthersAt { get; set; } = 50;
|
||||
public int RestamOthersAt { get; set; } = 10;
|
||||
public int InfuseOthersAt { get; set; } = 10;
|
||||
// Kits, potions and safety stops
|
||||
public bool UsePotions { get; set; } = true;
|
||||
public bool UseBuffItems { get; set; } = true;
|
||||
public int MakeRationsBelow { get; set; } = 5;
|
||||
public bool UseKitsInMagicMode { get; set; } = true;
|
||||
public bool PeaceModeForKits { get; set; }
|
||||
public int KitMinSuccessPct { get; set; } = 70;
|
||||
public int EmergencyHealAt { get; set; } = 30;
|
||||
public int StaminaToHealthAt { get; set; } = 30;
|
||||
public int StaminaToHealthMinStamina { get; set; } = 20;
|
||||
public bool StopMacroOnDeath { get; set; }
|
||||
public bool StopMacroOnNoComponents { get; set; }
|
||||
public bool StopLootingWhenPackFull { get; set; } = true;
|
||||
public bool StopMacroWhenPackFull { get; set; }
|
||||
// Melee Combat
|
||||
public bool UseRecklessness { get; set; }
|
||||
public int MeleeAttackPower { get; set; } = -1;
|
||||
public int MeleeAttackHeight { get; set; } = 1;
|
||||
public int MissileAttackPower { get; set; } = -1;
|
||||
public int MissileAttackHeight { get; set; } = 1;
|
||||
public bool UseNativeAttack { get; set; } = true;
|
||||
public bool SummonPets { get; set; }
|
||||
public int PetMinMonsters { get; set; } = 1;
|
||||
// Spell Combat
|
||||
public int SpellCastIntervalMs { get; set; } = 400;
|
||||
public int AttackSpellIntervalMs { get; set; } = 1500;
|
||||
public bool CastDispelSelf { get; set; }
|
||||
public int MinRingTargets { get; set; } = 4;
|
||||
public int BlastRange { get; set; }
|
||||
public int MinBlastTargets { get; set; } = 3;
|
||||
public int MinSkillLevelTier1 { get; set; } = 35;
|
||||
public int MinSkillLevelTier2 { get; set; } = 85;
|
||||
public int MinSkillLevelTier3 { get; set; } = 135;
|
||||
public int MinSkillLevelTier4 { get; set; } = 185;
|
||||
public int MinSkillLevelTier5 { get; set; } = 235;
|
||||
public int MinSkillLevelTier6 { get; set; } = 285;
|
||||
public int MinSkillLevelTier7 { get; set; } = 335;
|
||||
public int MinSkillLevelTier8 { get; set; } = 435;
|
||||
// Ranges
|
||||
public int MonsterRange { get; set; } = 50;
|
||||
public int RingRange { get; set; } = 5;
|
||||
public int ApproachRange { get; set; } = 4;
|
||||
public double CorpseApproachRangeMax { get; set; } = 10.0;
|
||||
public double CorpseApproachRangeMin { get; set; } = 2.0;
|
||||
// Navigation
|
||||
public bool BoostNavPriority { get; set; }
|
||||
public float FollowNavMin { get; set; } = 1.5f;
|
||||
public float NavRingThickness { get; set; } = 6f;
|
||||
public float NavLineThickness { get; set; } = 6f;
|
||||
public float NavHeightOffset { get; set; } = 0.05f;
|
||||
public float NavSlopeSink { get; set; } = 1.5f;
|
||||
public bool ShowTerrainPassability { get; set; } = true;
|
||||
public bool OpenDoors { get; set; }
|
||||
public float OpenDoorRange { get; set; } = 5f;
|
||||
public bool AutoUnlockDoors { get; set; }
|
||||
public int MovementMode { get; set; }
|
||||
public float NavStopTurnAngle { get; set; } = 20f;
|
||||
public float NavResumeTurnAngle { get; set; } = 10f;
|
||||
public float NavDeadZone { get; set; } = 4f;
|
||||
public float NavSweepMult { get; set; } = 2.5f;
|
||||
public float NavLookaheadYards { get; set; } = 4f;
|
||||
public float NavShortcutYards { get; set; } = 1f;
|
||||
public float NavTurnRateDegPerSec { get; set; } = 270f;
|
||||
public float NavTier1TurnSpeed { get; set; } = 3f;
|
||||
public float PostPortalDelaySec { get; set; } = 4f;
|
||||
public float T2Speed { get; set; } = 1f;
|
||||
public float T2WalkWithinYd { get; set; } = 5f;
|
||||
public float T2DistanceTo { get; set; } = 0.5f;
|
||||
public float T2ReissueMs { get; set; } = 2000f;
|
||||
public float T2MaxRangeYd { get; set; } = 500f;
|
||||
public int T2MaxLandblocks { get; set; } = 3;
|
||||
// Buffing
|
||||
public bool EnableBuffing { get; set; } = true;
|
||||
public bool RebuffWhenIdle { get; set; }
|
||||
public int RebuffSecondsRemaining { get; set; } = 300;
|
||||
public int RebuffTopOffSecondsRemaining { get; set; } = 1200;
|
||||
public int BuffMinSkillLevelTier1 { get; set; } = 35;
|
||||
public int BuffMinSkillLevelTier2 { get; set; } = 85;
|
||||
public int BuffMinSkillLevelTier3 { get; set; } = 135;
|
||||
public int BuffMinSkillLevelTier4 { get; set; } = 185;
|
||||
public int BuffMinSkillLevelTier5 { get; set; } = 235;
|
||||
public int BuffMinSkillLevelTier6 { get; set; } = 285;
|
||||
public int BuffMinSkillLevelTier7 { get; set; } = 335;
|
||||
public int BuffMinSkillLevelTier8 { get; set; } = 435;
|
||||
// Crafting
|
||||
public bool EnableMissileCrafting { get; set; } = true;
|
||||
public string MissileCraftingState { get; set; } = string.Empty;
|
||||
public bool MissileCraftingActive { get; set; }
|
||||
public string MissileCraftingStatus { get; set; } = string.Empty;
|
||||
// Looting
|
||||
public bool EnableLooting { get; set; }
|
||||
public bool BoostLootPriority { get; set; }
|
||||
public bool LootOnlyRareCorpses { get; set; }
|
||||
public bool LootJumpEnabled { get; set; }
|
||||
public int LootJumpHeight { get; set; } = 10;
|
||||
public int LootOwnership { get; set; }
|
||||
public bool EnableAutostack { get; set; } = true;
|
||||
public bool ReadUnknownScrolls { get; set; } = true; // VTank's default
|
||||
public bool EnableCombineSalvage { get; set; } = true;
|
||||
public bool CombineBagsDuringSalvage { get; set; } = true;
|
||||
public int LootInterItemDelayMs { get; set; } = 50;
|
||||
public int LootContentSettleMs { get; set; } = 100;
|
||||
public int LootEmptyCorpseMs { get; set; } = 300;
|
||||
public int LootClosingDelayMs { get; set; } = 200;
|
||||
public int LootAssessWindowMs { get; set; } = 200;
|
||||
public int LootRetryTimeoutMs { get; set; } = 500;
|
||||
public int LootOpenRetryMs { get; set; } = 1500;
|
||||
public int LootCorpseTimeoutMs { get; set; } = 12000;
|
||||
public int SalvageOpenDelayFirstMs { get; set; } = 400;
|
||||
public int SalvageOpenDelayFastMs { get; set; } = 50;
|
||||
public int SalvageAddDelayFirstMs { get; set; } = 600;
|
||||
public int SalvageAddDelayFastMs { get; set; } = 50;
|
||||
public int SalvageSalvageDelayMs { get; set; } = 50;
|
||||
public int SalvageResultDelayFirstMs { get; set; } = 1000;
|
||||
public int SalvageResultDelayFastMs { get; set; } = 250;
|
||||
|
||||
/// <summary>A private copy for a face to edit (all members are values or strings).</summary>
|
||||
public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone();
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(RynthAiSettings))]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
|
||||
internal partial class RynthAiSettingsJsonContext : JsonSerializerContext { }
|
||||
|
||||
/// <summary>RynthPluginGetSettingsJson while a Settings face is open (5 s, and right after each save).</summary>
|
||||
internal sealed unsafe class SettingsSource : UiSource<RynthAiSettings>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _getSettingsJson;
|
||||
private string? _lastJson;
|
||||
|
||||
public SettingsSource() : base("Settings", periodMs: 5000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_getSettingsJson == null)
|
||||
_getSettingsJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetSettingsJson");
|
||||
if (_getSettingsJson == null) return;
|
||||
IntPtr ptr = _getSettingsJson();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
RynthAiSettings? parsed = JsonSerializer.Deserialize(json, RynthAiSettingsJsonContext.Default.RynthAiSettings);
|
||||
if (parsed != null) Publish(parsed);
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_getSettingsJson = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Saves the whole settings payload through RynthPluginSetSettingsJson, on the pump thread.</summary>
|
||||
internal static unsafe class SettingsCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _setSettingsJson;
|
||||
|
||||
static SettingsCommands()
|
||||
{
|
||||
Plugins.PluginManager.PluginsUnloaded += () => _setSettingsJson = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="settings"/> must be a copy the caller no longer changes
|
||||
/// (it is serialized later, on the pump thread). Any thread.
|
||||
/// </summary>
|
||||
public static void Save(RynthAiSettings settings)
|
||||
{
|
||||
UiDataHub.Post("RynthAi settings save", () =>
|
||||
{
|
||||
if (_setSettingsJson == null)
|
||||
_setSettingsJson = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSetSettingsJson");
|
||||
if (_setSettingsJson == null) return;
|
||||
string json = JsonSerializer.Serialize(settings, RynthAiSettingsJsonContext.Default.RynthAiSettings);
|
||||
IntPtr ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _setSettingsJson(ansi); }
|
||||
finally { Marshal.FreeHGlobal(ansi); }
|
||||
UiSources.Settings.RequestRefresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Schema ─────────────────────────────────────────────────────────────────
|
||||
|
||||
internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus }
|
||||
|
||||
/// <summary>
|
||||
/// One row of a settings tab. Numeric values go through double (bools as
|
||||
/// 0/1, combos as the index). <see cref="Gates"/> marks rows whose value
|
||||
/// shows or hides other rows (the Avalonia face rebuilds the tab on change).
|
||||
/// </summary>
|
||||
internal sealed record SettingRow(
|
||||
SettingKind Kind,
|
||||
string Label,
|
||||
string? Tooltip = null,
|
||||
Func<RynthAiSettings, double>? Get = null,
|
||||
Action<RynthAiSettings, double>? Set = null,
|
||||
double Min = 0,
|
||||
double Max = 0,
|
||||
double Step = 1,
|
||||
string[]? Items = null,
|
||||
Func<RynthAiSettings, bool>? VisibleWhen = null,
|
||||
bool Gates = false)
|
||||
{
|
||||
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
|
||||
}
|
||||
|
||||
internal sealed record SettingsTab(string Name, SettingRow[] Rows);
|
||||
|
||||
internal static class SettingsSchema
|
||||
{
|
||||
// Also drawn on the Nav panel (ImGui/Panels/NavFace.cs).
|
||||
public const string NavPointReachLabel = "Nav point reach (yd)";
|
||||
public const string NavPointReachTip =
|
||||
"How close to get to each nav point before moving on to the next, in yards. VTank calls it " +
|
||||
"Follow/Nav Min Distance (metas: FollowNavMin, or VTank's NavCloseStopRange). Follow stops this " +
|
||||
"close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd.";
|
||||
|
||||
public static readonly string[] AttackHeights = { "Low", "Medium", "High" };
|
||||
public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
|
||||
|
||||
private static SettingRow Bool(string label, Func<RynthAiSettings, bool> get, Action<RynthAiSettings, bool> set,
|
||||
string? tip = null, Func<RynthAiSettings, bool>? when = null, bool gates = false) =>
|
||||
new(SettingKind.Bool, label, tip, s => get(s) ? 1 : 0, (s, v) => set(s, v != 0), VisibleWhen: when, Gates: gates);
|
||||
|
||||
private static SettingRow Int(string label, Func<RynthAiSettings, int> get, Action<RynthAiSettings, int> set,
|
||||
int min, int max, int step, string? tip = null, Func<RynthAiSettings, bool>? when = null) =>
|
||||
new(SettingKind.Int, label, tip, s => get(s), (s, v) => set(s, (int)Math.Round(v)), min, max, step, VisibleWhen: when);
|
||||
|
||||
private static SettingRow Float(string label, Func<RynthAiSettings, float> get, Action<RynthAiSettings, float> set,
|
||||
float min, float max, float step, string? tip = null, Func<RynthAiSettings, bool>? when = null) =>
|
||||
new(SettingKind.Float, label, tip, s => get(s), (s, v) => set(s, (float)v), min, max, step, VisibleWhen: when);
|
||||
|
||||
private static SettingRow Double(string label, Func<RynthAiSettings, double> get, Action<RynthAiSettings, double> set,
|
||||
double min, double max, double step, string? tip = null) =>
|
||||
new(SettingKind.Double, label, tip, get, set, min, max, step);
|
||||
|
||||
private static SettingRow Combo(string label, string[] items, Func<RynthAiSettings, int> get, Action<RynthAiSettings, int> set,
|
||||
string? tip = null) =>
|
||||
new(SettingKind.Combo, label, tip, s => get(s), (s, v) => set(s, (int)v), 0, items.Length - 1, 1, items);
|
||||
|
||||
// Text size rows are stored by the engine (PanelTextScale), not in the
|
||||
// RynthAi profile, so the settings object is ignored here.
|
||||
private static SettingRow TextSize(string label, string panelTitle) =>
|
||||
Combo(" " + label, PanelTextScale.SizeNames, _ => PanelTextScale.GetOwn(panelTitle), (_, v) => PanelTextScale.Set(panelTitle, v),
|
||||
"Text size for this panel in the game: 0 = normal, each step 10% bigger, yourjokin = 2.5x.")
|
||||
with { VisibleWhen = _ => PanelTextScale.PerPanel };
|
||||
|
||||
private static SettingRow Section(string text, Func<RynthAiSettings, bool>? when = null) =>
|
||||
new(SettingKind.Section, text, VisibleWhen: when);
|
||||
|
||||
private static SettingRow Spacer(Func<RynthAiSettings, bool>? when = null) =>
|
||||
new(SettingKind.Spacer, "", VisibleWhen: when);
|
||||
|
||||
private static SettingRow Note(string text, Func<RynthAiSettings, bool>? when = null) =>
|
||||
new(SettingKind.Note, text, VisibleWhen: when);
|
||||
|
||||
private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set)
|
||||
{
|
||||
var rows = new SettingRow[get.Length];
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
rows[i] = Int($"Level {i + 1}", get[i], set[i], 1, 500, 5);
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static SettingRow[] Concat(params object[] parts)
|
||||
{
|
||||
var list = new System.Collections.Generic.List<SettingRow>();
|
||||
foreach (object p in parts)
|
||||
{
|
||||
if (p is SettingRow r) list.Add(r);
|
||||
else if (p is SettingRow[] rs) list.AddRange(rs);
|
||||
}
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
public static readonly SettingsTab[] Tabs =
|
||||
{
|
||||
new("Display", new[]
|
||||
{
|
||||
Bool("Show Target Stamina / Mana", s => s.ShowTargetStaminaMana, (s, v) => s.ShowTargetStaminaMana = v,
|
||||
"When enabled, displays stamina and mana bars for the selected target (requires appraisal data)."),
|
||||
Spacer(),
|
||||
Section("Text Size (in-game panels)"),
|
||||
Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v),
|
||||
"Text size for every in-game panel: 0 = normal, each step 10% bigger, yourjokin = 2.5x."),
|
||||
Bool("Size Each Panel Separately", _ => PanelTextScale.PerPanel, (_, v) => PanelTextScale.PerPanel = v,
|
||||
"Off: every panel uses All Panels. On: set each panel's text size below.", gates: true),
|
||||
TextSize("RynthAi Dashboard", "RynthAi"),
|
||||
TextSize("Meta", "Meta"),
|
||||
TextSize("Damage", "Damage"),
|
||||
TextSize("Settings", "Settings"),
|
||||
TextSize("Monsters", "Monsters"),
|
||||
TextSize("Nav", "Nav"),
|
||||
TextSize("Items", "Items"),
|
||||
TextSize("Lua", "Lua"),
|
||||
TextSize("Radar", "Radar"),
|
||||
TextSize("Chat Filters", "ChatFilters"),
|
||||
TextSize("RynthNav", "RynthNav"),
|
||||
TextSize("Vision", "Vision"),
|
||||
TextSize("Status", "Status"),
|
||||
TextSize("Log", "Log"),
|
||||
TextSize("Tracker", "Tracker"),
|
||||
}),
|
||||
|
||||
new("UI", new[]
|
||||
{
|
||||
Section("Radar"),
|
||||
Bool("Hide retail radar", s => s.SuppressRetailRadar, (s, v) => s.SuppressRetailRadar = v,
|
||||
"Suppress the game's built-in radar (bezel, compass, coords, blips)."),
|
||||
// "Show RynthRadar" / "Radar Click-Through" and "Show RynthChat" / "Chat Click-Through"
|
||||
// drove RynthAi's plugin-drawn radar and chat windows, which the engine no longer
|
||||
// draws (plugin ImGui rendering is RYNTHCORE_FORCE_IMGUI only). The Radar and Chat
|
||||
// panels open from the bar and have their own click-through (hold Ctrl) in their
|
||||
// gear menus. "Hide retail chat" lives in the Chat panel's gear menu
|
||||
// ("Hide retail chat"). The four fields stay in the payload so RynthAi and the
|
||||
// engine keep round-tripping them whichever is newer.
|
||||
Spacer(),
|
||||
Section("Power Bar"),
|
||||
Bool("Hide retail power bar", s => s.SuppressRetailPowerbar, (s, v) => s.SuppressRetailPowerbar = v,
|
||||
"Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden."),
|
||||
Spacer(),
|
||||
Section("Vitals"),
|
||||
// Stored by the engine (RetailVitalsHooks, %LOCALAPPDATA%\RynthCore\retail_ui.txt),
|
||||
// not in the RynthAi profile, so the settings object is ignored here.
|
||||
Bool("Hide retail vitals bar", _ => Compatibility.RetailVitalsHooks.HideRetailVitals,
|
||||
(_, v) => Compatibility.RetailVitalsHooks.HideRetailVitals = v,
|
||||
"Hide the game's own health/stamina/mana bars; the RynthVision player plate and the RynthAi dashboard show them.\nSaved for this PC. Also: /rc ui retailvitals on|off."),
|
||||
}),
|
||||
|
||||
new("Misc", new[]
|
||||
{
|
||||
Bool("Enable FPS Limit", s => s.EnableFPSLimit, (s, v) => s.EnableFPSLimit = v, gates: true),
|
||||
Int("Focused FPS", s => s.TargetFPSFocused, (s, v) => s.TargetFPSFocused = v, 10, 240, 1, when: s => s.EnableFPSLimit),
|
||||
Int("Background FPS", s => s.TargetFPSBackground, (s, v) => s.TargetFPSBackground = v, 5, 60, 1, when: s => s.EnableFPSLimit),
|
||||
Spacer(),
|
||||
Bool("Auto Cram", 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."),
|
||||
Bool("Peace Mode When Idle", s => s.PeaceModeWhenIdle, (s, v) => s.PeaceModeWhenIdle = v),
|
||||
Bool("Start Macro On Login", s => s.StartMacroOnLogin, (s, v) => s.StartMacroOnLogin = v,
|
||||
"Automatically starts the macro when RynthAi loads."),
|
||||
Bool("Patrol On Login", s => s.PatrolOnLogin, (s, v) => s.PatrolOnLogin = v,
|
||||
"Automatically starts dungeon patrol when RynthAi loads."),
|
||||
Bool("Yield to VTank", s => s.YieldToVTank, (s, v) => s.YieldToVTank = v,
|
||||
"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("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),
|
||||
Float("Bow", s => s.BowArcVelocity, (s, v) => s.BowArcVelocity = v, 10f, 60f, 0.5f,
|
||||
"Bow projectile speed (m/s). Lower = higher arc.", when: s => s.UseArcs),
|
||||
Float("Crossbow", s => s.CrossbowArcVelocity, (s, v) => s.CrossbowArcVelocity = v, 10f, 80f, 0.5f, when: s => s.UseArcs),
|
||||
Float("Atlatl", s => s.AtlatlArcVelocity, (s, v) => s.AtlatlArcVelocity = v, 10f, 60f, 0.5f, when: s => s.UseArcs),
|
||||
Float("Magic Arc", s => s.MagicArcVelocity, (s, v) => s.MagicArcVelocity = v, 10f, 60f, 0.5f,
|
||||
"Arc spells' horizontal speed (m/s). ACE: 40. Lower = higher arc.\nA monster rule with Arc on casts an arc only when this path reaches the target (walls, and ceilings in dungeons); otherwise its other shape (Streak, Blast) or a bolt. Needs Enable Raycasting. /ra lostest magic shows the arc to the selected mob."),
|
||||
Float("Arc Clearance (m)", s => s.MissileArcClearance, (s, v) => s.MissileArcClearance = MathF.Max(0f, v), 0f, 3f, 0.1f,
|
||||
"Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped.", when: s => s.UseArcs),
|
||||
Bool("LoS Debug Log", s => s.LosDebugLog, (s, v) => s.LosDebugLog = v,
|
||||
"Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob."),
|
||||
Spacer(),
|
||||
Section("Monster Blacklist"),
|
||||
Int("Attempts Before Blacklist", s => s.BlacklistAttempts, (s, v) => s.BlacklistAttempts = v, 1, 20, 1,
|
||||
"How many failed attack attempts on a mob before it gets blacklisted."),
|
||||
Int("Blacklist Timeout (sec)", s => s.BlacklistTimeoutSec, (s, v) => s.BlacklistTimeoutSec = v, 5, 120, 5,
|
||||
"How long a blacklisted mob is ignored before re-trying."),
|
||||
Int("No Progress Timeout (sec)", s => s.TargetNoProgressTimeoutSec, (s, v) => s.TargetNoProgressTimeoutSec = v, 0, 300, 10,
|
||||
"Blacklist a target after being engaged this many seconds without dealing damage.\n0 = disabled. Default 60s."),
|
||||
Spacer(),
|
||||
Section("Give Queue"),
|
||||
Int("Give Interval (ms)", s => s.GiveQueueIntervalMs, (s, v) => s.GiveQueueIntervalMs = v, 50, 2000, 50,
|
||||
"Minimum delay between each item sent by /ra givea commands."),
|
||||
}),
|
||||
|
||||
new("Recharge", new[]
|
||||
{
|
||||
Section("In Combat — target within Monster Range (%)"),
|
||||
Int("Heal At", s => s.HealAt, (s, v) => s.HealAt = v, 0, 100, 1,
|
||||
"While a target is within Monster Range, cast Heal Self when HP < this %."),
|
||||
Int("Re-stam At", s => s.RestamAt, (s, v) => s.RestamAt = v, 0, 100, 1,
|
||||
"While a target is within Monster Range, cast Revitalize Self when Stamina < this %."),
|
||||
Int("Get Mana At", s => s.GetManaAt, (s, v) => s.GetManaAt = v, 0, 100, 1,
|
||||
"While a target is within Monster Range, cast Stamina to Mana Self when Mana < this % (needs stam > 15%)."),
|
||||
Spacer(),
|
||||
Section("Idle Top-Off — no targets in range (%)"),
|
||||
Int("Top HP", s => s.TopOffHP, (s, v) => s.TopOffHP = v, 0, 100, 1,
|
||||
"When no targets are within Monster Range, heal up to this HP %. Usually set higher than Heal At."),
|
||||
Int("Top Stam", s => s.TopOffStam, (s, v) => s.TopOffStam = v, 0, 100, 1,
|
||||
"When no targets are within Monster Range, re-stam up to this %."),
|
||||
Int("Top Mana", s => s.TopOffMana, (s, v) => s.TopOffMana = v, 0, 100, 1,
|
||||
"When no targets are within Monster Range, recharge mana up to this %."),
|
||||
Spacer(),
|
||||
Section("Kits & Potions"),
|
||||
Bool("Use Potions", s => s.UsePotions, (s, v) => s.UsePotions = v,
|
||||
"Drink health, mana and stamina potions from the Items panel when a vital is low\nand no spell can fix it (no spell, Life Magic untrained, out of components)."),
|
||||
Bool("Use Buff Items", s => s.UseBuffItems, (s, v) => s.UseBuffItems = v,
|
||||
"Use Asheron's Benediction, Asheron's Lesser Benediction and Blackmoor's Favor\nfrom your pack whenever their buff isn't on you (they're never used up)."),
|
||||
Int("Make Field Rations Below", s => s.MakeRationsBelow, (s, v) => s.MakeRationsBelow = v, 0, 100, 1,
|
||||
"Cook field rations (Cooking Pot on Dried Rations, 25 at a time) when you have fewer than this.\n0 = off. Rations restore stamina and are eaten like stamina potions."),
|
||||
Bool("Use Kits In Magic Mode", s => s.UseKitsInMagicMode, (s, v) => s.UseKitsInMagicMode = v,
|
||||
"Allow healing kits while in magic mode."),
|
||||
Bool("Peace Mode For Kits", s => s.PeaceModeForKits, (s, v) => s.PeaceModeForKits = v,
|
||||
"Switch to peace mode before using a healing kit."),
|
||||
Int("Emergency Heal At", s => s.EmergencyHealAt, (s, v) => s.EmergencyHealAt = v, 0, 100, 1,
|
||||
"At or under this health %, out of Magic mode a healing kit is used ahead of the\nnormal Heal At chain (kit, Heal Self, potion), and while a spell cast is pending a kit\nor potion is used. Stamina to Health has its own line below. 0 = off. Starts at 30."),
|
||||
Int("Stamina To Health At", s => s.StaminaToHealthAt, (s, v) => s.StaminaToHealthAt = v, 0, 100, 1,
|
||||
"At or under this health %, cast Stamina to Health Self ahead of the normal\nHeal At chain (out of Magic mode a kit is tried first). If it can't be cast,\nthe normal chain (kit, Heal Self, potion) runs. 0 = never cast it. Starts at 30."),
|
||||
Int("Stamina To Health Min Stamina", s => s.StaminaToHealthMinStamina, (s, v) => s.StaminaToHealthMinStamina = v, 0, 100, 1,
|
||||
"Cast Stamina to Health only while stamina is over this %, so it doesn't\ndrain you to nothing. Starts at 20."),
|
||||
Int("Kit Min Success %", s => s.KitMinSuccessPct, (s, v) => s.KitMinSuccessPct = v, 0, 100, 1,
|
||||
"Use a healing or stamina kit only when its chance to work is at least this %,\nworked out like the server does: Healing skill + the kit's bonus vs. what's missing.\nBelow it, the spell is cast instead. 0 = always use kits. Starts at 70."),
|
||||
Spacer(),
|
||||
Section("Safety Stops"),
|
||||
Bool("Stop Macro On Death", s => s.StopMacroOnDeath, (s, v) => s.StopMacroOnDeath = v,
|
||||
"Stop the macro when you die. Off by default: most metas run back on their own."),
|
||||
Bool("Stop Macro On No Components", s => s.StopMacroOnNoComponents, (s, v) => s.StopMacroOnNoComponents = v,
|
||||
"Stop the macro after 3 \"missing components\" failures within a minute."),
|
||||
Bool("Stop Macro When Pack Full", s => s.StopMacroWhenPackFull, (s, v) => s.StopMacroWhenPackFull = v,
|
||||
"Stop the macro when no pack has a free slot."),
|
||||
Spacer(),
|
||||
Section("Helper Settings (%) — NOT WIRED YET"),
|
||||
Int("Heal Others", s => s.HealOthersAt, (s, v) => s.HealOthersAt = v, 0, 100, 1,
|
||||
"Intended: cast Heal Other on a fellow when their HP < this %. Not implemented yet — slider is inert."),
|
||||
Int("Re-stam Others", s => s.RestamOthersAt, (s, v) => s.RestamOthersAt = v, 0, 100, 1,
|
||||
"Intended: cast Revitalize Other on a fellow when their Stamina < this %. Not implemented yet — slider is inert."),
|
||||
Int("Infuse Others", s => s.InfuseOthersAt, (s, v) => s.InfuseOthersAt = v, 0, 100, 1,
|
||||
"Intended: cast Infuse Mana Other on a fellow when their Mana < this %. Not implemented yet — slider is inert."),
|
||||
}),
|
||||
|
||||
new("Melee Combat", new[]
|
||||
{
|
||||
Section("Attack Power & Height"),
|
||||
Bool("Use Recklessness", s => s.UseRecklessness, (s, v) => s.UseRecklessness = v,
|
||||
"When enabled and Recklessness is trained, auto power uses 80% instead of 100%."),
|
||||
Spacer(),
|
||||
Bool("Melee Auto Power", s => s.MeleeAttackPower < 0, (s, v) => s.MeleeAttackPower = v ? -1 : 100, gates: true),
|
||||
Int("Melee Power %", s => s.MeleeAttackPower, (s, v) => s.MeleeAttackPower = v, 0, 100, 5, when: s => s.MeleeAttackPower >= 0),
|
||||
Combo("Melee Attack Height", AttackHeights, s => s.MeleeAttackHeight, (s, v) => s.MeleeAttackHeight = v),
|
||||
Spacer(),
|
||||
Bool("Missile Auto Power", s => s.MissileAttackPower < 0, (s, v) => s.MissileAttackPower = v ? -1 : 100, gates: true),
|
||||
Int("Missile Power %", s => s.MissileAttackPower, (s, v) => s.MissileAttackPower = v, 0, 100, 5, when: s => s.MissileAttackPower >= 0),
|
||||
Combo("Missile Attack Height", AttackHeights, s => s.MissileAttackHeight, (s, v) => s.MissileAttackHeight = v),
|
||||
Spacer(),
|
||||
Bool("Use Native Attack", s => s.UseNativeAttack, (s, v) => s.UseNativeAttack = v,
|
||||
"Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows)."),
|
||||
Spacer(),
|
||||
Bool("Summon Pets", s => s.SummonPets, (s, v) => s.SummonPets = v),
|
||||
Int("Pet Min Monsters", s => s.PetMinMonsters, (s, v) => s.PetMinMonsters = v, 1, 20, 1),
|
||||
}),
|
||||
|
||||
new("Spell Combat", Concat(
|
||||
Section("War/Void Casting Settings"),
|
||||
Int("Buff Spell Interval (ms)", s => s.SpellCastIntervalMs, (s, v) => s.SpellCastIntervalMs = v, 100, 1500, 50,
|
||||
"Delay between BUFF / utility spell casts (not combat).\nLower = faster buff chains. 400ms is a good balance.\nBelow 200ms may cause fizzles or dropped casts on laggy servers."),
|
||||
Int("Attack Spell Delay (ms)", s => s.AttackSpellIntervalMs, (s, v) => s.AttackSpellIntervalMs = v, 250, 5000, 50,
|
||||
"Delay between offensive (war/void) COMBAT casts only.\nSpacing casts ~1-2s (1500ms default) stops back-to-back\n\"You're too busy!\" refusals that drop casts and cost kills.\nDoes NOT affect buffing speed."),
|
||||
Bool("Cast Dispel Self", s => s.CastDispelSelf, (s, v) => s.CastDispelSelf = v),
|
||||
Spacer(),
|
||||
Section("Ring Spell Override"),
|
||||
Int("Min Ring Targets", s => s.MinRingTargets, (s, v) => s.MinRingTargets = v, 1, 20, 1,
|
||||
"If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak."),
|
||||
Spacer(),
|
||||
Section("Blast Spell Override"),
|
||||
Int("Blast Range (yd)", s => s.BlastRange, (s, v) => s.BlastRange = v, 0, 100, 1,
|
||||
"0 = off: monsters with Blast on always cast blasts.\nAbove 0: a blast is cast only when Min Blast Targets monsters are\nwithin this range in the blast's fan toward the target (it fires 3\nprojectiles over 90 degrees); otherwise the monster's other shape, or a bolt."),
|
||||
Int("Min Blast Targets", s => s.MinBlastTargets, (s, v) => s.MinBlastTargets = v, 1, 20, 1,
|
||||
"How many monsters (the target included) must be in the blast's fan, within Blast Range."),
|
||||
Spacer(),
|
||||
Section("Spell Difficulty (Min Buffed Skill)"),
|
||||
Tiers(
|
||||
new Func<RynthAiSettings, int>[] { s => s.MinSkillLevelTier1, s => s.MinSkillLevelTier2, s => s.MinSkillLevelTier3, s => s.MinSkillLevelTier4,
|
||||
s => s.MinSkillLevelTier5, s => s.MinSkillLevelTier6, s => s.MinSkillLevelTier7, s => s.MinSkillLevelTier8 },
|
||||
new Action<RynthAiSettings, int>[] { (s, v) => s.MinSkillLevelTier1 = v, (s, v) => s.MinSkillLevelTier2 = v, (s, v) => s.MinSkillLevelTier3 = v, (s, v) => s.MinSkillLevelTier4 = v,
|
||||
(s, v) => s.MinSkillLevelTier5 = v, (s, v) => s.MinSkillLevelTier6 = v, (s, v) => s.MinSkillLevelTier7 = v, (s, v) => s.MinSkillLevelTier8 = v }))),
|
||||
|
||||
new("Ranges", new[]
|
||||
{
|
||||
Section("Standard Ranges (Yards)"),
|
||||
Int("Monster Range", s => s.MonsterRange, (s, v) => s.MonsterRange = v, 1, 200, 1),
|
||||
Int("Ring Range", s => s.RingRange, (s, v) => s.RingRange = v, 1, 50, 1),
|
||||
Int("Approach Range", s => s.ApproachRange, (s, v) => s.ApproachRange = v, 1, 50, 1),
|
||||
Spacer(),
|
||||
Section("Corpse Acquisition (Yards)"),
|
||||
Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5),
|
||||
Double("Corpse Min (yd)", s => s.CorpseApproachRangeMin, (s, v) => s.CorpseApproachRangeMin = v, 0.5, 20.0, 0.5),
|
||||
}),
|
||||
|
||||
new("Navigation", new[]
|
||||
{
|
||||
Bool("Boost Nav Priority", s => s.BoostNavPriority, (s, v) => s.BoostNavPriority = v),
|
||||
Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip),
|
||||
Spacer(),
|
||||
Section("Nav Marker Display"),
|
||||
Float("Ring Thickness", s => s.NavRingThickness, (s, v) => s.NavRingThickness = v, 1f, 16f, 1f),
|
||||
Float("Line Thickness", s => s.NavLineThickness, (s, v) => s.NavLineThickness = v, 1f, 16f, 1f),
|
||||
Float("Height Offset", s => s.NavHeightOffset, (s, v) => s.NavHeightOffset = v, -5f, 5f, 0.05f,
|
||||
"Vertical offset for nav markers above the ground. Negative = lower."),
|
||||
Float("Slope Sink", s => s.NavSlopeSink, (s, v) => s.NavSlopeSink = v, 0f, 8f, 0.1f,
|
||||
"Extra downward offset on slopes only, per unit of terrain steepness. 0 = off; flat ground is unaffected. ~1.5 cancels the float for a default-radius ring."),
|
||||
Bool("Show Terrain Passability", s => s.ShowTerrainPassability, (s, v) => s.ShowTerrainPassability = v,
|
||||
"Highlight impassable terrain triangles in red."),
|
||||
Spacer(),
|
||||
Section("Doors"),
|
||||
Bool("Open Doors While Navigating", s => s.OpenDoors, (s, v) => s.OpenDoors = v,
|
||||
"Automatically open doors encountered during navigation.", gates: true),
|
||||
Float("Door Detection Range (yd)", s => s.OpenDoorRange, (s, v) => s.OpenDoorRange = v, 0.1f, 70f, 1f, when: s => s.OpenDoors),
|
||||
Bool("Auto-Unlock Doors", s => s.AutoUnlockDoors, (s, v) => s.AutoUnlockDoors = v,
|
||||
"If a door is locked, try to use a lockpick from your Consumable Items list.", when: s => s.OpenDoors),
|
||||
Spacer(),
|
||||
Section("Steering"),
|
||||
Float("Stop & Turn Angle", s => s.NavStopTurnAngle, (s, v) => s.NavStopTurnAngle = v, 1f, 90f, 1f,
|
||||
"Stop forward motion and turn in place when heading error exceeds this."),
|
||||
Float("Resume Run Angle", s => s.NavResumeTurnAngle, (s, v) => s.NavResumeTurnAngle = v, 1f, 45f, 1f,
|
||||
"Resume running once the turn-in-place error drops below this."),
|
||||
Float("Dead Zone", s => s.NavDeadZone, (s, v) => s.NavDeadZone = v, 0.5f, 20f, 0.5f,
|
||||
"Ignore heading corrections smaller than this."),
|
||||
Float("Sweep Detect Mult", s => s.NavSweepMult, (s, v) => s.NavSweepMult = v, 0.5f, 10f, 0.1f,
|
||||
"Closest-approach detection radius multiplier."),
|
||||
Float("Lookahead (yd)", s => s.NavLookaheadYards, (s, v) => s.NavLookaheadYards = MathF.Max(0f, v), 0f, 30f, 0.5f,
|
||||
"Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off."),
|
||||
Float("Turn Rate (deg/s)", s => s.NavTurnRateDegPerSec, (s, v) => s.NavTurnRateDegPerSec = v, 30f, 720f, 15f,
|
||||
"Max turn speed while navigating. Higher = snappier turns, lower = gentler."),
|
||||
Float("Post-Portal Delay (s)", s => s.PostPortalDelaySec, (s, v) => s.PostPortalDelaySec = MathF.Max(0f, v), 0f, 30f, 0.25f,
|
||||
"Seconds to settle after any portal/recall teleport before nav resumes."),
|
||||
Spacer(when: s => s.MovementMode == 2),
|
||||
Section("Tier 2 Tuning", when: s => s.MovementMode == 2),
|
||||
Float("Speed", s => s.T2Speed, (s, v) => s.T2Speed = v, 0.1f, 5f, 0.1f, when: s => s.MovementMode == 2),
|
||||
Float("Walk Within (yd)", s => s.T2WalkWithinYd, (s, v) => s.T2WalkWithinYd = v, 1f, 50f, 1f, when: s => s.MovementMode == 2),
|
||||
Float("Stop Distance (yd)", s => s.T2DistanceTo, (s, v) => s.T2DistanceTo = v, 0.1f, 10f, 0.1f, when: s => s.MovementMode == 2),
|
||||
Float("Reissue Timeout (ms)", s => s.T2ReissueMs, (s, v) => s.T2ReissueMs = v, 100f, 10000f, 100f, when: s => s.MovementMode == 2),
|
||||
Float("Max Range (yd)", s => s.T2MaxRangeYd, (s, v) => s.T2MaxRangeYd = v, 50f, 2000f, 50f, when: s => s.MovementMode == 2),
|
||||
Int("Max Landblock Dist", s => s.T2MaxLandblocks, (s, v) => s.T2MaxLandblocks = v, 1, 20, 1, when: s => s.MovementMode == 2),
|
||||
}),
|
||||
|
||||
new("Buffing", Concat(
|
||||
Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v),
|
||||
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."),
|
||||
Int("Also Refresh Under (seconds left)", s => s.RebuffTopOffSecondsRemaining, (s, v) => s.RebuffTopOffSecondsRemaining = v, 30, 3600, 60,
|
||||
"When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."),
|
||||
Spacer(),
|
||||
Section("Buff Difficulty (Min Buffed Skill)"),
|
||||
Tiers(
|
||||
new Func<RynthAiSettings, int>[] { s => s.BuffMinSkillLevelTier1, s => s.BuffMinSkillLevelTier2, s => s.BuffMinSkillLevelTier3, s => s.BuffMinSkillLevelTier4,
|
||||
s => s.BuffMinSkillLevelTier5, s => s.BuffMinSkillLevelTier6, s => s.BuffMinSkillLevelTier7, s => s.BuffMinSkillLevelTier8 },
|
||||
new Action<RynthAiSettings, int>[] { (s, v) => s.BuffMinSkillLevelTier1 = v, (s, v) => s.BuffMinSkillLevelTier2 = v, (s, v) => s.BuffMinSkillLevelTier3 = v, (s, v) => s.BuffMinSkillLevelTier4 = v,
|
||||
(s, v) => s.BuffMinSkillLevelTier5 = v, (s, v) => s.BuffMinSkillLevelTier6 = v, (s, v) => s.BuffMinSkillLevelTier7 = v, (s, v) => s.BuffMinSkillLevelTier8 = v }))),
|
||||
|
||||
new("Crafting", new[]
|
||||
{
|
||||
Section("Missile Ammo Crafting"),
|
||||
Bool("Enable Missile Crafting", s => s.EnableMissileCrafting, (s, v) => s.EnableMissileCrafting = v,
|
||||
"Auto-manage missile ammo when the ammo slot is empty or low.", gates: true),
|
||||
Note("(Disabled)", when: s => !s.EnableMissileCrafting),
|
||||
Spacer(when: s => s.EnableMissileCrafting),
|
||||
new SettingRow(SettingKind.CraftingStatus, "State:", VisibleWhen: s => s.EnableMissileCrafting && !string.IsNullOrEmpty(s.MissileCraftingState)),
|
||||
}),
|
||||
|
||||
new("Looting", new[]
|
||||
{
|
||||
Bool("Enable Looting", s => s.EnableLooting, (s, v) => s.EnableLooting = v),
|
||||
Bool("Boost Loot Priority", s => s.BoostLootPriority, (s, v) => s.BoostLootPriority = v),
|
||||
Bool("Loot Only Rare Corpses", s => s.LootOnlyRareCorpses, (s, v) => s.LootOnlyRareCorpses = v),
|
||||
Bool("Learn Unknown Spells", s => s.ReadUnknownScrolls, (s, v) => s.ReadUnknownScrolls = v,
|
||||
"Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too. Needs Enable Looting for corpses."),
|
||||
Bool("Stop Looting When Pack Full", s => s.StopLootingWhenPackFull, (s, v) => s.StopLootingWhenPackFull = v,
|
||||
"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),
|
||||
Spacer(),
|
||||
Section("Corpse Ownership"),
|
||||
Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v),
|
||||
Spacer(),
|
||||
Section("Inventory Management"),
|
||||
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."),
|
||||
Bool("Combine Salvage Bags", s => s.EnableCombineSalvage, (s, v) => s.EnableCombineSalvage = v,
|
||||
"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."),
|
||||
Spacer(),
|
||||
Section("Loot Timers (ms)"),
|
||||
Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25),
|
||||
Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25),
|
||||
Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25),
|
||||
Int("Closing Delay", s => s.LootClosingDelayMs, (s, v) => s.LootClosingDelayMs = v, 0, 5000, 25),
|
||||
Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25),
|
||||
Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100),
|
||||
Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100),
|
||||
Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500),
|
||||
Spacer(),
|
||||
Section("Salvage Timers (ms) - First / Fast"),
|
||||
Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50),
|
||||
Int("Open (Fast)", s => s.SalvageOpenDelayFastMs, (s, v) => s.SalvageOpenDelayFastMs = v, 0, 2000, 25),
|
||||
Int("Add Item (First)", s => s.SalvageAddDelayFirstMs, (s, v) => s.SalvageAddDelayFirstMs = v, 0, 5000, 50),
|
||||
Int("Add Item (Fast)", s => s.SalvageAddDelayFastMs, (s, v) => s.SalvageAddDelayFastMs = v, 0, 2000, 25),
|
||||
Int("Salvage Click", s => s.SalvageSalvageDelayMs, (s, v) => s.SalvageSalvageDelayMs = v, 0, 2000, 25),
|
||||
Int("Result (First)", s => s.SalvageResultDelayFirstMs, (s, v) => s.SalvageResultDelayFirstMs = v, 0, 5000, 50),
|
||||
Int("Result (Fast)", s => s.SalvageResultDelayFastMs, (s, v) => s.SalvageResultDelayFastMs = v, 0, 2000, 25),
|
||||
}),
|
||||
|
||||
new("Vendoring", new[]
|
||||
{
|
||||
Section("AutoVendor"),
|
||||
Bool("Enabled", s => s.AutoVendorEnabled, (s, v) => s.AutoVendorEnabled = v,
|
||||
"Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, in the AutoVendor folder."),
|
||||
Bool("Test Mode (only print what it would do)", s => s.AutoVendorTestMode, (s, v) => s.AutoVendorTestMode = v,
|
||||
"Lists what would be bought and sold without trading. Leave this on until the lists look right."),
|
||||
Bool("Buy", s => s.AutoVendorEnableBuying, (s, v) => s.AutoVendorEnableBuying = v),
|
||||
Bool("Sell", s => s.AutoVendorEnableSelling, (s, v) => s.AutoVendorEnableSelling = v),
|
||||
Bool("Only Sell From Main Pack", s => s.AutoVendorOnlyFromMainPack, (s, v) => s.AutoVendorOnlyFromMainPack = v),
|
||||
Bool("Show Merchant Info", s => s.AutoVendorShowMerchantInfo, (s, v) => s.AutoVendorShowMerchantInfo = v,
|
||||
"Print the vendor's buy/sell rates and max value when it opens."),
|
||||
Bool("Think When Finished", s => s.AutoVendorThink, (s, v) => s.AutoVendorThink = v,
|
||||
"Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself, for metas."),
|
||||
Spacer(),
|
||||
Section("/ub vendor open"),
|
||||
Int("Tries", s => s.AutoVendorTries, (s, v) => s.AutoVendorTries = v, 1, 20, 1),
|
||||
Int("Time Between Tries (ms)", s => s.AutoVendorTriesTime, (s, v) => s.AutoVendorTriesTime = v, 500, 30000, 250),
|
||||
Spacer(),
|
||||
Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."),
|
||||
}),
|
||||
};
|
||||
}
|
||||
152
src/RynthCore.Engine/UI/Data/UiDataHub.cs
Normal file
152
src/RynthCore.Engine/UI/Data/UiDataHub.cs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/UiDataHub.cs
|
||||
// The one fetcher for panel data (docs/IMGUI_PARITY_PLAN.md §4.3).
|
||||
//
|
||||
// Step() runs on the plugin pump thread right after PluginManager.TickAll,
|
||||
// so every plugin export a panel needs is called on the same thread as the
|
||||
// plugin's own tick and object events: no race with the plugin, and exports
|
||||
// that free their previous return buffer on the next call never see two
|
||||
// callers. Panels (either face) only read published snapshots and post
|
||||
// commands; they never call a plugin export themselves.
|
||||
//
|
||||
// Commands (mutating calls: toggles, settings writes, nav edits) are queued
|
||||
// from any thread and executed here, before the sources poll, so the next
|
||||
// snapshot already reflects them.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal static class UiDataHub
|
||||
{
|
||||
private const int MaxQueuedCommands = 256;
|
||||
private const double CommandBudgetMs = 2.0;
|
||||
/// <summary>A step slower than this is logged (at most once a minute).</summary>
|
||||
private const double StepWarnMs = 4.0;
|
||||
|
||||
private static UiSource[] _sources = Array.Empty<UiSource>();
|
||||
private static readonly object RegisterSync = new();
|
||||
private static readonly ConcurrentQueue<(string Label, Action Action)> _commands = new();
|
||||
private static int _queued;
|
||||
private static volatile bool _armed = true;
|
||||
private static volatile bool _resetPending;
|
||||
private static long _lastSlowLogTicks;
|
||||
private static int _droppedCommands;
|
||||
|
||||
static UiDataHub()
|
||||
{
|
||||
// Raised on the pump thread after every plugin is shut down (RL /
|
||||
// rescan). Sources re-bind to the fresh plugin copies on their next poll.
|
||||
PluginManager.PluginsUnloaded += () => _resetPending = true;
|
||||
}
|
||||
|
||||
/// <summary>Adds a source. Call at init (any thread); sources are never removed.</summary>
|
||||
public static void Register(UiSource source)
|
||||
{
|
||||
lock (RegisterSync)
|
||||
{
|
||||
var next = new UiSource[_sources.Length + 1];
|
||||
Array.Copy(_sources, next, _sources.Length);
|
||||
next[^1] = source;
|
||||
Volatile.Write(ref _sources, next);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues <paramref name="action"/> to run on the pump thread at the next
|
||||
/// step. Any thread. Returns false (and logs) when the hub is shutting down
|
||||
/// or the queue is full; commands are never run after shutdown begins.
|
||||
/// </summary>
|
||||
public static bool Post(string label, Action action)
|
||||
{
|
||||
if (!_armed)
|
||||
{
|
||||
RynthLog.UI($"UiDataHub: '{label}' dropped - shutting down.");
|
||||
return false;
|
||||
}
|
||||
if (Interlocked.Increment(ref _queued) > MaxQueuedCommands)
|
||||
{
|
||||
Interlocked.Decrement(ref _queued);
|
||||
if (Interlocked.Increment(ref _droppedCommands) <= 20)
|
||||
RynthLog.UI($"UiDataHub: '{label}' dropped - command queue full.");
|
||||
return false;
|
||||
}
|
||||
_commands.Enqueue((label, action));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Stops accepting commands and drops the queued ones. Engine shutdown.</summary>
|
||||
public static void Disarm()
|
||||
{
|
||||
_armed = false;
|
||||
int dropped = 0;
|
||||
while (_commands.TryDequeue(out _)) dropped++;
|
||||
Interlocked.Exchange(ref _queued, 0);
|
||||
if (dropped > 0)
|
||||
RynthLog.UI($"UiDataHub: disarmed, {dropped} queued command(s) dropped.");
|
||||
}
|
||||
|
||||
/// <summary>Pump thread only, right after PluginManager.TickAll.</summary>
|
||||
public static void Step()
|
||||
{
|
||||
if (!_armed) return;
|
||||
long start = Stopwatch.GetTimestamp();
|
||||
UiSource[] sources = Volatile.Read(ref _sources);
|
||||
|
||||
if (_resetPending)
|
||||
{
|
||||
_resetPending = false;
|
||||
foreach (UiSource source in sources)
|
||||
{
|
||||
try { source.Reset(); }
|
||||
catch (Exception ex) { RynthLog.UI($"UiDataHub: {source.Name}.Reset threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh deferred by a command in the previous step: the plugin has
|
||||
// ticked since, so it has applied that command.
|
||||
foreach (UiSource source in sources)
|
||||
source.PromoteDeferredRefresh();
|
||||
|
||||
// Commands first, so this step's polls already see their effect. A long
|
||||
// burst yields after the budget; the rest run next step.
|
||||
long commandDeadline = start + (long)(Stopwatch.Frequency * CommandBudgetMs / 1000);
|
||||
while (_commands.TryDequeue(out var command))
|
||||
{
|
||||
Interlocked.Decrement(ref _queued);
|
||||
try { command.Action(); }
|
||||
catch (Exception ex) { RynthLog.UI($"UiDataHub: command '{command.Label}' threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
if (Stopwatch.GetTimestamp() > commandDeadline) break;
|
||||
}
|
||||
|
||||
string? slowest = null;
|
||||
long slowestTicks = 0;
|
||||
foreach (UiSource source in sources)
|
||||
{
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
if (!source.HasSubscribers || !source.IsDue(now)) continue;
|
||||
try { source.Poll(); }
|
||||
catch (Exception ex) { RynthLog.UI($"UiDataHub: {source.Name}.Poll threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
long after = Stopwatch.GetTimestamp();
|
||||
source.MarkPolled(after, after - now); // an expensive poll backs off (UiSource.CostBackoff)
|
||||
if (after - now > slowestTicks) { slowestTicks = after - now; slowest = source.Name; }
|
||||
}
|
||||
|
||||
long total = Stopwatch.GetTimestamp() - start;
|
||||
if (total > Stopwatch.Frequency * StepWarnMs / 1000 && total > 0)
|
||||
{
|
||||
long nowTicks = Stopwatch.GetTimestamp();
|
||||
if (nowTicks - _lastSlowLogTicks > Stopwatch.Frequency * 60)
|
||||
{
|
||||
_lastSlowLogTicks = nowTicks;
|
||||
double toMs = 1000.0 / Stopwatch.Frequency;
|
||||
RynthLog.UI($"UiDataHub: slow step {total * toMs:0.0} ms (slowest source {slowest ?? "-"} {slowestTicks * toMs:0.0} ms). The plugin tick waits for this.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
125
src/RynthCore.Engine/UI/Data/UiSource.cs
Normal file
125
src/RynthCore.Engine/UI/Data/UiSource.cs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/UiSource.cs
|
||||
// One piece of panel data kept fresh by UiDataHub (docs/IMGUI_PARITY_PLAN.md
|
||||
// §4.3). A source polls on the plugin pump thread and publishes an immutable
|
||||
// snapshot; the ImGui faces (AC's render thread) and the Avalonia faces (the
|
||||
// Avalonia UI thread) only ever read the published snapshot.
|
||||
// ============================================================================
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
/// <summary>An immutable published value. Readers compare Version to detect change.</summary>
|
||||
internal sealed class UiSnapshot<T> where T : class
|
||||
{
|
||||
public UiSnapshot(long version, T value)
|
||||
{
|
||||
Version = version;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public long Version { get; }
|
||||
public T Value { get; }
|
||||
}
|
||||
|
||||
internal abstract class UiSource
|
||||
{
|
||||
private int _subscribers;
|
||||
private long _nextDueTicks;
|
||||
private volatile bool _refreshRequested;
|
||||
private volatile bool _refreshAfterPluginTick;
|
||||
|
||||
protected UiSource(string name, int periodMs)
|
||||
{
|
||||
Name = name;
|
||||
PeriodMs = periodMs;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>Minimum time between polls while subscribed.</summary>
|
||||
public int PeriodMs { get; }
|
||||
|
||||
/// <summary>
|
||||
/// A panel face that shows this data calls Subscribe when it opens and
|
||||
/// Unsubscribe when it closes; a source with no subscribers is not polled.
|
||||
/// Any thread.
|
||||
/// </summary>
|
||||
public void Subscribe() => Interlocked.Increment(ref _subscribers);
|
||||
|
||||
public void Unsubscribe()
|
||||
{
|
||||
if (Interlocked.Decrement(ref _subscribers) < 0)
|
||||
Interlocked.Exchange(ref _subscribers, 0);
|
||||
}
|
||||
|
||||
public bool HasSubscribers => Volatile.Read(ref _subscribers) > 0;
|
||||
|
||||
/// <summary>Poll on the next hub step regardless of the period (e.g. after a command). Any thread.</summary>
|
||||
public void RequestRefresh() => _refreshRequested = true;
|
||||
|
||||
/// <summary>
|
||||
/// Poll after the plugin's next tick, not before: for exports that only
|
||||
/// queue a command the plugin applies on its tick (Meta). Until then the
|
||||
/// source is not polled at all, so no snapshot from before the command
|
||||
/// lands in between. Pump thread (from a hub command).
|
||||
/// </summary>
|
||||
public void RequestRefreshAfterPluginTick() => _refreshAfterPluginTick = true;
|
||||
|
||||
/// <summary>Hub, at the start of a step (the plugin has ticked since the last step).</summary>
|
||||
internal void PromoteDeferredRefresh()
|
||||
{
|
||||
if (!_refreshAfterPluginTick) return;
|
||||
_refreshAfterPluginTick = false;
|
||||
_refreshRequested = true;
|
||||
}
|
||||
|
||||
internal bool IsDue(long now) => !_refreshAfterPluginTick && (_refreshRequested || now >= _nextDueTicks);
|
||||
|
||||
/// <summary>
|
||||
/// A source whose poll took <c>cost</c> waits at least CostBackoff times that before its
|
||||
/// next poll, so no source can take more than ~1/CostBackoff of the plugin pump however
|
||||
/// big its data gets. Below PeriodMs / CostBackoff (3.3 ms for the radar's 33 ms) nothing
|
||||
/// changes. Added 2026-10-02: in a crowded dungeon the radar's poll (snapshot build, JSON,
|
||||
/// parse; 300+ markers) took 4-7 ms every 33 ms on the thread the plugin tick runs on.
|
||||
/// </summary>
|
||||
internal const int CostBackoff = 10;
|
||||
|
||||
internal void MarkPolled(long now, long costTicks = 0)
|
||||
{
|
||||
_refreshRequested = false;
|
||||
long period = Stopwatch.Frequency * PeriodMs / 1000;
|
||||
long backoff = costTicks > 0 ? costTicks * CostBackoff : 0;
|
||||
_nextDueTicks = now + (backoff > period ? backoff : period);
|
||||
}
|
||||
|
||||
/// <summary>Fetch and publish. Pump thread, after the plugin tick; may call plugin exports.</summary>
|
||||
protected internal abstract void Poll();
|
||||
|
||||
/// <summary>
|
||||
/// Plugins were unloaded (RL / rescan): drop cached export bindings and
|
||||
/// anything derived from the old plugin copy. Pump thread.
|
||||
/// </summary>
|
||||
protected internal virtual void Reset() { }
|
||||
}
|
||||
|
||||
/// <summary>A source that publishes a <typeparamref name="T"/> snapshot.</summary>
|
||||
internal abstract class UiSource<T> : UiSource where T : class
|
||||
{
|
||||
private UiSnapshot<T>? _current;
|
||||
|
||||
protected UiSource(string name, int periodMs) : base(name, periodMs) { }
|
||||
|
||||
/// <summary>The latest snapshot, or null before the first poll / after a reset. Any thread; never blocks.</summary>
|
||||
public UiSnapshot<T>? Current => Volatile.Read(ref _current);
|
||||
|
||||
protected void Publish(T value)
|
||||
{
|
||||
long version = (Volatile.Read(ref _current)?.Version ?? 0) + 1;
|
||||
Volatile.Write(ref _current, new UiSnapshot<T>(version, value));
|
||||
}
|
||||
|
||||
protected void ClearSnapshot() => Volatile.Write(ref _current, null);
|
||||
}
|
||||
92
src/RynthCore.Engine/UI/Data/UiSources.cs
Normal file
92
src/RynthCore.Engine/UI/Data/UiSources.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/UiSources.cs
|
||||
// The hub's sources, one instance each. Touching this class registers them
|
||||
// with UiDataHub; a source is only polled while a panel face subscribes.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal static class UiSources
|
||||
{
|
||||
public static readonly PluginStatusSource PluginStatus = new();
|
||||
public static readonly LogSource Log = new();
|
||||
public static readonly TrackerSource Tracker = new();
|
||||
public static readonly RynthAiSource RynthAi = new();
|
||||
public static readonly PatrolSource Patrol = new();
|
||||
public static readonly RadarSource Radar = new();
|
||||
public static readonly SettingsSource Settings = new();
|
||||
public static readonly MetaSource Meta = new();
|
||||
public static readonly LuaSource Lua = new();
|
||||
public static readonly NavSource Nav = new();
|
||||
public static readonly ItemsSource Items = new();
|
||||
public static readonly VisionSource Vision = new();
|
||||
public static readonly RynthNavSource RynthNav = new();
|
||||
public static readonly RynthNavAtlasSource RynthNavAtlas = new();
|
||||
public static readonly RynthNavArrowWatch RynthNavArrowWatch = new();
|
||||
public static readonly ChatSource Chat = new();
|
||||
public static readonly DamageSource Damage = new();
|
||||
public static readonly MonsterRulesSource MonsterRules = new();
|
||||
public static readonly MonsterDetailSource MonsterDetail = new();
|
||||
public static readonly LootEditSource LootEdit = new();
|
||||
public static readonly SenseSource Sense = new();
|
||||
|
||||
static UiSources()
|
||||
{
|
||||
UiDataHub.Register(Settings);
|
||||
UiDataHub.Register(Meta);
|
||||
UiDataHub.Register(LootEdit);
|
||||
UiDataHub.Register(Lua);
|
||||
UiDataHub.Register(Nav);
|
||||
UiDataHub.Register(Items);
|
||||
UiDataHub.Register(Vision);
|
||||
UiDataHub.Register(RynthNav);
|
||||
UiDataHub.Register(RynthNavAtlas);
|
||||
UiDataHub.Register(RynthNavArrowWatch);
|
||||
UiDataHub.Register(Chat);
|
||||
UiDataHub.Register(Damage);
|
||||
UiDataHub.Register(MonsterRules);
|
||||
UiDataHub.Register(MonsterDetail);
|
||||
UiDataHub.Register(Radar);
|
||||
UiDataHub.Register(RynthAi);
|
||||
UiDataHub.Register(Patrol);
|
||||
UiDataHub.Register(PluginStatus);
|
||||
UiDataHub.Register(Log);
|
||||
UiDataHub.Register(Tracker);
|
||||
UiDataHub.Register(Sense);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One row of the Status panel's plugin list, preformatted.</summary>
|
||||
internal readonly record struct PluginStatusRow(string Label, string State, bool IsError);
|
||||
|
||||
/// <summary>
|
||||
/// Loaded plugins with version and state, for the Status panel. Engine-local:
|
||||
/// reads PluginManager's list on the pump thread (which owns it) instead of
|
||||
/// from a UI thread as the Avalonia panel used to.
|
||||
/// </summary>
|
||||
internal sealed class PluginStatusSource : UiSource<PluginStatusRow[]>
|
||||
{
|
||||
public PluginStatusSource() : base("PluginStatus", periodMs: 1000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
var plugins = PluginManager.Plugins;
|
||||
var rows = new PluginStatusRow[plugins.Count];
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
{
|
||||
LoadedPlugin p = plugins[i];
|
||||
string version = p.VersionString.Length > 0 ? " " + p.VersionString : "";
|
||||
string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending";
|
||||
rows[i] = new PluginStatusRow(p.DisplayName + version, state, p.Failed);
|
||||
}
|
||||
|
||||
PluginStatusRow[]? previous = Current?.Value;
|
||||
if (previous == null || !previous.AsSpan().SequenceEqual(rows))
|
||||
Publish(rows);
|
||||
}
|
||||
|
||||
protected internal override void Reset() => ClearSnapshot();
|
||||
}
|
||||
212
src/RynthCore.Engine/UI/Data/VisionData.cs
Normal file
212
src/RynthCore.Engine/UI/Data/VisionData.cs
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Data/VisionData.cs
|
||||
// The RynthVision plugin's settings (overlays, colours, tuning, water terrain
|
||||
// types) for both Vision faces.
|
||||
//
|
||||
// RynthVisionGetSettingsJson frees its previous buffer on each call, so the
|
||||
// hub is its only caller (VisionSource, 5 s). Saving and "Log terrain types
|
||||
// here" run on the pump too. The JSON keys are the plugin's; a still-starting
|
||||
// plugin answers "{}", which is never published (a face would otherwise show
|
||||
// defaults and save them over the real settings).
|
||||
//
|
||||
// Faces save one field at a time ({"key":value}; the plugin applies any
|
||||
// subset), so a save never writes back stale values over a change made
|
||||
// elsewhere (a /rv command, the other face). After every save the settings
|
||||
// are re-read and republished even if unchanged: the plugin may have
|
||||
// normalised the value (an empty water-type list resets to the defaults).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.Data;
|
||||
|
||||
internal sealed class VisionSettings
|
||||
{
|
||||
public bool Radar, Slopes, Water, WaterAnyCorner, WaterImpassableOnly;
|
||||
public uint SlopeColor = 0x60FF2020, WaterColor = 0x600060FF, RadarColor = 0x80FFD000;
|
||||
public double RadarRange = 192, RingThick = 2, RingHeight = 3, SlopeFloorZ = 0.664, SlopeBias = 0.15;
|
||||
public int SlopeRadius = 12, WaterRadius = 12;
|
||||
public List<int> WaterTypes = new();
|
||||
|
||||
public VisionSettings Clone()
|
||||
{
|
||||
var c = (VisionSettings)MemberwiseClone();
|
||||
c.WaterTypes = new List<int>(WaterTypes);
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>Parses the plugin's JSON; false for "{}" or when no known field is present.</summary>
|
||||
public static bool TryParse(string json, out VisionSettings settings)
|
||||
{
|
||||
settings = new VisionSettings();
|
||||
if (string.IsNullOrEmpty(json) || json == "{}") return false;
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
JsonElement r = doc.RootElement;
|
||||
bool any = false;
|
||||
bool Int(string key, ref bool field) { if (!r.TryGetProperty(key, out var v)) return false; field = v.GetInt32() != 0; return true; }
|
||||
any |= Int("radar", ref settings.Radar);
|
||||
any |= Int("slopes", ref settings.Slopes);
|
||||
any |= Int("water", ref settings.Water);
|
||||
any |= Int("waterAnyCorner", ref settings.WaterAnyCorner);
|
||||
any |= Int("waterImpassableOnly", ref settings.WaterImpassableOnly);
|
||||
if (r.TryGetProperty("slopeColor", out var e)) { settings.SlopeColor = e.GetUInt32(); any = true; }
|
||||
if (r.TryGetProperty("waterColor", out e)) { settings.WaterColor = e.GetUInt32(); any = true; }
|
||||
if (r.TryGetProperty("radarColor", out e)) { settings.RadarColor = e.GetUInt32(); any = true; }
|
||||
if (r.TryGetProperty("radarRange", out e)) { settings.RadarRange = e.GetDouble(); any = true; }
|
||||
if (r.TryGetProperty("ringThick", out e)) { settings.RingThick = e.GetDouble(); any = true; }
|
||||
if (r.TryGetProperty("ringHeight", out e)) { settings.RingHeight = e.GetDouble(); any = true; }
|
||||
if (r.TryGetProperty("slopeRadius", out e)) { settings.SlopeRadius = e.GetInt32(); any = true; }
|
||||
if (r.TryGetProperty("slopeFloorZ", out e)) { settings.SlopeFloorZ = e.GetDouble(); any = true; }
|
||||
if (r.TryGetProperty("slopeBias", out e)) { settings.SlopeBias = e.GetDouble(); any = true; }
|
||||
if (r.TryGetProperty("waterRadius", out e)) { settings.WaterRadius = e.GetInt32(); any = true; }
|
||||
if (r.TryGetProperty("waterTypes", out e) && e.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement t in e.EnumerateArray()) settings.WaterTypes.Add(t.GetInt32());
|
||||
any = true;
|
||||
}
|
||||
return any;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>One field as the plugin's JSON, e.g. {"radar":1}. Key: a <see cref="VisionKeys"/> constant.</summary>
|
||||
public string FieldJson(string key)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
string value = key switch
|
||||
{
|
||||
VisionKeys.Radar => Radar ? "1" : "0",
|
||||
VisionKeys.Slopes => Slopes ? "1" : "0",
|
||||
VisionKeys.Water => Water ? "1" : "0",
|
||||
VisionKeys.WaterAnyCorner => WaterAnyCorner ? "1" : "0",
|
||||
VisionKeys.WaterImpassableOnly => WaterImpassableOnly ? "1" : "0",
|
||||
VisionKeys.SlopeColor => SlopeColor.ToString(ci),
|
||||
VisionKeys.WaterColor => WaterColor.ToString(ci),
|
||||
VisionKeys.RadarColor => RadarColor.ToString(ci),
|
||||
VisionKeys.RadarRange => RadarRange.ToString("R", ci),
|
||||
VisionKeys.RingThick => RingThick.ToString("R", ci),
|
||||
VisionKeys.RingHeight => RingHeight.ToString("R", ci),
|
||||
VisionKeys.SlopeRadius => SlopeRadius.ToString(ci),
|
||||
VisionKeys.SlopeFloorZ => SlopeFloorZ.ToString("R", ci),
|
||||
VisionKeys.SlopeBias => SlopeBias.ToString("R", ci),
|
||||
VisionKeys.WaterRadius => WaterRadius.ToString(ci),
|
||||
VisionKeys.WaterTypes => "[" + string.Join(",", WaterTypes) + "]",
|
||||
_ => throw new ArgumentException($"Unknown Vision setting '{key}'", nameof(key)),
|
||||
};
|
||||
return "{\"" + key + "\":" + value + "}";
|
||||
}
|
||||
|
||||
/// <summary>"18,19,20" -> the numbers in it (anything else is dropped).</summary>
|
||||
public static List<int> ParseCsv(string? csv)
|
||||
{
|
||||
var list = new List<int>();
|
||||
if (string.IsNullOrWhiteSpace(csv)) return list;
|
||||
foreach (string part in csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
if (int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) list.Add(n);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>"AARRGGBB" or "RRGGBB" (opaque), with or without '#'.</summary>
|
||||
public static bool TryParseHex(string? s, out uint argb)
|
||||
{
|
||||
argb = 0;
|
||||
if (string.IsNullOrWhiteSpace(s)) return false;
|
||||
s = s.Trim().TrimStart('#');
|
||||
if (s.Length == 6) s = "FF" + s;
|
||||
return s.Length == 8 && uint.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The plugin's settings JSON keys.</summary>
|
||||
internal static class VisionKeys
|
||||
{
|
||||
public const string Radar = "radar", Slopes = "slopes", Water = "water";
|
||||
public const string WaterAnyCorner = "waterAnyCorner", WaterImpassableOnly = "waterImpassableOnly";
|
||||
public const string SlopeColor = "slopeColor", WaterColor = "waterColor", RadarColor = "radarColor";
|
||||
public const string RadarRange = "radarRange", RingThick = "ringThick", RingHeight = "ringHeight";
|
||||
public const string SlopeRadius = "slopeRadius", SlopeFloorZ = "slopeFloorZ", SlopeBias = "slopeBias";
|
||||
public const string WaterRadius = "waterRadius", WaterTypes = "waterTypes";
|
||||
}
|
||||
|
||||
internal sealed class VisionSnapshot
|
||||
{
|
||||
public VisionSnapshot(string json, VisionSettings settings) { Json = json; Settings = settings; }
|
||||
public string Json { get; }
|
||||
/// <summary>Shared: copy before changing (Clone).</summary>
|
||||
public VisionSettings Settings { get; }
|
||||
}
|
||||
|
||||
/// <summary>RynthVisionGetSettingsJson while a Vision face is open (5 s, and after each save).</summary>
|
||||
internal sealed unsafe class VisionSource : UiSource<VisionSnapshot>
|
||||
{
|
||||
private delegate* unmanaged[Cdecl]<IntPtr> _get;
|
||||
private string? _lastJson;
|
||||
|
||||
public VisionSource() : base("Vision", periodMs: 5000) { }
|
||||
|
||||
protected internal override void Poll()
|
||||
{
|
||||
if (_get == null)
|
||||
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthVision", "RynthVisionGetSettingsJson");
|
||||
if (_get == null) return;
|
||||
IntPtr ptr = _get();
|
||||
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
|
||||
if (!VisionSettings.TryParse(json, out VisionSettings settings)) return;
|
||||
_lastJson = json;
|
||||
Publish(new VisionSnapshot(json, settings));
|
||||
}
|
||||
|
||||
protected internal override void Reset()
|
||||
{
|
||||
_get = null;
|
||||
_lastJson = null;
|
||||
ClearSnapshot();
|
||||
}
|
||||
|
||||
/// <summary>Publish on the next poll even if the JSON is unchanged. Pump thread.</summary>
|
||||
internal void RequestRepublish()
|
||||
{
|
||||
_lastJson = null;
|
||||
RequestRefresh();
|
||||
}
|
||||
}
|
||||
|
||||
internal static unsafe class VisionCommands
|
||||
{
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, void> _set;
|
||||
private static delegate* unmanaged[Cdecl]<void> _inspect;
|
||||
|
||||
static VisionCommands()
|
||||
{
|
||||
PluginManager.PluginsUnloaded += () => { _set = null; _inspect = null; };
|
||||
}
|
||||
|
||||
/// <summary>Applies and saves one field: <paramref name="key"/>'s value from <paramref name="settings"/>.</summary>
|
||||
public static void SaveField(VisionSettings settings, string key) => Save(settings.FieldJson(key));
|
||||
|
||||
/// <summary>Applies and saves the settings in <paramref name="json"/> (any subset of the keys).</summary>
|
||||
public static void Save(string json) => UiDataHub.Post("Vision save", () =>
|
||||
{
|
||||
if (_set == null) _set = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthVision", "RynthVisionSetSettings");
|
||||
if (_set == null) return;
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _set(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
UiSources.Vision.RequestRepublish();
|
||||
});
|
||||
|
||||
/// <summary>Logs the terrain types under the player (RynthVision's diagnostic).</summary>
|
||||
public static void Inspect() => UiDataHub.Post("Vision inspect", () =>
|
||||
{
|
||||
if (_inspect == null) _inspect = (delegate* unmanaged[Cdecl]<void>)PluginExportBinder.Resolve("RynthVision", "RynthVisionInspectTerrain");
|
||||
if (_inspect != null) _inspect();
|
||||
});
|
||||
}
|
||||
|
|
@ -308,6 +308,7 @@ internal sealed class DcompOverlayWindow : Window
|
|||
["Monsters"] = new(MonstersPanel.Create, true, 460, 480),
|
||||
["Nav"] = new(NavPanel.Create, true, 420, 480),
|
||||
["Meta"] = new(MetaPanel.Create, true, 460, 480),
|
||||
["Lua"] = new(LuaPanel.Create, true, 460, 560),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -193,7 +193,15 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
[DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hWnd);
|
||||
[DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
|
||||
[DllImport("user32.dll")] private static extern IntPtr SetCapture(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetCapture();
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MONITORINFO { public int cbSize; public RECT rcMonitor; public RECT rcWork; public uint dwFlags; }
|
||||
private const uint MONITOR_DEFAULTTONEAREST = 2;
|
||||
[DllImport("user32.dll")] private static extern IntPtr MonitorFromRect(ref RECT rect, uint flags);
|
||||
[DllImport("user32.dll")] private static extern bool GetMonitorInfoW(IntPtr monitor, ref MONITORINFO info);
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
[DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd);
|
||||
|
|
@ -261,9 +269,24 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
private static readonly Dictionary<IntPtr, LayeredWindow> _instances = new();
|
||||
private static int _hittestDiagCount;
|
||||
|
||||
/// <summary>
|
||||
/// Posted to a panel window to destroy itself. Handled here, before the
|
||||
/// instance lookup, so it runs on whichever thread created the window —
|
||||
/// 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.
|
||||
/// </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)
|
||||
{
|
||||
if (msg == WM_RYNTH_SELF_DESTROY)
|
||||
{
|
||||
DestroyWindow(hwnd);
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
LayeredWindow? self;
|
||||
lock (_instancesLock)
|
||||
_instances.TryGetValue(hwnd, out self);
|
||||
|
|
@ -305,6 +328,87 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
/// load's own windows (class names carry a per-load Guid) and removes only
|
||||
/// ones an earlier load left behind.
|
||||
/// </summary>
|
||||
[DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
|
||||
[DllImport("user32.dll")] private static extern bool IsWindow(IntPtr hWnd);
|
||||
[DllImport("user32.dll")] private static extern int EnumWindows(delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int> lpfn, IntPtr lParam);
|
||||
[DllImport("kernel32.dll")] private static extern uint GetCurrentProcessId();
|
||||
|
||||
/// <summary>
|
||||
/// Takes a panel window off the screen at once (never blocks, any thread)
|
||||
/// and asks its own thread to destroy it.
|
||||
/// </summary>
|
||||
internal static bool Retire(IntPtr hwnd)
|
||||
{
|
||||
if (hwnd == IntPtr.Zero || !IsWindow(hwnd)) return false;
|
||||
ShowWindowAsync(hwnd, SW_HIDE);
|
||||
return PostMessage(hwnd, WM_RYNTH_SELF_DESTROY, IntPtr.Zero, IntPtr.Zero);
|
||||
}
|
||||
|
||||
// Panel title → the window currently showing it popped out.
|
||||
private static readonly Dictionary<string, IntPtr> _windowByTitle = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Records <paramref name="hwnd"/> as the one popped-out window for
|
||||
/// <paramref name="title"/>; any earlier window for that title is retired.
|
||||
/// A panel can never have two popped-out windows.
|
||||
/// </summary>
|
||||
internal static void ClaimTitle(string title, IntPtr hwnd)
|
||||
{
|
||||
IntPtr prior;
|
||||
lock (_instancesLock)
|
||||
{
|
||||
_windowByTitle.TryGetValue(title, out prior);
|
||||
_windowByTitle[title] = hwnd;
|
||||
}
|
||||
if (prior != IntPtr.Zero && prior != hwnd && IsWindow(prior))
|
||||
{
|
||||
RynthCore.Engine.RynthLog.Info($"LayeredWindow: '{title}' already had window 0x{prior.ToInt64():X}; retiring it for 0x{hwnd.ToInt64():X}.");
|
||||
Retire(prior);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly HashSet<IntPtr> _sweptLogged = new();
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
|
||||
private static int CollectTopWindow(IntPtr hwnd, IntPtr lParam)
|
||||
{
|
||||
if (GCHandle.FromIntPtr(lParam).Target is List<IntPtr> found)
|
||||
found.Add(hwnd);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every visible panel window of this process that no live LayeredWindow
|
||||
/// owns (it was disposed but survived, or an earlier engine load left it)
|
||||
/// is hidden and destroyed. Live windows are always in _instances, so this
|
||||
/// can't touch an open panel. Any thread; run from the heartbeat.
|
||||
/// </summary>
|
||||
internal static void SweepOrphans()
|
||||
{
|
||||
var found = new List<IntPtr>();
|
||||
GCHandle handle = GCHandle.Alloc(found);
|
||||
try { EnumWindows(&CollectTopWindow, GCHandle.ToIntPtr(handle)); }
|
||||
finally { handle.Free(); }
|
||||
|
||||
uint pid = GetCurrentProcessId();
|
||||
char* buffer = stackalloc char[128];
|
||||
foreach (IntPtr hwnd in found)
|
||||
{
|
||||
GetWindowThreadProcessId(hwnd, out uint winPid);
|
||||
if (winPid != pid || !IsWindowVisible(hwnd)) continue;
|
||||
int length = GetClassNameW(hwnd, buffer, 128);
|
||||
if (length <= 0) continue;
|
||||
if (!new string(buffer, 0, length).StartsWith(ClassNamePrefix, StringComparison.Ordinal)) continue;
|
||||
bool live;
|
||||
lock (_instancesLock) live = _instances.ContainsKey(hwnd);
|
||||
if (live) continue;
|
||||
bool first;
|
||||
lock (_instancesLock) first = _sweptLogged.Add(hwnd);
|
||||
if (first) RynthCore.Engine.RynthLog.Info($"LayeredWindow: orphan panel window 0x{hwnd.ToInt64():X} still visible; hiding and destroying it.");
|
||||
Retire(hwnd);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DestroyThreadPanelWindows(bool includeThisGeneration)
|
||||
{
|
||||
var found = new List<IntPtr>();
|
||||
|
|
@ -338,17 +442,44 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
|
||||
// ─── Instance state ────────────────────────────────────────────────────
|
||||
public IntPtr Hwnd { get; private set; }
|
||||
|
||||
// The panel ("content") rect on the screen. The HWND can be larger: a popped-out
|
||||
// ImGui panel's window grows a transparent margin while a tooltip or popup reaches
|
||||
// past the panel (Present). The margins are the _inset* fields; they are always 0
|
||||
// for windows fed by UpdatePixels (the Avalonia pop-outs), where the HWND is the
|
||||
// content. Drag band, grip, moves, resizes and EnsureOnScreen all work on the content.
|
||||
public int Width { get; private set; }
|
||||
public int Height { get; private set; }
|
||||
public int ScreenLeft { get; private set; }
|
||||
public int ScreenTop { get; private set; }
|
||||
|
||||
private int _insetL, _insetT, _insetR, _insetB;
|
||||
|
||||
/// <summary>The HWND's rect (the content plus its transparent margins).</summary>
|
||||
public int SurfaceLeft => ScreenLeft - _insetL;
|
||||
public int SurfaceTop => ScreenTop - _insetT;
|
||||
public int SurfaceWidth => Width + _insetL + _insetR;
|
||||
public int SurfaceHeight => Height + _insetT + _insetB;
|
||||
|
||||
/// <summary>True while the window is being moved or resized by the mouse.</summary>
|
||||
public bool IsDragging => _dragMode != DragNone;
|
||||
|
||||
/// <summary>
|
||||
/// True: only the content rect takes the mouse; anything drawn in the margins (a
|
||||
/// tooltip) lets clicks through to the window below, like its transparent pixels.
|
||||
/// Set false while the margins hold something clickable (a popup menu).
|
||||
/// </summary>
|
||||
public bool MarginsClickThrough { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Pixel height of the top "drag" region — WM_NCHITTEST returns HTCAPTION
|
||||
/// here so the OS handles drag-to-move with no input forwarding needed.
|
||||
/// </summary>
|
||||
public int CaptionHeight { get; set; } = 24;
|
||||
|
||||
/// <summary>False: no bottom-right resize corner (a window sized to its content, like the bar).</summary>
|
||||
public bool ResizeGripEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Pixel width of the right portion of the caption that should NOT act
|
||||
/// as a drag handle — used to keep the popout/close buttons clickable
|
||||
|
|
@ -502,8 +633,13 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
// lParam is screen coord — convert to layered-client.
|
||||
int sx = (short)((long)lParam & 0xFFFF);
|
||||
int sy = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
int cx = sx - ScreenLeft;
|
||||
int cy = sy - ScreenTop;
|
||||
int cx = sx - SurfaceLeft;
|
||||
int cy = sy - SurfaceTop;
|
||||
|
||||
// Outside the content, in a margin holding only a tooltip: not ours.
|
||||
if (MarginsClickThrough && (_insetL | _insetT | _insetR | _insetB) != 0
|
||||
&& (cx < _insetL || cy < _insetT || cx >= _insetL + Width || cy >= _insetT + Height))
|
||||
return (IntPtr)HTTRANSPARENT;
|
||||
|
||||
// NOTE: we intentionally do NOT return HTBOTTOMRIGHT (resize
|
||||
// grip) or HTCAPTION (move) here. Either would make DefWindowProc
|
||||
|
|
@ -604,15 +740,16 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
{
|
||||
int x = (short)((long)lParam & 0xFFFF);
|
||||
int y = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
ScreenLeft = x;
|
||||
ScreenTop = y;
|
||||
ScreenLeft = x + _insetL;
|
||||
ScreenTop = y + _insetT;
|
||||
// During the OS HTCAPTION modal drag loop, WM_TIMER can be
|
||||
// suppressed so Tick() / UpdateLayeredWindow may not fire
|
||||
// while the HWND moves. Repaint existing pixels at the new
|
||||
// screen position on every WM_MOVE so the layered visual
|
||||
// tracks the HWND without waiting for the next timer tick.
|
||||
// No pixel copy — just repositions the existing DIB.
|
||||
if (_modalSizeMoveActive)
|
||||
// (Not from inside Present's own UpdateLayeredWindow.)
|
||||
if (_modalSizeMoveActive && !_presenting)
|
||||
PaintExistingPixelsAt(x, y);
|
||||
if (_suppressMoveCallback) break;
|
||||
// Defer the persist callback to drag end (WM_EXITSIZEMOVE) —
|
||||
|
|
@ -620,14 +757,14 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
if (_modalSizeMoveActive)
|
||||
_pendingMoveNotify = true;
|
||||
else
|
||||
OnMoved?.Invoke(x, y);
|
||||
OnMoved?.Invoke(ScreenLeft, ScreenTop);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_SIZE:
|
||||
{
|
||||
int w = (short)((long)lParam & 0xFFFF);
|
||||
int h = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
int w = (short)((long)lParam & 0xFFFF) - _insetL - _insetR;
|
||||
int h = (short)(((long)lParam >> 16) & 0xFFFF) - _insetT - _insetB;
|
||||
if (w > 0 && h > 0)
|
||||
{
|
||||
Width = w;
|
||||
|
|
@ -647,8 +784,9 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
|
||||
case WM_LBUTTONDOWN:
|
||||
{
|
||||
int cx = (short)((long)lParam & 0xFFFF);
|
||||
int cy = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
// Client coordinates are the HWND's; the chrome below is the content's.
|
||||
int cx = (short)((long)lParam & 0xFFFF) - _insetL;
|
||||
int cy = (short)(((long)lParam >> 16) & 0xFFFF) - _insetT;
|
||||
RynthCore.Engine.RynthLog.Info($"LayeredWindow(0x{Hwnd.ToInt64():X}): WM_LBUTTONDOWN at layered=({cx},{cy}).");
|
||||
|
||||
// Native chrome-button detection: floating panels live at
|
||||
|
|
@ -677,7 +815,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
// Resize grip (bottom-right). Handle the resize ourselves rather
|
||||
// than via the OS modal loop — see BeginDrag / the WM_NCHITTEST
|
||||
// note. Checked before the caption so the corner wins.
|
||||
if (cx >= Width - GripPx && cy >= Height - GripPx && cx < Width && cy < Height)
|
||||
if (ResizeGripEnabled && cx >= Width - GripPx && cy >= Height - GripPx && cx < Width && cy < Height)
|
||||
{
|
||||
BeginDrag(DragResize);
|
||||
return IntPtr.Zero;
|
||||
|
|
@ -743,7 +881,12 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
case WM_CAPTURECHANGED:
|
||||
// Mouse capture was taken from us (alt-tab, another grab, or our
|
||||
// own ReleaseCapture in EndDrag). Don't leave a drag latched.
|
||||
CancelDragFromCaptureLoss();
|
||||
// lParam is the window gaining capture: this window taking it
|
||||
// again is not a loss (a content drag starts while the press
|
||||
// already holds capture, and SetCapture on the capturing window
|
||||
// still sends this message - it cancelled every content drag).
|
||||
if (lParam != Hwnd)
|
||||
CancelDragFromCaptureLoss();
|
||||
break;
|
||||
|
||||
case WM_DESTROY:
|
||||
|
|
@ -855,7 +998,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
{
|
||||
if (_disposed || Hwnd == IntPtr.Zero || _memDc == IntPtr.Zero || _hbm == IntPtr.Zero) return;
|
||||
var dstPt = new POINT { X = screenX, Y = screenY };
|
||||
var size = new SIZE { CX = Width, CY = Height };
|
||||
var size = new SIZE { CX = SurfaceWidth, CY = SurfaceHeight };
|
||||
var srcPt = new POINT { X = 0, Y = 0 };
|
||||
var blend = new BLENDFUNCTION
|
||||
{
|
||||
|
|
@ -869,6 +1012,29 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
|
||||
// ─── Custom non-modal move/resize (see the _dragMode fields) ─────────────
|
||||
|
||||
/// <summary>
|
||||
/// Starts moving the window from a press inside the content (a chromeless
|
||||
/// ImGui panel dragged by its own surface). The content saw the button go
|
||||
/// down, so it is sent a button-up at the end of the move.
|
||||
/// </summary>
|
||||
public void BeginContentMove()
|
||||
{
|
||||
if (_disposed || Hwnd == IntPtr.Zero || _dragMode != DragNone) return;
|
||||
_dragFromContent = true;
|
||||
BeginDrag(DragMove);
|
||||
}
|
||||
|
||||
private bool _dragFromContent;
|
||||
|
||||
private void ReleaseContentButton()
|
||||
{
|
||||
if (!_dragFromContent) return;
|
||||
_dragFromContent = false;
|
||||
if (!GetCursorPos(out POINT p)) return;
|
||||
int cx = p.X - SurfaceLeft, cy = p.Y - SurfaceTop; // HWND client coordinates, like any mouse message
|
||||
ForwardInput(WM_LBUTTONUP, IntPtr.Zero, (IntPtr)((cy << 16) | (cx & 0xFFFF)));
|
||||
}
|
||||
|
||||
private void BeginDrag(int mode)
|
||||
{
|
||||
if (!GetCursorPos(out POINT p)) return;
|
||||
|
|
@ -886,7 +1052,12 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
_pendingMoveNotify = false;
|
||||
_pendingResizeNotify = false;
|
||||
_lastResizeApplyTick = 0;
|
||||
SetCapture(Hwnd);
|
||||
// A content move starts while the press that began it already holds capture
|
||||
// (WM_LBUTTONDOWN took it). Taking it again sent WM_CAPTURECHANGED, which
|
||||
// ended the drag as soon as it began: popped-out faces that drag by their
|
||||
// own surface (the RynthAi dashboard, the bar) could not be moved.
|
||||
if (GetCapture() != Hwnd)
|
||||
SetCapture(Hwnd);
|
||||
}
|
||||
|
||||
private void UpdateDrag()
|
||||
|
|
@ -928,11 +1099,15 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
_pendingMoveNotify = false;
|
||||
_pendingResizeNotify = false;
|
||||
ReleaseCapture();
|
||||
ReleaseContentButton();
|
||||
|
||||
// Persist the final geometry (mirrors what WM_EXITSIZEMOVE used to do
|
||||
// for the OS modal loop).
|
||||
// for the OS modal loop). A move never leaves the window off the screen.
|
||||
if (mode == DragMove)
|
||||
{
|
||||
EnsureOnScreen();
|
||||
OnMoved?.Invoke(ScreenLeft, ScreenTop);
|
||||
}
|
||||
else if (mode == DragResize)
|
||||
OnResizeEnd?.Invoke(Width, Height);
|
||||
}
|
||||
|
|
@ -952,12 +1127,65 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
_modalSizeMoveActive = false;
|
||||
_pendingMoveNotify = false;
|
||||
_pendingResizeNotify = false;
|
||||
ReleaseContentButton();
|
||||
if (mode == DragMove)
|
||||
{
|
||||
EnsureOnScreen();
|
||||
OnMoved?.Invoke(ScreenLeft, ScreenTop);
|
||||
}
|
||||
else if (mode == DragResize)
|
||||
OnResizeEnd?.Invoke(Width, Height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pulls a (left, top, width, height) rectangle inside the work area of the
|
||||
/// monitor nearest to it: wholly inside when it fits, else its top-left corner.
|
||||
/// True when it had to move. Any thread.
|
||||
/// </summary>
|
||||
public static bool ClampToWorkArea(ref int left, ref int top, int width, int height)
|
||||
{
|
||||
var r = new RECT { Left = left, Top = top, Right = left + Math.Max(1, width), Bottom = top + Math.Max(1, height) };
|
||||
IntPtr monitor = MonitorFromRect(ref r, MONITOR_DEFAULTTONEAREST);
|
||||
var info = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
|
||||
if (monitor == IntPtr.Zero || !GetMonitorInfoW(monitor, ref info)) return false;
|
||||
RECT work = info.rcWork;
|
||||
int x = Math.Clamp(left, work.Left, Math.Max(work.Left, work.Right - width));
|
||||
int y = Math.Clamp(top, work.Top, Math.Max(work.Top, work.Bottom - height));
|
||||
if (x == left && y == top) return false;
|
||||
left = x;
|
||||
top = y;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The work area of the monitor nearest a rectangle (screen px). Any thread.</summary>
|
||||
public static bool TryGetWorkArea(int left, int top, int width, int height, out int workLeft, out int workTop, out int workRight, out int workBottom)
|
||||
{
|
||||
workLeft = workTop = workRight = workBottom = 0;
|
||||
var r = new RECT { Left = left, Top = top, Right = left + Math.Max(1, width), Bottom = top + Math.Max(1, height) };
|
||||
IntPtr monitor = MonitorFromRect(ref r, MONITOR_DEFAULTTONEAREST);
|
||||
var info = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
|
||||
if (monitor == IntPtr.Zero || !GetMonitorInfoW(monitor, ref info)) return false;
|
||||
workLeft = info.rcWork.Left;
|
||||
workTop = info.rcWork.Top;
|
||||
workRight = info.rcWork.Right;
|
||||
workBottom = info.rcWork.Bottom;
|
||||
return workRight > workLeft && workBottom > workTop;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the window back inside the nearest monitor's work area when any of
|
||||
/// it is off the screen. No OnMoved (the caller persists). True when it moved.
|
||||
/// The window's thread.
|
||||
/// </summary>
|
||||
public bool EnsureOnScreen()
|
||||
{
|
||||
if (_disposed || Hwnd == IntPtr.Zero || _dragMode != DragNone) return false; // a drag ends with its own check
|
||||
int x = ScreenLeft, y = ScreenTop;
|
||||
if (!ClampToWorkArea(ref x, ref y, Width, Height)) return false;
|
||||
Move(x, y);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resize the HWND in place without the OS modal loop. SetWindowPos sends
|
||||
/// WM_SIZE synchronously to our WndProc, which updates Width/Height and fires
|
||||
|
|
@ -970,7 +1198,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
if (newW < MinDragW) newW = MinDragW;
|
||||
if (newH < MinDragH) newH = MinDragH;
|
||||
if (newW == Width && newH == Height) return;
|
||||
SetWindowPos(Hwnd, IntPtr.Zero, 0, 0, newW, newH,
|
||||
SetWindowPos(Hwnd, IntPtr.Zero, 0, 0, newW + _insetL + _insetR, newH + _insetT + _insetB,
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
|
||||
|
|
@ -1106,6 +1334,69 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
}
|
||||
}
|
||||
|
||||
private bool _presenting;
|
||||
|
||||
/// <summary>
|
||||
/// Shows a picture of <paramref name="surfaceWidth"/> x <paramref name="surfaceHeight"/>
|
||||
/// premultiplied BGRA pixels in which the content (the panel) is the
|
||||
/// <paramref name="contentWidth"/> x <paramref name="contentHeight"/> rect at
|
||||
/// (<paramref name="insetLeft"/>, <paramref name="insetTop"/>); the rest is margin
|
||||
/// (transparent, or a tooltip or popup reaching past the panel). The content stays
|
||||
/// where it is on the screen: the HWND takes the picture's size and moves by the
|
||||
/// margin, all in one UpdateLayeredWindow call, so nothing flickers or jumps.
|
||||
/// The popped-out ImGui panels use this; UpdatePixels (no margins) is the Avalonia
|
||||
/// pop-outs'. The window's thread.
|
||||
/// </summary>
|
||||
public void Present(IntPtr bgraData, int rowPitch, int surfaceWidth, int surfaceHeight,
|
||||
int insetLeft, int insetTop, int contentWidth, int contentHeight)
|
||||
{
|
||||
if (_disposed || Hwnd == IntPtr.Zero || bgraData == IntPtr.Zero) return;
|
||||
if (surfaceWidth <= 0 || surfaceHeight <= 0 || contentWidth <= 0 || contentHeight <= 0) return;
|
||||
int insetRight = surfaceWidth - insetLeft - contentWidth;
|
||||
int insetBottom = surfaceHeight - insetTop - contentHeight;
|
||||
if (insetLeft < 0 || insetTop < 0 || insetRight < 0 || insetBottom < 0) return;
|
||||
// A resize drag outran this picture (it was rendered at the size before the last
|
||||
// step): keep the last one up; the next frame is drawn at the new size.
|
||||
if (_dragMode == DragResize && (contentWidth != Width || contentHeight != Height)) return;
|
||||
|
||||
EnsureDib(surfaceWidth, surfaceHeight);
|
||||
if (_dibBits == IntPtr.Zero) return;
|
||||
int dibStride = _dibWidth * 4;
|
||||
int rowBytes = surfaceWidth * 4;
|
||||
for (int y = 0; y < surfaceHeight; y++)
|
||||
Buffer.MemoryCopy((byte*)bgraData + (long)y * rowPitch, (byte*)_dibBits + (long)y * dibStride, dibStride, rowBytes);
|
||||
|
||||
// The picture's geometry becomes the window's. Set first: the WM_MOVE / WM_SIZE
|
||||
// the update sends read the content back out of the HWND rect with these.
|
||||
_insetL = insetLeft; _insetT = insetTop; _insetR = insetRight; _insetB = insetBottom;
|
||||
Width = contentWidth;
|
||||
Height = contentHeight;
|
||||
|
||||
var dstPt = new POINT { X = ScreenLeft - insetLeft, Y = ScreenTop - insetTop };
|
||||
var size = new SIZE { CX = surfaceWidth, CY = surfaceHeight };
|
||||
var srcPt = new POINT { X = 0, Y = 0 };
|
||||
var blend = new BLENDFUNCTION { BlendOp = AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = 255, AlphaFormat = AC_SRC_ALPHA };
|
||||
_suppressMoveCallback = true;
|
||||
_suppressResizeCallback = true;
|
||||
_presenting = true;
|
||||
bool ok;
|
||||
try
|
||||
{
|
||||
ok = UpdateLayeredWindow(Hwnd, IntPtr.Zero, ref dstPt, ref size, _memDc, ref srcPt, 0, ref blend, ULW_ALPHA);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_presenting = false;
|
||||
_suppressMoveCallback = false;
|
||||
_suppressResizeCallback = false;
|
||||
}
|
||||
if (!ok && _updateLogCount < 6)
|
||||
{
|
||||
_updateLogCount++;
|
||||
RynthLog.Info($"LayeredWindow(0x{Hwnd.ToInt64():X}): Present {surfaceWidth}x{surfaceHeight} at ({dstPt.X},{dstPt.Y}) failed, err={Marshal.GetLastWin32Error()}.");
|
||||
}
|
||||
}
|
||||
|
||||
private const int GWL_HWNDPARENT = -8;
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -1133,7 +1424,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
_suppressMoveCallback = true;
|
||||
try
|
||||
{
|
||||
SetWindowPos(Hwnd, IntPtr.Zero, screenLeft, screenTop, 0, 0,
|
||||
SetWindowPos(Hwnd, IntPtr.Zero, screenLeft - _insetL, screenTop - _insetT, 0, 0,
|
||||
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
finally { _suppressMoveCallback = false; }
|
||||
|
|
@ -1178,7 +1469,18 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
|||
if (hwnd != IntPtr.Zero)
|
||||
{
|
||||
lock (_instancesLock)
|
||||
{
|
||||
_instances.Remove(hwnd);
|
||||
string? owned = null;
|
||||
foreach (var kv in _windowByTitle) if (kv.Value == hwnd) { owned = kv.Key; break; }
|
||||
if (owned != null) _windowByTitle.Remove(owned);
|
||||
}
|
||||
|
||||
// Off the screen now, and ask the window's own thread to destroy it
|
||||
// (works for a window created on any thread). Only if that post fails
|
||||
// fall back to the game-thread destroy below: doing both could destroy
|
||||
// an unrelated window that reused the handle in between.
|
||||
if (Retire(hwnd)) { DisposeDib(); return; }
|
||||
|
||||
// DestroyWindow MUST run on the thread that owns the HWND — Win32
|
||||
// silently no-ops it otherwise. The HWND was created on the game
|
||||
|
|
|
|||
67
src/RynthCore.Engine/UI/PanelColumnStore.cs
Normal file
67
src/RynthCore.Engine/UI/PanelColumnStore.cs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/PanelColumnStore.cs
|
||||
// Column widths the user dragged in the in-game panels (Damage, Monsters,
|
||||
// Meta). Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_columns.txt
|
||||
// as "Panel.key=value" lines. Read once; written when a drag ends.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class PanelColumnStore
|
||||
{
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<string, float> Values = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static bool _loaded;
|
||||
|
||||
private static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_columns.txt");
|
||||
|
||||
public static float Get(string key, float fallback)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
return Values.TryGetValue(key, out float v) ? v : fallback;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Set(string key, float value)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
Values[key] = value;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
|
||||
var lines = new List<string>();
|
||||
foreach (var kv in Values) lines.Add($"{kv.Key}={kv.Value.ToString("0.###", CultureInfo.InvariantCulture)}");
|
||||
File.WriteAllLines(FilePath, lines);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static void Load()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return;
|
||||
foreach (string line in File.ReadAllLines(FilePath))
|
||||
{
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
if (float.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float v))
|
||||
Values[line[..eq].Trim()] = v;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
120
src/RynthCore.Engine/UI/PanelFaceStore.cs
Normal file
120
src/RynthCore.Engine/UI/PanelFaceStore.cs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/PanelFaceStore.cs
|
||||
// Which face shows a panel while it is docked in the client:
|
||||
// %LocalAppData%\RynthCore\panel_faces.txt, one "<Title>=avalonia|imgui|both"
|
||||
// per line. Popped-out panels are always Avalonia windows, so only the docked
|
||||
// face is a choice (docs/IMGUI_PARITY_PLAN.md, "ImGui in game, Avalonia when
|
||||
// popped out").
|
||||
//
|
||||
// Its own file rather than a panel_state.txt row: PanelStateStore rewrites
|
||||
// that file from memory and drops rows it doesn't recognise, so an older
|
||||
// engine would silently erase the choice. Engine-owned; the launcher never
|
||||
// writes it. A missing entry means "use the code default".
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal enum PanelFace
|
||||
{
|
||||
Avalonia,
|
||||
ImGui,
|
||||
/// <summary>Both faces docked at once, the ImGui copy offset, for side-by-side checks.</summary>
|
||||
Both,
|
||||
}
|
||||
|
||||
internal static class PanelFaceStore
|
||||
{
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<string, PanelFace> Faces = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static bool _loaded;
|
||||
|
||||
private static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_faces.txt");
|
||||
|
||||
public static bool TryGet(string title, out PanelFace face)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return Faces.TryGetValue(title, out face);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stores a choice; null clears it back to the code default.</summary>
|
||||
public static void Set(string title, PanelFace? face)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
EnsureLoaded();
|
||||
if (face is PanelFace f) Faces[title] = f;
|
||||
else Faces.Remove(title);
|
||||
}
|
||||
// May be called from AC's thread (the ImGui bar's menu): write in the background.
|
||||
UiBackgroundWriter.Enqueue("panel faces", () => { lock (Sync) Save(); });
|
||||
}
|
||||
|
||||
public static string FaceName(PanelFace face) => face switch
|
||||
{
|
||||
PanelFace.ImGui => "imgui",
|
||||
PanelFace.Both => "both",
|
||||
_ => "avalonia",
|
||||
};
|
||||
|
||||
public static bool TryParseFace(string text, out PanelFace face)
|
||||
{
|
||||
switch (text.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "avalonia": face = PanelFace.Avalonia; return true;
|
||||
case "imgui": face = PanelFace.ImGui; return true;
|
||||
case "both": face = PanelFace.Both; return true;
|
||||
default: face = PanelFace.Avalonia; return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureLoaded()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
if (!File.Exists(path)) return;
|
||||
foreach (string raw in File.ReadAllLines(path))
|
||||
{
|
||||
string line = raw.Trim();
|
||||
if (line.Length == 0 || line[0] == '#') continue;
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
if (TryParseFace(line.Substring(eq + 1), out PanelFace face))
|
||||
Faces[line.Substring(0, eq).Trim()] = face;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.UI($"PanelFaceStore: load failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("# RynthCore docked panel face (avalonia|imgui|both). Set with /rc ui <Panel> <face>.");
|
||||
foreach (var (title, face) in Faces)
|
||||
sb.Append(title).Append('=').AppendLine(FaceName(face));
|
||||
File.WriteAllText(path, sb.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.UI($"PanelFaceStore: save failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
227
src/RynthCore.Engine/UI/PanelRouter.cs
Normal file
227
src/RynthCore.Engine/UI/PanelRouter.cs
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/PanelRouter.cs
|
||||
// The one place that decides which face shows a panel.
|
||||
//
|
||||
// Model (Tom, 2026-09-27): a panel docked in the client is drawn by its
|
||||
// ImGui face; a panel popped out of the client is an Avalonia window. While
|
||||
// the ImGui faces are being built, each panel's docked face is chosen per
|
||||
// panel (PanelFaceStore; code default Avalonia) and falls back to Avalonia
|
||||
// whenever ImGui can't show it.
|
||||
//
|
||||
// Every "open/close this panel" request goes through Toggle: bar buttons
|
||||
// (docked and floating bar), the RynthAi launcher, Chat's Filters button and
|
||||
// chat commands. Bar actions that aren't panels (RL, bar pop-out) pass
|
||||
// straight through.
|
||||
//
|
||||
// Pop-out/redock: the ImGui face's ↗ and ↙ go through ImGuiPanelHost.PopOut
|
||||
// and Redock; a popped-out panel is the same ImGui face in its own window
|
||||
// (ImGuiPopOuts; Tom, 2026-09-29). The Avalonia face's ↙ (a panel still popped
|
||||
// out in Avalonia from before) asks RedockToImGui first.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class PanelRouter
|
||||
{
|
||||
/// <summary>The face that shows <paramref name="title"/> while it is docked in the client.</summary>
|
||||
public static PanelFace ResolveDockedFace(string title)
|
||||
{
|
||||
title = Canonical(title);
|
||||
if (!EngineSettings.EnableImGuiBackend || !ImGuiPanelHost.HasFace(title))
|
||||
return PanelFace.Avalonia;
|
||||
// Tom, 2026-09-28: in the client it's always ImGui; Avalonia only when
|
||||
// popped out. A per-panel face saved while the faces were being built
|
||||
// (PanelFaceStore) no longer puts an Avalonia panel back in the client.
|
||||
return PanelFace.ImGui;
|
||||
}
|
||||
|
||||
/// <summary>True when panels can pop out of the client (into ImGui windows, ImGuiPopOuts).</summary>
|
||||
public static bool CanPopOut => EngineSettings.EnableImGuiBackend;
|
||||
|
||||
/// <summary>Opens the panel if it is closed, closes it if it is open. Any thread.</summary>
|
||||
public static void Toggle(string title)
|
||||
{
|
||||
title = Canonical(title);
|
||||
PanelFace face = ResolveDockedFace(title);
|
||||
if (face == PanelFace.Avalonia)
|
||||
{
|
||||
AvaloniaOverlay.ActivateBarButton(title);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ImGuiPanelHost.IsOpen(title))
|
||||
{
|
||||
ImGuiPanelHost.Close(title);
|
||||
if (face == PanelFace.Both) AvaloniaOverlay.ActivateBarButton(title);
|
||||
return;
|
||||
}
|
||||
|
||||
// Open (popped out or in the client, the button closes it) is handled above;
|
||||
// a panel last left popped out reopens popped out (ImGuiPanelHost.Apply).
|
||||
ImGuiPanelHost.Open(title);
|
||||
if (face == PanelFace.Both) AvaloniaOverlay.ActivateBarButton(title);
|
||||
}
|
||||
|
||||
// The basic Monsters panel was retired (2026-10-01): its rule editing moved into
|
||||
// the Damage panel and Monster Detail. "Monsters" stays a known title (EntryPoint
|
||||
// still registers its Avalonia view, and saved layouts and commands name it), and
|
||||
// every request for it goes to Damage.
|
||||
private const string RetiredMonstersTitle = "Monsters", MonstersPanelTitle = "Damage";
|
||||
|
||||
/// <summary>The panel that shows <paramref name="title"/>: "Monsters" is the Damage panel now.</summary>
|
||||
public static string Canonical(string title) =>
|
||||
title.Equals(RetiredMonstersTitle, StringComparison.OrdinalIgnoreCase) ? MonstersPanelTitle : title;
|
||||
|
||||
/// <summary>The dashboard's Monsters button: the Damage panel.</summary>
|
||||
public static void ToggleMonsters() => Toggle(MonstersPanelTitle);
|
||||
|
||||
/// <summary>
|
||||
/// Engine init, before any panel restores: a "Monsters" panel saved open is saved
|
||||
/// closed, and Damage open in its place (where Monsters was if Damage has no spot yet).
|
||||
/// </summary>
|
||||
public static void MoveRetiredMonstersPanel()
|
||||
{
|
||||
if (!PanelStateStore.TryGetPanel(RetiredMonstersTitle, out PanelStateStore.PanelEntry mon) || !mon.Open) return;
|
||||
PanelStateStore.MarkPanelClosed(RetiredMonstersTitle);
|
||||
if (PanelStateStore.TryGetPanel(MonstersPanelTitle, out PanelStateStore.PanelEntry dmg))
|
||||
{
|
||||
if (!dmg.Open) PanelStateStore.SetPanel(MonstersPanelTitle, dmg with { Open = true });
|
||||
}
|
||||
else PanelStateStore.SetPanel(MonstersPanelTitle, mon);
|
||||
RynthLog.UI("PanelRouter: the Monsters panel was saved open; opening Damage in its place (Monsters is retired).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asked by the Avalonia face's redock (↙) before it docks itself. True
|
||||
/// when the docked face is ImGui: the caller closes its floating window and
|
||||
/// calls <see cref="CompleteRedockToImGui"/> instead of docking.
|
||||
/// </summary>
|
||||
public static bool RedockGoesToImGui(string title) => ResolveDockedFace(title) == PanelFace.ImGui;
|
||||
|
||||
/// <summary>
|
||||
/// After the Avalonia floating window closed (its close saved "popped out,
|
||||
/// closed"): mark the panel docked and open, then open the ImGui face at
|
||||
/// the docked placement. Ordered with the other UI writes.
|
||||
/// </summary>
|
||||
public static void CompleteRedockToImGui(string title)
|
||||
{
|
||||
title = Canonical(title);
|
||||
UiBackgroundWriter.Enqueue($"redock {title}", () =>
|
||||
{
|
||||
PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry prior);
|
||||
PanelStateStore.SetPanel(title, prior with { Open = true, Floating = false });
|
||||
ImGuiPanelHost.Open(title);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the docked face for a panel ("bar" for the overlay bar) and, if
|
||||
/// the panel is open docked, moves it to the new face now. Returns a
|
||||
/// one-line result for chat. Game thread or AC thread.
|
||||
/// </summary>
|
||||
public static string SetDockedFace(string title, PanelFace face)
|
||||
{
|
||||
if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) || title == ImGuiBar.FaceKey)
|
||||
{
|
||||
PanelFaceStore.Set(ImGuiBar.FaceKey, face == PanelFace.ImGui ? null : face);
|
||||
ImGuiBar.ApplyFace();
|
||||
PanelFace barNow = ImGuiBar.ResolveFace();
|
||||
return $"Bar: docked face = {PanelFaceStore.FaceName(face)}{Note(barNow, face)}.";
|
||||
}
|
||||
|
||||
string? known = FindRegisteredTitle(Canonical(title));
|
||||
if (known == null)
|
||||
return $"No panel named '{title}'. Try /rc ui list.";
|
||||
if (face != PanelFace.Avalonia && !ImGuiPanelHost.HasFace(known))
|
||||
return $"{known} has no ImGui version yet; it stays Avalonia.";
|
||||
|
||||
PanelFace before = ResolveDockedFace(known);
|
||||
PanelFaceStore.Set(known, face == ImGuiPanelHost.CodeDefault(known) ? null : face);
|
||||
PanelFace now = ResolveDockedFace(known);
|
||||
if (now != before)
|
||||
MoveOpenPanel(known, before, now);
|
||||
// Last closed while popped out: Toggle would reopen the Avalonia
|
||||
// window. The player just picked the docked face, so the next open
|
||||
// shows that instead. (An open pop-out is left alone.)
|
||||
if (now != PanelFace.Avalonia && PanelStateStore.TryGetPanel(known, out PanelStateStore.PanelEntry saved)
|
||||
&& saved.Floating && !saved.Open)
|
||||
PanelStateStore.SetPanel(known, saved with { Floating = false });
|
||||
return $"{known}: docked face = {PanelFaceStore.FaceName(face)}{Note(now, face)}.";
|
||||
}
|
||||
|
||||
private static string Note(PanelFace now, PanelFace asked) =>
|
||||
now == asked ? "" : $" (showing {PanelFaceStore.FaceName(now)}: the ImGui layer is off or Avalonia is disabled)";
|
||||
|
||||
/// <summary>
|
||||
/// "Switching while the panel is open: close in the old face, open in the
|
||||
/// new one at the same place" (plan §3.4). Popped-out panels aren't
|
||||
/// affected - they are always the Avalonia window. Each hand-off runs its
|
||||
/// steps in one ordered sequence so the last panel_state write wins.
|
||||
/// </summary>
|
||||
private static void MoveOpenPanel(string title, PanelFace before, PanelFace now)
|
||||
{
|
||||
if (!PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry saved) || saved.Floating)
|
||||
return;
|
||||
bool imguiOpen = ImGuiPanelHost.IsOpen(title);
|
||||
bool avaloniaOpen = before != PanelFace.ImGui && saved.Open; // docked Avalonia face showing
|
||||
|
||||
switch (before, now)
|
||||
{
|
||||
case (PanelFace.Avalonia, PanelFace.ImGui):
|
||||
if (avaloniaOpen)
|
||||
AvaloniaOverlay.PostToUi(() =>
|
||||
{
|
||||
AvaloniaOverlay.TogglePanelOnUiThread(title); // closes it, saving its placement
|
||||
ImGuiPanelHost.Open(title); // then opens there (and saves open)
|
||||
});
|
||||
break;
|
||||
case (PanelFace.Avalonia, PanelFace.Both):
|
||||
if (avaloniaOpen) ImGuiPanelHost.Open(title);
|
||||
break;
|
||||
case (PanelFace.ImGui, PanelFace.Avalonia):
|
||||
if (imguiOpen) ImGuiPanelHost.HandOffToAvalonia(title);
|
||||
break;
|
||||
case (PanelFace.ImGui, PanelFace.Both):
|
||||
if (imguiOpen) AvaloniaOverlay.ActivateBarButton(title);
|
||||
break;
|
||||
case (PanelFace.Both, PanelFace.ImGui):
|
||||
if (avaloniaOpen) AvaloniaOverlay.ActivateBarButton(title); // the ImGui copy stays
|
||||
break;
|
||||
case (PanelFace.Both, PanelFace.Avalonia):
|
||||
if (imguiOpen) ImGuiPanelHost.Close(title); // the Avalonia copy stays
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One line per registered panel for /rc ui list and the Status panel.</summary>
|
||||
public static List<string> Describe()
|
||||
{
|
||||
var lines = new List<string>
|
||||
{
|
||||
$"Bar: docked={PanelFaceStore.FaceName(ImGuiBar.ResolveFace())}{(PanelStateStore.BarFloating ? ", popped out" : ", docked")}",
|
||||
};
|
||||
foreach (var (title, _) in OverlayHost.GetPanels())
|
||||
{
|
||||
var sb = new StringBuilder(title).Append(": docked=").Append(PanelFaceStore.FaceName(ResolveDockedFace(title)));
|
||||
sb.Append(ImGuiPanelHost.HasFace(title) ? "" : " (no ImGui version yet)");
|
||||
if (PanelStateStore.TryGetPanel(title, out var entry))
|
||||
sb.Append(entry.Floating ? ", popped out" : ", docked").Append(entry.Open ? ", open" : ", closed");
|
||||
lines.Add(sb.ToString());
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static string? FindRegisteredTitle(string title)
|
||||
{
|
||||
foreach (var (registered, _) in OverlayHost.GetPanels())
|
||||
if (string.Equals(registered, title, StringComparison.OrdinalIgnoreCase))
|
||||
return registered;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
195
src/RynthCore.Engine/UI/PanelTextScale.cs
Normal file
195
src/RynthCore.Engine/UI/PanelTextScale.cs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/PanelTextScale.cs
|
||||
// Per-panel text size for the in-client (ImGui) panels. Sizes 0-10; 0 is the
|
||||
// normal size, each step is 10% bigger, and the last one ("yourjokin") is
|
||||
// 2.5x. Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_text_size.txt
|
||||
// as "Title=size" lines; set from Settings > Display or from a window's own
|
||||
// title bar (the text size button, Ctrl+wheel; ImGuiPanelHost). One size
|
||||
// ("All Panels") applies to every panel unless "Size each panel separately"
|
||||
// is on.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class PanelTextScale
|
||||
{
|
||||
/// <summary>Picker labels, index = size.</summary>
|
||||
public static readonly string[] SizeNames = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "yourjokin" };
|
||||
|
||||
private static readonly float[] Scales = { 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f, 2.5f };
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<string, int> Sizes = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static bool _loaded;
|
||||
|
||||
private static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_text_size.txt");
|
||||
|
||||
private const string AllKey = "__all";
|
||||
private const string PerPanelKey = "__perPanel";
|
||||
|
||||
/// <summary>The size (0-10) a panel is drawn at: its own when sizing per panel, else All Panels.</summary>
|
||||
public static int Get(string title)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
int all = Sizes.TryGetValue(AllKey, out int a) ? a : 0;
|
||||
if (!(Sizes.TryGetValue(PerPanelKey, out int pp) && pp != 0)) return all;
|
||||
return Sizes.TryGetValue(title, out int s) ? s : all;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The panel's own size setting (per-panel rows), falling back to All Panels.</summary>
|
||||
public static int GetOwn(string title)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
if (Sizes.TryGetValue(title, out int s)) return s;
|
||||
return Sizes.TryGetValue(AllKey, out int a) ? a : 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static int GetAll() => GetOwn(AllKey);
|
||||
public static void SetAll(int size) => Set(AllKey, size);
|
||||
|
||||
/// <summary>Off: every panel uses All Panels. On: each panel has its own size.</summary>
|
||||
public static bool PerPanel
|
||||
{
|
||||
get { lock (Sync) { Load(); return Sizes.TryGetValue(PerPanelKey, out int v) && v != 0; } }
|
||||
set => Set(PerPanelKey, value ? 1 : 0);
|
||||
}
|
||||
|
||||
public static void Set(string title, int size)
|
||||
{
|
||||
size = Math.Clamp(size, 0, SizeNames.Length - 1);
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
if (Sizes.TryGetValue(title, out int cur) && cur == size) return;
|
||||
Sizes[title] = size;
|
||||
Save();
|
||||
RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs);
|
||||
}
|
||||
}
|
||||
|
||||
// Changes a few clicks or wheel notches apart re-bake the fonts once, after the
|
||||
// last one (ImGuiFonts.RequestRebuild). Until then a panel draws at the nearest
|
||||
// size already baked (ImGuiFonts.BakedStepNear).
|
||||
private const int RebuildDelayMs = 250;
|
||||
|
||||
/// <summary>
|
||||
/// Sets one window's size from its own title bar (ImGuiPanelHost). If every panel
|
||||
/// shares All Panels, this switches on "Size each panel separately" with every
|
||||
/// other panel kept at the All Panels size, so only this window changes.
|
||||
/// </summary>
|
||||
public static void SetForWindow(string title, int size)
|
||||
{
|
||||
size = Math.Clamp(size, 0, SizeNames.Length - 1);
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
bool perPanel = Sizes.TryGetValue(PerPanelKey, out int pp) && pp != 0;
|
||||
if (perPanel)
|
||||
{
|
||||
if (Sizes.TryGetValue(title, out int cur) && cur == size) return;
|
||||
}
|
||||
else
|
||||
{
|
||||
int all = Sizes.TryGetValue(AllKey, out int a) ? a : 0;
|
||||
if (size == all) return;
|
||||
// Rows left over from an earlier per-panel session would come back into
|
||||
// effect: start them from what every panel shows now.
|
||||
var keys = new List<string>(Sizes.Keys);
|
||||
foreach (string k in keys)
|
||||
if (k != AllKey && k != PerPanelKey) Sizes[k] = all;
|
||||
Sizes[PerPanelKey] = 1;
|
||||
}
|
||||
Sizes[title] = size;
|
||||
Save();
|
||||
RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One window back to the size every other panel uses (All Panels).</summary>
|
||||
public static void ResetWindow(string title) => SetForWindow(title, GetAll());
|
||||
|
||||
/// <summary>Every panel at <paramref name="size"/>: All Panels, per-panel sizing off.</summary>
|
||||
public static void UseForAll(int size)
|
||||
{
|
||||
size = Math.Clamp(size, 0, SizeNames.Length - 1);
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
Sizes[AllKey] = size;
|
||||
Sizes[PerPanelKey] = 0;
|
||||
Save();
|
||||
RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Size 3 (130%)": a size for tooltips.</summary>
|
||||
public static string Describe(int step)
|
||||
{
|
||||
step = Math.Clamp(step, 0, SizeNames.Length - 1);
|
||||
int pct = (int)MathF.Round(Factor(step) * 100f);
|
||||
return step == 0 ? "normal (100%)" : $"{SizeNames[step]} ({pct.ToString(CultureInfo.InvariantCulture)}%)";
|
||||
}
|
||||
|
||||
/// <summary>Font size factor for a size step.</summary>
|
||||
public static float Factor(int step) => Scales[Math.Clamp(step, 0, Scales.Length - 1)];
|
||||
|
||||
/// <summary>The distinct non-zero sizes any panel uses (fonts are baked for these).</summary>
|
||||
public static List<int> StepsInUse()
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
Load();
|
||||
var steps = new List<int>();
|
||||
bool perPanel = Sizes.TryGetValue(PerPanelKey, out int pp) && pp != 0;
|
||||
foreach (var kv in Sizes)
|
||||
{
|
||||
if (kv.Key == PerPanelKey) continue;
|
||||
if (!perPanel && kv.Key != AllKey) continue; // only All Panels is in use
|
||||
if (kv.Value > 0 && !steps.Contains(kv.Value)) steps.Add(kv.Value);
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Load()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return;
|
||||
foreach (string line in File.ReadAllLines(FilePath))
|
||||
{
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
if (int.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int s))
|
||||
Sizes[line[..eq].Trim()] = Math.Clamp(s, 0, SizeNames.Length - 1);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
|
||||
var lines = new List<string>();
|
||||
foreach (var kv in Sizes) lines.Add($"{kv.Key}={kv.Value.ToString(CultureInfo.InvariantCulture)}");
|
||||
File.WriteAllLines(FilePath, lines);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -7,11 +7,10 @@
|
|||
// Consumables — Name, Type picker, Delete
|
||||
// Mana Stones — Enable tapping toggle, keep count, min mana threshold
|
||||
//
|
||||
// Plugin exports used:
|
||||
// RynthPluginGetItemsJson → polled every 1s for external edits
|
||||
// RynthPluginSetItemsJson → write-back on edit
|
||||
// RynthPluginAddSelectedWeapon → add currently selected inventory item as weapon
|
||||
// RynthPluginAddSelectedConsumable → add currently selected inventory item as consumable
|
||||
// Data goes through UiDataHub (UI/Data/ItemsData.cs): UiSources.Items polls
|
||||
// RynthPluginGetItemsJson on the pump thread; ItemsCommands saves
|
||||
// (RynthPluginSetItemsJson) and adds the selected item there. The ImGui face
|
||||
// (ImGui/Panels/ItemsFace.cs) reads the same snapshot.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -26,6 +25,7 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
|
|
@ -35,21 +35,6 @@ internal partial class ItemsPanelJsonContext : JsonSerializerContext { }
|
|||
|
||||
internal static class ItemsPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetItemsJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetItemsJsonFn(IntPtr ansiJson);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void VoidFn();
|
||||
|
||||
private static GetItemsJsonFn? _getItemsJson;
|
||||
private static SetItemsJsonFn? _setItemsJson;
|
||||
private static VoidFn? _addSelectedWeapon;
|
||||
private static VoidFn? _addSelectedConsumable;
|
||||
|
||||
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
|
||||
private static readonly IBrush ColRed = new SolidColorBrush(Color.FromRgb(0xFF, 0x55, 0x55));
|
||||
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
|
||||
|
|
@ -66,7 +51,7 @@ internal static class ItemsPanel
|
|||
{ "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
|
||||
private static readonly string[] ConsumableTypes =
|
||||
{ "General", "Lockpick", "HealthKit", "ManaStone", "Stamina", "Pet" };
|
||||
{ "General", "Lockpick", "HealthKit", "HealthPotion", "ManaPotion", "StaminaPotion", "ManaStone", "Stamina", "Pet" };
|
||||
|
||||
internal sealed class Payload
|
||||
{
|
||||
|
|
@ -100,7 +85,6 @@ internal static class ItemsPanel
|
|||
|
||||
public static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
|
||||
var state = new State();
|
||||
|
||||
|
|
@ -249,11 +233,7 @@ internal static class ItemsPanel
|
|||
}
|
||||
|
||||
body.Children.Add(BuildAddButton("Add Selected Weapon", "(select a weapon in inventory first)",
|
||||
() =>
|
||||
{
|
||||
if (_addSelectedWeapon == null) TryBind();
|
||||
_addSelectedWeapon?.Invoke();
|
||||
}));
|
||||
ItemsCommands.AddSelectedWeapon));
|
||||
|
||||
body.Children.Add(BuildDivider());
|
||||
|
||||
|
|
@ -284,11 +264,7 @@ internal static class ItemsPanel
|
|||
}
|
||||
|
||||
body.Children.Add(BuildAddButton("Add Selected Consumable", "(select an item in inventory first)",
|
||||
() =>
|
||||
{
|
||||
if (_addSelectedConsumable == null) TryBind();
|
||||
_addSelectedConsumable?.Invoke();
|
||||
}));
|
||||
ItemsCommands.AddSelectedConsumable));
|
||||
|
||||
body.Children.Add(BuildDivider());
|
||||
|
||||
|
|
@ -307,7 +283,6 @@ internal static class ItemsPanel
|
|||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getItemsJson == null) TryBind();
|
||||
if (state.Dirty) return;
|
||||
if (!TryFetch(out var fresh)) return;
|
||||
|
||||
|
|
@ -340,8 +315,17 @@ internal static class ItemsPanel
|
|||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Items.Subscribe();
|
||||
UiSources.Items.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Items.Unsubscribe();
|
||||
};
|
||||
|
||||
return root;
|
||||
}
|
||||
|
|
@ -728,81 +712,26 @@ internal static class ItemsPanel
|
|||
return b;
|
||||
}
|
||||
|
||||
// ── Plugin binding ────────────────────────────────────────────────────────
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static ItemsPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getItemsJson = null;
|
||||
_setItemsJson = null;
|
||||
_addSelectedWeapon = null;
|
||||
_addSelectedConsumable = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
if (_getItemsJson == null)
|
||||
{
|
||||
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetItemsJson");
|
||||
if (p != IntPtr.Zero) _getItemsJson = Marshal.GetDelegateForFunctionPointer<GetItemsJsonFn>(p);
|
||||
}
|
||||
if (_setItemsJson == null)
|
||||
{
|
||||
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetItemsJson");
|
||||
if (p != IntPtr.Zero) _setItemsJson = Marshal.GetDelegateForFunctionPointer<SetItemsJsonFn>(p);
|
||||
}
|
||||
if (_addSelectedWeapon == null)
|
||||
{
|
||||
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedWeapon");
|
||||
if (p != IntPtr.Zero) _addSelectedWeapon = Marshal.GetDelegateForFunctionPointer<VoidFn>(p);
|
||||
}
|
||||
if (_addSelectedConsumable == null)
|
||||
{
|
||||
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedConsumable");
|
||||
if (p != IntPtr.Zero) _addSelectedConsumable = Marshal.GetDelegateForFunctionPointer<VoidFn>(p);
|
||||
}
|
||||
}
|
||||
// ── Hub ───────────────────────────────────────────────────────────────────
|
||||
// The hub version at the last save: older snapshots predate it and would
|
||||
// briefly revert the edit on screen, so they're skipped.
|
||||
private static long _savedAtVersion = -1;
|
||||
|
||||
// A private copy of the hub's latest items (the panel edits it in place).
|
||||
private static bool TryFetch(out Payload payload)
|
||||
{
|
||||
payload = new Payload();
|
||||
if (_getItemsJson == null) return false;
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getItemsJson();
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return false;
|
||||
var parsed = JsonSerializer.Deserialize(json, ItemsPanelJsonContext.Default.Payload);
|
||||
if (parsed == null) return false;
|
||||
payload = parsed;
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
var snap = UiSources.Items.Current;
|
||||
if (snap == null || snap.Version <= _savedAtVersion) return false;
|
||||
payload = snap.Value.ParseCopy();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void PushChanges(State state)
|
||||
{
|
||||
if (_setItemsJson == null) TryBind();
|
||||
if (_setItemsJson == null) return;
|
||||
|
||||
IntPtr ansi = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
string json = JsonSerializer.Serialize(state.Data, ItemsPanelJsonContext.Default.Payload);
|
||||
ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
_setItemsJson(ansi);
|
||||
state.Dirty = false;
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
|
||||
}
|
||||
_savedAtVersion = UiSources.Items.Current?.Version ?? _savedAtVersion;
|
||||
ItemsCommands.SetJson(ItemsCommands.Serialize(state.Data));
|
||||
state.Dirty = false;
|
||||
}
|
||||
|
||||
// ── Change detection ──────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/Panels/LogPanel.cs
|
||||
// Scrollable log viewer. Polls EntryPoint.GetRecentLogLines() every second.
|
||||
// Scrollable log viewer. Shows UiDataHub's log snapshot (UiSources.Log).
|
||||
// Auto-scroll follows the tail; checkbox to pin scroll position.
|
||||
// ============================================================================
|
||||
|
||||
|
|
@ -11,6 +11,8 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class LogPanel
|
||||
|
|
@ -25,6 +27,10 @@ internal static class LogPanel
|
|||
BorderThickness = new Avalonia.Thickness(0)
|
||||
};
|
||||
ScrollViewer.SetHorizontalScrollBarVisibility(listBox, ScrollBarVisibility.Disabled);
|
||||
// Not virtualized: popped out, the panel is rendered from a copy parked
|
||||
// off-screen (x=2500), where a virtualizing panel realizes no rows and
|
||||
// the list showed empty. At most 256 lines, so realizing all is cheap.
|
||||
listBox.ItemsPanel = new Avalonia.Controls.Templates.FuncTemplate<Panel?>(() => new StackPanel());
|
||||
|
||||
var autoScrollCheck = new CheckBox
|
||||
{
|
||||
|
|
@ -39,10 +45,15 @@ internal static class LogPanel
|
|||
Margin = new Avalonia.Thickness(4, 0, 0, 0)
|
||||
};
|
||||
|
||||
string[]? _clearedSnapshot = null;
|
||||
// Clear remembers the sequence number of the newest line; later ticks
|
||||
// show only newer lines. (It used to remember a line count, which left
|
||||
// the panel blank for good once the 256-line ring was full.)
|
||||
long clearedSeq = 0;
|
||||
long seenVersion = -1;
|
||||
clearButton.Click += (_, _) =>
|
||||
{
|
||||
_clearedSnapshot = EntryPoint.GetRecentLogLines();
|
||||
clearedSeq = UiSources.Log.Current?.Value.LastSeq ?? EntryPoint.RecentLogSeq;
|
||||
seenVersion = -1;
|
||||
listBox.ItemsSource = Array.Empty<string>();
|
||||
};
|
||||
|
||||
|
|
@ -67,29 +78,34 @@ internal static class LogPanel
|
|||
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
string[] lines = EntryPoint.GetRecentLogLines();
|
||||
|
||||
// If cleared, only show lines that arrived after the clear snapshot
|
||||
if (_clearedSnapshot != null)
|
||||
{
|
||||
int clearCount = _clearedSnapshot.Length;
|
||||
if (lines.Length > clearCount)
|
||||
lines = lines[clearCount..];
|
||||
else
|
||||
lines = Array.Empty<string>();
|
||||
}
|
||||
var snap = UiSources.Log.Current;
|
||||
if (snap == null || snap.Version == seenVersion) return;
|
||||
seenVersion = snap.Version;
|
||||
|
||||
LogSnapshot log = snap.Value;
|
||||
int start = (int)Math.Clamp(clearedSeq - log.FirstSeq + 1, 0, log.Lines.Length);
|
||||
string[] lines = start == 0 ? log.Lines : log.Lines[start..];
|
||||
listBox.ItemsSource = lines;
|
||||
|
||||
if (autoScrollCheck.IsChecked == true && lines.Length > 0)
|
||||
scroll.ScrollToEnd();
|
||||
};
|
||||
timer.Start();
|
||||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
// must restart on attach: drag/resize fires Detached→Attached. The data
|
||||
// comes from UiDataHub, which polls only while a face is subscribed.
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Log.Subscribe();
|
||||
UiSources.Log.RequestRefresh();
|
||||
seenVersion = -1;
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Log.Unsubscribe();
|
||||
};
|
||||
|
||||
return root;
|
||||
}
|
||||
|
|
|
|||
279
src/RynthCore.Engine/UI/Panels/LuaPanel.cs
Normal file
279
src/RynthCore.Engine/UI/Panels/LuaPanel.cs
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine — UI/Panels/LuaPanel.cs
|
||||
// Lua scripts for RynthAi: script list, editor, Run/Stop, console.
|
||||
//
|
||||
// Data goes through UiDataHub (UI/Data/LuaData.cs): UiSources.Lua polls
|
||||
// RynthPluginGetLuaJson on the pump thread and LuaCommands sends
|
||||
// RynthPluginSendLuaCommand there; the ImGui face (ImGui/Panels/LuaFace.cs)
|
||||
// reads the same snapshot.
|
||||
//
|
||||
// Controls are built once and updated in place: a full rebuild every poll
|
||||
// (the NavPanel pattern) would reset the editor's caret while typing. The
|
||||
// script list uses plain buttons, not a dropdown, because overlay popups
|
||||
// blank the docked panels.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class LuaPanel
|
||||
{
|
||||
// Lazy: see the dispatcher-poison invariant in EntryPoint.InitWorker.
|
||||
private static IBrush? _amber, _green, _mute, _text, _shell, _btnFill, _btnBord, _startBg, _stopBg, _consoleBg;
|
||||
private static IBrush ColAmber => _amber ??= new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
|
||||
private static IBrush ColGreen => _green ??= new SolidColorBrush(Color.FromRgb(0x33, 0xCC, 0x66));
|
||||
private static IBrush ColMute => _mute ??= new SolidColorBrush(Color.FromRgb(0x8C, 0xA6, 0xBF));
|
||||
private static IBrush ColTextDim => _text ??= new SolidColorBrush(Color.FromRgb(0xD9, 0xE6, 0xF2));
|
||||
private static IBrush ColShellBg => _shell ??= new SolidColorBrush(Color.FromRgb(0x0A, 0x0F, 0x14));
|
||||
private static IBrush ColBtnFill => _btnFill ??= new SolidColorBrush(Color.FromRgb(0x0F, 0x1F, 0x2E));
|
||||
private static IBrush ColBtnBord => _btnBord ??= new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59));
|
||||
private static IBrush ColStartBg => _startBg ??= new SolidColorBrush(Color.FromRgb(0x19, 0x61, 0x19));
|
||||
private static IBrush ColStopBg => _stopBg ??= new SolidColorBrush(Color.FromRgb(0x80, 0x19, 0x19));
|
||||
private static IBrush ColConsole => _consoleBg ??= new SolidColorBrush(Color.FromRgb(0x05, 0x09, 0x0D));
|
||||
|
||||
// =========================================================================
|
||||
// Create
|
||||
// =========================================================================
|
||||
|
||||
public static Control Create()
|
||||
{
|
||||
|
||||
var root = new Border
|
||||
{
|
||||
Background = ColShellBg,
|
||||
BorderBrush = ColBtnBord,
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(4),
|
||||
MinWidth = 380,
|
||||
};
|
||||
var content = new StackPanel { Margin = new Thickness(6), Spacing = 4 };
|
||||
root.Child = new ScrollViewer
|
||||
{
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
|
||||
Content = content,
|
||||
};
|
||||
|
||||
// ── Status + Run/Stop ────────────────────────────────────────────────
|
||||
var statusText = new TextBlock
|
||||
{
|
||||
Text = "Lua: idle", Foreground = ColAmber, FontSize = 11, FontWeight = FontWeight.Bold,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center,
|
||||
};
|
||||
var runBtn = MakeBtn("▶ Run");
|
||||
runBtn.Background = ColStartBg;
|
||||
var stopBtn = MakeBtn("■ Stop");
|
||||
stopBtn.Background = ColStopBg;
|
||||
var topRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") };
|
||||
Grid.SetColumn(statusText, 0);
|
||||
Grid.SetColumn(runBtn, 1);
|
||||
Grid.SetColumn(stopBtn, 2);
|
||||
topRow.Children.Add(statusText);
|
||||
topRow.Children.Add(runBtn);
|
||||
topRow.Children.Add(stopBtn);
|
||||
content.Children.Add(topRow);
|
||||
|
||||
// ── Script list (LuaScripts folder) ──────────────────────────────────
|
||||
content.Children.Add(new TextBlock { Text = "Scripts (click to open):", Foreground = ColMute, FontSize = 10 });
|
||||
var scriptWrap = new WrapPanel { Orientation = Orientation.Horizontal };
|
||||
content.Children.Add(scriptWrap);
|
||||
|
||||
// ── Name + Save ──────────────────────────────────────────────────────
|
||||
var nameBox = new TextBox
|
||||
{
|
||||
Watermark = "Script name...",
|
||||
Background = ColBtnFill, Foreground = ColTextDim,
|
||||
BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
|
||||
FontSize = 10, Height = 22, Padding = new Thickness(4, 1),
|
||||
Margin = new Thickness(0, 0, 4, 0),
|
||||
};
|
||||
var saveBtn = MakeBtn("Save");
|
||||
var deleteBtn = MakeBtn("Delete");
|
||||
var newBtn = MakeBtn("New");
|
||||
var saveRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto") };
|
||||
Grid.SetColumn(nameBox, 0);
|
||||
Grid.SetColumn(saveBtn, 1);
|
||||
Grid.SetColumn(newBtn, 2);
|
||||
Grid.SetColumn(deleteBtn, 3);
|
||||
saveRow.Children.Add(nameBox);
|
||||
saveRow.Children.Add(saveBtn);
|
||||
saveRow.Children.Add(newBtn);
|
||||
saveRow.Children.Add(deleteBtn);
|
||||
content.Children.Add(saveRow);
|
||||
|
||||
// ── Editor ───────────────────────────────────────────────────────────
|
||||
var editor = new TextBox
|
||||
{
|
||||
AcceptsReturn = true,
|
||||
AcceptsTab = true,
|
||||
TextWrapping = TextWrapping.NoWrap,
|
||||
FontFamily = new FontFamily("Consolas, Courier New, monospace"),
|
||||
FontSize = 11,
|
||||
Height = 240,
|
||||
Background = ColBtnFill, Foreground = ColTextDim,
|
||||
BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
|
||||
Padding = new Thickness(4),
|
||||
Watermark = "-- Lua script\nprint('hello from ' .. me.name)",
|
||||
};
|
||||
ScrollViewer.SetHorizontalScrollBarVisibility(editor, Avalonia.Controls.Primitives.ScrollBarVisibility.Auto);
|
||||
ScrollViewer.SetVerticalScrollBarVisibility(editor, Avalonia.Controls.Primitives.ScrollBarVisibility.Auto);
|
||||
content.Children.Add(editor);
|
||||
|
||||
// ── Console ──────────────────────────────────────────────────────────
|
||||
var clearBtn = MakeBtn("Clear");
|
||||
var consoleHdr = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
var consoleLbl = new TextBlock { Text = "Console", Foreground = ColMute, FontSize = 10, VerticalAlignment = VerticalAlignment.Center };
|
||||
Grid.SetColumn(consoleLbl, 0);
|
||||
Grid.SetColumn(clearBtn, 1);
|
||||
consoleHdr.Children.Add(consoleLbl);
|
||||
consoleHdr.Children.Add(clearBtn);
|
||||
content.Children.Add(consoleHdr);
|
||||
|
||||
var consoleText = new SelectableTextBlock
|
||||
{
|
||||
Foreground = ColGreen,
|
||||
FontFamily = new FontFamily("Consolas, Courier New, monospace"),
|
||||
FontSize = 10,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
};
|
||||
var consoleScroll = new ScrollViewer
|
||||
{
|
||||
Height = 150,
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
|
||||
Content = consoleText,
|
||||
};
|
||||
content.Children.Add(new Border
|
||||
{
|
||||
Background = ColConsole, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
|
||||
Padding = new Thickness(4), Child = consoleScroll,
|
||||
});
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
runBtn.Click += (_, _) =>
|
||||
LuaCommands.Send("run", nameBox.Text?.Trim() ?? string.Empty, editor.Text ?? string.Empty);
|
||||
stopBtn.Click += (_, _) => LuaCommands.Send("stop");
|
||||
clearBtn.Click += (_, _) => { LuaCommands.Send("clearConsole"); consoleText.Text = string.Empty; };
|
||||
saveBtn.Click += (_, _) =>
|
||||
{
|
||||
string name = nameBox.Text?.Trim() ?? string.Empty;
|
||||
if (name.Length == 0) { consoleText.Text += "\n[panel] Type a script name first."; return; }
|
||||
LuaCommands.Send("save", name, editor.Text ?? string.Empty);
|
||||
};
|
||||
newBtn.Click += (_, _) => { editor.Text = string.Empty; nameBox.Text = string.Empty; };
|
||||
deleteBtn.Click += (_, _) =>
|
||||
{
|
||||
string name = nameBox.Text?.Trim() ?? string.Empty;
|
||||
if (name.Length > 0) LuaCommands.Send("delete", name);
|
||||
};
|
||||
|
||||
// ── Poll ─────────────────────────────────────────────────────────────
|
||||
int lastConsoleSeq = -1, lastLoadSeq = -1;
|
||||
string lastScripts = "\0";
|
||||
bool firstFetch = true;
|
||||
long seenVersion = -1;
|
||||
|
||||
void Refresh()
|
||||
{
|
||||
var snap = UiSources.Lua.Current;
|
||||
if (snap == null)
|
||||
{
|
||||
statusText.Text = "Lua: RynthLua not connected";
|
||||
return;
|
||||
}
|
||||
if (snap.Version == seenVersion) return;
|
||||
seenVersion = snap.Version;
|
||||
LuaPayload d = snap.Value;
|
||||
|
||||
statusText.Text = d.Running
|
||||
? $"Running: {(d.ScriptName.Length > 0 ? d.ScriptName : "(editor)")}"
|
||||
: (d.Status.Length > 0 ? d.Status : "Lua: idle");
|
||||
statusText.Foreground = d.Running ? ColGreen : ColAmber;
|
||||
|
||||
string joined = string.Join("\n", d.Scripts);
|
||||
if (joined != lastScripts)
|
||||
{
|
||||
lastScripts = joined;
|
||||
scriptWrap.Children.Clear();
|
||||
if (d.Scripts.Count == 0)
|
||||
scriptWrap.Children.Add(new TextBlock { Text = "(none yet: write one and Save)", Foreground = ColMute, FontSize = 10 });
|
||||
foreach (string s in d.Scripts)
|
||||
{
|
||||
string name = s;
|
||||
var b = MakeBtn(name);
|
||||
b.Click += (_, _) => LuaCommands.Send("load", name);
|
||||
scriptWrap.Children.Add(b);
|
||||
}
|
||||
}
|
||||
|
||||
// Take a loaded script into the editor; on first open, restore the
|
||||
// plugin's current editor text without counting it as a new load.
|
||||
if (d.LoadSeq != lastLoadSeq)
|
||||
{
|
||||
bool take = !firstFetch || string.IsNullOrEmpty(editor.Text);
|
||||
lastLoadSeq = d.LoadSeq;
|
||||
if (take)
|
||||
{
|
||||
editor.Text = d.LoadedText;
|
||||
nameBox.Text = d.LoadedName;
|
||||
}
|
||||
}
|
||||
|
||||
if (d.ConsoleSeq != lastConsoleSeq)
|
||||
{
|
||||
lastConsoleSeq = d.ConsoleSeq;
|
||||
consoleText.Text = d.Console;
|
||||
consoleScroll.ScrollToEnd();
|
||||
}
|
||||
firstFetch = false;
|
||||
}
|
||||
|
||||
// Reads the hub's snapshot (fetched every 500 ms while subscribed, and
|
||||
// right after each command).
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
timer.Tick += (_, _) => Refresh();
|
||||
// Stop with the visual tree (RadarPanel idiom); restart on attach since
|
||||
// drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Lua.Subscribe();
|
||||
UiSources.Lua.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Lua.Unsubscribe();
|
||||
};
|
||||
|
||||
Refresh();
|
||||
return root;
|
||||
}
|
||||
|
||||
private static Button MakeBtn(string text) => new Button
|
||||
{
|
||||
Content = text,
|
||||
Background = ColBtnFill,
|
||||
Foreground = ColTextDim,
|
||||
BorderBrush = ColBtnBord,
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(3),
|
||||
Padding = new Thickness(8, 3),
|
||||
FontSize = 10,
|
||||
Height = 24,
|
||||
Margin = new Thickness(0, 0, 4, 4),
|
||||
};
|
||||
}
|
||||
|
|
@ -2,9 +2,10 @@
|
|||
// RynthCore.Engine — UI/Panels/MetaPanel.cs
|
||||
// Avalonia port of LegacyMetaUi.cs (RynthSuite plugin).
|
||||
//
|
||||
// Plugin exports used:
|
||||
// RynthPluginGetMetaJson → polled every 2s for live state
|
||||
// RynthPluginSendMetaCommand → dispatched on user actions
|
||||
// Data goes through UiDataHub (UI/Data/MetaData.cs): the snapshot comes
|
||||
// from UiSources.Meta and commands go out through MetaCommands, so the
|
||||
// plugin's exports run on the pump thread, not on this UI thread. The ImGui
|
||||
// face (ImGui/Panels/MetaFace.cs) reads the same snapshot.
|
||||
// =============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -20,32 +21,13 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using Payload = RynthCore.Engine.UI.Data.MetaPayload;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
[JsonSerializable(typeof(MetaPanel.Payload))]
|
||||
[JsonSerializable(typeof(MetaPanel.MetaCmd))]
|
||||
[JsonSerializable(typeof(MetaPanel.MetaRuleDto))]
|
||||
[JsonSerializable(typeof(MetaPanel.MetaFile))]
|
||||
[JsonSerializable(typeof(List<MetaPanel.MetaRuleDto>), TypeInfoPropertyName = "MetaRuleDtoList")]
|
||||
[JsonSerializable(typeof(List<MetaPanel.MetaFile>), TypeInfoPropertyName = "MetaFileList")]
|
||||
[JsonSerializable(typeof(List<string>), TypeInfoPropertyName = "StringList")]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
|
||||
internal partial class MetaPanelJsonContext : JsonSerializerContext { }
|
||||
|
||||
internal static class MetaPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetMetaJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SendMetaCommandFn(IntPtr ansiJson);
|
||||
|
||||
private static GetMetaJsonFn? _getMetaJson;
|
||||
private static SendMetaCommandFn? _sendMetaCommand;
|
||||
|
||||
// ── Colors ────────────────────────────────────────────────────────────────
|
||||
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
|
||||
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
|
||||
|
|
@ -63,115 +45,14 @@ internal static class MetaPanel
|
|||
private static readonly IBrush ColStateHdrA = new SolidColorBrush(Color.FromRgb(0x0E, 0x1E, 0x30));
|
||||
private static readonly IBrush ColStateHdrB = new SolidColorBrush(Color.FromRgb(0x16, 0x2A, 0x40));
|
||||
|
||||
// ── Condition / action name tables (mirrors LegacyMetaUi) ─────────────────
|
||||
private static readonly string[] ConditionNames =
|
||||
{
|
||||
"Never", "Always", "All", "Any", "Chat Message", "Pack Slots <=",
|
||||
"Seconds in State >=", "Character Death", "Any Vendor Open",
|
||||
"Vendor Closed", "Inventory Item Count <=", "Inventory Item Count >=",
|
||||
"Monster Name Count Within Dist", "Monster Priority Count Within Dist",
|
||||
"Need To Buff", "No Monsters Within Dist", "Landblock ==",
|
||||
"Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not",
|
||||
"Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=",
|
||||
"Burden % >=", "Dist Any Route PT >=", "Expression",
|
||||
"Chat Message Capture", "Navroute Empty",
|
||||
"Main Health <=", "Main Health % >=", "Main Mana <=", "Main Mana % >=",
|
||||
"Main Stam <=", "Vitae % >=",
|
||||
};
|
||||
|
||||
private static readonly string[] ConditionHints =
|
||||
{
|
||||
"", "", "(sub-conditions)", "(sub-conditions)", "Regex pattern", "Min slots (e.g. 5)",
|
||||
"Seconds (e.g. 10)", "", "", "",
|
||||
"name,count (e.g. Mana Stone,5)", "name,count (e.g. Mana Stone,5)",
|
||||
"name regex,distance,count", "count,distance (e.g. 1,20)",
|
||||
"", "Distance (e.g. 20)", "Hex (e.g. A9B40000)", "Hex (e.g. A9B40000)",
|
||||
"", "", "(sub-conditions)", "Seconds (e.g. 10)",
|
||||
"spellId,seconds (e.g. 2293,30)", "spellId,seconds (e.g. 2293,30)",
|
||||
"Percentage (e.g. 250)", "Distance (e.g. 10)", "Expression",
|
||||
"Regex pattern", "",
|
||||
"", "", "", "", "", "Vitae % (e.g. 5)",
|
||||
};
|
||||
|
||||
private static readonly string[] ActionNames =
|
||||
{
|
||||
"None", "Chat Command", "Set Meta State", "Embedded Nav Route", "All",
|
||||
"Call Meta State", "Return From Call", "Expression Action", "Chat Expression",
|
||||
"Set Watchdog", "Clear Watchdog", "Get RA Option", "Set RA Option",
|
||||
"Create View", "Destroy View", "Destroy All Views",
|
||||
};
|
||||
|
||||
private static readonly string[] ActionHints =
|
||||
{
|
||||
"", "e.g. /say hello", "State name", "Route name", "(sub-actions)",
|
||||
"State name", "", "Expression", "Expression",
|
||||
"state;meters;seconds (e.g. Default;10;60)", "", "Option name", "OptionName;Value",
|
||||
"", "", "",
|
||||
};
|
||||
|
||||
// Composite condition indices: All=2, Any=3, Not=20
|
||||
private static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20;
|
||||
|
||||
/// <summary>One condition as text, nested ones included: "Not No Monsters Within Dist: 5",
|
||||
/// "Any(Chat Message: …, Navroute Empty)".</summary>
|
||||
private static string CondText(MetaRuleDto c, int depth = 0)
|
||||
{
|
||||
string name = c.Condition >= 0 && c.Condition < ConditionNames.Length
|
||||
? ConditionNames[c.Condition] : $"Cond({c.Condition})";
|
||||
if (IsCompositeCondition(c.Condition) && c.Children.Count > 0 && depth < MaxSubConditionDepth)
|
||||
{
|
||||
if (c.Condition == 20) return $"Not {CondText(c.Children[0], depth + 1)}";
|
||||
return $"{name}({string.Join(", ", c.Children.Select(x => CondText(x, depth + 1)))})";
|
||||
}
|
||||
return string.IsNullOrEmpty(c.ConditionData) ? name : $"{name}: {c.ConditionData}";
|
||||
}
|
||||
// All action index = 4
|
||||
private static bool IsAllAction(int idx) => idx == 4;
|
||||
|
||||
// ── Data types ────────────────────────────────────────────────────────────
|
||||
|
||||
internal sealed class MetaRuleDto
|
||||
{
|
||||
public string State { get; set; } = "Default";
|
||||
public int Condition { get; set; }
|
||||
public string ConditionData { get; set; } = string.Empty;
|
||||
public int Action { get; set; }
|
||||
public string ActionData { get; set; } = string.Empty;
|
||||
public List<MetaRuleDto> Children { get; set; } = new();
|
||||
public List<MetaRuleDto> ActionChildren { get; set; } = new();
|
||||
public bool Enabled { get; set; } = true;
|
||||
public long LastFiredMs { get; set; } = 99999;
|
||||
}
|
||||
|
||||
internal sealed class MetaFile
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string Display { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class Payload
|
||||
{
|
||||
public bool EnableMeta { get; set; }
|
||||
public bool MetaDebug { get; set; }
|
||||
public string CurrentState { get; set; } = "Default";
|
||||
public string CurrentMetaPath { get; set; } = string.Empty;
|
||||
public List<MetaRuleDto> Rules { get; set; } = new();
|
||||
public List<MetaFile> Files { get; set; } = new();
|
||||
public List<string> States { get; set; } = new();
|
||||
public List<string> NavFiles { get; set; } = new();
|
||||
public List<string> EmbeddedNavKeys { get; set; } = new();
|
||||
public string SourceText { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class MetaCmd
|
||||
{
|
||||
public string Op { get; set; } = string.Empty;
|
||||
public int Index { get; set; } = -1;
|
||||
public string Value { get; set; } = string.Empty;
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public string Text { get; set; } = string.Empty;
|
||||
public MetaRuleDto? Rule { get; set; }
|
||||
}
|
||||
// ── Names, hints, text helpers (shared with the ImGui face) ──────────────
|
||||
private static readonly string[] ConditionNames = MetaVocabulary.ConditionNames;
|
||||
private static readonly string[] ConditionHints = MetaVocabulary.ConditionHints;
|
||||
private static readonly string[] ActionNames = MetaVocabulary.ActionNames;
|
||||
private static readonly string[] ActionHints = MetaVocabulary.ActionHints;
|
||||
private static bool IsCompositeCondition(int idx) => MetaVocabulary.IsCompositeCondition(idx);
|
||||
private static bool IsAllAction(int idx) => MetaVocabulary.IsAllAction(idx);
|
||||
private static string CondText(MetaRuleDto c) => MetaVocabulary.CondText(c);
|
||||
|
||||
// ── View state ────────────────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -185,7 +66,13 @@ internal static class MetaPanel
|
|||
public MetaRuleDto EditingRule = new() { State = "Default", Action = 1 };
|
||||
public string SourceText = string.Empty;
|
||||
public string SourceMsg = string.Empty;
|
||||
public bool SourceMsgOk = true;
|
||||
public DateTime SourceMsgTime = DateTime.MinValue;
|
||||
public TextBlock? SourceMsgRef;
|
||||
// Source "Apply": the plugin's ApplyResult.Seq before the apply was
|
||||
// sent; a newer seq in a snapshot is this apply's result. -2 = none pending.
|
||||
public long ApplySeqBefore = -2;
|
||||
public DateTime ApplySentAt;
|
||||
public string SaveName = string.Empty;
|
||||
public bool ShowSaveInput;
|
||||
public HashSet<string> CollapsedStates = new();
|
||||
|
|
@ -204,9 +91,7 @@ internal static class MetaPanel
|
|||
// reusing stale ones built from a prior Payload.
|
||||
public Dictionary<string, Panel> GroupRowCache = new();
|
||||
public string LastSig = "init_sig"; // content signature of the last Rebuild
|
||||
// UI deep-dive Roadmap #4 (2026-07-02): one-shot reconcile timer for
|
||||
// the optimistic-local-mutation pattern — see ScheduleReconcile.
|
||||
public DispatcherTimer? ReconcileTimer;
|
||||
public long SeenVersion = -1; // hub snapshot version last taken
|
||||
// Roadmap #5 (2026-07-02): live references to the bottom-bar state
|
||||
// button and the file-picker button, so the poll timer can update
|
||||
// their displayed text in place once CurrentState/CurrentMetaPath
|
||||
|
|
@ -216,37 +101,11 @@ internal static class MetaPanel
|
|||
public Button? FileBtnRef;
|
||||
}
|
||||
|
||||
// Roadmap #4 (2026-07-02): enable/move/duplicate/delete used to be pure
|
||||
// fire-and-forget Send() calls with no local mutation — the row buttons
|
||||
// stayed dead until the next 2s poll rebuilt the list from the plugin's
|
||||
// authoritative state. Two problems: (1) up to 2s of "did my click even
|
||||
// register?" with no feedback, and (2) capturedGlobalIdx is captured at
|
||||
// RENDER time — a second click on a stale row (e.g. rapid double-delete
|
||||
// before the poll catches up) sends an index that no longer matches
|
||||
// what the plugin thinks is at that position once the first command
|
||||
// has already shifted subsequent rows, deleting/moving/toggling the
|
||||
// WRONG rule. Fix: apply the same mutation locally to ps.Data.Rules
|
||||
// immediately (so capturedGlobalIdx stays valid for anything queued
|
||||
// behind it in the SAME rebuild), rebuild once (user-initiated, so a
|
||||
// single rebuild here is acceptable — this isn't the poll-driven flash
|
||||
// path), then reconcile with the plugin's authoritative state ~250ms
|
||||
// later in case the local guess and the plugin's actual result diverged
|
||||
// (e.g. a command that failed server-side).
|
||||
private static void ScheduleReconcile(PanelState ps, Action rebuild)
|
||||
{
|
||||
ps.ReconcileTimer?.Stop();
|
||||
var t = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
t.Tick += (_, _) =>
|
||||
{
|
||||
t.Stop();
|
||||
if (!TryFetch(out var fresh)) return;
|
||||
ps.Data = fresh;
|
||||
ps.LastSig = PayloadSig(fresh);
|
||||
rebuild();
|
||||
};
|
||||
ps.ReconcileTimer = t;
|
||||
t.Start();
|
||||
}
|
||||
// Roadmap #4 (2026-07-02): enable/move/duplicate/delete apply the same
|
||||
// change locally to ps.Data.Rules right away (instant feedback, and a
|
||||
// second click on a stale row can't hit the wrong index), then the hub's
|
||||
// next snapshot, taken after the plugin applied the command, replaces the
|
||||
// local guess (MetaCommands defers the refresh past the plugin tick).
|
||||
|
||||
// Cheap content signature — everything the list view shows EXCEPT the
|
||||
// per-tick LastFiredMs (excluded so an idle/botting panel stops flashing;
|
||||
|
|
@ -356,7 +215,6 @@ internal static class MetaPanel
|
|||
|
||||
public static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
var ps = new PanelState();
|
||||
|
||||
var root = new Border
|
||||
|
|
@ -400,13 +258,20 @@ internal static class MetaPanel
|
|||
}
|
||||
}
|
||||
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
|
||||
// Polls the hub's snapshot (fetched every 2 s while subscribed, and
|
||||
// right after each command).
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getMetaJson == null) TryBind();
|
||||
var snap = UiSources.Meta.Current;
|
||||
if (snap != null && snap.Version != ps.SeenVersion)
|
||||
CheckApplyResult(ps, snap.Value);
|
||||
UpdateSourceMsg(ps);
|
||||
if (picker.ActivePicker != null) return;
|
||||
if (ps.Mode == ViewMode.Editor) return; // don't clobber in-progress edits
|
||||
if (!TryFetch(out var fresh)) return;
|
||||
if (snap == null || snap.Version == ps.SeenVersion) return;
|
||||
ps.SeenVersion = snap.Version;
|
||||
var fresh = snap.Value.Clone();
|
||||
ps.Data = fresh; // keep click-handlers on fresh data even if we skip the redraw
|
||||
if (ps.Mode == ViewMode.Source && string.IsNullOrEmpty(ps.SourceText))
|
||||
ps.SourceText = fresh.SourceText;
|
||||
|
|
@ -416,16 +281,7 @@ internal static class MetaPanel
|
|||
// controls in place, every poll, regardless of whether the sig
|
||||
// changed — property sets only, no layout churn, no rebuild.
|
||||
if (ps.StateBtnRef != null) ps.StateBtnRef.Content = fresh.CurrentState;
|
||||
if (ps.FileBtnRef != null)
|
||||
{
|
||||
string display = "-- None --";
|
||||
if (!string.IsNullOrEmpty(fresh.CurrentMetaPath) && fresh.Files.Count > 1)
|
||||
{
|
||||
var match = fresh.Files.FirstOrDefault(f => string.Equals(f.Path, fresh.CurrentMetaPath, StringComparison.OrdinalIgnoreCase));
|
||||
if (match != null) display = match.Display;
|
||||
}
|
||||
ps.FileBtnRef.Content = display;
|
||||
}
|
||||
if (ps.FileBtnRef != null) ps.FileBtnRef.Content = MetaVocabulary.CurrentFileDisplay(fresh);
|
||||
string sig = PayloadSig(fresh);
|
||||
if (sig == ps.LastSig) return; // nothing visible changed → no rebuild → no flash
|
||||
ps.LastSig = sig;
|
||||
|
|
@ -446,13 +302,28 @@ internal static class MetaPanel
|
|||
if (ps.Mode != ViewMode.List) return;
|
||||
Rebuild();
|
||||
};
|
||||
timer.Start();
|
||||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Meta.Subscribe();
|
||||
UiSources.Meta.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Meta.Unsubscribe();
|
||||
};
|
||||
|
||||
var first = UiSources.Meta.Current;
|
||||
if (first != null)
|
||||
{
|
||||
ps.SeenVersion = first.Version;
|
||||
ps.Data = first.Value.Clone();
|
||||
ps.LastSig = PayloadSig(ps.Data);
|
||||
}
|
||||
Rebuild();
|
||||
return root;
|
||||
}
|
||||
|
|
@ -660,7 +531,6 @@ internal static class MetaPanel
|
|||
if (capturedGlobalIdx >= 0 && capturedGlobalIdx < ps.Data.Rules.Count)
|
||||
ps.Data.Rules[capturedGlobalIdx].Enabled = newEnabled;
|
||||
rebuild();
|
||||
ScheduleReconcile(ps, rebuild);
|
||||
};
|
||||
Grid.SetColumn(enBtn, 0);
|
||||
row.Children.Add(enBtn);
|
||||
|
|
@ -716,7 +586,6 @@ internal static class MetaPanel
|
|||
(ps.Data.Rules[otherGlobalIdx], ps.Data.Rules[capturedGlobalIdx]);
|
||||
}
|
||||
rebuild();
|
||||
ScheduleReconcile(ps, rebuild);
|
||||
};
|
||||
Grid.SetColumn(upBtn, 2);
|
||||
row.Children.Add(upBtn);
|
||||
|
|
@ -745,7 +614,6 @@ internal static class MetaPanel
|
|||
(ps.Data.Rules[otherGlobalIdx], ps.Data.Rules[capturedGlobalIdx]);
|
||||
}
|
||||
rebuild();
|
||||
ScheduleReconcile(ps, rebuild);
|
||||
};
|
||||
Grid.SetColumn(dnBtn, 3);
|
||||
row.Children.Add(dnBtn);
|
||||
|
|
@ -771,7 +639,6 @@ internal static class MetaPanel
|
|||
int insertAt = Math.Clamp(capturedGlobalIdx + 1, 0, ps.Data.Rules.Count);
|
||||
ps.Data.Rules.Insert(insertAt, CloneRule(rule));
|
||||
rebuild();
|
||||
ScheduleReconcile(ps, rebuild);
|
||||
};
|
||||
Grid.SetColumn(dupBtn, 4);
|
||||
row.Children.Add(dupBtn);
|
||||
|
|
@ -799,7 +666,6 @@ internal static class MetaPanel
|
|||
if (capturedGlobalIdx >= 0 && capturedGlobalIdx < ps.Data.Rules.Count)
|
||||
ps.Data.Rules.RemoveAt(capturedGlobalIdx);
|
||||
rebuild();
|
||||
ScheduleReconcile(ps, rebuild);
|
||||
};
|
||||
Grid.SetColumn(delBtn, 5);
|
||||
row.Children.Add(delBtn);
|
||||
|
|
@ -955,7 +821,7 @@ internal static class MetaPanel
|
|||
string n = ps.SaveName.Trim();
|
||||
if (!string.IsNullOrEmpty(n))
|
||||
{
|
||||
string path = @$"C:\Games\RynthSuite\RynthAi\MetaFiles\{n}.af";
|
||||
string path = System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af");
|
||||
Send(new MetaCmd { Op = "save_file", Path = path });
|
||||
}
|
||||
ps.ShowSaveInput = false;
|
||||
|
|
@ -976,13 +842,7 @@ internal static class MetaPanel
|
|||
var bar = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto") };
|
||||
|
||||
// File picker button
|
||||
string currentDisplay = string.Empty;
|
||||
if (!string.IsNullOrEmpty(d.CurrentMetaPath) && d.Files.Count > 1)
|
||||
{
|
||||
var match = d.Files.FirstOrDefault(f => string.Equals(f.Path, d.CurrentMetaPath, StringComparison.OrdinalIgnoreCase));
|
||||
if (match != null) currentDisplay = match.Display;
|
||||
}
|
||||
var fileBtn = MakePickerBtn(string.IsNullOrEmpty(currentDisplay) ? "-- None --" : currentDisplay);
|
||||
var fileBtn = MakePickerBtn(MetaVocabulary.CurrentFileDisplay(d));
|
||||
fileBtn.Click += (_, _) =>
|
||||
{
|
||||
var items = ps.Data.Files.Select(f => f.Display).ToArray();
|
||||
|
|
@ -1000,10 +860,7 @@ internal static class MetaPanel
|
|||
|
||||
var refreshBtn = MakeSmallBtn("↺");
|
||||
ToolTip.SetTip(refreshBtn, "Refresh file list");
|
||||
refreshBtn.Click += (_, _) =>
|
||||
{
|
||||
if (TryFetch(out var fresh)) { ps.Data = fresh; rebuild(); }
|
||||
};
|
||||
refreshBtn.Click += (_, _) => UiSources.Meta.RequestRefresh(); // the timer rebuilds on the new snapshot
|
||||
Grid.SetColumn(refreshBtn, 1);
|
||||
bar.Children.Add(refreshBtn);
|
||||
|
||||
|
|
@ -1262,7 +1119,7 @@ internal static class MetaPanel
|
|||
|
||||
var subRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,Auto"), Margin = new Thickness(0, 1, 0, 0) };
|
||||
|
||||
var typeBtn = MakePickerBtn(sub.Condition < names.Length ? names[isAction ? sub.Action : sub.Condition] : "?");
|
||||
var typeBtn = MakePickerBtn(isAction ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition));
|
||||
typeBtn.FontSize = 9;
|
||||
typeBtn.Height = 20;
|
||||
typeBtn.Click += (_, _) =>
|
||||
|
|
@ -1369,13 +1226,9 @@ internal static class MetaPanel
|
|||
|
||||
content.Children.Add(new Border { Height = 1, Background = ColBtnBord });
|
||||
|
||||
if (!string.IsNullOrEmpty(ps.SourceMsg) && (DateTime.Now - ps.SourceMsgTime).TotalSeconds < 5)
|
||||
{
|
||||
content.Children.Add(new TextBlock
|
||||
{
|
||||
Text = ps.SourceMsg, Foreground = ColGreen, FontSize = 10,
|
||||
});
|
||||
}
|
||||
ps.SourceMsgRef = new TextBlock { FontSize = 10, TextWrapping = TextWrapping.Wrap };
|
||||
content.Children.Add(ps.SourceMsgRef);
|
||||
UpdateSourceMsg(ps);
|
||||
|
||||
var sourceEditor = MetaSourceEditor.Create(
|
||||
getText: () => ps.SourceText,
|
||||
|
|
@ -1396,10 +1249,10 @@ internal static class MetaPanel
|
|||
};
|
||||
applyBtn.Click += (_, _) =>
|
||||
{
|
||||
ps.ApplySeqBefore = UiSources.Meta.Current?.Value.ApplyResult?.Seq ?? -1;
|
||||
ps.ApplySentAt = DateTime.Now;
|
||||
Send(new MetaCmd { Op = "set_source", Text = ps.SourceText });
|
||||
ps.SourceMsg = "Applied.";
|
||||
ps.SourceMsgTime = DateTime.Now;
|
||||
rebuild();
|
||||
SetSourceMsg(ps, "Applying…", ok: true);
|
||||
};
|
||||
btnRow.Children.Add(applyBtn);
|
||||
|
||||
|
|
@ -1509,85 +1362,48 @@ internal static class MetaPanel
|
|||
return combined;
|
||||
}
|
||||
|
||||
private static MetaRuleDto CloneRule(MetaRuleDto src)
|
||||
{
|
||||
var r = new MetaRuleDto
|
||||
{
|
||||
State = src.State, Condition = src.Condition,
|
||||
ConditionData = src.ConditionData, Action = src.Action,
|
||||
ActionData = src.ActionData, LastFiredMs = src.LastFiredMs,
|
||||
Enabled = src.Enabled,
|
||||
};
|
||||
foreach (var c in src.Children) r.Children.Add(CloneRule(c));
|
||||
foreach (var a in src.ActionChildren) r.ActionChildren.Add(CloneRule(a));
|
||||
return r;
|
||||
}
|
||||
private static MetaRuleDto CloneRule(MetaRuleDto src) => src.Clone();
|
||||
|
||||
// =========================================================================
|
||||
// Plugin bridge
|
||||
// Source Apply result
|
||||
// =========================================================================
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static MetaPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
private static void SetSourceMsg(PanelState ps, string text, bool ok)
|
||||
{
|
||||
_getMetaJson = null;
|
||||
_sendMetaCommand = null;
|
||||
};
|
||||
ps.SourceMsg = text;
|
||||
ps.SourceMsgOk = ok;
|
||||
ps.SourceMsgTime = DateTime.Now;
|
||||
UpdateSourceMsg(ps);
|
||||
}
|
||||
|
||||
private static void TryBind()
|
||||
/// <summary>A snapshot whose ApplyResult is newer than the pending Apply is its result.</summary>
|
||||
private static void CheckApplyResult(PanelState ps, Payload fresh)
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
if (_getMetaJson == null)
|
||||
if (ps.ApplySeqBefore == -2) return;
|
||||
MetaApplyResult? r = fresh.ApplyResult;
|
||||
if (r != null && r.Seq > ps.ApplySeqBefore)
|
||||
{
|
||||
IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMetaJson");
|
||||
if (p1 != IntPtr.Zero)
|
||||
_getMetaJson = Marshal.GetDelegateForFunctionPointer<GetMetaJsonFn>(p1);
|
||||
}
|
||||
if (_sendMetaCommand == null)
|
||||
{
|
||||
IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSendMetaCommand");
|
||||
if (p2 != IntPtr.Zero)
|
||||
_sendMetaCommand = Marshal.GetDelegateForFunctionPointer<SendMetaCommandFn>(p2);
|
||||
ps.ApplySeqBefore = -2;
|
||||
SetSourceMsg(ps, r.Text, r.Ok);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryFetch(out Payload payload)
|
||||
/// <summary>Shows the message for 8 s; a plugin that doesn't report results gets a pointer to chat.</summary>
|
||||
private static void UpdateSourceMsg(PanelState ps)
|
||||
{
|
||||
payload = new Payload();
|
||||
if (_getMetaJson == null) return false;
|
||||
try
|
||||
if (ps.ApplySeqBefore != -2 && (DateTime.Now - ps.ApplySentAt).TotalSeconds > 3)
|
||||
{
|
||||
IntPtr ptr = _getMetaJson();
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return false;
|
||||
var parsed = JsonSerializer.Deserialize(json, MetaPanelJsonContext.Default.Payload);
|
||||
if (parsed == null) return false;
|
||||
payload = parsed;
|
||||
return true;
|
||||
ps.ApplySeqBefore = -2;
|
||||
SetSourceMsg(ps, "Sent. This RynthAi version reports the result in chat.", ok: true);
|
||||
return;
|
||||
}
|
||||
catch { return false; }
|
||||
if (ps.SourceMsgRef == null) return;
|
||||
bool show = ps.SourceMsg.Length > 0 && (ps.ApplySeqBefore != -2 || (DateTime.Now - ps.SourceMsgTime).TotalSeconds < 8);
|
||||
ps.SourceMsgRef.IsVisible = show;
|
||||
if (!show) return;
|
||||
ps.SourceMsgRef.Text = ps.SourceMsg;
|
||||
ps.SourceMsgRef.Foreground = ps.SourceMsgOk ? ColGreen : ColRed;
|
||||
}
|
||||
|
||||
private static void Send(MetaCmd cmd)
|
||||
{
|
||||
if (_sendMetaCommand == null) TryBind();
|
||||
if (_sendMetaCommand == null) return;
|
||||
IntPtr ansi = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
string json = JsonSerializer.Serialize(cmd, MetaPanelJsonContext.Default.MetaCmd);
|
||||
ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
_sendMetaCommand(ansi);
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
|
||||
}
|
||||
}
|
||||
private static void Send(MetaCmd cmd) => MetaCommands.Send(cmd);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,41 +19,18 @@ using AvaloniaEdit.Document;
|
|||
using AvaloniaEdit.Editing;
|
||||
using AvaloniaEdit.Rendering;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class MetaSourceEditor
|
||||
{
|
||||
// ── .af vocabulary (mirrors MetaSchema in RynthSuite plugin) ──────────────
|
||||
// Top-level structural keywords.
|
||||
private static readonly HashSet<string> StructKeywords = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"STATE", "IF", "DO", "NAV",
|
||||
};
|
||||
|
||||
// Condition keywords as they appear in .af source (keyword form, not labels).
|
||||
internal static readonly string[] ConditionKeywords =
|
||||
{
|
||||
"Never", "Always", "All", "Any", "ChatMatch", "MainSlotsLE",
|
||||
"SecsInStateGE", "Death", "VendorOpen", "VendorClosed",
|
||||
"ItemCountLE", "ItemCountGE",
|
||||
"MobsInDist_Name", "MobsInDist_Priority",
|
||||
"NeedToBuff", "NoMobsInDist", "BlockE", "CellE",
|
||||
"IntoPortal", "ExitPortal", "Not",
|
||||
"PSecsInStateGE", "SecsOnSpellGE", "SecsOnSpellLE",
|
||||
"BuPercentGE", "DistToRteGE", "Expr",
|
||||
"ChatCapture", "NavEmpty",
|
||||
"MainHealthLE", "MainHealthPHE", "MainManaLE", "MainManaPHE",
|
||||
"MainStamLE", "VitaePHE",
|
||||
};
|
||||
|
||||
internal static readonly string[] ActionKeywords =
|
||||
{
|
||||
"None", "Chat", "SetState", "EmbedNav", "DoAll",
|
||||
"CallState", "Return", "DoExpr", "ChatExpr",
|
||||
"SetWatchdog", "ClearWatchdog", "GetOpt", "SetOpt",
|
||||
"CreateView", "DestroyView", "DestroyAllViews",
|
||||
};
|
||||
// The keyword lists live in UI/Data/MetaData.cs (MetaVocabulary), shared
|
||||
// with the ImGui face's editor.
|
||||
private static readonly HashSet<string> StructKeywords = new(MetaVocabulary.StructKeywords, StringComparer.OrdinalIgnoreCase);
|
||||
internal static readonly string[] ConditionKeywords = MetaVocabulary.ConditionKeywords;
|
||||
internal static readonly string[] ActionKeywords = MetaVocabulary.ActionKeywords;
|
||||
|
||||
private static readonly HashSet<string> CondSet = new(ConditionKeywords, StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly HashSet<string> ActSet = new(ActionKeywords, StringComparer.OrdinalIgnoreCase);
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine — UI/Panels/MonsterDamagePanel.cs
|
||||
// Interactive table of the RynthAi plugin's learned per-monster combat data.
|
||||
// Bridge exports (polled every 500ms):
|
||||
// Data comes through UiDataHub (UI/Data/DamageData.cs: UiSources.Damage and
|
||||
// UiSources.MonsterRules, DamageCommands), which calls these plugin exports
|
||||
// on the pump thread; the ImGui face (ImGui/Panels/DamageFace.cs) shares it:
|
||||
// RynthPluginGetMonsterDamageJson() → JSON rows (STABLE order)
|
||||
// RynthPluginSetMonsterHp(wcid, hp) → manual HP override
|
||||
// RynthPluginDeleteMonsterRow(key) → delete one learned row
|
||||
// RynthPluginGetCombatWeaponsJson() → selectable weapons [{id,name}]
|
||||
// RynthPluginSetMonsterWeapon(wcid, wid) → per-monster weapon override (0 = Auto/best)
|
||||
// RynthPluginSetMonsterOffhand(wcid, oid) → per-monster offhand override (0 = none; stored only)
|
||||
// Columns: WCID | Monster | Elem | Tier | HP(edit) | Crit | NonCrit | Casts/Kill | Kills | Weapon | Offhand | ✕
|
||||
// RynthPluginGetPetChoicesJson / RynthPluginSetMonsterPet(wcid, choice) → per-monster pet
|
||||
// ("" = Auto by weakest element, "E:<element>", "I:<essence id>")
|
||||
// Columns: WCID | Monster | Elem | Tier | HP(edit) | Crit | NonCrit | Casts/Kill | Kills | Weapon | Offhand | Pet | ✕
|
||||
// Weapon is per-MONSTER (wcid): it defaults to the learned-best ("Auto") and the
|
||||
// same value shows on every row of that monster; picking pins an override (gold).
|
||||
// Rows update IN PLACE (cells only) — the row Grids + HP TextBoxes are never
|
||||
|
|
@ -31,81 +35,15 @@ using Avalonia.Media;
|
|||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class MonsterDamagePanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetHpFn(uint wcid, int hp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int DelRowFn(IntPtr keyAnsi);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetU2Fn(uint wcid, uint id); // weapon/offhand override
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetU1Fn(uint id); // default weapon (one arg)
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetJsonFn(IntPtr ansiJson); // monsters rules write-back
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void VoidFn(); // parameterless action (clear stats)
|
||||
|
||||
private static GetJsonFn? _getJson;
|
||||
private static SetHpFn? _setHp;
|
||||
private static DelRowFn? _delRow;
|
||||
private static GetJsonFn? _getWeapons; // RynthPluginGetCombatWeaponsJson
|
||||
private static SetU2Fn? _setWeapon; // RynthPluginSetMonsterWeapon
|
||||
private static SetU2Fn? _setOffhand; // RynthPluginSetMonsterOffhand
|
||||
private static SetU1Fn? _setDefaultWeapon; // RynthPluginSetDefaultWeapon (sweeping default)
|
||||
private static GetJsonFn? _getMonsters; // RynthPluginGetMonstersJson (per-monster debuff/shape rules)
|
||||
private static SetJsonFn? _setMonsters; // RynthPluginSetMonstersJson (write-back, whole rules array)
|
||||
private static VoidFn? _clearStats; // RynthPluginClearMonsterStats (master reset)
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static MonsterDamagePanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getJson = null;
|
||||
_setHp = null;
|
||||
_delRow = null;
|
||||
_getWeapons = null;
|
||||
_setWeapon = null;
|
||||
_setOffhand = null;
|
||||
_getMonsters = null;
|
||||
_setMonsters = null;
|
||||
_clearStats = null;
|
||||
_setDefaultWeapon = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
if (_getJson != null) return;
|
||||
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
IntPtr a = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMonsterDamageJson");
|
||||
IntPtr b = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonsterHp");
|
||||
IntPtr c = GetProcAddress(plugin.ModuleHandle, "RynthPluginDeleteMonsterRow");
|
||||
IntPtr d = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetCombatWeaponsJson");
|
||||
IntPtr e = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonsterWeapon");
|
||||
IntPtr f = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonsterOffhand");
|
||||
IntPtr g = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMonstersJson");
|
||||
IntPtr h = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonstersJson");
|
||||
IntPtr i = GetProcAddress(plugin.ModuleHandle, "RynthPluginClearMonsterStats");
|
||||
IntPtr j = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetDefaultWeapon");
|
||||
if (a != IntPtr.Zero) _getJson = Marshal.GetDelegateForFunctionPointer<GetJsonFn>(a);
|
||||
if (b != IntPtr.Zero) _setHp = Marshal.GetDelegateForFunctionPointer<SetHpFn>(b);
|
||||
if (c != IntPtr.Zero) _delRow = Marshal.GetDelegateForFunctionPointer<DelRowFn>(c);
|
||||
if (d != IntPtr.Zero) _getWeapons = Marshal.GetDelegateForFunctionPointer<GetJsonFn>(d);
|
||||
if (e != IntPtr.Zero) _setWeapon = Marshal.GetDelegateForFunctionPointer<SetU2Fn>(e);
|
||||
if (f != IntPtr.Zero) _setOffhand = Marshal.GetDelegateForFunctionPointer<SetU2Fn>(f);
|
||||
if (g != IntPtr.Zero) _getMonsters = Marshal.GetDelegateForFunctionPointer<GetJsonFn>(g);
|
||||
if (h != IntPtr.Zero) _setMonsters = Marshal.GetDelegateForFunctionPointer<SetJsonFn>(h);
|
||||
if (i != IntPtr.Zero) _clearStats = Marshal.GetDelegateForFunctionPointer<VoidFn>(i);
|
||||
if (j != IntPtr.Zero) _setDefaultWeapon = Marshal.GetDelegateForFunctionPointer<SetU1Fn>(j);
|
||||
}
|
||||
|
||||
internal static Control Create() => new View().Root;
|
||||
|
||||
private const string Cols = "60,156,54,36,80,56,60,68,48,120,110,26";
|
||||
private const string Cols = "60,156,54,36,80,56,60,68,48,120,110,120,26";
|
||||
|
||||
private static readonly IBrush HeaderBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x12, 0x1C, 0x26));
|
||||
private static readonly IBrush PanelBg = new SolidColorBrush(Color.FromArgb(0xF0, 0x08, 0x10, 0x18));
|
||||
|
|
@ -128,47 +66,9 @@ internal static class MonsterDamagePanel
|
|||
// MonstersPanel.Rule.GetToggle/SetToggle; combat consumes them via BuildDebuffList /
|
||||
// the UseArc/Bolt/Ring/Streak shape gate — so this drawer is just an editor of the
|
||||
// existing name-keyed rule (no combat/storage changes).
|
||||
private static readonly (string Field, string Label, string Tip)[] DebuffDefs =
|
||||
{
|
||||
("Imperil", "Imperil", "Imperil (Gossamer Flesh / Imperil Other)"),
|
||||
("Vuln", "Vuln", "Vulnerability (element-matched)"),
|
||||
("Fester", "Fester", "Fester (Decrepitude's Grasp / Fester Other)"),
|
||||
("Yield", "Yield", "Yield (Magic Yield Other)"),
|
||||
("Broadside", "Broadside","Broadside (Missile Weapons Ineptitude)"),
|
||||
("GravityWell", "Gravity", "Gravity Well (Vulnerability Other)"),
|
||||
};
|
||||
private static readonly (string Field, string Label, string Tip)[] ShapeDefs =
|
||||
{
|
||||
("UseArc", "Arc", "Arc spells"),
|
||||
("UseBolt", "Bolt", "Bolt spells (default)"),
|
||||
("UseRing", "Ring", "Ring spells"),
|
||||
("UseStreak", "Streak", "Streak spells"),
|
||||
};
|
||||
private static readonly string[] ExVulnTypes =
|
||||
{ "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
private static bool IsShape(string f) => f is "UseArc" or "UseBolt" or "UseRing" or "UseStreak";
|
||||
private static bool NoShapeOn(MonstersPanel.Rule r) => !r.UseArc && !r.UseBolt && !r.UseRing && !r.UseStreak;
|
||||
|
||||
private sealed class Row
|
||||
{
|
||||
public uint Wcid; public string Name = ""; public uint Wid; public string Weapon = "";
|
||||
public string Elem = ""; public int Tier; public int Hp; public bool HpManual;
|
||||
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
|
||||
public double Casts; public int Kills; public string Key = "";
|
||||
// Per-monster (wcid) weapon picker state (same on every row of a wcid).
|
||||
public uint AssignedWid; public string AssignedWeapon = ""; // user override (0 = none)
|
||||
public uint BestWid; public string BestWeapon = ""; // learned recommendation (0 = none yet)
|
||||
public uint AssignedOff; public string AssignedOffName = ""; // offhand override (stored only)
|
||||
public List<TierStat> Tiers = new(); // per-tier breakdown for the expand drawer
|
||||
public bool IsDefault; // the synthetic top "Default" line (wcid 0)
|
||||
}
|
||||
|
||||
private sealed class TierStat
|
||||
{
|
||||
public int Tier; public string Elem = ""; public string Weapon = "";
|
||||
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
|
||||
public double Casts; public int Kills;
|
||||
}
|
||||
private static (string Field, string Label, string Tip)[] DebuffDefs => DamageCommands.DebuffDefs;
|
||||
private static (string Field, string Label, string Tip)[] ShapeDefs => DamageCommands.ShapeDefs;
|
||||
private static string[] ExVulnTypes => DamageCommands.ExVulnTypes;
|
||||
|
||||
private sealed class RowWidgets
|
||||
{
|
||||
|
|
@ -178,9 +78,9 @@ internal static class MonsterDamagePanel
|
|||
public TextBox Hp = null!;
|
||||
public Button HpManualToggle = null!; // "M": on = manual HP entry, off = auto
|
||||
public Button DefaultToggle = null!; // "D": on = this monster follows Default (debuffs/shapes/weapon)
|
||||
public Button Weapon = null!, Offhand = null!;
|
||||
public Button Weapon = null!, Offhand = null!, Pet = null!;
|
||||
public Button Chevron = null!; // toggles the per-monster debuff drawer
|
||||
public Row Data = null!; // latest row data (so picker click handlers read current best/override)
|
||||
public DamageRow Data = null!; // latest row data (so picker click handlers read current best/override)
|
||||
}
|
||||
|
||||
private sealed class View
|
||||
|
|
@ -202,14 +102,13 @@ internal static class MonsterDamagePanel
|
|||
private uint _filterWid; // 0 = all weapons
|
||||
private string _filterName = "All weapons";
|
||||
private string _filterText = ""; // monster name / wcid search (case-insensitive)
|
||||
private string _lastJson = "";
|
||||
private long _seenVersion = -1, _seenRulesVersion = -1;
|
||||
private bool _editing; // an HP box is focused → defer structural rebuilds
|
||||
private List<Row> _data = new();
|
||||
private readonly List<(uint Wid, string Name)> _weapons = new();
|
||||
private readonly List<(uint Id, string Name)> _items = new(); // selectable weapons (from plugin ItemRules)
|
||||
private string _lastWeaponsJson = "";
|
||||
private MonstersPanel.Payload _monsters = new(); // name-keyed debuff/shape rules (for the drawer)
|
||||
private string _lastMonstersJson = "";
|
||||
private List<DamageRow> _data = new();
|
||||
private List<(uint Id, string Name)> _weapons = new(); // learned weapons (filter)
|
||||
private List<(uint Id, string Name)> _choices = new(); // per-row weapon picker list
|
||||
private List<(string Key, string Name)> _pets = new();
|
||||
private MonsterRulesSnapshot? _rules; // name-keyed debuff/shape rules (drawer)
|
||||
private uint _expandedWcid; // monster (wcid) whose drawer is open (0 = none)
|
||||
private bool _defaultExpanded; // the top Default line's drawer is open
|
||||
|
||||
|
|
@ -310,80 +209,59 @@ internal static class MonsterDamagePanel
|
|||
rootGrid.Children.Add(_pickerCanvas);
|
||||
Root = rootGrid;
|
||||
|
||||
TryBind();
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
|
||||
// Reads the hub's snapshots (fetched every 500 ms / 1 s while
|
||||
// subscribed, and right after each command).
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
timer.Tick += (_, _) => Poll();
|
||||
timer.Start();
|
||||
// Stop with the visual tree (RadarPanel idiom): a running
|
||||
// DispatcherTimer roots the closed panel view forever — every
|
||||
// open/close otherwise adds another immortal poller hitting the
|
||||
// plugin C exports against a detached tree.
|
||||
rootGrid.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
rootGrid.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
// DispatcherTimer roots the closed panel view forever.
|
||||
rootGrid.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Damage.Subscribe();
|
||||
UiSources.MonsterRules.Subscribe();
|
||||
UiSources.Damage.RequestRefresh();
|
||||
UiSources.MonsterRules.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
rootGrid.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Damage.Unsubscribe();
|
||||
UiSources.MonsterRules.Unsubscribe();
|
||||
};
|
||||
Poll();
|
||||
}
|
||||
|
||||
private void Poll()
|
||||
{
|
||||
if (_getJson == null) { TryBind(); if (_getJson == null) { _status.Text = "Waiting for RynthAi plugin…"; return; } }
|
||||
var rules = UiSources.MonsterRules.Current;
|
||||
bool rulesChanged = rules != null && rules.Version != _seenRulesVersion;
|
||||
if (rulesChanged)
|
||||
{
|
||||
_seenRulesVersion = rules!.Version;
|
||||
_rules = rules.Value;
|
||||
}
|
||||
|
||||
RefreshItems();
|
||||
RefreshMonsters();
|
||||
|
||||
IntPtr ptr;
|
||||
try { ptr = _getJson(); } catch { return; }
|
||||
if (ptr == IntPtr.Zero) return;
|
||||
string json = Marshal.PtrToStringAnsi(ptr) ?? "[]";
|
||||
if (json == _lastJson) return;
|
||||
_lastJson = json;
|
||||
|
||||
_data = Parse(json);
|
||||
var snap = UiSources.Damage.Current;
|
||||
if (snap == null) { _status.Text = "Binding to RynthAi…"; return; }
|
||||
if (!snap.Value.Bound) { _status.Text = "Waiting for RynthAi plugin…"; return; }
|
||||
if (snap.Version == _seenVersion)
|
||||
{
|
||||
if (rulesChanged) RebuildDrawer(); // drawer + chevron/D colours follow the rules
|
||||
return;
|
||||
}
|
||||
_seenVersion = snap.Version;
|
||||
_data = snap.Value.Rows;
|
||||
_weapons = snap.Value.LearnedWeapons;
|
||||
_choices = snap.Value.WeaponChoices;
|
||||
_pets = snap.Value.PetChoices;
|
||||
UpdateWeapons();
|
||||
Reconcile();
|
||||
}
|
||||
|
||||
// Refresh the selectable-weapons list (configured ItemRules) shown in the row pickers.
|
||||
private void RefreshItems()
|
||||
{
|
||||
if (_getWeapons == null) return;
|
||||
IntPtr p;
|
||||
try { p = _getWeapons(); } catch { return; }
|
||||
if (p == IntPtr.Zero) return;
|
||||
string json = Marshal.PtrToStringAnsi(p) ?? "[]";
|
||||
if (json == _lastWeaponsJson) return;
|
||||
_lastWeaponsJson = json;
|
||||
_items.Clear();
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
foreach (var e in doc.RootElement.EnumerateArray())
|
||||
_items.Add(((uint)e.GetProperty("id").GetInt64(), e.GetProperty("name").GetString() ?? ""));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// Refresh the name-keyed debuff/shape rules (shared with the Monsters tab) used by
|
||||
// the per-monster drawer. Reuses MonstersPanel's payload type + JSON context.
|
||||
private void RefreshMonsters()
|
||||
{
|
||||
if (_getMonsters == null) return;
|
||||
IntPtr p;
|
||||
try { p = _getMonsters(); } catch { return; }
|
||||
if (p == IntPtr.Zero) return;
|
||||
string json = Marshal.PtrToStringAnsi(p) ?? "";
|
||||
if (json.Length == 0 || json == _lastMonstersJson) return;
|
||||
_lastMonstersJson = json;
|
||||
try
|
||||
{
|
||||
var parsed = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload);
|
||||
if (parsed != null) _monsters = parsed;
|
||||
}
|
||||
catch { }
|
||||
if (rulesChanged) RebuildDrawer(); else Reconcile();
|
||||
}
|
||||
|
||||
private void Reconcile()
|
||||
{
|
||||
List<Row> filtered = ApplyFilters();
|
||||
List<DamageRow> filtered = ApplyFilters();
|
||||
var newKeys = filtered.Select(r => r.Key).ToList();
|
||||
bool structural = !newKeys.SequenceEqual(_displayedKeys);
|
||||
|
||||
|
|
@ -434,9 +312,9 @@ internal static class MonsterDamagePanel
|
|||
}
|
||||
|
||||
// Weapon filter (dropdown) AND monster search (name substring or wcid) combined.
|
||||
private List<Row> ApplyFilters()
|
||||
private List<DamageRow> ApplyFilters()
|
||||
{
|
||||
IEnumerable<Row> q = _data;
|
||||
IEnumerable<DamageRow> q = _data;
|
||||
// The Default line is always kept (pinned at top), exempt from filters.
|
||||
if (_filterWid != 0)
|
||||
q = q.Where(r => r.IsDefault || r.Wid == _filterWid);
|
||||
|
|
@ -447,75 +325,9 @@ internal static class MonsterDamagePanel
|
|||
return q.ToList();
|
||||
}
|
||||
|
||||
private static List<Row> Parse(string json)
|
||||
{
|
||||
var list = new List<Row>();
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
foreach (var e in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
var row = new Row
|
||||
{
|
||||
Wcid = (uint)e.GetProperty("wcid").GetInt64(),
|
||||
Name = e.GetProperty("name").GetString() ?? "",
|
||||
Wid = (uint)e.GetProperty("wid").GetInt64(),
|
||||
Weapon = e.GetProperty("weapon").GetString() ?? "",
|
||||
Elem = e.GetProperty("elem").GetString() ?? "",
|
||||
Tier = e.GetProperty("tier").GetInt32(),
|
||||
Hp = e.GetProperty("hp").GetInt32(),
|
||||
HpManual = e.GetProperty("hpManual").GetBoolean(),
|
||||
Crit = e.GetProperty("crit").GetDouble(),
|
||||
CritN = e.GetProperty("critN").GetInt32(),
|
||||
NonCrit = e.GetProperty("noncrit").GetDouble(),
|
||||
NonCritN = e.GetProperty("noncritN").GetInt32(),
|
||||
Casts = e.GetProperty("casts").GetDouble(),
|
||||
Kills = e.GetProperty("kills").GetInt32(),
|
||||
Key = e.GetProperty("key").GetString() ?? "",
|
||||
};
|
||||
// New per-monster weapon fields (TryGetProperty so an older plugin
|
||||
// build that omits them doesn't blank the whole table).
|
||||
if (e.TryGetProperty("assignedWid", out var aw)) row.AssignedWid = (uint)aw.GetInt64();
|
||||
if (e.TryGetProperty("assignedWeapon", out var awn)) row.AssignedWeapon = awn.GetString() ?? "";
|
||||
if (e.TryGetProperty("bestWid", out var bw)) row.BestWid = (uint)bw.GetInt64();
|
||||
if (e.TryGetProperty("bestWeapon", out var bwn)) row.BestWeapon = bwn.GetString() ?? "";
|
||||
if (e.TryGetProperty("assignedOff", out var ao)) row.AssignedOff = (uint)ao.GetInt64();
|
||||
if (e.TryGetProperty("assignedOffName", out var aon))row.AssignedOffName = aon.GetString() ?? "";
|
||||
if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean();
|
||||
// Per-tier breakdown (for the expand drawer). Optional so an older plugin doesn't break the table.
|
||||
if (e.TryGetProperty("tiers", out var tarr) && tarr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var te in tarr.EnumerateArray())
|
||||
{
|
||||
row.Tiers.Add(new TierStat
|
||||
{
|
||||
Tier = te.GetProperty("tier").GetInt32(),
|
||||
Elem = te.GetProperty("elem").GetString() ?? "",
|
||||
Weapon = te.GetProperty("weapon").GetString() ?? "",
|
||||
Crit = te.GetProperty("crit").GetDouble(),
|
||||
CritN = te.GetProperty("critN").GetInt32(),
|
||||
NonCrit = te.GetProperty("noncrit").GetDouble(),
|
||||
NonCritN = te.GetProperty("noncritN").GetInt32(),
|
||||
Casts = te.GetProperty("casts").GetDouble(),
|
||||
Kills = te.GetProperty("kills").GetInt32(),
|
||||
});
|
||||
}
|
||||
}
|
||||
list.Add(row);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return list;
|
||||
}
|
||||
|
||||
private void UpdateWeapons()
|
||||
{
|
||||
_weapons.Clear();
|
||||
var seen = new HashSet<uint>();
|
||||
foreach (var r in _data)
|
||||
if (r.Wid != 0 && seen.Add(r.Wid)) _weapons.Add((r.Wid, r.Weapon));
|
||||
|
||||
if (_filterWid != 0 && !seen.Contains(_filterWid)) { _filterWid = 0; _filterName = "All weapons"; }
|
||||
if (_filterWid != 0 && !_weapons.Exists(w => w.Id == _filterWid)) { _filterWid = 0; _filterName = "All weapons"; }
|
||||
_filterBtn.Content = "Weapon: " + Trunc(_filterName, 22) + " ▾";
|
||||
_status.Text = _data.Count == 0 ? "No kills recorded yet." : $"{_data.Count} rows · {_weapons.Count} weapon(s)";
|
||||
}
|
||||
|
|
@ -586,11 +398,11 @@ internal static class MonsterDamagePanel
|
|||
private void ShowWeaponPicker()
|
||||
{
|
||||
var items = new List<(uint Id, string Name)>(_weapons.Count + 1) { (0u, "All weapons") };
|
||||
foreach (var w in _weapons) items.Add((w.Wid, w.Name));
|
||||
foreach (var w in _weapons) items.Add((w.Id, w.Name));
|
||||
ShowPicker(_filterBtn, items, _filterWid, id =>
|
||||
{
|
||||
_filterWid = id;
|
||||
var match = _weapons.FirstOrDefault(w => w.Wid == id);
|
||||
var match = _weapons.FirstOrDefault(w => w.Id == id);
|
||||
_filterName = id == 0 ? "All weapons" : (match.Name ?? ("Weapon " + id));
|
||||
_filterBtn.Content = "Weapon: " + Trunc(_filterName, 22) + " ▾";
|
||||
_displayedKeys = new List<string> { "\0force" }; // force a structural rebuild for the new filter
|
||||
|
|
@ -598,20 +410,9 @@ internal static class MonsterDamagePanel
|
|||
});
|
||||
}
|
||||
|
||||
// Distinct selectable weapons for the per-row pickers: configured weapons
|
||||
// (ItemRules, from the plugin) merged with weapons we have learned data for,
|
||||
// sorted by name.
|
||||
private List<(uint Id, string Name)> WeaponChoices()
|
||||
{
|
||||
var seen = new HashSet<uint>();
|
||||
var list = new List<(uint Id, string Name)>();
|
||||
foreach (var it in _items)
|
||||
if (it.Id != 0 && seen.Add(it.Id)) list.Add(it);
|
||||
foreach (var w in _weapons)
|
||||
if (w.Wid != 0 && seen.Add(w.Wid)) list.Add((w.Wid, w.Name));
|
||||
list.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||
return list;
|
||||
}
|
||||
private List<(string Key, string Name)> PetChoices() => _pets;
|
||||
|
||||
private List<(uint Id, string Name)> WeaponChoices() => _choices;
|
||||
|
||||
private void ClosePicker()
|
||||
{
|
||||
|
|
@ -655,10 +456,8 @@ internal static class MonsterDamagePanel
|
|||
cancel.Click += (_, _) => ClosePicker();
|
||||
confirm.Click += (_, _) =>
|
||||
{
|
||||
if (_clearStats != null) { try { _clearStats(); } catch { } }
|
||||
DamageCommands.ClearStats();
|
||||
ClosePicker();
|
||||
_lastJson = ""; // force the next poll to re-read the zeroed stats
|
||||
Dispatcher.UIThread.Post(Poll);
|
||||
};
|
||||
var btnRow = new StackPanel
|
||||
{
|
||||
|
|
@ -688,92 +487,11 @@ internal static class MonsterDamagePanel
|
|||
// The drawer edits an EXACT-name rule for the monster: editing while inheriting
|
||||
// clones Default into one (so other config carries over); Reset deletes it.
|
||||
|
||||
private MonstersPanel.Rule? FindRule(string name) =>
|
||||
_monsters.Rules?.FirstOrDefault(r =>
|
||||
!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)
|
||||
&& r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
private MonstersPanel.Rule? FindRule(string name) => _rules?.FindRule(name);
|
||||
|
||||
private bool HasCustomRule(string name) => FindRule(name) != null;
|
||||
private bool HasCustomRule(string name) => _rules?.HasCustomRule(name) ?? false;
|
||||
|
||||
private MonstersPanel.Rule DefaultRule() =>
|
||||
_monsters.Rules?.FirstOrDefault(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase))
|
||||
?? new MonstersPanel.Rule { Name = "Default", UseBolt = true };
|
||||
|
||||
private static MonstersPanel.Rule CloneRule(MonstersPanel.Rule s, string name) => new MonstersPanel.Rule
|
||||
{
|
||||
Name = name,
|
||||
Category = s.Category,
|
||||
MatchExpression = "", // exact-name rule matches by name, not a (possibly false) expression
|
||||
Priority = s.Priority,
|
||||
DamageType = s.DamageType,
|
||||
WeaponId = s.WeaponId,
|
||||
OffhandId = s.OffhandId,
|
||||
ExVuln = s.ExVuln,
|
||||
PetDamage = s.PetDamage,
|
||||
Fester = s.Fester, Broadside = s.Broadside, GravityWell = s.GravityWell,
|
||||
Imperil = s.Imperil, Yield = s.Yield, Vuln = s.Vuln,
|
||||
UseArc = s.UseArc, UseBolt = s.UseBolt, UseRing = s.UseRing, UseStreak = s.UseStreak,
|
||||
};
|
||||
|
||||
// Force a fresh re-read of the rules right before a write. Both panels run on the
|
||||
// single UI thread, so re-reading here means the drawer builds its edit on the very
|
||||
// latest plugin state and can't clobber a rule just added on the Monsters tab.
|
||||
private void RefreshMonstersNow() { _lastMonstersJson = ""; RefreshMonsters(); }
|
||||
|
||||
// Return the editable exact-name rule, creating it (cloned from Default) if the
|
||||
// monster is currently inheriting. Inserted right after Default so the more-specific
|
||||
// rule wins GetRuleForTarget's first-substring-match resolution.
|
||||
private MonstersPanel.Rule EnsureCustomRule(string name)
|
||||
{
|
||||
RefreshMonstersNow();
|
||||
// The Default line edits the real Default rule in place (not a clone).
|
||||
if (name.Equals("Default", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var def = DefaultRule();
|
||||
if (_monsters.Rules != null && !_monsters.Rules.Contains(def)) _monsters.Rules.Add(def);
|
||||
return def;
|
||||
}
|
||||
var existing = FindRule(name);
|
||||
if (existing != null) return existing;
|
||||
var clone = CloneRule(DefaultRule(), name);
|
||||
int defIdx = _monsters.Rules.FindIndex(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
|
||||
_monsters.Rules.Insert(defIdx >= 0 ? defIdx + 1 : 0, clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
private void ResetRule(string name)
|
||||
{
|
||||
RefreshMonstersNow();
|
||||
int i = _monsters.Rules.FindIndex(r =>
|
||||
!r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)
|
||||
&& r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (i < 0) return;
|
||||
_monsters.Rules.RemoveAt(i);
|
||||
PushMonsters();
|
||||
RebuildDrawer();
|
||||
}
|
||||
|
||||
// Whole-rules-array write-back over the existing Monsters bridge (same shape the
|
||||
// Monsters tab pushes). The plugin's ApplyMonstersJson preserves the Default rule.
|
||||
private void PushMonsters()
|
||||
{
|
||||
if (_setMonsters == null) return;
|
||||
// Never write back an empty/un-loaded array — that would wipe the user's rules
|
||||
// (incl. Default) on the plugin side.
|
||||
if (_monsters?.Rules == null || _monsters.Rules.Count == 0) return;
|
||||
IntPtr ansi = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
string json = JsonSerializer.Serialize(
|
||||
new MonstersPanel.Payload { Rules = _monsters.Rules },
|
||||
MonstersPanelJsonContext.Default.Payload);
|
||||
ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
_setMonsters(ansi);
|
||||
}
|
||||
catch { }
|
||||
finally { if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi); }
|
||||
_lastMonstersJson = ""; // re-read the plugin's applied copy on the next poll
|
||||
}
|
||||
private MonstersPanel.Rule DefaultRule() => _rules?.DefaultRule() ?? new MonstersPanel.Rule { Name = "Default", UseBolt = true };
|
||||
|
||||
private void RebuildDrawer()
|
||||
{
|
||||
|
|
@ -781,7 +499,7 @@ internal static class MonsterDamagePanel
|
|||
Reconcile();
|
||||
}
|
||||
|
||||
private Control BuildDebuffDrawer(Row row)
|
||||
private Control BuildDebuffDrawer(DamageRow row)
|
||||
{
|
||||
string monsterName = row.Name;
|
||||
var border = new Border
|
||||
|
|
@ -796,7 +514,7 @@ internal static class MonsterDamagePanel
|
|||
border.Child = stack;
|
||||
|
||||
// Guard: never write back an empty/un-loaded rules array (would clobber Default).
|
||||
if (_setMonsters == null || _monsters.Rules == null || _monsters.Rules.Count == 0)
|
||||
if (_rules == null || _rules.Parsed.Rules.Count == 0)
|
||||
{
|
||||
stack.Children.Add(new TextBlock
|
||||
{
|
||||
|
|
@ -831,7 +549,7 @@ internal static class MonsterDamagePanel
|
|||
Background = EntryBg, Foreground = custom ? Brushes.White : Dim,
|
||||
BorderBrush = EntryBorder, BorderThickness = new Thickness(1), IsEnabled = custom,
|
||||
};
|
||||
reset.Click += (_, _) => ResetRule(monsterName);
|
||||
reset.Click += (_, _) => DamageCommands.ResetRule(monsterName);
|
||||
header.Children.Add(reset);
|
||||
stack.Children.Add(header);
|
||||
|
||||
|
|
@ -866,9 +584,8 @@ internal static class MonsterDamagePanel
|
|||
uint sel = (uint)Math.Max(0, Array.IndexOf(ExVulnTypes, nowEx));
|
||||
ShowPicker(exBtn, items, sel, id =>
|
||||
{
|
||||
EnsureCustomRule(monsterName).ExVuln = ExVulnTypes[id];
|
||||
PushMonsters();
|
||||
RebuildDrawer();
|
||||
string ex = ExVulnTypes[id];
|
||||
DamageCommands.EditRule(monsterName, r => r.ExVuln = ex);
|
||||
});
|
||||
};
|
||||
exRow.Children.Add(exBtn);
|
||||
|
|
@ -889,7 +606,7 @@ internal static class MonsterDamagePanel
|
|||
string crit = t.CritN > 0 ? t.Crit.ToString("0", CultureInfo.InvariantCulture) : "—";
|
||||
string nc = t.NonCritN > 0 ? t.NonCrit.ToString("0", CultureInfo.InvariantCulture) : "—";
|
||||
string ck = t.Kills > 0 ? t.Casts.ToString("0.00", CultureInfo.InvariantCulture) : "—";
|
||||
string line = $"{FormatTier(t.Tier),-4} {(string.IsNullOrEmpty(t.Elem) ? "" : t.Elem),-8} kills {t.Kills,-4} crit {crit,-5} non-crit {nc,-5} casts/kill {ck}";
|
||||
string line = $"{DamageSource.FormatTier(t.Tier),-4} {(string.IsNullOrEmpty(t.Elem) ? "" : t.Elem),-8} kills {t.Kills,-4} crit {crit,-5} non-crit {nc,-5} casts/kill {ck}";
|
||||
stack.Children.Add(new TextBlock
|
||||
{
|
||||
Text = line, FontSize = 11, Foreground = Brushes.White,
|
||||
|
|
@ -923,16 +640,7 @@ internal static class MonsterDamagePanel
|
|||
},
|
||||
};
|
||||
ToolTip.SetTip(btn, tip);
|
||||
btn.Click += (_, _) =>
|
||||
{
|
||||
var rule = EnsureCustomRule(monsterName);
|
||||
bool nv = !rule.GetToggle(field);
|
||||
rule.SetToggle(field, nv);
|
||||
// Never leave a monster with no offensive shape (combat would refuse to cast).
|
||||
if (IsShape(field) && !nv && NoShapeOn(rule)) rule.UseBolt = true;
|
||||
PushMonsters();
|
||||
RebuildDrawer();
|
||||
};
|
||||
btn.Click += (_, _) => DamageCommands.EditRule(monsterName, r => DamageCommands.FlipToggle(r, field));
|
||||
return btn;
|
||||
}
|
||||
|
||||
|
|
@ -963,7 +671,8 @@ internal static class MonsterDamagePanel
|
|||
AddCell(g, 8, "Kills", bold: true);
|
||||
AddCell(g, 9, "Weapon", bold: true);
|
||||
AddCell(g, 10, "Offhand", bold: true);
|
||||
AddCell(g, 11, "", bold: true);
|
||||
AddCell(g, 11, "Pet", bold: true);
|
||||
AddCell(g, 12, "", bold: true);
|
||||
return g;
|
||||
}
|
||||
|
||||
|
|
@ -984,7 +693,7 @@ internal static class MonsterDamagePanel
|
|||
BorderThickness = new Thickness(1),
|
||||
};
|
||||
|
||||
private RowWidgets CreateRow(Row r)
|
||||
private RowWidgets CreateRow(DamageRow r)
|
||||
{
|
||||
if (r.IsDefault) return CreateDefaultRow();
|
||||
var g = NewRowGrid(22);
|
||||
|
|
@ -1028,17 +737,12 @@ internal static class MonsterDamagePanel
|
|||
var cur = rw.Data;
|
||||
bool onDefault = !HasCustomRule(cur.Name) && cur.AssignedWid == 0;
|
||||
if (onDefault)
|
||||
{
|
||||
EnsureCustomRule(cur.Name); // turn OFF default → give it an editable custom rule
|
||||
PushMonsters();
|
||||
}
|
||||
DamageCommands.EditRule(cur.Name, static _ => { }); // turn OFF default → an editable custom rule
|
||||
else
|
||||
{
|
||||
ResetRule(cur.Name); // turn ON default → drop custom rule (PushMonsters inside)
|
||||
if (_setWeapon != null && cur.Wcid != 0) { try { _setWeapon(cur.Wcid, 0); } catch { } } // weapon → Default
|
||||
DamageCommands.ResetRule(cur.Name); // turn ON default → drop the custom rule
|
||||
if (cur.Wcid != 0) DamageCommands.SetWeapon(cur.Wcid, 0); // weapon → Default
|
||||
}
|
||||
_lastJson = "";
|
||||
Dispatcher.UIThread.Post(Poll);
|
||||
};
|
||||
rw.DefaultToggle = dToggle;
|
||||
|
||||
|
|
@ -1074,14 +778,10 @@ internal static class MonsterDamagePanel
|
|||
uint wcid = r.Wcid;
|
||||
void CommitHp()
|
||||
{
|
||||
if (_setHp == null) return;
|
||||
string t = (hp.Text ?? "").Trim();
|
||||
if (t.Length == 0) { try { _setHp(wcid, 0); } catch { } _lastJson = ""; return; }
|
||||
if (t.Length == 0) { DamageCommands.SetHp(wcid, 0); return; }
|
||||
if (int.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) && v > 0)
|
||||
{
|
||||
try { _setHp(wcid, v); } catch { }
|
||||
_lastJson = ""; // force a refresh so the gold "manual" flag shows
|
||||
}
|
||||
DamageCommands.SetHp(wcid, v);
|
||||
}
|
||||
hp.GotFocus += (_, _) => { _editing = true; Win32Backend.AvaloniaTextInputActive = true; };
|
||||
hp.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; _editing = false; CommitHp(); };
|
||||
|
|
@ -1112,17 +812,13 @@ internal static class MonsterDamagePanel
|
|||
ToolTip.SetTip(mToggle, "Manual max-HP for this monster (off = auto)");
|
||||
mToggle.Click += (_, _) =>
|
||||
{
|
||||
if (_setHp == null) return;
|
||||
var cur = rw.Data;
|
||||
if (cur.HpManual)
|
||||
{
|
||||
try { _setHp(cur.Wcid, 0); } catch { } // manual -> auto
|
||||
_lastJson = "";
|
||||
}
|
||||
DamageCommands.SetHp(cur.Wcid, 0); // manual -> auto
|
||||
else
|
||||
{
|
||||
// auto -> manual: seed with the known auto HP (if any), then open the box.
|
||||
if (cur.Hp > 0) { try { _setHp(cur.Wcid, cur.Hp); } catch { } _lastJson = ""; }
|
||||
if (cur.Hp > 0) DamageCommands.SetHp(cur.Wcid, cur.Hp);
|
||||
rw.Hp.IsReadOnly = false;
|
||||
rw.Hp.Focus();
|
||||
}
|
||||
|
|
@ -1151,12 +847,7 @@ internal static class MonsterDamagePanel
|
|||
: "Auto (best: —)";
|
||||
var choices = new List<(uint Id, string Name)> { (0u, bestLabel) };
|
||||
choices.AddRange(WeaponChoices());
|
||||
ShowPicker(weaponBtn, choices, cur.AssignedWid, id =>
|
||||
{
|
||||
if (_setWeapon != null) { try { _setWeapon(cur.Wcid, id); } catch { } }
|
||||
_lastJson = "";
|
||||
Dispatcher.UIThread.Post(Poll);
|
||||
});
|
||||
ShowPicker(weaponBtn, choices, cur.AssignedWid, id => DamageCommands.SetWeapon(cur.Wcid, id));
|
||||
};
|
||||
rw.Weapon = weaponBtn;
|
||||
g.Children.Add(weaponBtn); Grid.SetColumn(weaponBtn, 9);
|
||||
|
|
@ -1169,16 +860,35 @@ internal static class MonsterDamagePanel
|
|||
var cur = rw.Data;
|
||||
var choices = new List<(uint Id, string Name)> { (0u, "(none)") };
|
||||
choices.AddRange(WeaponChoices());
|
||||
ShowPicker(offhandBtn, choices, cur.AssignedOff, id =>
|
||||
{
|
||||
if (_setOffhand != null) { try { _setOffhand(cur.Wcid, id); } catch { } }
|
||||
_lastJson = "";
|
||||
Dispatcher.UIThread.Post(Poll);
|
||||
});
|
||||
ShowPicker(offhandBtn, choices, cur.AssignedOff, id => DamageCommands.SetOffhand(cur.Wcid, id));
|
||||
};
|
||||
rw.Offhand = offhandBtn;
|
||||
g.Children.Add(offhandBtn); Grid.SetColumn(offhandBtn, 10);
|
||||
|
||||
// Pet (col 11): which combat pet to summon for this monster. Auto = the
|
||||
// essence whose element it resists least; or an element; or a specific
|
||||
// essence from the Items panel.
|
||||
var petBtn = MakePickerButton();
|
||||
ToolTip.SetTip(petBtn, "Pet to summon for this monster. Auto = the essence element it resists least (learned resists); or pick an element or a specific essence from the Items panel.");
|
||||
petBtn.Click += (_, _) =>
|
||||
{
|
||||
var cur = rw.Data;
|
||||
var opts = PetChoices();
|
||||
var items = new List<(uint Id, string Name)>();
|
||||
uint sel = 0;
|
||||
for (int pi = 0; pi < opts.Count; pi++)
|
||||
{
|
||||
items.Add(((uint)pi, opts[pi].Name));
|
||||
if (opts[pi].Key == cur.Pet) sel = (uint)pi;
|
||||
}
|
||||
ShowPicker(petBtn, items, sel, idx =>
|
||||
{
|
||||
if (idx < opts.Count) DamageCommands.SetPet(cur.Wcid, opts[(int)idx].Key);
|
||||
});
|
||||
};
|
||||
rw.Pet = petBtn;
|
||||
g.Children.Add(petBtn); Grid.SetColumn(petBtn, 11);
|
||||
|
||||
var del = new Button
|
||||
{
|
||||
Content = "✕", FontSize = 11, Padding = new Thickness(0),
|
||||
|
|
@ -1190,17 +900,8 @@ internal static class MonsterDamagePanel
|
|||
};
|
||||
ToolTip.SetTip(del, $"Delete learned history for this row (wcid {r.Wcid}).");
|
||||
string key = r.Key;
|
||||
del.Click += (_, _) =>
|
||||
{
|
||||
if (_delRow != null && key.Length > 0)
|
||||
{
|
||||
IntPtr k = Marshal.StringToHGlobalAnsi(key);
|
||||
try { _delRow(k); } catch { } finally { Marshal.FreeHGlobal(k); }
|
||||
}
|
||||
_lastJson = "";
|
||||
Dispatcher.UIThread.Post(Poll);
|
||||
};
|
||||
g.Children.Add(del); Grid.SetColumn(del, 11);
|
||||
del.Click += (_, _) => DamageCommands.DeleteRow(key);
|
||||
g.Children.Add(del); Grid.SetColumn(del, 12);
|
||||
|
||||
rw.Data = r;
|
||||
return rw;
|
||||
|
|
@ -1255,12 +956,7 @@ internal static class MonsterDamagePanel
|
|||
var cur = rw.Data;
|
||||
var choices = new List<(uint Id, string Name)> { (0u, "Auto (learned best)") };
|
||||
choices.AddRange(WeaponChoices());
|
||||
ShowPicker(weaponBtn, choices, cur.AssignedWid, id =>
|
||||
{
|
||||
if (_setDefaultWeapon != null) { try { _setDefaultWeapon(id); } catch { } }
|
||||
_lastJson = "";
|
||||
Dispatcher.UIThread.Post(Poll);
|
||||
});
|
||||
ShowPicker(weaponBtn, choices, cur.AssignedWid, id => DamageCommands.SetDefaultWeapon(id));
|
||||
};
|
||||
rw.Weapon = weaponBtn;
|
||||
g.Children.Add(weaponBtn); Grid.SetColumn(weaponBtn, 9);
|
||||
|
|
@ -1268,7 +964,7 @@ internal static class MonsterDamagePanel
|
|||
return rw;
|
||||
}
|
||||
|
||||
private void UpdateRow(RowWidgets rw, Row r)
|
||||
private void UpdateRow(RowWidgets rw, DamageRow r)
|
||||
{
|
||||
rw.Data = r; // picker click handlers read the latest best/override from here
|
||||
if (r.IsDefault)
|
||||
|
|
@ -1288,7 +984,7 @@ internal static class MonsterDamagePanel
|
|||
rw.Chevron.Content = expanded ? "▾" : "▸";
|
||||
rw.Chevron.Foreground = HasCustomRule(r.Name) ? ManualHp : Dim;
|
||||
rw.Elem.Text = r.Elem;
|
||||
rw.Tier.Text = FormatTier(r.Tier);
|
||||
rw.Tier.Text = DamageSource.FormatTier(r.Tier);
|
||||
rw.Crit.Text = r.CritN > 0 ? r.Crit.ToString("0") : "—";
|
||||
rw.Crit.Foreground = r.CritN > 0 ? Brushes.White : Dim;
|
||||
rw.NonCrit.Text = r.NonCritN > 0 ? r.NonCrit.ToString("0") : "—";
|
||||
|
|
@ -1318,6 +1014,12 @@ internal static class MonsterDamagePanel
|
|||
rw.Offhand.Content = "(none)";
|
||||
rw.Offhand.Foreground = Dim;
|
||||
}
|
||||
// Pet: gold = chosen element/essence, dim "Auto" otherwise.
|
||||
if (rw.Pet != null)
|
||||
{
|
||||
rw.Pet.Content = Trunc(r.Pet.Length > 0 ? r.PetLabel : "Auto", 16);
|
||||
rw.Pet.Foreground = r.Pet.Length > 0 ? ManualHp : Dim;
|
||||
}
|
||||
|
||||
// Never overwrite the HP box while the user is editing it.
|
||||
if (!rw.Hp.IsFocused)
|
||||
|
|
@ -1337,11 +1039,6 @@ internal static class MonsterDamagePanel
|
|||
rw.DefaultToggle.BorderBrush = onDefault ? ToggleOn : EntryBorder;
|
||||
}
|
||||
|
||||
// Tier display: 0 = none ("—"); negative = ring spell ("R<level>"); positive = spell level.
|
||||
private static string FormatTier(int t) =>
|
||||
t == 0 ? "—" : (t < 0 ? "R" + (-t).ToString(CultureInfo.InvariantCulture)
|
||||
: t.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
private static TextBlock AddCell(Grid g, int col, string text, bool bold = false, bool trim = false, IBrush? brush = null)
|
||||
{
|
||||
var tb = new TextBlock
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@
|
|||
// the snapshot.
|
||||
//
|
||||
// Plugin exports used:
|
||||
// RynthPluginGetMonstersJson → polled every 1s for external edits
|
||||
// RynthPluginSetMonstersJson → debounced write-back on edit
|
||||
// RynthPluginGetMonstersJson → UiSources.MonsterRules (hub, pump thread; shared with Damage)
|
||||
// RynthPluginSetMonstersJson → DamageCommands.SetRulesJson (hub)
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -25,6 +25,7 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
|
|
@ -35,16 +36,8 @@ internal partial class MonstersPanelJsonContext : JsonSerializerContext { }
|
|||
|
||||
internal static class MonstersPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetMonstersJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetMonstersJsonFn(IntPtr ansiJson);
|
||||
|
||||
private static GetMonstersJsonFn? _getMonstersJson;
|
||||
private static SetMonstersJsonFn? _setMonstersJson;
|
||||
|
||||
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
|
||||
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
|
||||
|
|
@ -125,9 +118,13 @@ internal static class MonstersPanel
|
|||
public bool UseRing { get; set; }
|
||||
public bool UseStreak { get; set; }
|
||||
public bool UseBolt { get; set; } = true;
|
||||
/// <summary>Blast spells (a spread of projectiles). Off in rules saved before 2026-10-03.</summary>
|
||||
public bool UseBlast { get; set; }
|
||||
public string ExVuln { get; set; } = "None";
|
||||
public int OffhandId { get; set; }
|
||||
public string PetDamage { get; set; } = "PAuto";
|
||||
/// <summary>Debuffs the player typed in, comma separated (spell base or full names).</summary>
|
||||
public string CustomDebuffs { get; set; } = string.Empty;
|
||||
|
||||
public bool GetToggle(string field) => field switch
|
||||
{
|
||||
|
|
@ -141,6 +138,7 @@ internal static class MonstersPanel
|
|||
"UseBolt" => UseBolt,
|
||||
"UseRing" => UseRing,
|
||||
"UseStreak" => UseStreak,
|
||||
"UseBlast" => UseBlast,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
|
|
@ -158,6 +156,7 @@ internal static class MonstersPanel
|
|||
case "UseBolt": UseBolt = v; break;
|
||||
case "UseRing": UseRing = v; break;
|
||||
case "UseStreak": UseStreak = v; break;
|
||||
case "UseBlast": UseBlast = v; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -175,7 +174,6 @@ internal static class MonstersPanel
|
|||
|
||||
public static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
|
||||
var state = new State();
|
||||
|
||||
|
|
@ -424,7 +422,6 @@ internal static class MonstersPanel
|
|||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getMonstersJson == null) TryBind();
|
||||
if (state.Dirty) return; // don't clobber pending edits
|
||||
if (!TryFetch(out var fresh)) return;
|
||||
|
||||
|
|
@ -449,8 +446,17 @@ internal static class MonstersPanel
|
|||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.MonsterRules.Subscribe();
|
||||
UiSources.MonsterRules.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.MonsterRules.Unsubscribe();
|
||||
};
|
||||
|
||||
return root;
|
||||
}
|
||||
|
|
@ -957,73 +963,28 @@ internal static class MonstersPanel
|
|||
// ── Plugin export binding ───────────────────────────────────────────────
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static MonstersPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getMonstersJson = null;
|
||||
_setMonstersJson = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
if (_getMonstersJson == null)
|
||||
{
|
||||
IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetMonstersJson");
|
||||
if (p1 != IntPtr.Zero)
|
||||
_getMonstersJson = Marshal.GetDelegateForFunctionPointer<GetMonstersJsonFn>(p1);
|
||||
}
|
||||
|
||||
if (_setMonstersJson == null)
|
||||
{
|
||||
IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetMonstersJson");
|
||||
if (p2 != IntPtr.Zero)
|
||||
_setMonstersJson = Marshal.GetDelegateForFunctionPointer<SetMonstersJsonFn>(p2);
|
||||
}
|
||||
}
|
||||
// The hub version at the last save: older snapshots predate it and would
|
||||
// briefly revert the edit on screen, so they're skipped.
|
||||
private static long _savedAtVersion = -1;
|
||||
|
||||
// A private copy of the hub's latest rules (the panel edits it in place).
|
||||
private static bool TryFetch(out Payload payload)
|
||||
{
|
||||
payload = new Payload();
|
||||
if (_getMonstersJson == null) return false;
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getMonstersJson();
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return false;
|
||||
var parsed = JsonSerializer.Deserialize(json, MonstersPanelJsonContext.Default.Payload);
|
||||
if (parsed == null) return false;
|
||||
payload = parsed;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var snap = UiSources.MonsterRules.Current;
|
||||
if (snap == null || snap.Version <= _savedAtVersion) return false;
|
||||
payload = snap.Value.ParseCopy();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void PushChanges(State state)
|
||||
{
|
||||
if (_setMonstersJson == null) TryBind();
|
||||
if (_setMonstersJson == null) return;
|
||||
|
||||
IntPtr ansi = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
// Only the rules array is needed by the setter — avoids round-tripping items list.
|
||||
string json = JsonSerializer.Serialize(new Payload { Rules = state.Data.Rules }, MonstersPanelJsonContext.Default.Payload);
|
||||
ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
_setMonstersJson(ansi);
|
||||
state.Dirty = false;
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
|
||||
}
|
||||
// Only the rules array is needed by the setter; serialized here, on the
|
||||
// UI thread, because the panel keeps editing state.Data afterwards.
|
||||
string json = JsonSerializer.Serialize(new Payload { Rules = state.Data.Rules }, MonstersPanelJsonContext.Default.Payload);
|
||||
_savedAtVersion = UiSources.MonsterRules.Current?.Version ?? _savedAtVersion;
|
||||
DamageCommands.SetRulesJson(json);
|
||||
state.Dirty = false;
|
||||
}
|
||||
|
||||
private static bool CapturedEqual(Dictionary<string, CapturedInfo>? a, Dictionary<string, CapturedInfo>? b)
|
||||
|
|
@ -1056,7 +1017,8 @@ internal static class MonstersPanel
|
|||
|| x.Fester != y.Fester || x.Broadside != y.Broadside || x.GravityWell != y.GravityWell
|
||||
|| x.Imperil != y.Imperil || x.Yield != y.Yield || x.Vuln != y.Vuln
|
||||
|| x.UseArc != y.UseArc || x.UseBolt != y.UseBolt
|
||||
|| x.UseRing != y.UseRing || x.UseStreak != y.UseStreak)
|
||||
|| x.UseRing != y.UseRing || x.UseStreak != y.UseStreak || x.UseBlast != y.UseBlast
|
||||
|| (x.CustomDebuffs ?? "") != (y.CustomDebuffs ?? ""))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@
|
|||
// RynthCore.Engine — UI/Panels/NavPanel.cs
|
||||
// Avalonia replica of LegacyNavigationUi.cs (RynthSuite plugin).
|
||||
//
|
||||
// Plugin exports used:
|
||||
// RynthPluginGetNavJson → polled every 1s for live state
|
||||
// RynthPluginSendNavCommand → dispatched on button actions
|
||||
// Data goes through UiDataHub (UI/Data/NavData.cs): UiSources.Nav polls
|
||||
// RynthPluginGetNavJson on the pump thread and NavCommands sends
|
||||
// RynthPluginSendNavCommand there; the ImGui face (ImGui/Panels/NavFace.cs)
|
||||
// reads the same snapshot.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -19,29 +20,13 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using Payload = RynthCore.Engine.UI.Data.NavPayload;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
[JsonSerializable(typeof(NavPanel.Payload))]
|
||||
[JsonSerializable(typeof(NavPanel.NavCmd))]
|
||||
[JsonSerializable(typeof(List<NavPanel.NavPoint>))]
|
||||
[JsonSerializable(typeof(List<string>), TypeInfoPropertyName = "StringList")]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
|
||||
internal partial class NavPanelJsonContext : JsonSerializerContext { }
|
||||
|
||||
internal static class NavPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetNavJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SendNavCommandFn(IntPtr ansiJson);
|
||||
|
||||
private static GetNavJsonFn? _getNavJson;
|
||||
private static SendNavCommandFn? _sendNavCommand;
|
||||
|
||||
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
|
||||
private static readonly IBrush ColGreen = new SolidColorBrush(Color.FromRgb(0x33, 0xCC, 0x66));
|
||||
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
|
||||
|
|
@ -56,62 +41,20 @@ internal static class NavPanel
|
|||
private static readonly IBrush ColStartBg = new SolidColorBrush(Color.FromRgb(0x19, 0x61, 0x19));
|
||||
private static readonly IBrush ColStopBg = new SolidColorBrush(Color.FromRgb(0x80, 0x19, 0x19));
|
||||
|
||||
private static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" };
|
||||
private static readonly string[] AddModes = { "End", "Above", "Below" };
|
||||
private static readonly string[] RouteTypes = NavCommands.RouteTypes;
|
||||
private static readonly string[] AddModes = NavCommands.AddModes;
|
||||
|
||||
private static readonly int[] RecallIds =
|
||||
{
|
||||
48, 2645, 2647,
|
||||
1635, 1636,
|
||||
157, 158, 1637,
|
||||
2648, 2649, 2650,
|
||||
2931, 2023, 2041, 2358, 2813, 2941, 2943,
|
||||
3865, 3929, 3930, 4084, 4198, 4213,
|
||||
4907, 4908, 4909,
|
||||
5175, 5330, 5541, 6150, 6321, 6322,
|
||||
};
|
||||
|
||||
// ── Data types (mirror NavBridgePayload / NavCommand on plugin side) ──────
|
||||
|
||||
internal sealed class NavPoint
|
||||
{
|
||||
public int Idx { get; set; }
|
||||
public string Type { get; set; } = string.Empty;
|
||||
public string Desc { get; set; } = string.Empty;
|
||||
public double NS { get; set; }
|
||||
public double EW { get; set; }
|
||||
public double Z { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class Payload
|
||||
{
|
||||
public string ActiveNavName { get; set; } = string.Empty;
|
||||
public string NavStatusLine { get; set; } = string.Empty;
|
||||
public bool NavIsStuck { get; set; }
|
||||
public bool MacroRunning { get; set; }
|
||||
public bool NavigationEnabled { get; set; }
|
||||
public int RouteType { get; set; }
|
||||
public int ActiveNavIndex { get; set; }
|
||||
public List<string> NavFiles { get; set; } = new();
|
||||
public List<NavPoint> Points { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class NavCmd
|
||||
{
|
||||
public string Cmd { get; set; } = string.Empty;
|
||||
public int SpellId { get; set; }
|
||||
public int Index { get; set; }
|
||||
public int RouteType { get; set; }
|
||||
public int AddMode { get; set; }
|
||||
public int InsertAt { get; set; } = -1;
|
||||
public string NavName { get; set; } = string.Empty;
|
||||
}
|
||||
private static readonly int[] RecallIds = NavCommands.RecallIds;
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
public Payload Data = new();
|
||||
public int SelectedIdx = -1;
|
||||
public int AddModeIdx = 0;
|
||||
public string SaveName = string.Empty;
|
||||
public string ChatText = string.Empty;
|
||||
public int ChatFor = -1; // waypoint whose command is in ChatText
|
||||
public bool Typing; // name box focused: the poll must not rebuild it away
|
||||
}
|
||||
|
||||
// ── Picker overlay (identical pattern to SettingsPanel) ──────────────────
|
||||
|
|
@ -195,7 +138,6 @@ internal static class NavPanel
|
|||
|
||||
public static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
var state = new State();
|
||||
|
||||
var root = new Border
|
||||
|
|
@ -341,7 +283,7 @@ internal static class NavPanel
|
|||
var addRecallBtn = MakeActionBtn("Add Recall");
|
||||
var recallLabels = new string[RecallIds.Length];
|
||||
for (int ri = 0; ri < RecallIds.Length; ri++)
|
||||
recallLabels[ri] = $"Spell {RecallIds[ri]} ({RecallIds[ri]})";
|
||||
recallLabels[ri] = NavCommands.RecallLabels[ri];
|
||||
addRecallBtn.Click += (_, _) =>
|
||||
picker.Show(addRecallBtn, recallLabels, -1, idx =>
|
||||
Send(new NavCmd { Cmd = "addRecall", SpellId = RecallIds[idx], AddMode = state.AddModeIdx, InsertAt = state.SelectedIdx }));
|
||||
|
|
@ -367,6 +309,100 @@ internal static class NavPanel
|
|||
|
||||
content.Children.Add(actionWrap);
|
||||
|
||||
// ── Chat waypoint ─────────────────────────────────────────────────
|
||||
// Sent as if typed when the route reaches it: /ra, /ub, /mt commands,
|
||||
// game commands, or plain text to say. Placed per the Add mode.
|
||||
// Selecting an existing chat waypoint loads its command; Update saves the edit.
|
||||
bool chatSelected = state.SelectedIdx >= 0 && state.SelectedIdx < d.Points.Count
|
||||
&& d.Points[state.SelectedIdx].Type == "Chat";
|
||||
if (state.SelectedIdx != state.ChatFor)
|
||||
{
|
||||
if (chatSelected) state.ChatText = d.Points[state.SelectedIdx].Text;
|
||||
else if (state.ChatFor >= 0) state.ChatText = string.Empty;
|
||||
state.ChatFor = chatSelected ? state.SelectedIdx : -1;
|
||||
}
|
||||
var chatRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") };
|
||||
var chatBox = new TextBox
|
||||
{
|
||||
Text = state.ChatText, Watermark = "Chat command, e.g. /ub usei Healing Kit",
|
||||
Background = ColBtnFill, Foreground = ColTextDim,
|
||||
BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
|
||||
FontSize = 10, Height = 22, Padding = new Thickness(4, 1),
|
||||
Margin = new Thickness(0, 0, 4, 0),
|
||||
};
|
||||
chatBox.TextChanged += (_, _) => state.ChatText = chatBox.Text ?? string.Empty;
|
||||
chatBox.GotFocus += (_, _) => state.Typing = true;
|
||||
chatBox.LostFocus += (_, _) => state.Typing = false;
|
||||
var addChatBtn = MakeActionBtn("Add Chat");
|
||||
var updChatBtn = MakeActionBtn("Update");
|
||||
updChatBtn.IsVisible = chatSelected;
|
||||
void AddChat()
|
||||
{
|
||||
string text = state.ChatText.Trim();
|
||||
if (text.Length == 0) return;
|
||||
Send(new NavCmd { Cmd = "addChat", Text = text, AddMode = state.AddModeIdx, InsertAt = state.SelectedIdx });
|
||||
state.ChatText = string.Empty;
|
||||
state.ChatFor = -1;
|
||||
state.Typing = false;
|
||||
Rebuild();
|
||||
}
|
||||
void UpdateChat()
|
||||
{
|
||||
string text = state.ChatText.Trim();
|
||||
if (text.Length == 0 || !chatSelected) return;
|
||||
Send(new NavCmd { Cmd = "editChat", Index = state.SelectedIdx, Text = text });
|
||||
state.Typing = false;
|
||||
Rebuild();
|
||||
}
|
||||
addChatBtn.Click += (_, _) => AddChat();
|
||||
updChatBtn.Click += (_, _) => UpdateChat();
|
||||
chatBox.KeyDown += (_, e) =>
|
||||
{
|
||||
if (e.Key != Avalonia.Input.Key.Enter) return;
|
||||
e.Handled = true;
|
||||
if (chatSelected) UpdateChat(); else AddChat();
|
||||
};
|
||||
Grid.SetColumn(chatBox, 0);
|
||||
Grid.SetColumn(updChatBtn, 1);
|
||||
Grid.SetColumn(addChatBtn, 2);
|
||||
chatRow.Children.Add(chatBox);
|
||||
chatRow.Children.Add(updChatBtn);
|
||||
chatRow.Children.Add(addChatBtn);
|
||||
content.Children.Add(chatRow);
|
||||
|
||||
// ── Save as a named nav ───────────────────────────────────────────
|
||||
// Save Route writes the current file; a route with no file got
|
||||
// nowhere to go and there was no way to name one.
|
||||
var saveAsRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
var nameBox = new TextBox
|
||||
{
|
||||
Text = state.SaveName, Watermark = "Nav name...",
|
||||
Background = ColBtnFill, Foreground = ColTextDim,
|
||||
BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
|
||||
FontSize = 10, Height = 22, Padding = new Thickness(4, 1),
|
||||
Margin = new Thickness(0, 0, 4, 0),
|
||||
};
|
||||
nameBox.TextChanged += (_, _) => state.SaveName = nameBox.Text ?? string.Empty;
|
||||
nameBox.GotFocus += (_, _) => state.Typing = true;
|
||||
nameBox.LostFocus += (_, _) => state.Typing = false;
|
||||
var saveAsBtn = MakeActionBtn("Save As");
|
||||
void SaveAs()
|
||||
{
|
||||
string name = state.SaveName.Trim();
|
||||
if (name.Length == 0) return;
|
||||
Send(new NavCmd { Cmd = "saveRoute", NavName = name });
|
||||
state.SaveName = string.Empty;
|
||||
state.Typing = false;
|
||||
Rebuild();
|
||||
}
|
||||
saveAsBtn.Click += (_, _) => SaveAs();
|
||||
nameBox.KeyDown += (_, e) => { if (e.Key == Avalonia.Input.Key.Enter) { e.Handled = true; SaveAs(); } };
|
||||
Grid.SetColumn(nameBox, 0);
|
||||
Grid.SetColumn(saveAsBtn, 1);
|
||||
saveAsRow.Children.Add(nameBox);
|
||||
saveAsRow.Children.Add(saveAsBtn);
|
||||
content.Children.Add(saveAsRow);
|
||||
|
||||
// ── Nav file selector ─────────────────────────────────────────────
|
||||
if (d.NavFiles.Count > 0)
|
||||
{
|
||||
|
|
@ -457,9 +493,7 @@ internal static class NavPanel
|
|||
Grid.SetColumn(indicator, 1);
|
||||
row.Children.Add(indicator);
|
||||
|
||||
string disp = !string.IsNullOrEmpty(pt.Desc)
|
||||
? $"[{i}] {pt.Desc}"
|
||||
: $"[{i}] {pt.Type} ({pt.NS:F2}N, {pt.EW:F2}E, {pt.Z:F1})";
|
||||
string disp = NavCommands.PointText(pt, i);
|
||||
var desc = new TextBlock
|
||||
{
|
||||
Text = disp,
|
||||
|
|
@ -495,21 +529,33 @@ internal static class NavPanel
|
|||
}
|
||||
|
||||
// ── Poll timer ────────────────────────────────────────────────────────
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
// Reads the hub's snapshot (fetched every 1 s while subscribed, and
|
||||
// right after each command).
|
||||
long seenVersion = -1;
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getNavJson == null) TryBind();
|
||||
if (picker.ActivePicker != null) return;
|
||||
if (!TryFetch(out var fresh)) return;
|
||||
state.Data = fresh;
|
||||
if (picker.ActivePicker != null || state.Typing) return;
|
||||
var snap = UiSources.Nav.Current;
|
||||
if (snap == null || snap.Version == seenVersion) return;
|
||||
seenVersion = snap.Version;
|
||||
state.Data = snap.Value.Clone();
|
||||
Rebuild();
|
||||
};
|
||||
timer.Start();
|
||||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Nav.Subscribe();
|
||||
UiSources.Nav.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Nav.Unsubscribe();
|
||||
};
|
||||
|
||||
Rebuild();
|
||||
return root;
|
||||
|
|
@ -548,71 +594,5 @@ internal static class NavPanel
|
|||
Margin = new Thickness(0, 0, 4, 4),
|
||||
};
|
||||
|
||||
// =========================================================================
|
||||
// Plugin bridge
|
||||
// =========================================================================
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static NavPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getNavJson = null;
|
||||
_sendNavCommand = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
if (_getNavJson == null)
|
||||
{
|
||||
IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetNavJson");
|
||||
if (p1 != IntPtr.Zero)
|
||||
_getNavJson = Marshal.GetDelegateForFunctionPointer<GetNavJsonFn>(p1);
|
||||
}
|
||||
if (_sendNavCommand == null)
|
||||
{
|
||||
IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSendNavCommand");
|
||||
if (p2 != IntPtr.Zero)
|
||||
_sendNavCommand = Marshal.GetDelegateForFunctionPointer<SendNavCommandFn>(p2);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryFetch(out Payload payload)
|
||||
{
|
||||
payload = new Payload();
|
||||
if (_getNavJson == null) return false;
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getNavJson();
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return false;
|
||||
var parsed = JsonSerializer.Deserialize(json, NavPanelJsonContext.Default.Payload);
|
||||
if (parsed == null) return false;
|
||||
payload = parsed;
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private static void Send(NavCmd cmd)
|
||||
{
|
||||
if (_sendNavCommand == null) TryBind();
|
||||
if (_sendNavCommand == null) return;
|
||||
IntPtr ansi = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
string json = JsonSerializer.Serialize(cmd, NavPanelJsonContext.Default.NavCmd);
|
||||
ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
_sendNavCommand(ansi);
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
|
||||
}
|
||||
}
|
||||
private static void Send(NavCmd cmd) => NavCommands.Send(cmd);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@
|
|||
// RynthCore.Engine — UI/Panels/RadarPanel.cs
|
||||
// Avalonia replica of the ImGui RynthRadar (RynthRadarUi.cs).
|
||||
//
|
||||
// Renders the same view, fed by the plugin's RynthPluginGetRadarSnapshot
|
||||
// export. Geometry is cached by MapVersion (= landblock); per-frame data
|
||||
// (player pose, visited overlay, markers) refreshes every 100 ms.
|
||||
// Renders the same view from UiDataHub's radar view (UiSources.Radar,
|
||||
// UI/Data/RadarData.cs), which calls RynthPluginGetRadarSnapshot on the pump
|
||||
// thread and keeps the per-landblock geometry cache. The ImGui face
|
||||
// (ImGui/Panels/RadarFace.cs) draws the same view.
|
||||
//
|
||||
// Render order matches the ImGui original:
|
||||
// 1. Frame outer/inner/accent + canvas bg
|
||||
|
|
@ -38,6 +39,7 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
|
|
@ -60,6 +62,76 @@ internal static class RadarSettingsStore
|
|||
public static bool ShowNpcs = true;
|
||||
public static bool ShowPortals = true;
|
||||
public static bool ShowDoors = true;
|
||||
// Kinds added 2026-10-04 (RadarKind 4..11). Items on the ground start hidden: noisy.
|
||||
public static bool ShowPlayers = true;
|
||||
public static bool ShowFellows = true;
|
||||
public static bool ShowPets = true;
|
||||
public static bool ShowVendors = true;
|
||||
public static bool ShowCorpses = true;
|
||||
public static bool ShowOwnCorpses = true;
|
||||
public static bool ShowLifestones = true;
|
||||
public static bool ShowGroundItems = false;
|
||||
/// <summary>ImGui face: a left-click on a dot selects that object in game.</summary>
|
||||
public static bool ClickToSelect = true;
|
||||
|
||||
/// <summary>
|
||||
/// Default marker colour per <see cref="RadarKind"/> (ARGB). Chosen to stay apart for
|
||||
/// red-green colour blindness as well: the kinds that share a hue family also differ
|
||||
/// in shape (see RadarMarkerStyle) or brightness.
|
||||
/// </summary>
|
||||
public static readonly uint[] DefaultKindColors =
|
||||
{
|
||||
0xFFFF3333, // monster: red
|
||||
0xFFFFD933, // NPC: yellow
|
||||
0xFFBF4DFF, // portal: purple
|
||||
0xFFFF8C1A, // door: orange
|
||||
0xFF33C7FF, // player: cyan-blue
|
||||
0xFF4DE673, // fellow: green
|
||||
0xFF26BFA6, // your pet: teal
|
||||
0xFFFFB31A, // vendor: gold
|
||||
0xFF8C9399, // corpse: grey
|
||||
0xFFF2F2F2, // your corpse: near white
|
||||
0xFF99D1FF, // lifestone: light blue
|
||||
0xFFD9C78C, // item on the ground: pale tan
|
||||
};
|
||||
|
||||
/// <summary>Marker colour per <see cref="RadarKind"/> (ARGB); the user's picks, else the defaults.</summary>
|
||||
public static readonly uint[] KindColors = (uint[])DefaultKindColors.Clone();
|
||||
|
||||
// Settings-file keys per kind (color.<key>=AARRGGBB).
|
||||
private static readonly string[] KindKeys =
|
||||
{
|
||||
"monster", "npc", "portal", "door", "player", "fellow",
|
||||
"pet", "vendor", "corpse", "ownCorpse", "lifestone", "groundItem",
|
||||
};
|
||||
|
||||
/// <summary>The show/hide flag of a kind (the radar's per-kind check boxes).</summary>
|
||||
public static ref bool ShowFlag(byte kind)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case RadarKind.Monster: return ref ShowMonsters;
|
||||
case RadarKind.Npc: return ref ShowNpcs;
|
||||
case RadarKind.Portal: return ref ShowPortals;
|
||||
case RadarKind.Door: return ref ShowDoors;
|
||||
case RadarKind.Player: return ref ShowPlayers;
|
||||
case RadarKind.Fellow: return ref ShowFellows;
|
||||
case RadarKind.Pet: return ref ShowPets;
|
||||
case RadarKind.Vendor: return ref ShowVendors;
|
||||
case RadarKind.Corpse: return ref ShowCorpses;
|
||||
case RadarKind.OwnCorpse: return ref ShowOwnCorpses;
|
||||
case RadarKind.Lifestone: return ref ShowLifestones;
|
||||
default: return ref ShowGroundItems;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether markers of this kind are drawn; false for kinds this engine doesn't know.</summary>
|
||||
public static bool ShowKind(byte kind) => kind < RadarKind.Count && ShowFlag(kind);
|
||||
|
||||
/// <summary>The kind's colour (ARGB); white for a kind this engine doesn't know.</summary>
|
||||
public static uint KindColor(byte kind) => kind < KindColors.Length ? KindColors[kind] : 0xFFFFFFFF;
|
||||
|
||||
public static void ResetKindColors() => Array.Copy(DefaultKindColors, KindColors, KindColors.Length);
|
||||
|
||||
private static string FilePath
|
||||
{
|
||||
|
|
@ -105,6 +177,23 @@ internal static class RadarSettingsStore
|
|||
case "showNpcs": ShowNpcs = val == "1"; break;
|
||||
case "showPortals": ShowPortals = val == "1"; break;
|
||||
case "showDoors": ShowDoors = val == "1"; break;
|
||||
case "showPlayers": ShowPlayers = val == "1"; break;
|
||||
case "showFellows": ShowFellows = val == "1"; break;
|
||||
case "showPets": ShowPets = val == "1"; break;
|
||||
case "showVendors": ShowVendors = val == "1"; break;
|
||||
case "showCorpses": ShowCorpses = val == "1"; break;
|
||||
case "showOwnCorpses": ShowOwnCorpses = val == "1"; break;
|
||||
case "showLifestones": ShowLifestones = val == "1"; break;
|
||||
case "showGroundItems": ShowGroundItems = val == "1"; break;
|
||||
case "clickSelect": ClickToSelect = val == "1"; break;
|
||||
default:
|
||||
if (key.StartsWith("color.", StringComparison.Ordinal))
|
||||
{
|
||||
int k = Array.IndexOf(KindKeys, key["color.".Length..]);
|
||||
if (k >= 0 && uint.TryParse(val, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint argb))
|
||||
KindColors[k] = argb;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -112,7 +201,10 @@ internal static class RadarSettingsStore
|
|||
}
|
||||
}
|
||||
|
||||
public static void Save()
|
||||
/// <summary>Writes the settings in the background (callers include AC's render thread).</summary>
|
||||
public static void Save() => UiBackgroundWriter.Enqueue("radar settings", SaveNow);
|
||||
|
||||
private static void SaveNow()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
|
|
@ -132,6 +224,19 @@ internal static class RadarSettingsStore
|
|||
sw.WriteLine($"showNpcs={(ShowNpcs ? "1" : "0")}");
|
||||
sw.WriteLine($"showPortals={(ShowPortals ? "1" : "0")}");
|
||||
sw.WriteLine($"showDoors={(ShowDoors ? "1" : "0")}");
|
||||
sw.WriteLine($"showPlayers={(ShowPlayers ? "1" : "0")}");
|
||||
sw.WriteLine($"showFellows={(ShowFellows ? "1" : "0")}");
|
||||
sw.WriteLine($"showPets={(ShowPets ? "1" : "0")}");
|
||||
sw.WriteLine($"showVendors={(ShowVendors ? "1" : "0")}");
|
||||
sw.WriteLine($"showCorpses={(ShowCorpses ? "1" : "0")}");
|
||||
sw.WriteLine($"showOwnCorpses={(ShowOwnCorpses ? "1" : "0")}");
|
||||
sw.WriteLine($"showLifestones={(ShowLifestones ? "1" : "0")}");
|
||||
sw.WriteLine($"showGroundItems={(ShowGroundItems ? "1" : "0")}");
|
||||
sw.WriteLine($"clickSelect={(ClickToSelect ? "1" : "0")}");
|
||||
// Only colours that differ from the default, so a later default change still lands.
|
||||
for (int k = 0; k < KindColors.Length; k++)
|
||||
if (KindColors[k] != DefaultKindColors[k])
|
||||
sw.WriteLine(FormattableString.Invariant($"color.{KindKeys[k]}={KindColors[k]:X8}"));
|
||||
}
|
||||
catch { /* non-fatal */ }
|
||||
}
|
||||
|
|
@ -140,14 +245,6 @@ internal static class RadarSettingsStore
|
|||
|
||||
internal static partial class RadarPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetRadarSnapshotFn(uint mapVersion);
|
||||
|
||||
private static GetRadarSnapshotFn? _getRadarSnapshot;
|
||||
|
||||
// ── Chrome-less integration hooks ───────────────────────────────────────
|
||||
// The radar lives inside the panel system but visually has no window
|
||||
// chrome — just the gold-bordered square + coords below. The overlay
|
||||
|
|
@ -231,81 +328,19 @@ internal static partial class RadarPanel
|
|||
private static readonly IBrush ColDoor = new SolidColorBrush(Color.FromRgb(0xFF, 0x8C, 0x1A));
|
||||
private static readonly IBrush ColDoorEdge = new SolidColorBrush(Color.FromRgb(0x66, 0x33, 0x00));
|
||||
|
||||
// ── Snapshot DTO (mirrors RynthCore.Plugin.RynthAi.LegacyUi.RadarSnapshotPayload) ──
|
||||
public sealed class Snapshot
|
||||
{
|
||||
[JsonPropertyName("mapVersion")] public uint MapVersion { get; set; }
|
||||
[JsonPropertyName("geometryIncluded")] public bool GeometryIncluded { get; set; }
|
||||
[JsonPropertyName("isIndoor")] public bool IsIndoor { get; set; }
|
||||
[JsonPropertyName("player")] public PlayerInfo Player { get; set; } = new();
|
||||
[JsonPropertyName("ns")] public double Ns { get; set; } = double.NaN;
|
||||
[JsonPropertyName("ew")] public double Ew { get; set; } = double.NaN;
|
||||
[JsonPropertyName("layerZs")] public List<float> LayerZs { get; set; } = new();
|
||||
[JsonPropertyName("currentLayerZ")] public float CurrentLayerZ { get; set; }
|
||||
[JsonPropertyName("walls")] public List<WallLayer> Walls { get; set; } = new();
|
||||
[JsonPropertyName("fills")] public List<FillLayer> Fills { get; set; } = new();
|
||||
[JsonPropertyName("visited")] public List<VisitedLayer> Visited { get; set; } = new();
|
||||
[JsonPropertyName("markers")] public List<Marker> Markers { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class PlayerInfo
|
||||
{
|
||||
[JsonPropertyName("cellId")] public uint CellId { get; set; }
|
||||
[JsonPropertyName("landblock")] public uint Landblock { get; set; }
|
||||
[JsonPropertyName("x")] public float X { get; set; }
|
||||
[JsonPropertyName("y")] public float Y { get; set; }
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("worldX")] public float WorldX { get; set; }
|
||||
[JsonPropertyName("worldY")] public float WorldY { get; set; }
|
||||
[JsonPropertyName("heading")] public float Heading { get; set; }
|
||||
}
|
||||
|
||||
public sealed class WallLayer
|
||||
{
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("segments")] public float[] Segments { get; set; } = Array.Empty<float>();
|
||||
}
|
||||
|
||||
public sealed class FillLayer
|
||||
{
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
|
||||
}
|
||||
|
||||
public sealed class VisitedLayer
|
||||
{
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
|
||||
}
|
||||
|
||||
public sealed class Marker
|
||||
{
|
||||
[JsonPropertyName("kind")] public byte Kind { get; set; }
|
||||
[JsonPropertyName("x")] public float X { get; set; }
|
||||
[JsonPropertyName("y")] public float Y { get; set; }
|
||||
[JsonPropertyName("z")] public float Z { get; set; }
|
||||
[JsonPropertyName("label")] public string? Label { get; set; }
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(Snapshot))]
|
||||
[JsonSourceGenerationOptions(WriteIndented = false)]
|
||||
internal partial class RadarJsonContext : JsonSerializerContext { }
|
||||
|
||||
// ── Per-instance state, captured by the surface control ────────────────
|
||||
private sealed class State
|
||||
{
|
||||
// Live data (refreshed every poll).
|
||||
public Snapshot Live = new();
|
||||
public RadarSnapshot Live = new();
|
||||
|
||||
// Cached geometry, indexed by MapVersion. Walls/fills don't change
|
||||
// until the player crosses landblocks — store and reuse.
|
||||
public uint CachedMapVersion;
|
||||
public List<WallLayer> CachedWalls = new();
|
||||
public List<FillLayer> CachedFills = new();
|
||||
// Geometry cached per landblock by the hub (RadarSource).
|
||||
public List<RadarWallLayer> CachedWalls = new();
|
||||
public List<RadarFillLayer> CachedFills = new();
|
||||
|
||||
// UI deep-dive finding P1-A (2026-07-02): last raw snapshot JSON,
|
||||
// used to gate InvalidateVisual — see the timer tick below.
|
||||
public string? LastRawJson;
|
||||
// Hub view version last drawn; gates InvalidateVisual (UI deep-dive
|
||||
// finding P1-A: don't re-raster when nothing moved).
|
||||
public long SeenVersion = -1;
|
||||
|
||||
// User-controlled settings — driven by the gear popup. Loaded from
|
||||
// RadarSettingsStore on construction; Persist() writes back.
|
||||
|
|
@ -359,7 +394,6 @@ internal static partial class RadarPanel
|
|||
|
||||
public static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
State state = _persistentState ??= new State();
|
||||
|
||||
var surface = new RadarSurface(state);
|
||||
|
|
@ -600,38 +634,14 @@ internal static partial class RadarPanel
|
|||
// re-rastered at 30Hz for no visible change. Track whether
|
||||
// anything actually changed this tick and skip the whole
|
||||
// refresh+invalidate when it didn't.
|
||||
bool fetched = TryFetch(state.CachedMapVersion, out Snapshot? fresh, out string? rawJson);
|
||||
bool contentChanged = fetched && rawJson != null && rawJson != state.LastRawJson;
|
||||
if (fetched && rawJson != null) state.LastRawJson = rawJson;
|
||||
|
||||
if (fetched && fresh != null)
|
||||
var current = UiSources.Radar.Current;
|
||||
bool contentChanged = current != null && current.Version != state.SeenVersion;
|
||||
if (contentChanged)
|
||||
{
|
||||
state.Live = fresh;
|
||||
if (fresh.GeometryIncluded)
|
||||
{
|
||||
state.CachedMapVersion = fresh.MapVersion;
|
||||
state.CachedWalls = fresh.Walls;
|
||||
state.CachedFills = fresh.Fills;
|
||||
}
|
||||
else if (fresh.MapVersion != state.CachedMapVersion && fresh.MapVersion != 0 && !fresh.IsIndoor)
|
||||
{
|
||||
// Outdoor landblocks: no geometry sent, but version still
|
||||
// tracks landblock — clear stale walls so they don't bleed
|
||||
// through when transitioning indoor→outdoor.
|
||||
state.CachedMapVersion = fresh.MapVersion;
|
||||
state.CachedWalls = new List<WallLayer>();
|
||||
state.CachedFills = new List<FillLayer>();
|
||||
}
|
||||
|
||||
// First poll after login can land before raycast is ready, so
|
||||
// the plugin returns an indoor snapshot with empty walls. Once
|
||||
// raycast comes online, we have to re-ask with version=0 or
|
||||
// the plugin sees a matching version and skips the geometry
|
||||
// payload — leaving the radar permanently blank until the
|
||||
// user manually closes/reopens it. Force a re-fetch next tick
|
||||
// whenever we're indoors but lack walls.
|
||||
if (state.Live.IsIndoor && state.CachedWalls.Count == 0)
|
||||
state.CachedMapVersion = 0;
|
||||
state.SeenVersion = current!.Version;
|
||||
state.Live = current.Value.Live;
|
||||
state.CachedWalls = current.Value.Walls;
|
||||
state.CachedFills = current.Value.Fills;
|
||||
}
|
||||
// Sync overlay button visibility with current pop-out state.
|
||||
// docked → [↗ popout, ⚙ gear]
|
||||
|
|
@ -659,9 +669,19 @@ internal static partial class RadarPanel
|
|||
MarkDirty?.Invoke();
|
||||
}
|
||||
};
|
||||
timer.Start();
|
||||
surface.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
surface.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
// The hub polls the plugin only while some radar face is subscribed.
|
||||
surface.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Radar.Subscribe();
|
||||
UiSources.Radar.RequestRefresh();
|
||||
state.SeenVersion = -1;
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
surface.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Radar.Unsubscribe();
|
||||
};
|
||||
|
||||
return radarGrid;
|
||||
}
|
||||
|
|
@ -1304,7 +1324,7 @@ internal static partial class RadarPanel
|
|||
}
|
||||
private static float AlphaToFloat(byte a) => a == 0 ? 1f : a / 255f;
|
||||
|
||||
private static string FormatCoords(Snapshot s)
|
||||
private static string FormatCoords(RadarSnapshot s)
|
||||
{
|
||||
// Match the ImGui radar's footer behaviour exactly:
|
||||
// indoor → "LB AABB Z 12.3" (landblock id, no NS/EW)
|
||||
|
|
@ -1318,46 +1338,4 @@ internal static partial class RadarPanel
|
|||
|
||||
return $"Z {p.Z:0.0}";
|
||||
}
|
||||
|
||||
// ── Plugin export binding ───────────────────────────────────────────────
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static RadarPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getRadarSnapshot = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
if (_getRadarSnapshot != null) return;
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetRadarSnapshot");
|
||||
if (p1 != IntPtr.Zero)
|
||||
_getRadarSnapshot = Marshal.GetDelegateForFunctionPointer<GetRadarSnapshotFn>(p1);
|
||||
}
|
||||
|
||||
private static bool TryFetch(uint engineKnownVersion, out Snapshot? snapshot, out string? rawJson)
|
||||
{
|
||||
snapshot = null;
|
||||
rawJson = null;
|
||||
if (_getRadarSnapshot == null) TryBind();
|
||||
if (_getRadarSnapshot == null) return false;
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getRadarSnapshot(engineKnownVersion);
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json) || json == "{}") return false;
|
||||
snapshot = JsonSerializer.Deserialize(json, RadarJsonContext.Default.Snapshot);
|
||||
rawJson = json;
|
||||
return snapshot != null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,16 +12,12 @@
|
|||
// • Launcher grid: 3 cols × 2-3 rows of GridBtns (visual only — opens
|
||||
// no sub-windows yet; main-dashboard scope only).
|
||||
//
|
||||
// Live data comes from the RynthAi plugin via these C exports:
|
||||
// RynthPluginGetSnapshotJson → JSON blob (polled every 33 ms)
|
||||
// RynthPluginToggleMacro → flip IsMacroRunning
|
||||
// RynthPluginSetSubsystemEnabled(id) → 0=Combat 1=Buff 2=Nav 3=Loot 4=Meta
|
||||
// RynthPluginSelectProfile(kind, i) → 0=nav 1=loot 2=meta 3=profile
|
||||
// RynthPluginForceRebuff → buff manager force rebuff
|
||||
// RynthPluginCancelForceRebuff → cancel pending FR
|
||||
// RynthPluginAdjustOpacity(delta) → header +/- chips (mirrored)
|
||||
// RynthPluginTogglePanelLock → Lock chip (mirrored)
|
||||
// RynthPluginTogglePanelMinimize → _ chip (mirrored)
|
||||
// Live data comes from UiDataHub (UiSources.RynthAi / UiSources.Patrol,
|
||||
// UI/Data/RynthAiData.cs), which calls the plugin's exports on the pump
|
||||
// thread; clicks go through RynthAiCommands. This face never calls a
|
||||
// plugin export itself (they used to run on the Avalonia thread, racing the
|
||||
// plugin tick). The ImGui face (ImGui/Panels/RynthAiFace.cs) reads the same
|
||||
// view.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -39,27 +35,12 @@ using Avalonia.Layout;
|
|||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static partial class RynthAiPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetSnapshotJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void VoidFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void IntFn(int arg);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void IntIntFn(int a, int b);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void FloatFn(float arg);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void PtrFn(IntPtr arg);
|
||||
|
||||
// ── Color palette — exact match to LegacyDashboardRenderer ImGui Vector4
|
||||
// floats (multiplied by 255 and rounded). Don't deepen these; the ImGui
|
||||
// contrast is what makes the dashboard read crisp against AC scenes.
|
||||
|
|
@ -110,19 +91,6 @@ internal static partial class RynthAiPanel
|
|||
// FR button: (0.28,0.20,0.04).
|
||||
private static readonly IBrush ColFrFill = new SolidColorBrush(Color.FromRgb(0x47, 0x33, 0x0A));
|
||||
|
||||
private static GetSnapshotJsonFn? _getSnapshotJson;
|
||||
private static VoidFn? _toggleMacro;
|
||||
private static IntIntFn? _setSubsystemEnabled;
|
||||
private static IntIntFn? _selectProfile;
|
||||
private static VoidFn? _forceRebuff;
|
||||
private static VoidFn? _cancelForceRebuff;
|
||||
private static FloatFn? _adjustOpacity;
|
||||
private static VoidFn? _togglePanelLock;
|
||||
private static VoidFn? _togglePanelMinimize;
|
||||
private static PtrFn? _sendNavCommand;
|
||||
private static GetSnapshotJsonFn? _getPatrolInfoJson;
|
||||
private static bool _bindingLogged;
|
||||
|
||||
/// <summary>
|
||||
/// Set by AvaloniaOverlay.TogglePanel before invoking the factory. The
|
||||
/// panel calls this with its in-panel title-row Border so the wrapping
|
||||
|
|
@ -167,122 +135,21 @@ internal static partial class RynthAiPanel
|
|||
private const double MinimizedHeightPreset = 110;
|
||||
private const double MinimizedMinHeightFloor = 46;
|
||||
|
||||
// Last-known good vitals — persists across panel recreates AND across
|
||||
// engine hot-reloads (saved to disk). After a reload the plugin's vital
|
||||
// cache is cold for a tick or two; without this the panel shows 0/0,
|
||||
// which the user sees as the bars wiping. Updated only when the snapshot
|
||||
// gives us a real (non-zero max) reading.
|
||||
private static uint _cachedHp, _cachedMaxHp;
|
||||
private static uint _cachedSt, _cachedMaxSt;
|
||||
private static uint _cachedMn, _cachedMaxMn;
|
||||
private static bool _vitalCacheLoaded;
|
||||
private static long _vitalCacheLastSavedTick;
|
||||
// The minimized state lives in UI/RynthAiDashboardState.cs, not here:
|
||||
// engine init reads it before the overlay starts, and touching this class
|
||||
// then would run its static brushes on the wrong thread.
|
||||
|
||||
// Avalonia panel's OWN minimize state, persisted independently of the
|
||||
// ImGui dashboard. Sharing snap.IsMinimized via the plugin caused the
|
||||
// ImGui "_" chip to also collapse the Avalonia panel (and vice versa) —
|
||||
// which the user noticed because the Avalonia minimized look hadn't
|
||||
// been built out yet, so the panel just blanked.
|
||||
private static bool _avaloniaMinimized;
|
||||
private static bool _avaloniaMinimizedLoaded;
|
||||
|
||||
/// <summary>
|
||||
/// Live-testing finding 2026-09-02: lets the overlay pick the right
|
||||
/// initial MinHeight floor when (re)docking the panel, so a saved small
|
||||
/// (minimized) height from a previous session isn't immediately
|
||||
/// re-clamped back up to the expanded floor. Loads on first access if
|
||||
/// not already loaded, same as the panel's own Create() does.
|
||||
/// </summary>
|
||||
internal static bool IsAvaloniaMinimized
|
||||
{
|
||||
get { LoadAvaloniaMinimized(); return _avaloniaMinimized; }
|
||||
}
|
||||
|
||||
private static string VitalCachePath =>
|
||||
System.IO.Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "vitals.cache");
|
||||
|
||||
private static string AvaloniaMinimizedPath =>
|
||||
System.IO.Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "rynthai_avalonia.cache");
|
||||
|
||||
private static void LoadAvaloniaMinimized()
|
||||
{
|
||||
if (_avaloniaMinimizedLoaded) return;
|
||||
_avaloniaMinimizedLoaded = true;
|
||||
try
|
||||
{
|
||||
string path = AvaloniaMinimizedPath;
|
||||
if (!System.IO.File.Exists(path)) return;
|
||||
_avaloniaMinimized = string.Equals(
|
||||
System.IO.File.ReadAllText(path).Trim(),
|
||||
"minimized",
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch { /* corrupt cache — start fresh */ }
|
||||
}
|
||||
|
||||
private static void SaveAvaloniaMinimized()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = AvaloniaMinimizedPath;
|
||||
string dir = System.IO.Path.GetDirectoryName(path)!;
|
||||
System.IO.Directory.CreateDirectory(dir);
|
||||
System.IO.File.WriteAllText(path, _avaloniaMinimized ? "minimized" : "expanded");
|
||||
}
|
||||
catch { /* best-effort */ }
|
||||
}
|
||||
|
||||
private static void LoadVitalCache()
|
||||
{
|
||||
if (_vitalCacheLoaded) return;
|
||||
_vitalCacheLoaded = true;
|
||||
try
|
||||
{
|
||||
string path = VitalCachePath;
|
||||
if (!System.IO.File.Exists(path)) return;
|
||||
string[] parts = System.IO.File.ReadAllText(path).Split(',');
|
||||
if (parts.Length < 6) return;
|
||||
_cachedHp = uint.Parse(parts[0], System.Globalization.CultureInfo.InvariantCulture);
|
||||
_cachedMaxHp = uint.Parse(parts[1], System.Globalization.CultureInfo.InvariantCulture);
|
||||
_cachedSt = uint.Parse(parts[2], System.Globalization.CultureInfo.InvariantCulture);
|
||||
_cachedMaxSt = uint.Parse(parts[3], System.Globalization.CultureInfo.InvariantCulture);
|
||||
_cachedMn = uint.Parse(parts[4], System.Globalization.CultureInfo.InvariantCulture);
|
||||
_cachedMaxMn = uint.Parse(parts[5], System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
catch { /* corrupt cache — start fresh */ }
|
||||
}
|
||||
|
||||
private static void SaveVitalCache()
|
||||
{
|
||||
// Throttle disk writes to once per second so polling 4×/s doesn't
|
||||
// beat up AppData. We only save when at least one max changed anyway.
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _vitalCacheLastSavedTick < 1000) return;
|
||||
_vitalCacheLastSavedTick = now;
|
||||
try
|
||||
{
|
||||
string path = VitalCachePath;
|
||||
string dir = System.IO.Path.GetDirectoryName(path)!;
|
||||
System.IO.Directory.CreateDirectory(dir);
|
||||
System.IO.File.WriteAllText(path,
|
||||
$"{_cachedHp},{_cachedMaxHp},{_cachedSt},{_cachedMaxSt},{_cachedMn},{_cachedMaxMn}");
|
||||
}
|
||||
catch { /* best-effort, never throw out of a UI tick */ }
|
||||
}
|
||||
public const double ExpandedHeight = ExpandedHeightPreset, ExpandedMinHeight = ExpandedMinHeightFloor;
|
||||
public const double MinimizedHeight = MinimizedHeightPreset, MinimizedMinHeight = MinimizedMinHeightFloor;
|
||||
|
||||
internal static Control Create()
|
||||
{
|
||||
RynthLog.Info("RynthAiPanel.Create: entry");
|
||||
TryBind();
|
||||
LoadVitalCache();
|
||||
LoadAvaloniaMinimized();
|
||||
RynthLog.Info("RynthAiPanel.Create: TryBind ok");
|
||||
RynthAiDashboardState.EnsureLoaded();
|
||||
|
||||
Snapshot snap = new();
|
||||
// The latest hub view; its raw snapshot backs click handlers (current
|
||||
// toggle states, picker lists) exactly as the old per-tick snapshot did.
|
||||
RynthAiSnapshot snap = new();
|
||||
Border? activePicker = null;
|
||||
Button? activeAnchor = null;
|
||||
|
||||
|
|
@ -355,7 +222,6 @@ internal static partial class RynthAiPanel
|
|||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(8, 2, 0, 0)
|
||||
};
|
||||
int versionPollTicks = 0;
|
||||
titleStack.Children.Add(versionText);
|
||||
titleRow.Children.Add(titleStack);
|
||||
|
||||
|
|
@ -382,20 +248,19 @@ internal static partial class RynthAiPanel
|
|||
// Chip clicks must NOT also trigger drag — Button itself handles
|
||||
// PointerPressed and marks the event handled, so it doesn't bubble
|
||||
// to the title-border drag handler.
|
||||
lockChip.Click += (_, _) => { ClosePicker(); _togglePanelLock?.Invoke(); };
|
||||
minusChip.Click += (_, _) => { ClosePicker(); _adjustOpacity?.Invoke(-0.1f); };
|
||||
plusChip.Click += (_, _) => { ClosePicker(); _adjustOpacity?.Invoke(0.1f); };
|
||||
lockChip.Click += (_, _) => { ClosePicker(); RynthAiCommands.TogglePanelLock(); };
|
||||
minusChip.Click += (_, _) => { ClosePicker(); RynthAiCommands.AdjustOpacity(-0.1f); };
|
||||
plusChip.Click += (_, _) => { ClosePicker(); RynthAiCommands.AdjustOpacity(0.1f); };
|
||||
minChip.Click += (_, _) =>
|
||||
{
|
||||
ClosePicker();
|
||||
_avaloniaMinimized = !_avaloniaMinimized;
|
||||
SaveAvaloniaMinimized();
|
||||
RynthAiDashboardState.SetMinimized(!RynthAiDashboardState.Minimized);
|
||||
// Live-testing finding 2026-09-02: reducing used to hide content
|
||||
// rows but leave the window's own size untouched. Actually
|
||||
// resize to the preset for the mode just switched to.
|
||||
RequestDockedResize?.Invoke(
|
||||
_avaloniaMinimized ? MinimizedHeightPreset : ExpandedHeightPreset,
|
||||
_avaloniaMinimized ? MinimizedMinHeightFloor : ExpandedMinHeightFloor);
|
||||
RynthAiDashboardState.Minimized ? MinimizedHeightPreset : ExpandedHeightPreset,
|
||||
RynthAiDashboardState.Minimized ? MinimizedMinHeightFloor : ExpandedMinHeightFloor);
|
||||
};
|
||||
dockChip.Click += (_, _) =>
|
||||
{
|
||||
|
|
@ -439,7 +304,7 @@ internal static partial class RynthAiPanel
|
|||
CornerRadius = new CornerRadius(3),
|
||||
Padding = new Thickness(0)
|
||||
};
|
||||
macroButton.Click += (_, _) => { ClosePicker(); _toggleMacro?.Invoke(); };
|
||||
macroButton.Click += (_, _) => { ClosePicker(); RynthAiCommands.ToggleMacro(); };
|
||||
macroRow.Children.Add(macroButton);
|
||||
|
||||
// Status circle: 8px filled + 14px ring while running
|
||||
|
|
@ -555,7 +420,7 @@ internal static partial class RynthAiPanel
|
|||
IsVisible = false
|
||||
};
|
||||
ToolTip.SetTip(minimizedMacroButton, "Click to Start / Stop Macro");
|
||||
minimizedMacroButton.Click += (_, _) => { ClosePicker(); _toggleMacro?.Invoke(); };
|
||||
minimizedMacroButton.Click += (_, _) => { ClosePicker(); RynthAiCommands.ToggleMacro(); };
|
||||
togglesPanel.Children.Add(minimizedMacroButton);
|
||||
|
||||
// Avalonia 11 Grid has no ColumnSpacing/RowSpacing; we lay the cells
|
||||
|
|
@ -612,25 +477,25 @@ internal static partial class RynthAiPanel
|
|||
Margin = new Thickness(0, 1, 0, 0)
|
||||
};
|
||||
ToolTip.SetTip(frButton, "Force-recast all buffs.");
|
||||
frButton.Click += (_, _) => { ClosePicker(); _forceRebuff?.Invoke(); };
|
||||
frButton.Click += (_, _) => { ClosePicker(); RynthAiCommands.ForceRebuff(); };
|
||||
// Right-click cancel
|
||||
frButton.PointerPressed += (_, e) =>
|
||||
{
|
||||
if (e.GetCurrentPoint(frButton).Properties.IsRightButtonPressed)
|
||||
{
|
||||
e.Handled = true;
|
||||
_cancelForceRebuff?.Invoke();
|
||||
RynthAiCommands.CancelForceRebuff();
|
||||
}
|
||||
};
|
||||
togglesPanel.Children.Add(frButton);
|
||||
|
||||
combatGrid.Children.Add(togglesPanel);
|
||||
|
||||
combatToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(0, snap.CombatEnabled ? 0 : 1); };
|
||||
buffToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(1, snap.BuffingEnabled ? 0 : 1); };
|
||||
navToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(2, snap.NavigationEnabled ? 0 : 1); };
|
||||
lootToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(3, snap.LootingEnabled ? 0 : 1); };
|
||||
metaToggle.Click += (_, _) => { ClosePicker(); _setSubsystemEnabled?.Invoke(4, snap.MetaEnabled ? 0 : 1); };
|
||||
combatToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(0, !snap.CombatEnabled); };
|
||||
buffToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(1, !snap.BuffingEnabled); };
|
||||
navToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(2, !snap.NavigationEnabled); };
|
||||
lootToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(3, !snap.LootingEnabled); };
|
||||
metaToggle.Click += (_, _) => { ClosePicker(); RynthAiCommands.SetSubsystemEnabled(4, !snap.MetaEnabled); };
|
||||
|
||||
// Right column: target + vitals ──────────────────────
|
||||
var vitalsStack = new StackPanel { Orientation = Orientation.Vertical, Spacing = 3, Margin = new Thickness(6, 2, 0, 0) };
|
||||
|
|
@ -697,21 +562,17 @@ internal static partial class RynthAiPanel
|
|||
Margin = new Thickness(0, 4, 0, 0)
|
||||
};
|
||||
AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>",
|
||||
onLeftClick: () => AvaloniaOverlay.ActivateBarButton("Meta"));
|
||||
AddLauncher(launcherGrid, 0, 1, "Monsters", "◎",
|
||||
onClick: () => AvaloniaOverlay.ActivateBarButton("Monsters"));
|
||||
onLeftClick: () => PanelRouter.Toggle("Meta"),
|
||||
onRightClick: () => PanelRouter.Toggle("Lua"));
|
||||
AddMonstersLauncher(launcherGrid, 0, 1);
|
||||
AddLauncher(launcherGrid, 0, 2, "Settings", "⚒",
|
||||
onClick: () => AvaloniaOverlay.ActivateBarButton("Settings"));
|
||||
onClick: () => PanelRouter.Toggle("Settings"));
|
||||
AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺",
|
||||
onLeftClick: () => AvaloniaOverlay.ActivateBarButton("Nav"));
|
||||
onLeftClick: () => PanelRouter.Toggle("Nav"));
|
||||
AddLauncher(launcherGrid, 1, 1, "Items", "🛡",
|
||||
onClick: () => AvaloniaOverlay.ActivateBarButton("Items"));
|
||||
onClick: () => PanelRouter.Toggle("Items"));
|
||||
var patrolBtn = AddLauncher(launcherGrid, 1, 2, "Patrol", "⬡",
|
||||
onClick: () =>
|
||||
{
|
||||
if (_sendNavCommand == null) TryBind();
|
||||
SendNavCmd("{\"Cmd\":\"dunPatrol\"}");
|
||||
});
|
||||
onClick: () => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}"));
|
||||
ToolTip.SetTip(patrolBtn, "Left-click: start dungeon patrol. Right-click: routes & recorded hazards.");
|
||||
// Right-click → patrol management flyout (saved routes + recorded dungeon hazards).
|
||||
patrolBtn.PointerPressed += (_, e) =>
|
||||
|
|
@ -845,11 +706,11 @@ internal static partial class RynthAiPanel
|
|||
}
|
||||
|
||||
profileSelector.Click += (_, _) =>
|
||||
ShowPicker(profileSelector, snap.Profiles, snap.SelectedProfileIdx, idx => _selectProfile?.Invoke(3, idx));
|
||||
ShowPicker(profileSelector, snap.Profiles, snap.SelectedProfileIdx, idx => RynthAiCommands.SelectProfile(3, idx));
|
||||
navSelector.Click += (_, _) =>
|
||||
ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => _selectProfile?.Invoke(0, idx));
|
||||
ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => RynthAiCommands.SelectProfile(0, idx));
|
||||
lootSelector.Click += (_, _) =>
|
||||
ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => _selectProfile?.Invoke(1, idx));
|
||||
ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => RynthAiCommands.SelectProfile(1, idx));
|
||||
lootEditButton.Click += (_, _) =>
|
||||
{
|
||||
ClosePicker();
|
||||
|
|
@ -857,7 +718,7 @@ internal static partial class RynthAiPanel
|
|||
LaunchLootEditor(path);
|
||||
};
|
||||
metaSelector.Click += (_, _) =>
|
||||
ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => _selectProfile?.Invoke(2, idx));
|
||||
ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => RynthAiCommands.SelectProfile(2, idx));
|
||||
|
||||
// ── Polling timer: refresh from snapshot ────────────────────────────
|
||||
// 33 ms (~30 Hz) — vital changes feel instant to the eye. The
|
||||
|
|
@ -868,15 +729,6 @@ internal static partial class RynthAiPanel
|
|||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(33) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (versionPollTicks-- <= 0) // ~every 2 s; the timer runs at 30 Hz
|
||||
{
|
||||
versionPollTicks = 60;
|
||||
string ver = "";
|
||||
foreach (var p in PluginManager.Plugins)
|
||||
if (p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)) { ver = p.VersionString; break; }
|
||||
if (versionText.Text != ver) versionText.Text = ver;
|
||||
}
|
||||
if (_getSnapshotJson == null) TryBind();
|
||||
|
||||
// TL;DR #7: signal the popout host (if floating) that a new
|
||||
// snapshot arrived this 33ms tick. Unconditional (not gated on
|
||||
|
|
@ -885,19 +737,37 @@ internal static partial class RynthAiPanel
|
|||
// (was 60Hz via alwaysRender), not further gating below that.
|
||||
MarkDirty?.Invoke();
|
||||
|
||||
snap = ReadSnapshot();
|
||||
// Footer: FPS (refreshed once/sec by EndSceneHook) + engine
|
||||
// gen uptime (re-stamped on every hot-reload). Engine-local, so it
|
||||
// updates even before the first hub view arrives.
|
||||
float liveFps = D3D9.EndSceneHook.MeasuredFps;
|
||||
SetText(fpsText, liveFps > 0 ? $"FPS {liveFps:F0}" : "FPS —");
|
||||
DateTime startedUtc = EntryPoint.InitStartedUtc;
|
||||
if (startedUtc != DateTime.MinValue)
|
||||
{
|
||||
TimeSpan up = DateTime.UtcNow - startedUtc;
|
||||
SetText(uptimeText, up.TotalHours >= 1
|
||||
? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}"
|
||||
: $"Up {up.Minutes}:{up.Seconds:D2}");
|
||||
}
|
||||
SetText(minChip, RynthAiDashboardState.Minimized ? "^" : "_");
|
||||
SetText(dockChip, IsFloatingNow?.Invoke() == true ? "↙" : "↗");
|
||||
|
||||
var current = UiSources.RynthAi.Current;
|
||||
if (current == null) return;
|
||||
RynthAiView view = current.Value;
|
||||
snap = view.Raw;
|
||||
SetText(versionText, view.Version);
|
||||
|
||||
// Live-testing finding 2026-09-02: apply the opacity the header
|
||||
// +/- chips set (see ColPanelBg's declaration above). Same 0.1
|
||||
// floor as the plugin-side clamp so the panel can never fade to
|
||||
// fully invisible/unclickable-looking.
|
||||
byte bgAlpha = (byte)Math.Clamp(Math.Round(snap.BgOpacity * 255f), 25.5, 255);
|
||||
byte bgAlpha = view.PanelAlpha;
|
||||
if (ColPanelBg.Color.A != bgAlpha)
|
||||
ColPanelBg.Color = new Color(bgAlpha, ColPanelBg.Color.R, ColPanelBg.Color.G, ColPanelBg.Color.B);
|
||||
|
||||
SetText(lockChip, snap.IsLocked ? "Unlk" : "Lock");
|
||||
SetText(minChip, _avaloniaMinimized ? "^" : "_");
|
||||
SetText(dockChip, IsFloatingNow?.Invoke() == true ? "↙" : "↗");
|
||||
|
||||
// Mirrors LegacyDashboardRenderer's minimized layout:
|
||||
// • title row (always visible — chips live there)
|
||||
|
|
@ -905,7 +775,7 @@ internal static partial class RynthAiPanel
|
|||
// • inline ON/OFF macro button at top of toggles when minimized
|
||||
// • header grid (macro state, dropdowns) — hidden when minimized
|
||||
// • launcher grid (6 buttons) — hidden when minimized
|
||||
bool minimized = _avaloniaMinimized;
|
||||
bool minimized = RynthAiDashboardState.Minimized;
|
||||
headerGrid.IsVisible = !minimized;
|
||||
launcherGrid.IsVisible = !minimized;
|
||||
footerGrid.IsVisible = !minimized;
|
||||
|
|
@ -934,13 +804,13 @@ internal static partial class RynthAiPanel
|
|||
statusDot.Fill = running ? ColGreen : ColMute;
|
||||
statusRing.IsVisible = running;
|
||||
|
||||
SetText(metaStateValue, string.IsNullOrWhiteSpace(snap.CurrentState) ? "Default" : snap.CurrentState);
|
||||
SetText(botActivityValue, string.IsNullOrWhiteSpace(snap.BotAction) || snap.BotAction == "Default" ? "Idle" : snap.BotAction);
|
||||
SetText(metaStateValue, view.MetaStateText);
|
||||
SetText(botActivityValue, view.BotActivityText);
|
||||
|
||||
SetText(profileSelector, Truncate(snap.SelectedProfile, 16));
|
||||
SetText(navSelector, Truncate(snap.CurrentNavName, 16));
|
||||
SetText(lootSelector, Truncate(snap.CurrentLootName, 16));
|
||||
SetText(metaSelector, Truncate(snap.CurrentMetaName, 16));
|
||||
SetText(profileSelector, view.ProfileText);
|
||||
SetText(navSelector, view.NavText);
|
||||
SetText(lootSelector, view.LootText);
|
||||
SetText(metaSelector, view.MetaText);
|
||||
|
||||
UpdateToggle(combatToggle, snap.CombatEnabled);
|
||||
UpdateToggle(buffToggle, snap.BuffingEnabled);
|
||||
|
|
@ -949,58 +819,25 @@ internal static partial class RynthAiPanel
|
|||
UpdateMetaToggle(metaToggle, snap.MetaEnabled);
|
||||
|
||||
// Target headline + segmented bar
|
||||
string label = string.IsNullOrWhiteSpace(snap.TargetLabel) ? "NO TARGET" : snap.TargetLabel.ToUpperInvariant();
|
||||
SetText(targetLabel, Truncate(label, 32));
|
||||
SetText(targetLabel, view.TargetHeadline);
|
||||
SetText(targetHp, snap.TargetHealthDisplay);
|
||||
UpdateSegmentedBar(targetSegments, snap.TargetHealthPercent, ref targetSegLastLit);
|
||||
UpdateSegmentedBar(targetSegments, view.TargetSegmentsLit, ref targetSegLastLit);
|
||||
|
||||
bool showTargetSubBars = snap.ShowTargetStaminaMana && snap.TargetMaxStamina > 0;
|
||||
targetStRow.IsVisible = showTargetSubBars;
|
||||
targetMnRow.IsVisible = showTargetSubBars;
|
||||
if (showTargetSubBars)
|
||||
targetStRow.IsVisible = view.ShowTargetSubBars;
|
||||
targetMnRow.IsVisible = view.ShowTargetSubBars;
|
||||
if (view.ShowTargetSubBars)
|
||||
{
|
||||
UpdateCompactBar(targetStFill, targetStLabel, "ST", snap.TargetStamina, snap.TargetMaxStamina);
|
||||
UpdateCompactBar(targetMnFill, targetMnLabel, "MN", snap.TargetMana, snap.TargetMaxMana);
|
||||
UpdateBar(targetStFill, targetStLabel, view.TargetStamina);
|
||||
UpdateBar(targetMnFill, targetMnLabel, view.TargetMana);
|
||||
}
|
||||
|
||||
// Sticky vitals: keep showing last-known values when the plugin
|
||||
// briefly returns 0 after a hot reload (host cache is cold for a
|
||||
// tick or two). Update + persist the cache only when we get a
|
||||
// real reading.
|
||||
bool cacheChanged = false;
|
||||
if (snap.PlayerMaxHealth != 0) { _cachedHp = snap.PlayerHealth; _cachedMaxHp = snap.PlayerMaxHealth; cacheChanged = true; }
|
||||
if (snap.PlayerMaxStamina != 0) { _cachedSt = snap.PlayerStamina; _cachedMaxSt = snap.PlayerMaxStamina; cacheChanged = true; }
|
||||
if (snap.PlayerMaxMana != 0) { _cachedMn = snap.PlayerMana; _cachedMaxMn = snap.PlayerMaxMana; cacheChanged = true; }
|
||||
if (cacheChanged) SaveVitalCache();
|
||||
|
||||
UpdateVitalRow(hpFill, hpText, "HP",
|
||||
snap.PlayerMaxHealth != 0 ? snap.PlayerHealth : _cachedHp,
|
||||
snap.PlayerMaxHealth != 0 ? snap.PlayerMaxHealth : _cachedMaxHp);
|
||||
UpdateVitalRow(stFill, stText, "ST",
|
||||
snap.PlayerMaxStamina != 0 ? snap.PlayerStamina : _cachedSt,
|
||||
snap.PlayerMaxStamina != 0 ? snap.PlayerMaxStamina : _cachedMaxSt);
|
||||
UpdateVitalRow(mnFill, mnText, "MN",
|
||||
snap.PlayerMaxMana != 0 ? snap.PlayerMana : _cachedMn,
|
||||
snap.PlayerMaxMana != 0 ? snap.PlayerMaxMana : _cachedMaxMn);
|
||||
|
||||
// Footer: FPS (refreshed once/sec by EndSceneHook) + engine
|
||||
// gen uptime (re-stamped on every hot-reload). Cheap to recompute
|
||||
// every 100 ms — string interpolation only, no native calls.
|
||||
float liveFps = D3D9.EndSceneHook.MeasuredFps;
|
||||
SetText(fpsText, liveFps > 0 ? $"FPS {liveFps:F0}" : "FPS —");
|
||||
|
||||
DateTime startedUtc = EntryPoint.InitStartedUtc;
|
||||
if (startedUtc != DateTime.MinValue)
|
||||
{
|
||||
TimeSpan up = DateTime.UtcNow - startedUtc;
|
||||
string upStr = up.TotalHours >= 1
|
||||
? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}"
|
||||
: $"Up {up.Minutes}:{up.Seconds:D2}";
|
||||
SetText(uptimeText, upStr);
|
||||
}
|
||||
// Sticky vitals are applied by the hub (StickyVitals).
|
||||
UpdateBar(hpFill, hpText, view.Health);
|
||||
UpdateBar(stFill, stText, view.Stamina);
|
||||
UpdateBar(mnFill, mnText, view.Mana);
|
||||
};
|
||||
timer.Start();
|
||||
RynthLog.Info("RynthAiPanel.Create: timer started, returning root");
|
||||
// Not started here: AttachedToVisualTree starts it (and subscribes).
|
||||
RynthLog.Info("RynthAiPanel.Create: returning root");
|
||||
|
||||
// BringPanelToFront in AvaloniaOverlay does Remove+Add on the
|
||||
// windowFrame whenever a drag or resize starts — that fires
|
||||
|
|
@ -1009,8 +846,17 @@ internal static partial class RynthAiPanel
|
|||
// killed snapshot polling: numbers froze and dropdown selections
|
||||
// appeared not to change (the click DID reach the plugin, the
|
||||
// panel just never re-polled to refresh the visible label).
|
||||
root.AttachedToVisualTree += (_, _) => timer.Start();
|
||||
root.DetachedFromVisualTree += (_, _) => { timer.Stop(); ClosePicker(); };
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.RynthAi.Subscribe();
|
||||
timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.RynthAi.Unsubscribe();
|
||||
timer.Stop();
|
||||
ClosePicker();
|
||||
};
|
||||
return root;
|
||||
}
|
||||
|
||||
|
|
@ -1090,7 +936,7 @@ internal static partial class RynthAiPanel
|
|||
/// engine module (Runtime\ or Runtime\.engine_loads\) to find it. ShellExecute, not
|
||||
/// Process.Start: the Process API is the documented AV hazard inside acclient.exe.
|
||||
/// </summary>
|
||||
private static void LaunchLootEditor(string? profilePath)
|
||||
internal static void LaunchLootEditor(string? profilePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
|
@ -1249,14 +1095,9 @@ internal static partial class RynthAiPanel
|
|||
return brushes;
|
||||
}
|
||||
|
||||
private static void UpdateSegmentedBar(Rectangle[] segments, float pct, ref int lastLitCount)
|
||||
private static void UpdateSegmentedBar(Rectangle[] segments, int litCount, ref int lastLitCount)
|
||||
{
|
||||
float clamped = Math.Clamp(pct, 0f, 1f);
|
||||
int n = segments.Length;
|
||||
int litCount = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
if ((float)i / n <= clamped) litCount++;
|
||||
|
||||
if (litCount == lastLitCount)
|
||||
return; // nothing crossed a segment boundary since the last call — skip entirely
|
||||
|
||||
|
|
@ -1307,13 +1148,12 @@ internal static partial class RynthAiPanel
|
|||
return grid;
|
||||
}
|
||||
|
||||
private static void UpdateCompactBar(Rectangle fill, TextBlock label, string prefix, uint v, uint maxV)
|
||||
/// <summary>Sizes a bar's fill to the view's fraction and sets its text.</summary>
|
||||
private static void UpdateBar(Rectangle fill, TextBlock text, VitalView bar)
|
||||
{
|
||||
double pct = maxV == 0 ? 0 : Math.Clamp((double)v / maxV, 0, 1);
|
||||
// Width set via parent bounds — bind via width binding using grid actual width
|
||||
if (fill.Parent is Grid g && g.Bounds.Width > 0)
|
||||
fill.Width = g.Bounds.Width * pct;
|
||||
SetText(label, $"{prefix} {v}/{maxV}");
|
||||
fill.Width = g.Bounds.Width * bar.Fraction;
|
||||
SetText(text, bar.Text);
|
||||
}
|
||||
|
||||
private static Grid BuildVitalRow(string icon, IBrush color, out Rectangle fill, out TextBlock text)
|
||||
|
|
@ -1356,15 +1196,6 @@ internal static partial class RynthAiPanel
|
|||
return grid;
|
||||
}
|
||||
|
||||
private static void UpdateVitalRow(Rectangle fill, TextBlock text, string label, uint v, uint maxV)
|
||||
{
|
||||
double pct = maxV == 0 ? 0 : Math.Clamp((double)v / maxV, 0, 1);
|
||||
if (fill.Parent is Grid g && g.Bounds.Width > 0)
|
||||
fill.Width = g.Bounds.Width * pct;
|
||||
string display = maxV == 0 ? (v == 0 ? "--/--" : $"{v}/--") : $"{v}/{maxV}";
|
||||
SetText(text, $"{label}: {(int)(pct * 100)}% ({display})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits a single launcher cell into two half-width buttons sitting side
|
||||
/// by side. Used for Nav | Map so the user can pop the navigation panel
|
||||
|
|
@ -1416,6 +1247,14 @@ internal static partial class RynthAiPanel
|
|||
return btn;
|
||||
}
|
||||
|
||||
// Monsters opens the Damage panel (the basic Monsters panel and its
|
||||
// Simple/Advanced chip were retired 2026-10-01).
|
||||
private static void AddMonstersLauncher(Grid grid, int row, int col)
|
||||
{
|
||||
Button open = AddLauncher(grid, row, col, "Monsters", "◎", onClick: PanelRouter.ToggleMonsters);
|
||||
ToolTip.SetTip(open, "Monsters: weapons, spells and rules per monster (the Damage panel)");
|
||||
}
|
||||
|
||||
private static void UpdateToggle(Button btn, bool on)
|
||||
{
|
||||
btn.Background = on ? ColTealSoft : ColBarBg;
|
||||
|
|
@ -1430,12 +1269,6 @@ internal static partial class RynthAiPanel
|
|||
btn.Foreground = on ? ColTeal : ColMute;
|
||||
}
|
||||
|
||||
private static string Truncate(string? value, int max)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value)) return "None";
|
||||
return value.Length > max ? value[..(max - 1)] + "…" : value;
|
||||
}
|
||||
|
||||
private static void SetText(TextBlock tb, string s)
|
||||
{
|
||||
if (!string.Equals(tb.Text, s, StringComparison.Ordinal)) tb.Text = s;
|
||||
|
|
@ -1452,163 +1285,6 @@ internal static partial class RynthAiPanel
|
|||
if (!Equals(btn.Content as string, s)) btn.Content = s;
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// Plugin export binding + snapshot ingest
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private static int _snapshotDiagsLogged;
|
||||
private static string _lastLoggedTargetLabel = string.Empty;
|
||||
private static uint _lastLoggedPlayerHealth;
|
||||
private static uint _lastLoggedPlayerMaxHealth;
|
||||
|
||||
private static Snapshot ReadSnapshot()
|
||||
{
|
||||
if (_getSnapshotJson == null) return new Snapshot();
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getSnapshotJson();
|
||||
if (ptr == IntPtr.Zero) return new Snapshot();
|
||||
string json = Marshal.PtrToStringAnsi(ptr) ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(json)) return new Snapshot();
|
||||
Snapshot snap = JsonSerializer.Deserialize(json, SnapshotJsonContext.Default.Snapshot) ?? new Snapshot();
|
||||
|
||||
// Log first 3 snapshots for pipeline-up diagnostic. Then log on
|
||||
// any change to a vital/target field so we can see when data
|
||||
// starts flowing post-login without flooding.
|
||||
if (_snapshotDiagsLogged < 3 ||
|
||||
snap.TargetLabel != _lastLoggedTargetLabel ||
|
||||
snap.PlayerHealth != _lastLoggedPlayerHealth ||
|
||||
snap.PlayerMaxHealth != _lastLoggedPlayerMaxHealth)
|
||||
{
|
||||
_snapshotDiagsLogged++;
|
||||
_lastLoggedTargetLabel = snap.TargetLabel;
|
||||
_lastLoggedPlayerHealth = snap.PlayerHealth;
|
||||
_lastLoggedPlayerMaxHealth = snap.PlayerMaxHealth;
|
||||
RynthLog.Info(
|
||||
$"RynthAiPanel.ReadSnapshot[{_snapshotDiagsLogged}]: " +
|
||||
$"player HP={snap.PlayerHealth}/{snap.PlayerMaxHealth} " +
|
||||
$"ST={snap.PlayerStamina}/{snap.PlayerMaxStamina} " +
|
||||
$"MN={snap.PlayerMana}/{snap.PlayerMaxMana} " +
|
||||
$"target='{snap.TargetLabel}' hp={snap.TargetHealth}/{snap.TargetMaxHealth} " +
|
||||
$"jsonLen={json.Length}");
|
||||
}
|
||||
|
||||
return snap;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"RynthAiPanel.ReadSnapshot: deserialize threw {ex.GetType().Name}: {ex.Message}");
|
||||
return new Snapshot();
|
||||
}
|
||||
}
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static RynthAiPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getSnapshotJson = null;
|
||||
_toggleMacro = null;
|
||||
_setSubsystemEnabled = null;
|
||||
_selectProfile = null;
|
||||
_forceRebuff = null;
|
||||
_cancelForceRebuff = null;
|
||||
_adjustOpacity = null;
|
||||
_togglePanelLock = null;
|
||||
_togglePanelMinimize = null;
|
||||
_sendNavCommand = null;
|
||||
_getPatrolInfoJson = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
_getSnapshotJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthPluginGetSnapshotJson");
|
||||
_toggleMacro ??= Bind<VoidFn>(plugin, "RynthPluginToggleMacro");
|
||||
_setSubsystemEnabled ??= Bind<IntIntFn>(plugin, "RynthPluginSetSubsystemEnabled");
|
||||
_selectProfile ??= Bind<IntIntFn>(plugin, "RynthPluginSelectProfile");
|
||||
_forceRebuff ??= Bind<VoidFn>(plugin, "RynthPluginForceRebuff");
|
||||
_cancelForceRebuff ??= Bind<VoidFn>(plugin, "RynthPluginCancelForceRebuff");
|
||||
_adjustOpacity ??= Bind<FloatFn>(plugin, "RynthPluginAdjustOpacity");
|
||||
_togglePanelLock ??= Bind<VoidFn>(plugin, "RynthPluginTogglePanelLock");
|
||||
_togglePanelMinimize ??= Bind<VoidFn>(plugin, "RynthPluginTogglePanelMinimize");
|
||||
_sendNavCommand ??= Bind<PtrFn>(plugin, "RynthPluginSendNavCommand");
|
||||
_getPatrolInfoJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthPluginGetPatrolInfoJson");
|
||||
|
||||
if (!_bindingLogged && _getSnapshotJson != null)
|
||||
{
|
||||
_bindingLogged = true;
|
||||
RynthLog.UI("RynthAiPanel: bound RynthAi plugin exports for live dashboard data.");
|
||||
}
|
||||
}
|
||||
|
||||
private static T? Bind<T>(LoadedPlugin plugin, string exportName) where T : Delegate
|
||||
{
|
||||
IntPtr addr = GetProcAddress(plugin.ModuleHandle, exportName);
|
||||
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static void SendNavCmd(string json)
|
||||
{
|
||||
if (_sendNavCommand == null) return;
|
||||
IntPtr ptr = Marshal.StringToHGlobalAnsi(json);
|
||||
try { _sendNavCommand(ptr); }
|
||||
finally { Marshal.FreeHGlobal(ptr); }
|
||||
}
|
||||
|
||||
private sealed class Snapshot
|
||||
{
|
||||
[JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; }
|
||||
[JsonPropertyName("currentState")] public string CurrentState { get; set; } = string.Empty;
|
||||
[JsonPropertyName("botAction")] public string BotAction { get; set; } = string.Empty;
|
||||
[JsonPropertyName("selectedProfile")] public string SelectedProfile { get; set; } = "Default";
|
||||
[JsonPropertyName("profiles")] public string[] Profiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("navProfiles")] public string[] NavProfiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("lootProfiles")] public string[] LootProfiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty<string>();
|
||||
[JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("currentLootPath")] public string CurrentLootPath { get; set; } = string.Empty;
|
||||
// Set while a vendor is open: the AutoVendor profile it would use (may not exist yet).
|
||||
[JsonPropertyName("vendorProfilePath")] public string VendorProfilePath { get; set; } = string.Empty;
|
||||
[JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; }
|
||||
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; }
|
||||
[JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; }
|
||||
[JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; }
|
||||
[JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; }
|
||||
[JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; }
|
||||
[JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; }
|
||||
[JsonPropertyName("lootingEnabled")] public bool LootingEnabled { get; set; }
|
||||
[JsonPropertyName("metaEnabled")] public bool MetaEnabled { get; set; }
|
||||
[JsonPropertyName("currentTargetId")] public uint CurrentTargetId { get; set; }
|
||||
[JsonPropertyName("targetLabel")] public string TargetLabel { get; set; } = "NO TARGET";
|
||||
[JsonPropertyName("targetHealthPercent")] public float TargetHealthPercent { get; set; }
|
||||
[JsonPropertyName("targetHealthDisplay")] public string TargetHealthDisplay { get; set; } = "0";
|
||||
[JsonPropertyName("targetHealth")] public uint TargetHealth { get; set; }
|
||||
[JsonPropertyName("targetMaxHealth")] public uint TargetMaxHealth { get; set; }
|
||||
[JsonPropertyName("targetStamina")] public uint TargetStamina { get; set; }
|
||||
[JsonPropertyName("targetMaxStamina")] public uint TargetMaxStamina { get; set; }
|
||||
[JsonPropertyName("targetMana")] public uint TargetMana { get; set; }
|
||||
[JsonPropertyName("targetMaxMana")] public uint TargetMaxMana { get; set; }
|
||||
[JsonPropertyName("playerHealth")] public uint PlayerHealth { get; set; }
|
||||
[JsonPropertyName("playerMaxHealth")] public uint PlayerMaxHealth { get; set; }
|
||||
[JsonPropertyName("playerStamina")] public uint PlayerStamina { get; set; }
|
||||
[JsonPropertyName("playerMaxStamina")] public uint PlayerMaxStamina { get; set; }
|
||||
[JsonPropertyName("playerMana")] public uint PlayerMana { get; set; }
|
||||
[JsonPropertyName("playerMaxMana")] public uint PlayerMaxMana { get; set; }
|
||||
[JsonPropertyName("showTargetStaminaMana")] public bool ShowTargetStaminaMana { get; set; }
|
||||
[JsonPropertyName("isLocked")] public bool IsLocked { get; set; }
|
||||
[JsonPropertyName("isMinimized")] public bool IsMinimized { get; set; }
|
||||
[JsonPropertyName("bgOpacity")] public float BgOpacity { get; set; } = 0.95f;
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(Snapshot))]
|
||||
private sealed partial class SnapshotJsonContext : JsonSerializerContext { }
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// Patrol management flyout (right-click the Patrol launcher button)
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
|
|
@ -1617,6 +1293,17 @@ internal static partial class RynthAiPanel
|
|||
{
|
||||
var root = new StackPanel { Orientation = Orientation.Vertical, Spacing = 4, Width = 244, Margin = new Thickness(8) };
|
||||
PopulatePatrolFlyout(root);
|
||||
// Patrol info comes from the hub (single-consumer export): subscribe
|
||||
// while the flyout is open and repopulate when it changes.
|
||||
long seen = UiSources.Patrol.Current?.Version ?? -1;
|
||||
var poll = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(150) };
|
||||
poll.Tick += (_, _) =>
|
||||
{
|
||||
var cur = UiSources.Patrol.Current;
|
||||
if (cur == null || cur.Version == seen) return;
|
||||
seen = cur.Version;
|
||||
PopulatePatrolFlyout(root);
|
||||
};
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
Content = root,
|
||||
|
|
@ -1628,13 +1315,15 @@ internal static partial class RynthAiPanel
|
|||
Content = scroll,
|
||||
Placement = PlacementMode.Top,
|
||||
};
|
||||
flyout.Opened += (_, _) => { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); poll.Start(); };
|
||||
flyout.Closed += (_, _) => { poll.Stop(); UiSources.Patrol.Unsubscribe(); };
|
||||
flyout.ShowAt(anchor);
|
||||
}
|
||||
|
||||
private static void PopulatePatrolFlyout(StackPanel root)
|
||||
{
|
||||
root.Children.Clear();
|
||||
PatrolInfo info = FetchPatrolInfo();
|
||||
PatrolInfo info = UiSources.Patrol.Current?.Value ?? new PatrolInfo();
|
||||
|
||||
root.Children.Add(new TextBlock
|
||||
{
|
||||
|
|
@ -1656,8 +1345,7 @@ internal static partial class RynthAiPanel
|
|||
var clear = MiniButton("Clear");
|
||||
clear.Click += (_, _) =>
|
||||
{
|
||||
SendNavCmd($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}");
|
||||
PopulatePatrolFlyout(root);
|
||||
RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}", refreshPatrol: true);
|
||||
};
|
||||
Grid.SetColumn(clear, 1);
|
||||
row.Children.Add(clear);
|
||||
|
|
@ -1668,9 +1356,9 @@ internal static partial class RynthAiPanel
|
|||
// environmental lava/acid the name detector can't see.
|
||||
var markRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Margin = new Thickness(0, 2, 0, 0) };
|
||||
var mark = MiniButton("Mark cell as hazard");
|
||||
mark.Click += (_, _) => { SendNavCmd("{\"Cmd\":\"markHazardHere\"}"); PopulatePatrolFlyout(root); };
|
||||
mark.Click += (_, _) => RynthAiCommands.SendNavCommand("{\"Cmd\":\"markHazardHere\"}", refreshPatrol: true);
|
||||
var unmark = MiniButton("Unmark");
|
||||
unmark.Click += (_, _) => { SendNavCmd("{\"Cmd\":\"unmarkHazardHere\"}"); PopulatePatrolFlyout(root); };
|
||||
unmark.Click += (_, _) => RynthAiCommands.SendNavCommand("{\"Cmd\":\"unmarkHazardHere\"}", refreshPatrol: true);
|
||||
markRow.Children.Add(mark);
|
||||
markRow.Children.Add(unmark);
|
||||
root.Children.Add(markRow);
|
||||
|
|
@ -1693,7 +1381,7 @@ internal static partial class RynthAiPanel
|
|||
}
|
||||
else
|
||||
{
|
||||
foreach (DungeonHaz d in info.Dungeons)
|
||||
foreach (DungeonHazards d in info.Dungeons)
|
||||
{
|
||||
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
row.Children.Add(new TextBlock
|
||||
|
|
@ -1704,8 +1392,7 @@ internal static partial class RynthAiPanel
|
|||
var clear = MiniButton("Clear");
|
||||
clear.Click += (_, _) =>
|
||||
{
|
||||
SendNavCmd($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}");
|
||||
PopulatePatrolFlyout(root);
|
||||
RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true);
|
||||
};
|
||||
Grid.SetColumn(clear, 1);
|
||||
row.Children.Add(clear);
|
||||
|
|
@ -1717,8 +1404,7 @@ internal static partial class RynthAiPanel
|
|||
clearAll.Margin = new Thickness(0, 3, 0, 0);
|
||||
clearAll.Click += (_, _) =>
|
||||
{
|
||||
SendNavCmd("{\"Cmd\":\"clearHazardsAll\"}");
|
||||
PopulatePatrolFlyout(root);
|
||||
RynthAiCommands.SendNavCommand("{\"Cmd\":\"clearHazardsAll\"}", refreshPatrol: true);
|
||||
};
|
||||
root.Children.Add(clearAll);
|
||||
}
|
||||
|
|
@ -1754,36 +1440,4 @@ internal static partial class RynthAiPanel
|
|||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
};
|
||||
|
||||
private static PatrolInfo FetchPatrolInfo()
|
||||
{
|
||||
if (_getPatrolInfoJson == null) TryBind();
|
||||
if (_getPatrolInfoJson == null) return new PatrolInfo();
|
||||
try
|
||||
{
|
||||
IntPtr p = _getPatrolInfoJson();
|
||||
if (p == IntPtr.Zero) return new PatrolInfo();
|
||||
string json = Marshal.PtrToStringAnsi(p) ?? "{}";
|
||||
return JsonSerializer.Deserialize(json, PatrolJsonContext.Default.PatrolInfo) ?? new PatrolInfo();
|
||||
}
|
||||
catch { return new PatrolInfo(); }
|
||||
}
|
||||
|
||||
private sealed class PatrolInfo
|
||||
{
|
||||
[JsonPropertyName("inDungeon")] public bool InDungeon { get; set; }
|
||||
[JsonPropertyName("currentLandblock")] public string CurrentLandblock { get; set; } = "0000";
|
||||
[JsonPropertyName("currentHazards")] public int CurrentHazards { get; set; }
|
||||
[JsonPropertyName("liveHazards")] public int LiveHazards { get; set; }
|
||||
[JsonPropertyName("dungeons")] public DungeonHaz[] Dungeons { get; set; } = Array.Empty<DungeonHaz>();
|
||||
[JsonPropertyName("routes")] public string[] Routes { get; set; } = Array.Empty<string>();
|
||||
}
|
||||
|
||||
private sealed class DungeonHaz
|
||||
{
|
||||
[JsonPropertyName("landblock")] public string Landblock { get; set; } = "0000";
|
||||
[JsonPropertyName("cells")] public int Cells { get; set; }
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(PatrolInfo))]
|
||||
private sealed partial class PatrolJsonContext : JsonSerializerContext { }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,15 @@
|
|||
// "ChatFilters" panel (dockable/floatable) — rules get complex enough that
|
||||
// a small overlay inside the chat panel doesn't cut it.
|
||||
//
|
||||
// Rule semantics (shared state lives in RynthChatPanel):
|
||||
// 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.
|
||||
// • FIRST matching rule wins — order matters, hence the ▲▼ buttons.
|
||||
// • Tab name set → matching lines MOVE to that tab (still shown in All).
|
||||
// • Tab name set → matching lines MOVE to that tab (and leave All).
|
||||
// • Tab name empty → matching lines are hidden everywhere.
|
||||
// Since 2026-09-29 rules can also copy and colour (action, when, colour);
|
||||
// only the ImGui face edits those. Editing a tab here makes the rule a plain
|
||||
// Move (or Hide when empty) again.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -19,6 +23,7 @@ using Avalonia.Controls.Primitives;
|
|||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
|
|
@ -32,12 +37,12 @@ internal static class RynthChatFiltersPanel
|
|||
|
||||
internal static Control Create()
|
||||
{
|
||||
RynthChatPanel.EnsureSettingsLoaded();
|
||||
ChatModel.EnsureSettingsLoaded();
|
||||
|
||||
var hint = new TextBlock
|
||||
{
|
||||
Text = "Regex rules, case-insensitive — FIRST match wins (reorder with ▲▼).\n" +
|
||||
"Tab set: matching lines move to that tab (still visible in All).\n" +
|
||||
"Tab set: matching lines move to that tab (and leave All).\n" +
|
||||
"Tab empty: matching lines are hidden everywhere.",
|
||||
FontSize = 9,
|
||||
Foreground = Brushes.Gray,
|
||||
|
|
@ -71,9 +76,9 @@ internal static class RynthChatFiltersPanel
|
|||
|
||||
void RebuildRows()
|
||||
{
|
||||
var filters = RynthChatPanel.Filters;
|
||||
var filters = ChatModel.Filters;
|
||||
rows.Children.Clear();
|
||||
for (int i = 0; i < filters.Count; i++)
|
||||
for (int i = 0; i < filters.Length; i++)
|
||||
{
|
||||
var r = filters[i];
|
||||
int index = i;
|
||||
|
|
@ -87,7 +92,7 @@ internal static class RynthChatFiltersPanel
|
|||
enabledCheck.IsCheckedChanged += (_, _) =>
|
||||
{
|
||||
r.Enabled = enabledCheck.IsChecked == true;
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
ChatModel.FiltersChanged();
|
||||
};
|
||||
|
||||
var patternBox = new TextBox
|
||||
|
|
@ -111,7 +116,7 @@ internal static class RynthChatFiltersPanel
|
|||
r.Pattern = patternBox.Text ?? "";
|
||||
r.Recompile();
|
||||
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
ChatModel.FiltersChanged();
|
||||
};
|
||||
|
||||
var tabBox = new TextBox
|
||||
|
|
@ -133,7 +138,8 @@ internal static class RynthChatFiltersPanel
|
|||
tabBox.TextChanged += (_, _) =>
|
||||
{
|
||||
r.Tab = (tabBox.Text ?? "").Trim();
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
r.Action = r.Tab.Length == 0 ? ChatRuleAction.Hide : ChatRuleAction.Move;
|
||||
ChatModel.FiltersChanged();
|
||||
};
|
||||
|
||||
Button SmallBtn(string label, IBrush fg) => new()
|
||||
|
|
@ -151,30 +157,23 @@ internal static class RynthChatFiltersPanel
|
|||
upBtn.IsEnabled = index > 0;
|
||||
upBtn.Click += (_, _) =>
|
||||
{
|
||||
if (index <= 0) return;
|
||||
filters.RemoveAt(index);
|
||||
filters.Insert(index - 1, r);
|
||||
ChatModel.MoveFilter(r, -1);
|
||||
RebuildRows();
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
};
|
||||
|
||||
var downBtn = SmallBtn("▼", Brushes.White);
|
||||
downBtn.IsEnabled = index < filters.Count - 1;
|
||||
downBtn.IsEnabled = index < filters.Length - 1;
|
||||
downBtn.Click += (_, _) =>
|
||||
{
|
||||
if (index >= filters.Count - 1) return;
|
||||
filters.RemoveAt(index);
|
||||
filters.Insert(index + 1, r);
|
||||
ChatModel.MoveFilter(r, +1);
|
||||
RebuildRows();
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
};
|
||||
|
||||
var delBtn = SmallBtn("Delete", Brushes.IndianRed);
|
||||
delBtn.Click += (_, _) =>
|
||||
{
|
||||
filters.Remove(r);
|
||||
ChatModel.EditFilters(list => list.Remove(r));
|
||||
RebuildRows();
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
};
|
||||
|
||||
rows.Children.Add(new StackPanel
|
||||
|
|
@ -185,7 +184,7 @@ internal static class RynthChatFiltersPanel
|
|||
});
|
||||
}
|
||||
|
||||
if (filters.Count == 0)
|
||||
if (filters.Length == 0)
|
||||
{
|
||||
rows.Children.Add(new TextBlock
|
||||
{
|
||||
|
|
@ -199,15 +198,29 @@ internal static class RynthChatFiltersPanel
|
|||
|
||||
addBtn.Click += (_, _) =>
|
||||
{
|
||||
var rule = new RynthChatPanel.ChatFilterRule();
|
||||
var rule = new ChatFilterRule();
|
||||
rule.Recompile();
|
||||
RynthChatPanel.Filters.Add(rule);
|
||||
RebuildRows();
|
||||
// Empty pattern is inert until typed — no display change yet, but
|
||||
// persist the row so it survives a relaunch mid-edit.
|
||||
RynthChatPanel.NotifyFiltersChanged();
|
||||
ChatModel.EditFilters(list => list.Add(rule));
|
||||
RebuildRows();
|
||||
};
|
||||
|
||||
// The other face (ImGui) may change the rules too.
|
||||
long seen = ChatModel.FiltersVersion;
|
||||
var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
long v = ChatModel.FiltersVersion;
|
||||
if (v == seen) return;
|
||||
seen = v;
|
||||
// Don't rebuild under the user's typing (a keystroke bumps the version too).
|
||||
if (Win32Backend.AvaloniaTextInputActive && layout.IsKeyboardFocusWithin) return;
|
||||
RebuildRows();
|
||||
};
|
||||
layout.AttachedToVisualTree += (_, _) => { seen = ChatModel.FiltersVersion; RebuildRows(); timer.Start(); };
|
||||
layout.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
|
||||
RebuildRows();
|
||||
return layout;
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,11 +1,14 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine — UI/Panels/RynthNavPanel.cs
|
||||
// Avalonia bar panel for the RynthNav plugin (mesh navigation). Bridges to the
|
||||
// plugin DLL via GetProcAddress: polls a status JSON and drives load/test/preview.
|
||||
// Avalonia bar panel for the RynthNav plugin (mesh navigation): shows its
|
||||
// status and drives load/test/preview/go/move. Data goes through UiDataHub
|
||||
// (UI/Data/RynthNavData.cs): UiSources.RynthNav polls the status on the pump
|
||||
// thread and RynthNavCommands runs the actions there; the ImGui face
|
||||
// (ImGui/Panels/RynthNavFace.cs) reads the same snapshot.
|
||||
// This is the only visible RynthNav surface in Decal-coexistence mode (ImGui and
|
||||
// the Nav3D world overlay are both unavailable there).
|
||||
//
|
||||
// Bridge exports (resolved from the RynthNav plugin DLL):
|
||||
// Plugin exports (called by the hub):
|
||||
// RynthNavGetStatusJson() → ANSI JSON status
|
||||
// RynthNavLoadTile() → load current landblock's baked tile
|
||||
// RynthNavTestQuery() → FindNearestPoly at the player
|
||||
|
|
@ -25,28 +28,12 @@ using Avalonia.Media;
|
|||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class RynthNavPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetStatusJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void VoidFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void PreviewFn(IntPtr ansiCoord);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void MoveFn(int cmd);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void GotoFn(IntPtr ansiCoord);
|
||||
|
||||
private static GetStatusJsonFn? _getStatus;
|
||||
private static VoidFn? _loadTile;
|
||||
private static VoidFn? _testQuery;
|
||||
private static PreviewFn? _preview;
|
||||
private static MoveFn? _move;
|
||||
private static GotoFn? _goto;
|
||||
private static bool _bindingLogged;
|
||||
|
||||
// ── Palette (matches RynthAiPanel) ──────────────────────────────────────────
|
||||
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
|
||||
private static readonly IBrush ColGreen = new SolidColorBrush(Color.FromRgb(0x40, 0xD9, 0x73));
|
||||
|
|
@ -68,7 +55,6 @@ internal static class RynthNavPanel
|
|||
|
||||
internal static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
|
||||
var root = new StackPanel { Orientation = Orientation.Vertical, Margin = new Thickness(10), Spacing = 5, MinWidth = 300 };
|
||||
|
||||
|
|
@ -96,8 +82,8 @@ internal static class RynthNavPanel
|
|||
|
||||
// Actions
|
||||
var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 };
|
||||
actions.Children.Add(Btn("Load tile", () => { TryBind(); _loadTile?.Invoke(); }));
|
||||
actions.Children.Add(Btn("Test @ me", () => { TryBind(); _testQuery?.Invoke(); }));
|
||||
actions.Children.Add(Btn("Load tile", RynthNavCommands.LoadTile));
|
||||
actions.Children.Add(Btn("Test @ me", RynthNavCommands.TestQuery));
|
||||
root.Children.Add(actions);
|
||||
root.Children.Add(Sep());
|
||||
|
||||
|
|
@ -125,118 +111,49 @@ internal static class RynthNavPanel
|
|||
|
||||
// Poll the plugin for status (UI thread).
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
long seenVersion = -1;
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getStatus == null) TryBind();
|
||||
Refresh();
|
||||
var snap = UiSources.RynthNav.Current;
|
||||
if (snap == null) { if (_dot != null) _dot.Fill = ColMute; return; }
|
||||
if (snap.Version == seenVersion) return;
|
||||
seenVersion = snap.Version;
|
||||
Refresh(snap.Value);
|
||||
};
|
||||
var outer = new Border { Background = ColShellBg, CornerRadius = new CornerRadius(5), Child = new ScrollViewer { Content = root } };
|
||||
outer.AttachedToVisualTree += (_, _) => timer.Start();
|
||||
outer.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
outer.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.RynthNav.Subscribe();
|
||||
UiSources.RynthNav.RequestRefresh();
|
||||
timer.Start();
|
||||
};
|
||||
outer.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.RynthNav.Unsubscribe();
|
||||
};
|
||||
return outer;
|
||||
}
|
||||
|
||||
private static void Refresh()
|
||||
private static void Refresh(RynthNavStatus st)
|
||||
{
|
||||
if (_getStatus == null) { if (_dot != null) _dot.Fill = ColMute; return; }
|
||||
IntPtr ptr;
|
||||
try { ptr = _getStatus(); } catch { return; }
|
||||
if (ptr == IntPtr.Zero) return;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var r = doc.RootElement;
|
||||
|
||||
bool hasPose = r.TryGetProperty("hasPose", out var v) && v.GetInt32() != 0;
|
||||
string lb = r.TryGetProperty("landblock", out v) ? v.GetString() ?? "----" : "----";
|
||||
double ns = r.TryGetProperty("ns", out v) ? v.GetDouble() : 0;
|
||||
double ew = r.TryGetProperty("ew", out v) ? v.GetDouble() : 0;
|
||||
bool loaded = r.TryGetProperty("tileLoaded", out v) && v.GetInt32() != 0;
|
||||
string loadLb = r.TryGetProperty("loadedLb", out v) ? v.GetString() ?? "----" : "----";
|
||||
int polys = r.TryGetProperty("polyCount", out v) ? v.GetInt32() : 0;
|
||||
string status = r.TryGetProperty("status", out v) ? v.GetString() ?? "" : "";
|
||||
string path = r.TryGetProperty("lastPath", out v) ? v.GetString() ?? "" : "";
|
||||
|
||||
// Change-detection: only touch a control when its value actually changed,
|
||||
// so an idle panel issues zero invalidations (no GDI-overlay flicker).
|
||||
SetText(_playerVal, hasPose ? $"0x{lb} {Loc(ns, 'N', 'S')} {Loc(ew, 'E', 'W')}" : "— no pose —");
|
||||
SetText(_meshVal, loaded ? $"LOADED 0x{loadLb} · {polys} polys" : "not loaded");
|
||||
SetFg(_meshVal, loaded ? ColGreen : ColAmber);
|
||||
SetFill(_dot, loaded ? ColGreen : (hasPose ? ColAmber : ColMute));
|
||||
SetText(_statusVal, status);
|
||||
SetText(_pathVal, string.IsNullOrEmpty(path) ? "" : "↳ " + path);
|
||||
|
||||
int run = r.TryGetProperty("runState", out v) ? v.GetInt32() : 0;
|
||||
int turn = r.TryGetProperty("turnState", out v) ? v.GetInt32() : 0;
|
||||
SetBg(_fwdBtn, run == 1 ? ColGreen : ColBtnFill);
|
||||
SetBg(_backBtn, run == 2 ? ColGreen : ColBtnFill);
|
||||
SetBg(_leftBtn, turn == -1 ? ColGreen : ColBtnFill);
|
||||
SetBg(_rightBtn, turn == 1 ? ColGreen : ColBtnFill);
|
||||
}
|
||||
catch { /* transient partial JSON — ignore */ }
|
||||
// Change-detection: only touch a control when its value actually changed,
|
||||
// so an idle panel issues zero invalidations (no GDI-overlay flicker).
|
||||
SetText(_playerVal, st.PlayerText);
|
||||
SetText(_meshVal, st.MeshText);
|
||||
SetFg(_meshVal, st.TileLoaded ? ColGreen : ColAmber);
|
||||
SetFill(_dot, st.TileLoaded ? ColGreen : (st.HasPose ? ColAmber : ColMute));
|
||||
SetText(_statusVal, st.Status);
|
||||
SetText(_pathVal, st.PathText);
|
||||
SetBg(_fwdBtn, st.RunState == 1 ? ColGreen : ColBtnFill);
|
||||
SetBg(_backBtn, st.RunState == 2 ? ColGreen : ColBtnFill);
|
||||
SetBg(_leftBtn, st.TurnState == -1 ? ColGreen : ColBtnFill);
|
||||
SetBg(_rightBtn, st.TurnState == 1 ? ColGreen : ColBtnFill);
|
||||
}
|
||||
|
||||
private static void Preview()
|
||||
{
|
||||
TryBind();
|
||||
if (_preview == null) return;
|
||||
string txt = _coordBox?.Text ?? "";
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(txt);
|
||||
try { _preview(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
}
|
||||
private static void Preview() => RynthNavCommands.Preview(_coordBox?.Text ?? "");
|
||||
|
||||
private static void Go()
|
||||
{
|
||||
TryBind();
|
||||
if (_goto == null) return;
|
||||
string txt = _coordBox?.Text ?? "";
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(txt);
|
||||
try { _goto(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
}
|
||||
|
||||
// ── Plugin binding ──────────────────────────────────────────────────────────
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static RynthNavPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getStatus = null;
|
||||
_loadTile = null;
|
||||
_testQuery = null;
|
||||
_preview = null;
|
||||
_move = null;
|
||||
_goto = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthNav", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
_getStatus ??= Bind<GetStatusJsonFn>(plugin, "RynthNavGetStatusJson");
|
||||
_loadTile ??= Bind<VoidFn>(plugin, "RynthNavLoadTile");
|
||||
_testQuery ??= Bind<VoidFn>(plugin, "RynthNavTestQuery");
|
||||
_preview ??= Bind<PreviewFn>(plugin, "RynthNavPreviewPath");
|
||||
_move ??= Bind<MoveFn>(plugin, "RynthNavMove");
|
||||
_goto ??= Bind<GotoFn>(plugin, "RynthNavGoto");
|
||||
|
||||
if (!_bindingLogged && _getStatus != null)
|
||||
{
|
||||
_bindingLogged = true;
|
||||
RynthLog.UI("RynthNavPanel: bound RynthNav plugin exports.");
|
||||
}
|
||||
}
|
||||
|
||||
private static T? Bind<T>(LoadedPlugin plugin, string export) where T : Delegate
|
||||
{
|
||||
IntPtr addr = GetProcAddress(plugin.ModuleHandle, export);
|
||||
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
private static void Go() => RynthNavCommands.Goto(_coordBox?.Text ?? "");
|
||||
|
||||
// ── UI helpers ──────────────────────────────────────────────────────────────
|
||||
private static TextBlock ValueRow(StackPanel parent, string label)
|
||||
|
|
@ -316,7 +233,7 @@ internal static class RynthNavPanel
|
|||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
};
|
||||
ToolTip.SetTip(b, tip);
|
||||
b.Click += (_, _) => { TryBind(); _move?.Invoke(cmd); };
|
||||
b.Click += (_, _) => RynthNavCommands.Move(cmd);
|
||||
return b;
|
||||
}
|
||||
|
||||
|
|
@ -325,6 +242,4 @@ internal static class RynthNavPanel
|
|||
private static void SetBg(Button? b, IBrush br) { if (b != null && !ReferenceEquals(b.Background, br)) b.Background = br; }
|
||||
private static void SetFill(Ellipse? e, IBrush br) { if (e != null && !ReferenceEquals(e.Fill, br)) e.Fill = br; }
|
||||
|
||||
private static string Loc(double v, char pos, char neg)
|
||||
=> v.ToString("F1", CultureInfo.InvariantCulture).TrimStart('-') + (v >= 0 ? pos : neg);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,54 +2,29 @@
|
|||
// RynthCore.Engine — UI/Panels/RynthTrackerPanel.cs
|
||||
// Session-stats panel backed by the RynthTracker plugin (RynthSuite).
|
||||
//
|
||||
// Bridge exports (resolved from the RynthTracker plugin DLL via GetProcAddress):
|
||||
// RynthTrackerGetSnapshotJson() → ANSI JSON object, polled every 500ms
|
||||
// RynthTrackerReset() → resets session counters + timer
|
||||
// Data comes from UiDataHub (UiSources.Tracker), which is the only caller of
|
||||
// RynthTrackerGetSnapshotJson: the export frees its previous buffer on each
|
||||
// call, so this face and the ImGui face (ImGui/Panels/P1Faces.cs) must never
|
||||
// call it themselves. Reset goes through the hub too. The background opacity
|
||||
// is shared with the ImGui face (TrackerSettings).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class RynthTrackerPanel
|
||||
{
|
||||
// ── P/Invoke ──────────────────────────────────────────────────────────────
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetSnapshotJsonFn();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ResetFn();
|
||||
|
||||
// ── Bridge state ──────────────────────────────────────────────────────────
|
||||
|
||||
private static GetSnapshotJsonFn? _getSnapshotJson;
|
||||
private static ResetFn? _reset;
|
||||
private static bool _bindingLogged;
|
||||
|
||||
// ── Persisted settings ────────────────────────────────────────────────────
|
||||
|
||||
private static byte _bgAlpha = 0xCC; // ~80% default
|
||||
|
||||
// ── Panel construction ────────────────────────────────────────────────────
|
||||
|
||||
internal static Control Create()
|
||||
{
|
||||
LoadSettings();
|
||||
TryBind();
|
||||
|
||||
// ── Value TextBlocks (updated by poll timer) ───────────────────
|
||||
// Rates first — most important at the top when panel is tiny.
|
||||
|
|
@ -64,7 +39,7 @@ internal static class RynthTrackerPanel
|
|||
var deathVal = Val();
|
||||
|
||||
// ── Background brush — only this changes with the slider ───────
|
||||
SolidColorBrush MakeBg() => new(Color.FromArgb(_bgAlpha, 0x0A, 0x12, 0x1A));
|
||||
SolidColorBrush MakeBg() => new(Color.FromArgb(TrackerSettings.BgAlpha, 0x0A, 0x12, 0x1A));
|
||||
var stack = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Vertical,
|
||||
|
|
@ -76,7 +51,7 @@ internal static class RynthTrackerPanel
|
|||
{
|
||||
Minimum = 0,
|
||||
Maximum = 100,
|
||||
Value = Math.Round(_bgAlpha / 2.55),
|
||||
Value = Math.Round(TrackerSettings.BgAlpha / 2.55),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(4, 0, 4, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
|
|
@ -84,9 +59,8 @@ internal static class RynthTrackerPanel
|
|||
};
|
||||
opacitySlider.ValueChanged += (_, e) =>
|
||||
{
|
||||
_bgAlpha = (byte)Math.Round(e.NewValue * 2.55);
|
||||
TrackerSettings.SetBgAlpha((byte)Math.Round(e.NewValue * 2.55), save: true);
|
||||
stack.Background = MakeBg();
|
||||
SaveSettings();
|
||||
};
|
||||
|
||||
// ── Reset button ───────────────────────────────────────────────
|
||||
|
|
@ -101,7 +75,7 @@ internal static class RynthTrackerPanel
|
|||
BorderThickness = new Thickness(1),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
};
|
||||
resetBtn.Click += (_, _) => _reset?.Invoke();
|
||||
resetBtn.Click += (_, _) => UiSources.Tracker.RequestReset();
|
||||
|
||||
// ── Title row: [Tracker] [===slider===] [R] ────────────────────
|
||||
var titleText = new TextBlock
|
||||
|
|
@ -136,51 +110,35 @@ internal static class RynthTrackerPanel
|
|||
var root = new Grid { ClipToBounds = true };
|
||||
root.Children.Add(stack);
|
||||
|
||||
// ── Poll timer (500ms) ─────────────────────────────────────────
|
||||
// ── Hub snapshot (500ms) ───────────────────────────────────────
|
||||
var values = new[] { sessionVal, xpHrVal, lumHrVal, killHrVal, xpVal, lumVal, killVal, xpkVal, deathVal };
|
||||
long seen = -1;
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getSnapshotJson == null) { TryBind(); return; }
|
||||
|
||||
IntPtr ptr = _getSnapshotJson();
|
||||
if (ptr == IntPtr.Zero) return;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var r = doc.RootElement;
|
||||
|
||||
double ss = r.TryGetProperty("ss", out var v) ? v.GetDouble() : 0;
|
||||
long xt = r.TryGetProperty("xt", out v) ? v.GetInt64() : 0;
|
||||
long xh = r.TryGetProperty("xh", out v) ? v.GetInt64() : 0;
|
||||
long lt = r.TryGetProperty("lt", out v) ? v.GetInt64() : 0;
|
||||
long lh = r.TryGetProperty("lh", out v) ? v.GetInt64() : 0;
|
||||
int kt = r.TryGetProperty("kt", out v) ? v.GetInt32() : 0;
|
||||
double kh = r.TryGetProperty("kh", out v) ? v.GetDouble() : 0;
|
||||
long xk = r.TryGetProperty("xk", out v) ? v.GetInt64() : 0;
|
||||
int dt = r.TryGetProperty("dt", out v) ? v.GetInt32() : 0;
|
||||
|
||||
var ic = System.Globalization.CultureInfo.InvariantCulture;
|
||||
sessionVal.Text = FormatTime(ss);
|
||||
xpHrVal.Text = FormatNum(xh);
|
||||
lumHrVal.Text = FormatNum(lh);
|
||||
killHrVal.Text = kh.ToString("F1", ic);
|
||||
xpVal.Text = FormatNum(xt);
|
||||
lumVal.Text = FormatNum(lt);
|
||||
killVal.Text = kt.ToString();
|
||||
xpkVal.Text = FormatNum(xk);
|
||||
deathVal.Text = dt.ToString();
|
||||
}
|
||||
catch { }
|
||||
var snap = UiSources.Tracker.Current;
|
||||
if (snap == null || snap.Version == seen) return;
|
||||
seen = snap.Version;
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
values[i].Text = snap.Value.Values[i];
|
||||
// Opacity may have been changed by the ImGui face.
|
||||
stack.Background = MakeBg();
|
||||
};
|
||||
timer.Start();
|
||||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
// must restart on attach: drag/resize fires Detached→Attached. The hub
|
||||
// only polls the plugin while some face is subscribed.
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Tracker.Subscribe();
|
||||
UiSources.Tracker.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Tracker.Unsubscribe();
|
||||
};
|
||||
|
||||
return root;
|
||||
}
|
||||
|
|
@ -216,87 +174,4 @@ internal static class RynthTrackerPanel
|
|||
Foreground = Brushes.White,
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
};
|
||||
|
||||
private static string FormatTime(double totalSeconds)
|
||||
{
|
||||
var ts = TimeSpan.FromSeconds(totalSeconds);
|
||||
return ts.TotalHours >= 1
|
||||
? $"{(int)ts.TotalHours}:{ts.Minutes:D2}:{ts.Seconds:D2}"
|
||||
: $"{ts.Minutes}:{ts.Seconds:D2}";
|
||||
}
|
||||
|
||||
private static string FormatNum(long value)
|
||||
{
|
||||
if (value == 0) return "0";
|
||||
bool neg = value < 0;
|
||||
string s = (neg ? -value : value).ToString();
|
||||
var sb = new System.Text.StringBuilder(s.Length + s.Length / 3);
|
||||
int offset = s.Length % 3;
|
||||
for (int i = 0; i < s.Length; i++)
|
||||
{
|
||||
if (i > 0 && (i - offset) % 3 == 0) sb.Append(',');
|
||||
sb.Append(s[i]);
|
||||
}
|
||||
return neg ? "-" + sb : sb.ToString();
|
||||
}
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static RynthTrackerPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getSnapshotJson = null;
|
||||
_reset = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthTracker", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
_getSnapshotJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthTrackerGetSnapshotJson");
|
||||
_reset ??= Bind<ResetFn>(plugin, "RynthTrackerReset");
|
||||
|
||||
if (!_bindingLogged && _getSnapshotJson != null)
|
||||
{
|
||||
_bindingLogged = true;
|
||||
RynthLog.UI("RynthTrackerPanel: bound RynthTracker plugin exports.");
|
||||
}
|
||||
}
|
||||
|
||||
private static T? Bind<T>(LoadedPlugin plugin, string exportName) where T : Delegate
|
||||
{
|
||||
IntPtr addr = GetProcAddress(plugin.ModuleHandle, exportName);
|
||||
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
// ── Settings persistence ──────────────────────────────────────────────────
|
||||
|
||||
private static string SettingsPath =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "rynthtracker_settings.json");
|
||||
|
||||
private static void LoadSettings()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
if (!File.Exists(path)) return;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
if (doc.RootElement.TryGetProperty("bgAlpha", out var v))
|
||||
_bgAlpha = (byte)Math.Clamp(v.GetInt32(), 0, 255);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void SaveSettings()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,19 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine — UI/Panels/RynthVisionPanel.cs
|
||||
// Avalonia settings panel for the RynthVision plugin (RynthSuite). Bridges to
|
||||
// the plugin via GetProcAddress on its DLL: reads settings JSON to populate
|
||||
// controls and pushes changes back. Replaces the abandoned in-plugin ImGui UI.
|
||||
// Avalonia settings panel for the RynthVision plugin (RynthSuite): reads the
|
||||
// settings JSON to populate controls and pushes changes back.
|
||||
//
|
||||
// Bridge exports (resolved from the RynthVision plugin DLL):
|
||||
// RynthVisionGetSettingsJson() → ANSI JSON of current settings
|
||||
// RynthVisionSetSettings(char* json) → apply + persist settings
|
||||
// RynthVisionInspectTerrain() → log terrain types under the player
|
||||
// Data goes through UiDataHub (UI/Data/VisionData.cs): UiSources.Vision polls
|
||||
// RynthVisionGetSettingsJson on the pump thread; VisionCommands saves
|
||||
// (RynthVisionSetSettings) and runs RynthVisionInspectTerrain there. The
|
||||
// ImGui face (ImGui/Panels/VisionFace.cs) reads the same snapshot. Each
|
||||
// change pushes only its own field, like the ImGui face.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
|
|
@ -23,30 +22,12 @@ using Avalonia.Media;
|
|||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
internal static class RynthVisionPanel
|
||||
{
|
||||
// ── P/Invoke ──────────────────────────────────────────────────────────────
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetSettingsJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetSettingsFn(IntPtr ansiJson);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void InspectFn();
|
||||
|
||||
// ── Bridge state ──────────────────────────────────────────────────────────
|
||||
|
||||
private static GetSettingsJsonFn? _getSettings;
|
||||
private static SetSettingsFn? _setSettings;
|
||||
private static InspectFn? _inspect;
|
||||
private static bool _bindingLogged;
|
||||
|
||||
// ── Controls (Avalonia UI thread only) ─────────────────────────────────────
|
||||
|
||||
private static CheckBox? _cbRadar, _cbSlopes, _cbWater, _cbWaterAnyCorner, _cbWaterImpassableOnly;
|
||||
|
|
@ -62,6 +43,14 @@ internal static class RynthVisionPanel
|
|||
private static bool _populated;
|
||||
private static int _createCounter;
|
||||
|
||||
// The panel's one retry timer (see Create). It also re-runs Populate after
|
||||
// a water-types save: the plugin may normalise the list (empty resets to
|
||||
// the defaults), so the box is refreshed from the first snapshot newer
|
||||
// than _populateAfterVersion.
|
||||
private static DispatcherTimer? _populateTimer;
|
||||
private static int _populateRetries;
|
||||
private static long _populateAfterVersion = -1;
|
||||
|
||||
// ── Panel construction ──────────────────────────────────────────────────────
|
||||
|
||||
internal static Control Create()
|
||||
|
|
@ -79,6 +68,7 @@ internal static class RynthVisionPanel
|
|||
// Populate flips _suppressPush back to false in its finally block.
|
||||
_populated = false;
|
||||
_suppressPush = true;
|
||||
_populateAfterVersion = -1;
|
||||
|
||||
int createN = System.Threading.Interlocked.Increment(ref _createCounter);
|
||||
RynthLog.UI($"RynthVisionPanel.Create #{createN}: starting (_populated reset, _suppressPush=true)");
|
||||
|
|
@ -89,43 +79,41 @@ internal static class RynthVisionPanel
|
|||
_cbRadar = AddCheck(root, "Radar range ring");
|
||||
_cbSlopes = AddCheck(root, "Unclimbable slopes");
|
||||
_cbWater = AddCheck(root, "Impassable water");
|
||||
var dungeon = AddCheck(root, "Dungeon lighting (planned)");
|
||||
dungeon.IsEnabled = false;
|
||||
_cbRadar.IsCheckedChanged += (_, _) => Push();
|
||||
_cbSlopes.IsCheckedChanged += (_, _) => Push();
|
||||
_cbWater.IsCheckedChanged += (_, _) => Push();
|
||||
_cbRadar.IsCheckedChanged += (_, _) => Push(VisionKeys.Radar);
|
||||
_cbSlopes.IsCheckedChanged += (_, _) => Push(VisionKeys.Slopes);
|
||||
_cbWater.IsCheckedChanged += (_, _) => Push(VisionKeys.Water);
|
||||
|
||||
root.Children.Add(Header("Colors (hex AARRGGBB)"));
|
||||
(_tbSlope, _swSlope) = AddColorRow(root, "Slope", () => _slopeColor, c => _slopeColor = c);
|
||||
(_tbWater, _swWater) = AddColorRow(root, "Water", () => _waterColor, c => _waterColor = c);
|
||||
(_tbRadar, _swRadar) = AddColorRow(root, "Radar", () => _radarColor, c => _radarColor = c);
|
||||
(_tbSlope, _swSlope) = AddColorRow(root, "Slope", VisionKeys.SlopeColor, () => _slopeColor, c => _slopeColor = c);
|
||||
(_tbWater, _swWater) = AddColorRow(root, "Water", VisionKeys.WaterColor, () => _waterColor, c => _waterColor = c);
|
||||
(_tbRadar, _swRadar) = AddColorRow(root, "Radar", VisionKeys.RadarColor, () => _radarColor, c => _radarColor = c);
|
||||
|
||||
root.Children.Add(Header("Tuning"));
|
||||
(_slRange, _) = AddSlider(root, "Radar range", 24, 300, 0, false);
|
||||
(_slThick, _) = AddSlider(root, "Ring thickness", 0.5, 6, 1, false);
|
||||
(_slHeight, _) = AddSlider(root, "Ring height (m)",0.5, 30, 1, false);
|
||||
(_slSlopeR, _) = AddSlider(root, "Slope radius (cells)", 1, 24, 0, true);
|
||||
(_slSlopeFloor, _)= AddSlider(root, "Slope floor Z", 0.30, 0.95, 3, false);
|
||||
(_slSlopeBias, _) = AddSlider(root, "Slope height bias (m)",0.00, 1.00, 2, false);
|
||||
(_slWaterR, _) = AddSlider(root, "Water radius (cells)", 1, 24, 0, true);
|
||||
(_slRange, _) = AddSlider(root, "Radar range", VisionKeys.RadarRange, 24, 300, 0, false);
|
||||
(_slThick, _) = AddSlider(root, "Ring thickness", VisionKeys.RingThick, 0.5, 6, 1, false);
|
||||
(_slHeight, _) = AddSlider(root, "Ring height (m)",VisionKeys.RingHeight, 0.5, 30, 1, false);
|
||||
(_slSlopeR, _) = AddSlider(root, "Slope radius (cells)", VisionKeys.SlopeRadius, 1, 24, 0, true);
|
||||
(_slSlopeFloor, _)= AddSlider(root, "Slope floor Z", VisionKeys.SlopeFloorZ, 0.30, 0.95, 3, false);
|
||||
(_slSlopeBias, _) = AddSlider(root, "Slope height bias (m)",VisionKeys.SlopeBias, 0.00, 1.00, 2, false);
|
||||
(_slWaterR, _) = AddSlider(root, "Water radius (cells)", VisionKeys.WaterRadius, 1, 24, 0, true);
|
||||
|
||||
root.Children.Add(Header("Water terrain types"));
|
||||
_cbWaterAnyCorner = AddCheck(root, "Highlight cell if ANY corner is water (else all four)");
|
||||
_cbWaterAnyCorner.IsCheckedChanged += (_, _) => Push();
|
||||
_cbWaterAnyCorner.IsCheckedChanged += (_, _) => Push(VisionKeys.WaterAnyCorner);
|
||||
_cbWaterImpassableOnly = AddCheck(root, "Only paint water cells with an unwalkable triangle (real impassable)");
|
||||
_cbWaterImpassableOnly.IsCheckedChanged += (_, _) => Push();
|
||||
_cbWaterImpassableOnly.IsCheckedChanged += (_, _) => Push(VisionKeys.WaterImpassableOnly);
|
||||
_tbWaterTypes = new TextBox { Watermark = "18,19,20", FontSize = 11, MinWidth = 120 };
|
||||
_tbWaterTypes.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
|
||||
_tbWaterTypes.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; Push(); };
|
||||
_tbWaterTypes.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; Push(VisionKeys.WaterTypes); };
|
||||
var applyBtn = new Button { Content = "Apply", FontSize = 11, Margin = new Thickness(4, 0, 0, 0) };
|
||||
applyBtn.Click += (_, _) => Push();
|
||||
applyBtn.Click += (_, _) => Push(VisionKeys.WaterTypes);
|
||||
var wtRow = new StackPanel { Orientation = Orientation.Horizontal };
|
||||
wtRow.Children.Add(_tbWaterTypes);
|
||||
wtRow.Children.Add(applyBtn);
|
||||
root.Children.Add(wtRow);
|
||||
|
||||
var inspectBtn = new Button { Content = "Log terrain types here", FontSize = 11, Margin = new Thickness(0, 4, 0, 0) };
|
||||
inspectBtn.Click += (_, _) => { TryBind(); _inspect?.Invoke(); };
|
||||
inspectBtn.Click += (_, _) => VisionCommands.Inspect();
|
||||
root.Children.Add(inspectBtn);
|
||||
|
||||
// Bind + populate once the plugin DLL is loaded AND the plugin has
|
||||
|
|
@ -136,14 +124,15 @@ internal static class RynthVisionPanel
|
|||
// Retries every 500 ms until Populate succeeds (returns true) or the
|
||||
// panel is closed. Caps at 60 retries (~30 s) so we don't spin forever
|
||||
// if the plugin never initializes.
|
||||
int retries = 0;
|
||||
_populateRetries = 0;
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
|
||||
_populateTimer?.Stop();
|
||||
_populateTimer = timer;
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_populated) { timer.Stop(); return; }
|
||||
if (++retries > 60) { timer.Stop(); RynthLog.UI("RynthVisionPanel: gave up populating after 30s"); return; }
|
||||
TryBind();
|
||||
if (_getSettings != null && Populate())
|
||||
if (++_populateRetries > 60) { timer.Stop(); RynthLog.UI("RynthVisionPanel: gave up populating after 30s"); return; }
|
||||
if (Populate())
|
||||
{
|
||||
_populated = true;
|
||||
timer.Stop();
|
||||
|
|
@ -151,7 +140,19 @@ internal static class RynthVisionPanel
|
|||
};
|
||||
timer.Start();
|
||||
|
||||
return new ScrollViewer { Content = root };
|
||||
var scroll = new ScrollViewer { Content = root };
|
||||
scroll.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Vision.Subscribe();
|
||||
UiSources.Vision.RequestRefresh();
|
||||
if (!_populated && !timer.IsEnabled) { _populateRetries = 0; timer.Start(); }
|
||||
};
|
||||
scroll.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Vision.Unsubscribe();
|
||||
};
|
||||
return scroll;
|
||||
}
|
||||
|
||||
// ── Control factories ───────────────────────────────────────────────────────
|
||||
|
|
@ -172,7 +173,7 @@ internal static class RynthVisionPanel
|
|||
return cb;
|
||||
}
|
||||
|
||||
private static (Slider, TextBlock) AddSlider(StackPanel parent, string name, double min, double max, int decimals, bool snap)
|
||||
private static (Slider, TextBlock) AddSlider(StackPanel parent, string name, string key, double min, double max, int decimals, bool snap)
|
||||
{
|
||||
var label = new TextBlock { FontSize = 11, Foreground = Brushes.White, Text = name + ":" };
|
||||
var slider = new Slider { Minimum = min, Maximum = max, Width = 170, VerticalAlignment = VerticalAlignment.Center };
|
||||
|
|
@ -212,7 +213,7 @@ internal static class RynthVisionPanel
|
|||
syncing = true;
|
||||
box.Text = s;
|
||||
syncing = false;
|
||||
Push();
|
||||
Push(key);
|
||||
};
|
||||
box.GotFocus += (_, _) =>
|
||||
{
|
||||
|
|
@ -237,14 +238,14 @@ internal static class RynthVisionPanel
|
|||
box.Text = s;
|
||||
label.Text = $"{name}: {s}";
|
||||
syncing = false;
|
||||
Push();
|
||||
Push(key);
|
||||
}
|
||||
};
|
||||
|
||||
return (slider, label);
|
||||
}
|
||||
|
||||
private static (TextBox, Border) AddColorRow(StackPanel parent, string name, Func<uint> get, Action<uint> set)
|
||||
private static (TextBox, Border) AddColorRow(StackPanel parent, string name, string key, Func<uint> get, Action<uint> set)
|
||||
{
|
||||
var lbl = new TextBlock { Text = name, FontSize = 11, Foreground = Brushes.White, Width = 44, VerticalAlignment = VerticalAlignment.Center };
|
||||
var tb = new TextBox { FontSize = 11, Width = 92, FontFamily = new FontFamily("Consolas,monospace") };
|
||||
|
|
@ -259,46 +260,12 @@ internal static class RynthVisionPanel
|
|||
tb.LostFocus += (_, _) =>
|
||||
{
|
||||
Win32Backend.AvaloniaTextInputActive = false;
|
||||
if (TryParseHex(tb.Text, out uint c)) { set(c); sw.Background = ToBrush(c); Push(); }
|
||||
if (TryParseHex(tb.Text, out uint c)) { set(c); sw.Background = ToBrush(c); Push(key); }
|
||||
else tb.Text = get().ToString("X8"); // revert on bad input
|
||||
};
|
||||
return (tb, sw);
|
||||
}
|
||||
|
||||
// ── Plugin binding ────────────────────────────────────────────────────────
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static RynthVisionPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getSettings = null;
|
||||
_setSettings = null;
|
||||
_inspect = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthVision", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
_getSettings ??= Bind<GetSettingsJsonFn>(plugin, "RynthVisionGetSettingsJson");
|
||||
_setSettings ??= Bind<SetSettingsFn>(plugin, "RynthVisionSetSettings");
|
||||
_inspect ??= Bind<InspectFn>(plugin, "RynthVisionInspectTerrain");
|
||||
|
||||
if (!_bindingLogged && _getSettings != null)
|
||||
{
|
||||
_bindingLogged = true;
|
||||
RynthLog.UI("RynthVisionPanel: bound RynthVision plugin exports.");
|
||||
}
|
||||
}
|
||||
|
||||
private static T? Bind<T>(LoadedPlugin plugin, string export) where T : Delegate
|
||||
{
|
||||
IntPtr addr = GetProcAddress(plugin.ModuleHandle, export);
|
||||
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
// ── Sync ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -310,10 +277,9 @@ internal static class RynthVisionPanel
|
|||
/// </summary>
|
||||
private static bool Populate()
|
||||
{
|
||||
if (_getSettings == null) return false;
|
||||
IntPtr ptr = _getSettings();
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
var snap = UiSources.Vision.Current;
|
||||
if (snap == null || snap.Version <= _populateAfterVersion) return false;
|
||||
string? json = snap.Value.Json;
|
||||
if (string.IsNullOrEmpty(json) || json == "{}") return false;
|
||||
|
||||
RynthLog.UI($"RynthVisionPanel.Populate: applying JSON ({json.Length} chars): {json}");
|
||||
|
|
@ -352,46 +318,59 @@ internal static class RynthVisionPanel
|
|||
return true;
|
||||
}
|
||||
|
||||
private static void Push()
|
||||
/// <summary>
|
||||
/// Saves just the field that changed (<paramref name="key"/>, a
|
||||
/// <see cref="VisionKeys"/> constant) from its control, so values changed
|
||||
/// elsewhere since Populate (a /rv command, the ImGui face) aren't
|
||||
/// written back over.
|
||||
/// </summary>
|
||||
private static void Push(string key)
|
||||
{
|
||||
if (_suppressPush)
|
||||
{
|
||||
RynthLog.UI("RynthVisionPanel.Push: SUPPRESSED (Populate in flight or panel not yet ready)");
|
||||
return;
|
||||
}
|
||||
if (_setSettings == null)
|
||||
{
|
||||
RynthLog.UI("RynthVisionPanel.Push: SKIPPED (plugin not yet bound)");
|
||||
return;
|
||||
}
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder(256);
|
||||
sb.Append('{');
|
||||
sb.Append("\"radar\":").Append(_cbRadar?.IsChecked == true ? 1 : 0).Append(',');
|
||||
sb.Append("\"slopes\":").Append(_cbSlopes?.IsChecked == true ? 1 : 0).Append(',');
|
||||
sb.Append("\"water\":").Append(_cbWater?.IsChecked == true ? 1 : 0).Append(',');
|
||||
sb.Append("\"slopeColor\":").Append(_slopeColor).Append(',');
|
||||
sb.Append("\"waterColor\":").Append(_waterColor).Append(',');
|
||||
sb.Append("\"radarColor\":").Append(_radarColor).Append(',');
|
||||
sb.Append("\"radarRange\":").Append((_slRange?.Value ?? 192).ToString("R", ci)).Append(',');
|
||||
sb.Append("\"ringThick\":").Append((_slThick?.Value ?? 2).ToString("R", ci)).Append(',');
|
||||
sb.Append("\"ringHeight\":").Append((_slHeight?.Value ?? 3).ToString("R", ci)).Append(',');
|
||||
sb.Append("\"slopeRadius\":").Append((int)(_slSlopeR?.Value ?? 12)).Append(',');
|
||||
sb.Append("\"slopeFloorZ\":").Append((_slSlopeFloor?.Value ?? 0.664).ToString("R", ci)).Append(',');
|
||||
sb.Append("\"slopeBias\":").Append((_slSlopeBias?.Value ?? 0.15).ToString("R", ci)).Append(',');
|
||||
sb.Append("\"waterRadius\":").Append((int)(_slWaterR?.Value ?? 12)).Append(',');
|
||||
sb.Append("\"waterAnyCorner\":").Append(_cbWaterAnyCorner?.IsChecked == true ? 1 : 0).Append(',');
|
||||
sb.Append("\"waterImpassableOnly\":").Append(_cbWaterImpassableOnly?.IsChecked == true ? 1 : 0).Append(',');
|
||||
sb.Append("\"waterTypes\":[").Append(CleanCsv(_tbWaterTypes?.Text)).Append(']');
|
||||
sb.Append('}');
|
||||
string? value = key switch
|
||||
{
|
||||
VisionKeys.Radar => Flag(_cbRadar),
|
||||
VisionKeys.Slopes => Flag(_cbSlopes),
|
||||
VisionKeys.Water => Flag(_cbWater),
|
||||
VisionKeys.WaterAnyCorner => Flag(_cbWaterAnyCorner),
|
||||
VisionKeys.WaterImpassableOnly => Flag(_cbWaterImpassableOnly),
|
||||
VisionKeys.SlopeColor => _slopeColor.ToString(ci),
|
||||
VisionKeys.WaterColor => _waterColor.ToString(ci),
|
||||
VisionKeys.RadarColor => _radarColor.ToString(ci),
|
||||
VisionKeys.RadarRange => _slRange?.Value.ToString("R", ci),
|
||||
VisionKeys.RingThick => _slThick?.Value.ToString("R", ci),
|
||||
VisionKeys.RingHeight => _slHeight?.Value.ToString("R", ci),
|
||||
VisionKeys.SlopeRadius => _slSlopeR != null ? ((int)_slSlopeR.Value).ToString(ci) : null,
|
||||
VisionKeys.SlopeFloorZ => _slSlopeFloor?.Value.ToString("R", ci),
|
||||
VisionKeys.SlopeBias => _slSlopeBias?.Value.ToString("R", ci),
|
||||
VisionKeys.WaterRadius => _slWaterR != null ? ((int)_slWaterR.Value).ToString(ci) : null,
|
||||
// Empty resets to the defaults in the plugin; the republish after
|
||||
// the save repopulates the box.
|
||||
VisionKeys.WaterTypes => "[" + CleanCsv(_tbWaterTypes?.Text) + "]",
|
||||
_ => null,
|
||||
};
|
||||
if (value == null) return;
|
||||
|
||||
string outJson = sb.ToString();
|
||||
RynthLog.UI($"RynthVisionPanel.Push: writing JSON ({outJson.Length} chars): {outJson}");
|
||||
IntPtr p = Marshal.StringToHGlobalAnsi(outJson);
|
||||
try { _setSettings(p); }
|
||||
finally { Marshal.FreeHGlobal(p); }
|
||||
string outJson = "{\"" + key + "\":" + value + "}";
|
||||
RynthLog.UI($"RynthVisionPanel.Push: writing JSON: {outJson}");
|
||||
VisionCommands.Save(outJson);
|
||||
|
||||
if (key == VisionKeys.WaterTypes)
|
||||
{
|
||||
_populateAfterVersion = UiSources.Vision.Current?.Version ?? 0;
|
||||
_populated = false;
|
||||
_populateRetries = 0;
|
||||
_populateTimer?.Start();
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Flag(CheckBox? cb) => cb == null ? null : (cb.IsChecked == true ? "1" : "0");
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static void SetColor(TextBox? tb, Border? sw, uint argb)
|
||||
|
|
|
|||
|
|
@ -2,12 +2,10 @@
|
|||
// RynthCore.Engine — UI/Panels/SettingsPanel.cs
|
||||
// Avalonia replica of LegacyAdvancedSettingsUi (RynthSuite plugin).
|
||||
//
|
||||
// 11 tabs: Display | UI | Misc | Recharge | Melee Combat | Spell Combat |
|
||||
// Ranges | Navigation | Buffing | Crafting | Looting
|
||||
//
|
||||
// Plugin exports used:
|
||||
// RynthPluginGetSettingsJson → polled every 5s for external edits
|
||||
// RynthPluginSetSettingsJson → immediate write-back on any control change
|
||||
// Tabs and rows come from SettingsSchema (UI/Data/SettingsData.cs), which
|
||||
// the ImGui face draws too: add a setting there, not here. Data goes through
|
||||
// UiDataHub (UiSources.Settings, SettingsCommands.Save), so the plugin's
|
||||
// exports run on the pump thread instead of this UI thread.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -25,26 +23,12 @@ using Avalonia.Media;
|
|||
using Avalonia.Threading;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
[JsonSerializable(typeof(SettingsPanel.Settings))]
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
|
||||
internal partial class SettingsPanelJsonContext : JsonSerializerContext { }
|
||||
|
||||
internal static class SettingsPanel
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetSettingsJsonFn();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void SetSettingsJsonFn(IntPtr ansiJson);
|
||||
|
||||
private static GetSettingsJsonFn? _getSettingsJson;
|
||||
private static SetSettingsJsonFn? _setSettingsJson;
|
||||
|
||||
// ── Color palette (shared with other panels) ─────────────────────────────
|
||||
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
|
||||
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
|
||||
|
|
@ -59,181 +43,12 @@ internal static class SettingsPanel
|
|||
private static readonly IBrush ColToggleOff = new SolidColorBrush(Color.FromRgb(0x33, 0x44, 0x55));
|
||||
private static readonly IBrush ColTabActive = new SolidColorBrush(Color.FromRgb(0x1A, 0x2E, 0x42));
|
||||
|
||||
private static readonly string[] Tabs =
|
||||
{ "Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
|
||||
"Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring" };
|
||||
|
||||
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
|
||||
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
|
||||
private static readonly string[] MovementModes = { "Legacy (Autorun)", "Tier 1 (CM_Movement)", "Tier 2 (MoveToPosition)" };
|
||||
|
||||
// ── Settings mirror (matches SettingsBridgePayload on plugin side) ────────
|
||||
internal sealed class Settings
|
||||
{
|
||||
// Display
|
||||
public bool ShowTargetStaminaMana { get; set; }
|
||||
// UI
|
||||
public bool SuppressRetailRadar { get; set; }
|
||||
public bool ShowRynthRadar { get; set; }
|
||||
public bool RadarClickThrough { get; set; }
|
||||
// NOTE: retail-chatbox suppression intentionally removed here — it is owned by the
|
||||
// RynthChat plugin ("Hide retail chat" in the RynthChat panel's gear menu). Routing it
|
||||
// through RynthAi's settings push fought that toggle and didn't work. See RynthChatPanel.
|
||||
public bool ShowRynthChat { get; set; }
|
||||
public bool ChatClickThrough { get; set; }
|
||||
public bool SuppressRetailPowerbar { get; set; }
|
||||
// Misc
|
||||
public bool EnableFPSLimit { get; set; }
|
||||
public int TargetFPSFocused { get; set; } = 60;
|
||||
public int TargetFPSBackground { get; set; } = 30;
|
||||
public bool EnableAutocram { get; set; }
|
||||
public bool PeaceModeWhenIdle { get; set; }
|
||||
public bool StartMacroOnLogin { get; set; }
|
||||
public bool PatrolOnLogin { get; set; }
|
||||
public bool EnableRaycasting { get; set; }
|
||||
public bool UseArcs { get; set; }
|
||||
public float BowArcVelocity { get; set; } = 25f;
|
||||
public float MissileArcClearance { get; set; } = 0.5f;
|
||||
// Vendoring (RynthAi AutoVendor; defaults match LegacyUiSettings)
|
||||
public bool AutoVendorEnabled { get; set; }
|
||||
public bool AutoVendorEnableBuying { get; set; } = true;
|
||||
public bool AutoVendorEnableSelling { get; set; } = true;
|
||||
public bool AutoVendorTestMode { get; set; } = true;
|
||||
public bool AutoVendorThink { get; set; }
|
||||
public bool AutoVendorShowMerchantInfo { get; set; } = true;
|
||||
public bool AutoVendorOnlyFromMainPack { get; set; }
|
||||
public int AutoVendorTries { get; set; } = 4;
|
||||
public int AutoVendorTriesTime { get; set; } = 5000;
|
||||
public bool LosDebugLog { get; set; }
|
||||
public float CrossbowArcVelocity { get; set; } = 40f;
|
||||
public float AtlatlArcVelocity { get; set; } = 22f;
|
||||
public float MagicArcVelocity { get; set; } = 25f;
|
||||
public int BlacklistAttempts { get; set; } = 3;
|
||||
public int BlacklistTimeoutSec { get; set; } = 30;
|
||||
// Not shown in this panel, but carried so a save doesn't send them missing:
|
||||
// RynthAi applied the missing value as 0 on every panel click (2026-09-27).
|
||||
public int BlacklistCastSettleMs { get; set; } = 1500;
|
||||
public int MonsterDisengageRange { get; set; }
|
||||
public int TargetNoProgressTimeoutSec { get; set; }
|
||||
public int GiveQueueIntervalMs { get; set; } = 150;
|
||||
// Recharge
|
||||
public int HealAt { get; set; } = 60;
|
||||
public int RestamAt { get; set; } = 30;
|
||||
public int GetManaAt { get; set; } = 40;
|
||||
public int TopOffHP { get; set; } = 95;
|
||||
public int TopOffStam { get; set; } = 95;
|
||||
public int TopOffMana { get; set; } = 95;
|
||||
public int HealOthersAt { get; set; } = 50;
|
||||
public int RestamOthersAt { get; set; } = 10;
|
||||
public int InfuseOthersAt { get; set; } = 10;
|
||||
// Melee Combat
|
||||
public bool UseRecklessness { get; set; }
|
||||
public int MeleeAttackPower { get; set; } = -1;
|
||||
public int MeleeAttackHeight { get; set; } = 1;
|
||||
public int MissileAttackPower { get; set; } = -1;
|
||||
public int MissileAttackHeight { get; set; } = 1;
|
||||
public bool UseNativeAttack { get; set; } = true;
|
||||
public bool SummonPets { get; set; }
|
||||
public int PetMinMonsters { get; set; } = 1;
|
||||
// Spell Combat
|
||||
public int SpellCastIntervalMs { get; set; } = 400;
|
||||
public int AttackSpellIntervalMs { get; set; } = 1500;
|
||||
public bool CastDispelSelf { get; set; }
|
||||
public int MinRingTargets { get; set; } = 4;
|
||||
public int MinSkillLevelTier1 { get; set; } = 35;
|
||||
public int MinSkillLevelTier2 { get; set; } = 85;
|
||||
public int MinSkillLevelTier3 { get; set; } = 135;
|
||||
public int MinSkillLevelTier4 { get; set; } = 185;
|
||||
public int MinSkillLevelTier5 { get; set; } = 235;
|
||||
public int MinSkillLevelTier6 { get; set; } = 285;
|
||||
public int MinSkillLevelTier7 { get; set; } = 335;
|
||||
public int MinSkillLevelTier8 { get; set; } = 435;
|
||||
// Ranges
|
||||
public int MonsterRange { get; set; } = 50;
|
||||
public int RingRange { get; set; } = 5;
|
||||
public int ApproachRange { get; set; } = 4;
|
||||
public double CorpseApproachRangeMax { get; set; } = 10.0;
|
||||
public double CorpseApproachRangeMin { get; set; } = 2.0;
|
||||
// Navigation
|
||||
public bool BoostNavPriority { get; set; }
|
||||
public float FollowNavMin { get; set; } = 1.5f;
|
||||
public float NavRingThickness { get; set; } = 6f;
|
||||
public float NavLineThickness { get; set; } = 6f;
|
||||
public float NavHeightOffset { get; set; } = 0.05f;
|
||||
public float NavSlopeSink { get; set; } = 1.5f;
|
||||
public bool ShowTerrainPassability { get; set; } = true;
|
||||
public bool OpenDoors { get; set; }
|
||||
public float OpenDoorRange { get; set; } = 5f;
|
||||
public bool AutoUnlockDoors { get; set; }
|
||||
public int MovementMode { get; set; }
|
||||
public float NavStopTurnAngle { get; set; } = 20f;
|
||||
public float NavResumeTurnAngle { get; set; } = 10f;
|
||||
public float NavDeadZone { get; set; } = 4f;
|
||||
public float NavSweepMult { get; set; } = 2.5f;
|
||||
public float NavLookaheadYards { get; set; } = 4f;
|
||||
public float NavShortcutYards { get; set; } = 1f;
|
||||
public float NavTurnRateDegPerSec { get; set; } = 270f;
|
||||
public float NavTier1TurnSpeed { get; set; } = 3f;
|
||||
public float PostPortalDelaySec { get; set; } = 4f;
|
||||
public float T2Speed { get; set; } = 1f;
|
||||
public float T2WalkWithinYd { get; set; } = 5f;
|
||||
public float T2DistanceTo { get; set; } = 0.5f;
|
||||
public float T2ReissueMs { get; set; } = 2000f;
|
||||
public float T2MaxRangeYd { get; set; } = 500f;
|
||||
public int T2MaxLandblocks { get; set; } = 3;
|
||||
// Buffing
|
||||
public bool EnableBuffing { get; set; } = true;
|
||||
public bool RebuffWhenIdle { get; set; }
|
||||
public int RebuffSecondsRemaining { get; set; } = 300;
|
||||
public int RebuffTopOffSecondsRemaining { get; set; } = 1200;
|
||||
public int BuffMinSkillLevelTier1 { get; set; } = 35;
|
||||
public int BuffMinSkillLevelTier2 { get; set; } = 85;
|
||||
public int BuffMinSkillLevelTier3 { get; set; } = 135;
|
||||
public int BuffMinSkillLevelTier4 { get; set; } = 185;
|
||||
public int BuffMinSkillLevelTier5 { get; set; } = 235;
|
||||
public int BuffMinSkillLevelTier6 { get; set; } = 285;
|
||||
public int BuffMinSkillLevelTier7 { get; set; } = 335;
|
||||
public int BuffMinSkillLevelTier8 { get; set; } = 435;
|
||||
// Crafting
|
||||
public bool EnableMissileCrafting { get; set; } = true;
|
||||
public string MissileCraftingState { get; set; } = string.Empty;
|
||||
public bool MissileCraftingActive { get; set; }
|
||||
public string MissileCraftingStatus { get; set; } = string.Empty;
|
||||
// Looting
|
||||
public bool EnableLooting { get; set; }
|
||||
public bool BoostLootPriority { get; set; }
|
||||
public bool LootOnlyRareCorpses { get; set; }
|
||||
public bool LootJumpEnabled { get; set; }
|
||||
public int LootJumpHeight { get; set; } = 10;
|
||||
public int LootOwnership { get; set; }
|
||||
public bool EnableAutostack { get; set; } = true;
|
||||
public bool EnableCombineSalvage { get; set; } = true;
|
||||
public bool CombineBagsDuringSalvage { get; set; } = true;
|
||||
public int LootInterItemDelayMs { get; set; } = 50;
|
||||
public int LootContentSettleMs { get; set; } = 100;
|
||||
public int LootEmptyCorpseMs { get; set; } = 300;
|
||||
public int LootClosingDelayMs { get; set; } = 200;
|
||||
public int LootAssessWindowMs { get; set; } = 200;
|
||||
public int LootRetryTimeoutMs { get; set; } = 500;
|
||||
public int LootOpenRetryMs { get; set; } = 1500;
|
||||
public int LootCorpseTimeoutMs { get; set; } = 12000;
|
||||
public int SalvageOpenDelayFirstMs { get; set; } = 400;
|
||||
public int SalvageOpenDelayFastMs { get; set; } = 50;
|
||||
public int SalvageAddDelayFirstMs { get; set; } = 600;
|
||||
public int SalvageAddDelayFastMs { get; set; } = 50;
|
||||
public int SalvageSalvageDelayMs { get; set; } = 50;
|
||||
public int SalvageResultDelayFirstMs { get; set; } = 1000;
|
||||
public int SalvageResultDelayFastMs { get; set; } = 250;
|
||||
}
|
||||
|
||||
private sealed class PanelState
|
||||
{
|
||||
public Settings Data = new();
|
||||
public RynthAiSettings Data = new();
|
||||
public int SelectedTab;
|
||||
public bool Dirty;
|
||||
// UI deep-dive finding TL;DR #9 (2026-07-02): raw JSON from the last
|
||||
// poll that actually rebuilt content — see the timer.Tick JSON gate.
|
||||
public string? LastJson;
|
||||
// Hub snapshot version last applied (replaces the old raw-JSON gate).
|
||||
public long SeenVersion = -1;
|
||||
// Companion fix (SettingsPanel.cs:501 finding): visibility-gating
|
||||
// controls (EnableFPSLimit, UseArcs, meleeAuto, missileAuto,
|
||||
// OpenDoors, MovementMode, EnableMissileCrafting, LootJumpEnabled)
|
||||
|
|
@ -321,7 +136,6 @@ internal static class SettingsPanel
|
|||
|
||||
public static Control Create()
|
||||
{
|
||||
TryBind();
|
||||
var state = new PanelState();
|
||||
|
||||
var root = new Border
|
||||
|
|
@ -387,12 +201,13 @@ internal static class SettingsPanel
|
|||
|
||||
// ── Tab buttons ───────────────────────────────────────────────────────
|
||||
var tabButtons = new List<Button>();
|
||||
for (int i = 0; i < Tabs.Length; i++)
|
||||
SettingsTab[] tabs = SettingsSchema.Tabs;
|
||||
for (int i = 0; i < tabs.Length; i++)
|
||||
{
|
||||
int idx = i;
|
||||
var btn = new Button
|
||||
{
|
||||
Content = Tabs[i],
|
||||
Content = tabs[i].Name,
|
||||
HorizontalAlignment = HorizontalAlignment.Stretch,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Left,
|
||||
Background = ColBtnFill,
|
||||
|
|
@ -417,45 +232,43 @@ internal static class SettingsPanel
|
|||
|
||||
state.Rebuild = () => RebuildContent(state, contentStack, picker);
|
||||
|
||||
// ── Initial data load ─────────────────────────────────────────────────
|
||||
if (TryFetch(out var initial)) state.Data = initial;
|
||||
// ── Data: the hub's settings snapshot ─────────────────────────────────
|
||||
void ApplySnapshot()
|
||||
{
|
||||
var snap = UiSources.Settings.Current;
|
||||
if (snap == null || snap.Version == state.SeenVersion) return;
|
||||
state.SeenVersion = snap.Version;
|
||||
state.Data = snap.Value.Clone();
|
||||
RebuildContent(state, contentStack, picker);
|
||||
}
|
||||
|
||||
picker.Root = root;
|
||||
UpdateTabHighlight(tabButtons, 0);
|
||||
RebuildContent(state, contentStack, picker);
|
||||
|
||||
// ── Poll timer ────────────────────────────────────────────────────────
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
|
||||
// Poll the snapshot (the hub fetches every 5 s while subscribed, and
|
||||
// right after each save). Never while a field is being typed in: that
|
||||
// used to clobber in-progress edits (UI deep-dive TL;DR #9).
|
||||
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_getSettingsJson == null) TryBind();
|
||||
if (state.Dirty) return;
|
||||
// UI deep-dive finding TL;DR #9 (2026-07-02): state.Dirty was
|
||||
// declared, checked, and reset — but never actually SET true
|
||||
// anywhere in this file, making the guard above dead code. This
|
||||
// rebuild ran unconditionally every 5s, clobbering whatever the
|
||||
// user was doing in ANY field (in-progress typing, an open
|
||||
// picker, a slider mid-drag) with a fresh copy from the plugin.
|
||||
// Real guards: (1) AvaloniaTextInputActive is already wired by
|
||||
// every TextBox in this panel (GotFocus/LostFocus below) — reuse
|
||||
// it directly as a focus guard instead of the dead Dirty flag.
|
||||
// (2) A raw-JSON diff — the full payload (all settings including
|
||||
// any gating toggles) is compared, so a rebuild still fires
|
||||
// whenever a toggle that would reveal/hide conditional rows
|
||||
// actually changes; nothing is excluded from this gate the way
|
||||
// PayloadSig deliberately excludes fields elsewhere.
|
||||
if (Win32Backend.AvaloniaTextInputActive) return;
|
||||
if (!TryFetch(out var fresh, out string? rawJson)) return;
|
||||
if (rawJson != null && rawJson == state.LastJson) return;
|
||||
state.LastJson = rawJson;
|
||||
state.Data = fresh;
|
||||
RebuildContent(state, contentStack, picker);
|
||||
ApplySnapshot();
|
||||
};
|
||||
timer.Start();
|
||||
// Stop with the visual tree — a running DispatcherTimer roots the closed
|
||||
// view forever (one immortal poller per open/close). RadarPanel idiom;
|
||||
// must restart on attach: drag/resize fires Detached→Attached.
|
||||
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
|
||||
root.DetachedFromVisualTree += (_, _) => timer.Stop();
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.Settings.Subscribe();
|
||||
UiSources.Settings.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.Settings.Unsubscribe();
|
||||
};
|
||||
|
||||
return root;
|
||||
}
|
||||
|
|
@ -476,7 +289,7 @@ internal static class SettingsPanel
|
|||
// Tab header
|
||||
var header = new TextBlock
|
||||
{
|
||||
Text = $"Advanced Settings > {Tabs[state.SelectedTab]}",
|
||||
Text = $"Advanced Settings > {SettingsSchema.Tabs[state.SelectedTab].Name}",
|
||||
Foreground = ColTeal,
|
||||
FontSize = 11,
|
||||
FontWeight = Avalonia.Media.FontWeight.Bold,
|
||||
|
|
@ -485,503 +298,71 @@ internal static class SettingsPanel
|
|||
panel.Children.Add(header);
|
||||
panel.Children.Add(new Border { Height = 1, Background = ColBtnBord, Margin = new Thickness(0, 0, 0, 6) });
|
||||
|
||||
switch (state.SelectedTab)
|
||||
foreach (SettingRow row in SettingsSchema.Tabs[state.SelectedTab].Rows)
|
||||
{
|
||||
case 0: BuildDisplayTab(state, panel, picker); break;
|
||||
case 1: BuildUITab(state, panel, picker); break;
|
||||
case 2: BuildMiscTab(state, panel, picker); break;
|
||||
case 3: BuildRechargeTab(state, panel, picker); break;
|
||||
case 4: BuildMeleeCombatTab(state, panel, picker); break;
|
||||
case 5: BuildSpellCombatTab(state, panel, picker); break;
|
||||
case 6: BuildRangesTab(state, panel, picker); break;
|
||||
case 7: BuildNavigationTab(state, panel, picker); break;
|
||||
case 8: BuildBuffingTab(state, panel, picker); break;
|
||||
case 9: BuildCraftingTab(state, panel, picker); break;
|
||||
case 10: BuildLootingTab(state, panel, picker); break;
|
||||
case 11: BuildVendoringTab(state, panel, picker); break;
|
||||
if (!row.IsVisible(state.Data)) continue;
|
||||
Control? control = BuildRow(state, row, picker);
|
||||
if (control != null) panel.Children.Add(control);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Tab content builders
|
||||
// =========================================================================
|
||||
|
||||
private static void BuildDisplayTab(PanelState state, StackPanel p, PickerState picker)
|
||||
/// <summary>One schema row as the Avalonia control it has always been.</summary>
|
||||
private static Control? BuildRow(PanelState state, SettingRow row, PickerState picker)
|
||||
{
|
||||
p.Children.Add(BoolRow("Show Target Stamina / Mana",
|
||||
state.Data.ShowTargetStaminaMana,
|
||||
v => { state.Data.ShowTargetStaminaMana = v; Push(state); },
|
||||
"When enabled, displays stamina and mana bars for the selected target (requires appraisal data)."));
|
||||
}
|
||||
|
||||
private static void BuildUITab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("Radar"));
|
||||
p.Children.Add(BoolRow("Get Rid of Retail Radar", state.Data.SuppressRetailRadar,
|
||||
v => { state.Data.SuppressRetailRadar = v; Push(state); },
|
||||
"Suppress the game's built-in radar (bezel, compass, coords, blips)."));
|
||||
p.Children.Add(BoolRow("Show RynthRadar", state.Data.ShowRynthRadar,
|
||||
v => { state.Data.ShowRynthRadar = v; Push(state); },
|
||||
"Render the custom square radar widget (indoor walls + dot markers, works outdoors)."));
|
||||
p.Children.Add(BoolRow("Radar Click-Through", state.Data.RadarClickThrough,
|
||||
v => { state.Data.RadarClickThrough = v; Push(state); },
|
||||
"Mouse events over the radar pass through to the game instead of the widget."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Chat"));
|
||||
// "Get Rid of Retail Chatbox" lives in the RynthChat panel's gear menu ("Hide retail chat"),
|
||||
// which owns ChatHooks.SuppressOriginalChat directly. The old row here routed through RynthAi's
|
||||
// settings push and was clobbered every tick, so it was removed.
|
||||
p.Children.Add(BoolRow("Show RynthChat", state.Data.ShowRynthChat,
|
||||
v => { state.Data.ShowRynthChat = v; Push(state); },
|
||||
"Render the custom chat viewer (scrollback + channel coloring)."));
|
||||
p.Children.Add(BoolRow("Chat Click-Through", state.Data.ChatClickThrough,
|
||||
v => { state.Data.ChatClickThrough = v; Push(state); },
|
||||
"Mouse events over the chat pass through to the game. The gear button stays clickable."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Power Bar"));
|
||||
p.Children.Add(BoolRow("Get Rid of Retail Power Bar", state.Data.SuppressRetailPowerbar,
|
||||
v => { state.Data.SuppressRetailPowerbar = v; Push(state); },
|
||||
"Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden."));
|
||||
}
|
||||
|
||||
private static void BuildMiscTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(BoolRow("Enable FPS Limit", state.Data.EnableFPSLimit,
|
||||
v => { state.Data.EnableFPSLimit = v; Push(state); state.Rebuild?.Invoke(); }));
|
||||
if (state.Data.EnableFPSLimit)
|
||||
RynthAiSettings d = state.Data;
|
||||
void Changed(double v)
|
||||
{
|
||||
p.Children.Add(IntRow("Focused FPS", state.Data.TargetFPSFocused, 10, 240, 1,
|
||||
v => { state.Data.TargetFPSFocused = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Background FPS", state.Data.TargetFPSBackground, 5, 60, 1,
|
||||
v => { state.Data.TargetFPSBackground = v; Push(state); }));
|
||||
}
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(BoolRow("Auto Cram", state.Data.EnableAutocram,
|
||||
v => { state.Data.EnableAutocram = v; Push(state); },
|
||||
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."));
|
||||
p.Children.Add(BoolRow("Peace Mode When Idle", state.Data.PeaceModeWhenIdle,
|
||||
v => { state.Data.PeaceModeWhenIdle = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Start Macro On Login", state.Data.StartMacroOnLogin,
|
||||
v => { state.Data.StartMacroOnLogin = v; Push(state); },
|
||||
"Automatically starts the macro when RynthAi loads."));
|
||||
p.Children.Add(BoolRow("Patrol On Login", state.Data.PatrolOnLogin,
|
||||
v => { state.Data.PatrolOnLogin = v; Push(state); },
|
||||
"Automatically starts dungeon patrol when RynthAi loads."));
|
||||
p.Children.Add(BoolRow("Enable Raycasting", state.Data.EnableRaycasting,
|
||||
v => { state.Data.EnableRaycasting = v; Push(state); }));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Missile Arc Velocities (m/s)"));
|
||||
p.Children.Add(BoolRow("Use Arcs for Missile LoS", state.Data.UseArcs,
|
||||
v => { state.Data.UseArcs = v; Push(state); state.Rebuild?.Invoke(); },
|
||||
"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)."));
|
||||
if (state.Data.UseArcs)
|
||||
{
|
||||
p.Children.Add(FloatRow("Bow", state.Data.BowArcVelocity, 10f, 60f, 0.5f, v => { state.Data.BowArcVelocity = v; Push(state); }, "Bow projectile speed (m/s). Lower = higher arc."));
|
||||
p.Children.Add(FloatRow("Crossbow", state.Data.CrossbowArcVelocity, 10f, 80f, 0.5f, v => { state.Data.CrossbowArcVelocity = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Atlatl", state.Data.AtlatlArcVelocity, 10f, 60f, 0.5f, v => { state.Data.AtlatlArcVelocity = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Magic Arc", state.Data.MagicArcVelocity, 10f, 60f, 0.5f, v => { state.Data.MagicArcVelocity = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Arc Clearance (m)", state.Data.MissileArcClearance, 0f, 3f, 0.1f,
|
||||
v => { state.Data.MissileArcClearance = MathF.Max(0f, v); Push(state); },
|
||||
"Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped."));
|
||||
}
|
||||
p.Children.Add(BoolRow("LoS Debug Log", state.Data.LosDebugLog,
|
||||
v => { state.Data.LosDebugLog = v; Push(state); },
|
||||
"Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Monster Blacklist"));
|
||||
p.Children.Add(IntRow("Attempts Before Blacklist", state.Data.BlacklistAttempts, 1, 20, 1,
|
||||
v => { state.Data.BlacklistAttempts = v; Push(state); },
|
||||
"How many failed attack attempts on a mob before it gets blacklisted."));
|
||||
p.Children.Add(IntRow("Blacklist Timeout (sec)", state.Data.BlacklistTimeoutSec, 5, 120, 5,
|
||||
v => { state.Data.BlacklistTimeoutSec = v; Push(state); },
|
||||
"How long a blacklisted mob is ignored before re-trying."));
|
||||
p.Children.Add(IntRow("No Progress Timeout (sec)", state.Data.TargetNoProgressTimeoutSec, 0, 300, 10,
|
||||
v => { state.Data.TargetNoProgressTimeoutSec = v; Push(state); },
|
||||
"Blacklist a target after being engaged this many seconds without dealing damage.\n0 = disabled. Default 60s."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Give Queue"));
|
||||
p.Children.Add(IntRow("Give Interval (ms)", state.Data.GiveQueueIntervalMs, 50, 2000, 50,
|
||||
v => { state.Data.GiveQueueIntervalMs = v; Push(state); },
|
||||
"Minimum delay between each item sent by /ra givea commands."));
|
||||
}
|
||||
|
||||
private static void BuildRechargeTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("In Combat — target within Monster Range (%)"));
|
||||
p.Children.Add(IntRow("Heal At", state.Data.HealAt, 0, 100, 1, v => { state.Data.HealAt = v; Push(state); },
|
||||
"While a target is within Monster Range, cast Heal Self when HP < this %."));
|
||||
p.Children.Add(IntRow("Re-stam At", state.Data.RestamAt, 0, 100, 1, v => { state.Data.RestamAt = v; Push(state); },
|
||||
"While a target is within Monster Range, cast Revitalize Self when Stamina < this %."));
|
||||
p.Children.Add(IntRow("Get Mana At", state.Data.GetManaAt, 0, 100, 1, v => { state.Data.GetManaAt = v; Push(state); },
|
||||
"While a target is within Monster Range, cast Stamina to Mana Self when Mana < this % (needs stam > 15%)."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Idle Top-Off — no targets in range (%)"));
|
||||
p.Children.Add(IntRow("Top HP", state.Data.TopOffHP, 0, 100, 1, v => { state.Data.TopOffHP = v; Push(state); },
|
||||
"When no targets are within Monster Range, heal up to this HP %. Usually set higher than Heal At."));
|
||||
p.Children.Add(IntRow("Top Stam", state.Data.TopOffStam, 0, 100, 1, v => { state.Data.TopOffStam = v; Push(state); },
|
||||
"When no targets are within Monster Range, re-stam up to this %."));
|
||||
p.Children.Add(IntRow("Top Mana", state.Data.TopOffMana, 0, 100, 1, v => { state.Data.TopOffMana = v; Push(state); },
|
||||
"When no targets are within Monster Range, recharge mana up to this %."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Helper Settings (%) — NOT WIRED YET"));
|
||||
p.Children.Add(IntRow("Heal Others", state.Data.HealOthersAt, 0, 100, 1, v => { state.Data.HealOthersAt = v; Push(state); },
|
||||
"Intended: cast Heal Other on a fellow when their HP < this %. Not implemented yet — slider is inert."));
|
||||
p.Children.Add(IntRow("Re-stam Others", state.Data.RestamOthersAt, 0, 100, 1, v => { state.Data.RestamOthersAt = v; Push(state); },
|
||||
"Intended: cast Revitalize Other on a fellow when their Stamina < this %. Not implemented yet — slider is inert."));
|
||||
p.Children.Add(IntRow("Infuse Others", state.Data.InfuseOthersAt, 0, 100, 1, v => { state.Data.InfuseOthersAt = v; Push(state); },
|
||||
"Intended: cast Infuse Mana Other on a fellow when their Mana < this %. Not implemented yet — slider is inert."));
|
||||
}
|
||||
|
||||
private static void BuildMeleeCombatTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("Attack Power & Height"));
|
||||
p.Children.Add(BoolRow("Use Recklessness", state.Data.UseRecklessness,
|
||||
v => { state.Data.UseRecklessness = v; Push(state); },
|
||||
"When enabled and Recklessness is trained, auto power uses 80% instead of 100%."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
bool meleeAuto = state.Data.MeleeAttackPower < 0;
|
||||
p.Children.Add(BoolRow("Melee Auto Power", meleeAuto, v =>
|
||||
{
|
||||
state.Data.MeleeAttackPower = v ? -1 : 100;
|
||||
row.Set!(state.Data, v);
|
||||
Push(state);
|
||||
state.Rebuild?.Invoke();
|
||||
}));
|
||||
if (!meleeAuto)
|
||||
{
|
||||
p.Children.Add(IntRow("Melee Power %", state.Data.MeleeAttackPower, 0, 100, 5,
|
||||
v => { state.Data.MeleeAttackPower = v; Push(state); }));
|
||||
}
|
||||
p.Children.Add(ComboRow("Melee Attack Height", AttackHeights, state.Data.MeleeAttackHeight,
|
||||
v => { state.Data.MeleeAttackHeight = v; Push(state); }, picker));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
bool missileAuto = state.Data.MissileAttackPower < 0;
|
||||
p.Children.Add(BoolRow("Missile Auto Power", missileAuto, v =>
|
||||
{
|
||||
state.Data.MissileAttackPower = v ? -1 : 100;
|
||||
Push(state);
|
||||
state.Rebuild?.Invoke();
|
||||
}));
|
||||
if (!missileAuto)
|
||||
{
|
||||
p.Children.Add(IntRow("Missile Power %", state.Data.MissileAttackPower, 0, 100, 5,
|
||||
v => { state.Data.MissileAttackPower = v; Push(state); }));
|
||||
}
|
||||
p.Children.Add(ComboRow("Missile Attack Height", AttackHeights, state.Data.MissileAttackHeight,
|
||||
v => { state.Data.MissileAttackHeight = v; Push(state); }, picker));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(BoolRow("Use Native Attack", state.Data.UseNativeAttack,
|
||||
v => { state.Data.UseNativeAttack = v; Push(state); },
|
||||
"Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows)."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(BoolRow("Summon Pets", state.Data.SummonPets,
|
||||
v => { state.Data.SummonPets = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Pet Min Monsters", state.Data.PetMinMonsters, 1, 20, 1,
|
||||
v => { state.Data.PetMinMonsters = v; Push(state); }));
|
||||
}
|
||||
|
||||
private static void BuildSpellCombatTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("War/Void Casting Settings"));
|
||||
p.Children.Add(IntRow("Buff Spell Interval (ms)", state.Data.SpellCastIntervalMs, 100, 1500, 50,
|
||||
v => { state.Data.SpellCastIntervalMs = v; Push(state); },
|
||||
"Delay between BUFF / utility spell casts (not combat).\nLower = faster buff chains. 400ms is a good balance.\nBelow 200ms may cause fizzles or dropped casts on laggy servers."));
|
||||
p.Children.Add(IntRow("Attack Spell Delay (ms)", state.Data.AttackSpellIntervalMs, 250, 5000, 50,
|
||||
v => { state.Data.AttackSpellIntervalMs = v; Push(state); },
|
||||
"Delay between offensive (war/void) COMBAT casts only.\nSpacing casts ~1-2s (1500ms default) stops back-to-back\n\"You're too busy!\" refusals that drop casts and cost kills.\nDoes NOT affect buffing speed."));
|
||||
p.Children.Add(BoolRow("Cast Dispel Self", state.Data.CastDispelSelf,
|
||||
v => { state.Data.CastDispelSelf = v; Push(state); }));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Ring Spell Override"));
|
||||
p.Children.Add(IntRow("Min Ring Targets", state.Data.MinRingTargets, 1, 20, 1,
|
||||
v => { state.Data.MinRingTargets = v; Push(state); },
|
||||
"If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Spell Difficulty (Min Buffed Skill)"));
|
||||
p.Children.Add(IntRow("Level 1", state.Data.MinSkillLevelTier1, 1, 500, 5, v => { state.Data.MinSkillLevelTier1 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 2", state.Data.MinSkillLevelTier2, 1, 500, 5, v => { state.Data.MinSkillLevelTier2 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 3", state.Data.MinSkillLevelTier3, 1, 500, 5, v => { state.Data.MinSkillLevelTier3 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 4", state.Data.MinSkillLevelTier4, 1, 500, 5, v => { state.Data.MinSkillLevelTier4 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 5", state.Data.MinSkillLevelTier5, 1, 500, 5, v => { state.Data.MinSkillLevelTier5 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 6", state.Data.MinSkillLevelTier6, 1, 500, 5, v => { state.Data.MinSkillLevelTier6 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 7", state.Data.MinSkillLevelTier7, 1, 500, 5, v => { state.Data.MinSkillLevelTier7 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 8", state.Data.MinSkillLevelTier8, 1, 500, 5, v => { state.Data.MinSkillLevelTier8 = v; Push(state); }));
|
||||
}
|
||||
|
||||
private static void BuildRangesTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("Standard Ranges (Yards)"));
|
||||
p.Children.Add(IntRow("Monster Range", state.Data.MonsterRange, 1, 200, 1, v => { state.Data.MonsterRange = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Ring Range", state.Data.RingRange, 1, 50, 1, v => { state.Data.RingRange = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Approach Range", state.Data.ApproachRange, 1, 50, 1, v => { state.Data.ApproachRange = v; Push(state); }));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Corpse Acquisition (Yards)"));
|
||||
p.Children.Add(DoubleRow("Corpse Max (yd)", state.Data.CorpseApproachRangeMax, 0.5, 50.0, 0.5,
|
||||
v => { state.Data.CorpseApproachRangeMax = v; Push(state); }));
|
||||
p.Children.Add(DoubleRow("Corpse Min (yd)", state.Data.CorpseApproachRangeMin, 0.5, 20.0, 0.5,
|
||||
v => { state.Data.CorpseApproachRangeMin = v; Push(state); }));
|
||||
}
|
||||
|
||||
private static void BuildNavigationTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(BoolRow("Boost Nav Priority", state.Data.BoostNavPriority,
|
||||
v => { state.Data.BoostNavPriority = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Follow/Nav Min (yd)", state.Data.FollowNavMin, 0.5f, 20f, 0.1f,
|
||||
v => { state.Data.FollowNavMin = v; Push(state); },
|
||||
"Arrival distance in yards. Also sets the nav marker ring radius."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Nav Marker Display"));
|
||||
p.Children.Add(FloatRow("Ring Thickness", state.Data.NavRingThickness, 1f, 16f, 1f,
|
||||
v => { state.Data.NavRingThickness = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Line Thickness", state.Data.NavLineThickness, 1f, 16f, 1f,
|
||||
v => { state.Data.NavLineThickness = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Height Offset", state.Data.NavHeightOffset, -5f, 5f, 0.05f,
|
||||
v => { state.Data.NavHeightOffset = v; Push(state); },
|
||||
"Vertical offset for nav markers above the ground. Negative = lower."));
|
||||
p.Children.Add(FloatRow("Slope Sink", state.Data.NavSlopeSink, 0f, 8f, 0.1f,
|
||||
v => { state.Data.NavSlopeSink = v; Push(state); },
|
||||
"Extra downward offset on slopes only, per unit of terrain steepness. 0 = off; flat ground is unaffected. ~1.5 cancels the float for a default-radius ring."));
|
||||
p.Children.Add(BoolRow("Show Terrain Passability", state.Data.ShowTerrainPassability,
|
||||
v => { state.Data.ShowTerrainPassability = v; Push(state); },
|
||||
"Highlight impassable terrain triangles in red."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Doors"));
|
||||
p.Children.Add(BoolRow("Open Doors While Navigating", state.Data.OpenDoors,
|
||||
v => { state.Data.OpenDoors = v; Push(state); state.Rebuild?.Invoke(); },
|
||||
"Automatically open doors encountered during navigation."));
|
||||
if (state.Data.OpenDoors)
|
||||
{
|
||||
p.Children.Add(FloatRow("Door Detection Range (yd)", state.Data.OpenDoorRange, 0.1f, 70f, 1f,
|
||||
v => { state.Data.OpenDoorRange = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Auto-Unlock Doors", state.Data.AutoUnlockDoors,
|
||||
v => { state.Data.AutoUnlockDoors = v; Push(state); },
|
||||
"If a door is locked, try to use a lockpick from your Consumable Items list."));
|
||||
if (row.Gates) state.Rebuild?.Invoke();
|
||||
}
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Movement Engine"));
|
||||
p.Children.Add(ComboRow("Mode", MovementModes, state.Data.MovementMode,
|
||||
v => { state.Data.MovementMode = v; Push(state); state.Rebuild?.Invoke(); }, picker,
|
||||
"Legacy: SetAutorun + smooth heading servo (TurnToHeading)\nTier 1: SetAutorun + CM_Movement turn commands (DoMovement)\nTier 2: Client physics MoveToPosition (not built yet — falls back to Legacy)"));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Steering"));
|
||||
p.Children.Add(FloatRow("Stop & Turn Angle", state.Data.NavStopTurnAngle, 1f, 90f, 1f,
|
||||
v => { state.Data.NavStopTurnAngle = v; Push(state); },
|
||||
"Stop forward motion and turn in place when heading error exceeds this."));
|
||||
p.Children.Add(FloatRow("Resume Run Angle", state.Data.NavResumeTurnAngle, 1f, 45f, 1f,
|
||||
v => { state.Data.NavResumeTurnAngle = v; Push(state); },
|
||||
"Resume running once the turn-in-place error drops below this."));
|
||||
p.Children.Add(FloatRow("Dead Zone", state.Data.NavDeadZone, 0.5f, 20f, 0.5f,
|
||||
v => { state.Data.NavDeadZone = v; Push(state); },
|
||||
"Ignore heading corrections smaller than this."));
|
||||
p.Children.Add(FloatRow("Sweep Detect Mult", state.Data.NavSweepMult, 0.5f, 10f, 0.1f,
|
||||
v => { state.Data.NavSweepMult = v; Push(state); },
|
||||
"Closest-approach detection radius multiplier."));
|
||||
p.Children.Add(FloatRow("Lookahead (yd)", state.Data.NavLookaheadYards, 0f, 30f, 0.5f,
|
||||
v => { state.Data.NavLookaheadYards = MathF.Max(0f, v); Push(state); },
|
||||
"Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off."));
|
||||
p.Children.Add(FloatRow("Shortcut Tolerance (yd)", state.Data.NavShortcutYards, 0f, 10f, 0.5f,
|
||||
v => { state.Data.NavShortcutYards = MathF.Max(0f, v); Push(state); },
|
||||
"On reaching a waypoint, skip ahead only past points that all lie within this distance of the straight line to the new target. 0 = visit every waypoint."));
|
||||
p.Children.Add(FloatRow("Turn Rate (deg/s)", state.Data.NavTurnRateDegPerSec, 30f, 720f, 15f,
|
||||
v => { state.Data.NavTurnRateDegPerSec = v; Push(state); },
|
||||
"Legacy / Mode 0 heading-servo max turn speed. Ignored by Tier 1 and Tier 2."));
|
||||
p.Children.Add(FloatRow("Tier1 Turn Speed", state.Data.NavTier1TurnSpeed, 0.5f, 15f, 0.5f,
|
||||
v => { state.Data.NavTier1TurnSpeed = v; Push(state); },
|
||||
"Tier 1 (CM_Movement) turn-command speed = magnitude of the client turn_speed. Higher = snappier turns. Only used in Tier 1 mode."));
|
||||
p.Children.Add(FloatRow("Post-Portal Delay (s)", state.Data.PostPortalDelaySec, 0f, 30f, 0.25f,
|
||||
v => { state.Data.PostPortalDelaySec = MathF.Max(0f, v); Push(state); },
|
||||
"Seconds to settle after any portal/recall teleport before nav resumes."));
|
||||
|
||||
if (state.Data.MovementMode == 2)
|
||||
switch (row.Kind)
|
||||
{
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Tier 2 Tuning"));
|
||||
p.Children.Add(FloatRow("Speed", state.Data.T2Speed, 0.1f, 5f, 0.1f, v => { state.Data.T2Speed = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Walk Within (yd)", state.Data.T2WalkWithinYd, 1f, 50f, 1f, v => { state.Data.T2WalkWithinYd = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Stop Distance (yd)", state.Data.T2DistanceTo, 0.1f, 10f, 0.1f, v => { state.Data.T2DistanceTo = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Reissue Timeout (ms)",state.Data.T2ReissueMs, 100f, 10000f,100f, v => { state.Data.T2ReissueMs = v; Push(state); }));
|
||||
p.Children.Add(FloatRow("Max Range (yd)", state.Data.T2MaxRangeYd, 50f, 2000f, 50f, v => { state.Data.T2MaxRangeYd = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Max Landblock Dist", state.Data.T2MaxLandblocks, 1, 20, 1, v => { state.Data.T2MaxLandblocks = v; Push(state); }));
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildBuffingTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(BoolRow("Enable Buffing", state.Data.EnableBuffing,
|
||||
v => { state.Data.EnableBuffing = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Rebuff When Idle", state.Data.RebuffWhenIdle,
|
||||
v => { state.Data.RebuffWhenIdle = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Rebuff With (seconds left)", state.Data.RebuffSecondsRemaining, 30, 1800, 30,
|
||||
v => { state.Data.RebuffSecondsRemaining = v; Push(state); },
|
||||
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."));
|
||||
p.Children.Add(IntRow("Also Refresh Under (seconds left)", state.Data.RebuffTopOffSecondsRemaining, 30, 3600, 60,
|
||||
v => { state.Data.RebuffTopOffSecondsRemaining = v; Push(state); },
|
||||
"When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Buff Difficulty (Min Buffed Skill)"));
|
||||
p.Children.Add(IntRow("Level 1", state.Data.BuffMinSkillLevelTier1, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier1 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 2", state.Data.BuffMinSkillLevelTier2, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier2 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 3", state.Data.BuffMinSkillLevelTier3, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier3 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 4", state.Data.BuffMinSkillLevelTier4, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier4 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 5", state.Data.BuffMinSkillLevelTier5, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier5 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 6", state.Data.BuffMinSkillLevelTier6, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier6 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 7", state.Data.BuffMinSkillLevelTier7, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier7 = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Level 8", state.Data.BuffMinSkillLevelTier8, 1, 500, 5, v => { state.Data.BuffMinSkillLevelTier8 = v; Push(state); }));
|
||||
}
|
||||
|
||||
private static void BuildCraftingTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("Missile Ammo Crafting"));
|
||||
p.Children.Add(BoolRow("Enable Missile Crafting", state.Data.EnableMissileCrafting,
|
||||
v => { state.Data.EnableMissileCrafting = v; Push(state); state.Rebuild?.Invoke(); },
|
||||
"Auto-manage missile ammo when the ammo slot is empty or low."));
|
||||
|
||||
if (!state.Data.EnableMissileCrafting)
|
||||
{
|
||||
p.Children.Add(new TextBlock { Text = "(Disabled)", Foreground = ColMute, FontSize = 11, Margin = new Thickness(0, 4, 0, 0) });
|
||||
return;
|
||||
}
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
if (!string.IsNullOrEmpty(state.Data.MissileCraftingState))
|
||||
{
|
||||
var stateRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 2, 0, 2) };
|
||||
stateRow.Children.Add(new TextBlock { Text = "State:", Foreground = ColMute, FontSize = 11, VerticalAlignment = VerticalAlignment.Center });
|
||||
stateRow.Children.Add(new TextBlock
|
||||
{
|
||||
Text = state.Data.MissileCraftingState,
|
||||
Foreground = state.Data.MissileCraftingActive ? ColAmber : ColMute,
|
||||
FontSize = 11,
|
||||
FontWeight = Avalonia.Media.FontWeight.Bold,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
});
|
||||
p.Children.Add(stateRow);
|
||||
|
||||
if (!string.IsNullOrEmpty(state.Data.MissileCraftingStatus))
|
||||
{
|
||||
p.Children.Add(new TextBlock
|
||||
case SettingKind.Bool:
|
||||
return BoolRow(row.Label, row.Get!(d) != 0, v => Changed(v ? 1 : 0), row.Tooltip);
|
||||
case SettingKind.Int:
|
||||
return IntRow(row.Label, (int)row.Get!(d), (int)row.Min, (int)row.Max, (int)row.Step, v => Changed(v), row.Tooltip);
|
||||
case SettingKind.Float:
|
||||
return FloatRow(row.Label, (float)row.Get!(d), (float)row.Min, (float)row.Max, (float)row.Step, v => Changed(v), row.Tooltip);
|
||||
case SettingKind.Double:
|
||||
return DoubleRow(row.Label, row.Get!(d), row.Min, row.Max, row.Step, v => Changed(v), row.Tooltip);
|
||||
case SettingKind.Combo:
|
||||
return ComboRow(row.Label, row.Items!, (int)row.Get!(d), v => Changed(v), picker, row.Tooltip);
|
||||
case SettingKind.Section:
|
||||
return SectionHeader(row.Label);
|
||||
case SettingKind.Spacer:
|
||||
return Spacer();
|
||||
case SettingKind.Note:
|
||||
return new TextBlock
|
||||
{
|
||||
Text = state.Data.MissileCraftingStatus,
|
||||
Foreground = ColTextDim,
|
||||
FontSize = 10,
|
||||
TextWrapping = Avalonia.Media.TextWrapping.Wrap,
|
||||
Margin = new Thickness(0, 2, 0, 0),
|
||||
Text = row.Label, Foreground = ColMute, FontSize = row.Label.StartsWith('(') ? 11 : 10,
|
||||
TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0),
|
||||
};
|
||||
case SettingKind.CraftingStatus:
|
||||
{
|
||||
var box = new StackPanel();
|
||||
var stateRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 2, 0, 2) };
|
||||
stateRow.Children.Add(new TextBlock { Text = row.Label, Foreground = ColMute, FontSize = 11, VerticalAlignment = VerticalAlignment.Center });
|
||||
stateRow.Children.Add(new TextBlock
|
||||
{
|
||||
Text = d.MissileCraftingState,
|
||||
Foreground = d.MissileCraftingActive ? ColAmber : ColMute,
|
||||
FontSize = 11,
|
||||
FontWeight = Avalonia.Media.FontWeight.Bold,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
});
|
||||
box.Children.Add(stateRow);
|
||||
if (!string.IsNullOrEmpty(d.MissileCraftingStatus))
|
||||
box.Children.Add(new TextBlock
|
||||
{
|
||||
Text = d.MissileCraftingStatus, Foreground = ColTextDim, FontSize = 10,
|
||||
TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0),
|
||||
});
|
||||
return box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildVendoringTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(SectionHeader("AutoVendor"));
|
||||
p.Children.Add(BoolRow("Enabled", state.Data.AutoVendorEnabled,
|
||||
v => { state.Data.AutoVendorEnabled = v; Push(state); },
|
||||
"Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, in the AutoVendor folder."));
|
||||
p.Children.Add(BoolRow("Test Mode (only print what it would do)", state.Data.AutoVendorTestMode,
|
||||
v => { state.Data.AutoVendorTestMode = v; Push(state); },
|
||||
"Lists what would be bought and sold without trading. Leave this on until the lists look right."));
|
||||
p.Children.Add(BoolRow("Buy", state.Data.AutoVendorEnableBuying,
|
||||
v => { state.Data.AutoVendorEnableBuying = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Sell", state.Data.AutoVendorEnableSelling,
|
||||
v => { state.Data.AutoVendorEnableSelling = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Only Sell From Main Pack", state.Data.AutoVendorOnlyFromMainPack,
|
||||
v => { state.Data.AutoVendorOnlyFromMainPack = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Show Merchant Info", state.Data.AutoVendorShowMerchantInfo,
|
||||
v => { state.Data.AutoVendorShowMerchantInfo = v; Push(state); },
|
||||
"Print the vendor's buy/sell rates and max value when it opens."));
|
||||
p.Children.Add(BoolRow("Think When Finished", state.Data.AutoVendorThink,
|
||||
v => { state.Data.AutoVendorThink = v; Push(state); },
|
||||
"Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself, for metas."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("/ub vendor open"));
|
||||
p.Children.Add(IntRow("Tries", state.Data.AutoVendorTries, 1, 20, 1,
|
||||
v => { state.Data.AutoVendorTries = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Time Between Tries (ms)", state.Data.AutoVendorTriesTime, 500, 30000, 250,
|
||||
v => { state.Data.AutoVendorTriesTime = v; Push(state); }));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(new TextBlock
|
||||
{
|
||||
Text = "Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match.",
|
||||
Foreground = ColMute, FontSize = 10, TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0),
|
||||
});
|
||||
}
|
||||
|
||||
private static void BuildLootingTab(PanelState state, StackPanel p, PickerState picker)
|
||||
{
|
||||
p.Children.Add(BoolRow("Enable Looting", state.Data.EnableLooting,
|
||||
v => { state.Data.EnableLooting = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Boost Loot Priority", state.Data.BoostLootPriority,
|
||||
v => { state.Data.BoostLootPriority = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Loot Only Rare Corpses", state.Data.LootOnlyRareCorpses,
|
||||
v => { state.Data.LootOnlyRareCorpses = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Jump When Looting", state.Data.LootJumpEnabled,
|
||||
v => { state.Data.LootJumpEnabled = v; Push(state); state.Rebuild?.Invoke(); }));
|
||||
if (state.Data.LootJumpEnabled)
|
||||
{
|
||||
p.Children.Add(IntRow("Jump Height", state.Data.LootJumpHeight, 1, 100, 5,
|
||||
v => { state.Data.LootJumpHeight = v; Push(state); }));
|
||||
}
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Corpse Ownership"));
|
||||
p.Children.Add(ComboRow("Loot From", LootOwnershipModes, state.Data.LootOwnership,
|
||||
v => { state.Data.LootOwnership = v; Push(state); }, picker));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Inventory Management"));
|
||||
p.Children.Add(BoolRow("Enable Autostack", state.Data.EnableAutostack,
|
||||
v => { state.Data.EnableAutostack = v; Push(state); }));
|
||||
p.Children.Add(BoolRow("Enable Autocram", state.Data.EnableAutocram,
|
||||
v => { state.Data.EnableAutocram = v; Push(state); },
|
||||
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."));
|
||||
p.Children.Add(BoolRow("Combine Salvage Bags", state.Data.EnableCombineSalvage,
|
||||
v => { state.Data.EnableCombineSalvage = v; Push(state); },
|
||||
"After the salvage queue empties, move same-name bags together so the server merges them."));
|
||||
p.Children.Add(BoolRow("Combine Bags During Salvage", state.Data.CombineBagsDuringSalvage,
|
||||
v => { state.Data.CombineBagsDuringSalvage = v; Push(state); },
|
||||
"When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Loot Timers (ms)"));
|
||||
p.Children.Add(IntRow("Inter-Item Delay", state.Data.LootInterItemDelayMs, 0, 5000, 25, v => { state.Data.LootInterItemDelayMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Content Settle", state.Data.LootContentSettleMs, 0, 5000, 25, v => { state.Data.LootContentSettleMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Empty Corpse Wait", state.Data.LootEmptyCorpseMs, 0, 5000, 25, v => { state.Data.LootEmptyCorpseMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Closing Delay", state.Data.LootClosingDelayMs, 0, 5000, 25, v => { state.Data.LootClosingDelayMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Assess Window", state.Data.LootAssessWindowMs, 0, 5000, 25, v => { state.Data.LootAssessWindowMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Loot Retry Timeout", state.Data.LootRetryTimeoutMs, 0, 10000, 100, v => { state.Data.LootRetryTimeoutMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Corpse Open Retry", state.Data.LootOpenRetryMs, 0, 10000, 100, v => { state.Data.LootOpenRetryMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Corpse Timeout", state.Data.LootCorpseTimeoutMs, 0, 60000, 500, v => { state.Data.LootCorpseTimeoutMs = v; Push(state); }));
|
||||
|
||||
p.Children.Add(Spacer());
|
||||
p.Children.Add(SectionHeader("Salvage Timers (ms) - First / Fast"));
|
||||
p.Children.Add(IntRow("Open (First)", state.Data.SalvageOpenDelayFirstMs, 0, 5000, 50, v => { state.Data.SalvageOpenDelayFirstMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Open (Fast)", state.Data.SalvageOpenDelayFastMs, 0, 2000, 25, v => { state.Data.SalvageOpenDelayFastMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Add Item (First)", state.Data.SalvageAddDelayFirstMs, 0, 5000, 50, v => { state.Data.SalvageAddDelayFirstMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Add Item (Fast)", state.Data.SalvageAddDelayFastMs, 0, 2000, 25, v => { state.Data.SalvageAddDelayFastMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Salvage Click", state.Data.SalvageSalvageDelayMs, 0, 2000, 25, v => { state.Data.SalvageSalvageDelayMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Result (First)", state.Data.SalvageResultDelayFirstMs, 0, 5000, 50, v => { state.Data.SalvageResultDelayFirstMs = v; Push(state); }));
|
||||
p.Children.Add(IntRow("Result (Fast)", state.Data.SalvageResultDelayFastMs, 0, 2000, 25, v => { state.Data.SalvageResultDelayFastMs = v; Push(state); }));
|
||||
return null;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
|
|
@ -1361,75 +742,8 @@ internal static class SettingsPanel
|
|||
private static Border Spacer() => new Border { Height = 6 };
|
||||
|
||||
// =========================================================================
|
||||
// Plugin bridge
|
||||
// Save
|
||||
// =========================================================================
|
||||
|
||||
// RL loads fresh plugin copies without unloading the old ones: drop the
|
||||
// exports bound below so the next poll re-binds to the live copy.
|
||||
static SettingsPanel() => PluginManager.PluginsUnloaded += () =>
|
||||
{
|
||||
_getSettingsJson = null;
|
||||
_setSettingsJson = null;
|
||||
};
|
||||
|
||||
private static void TryBind()
|
||||
{
|
||||
var plugin = PluginManager.Plugins.FirstOrDefault(
|
||||
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
|
||||
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
|
||||
|
||||
if (_getSettingsJson == null)
|
||||
{
|
||||
IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetSettingsJson");
|
||||
if (p1 != IntPtr.Zero)
|
||||
_getSettingsJson = Marshal.GetDelegateForFunctionPointer<GetSettingsJsonFn>(p1);
|
||||
}
|
||||
if (_setSettingsJson == null)
|
||||
{
|
||||
IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetSettingsJson");
|
||||
if (p2 != IntPtr.Zero)
|
||||
_setSettingsJson = Marshal.GetDelegateForFunctionPointer<SetSettingsJsonFn>(p2);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryFetch(out Settings settings) => TryFetch(out settings, out _);
|
||||
|
||||
private static bool TryFetch(out Settings settings, out string? rawJson)
|
||||
{
|
||||
settings = new Settings();
|
||||
rawJson = null;
|
||||
if (_getSettingsJson == null) return false;
|
||||
try
|
||||
{
|
||||
IntPtr ptr = _getSettingsJson();
|
||||
if (ptr == IntPtr.Zero) return false;
|
||||
string? json = Marshal.PtrToStringAnsi(ptr);
|
||||
if (string.IsNullOrEmpty(json)) return false;
|
||||
var parsed = JsonSerializer.Deserialize(json, SettingsPanelJsonContext.Default.Settings);
|
||||
if (parsed == null) return false;
|
||||
settings = parsed;
|
||||
rawJson = json;
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private static void Push(PanelState state)
|
||||
{
|
||||
if (_setSettingsJson == null) TryBind();
|
||||
if (_setSettingsJson == null) return;
|
||||
IntPtr ansi = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
string json = JsonSerializer.Serialize(state.Data, SettingsPanelJsonContext.Default.Settings);
|
||||
ansi = Marshal.StringToHGlobalAnsi(json);
|
||||
_setSettingsJson(ansi);
|
||||
state.Dirty = false;
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
|
||||
}
|
||||
}
|
||||
private static void Push(PanelState state) => SettingsCommands.Save(state.Data.Clone());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ using Avalonia.Controls;
|
|||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.UI.Panels;
|
||||
|
||||
|
|
@ -19,7 +20,11 @@ internal static class StatusPanel
|
|||
var content = new StackPanel { Spacing = 4 };
|
||||
|
||||
var refreshButton = new Button { Content = "Refresh", HorizontalAlignment = HorizontalAlignment.Left };
|
||||
refreshButton.Click += (_, _) => Populate(content);
|
||||
refreshButton.Click += (_, _) =>
|
||||
{
|
||||
UiSources.PluginStatus.RequestRefresh();
|
||||
Populate(content);
|
||||
};
|
||||
|
||||
var root = new DockPanel { Margin = new Avalonia.Thickness(8) };
|
||||
DockPanel.SetDock(refreshButton, Dock.Bottom);
|
||||
|
|
@ -32,6 +37,29 @@ internal static class StatusPanel
|
|||
};
|
||||
root.Children.Add(scroll);
|
||||
|
||||
// Plugin rows come from UiDataHub (read on the pump thread that owns the
|
||||
// plugin list); repopulate when that snapshot changes.
|
||||
long seen = -1;
|
||||
var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
var snap = UiSources.PluginStatus.Current;
|
||||
if (snap == null || snap.Version == seen) return;
|
||||
seen = snap.Version;
|
||||
Populate(content);
|
||||
};
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
UiSources.PluginStatus.Subscribe();
|
||||
UiSources.PluginStatus.RequestRefresh();
|
||||
if (!timer.IsEnabled) timer.Start();
|
||||
};
|
||||
root.DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
UiSources.PluginStatus.Unsubscribe();
|
||||
};
|
||||
|
||||
Populate(content);
|
||||
return root;
|
||||
}
|
||||
|
|
@ -52,22 +80,33 @@ internal static class StatusPanel
|
|||
Margin = new Avalonia.Thickness(0, 6, 0, 6)
|
||||
});
|
||||
|
||||
var plugins = PluginManager.Plugins;
|
||||
AddHeader(panel, $"Plugins ({plugins.Count})");
|
||||
PluginStatusRow[] plugins = UiSources.PluginStatus.Current?.Value ?? Array.Empty<PluginStatusRow>();
|
||||
AddHeader(panel, $"Plugins ({plugins.Length})");
|
||||
|
||||
if (plugins.Count == 0)
|
||||
if (plugins.Length == 0)
|
||||
{
|
||||
AddRow(panel, "", "None loaded");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var p in plugins)
|
||||
{
|
||||
string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending";
|
||||
string version = p.VersionString.Length > 0 ? $" {p.VersionString}" : "";
|
||||
AddRow(panel, p.DisplayName + version, state, p.Failed);
|
||||
}
|
||||
foreach (PluginStatusRow p in plugins)
|
||||
AddRow(panel, p.Label, p.State, p.IsError);
|
||||
}
|
||||
|
||||
AddSeparator(panel);
|
||||
AddHeader(panel, "UI faces");
|
||||
foreach (string line in PanelRouter.Describe())
|
||||
AddRow(panel, "", line);
|
||||
}
|
||||
|
||||
private static void AddSeparator(StackPanel panel)
|
||||
{
|
||||
panel.Children.Add(new Border
|
||||
{
|
||||
Height = 1,
|
||||
Background = new SolidColorBrush(Color.FromArgb(60, 255, 255, 255)),
|
||||
Margin = new Avalonia.Thickness(0, 6, 0, 6)
|
||||
});
|
||||
}
|
||||
|
||||
private static void AddHeader(StackPanel panel, string text)
|
||||
|
|
|
|||
179
src/RynthCore.Engine/UI/RynthAiDashboardState.cs
Normal file
179
src/RynthCore.Engine/UI/RynthAiDashboardState.cs
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/RynthAiDashboardState.cs
|
||||
// The RynthAi dashboard's minimized state, shared by its Avalonia and ImGui
|
||||
// faces, and the ImGui face's target bar and player vitals toggles,
|
||||
// persisted to %AppData%\RynthCore\rynthai_avalonia.cache (line 1
|
||||
// minimized|expanded, line 2 unused, line 3 target|notarget, line 4
|
||||
// vitals|novitals). 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.
|
||||
//
|
||||
// Deliberately NOT on RynthAiPanel: the engine loads this before
|
||||
// AvaloniaOverlay.Start(), and touching RynthAiPanel there runs its static
|
||||
// constructor, whose brushes create Dispatcher.UIThread on the wrong thread
|
||||
// and kill the whole overlay (PlatformNotSupportedException in MainLoop; see
|
||||
// the invariant in EntryPoint next to ChatModel.EnsureSettingsLoaded).
|
||||
// Keep Avalonia types out of this class.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class RynthAiDashboardState
|
||||
{
|
||||
private static volatile bool _minimized;
|
||||
private static volatile bool _showTargetBar = true;
|
||||
private static volatile bool _showVitals = true;
|
||||
private static volatile bool _showFiles; // the Profile/Nav/Loot/Meta block (folded by default)
|
||||
private static volatile bool _barCollapsed; // the RynthCore bar shows only its grip + expand
|
||||
// The dashboard's size (logical units) with the files folded and open, so flipping
|
||||
// between them brings back each one's own size. Zero = not set yet (fit to content).
|
||||
private static float _foldedW, _foldedH, _openW, _openH;
|
||||
private static bool _loaded;
|
||||
private static readonly object LoadSync = new();
|
||||
|
||||
private static string CachePath =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthai_avalonia.cache");
|
||||
|
||||
/// <summary>Minimized (loaded from disk on first use). Any thread.</summary>
|
||||
public static bool Minimized
|
||||
{
|
||||
get { EnsureLoaded(); return _minimized; }
|
||||
}
|
||||
|
||||
/// <summary>Any thread; the file is written in the background.</summary>
|
||||
public static void SetMinimized(bool minimized)
|
||||
{
|
||||
EnsureLoaded();
|
||||
_minimized = minimized;
|
||||
UiBackgroundWriter.Enqueue("rynthai minimized", Save);
|
||||
}
|
||||
|
||||
/// <summary>The ImGui dashboard shows the target's name and health bar (at its bottom). Any thread.</summary>
|
||||
public static bool ShowTargetBar
|
||||
{
|
||||
get { EnsureLoaded(); return _showTargetBar; }
|
||||
}
|
||||
|
||||
public static void SetShowTargetBar(bool show)
|
||||
{
|
||||
EnsureLoaded();
|
||||
_showTargetBar = show;
|
||||
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
|
||||
}
|
||||
|
||||
/// <summary>The ImGui dashboard shows the player's health, stamina and mana bars (at its bottom). Any thread.</summary>
|
||||
public static bool ShowVitals
|
||||
{
|
||||
get { EnsureLoaded(); return _showVitals; }
|
||||
}
|
||||
|
||||
public static void SetShowVitals(bool show)
|
||||
{
|
||||
EnsureLoaded();
|
||||
_showVitals = show;
|
||||
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
|
||||
}
|
||||
|
||||
/// <summary>The dashboard shows the loaded-files block (Profile/Nav/Loot/Meta pickers, meta state). Any thread.</summary>
|
||||
public static bool ShowFiles
|
||||
{
|
||||
get { EnsureLoaded(); return _showFiles; }
|
||||
}
|
||||
|
||||
public static void SetShowFiles(bool show)
|
||||
{
|
||||
EnsureLoaded();
|
||||
_showFiles = show;
|
||||
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
|
||||
}
|
||||
|
||||
/// <summary>The ImGui bar is collapsed to its grip and an expand button. Any thread.</summary>
|
||||
public static bool BarCollapsed
|
||||
{
|
||||
get { EnsureLoaded(); return _barCollapsed; }
|
||||
}
|
||||
|
||||
public static void SetBarCollapsed(bool collapsed)
|
||||
{
|
||||
EnsureLoaded();
|
||||
_barCollapsed = collapsed;
|
||||
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
|
||||
}
|
||||
|
||||
/// <summary>The size the dashboard had last time with the files folded (open). False if never set.</summary>
|
||||
public static bool TryGetFilesModeSize(bool open, out float width, out float height)
|
||||
{
|
||||
EnsureLoaded();
|
||||
width = open ? _openW : _foldedW;
|
||||
height = open ? _openH : _foldedH;
|
||||
return width > 0 && height > 0;
|
||||
}
|
||||
|
||||
public static void SetFilesModeSize(bool open, float width, float height)
|
||||
{
|
||||
EnsureLoaded();
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (open) { _openW = width; _openH = height; } else { _foldedW = width; _foldedH = height; }
|
||||
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
|
||||
}
|
||||
|
||||
private static void ParseSize(string line, out float w, out float h)
|
||||
{
|
||||
w = h = 0;
|
||||
string[] parts = line.Split(',');
|
||||
if (parts.Length == 2
|
||||
&& float.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float pw)
|
||||
&& float.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float ph))
|
||||
{
|
||||
w = pw; h = ph;
|
||||
}
|
||||
}
|
||||
|
||||
private static string SizeText(float w, float h) =>
|
||||
w > 0 && h > 0 ? FormattableString.Invariant($"{w:0.#},{h:0.#}") : "-";
|
||||
|
||||
/// <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()
|
||||
{
|
||||
if (_loaded) return;
|
||||
lock (LoadSync)
|
||||
{
|
||||
if (_loaded) return;
|
||||
try
|
||||
{
|
||||
string path = CachePath;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
string[] lines = File.ReadAllLines(path);
|
||||
_minimized = lines.Length > 0 && lines[0].Trim().Equals("minimized", StringComparison.OrdinalIgnoreCase);
|
||||
_showTargetBar = lines.Length < 3 || !lines[2].Trim().Equals("notarget", StringComparison.OrdinalIgnoreCase);
|
||||
_showVitals = lines.Length < 4 || !lines[3].Trim().Equals("novitals", StringComparison.OrdinalIgnoreCase);
|
||||
// "filesopen" only once the player opened them; the old "files" default reads as folded.
|
||||
_showFiles = lines.Length >= 5 && lines[4].Trim().Equals("filesopen", StringComparison.OrdinalIgnoreCase);
|
||||
_barCollapsed = lines.Length >= 6 && lines[5].Trim().Equals("barcollapsed", StringComparison.OrdinalIgnoreCase);
|
||||
if (lines.Length >= 7) ParseSize(lines[6].Trim(), out _foldedW, out _foldedH);
|
||||
if (lines.Length >= 8) ParseSize(lines[7].Trim(), out _openW, out _openH);
|
||||
}
|
||||
}
|
||||
catch { /* corrupt cache: start expanded */ }
|
||||
_loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = CachePath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, (_minimized ? "minimized" : "expanded") + "\nadvanced\n"
|
||||
+ (_showTargetBar ? "target" : "notarget") + "\n" + (_showVitals ? "vitals" : "novitals") + "\n"
|
||||
+ (_showFiles ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n"
|
||||
+ SizeText(_foldedW, _foldedH) + "\n" + SizeText(_openW, _openH) + "\n");
|
||||
}
|
||||
catch { /* best-effort */ }
|
||||
}
|
||||
}
|
||||
379
src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs
Normal file
379
src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/ScriptWindows/AcIconDecoder.cs
|
||||
// Script windows: decodes Asheron's Call icons (0x06 Texture files in
|
||||
// client_portal.dat) to RGBA, and stacks an item's underlay, icon and overlay
|
||||
// into one picture. Pure code: no AC memory, no D3D, no engine state, so the
|
||||
// RynthSuite offline tests compile it in and decode real icons.
|
||||
//
|
||||
// The texture formats and their byte layouts are the ones RynthCore.StatusAgent
|
||||
// (Dat/IconDecoder.cs, the phone remote's icons) decodes, ported from
|
||||
// ACEmulator's DatLoader; DXT1/3/5 use the StatusAgent's DxtUtil.cs (MonoGame,
|
||||
// Ms-PL), linked into the engine project. The dat reader is the on-demand
|
||||
// B-tree walk of ImGui/MonsterHud/PortalSpellTable.cs over one open stream:
|
||||
// header at 0x140, a B-tree searched by file id, block chains whose first
|
||||
// dword is the next block's offset.
|
||||
//
|
||||
// Threads: whatever thread owns the AcDatFile (the icon worker). Every read is
|
||||
// bounds-checked; a bad file returns null, never throws out of Decode/Compose.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using ACE.DatLoader;
|
||||
|
||||
namespace RynthCore.Engine.UI.ScriptWindows;
|
||||
|
||||
/// <summary>A read-only portal.dat opened for a batch of reads. Not thread-safe.</summary>
|
||||
internal sealed class AcDatFile : IDisposable
|
||||
{
|
||||
private const int HeaderOffset = 0x140;
|
||||
private const int Branches = 62, MaxEntries = 61, EntrySize = 24;
|
||||
private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716
|
||||
private const int MaxDepth = 16;
|
||||
|
||||
private readonly FileStream _fs;
|
||||
private readonly uint _blockSize;
|
||||
private readonly uint _root;
|
||||
|
||||
private AcDatFile(FileStream fs, uint blockSize, uint root)
|
||||
{
|
||||
_fs = fs;
|
||||
_blockSize = blockSize;
|
||||
_root = root;
|
||||
}
|
||||
|
||||
/// <summary>Opens <paramref name="path"/> read-only, sharing everything (AC holds its own handles).</summary>
|
||||
public static AcDatFile? Open(string path, out string why)
|
||||
{
|
||||
FileStream? fs = null;
|
||||
try
|
||||
{
|
||||
fs = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
|
||||
Span<byte> hdr = stackalloc byte[36];
|
||||
fs.Seek(HeaderOffset, SeekOrigin.Begin);
|
||||
if (!ReadFully(fs, hdr)) { why = "short header"; fs.Dispose(); return null; }
|
||||
uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
|
||||
uint root = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(32, 4));
|
||||
if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length)
|
||||
{
|
||||
why = "bad header";
|
||||
fs.Dispose();
|
||||
return null;
|
||||
}
|
||||
why = string.Empty;
|
||||
return new AcDatFile(fs, blockSize, root);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
fs?.Dispose();
|
||||
why = $"{ex.GetType().Name}: {ex.Message}";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>client_portal.dat (or portal.dat) next to the running exe or in the current directory; null when none.</summary>
|
||||
public static string? FindPortalDat()
|
||||
{
|
||||
var dirs = new List<string>(2);
|
||||
try
|
||||
{
|
||||
string? exe = Environment.ProcessPath;
|
||||
string? dir = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe);
|
||||
if (!string.IsNullOrEmpty(dir)) dirs.Add(dir);
|
||||
}
|
||||
catch { }
|
||||
try { dirs.Add(Environment.CurrentDirectory); } catch { }
|
||||
foreach (string dir in dirs)
|
||||
foreach (string name in new[] { "client_portal.dat", "portal.dat" })
|
||||
{
|
||||
try
|
||||
{
|
||||
string full = Path.Combine(dir, name);
|
||||
if (File.Exists(full)) return full;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A file's bytes by id, or null (not in the dat, over <paramref name="maxSize"/>, or unreadable).</summary>
|
||||
public byte[]? Read(uint fileId, int maxSize)
|
||||
{
|
||||
try
|
||||
{
|
||||
uint offset = _root;
|
||||
for (int depth = 0; depth < MaxDepth && offset != 0; depth++)
|
||||
{
|
||||
byte[]? node = ReadChain(offset, NodeSize);
|
||||
if (node == null) return null;
|
||||
uint count = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches));
|
||||
if (count > MaxEntries) return null;
|
||||
int i = 0;
|
||||
while (i < count && EntryId(node, i) < fileId) i++;
|
||||
if (i < count && EntryId(node, i) == fileId)
|
||||
{
|
||||
int e = 4 * Branches + 4 + i * EntrySize;
|
||||
uint fileOffset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 8));
|
||||
uint fileSize = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 12));
|
||||
if (fileSize == 0 || fileSize > (uint)maxSize) return null;
|
||||
return ReadChain(fileOffset, (int)fileSize);
|
||||
}
|
||||
bool leaf = BinaryPrimitives.ReadUInt32LittleEndian(node) == 0;
|
||||
if (leaf || i >= Branches) return null;
|
||||
offset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(i * 4));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static uint EntryId(byte[] node, int i) =>
|
||||
BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches + 4 + i * EntrySize + 4));
|
||||
|
||||
/// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary>
|
||||
private byte[]? ReadChain(uint offset, int size)
|
||||
{
|
||||
if ((long)offset + 4 > _fs.Length) return null;
|
||||
var buffer = new byte[size];
|
||||
Span<byte> next = stackalloc byte[4];
|
||||
_fs.Seek(offset, SeekOrigin.Begin);
|
||||
if (!ReadFully(_fs, next)) return null;
|
||||
uint nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next);
|
||||
int done = 0;
|
||||
int guard = 0;
|
||||
while (done < size)
|
||||
{
|
||||
int take = Math.Min((int)_blockSize - 4, size - done);
|
||||
if (!ReadFully(_fs, buffer.AsSpan(done, take))) return null;
|
||||
done += take;
|
||||
if (done >= size) break;
|
||||
if (nextAddr == 0 || nextAddr >= _fs.Length || ++guard > 1_000_000) return null;
|
||||
_fs.Seek(nextAddr, SeekOrigin.Begin);
|
||||
if (!ReadFully(_fs, next)) return null;
|
||||
nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static bool ReadFully(FileStream fs, Span<byte> dest)
|
||||
{
|
||||
while (dest.Length > 0)
|
||||
{
|
||||
int n = fs.Read(dest);
|
||||
if (n <= 0) return false;
|
||||
dest = dest.Slice(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose() => _fs.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>An RGBA picture (Pixels = Width * Height * 4, bytes R, G, B, A).</summary>
|
||||
internal sealed class AcIconImage
|
||||
{
|
||||
public int Width;
|
||||
public int Height;
|
||||
public byte[] Pixels = Array.Empty<byte>();
|
||||
}
|
||||
|
||||
internal static class AcIconDecoder
|
||||
{
|
||||
/// <summary>Icons are 32 x 32; anything bigger than this (a UI picture, not an icon) is refused.</summary>
|
||||
public const int MaxSide = 128;
|
||||
/// <summary>The largest side a retail UI picture (a window background, a title bar) may have.</summary>
|
||||
public const int MaxUiSide = 512;
|
||||
private const int MaxTextureFile = 1024 * 1024;
|
||||
private const int MaxPaletteFile = 256 * 1024;
|
||||
|
||||
/// <summary>UtilityBelt's rule for an icon id: below 0x06000000, 0x06000000 is added.</summary>
|
||||
public static uint NormalizeIconId(uint id) => id < 0x06000000u ? id + 0x06000000u : id;
|
||||
|
||||
/// <summary>0x06xxxxxx: a Texture file (icons live there).</summary>
|
||||
public static bool IsTextureId(uint id) => (id >> 24) == 0x06;
|
||||
|
||||
/// <summary>
|
||||
/// The item picture AC shows: the underlay, then the icon, then the overlay, each drawn over
|
||||
/// the last (alpha blended) at the icon's size. 0 = no underlay / overlay. Null when the icon
|
||||
/// itself can't be decoded; an underlay or overlay that can't be is left out.
|
||||
/// </summary>
|
||||
public static AcIconImage? Compose(AcDatFile dat, uint icon, uint underlay, uint overlay)
|
||||
{
|
||||
AcIconImage? baseImage = Decode(dat, icon);
|
||||
if (baseImage == null) return null;
|
||||
AcIconImage? under = underlay != 0 ? Decode(dat, underlay) : null;
|
||||
AcIconImage? over = overlay != 0 ? Decode(dat, overlay) : null;
|
||||
if (under == null && over == null) return baseImage;
|
||||
|
||||
int w = baseImage.Width, h = baseImage.Height;
|
||||
var outPx = new byte[w * h * 4];
|
||||
if (under != null) Over(outPx, w, h, under);
|
||||
Over(outPx, w, h, baseImage);
|
||||
if (over != null) Over(outPx, w, h, over);
|
||||
return new AcIconImage { Width = w, Height = h, Pixels = outPx };
|
||||
}
|
||||
|
||||
/// <summary>Draws <paramref name="src"/> over <paramref name="dst"/> (w x h), scaled nearest-neighbour when sizes differ.</summary>
|
||||
private static void Over(byte[] dst, int w, int h, AcIconImage src)
|
||||
{
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
int sy = src.Height == h ? y : y * src.Height / h;
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
int sx = src.Width == w ? x : x * src.Width / w;
|
||||
int s = (sy * src.Width + sx) * 4, d = (y * w + x) * 4;
|
||||
int sa = src.Pixels[s + 3];
|
||||
if (sa == 0) continue;
|
||||
if (sa == 255)
|
||||
{
|
||||
dst[d] = src.Pixels[s];
|
||||
dst[d + 1] = src.Pixels[s + 1];
|
||||
dst[d + 2] = src.Pixels[s + 2];
|
||||
dst[d + 3] = 255;
|
||||
continue;
|
||||
}
|
||||
int da = dst[d + 3];
|
||||
int outA = sa + da * (255 - sa) / 255;
|
||||
if (outA <= 0) continue;
|
||||
for (int c = 0; c < 3; c++)
|
||||
dst[d + c] = (byte)((src.Pixels[s + c] * sa + dst[d + c] * da * (255 - sa) / 255) / outA);
|
||||
dst[d + 3] = (byte)outA;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A 0x06 Texture as RGBA, or null (not a texture id, missing, an unsupported format, larger
|
||||
/// than <see cref="MaxSide"/>, or short data). Layout: id u32, unknown i32, width i32,
|
||||
/// height i32, format u32, length i32, data[length], then for INDEX16/P8 a palette id u32.
|
||||
/// </summary>
|
||||
public static AcIconImage? Decode(AcDatFile dat, uint textureId) => Decode(dat, textureId, MaxSide);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="Decode(AcDatFile, uint)"/>, allowing sides up to <paramref name="maxSide"/>
|
||||
/// (at most <see cref="MaxUiSide"/>): the retail UI pictures (ImGui/RetailSprites).
|
||||
/// </summary>
|
||||
public static AcIconImage? Decode(AcDatFile dat, uint textureId, int maxSide)
|
||||
{
|
||||
if (!IsTextureId(textureId)) return null;
|
||||
try
|
||||
{
|
||||
byte[]? data = dat.Read(textureId, MaxTextureFile);
|
||||
return data == null ? null : DecodeTextureFile(data, id => dat.Read(id, MaxPaletteFile), maxSide);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Texture file's bytes as RGBA (see <see cref="Decode(AcDatFile, uint)"/>); <paramref name="readPalette"/> loads a 0x04 palette.</summary>
|
||||
internal static AcIconImage? DecodeTextureFile(byte[] data, Func<uint, byte[]?> readPalette, int maxSide = MaxSide)
|
||||
{
|
||||
if (data.Length < 24) return null;
|
||||
maxSide = Math.Clamp(maxSide, 1, MaxUiSide);
|
||||
ReadOnlySpan<byte> d = data;
|
||||
int w = BinaryPrimitives.ReadInt32LittleEndian(d[8..]);
|
||||
int h = BinaryPrimitives.ReadInt32LittleEndian(d[12..]);
|
||||
uint fmt = BinaryPrimitives.ReadUInt32LittleEndian(d[16..]);
|
||||
int len = BinaryPrimitives.ReadInt32LittleEndian(d[20..]);
|
||||
if (w <= 0 || h <= 0 || w > maxSide || h > maxSide || len < 0 || len > data.Length - 24) return null;
|
||||
byte[] src = d.Slice(24, len).ToArray();
|
||||
int n = w * h;
|
||||
|
||||
switch (fmt)
|
||||
{
|
||||
case 827611204: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1); // DXT1
|
||||
case 861165636: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3); // DXT3
|
||||
case 894720068: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5); // DXT5
|
||||
}
|
||||
|
||||
var rgba = new byte[n * 4];
|
||||
void Px(int i, int r, int g, int b, int a)
|
||||
{
|
||||
int o = i * 4;
|
||||
rgba[o] = (byte)r; rgba[o + 1] = (byte)g; rgba[o + 2] = (byte)b; rgba[o + 3] = (byte)a;
|
||||
}
|
||||
|
||||
switch (fmt)
|
||||
{
|
||||
case 20: // R8G8B8, stored B, G, R
|
||||
for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
|
||||
break;
|
||||
case 243: // CUSTOM_LSCAPE_R8G8B8, stored R, G, B
|
||||
for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
|
||||
break;
|
||||
case 21: // A8R8G8B8, stored B, G, R, A
|
||||
case 22: // X8R8G8B8
|
||||
for (int i = 0; i < n && i * 4 + 3 < src.Length; i++)
|
||||
Px(i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], fmt == 22 ? 255 : src[i * 4 + 3]);
|
||||
break;
|
||||
case 23: // R5G6B5
|
||||
for (int i = 0; i < n && i * 2 + 1 < src.Length; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255);
|
||||
}
|
||||
break;
|
||||
case 26: // A4R4G4B4
|
||||
for (int i = 0; i < n && i * 2 + 1 < src.Length; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17);
|
||||
}
|
||||
break;
|
||||
case 28: // A8 (greyscale)
|
||||
case 244: // LSCAPE_ALPHA
|
||||
for (int i = 0; i < n && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255);
|
||||
break;
|
||||
case 101: // INDEX16
|
||||
case 41: // P8
|
||||
{
|
||||
if (data.Length < 24 + len + 4) return null;
|
||||
uint paletteId = BinaryPrimitives.ReadUInt32LittleEndian(d[(24 + len)..]);
|
||||
uint[]? pal = Palette(readPalette(paletteId));
|
||||
if (pal == null || pal.Length == 0) return null;
|
||||
bool p8 = fmt == 41;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int idx;
|
||||
if (p8) { if (i >= src.Length) break; idx = src[i]; }
|
||||
else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); }
|
||||
uint c = pal[idx % pal.Length];
|
||||
Px(i, (int)((c >> 16) & 0xFF), (int)((c >> 8) & 0xFF), (int)(c & 0xFF), (int)((c >> 24) & 0xFF));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return null; // a format icons don't use
|
||||
}
|
||||
return new AcIconImage { Width = w, Height = h, Pixels = rgba };
|
||||
}
|
||||
|
||||
private static AcIconImage? Dxt(byte[] src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> decompress)
|
||||
{
|
||||
long need = (long)((w + 3) / 4) * ((h + 3) / 4) * blockBytes;
|
||||
if (src.Length < need) return null; // DxtUtil would read past the end
|
||||
byte[] rgba = decompress(src, w, h);
|
||||
return rgba.Length == w * h * 4 ? new AcIconImage { Width = w, Height = h, Pixels = rgba } : null;
|
||||
}
|
||||
|
||||
/// <summary>Palette (0x04): id u32, count i32, count x u32 ARGB.</summary>
|
||||
private static uint[]? Palette(byte[]? data)
|
||||
{
|
||||
if (data == null || data.Length < 8) return null;
|
||||
int n = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
|
||||
if (n <= 0 || n > 65536) return null;
|
||||
n = Math.Min(n, (data.Length - 8) / 4);
|
||||
var pal = new uint[n];
|
||||
for (int i = 0; i < n; i++) pal[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4));
|
||||
return pal;
|
||||
}
|
||||
}
|
||||
1007
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs
Normal file
1007
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs
Normal file
File diff suppressed because it is too large
Load diff
962
src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs
Normal file
962
src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs
Normal file
|
|
@ -0,0 +1,962 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/ScriptWindows/ScriptWindowRegistry.cs
|
||||
// Script windows (API v71): owners, their windows, the latest display list
|
||||
// per window and the event queue back to each owner.
|
||||
// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §3, §4.
|
||||
//
|
||||
// Threads:
|
||||
// Submit / PollEvents plugin pump thread, inside the owner's own dispatch
|
||||
// (PluginManager.CurrentDispatch). The buffer is read
|
||||
// or written only during the call.
|
||||
// GetInfo any thread.
|
||||
// Replay (the faces) AC's thread: reads each window's latest list
|
||||
// (Volatile) and appends events under the owner's
|
||||
// short queue lock. It never takes Sync.
|
||||
// The engine never calls into a plugin for this and keeps no plugin pointer:
|
||||
// an owner is the engine's own LoadedPlugin record, dropped at unload.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
using RynthCore.Engine.ImGuiBackend.Panels;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.UI.ScriptWindows;
|
||||
|
||||
/// <summary>
|
||||
/// Event types (format 1, §4.3). Every event starts with u16 Type, u16 Size (whole event),
|
||||
/// u32 Seq, u32 WindowHash, u32 WidgetKey (0 for window-level events); payloads:
|
||||
/// Clicked u16 count, u8 button (0 = left)
|
||||
/// Bool u8 value
|
||||
/// Int i32 value (SliderInt, Combo)
|
||||
/// Float f32 value (SliderFloat)
|
||||
/// Text u8 submitted, u16 length + UTF-8 (≤ 4096 bytes)
|
||||
/// Open u8 open (CollapsingHeader, TreeNode)
|
||||
/// Geometry f32×8 windowPos x,y; windowSize w,h; contentAvail w,h; cursorStart x,y
|
||||
/// (logical units at UI scale 1), u32 flags (bit0 focused, bit1 collapsed, bit2 hovered)
|
||||
/// Visibility u8 visible, u8 reason
|
||||
/// Error u16 length + UTF-8
|
||||
/// </summary>
|
||||
internal static class ScriptEventType
|
||||
{
|
||||
public const ushort Clicked = 1;
|
||||
public const ushort Bool = 2;
|
||||
public const ushort Int = 3;
|
||||
public const ushort Float = 4;
|
||||
public const ushort Text = 5;
|
||||
public const ushort Open = 6;
|
||||
public const ushort Geometry = 7;
|
||||
public const ushort Visibility = 8;
|
||||
public const ushort Error = 10;
|
||||
|
||||
/// <summary>Per-widget value events: coalesced per (type, window, key), latest wins.</summary>
|
||||
public static bool IsValue(ushort type) => type is Bool or Int or Float or Text or Open;
|
||||
}
|
||||
|
||||
/// <summary>Visibility event reasons (§4.3).</summary>
|
||||
internal static class VisibilityReason
|
||||
{
|
||||
public const byte Script = 0;
|
||||
/// <summary>The player closed it with the X (the default for a close the owner didn't ask for).</summary>
|
||||
public const byte PlayerClose = 1;
|
||||
/// <summary>The bar's Scripts menu or a command (the default for an open the owner didn't ask for).</summary>
|
||||
public const byte BarOrCommand = 2;
|
||||
}
|
||||
|
||||
/// <summary>A window's geometry, in logical units at UI scale 1 (Geometry events).</summary>
|
||||
internal struct ScriptGeometry
|
||||
{
|
||||
public Vector2 Pos, Size, Avail, Cursor;
|
||||
public uint Flags;
|
||||
|
||||
public const uint Focused = 1u << 0;
|
||||
public const uint Collapsed = 1u << 1;
|
||||
public const uint Hovered = 1u << 2;
|
||||
}
|
||||
|
||||
/// <summary>One owner's queue of events for the plugin. Appended on AC's thread, drained on the pump thread.</summary>
|
||||
internal sealed class ScriptEventQueue
|
||||
{
|
||||
public const int MaxTextBytes = 4096;
|
||||
|
||||
private struct Item
|
||||
{
|
||||
public ushort Type;
|
||||
public uint Seq;
|
||||
public uint WindowHash;
|
||||
public uint WidgetKey;
|
||||
public int Count; // Clicked
|
||||
public byte Value; // Bool/Open value; Visibility visible; Text submitted
|
||||
public byte Reason; // Visibility reason
|
||||
public int Int; // Int
|
||||
public float Float; // Float
|
||||
public string? Text; // Error
|
||||
public byte[]? Bytes; // Text (UTF-8)
|
||||
public ScriptGeometry Geo; // Geometry
|
||||
}
|
||||
|
||||
private readonly object _lock = new();
|
||||
private readonly List<Item> _items = new();
|
||||
private uint _nextSeq = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Adds a value or geometry event, replacing the queued one for the same (type, window, key)
|
||||
/// (Geometry: the same window). A Text event keeps "submitted" if either had it. Returns the seq.
|
||||
/// </summary>
|
||||
private uint AddCoalesced(Item item)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
uint seq = _nextSeq++;
|
||||
item.Seq = seq;
|
||||
bool geometry = item.Type == ScriptEventType.Geometry;
|
||||
for (int i = 0; i < _items.Count; i++)
|
||||
{
|
||||
Item e = _items[i];
|
||||
if (e.Type == item.Type && e.WindowHash == item.WindowHash && (geometry || e.WidgetKey == item.WidgetKey))
|
||||
{
|
||||
if (item.Type == ScriptEventType.Text) item.Value |= e.Value;
|
||||
_items.RemoveAt(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
MakeRoom();
|
||||
_items.Add(item);
|
||||
return seq;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new integer value (SliderInt, Combo index). Returns the event's seq.</summary>
|
||||
public uint Int(uint windowHash, uint key, int value) =>
|
||||
AddCoalesced(new Item { Type = ScriptEventType.Int, WindowHash = windowHash, WidgetKey = key, Int = value });
|
||||
|
||||
/// <summary>A new float value (SliderFloat). Returns the event's seq.</summary>
|
||||
public uint Float(uint windowHash, uint key, float value) =>
|
||||
AddCoalesced(new Item { Type = ScriptEventType.Float, WindowHash = windowHash, WidgetKey = key, Float = value });
|
||||
|
||||
/// <summary>InputText's text (UTF-8, cut to 4096 bytes); <paramref name="submitted"/> = Enter on an EnterReturnsTrue field.</summary>
|
||||
public uint Text(uint windowHash, uint key, ReadOnlySpan<byte> utf8, bool submitted)
|
||||
{
|
||||
if (utf8.Length > MaxTextBytes)
|
||||
{
|
||||
int n = MaxTextBytes;
|
||||
while (n > 0 && (utf8[n] & 0xC0) == 0x80) n--;
|
||||
utf8 = utf8[..n];
|
||||
}
|
||||
return AddCoalesced(new Item { Type = ScriptEventType.Text, WindowHash = windowHash, WidgetKey = key, Value = submitted ? (byte)1 : (byte)0, Bytes = utf8.ToArray() });
|
||||
}
|
||||
|
||||
/// <summary>A tree node's or collapsing header's live open state. Returns the event's seq.</summary>
|
||||
public uint Open(uint windowHash, uint key, bool open) =>
|
||||
AddCoalesced(new Item { Type = ScriptEventType.Open, WindowHash = windowHash, WidgetKey = key, Value = open ? (byte)1 : (byte)0 });
|
||||
|
||||
/// <summary>The window's geometry changed (coalesced per window). Returns the event's seq.</summary>
|
||||
public uint Geometry(uint windowHash, in ScriptGeometry geo) =>
|
||||
AddCoalesced(new Item { Type = ScriptEventType.Geometry, WindowHash = windowHash, Geo = geo });
|
||||
|
||||
/// <summary>A click on a button: coalesced per widget into a count, never dropped. Returns the event's seq.</summary>
|
||||
public uint Click(uint windowHash, uint key)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
uint seq = _nextSeq++;
|
||||
for (int i = 0; i < _items.Count; i++)
|
||||
{
|
||||
Item e = _items[i];
|
||||
if (e.Type == ScriptEventType.Clicked && e.WindowHash == windowHash && e.WidgetKey == key)
|
||||
{
|
||||
e.Count = Math.Min(e.Count + 1, ushort.MaxValue);
|
||||
e.Seq = seq;
|
||||
_items[i] = e;
|
||||
return seq;
|
||||
}
|
||||
}
|
||||
MakeRoom();
|
||||
_items.Add(new Item { Type = ScriptEventType.Clicked, Seq = seq, WindowHash = windowHash, WidgetKey = key, Count = 1 });
|
||||
return seq;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new bool value: coalesced per widget (the latest wins). Returns the event's seq.</summary>
|
||||
public uint Bool(uint windowHash, uint key, bool value) =>
|
||||
AddCoalesced(new Item { Type = ScriptEventType.Bool, WindowHash = windowHash, WidgetKey = key, Value = value ? (byte)1 : (byte)0 });
|
||||
|
||||
/// <summary>The window was shown or hidden outside the owner's own flag. Returns the event's seq.</summary>
|
||||
public uint Visibility(uint windowHash, bool visible, byte reason)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
uint seq = _nextSeq++;
|
||||
MakeRoom();
|
||||
_items.Add(new Item { Type = ScriptEventType.Visibility, Seq = seq, WindowHash = windowHash, Value = visible ? (byte)1 : (byte)0, Reason = reason });
|
||||
return seq;
|
||||
}
|
||||
}
|
||||
|
||||
public void Error(uint windowHash, string text)
|
||||
{
|
||||
if (text.Length > 1024) text = text[..1024];
|
||||
lock (_lock)
|
||||
{
|
||||
MakeRoom();
|
||||
_items.Add(new Item { Type = ScriptEventType.Error, Seq = _nextSeq++, WindowHash = windowHash, Text = text });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Full: drop the oldest Geometry event, else the oldest value/Open event, else the oldest
|
||||
/// Visibility or Error event. Clicks are counted, never dropped. Caller holds the lock.
|
||||
/// </summary>
|
||||
private void MakeRoom()
|
||||
{
|
||||
if (_items.Count < ScriptWindowRegistry.MaxEventsPerOwner) return;
|
||||
int value = -1, other = -1;
|
||||
for (int i = 0; i < _items.Count; i++)
|
||||
{
|
||||
ushort t = _items[i].Type;
|
||||
if (t == ScriptEventType.Geometry) { _items.RemoveAt(i); return; }
|
||||
if (value < 0 && ScriptEventType.IsValue(t)) value = i;
|
||||
else if (other < 0 && t is ScriptEventType.Visibility or ScriptEventType.Error) other = i;
|
||||
}
|
||||
if (value >= 0) _items.RemoveAt(value);
|
||||
else if (other >= 0) _items.RemoveAt(other);
|
||||
}
|
||||
|
||||
/// <summary>Writes whole events into <paramref name="buffer"/>; returns the bytes written.</summary>
|
||||
public unsafe int Drain(byte* buffer, int capacity, int* remaining)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
int written = 0, taken = 0;
|
||||
var dst = buffer == null || capacity <= 0 ? Span<byte>.Empty : new Span<byte>(buffer, capacity);
|
||||
for (; taken < _items.Count; taken++)
|
||||
{
|
||||
Item e = _items[taken];
|
||||
int size = 16 + e.Type switch
|
||||
{
|
||||
ScriptEventType.Clicked => 3,
|
||||
ScriptEventType.Bool => 1,
|
||||
ScriptEventType.Int => 4,
|
||||
ScriptEventType.Float => 4,
|
||||
ScriptEventType.Text => 3 + (e.Bytes?.Length ?? 0),
|
||||
ScriptEventType.Open => 1,
|
||||
ScriptEventType.Geometry => 36,
|
||||
ScriptEventType.Visibility => 2,
|
||||
ScriptEventType.Error => 2 + Encoding.UTF8.GetByteCount(e.Text ?? string.Empty),
|
||||
_ => 0,
|
||||
};
|
||||
if (written + size > dst.Length) break;
|
||||
Span<byte> o = dst.Slice(written, size);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(o, e.Type);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(o[2..], (ushort)size);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(o[4..], e.Seq);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(o[8..], e.WindowHash);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(o[12..], e.WidgetKey);
|
||||
Span<byte> p = o[16..];
|
||||
switch (e.Type)
|
||||
{
|
||||
case ScriptEventType.Clicked:
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(p, (ushort)e.Count);
|
||||
p[2] = 0; // left button
|
||||
break;
|
||||
case ScriptEventType.Bool:
|
||||
case ScriptEventType.Open:
|
||||
p[0] = e.Value;
|
||||
break;
|
||||
case ScriptEventType.Int:
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(p, e.Int);
|
||||
break;
|
||||
case ScriptEventType.Float:
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p, e.Float);
|
||||
break;
|
||||
case ScriptEventType.Text:
|
||||
{
|
||||
byte[] text = e.Bytes ?? Array.Empty<byte>();
|
||||
p[0] = e.Value;
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(p[1..], (ushort)text.Length);
|
||||
text.CopyTo(p[3..]);
|
||||
break;
|
||||
}
|
||||
case ScriptEventType.Geometry:
|
||||
{
|
||||
ScriptGeometry g = e.Geo;
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p, g.Pos.X);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[4..], g.Pos.Y);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[8..], g.Size.X);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[12..], g.Size.Y);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[16..], g.Avail.X);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[20..], g.Avail.Y);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[24..], g.Cursor.X);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(p[28..], g.Cursor.Y);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(p[32..], g.Flags);
|
||||
break;
|
||||
}
|
||||
case ScriptEventType.Visibility:
|
||||
p[0] = e.Value;
|
||||
p[1] = e.Reason;
|
||||
break;
|
||||
case ScriptEventType.Error:
|
||||
int n = Encoding.UTF8.GetBytes(e.Text ?? string.Empty, p[2..]);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(p, (ushort)n);
|
||||
break;
|
||||
}
|
||||
written += size;
|
||||
}
|
||||
_items.RemoveRange(0, taken);
|
||||
if (remaining != null) *remaining = _items.Count;
|
||||
return written;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A plugin that has script windows.</summary>
|
||||
internal sealed class ScriptWindowOwner
|
||||
{
|
||||
public readonly LoadedPlugin Plugin;
|
||||
public readonly Dictionary<string, ScriptWindow> Windows = new(StringComparer.Ordinal);
|
||||
public readonly ScriptEventQueue Events = new();
|
||||
|
||||
public ScriptWindowOwner(LoadedPlugin plugin) => Plugin = plugin;
|
||||
}
|
||||
|
||||
/// <summary>One script window: shared between the pump thread (submit) and AC's thread (replay).</summary>
|
||||
internal sealed class ScriptWindow
|
||||
{
|
||||
public readonly ScriptWindowOwner Owner;
|
||||
public readonly string Key;
|
||||
public readonly string PanelKey;
|
||||
public readonly uint Hash;
|
||||
|
||||
// Pump thread (Submit), read on AC's thread.
|
||||
private DisplayList _list = DisplayList.Empty;
|
||||
public DisplayList List => Volatile.Read(ref _list);
|
||||
public void Publish(DisplayList list) => Volatile.Write(ref _list, list);
|
||||
public volatile bool SubmittedVisible;
|
||||
public volatile bool Removed;
|
||||
public string Title = string.Empty;
|
||||
public uint Flags;
|
||||
/// <summary>Panel logical units. RequestSize/RequestPos: NaN = none.</summary>
|
||||
public Vector2 DefaultSize, MinSize, RequestSize = new(float.NaN), RequestPos = new(float.NaN);
|
||||
/// <summary>RequestPos is a FirstUseEver default position, used only when nothing is saved.</summary>
|
||||
public bool PosIsDefault;
|
||||
/// <summary>The spec's first-open position (PosIsDefault with a RequestPos); null = the cascade.</summary>
|
||||
public Vector2? DefaultPos;
|
||||
// Pump thread only: the placement requests last passed to the panel host (NaN = none)
|
||||
// and the window's ListSeq at that time (the §3.2 re-application rule).
|
||||
public Vector2 AppliedRequestSize = new(float.NaN), AppliedRequestPos = new(float.NaN);
|
||||
public uint AppliedSizeListSeq, AppliedPosListSeq;
|
||||
|
||||
// Visibility, last change wins (§3.3). The markers are set on the pump thread just
|
||||
// before the owner's own Open/Close and consumed by the face on AC's thread, so an
|
||||
// open or close the owner asked for sends no Visibility event.
|
||||
public volatile bool ExpectOpen, ExpectClose;
|
||||
/// <summary>Seq of the last Visibility event the player caused; an owner flag recorded before it (AckSeq below it) is stale.</summary>
|
||||
public volatile uint PlayerVisibilitySeq;
|
||||
/// <summary>The reason for the next player-caused open/close (0 = none: the face's default). Any thread.</summary>
|
||||
public volatile int PendingReason;
|
||||
// Pump thread only, under Sync: the owner's last submit for this window, kept so a
|
||||
// visibility decision put off while an open/close was still in flight (ApplyVisible)
|
||||
// is made at the owner's next poll, without waiting for another submit.
|
||||
public bool VisibilityDeferred;
|
||||
public uint LastAckSeq;
|
||||
public uint LastListSeq;
|
||||
/// <summary>The script error text the pump thread last applied (compared to avoid re-encoding).</summary>
|
||||
public string? ErrorText;
|
||||
private byte[]? _errorUtf8;
|
||||
/// <summary>The script's error as pinned, NUL-terminated UTF-8; null = no error. Read on AC's thread.</summary>
|
||||
public byte[]? ErrorUtf8 => Volatile.Read(ref _errorUtf8);
|
||||
|
||||
/// <summary>Pump thread: stores the error text, allocating only when it changed.</summary>
|
||||
public void SetError(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) text = null;
|
||||
if (string.Equals(text, ErrorText, StringComparison.Ordinal)) return;
|
||||
ErrorText = text;
|
||||
byte[]? bytes = null;
|
||||
if (text != null)
|
||||
{
|
||||
int n = Encoding.UTF8.GetByteCount(text);
|
||||
bytes = GC.AllocateArray<byte>(n + 1, pinned: true);
|
||||
Encoding.UTF8.GetBytes(text, bytes);
|
||||
}
|
||||
Volatile.Write(ref _errorUtf8, bytes);
|
||||
}
|
||||
|
||||
// AC thread only (replay).
|
||||
/// <summary>The player's edits the plugin hasn't acknowledged yet, and InputText buffers (no snap-back, §2.5).</summary>
|
||||
public readonly ScriptLocals Locals = new();
|
||||
/// <summary>The geometry last sent in a Geometry event (logical units).</summary>
|
||||
public ScriptGeometry LastGeometry;
|
||||
public bool GeometrySent;
|
||||
public DisplayList? LastReplayed;
|
||||
/// <summary>First input not yet reflected in a replayed list: for the click → reaction measurement.</summary>
|
||||
public uint PendingInputSeq;
|
||||
public int PendingInputFrame;
|
||||
public long PendingInputTicks;
|
||||
|
||||
public ScriptWindow(ScriptWindowOwner owner, string key, string panelKey, uint hash)
|
||||
{
|
||||
Owner = owner;
|
||||
Key = key;
|
||||
PanelKey = panelKey;
|
||||
Hash = hash;
|
||||
}
|
||||
|
||||
/// <summary>Records an input for the latency measurement (AC thread).</summary>
|
||||
public void NoteInput(uint seq, int frame)
|
||||
{
|
||||
if (PendingInputSeq != 0) return;
|
||||
PendingInputSeq = seq;
|
||||
PendingInputFrame = frame;
|
||||
PendingInputTicks = Stopwatch.GetTimestamp();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One line of the bar's Scripts menu. Built once per snapshot, never per frame.</summary>
|
||||
internal sealed class ScriptBarItem
|
||||
{
|
||||
public readonly ScriptWindow Window;
|
||||
/// <summary>The key up to its last '/', e.g. "RynthLua/Tracker" (the owner's name when the key has none).</summary>
|
||||
public readonly string Group;
|
||||
/// <summary>True for the first item of its group (the menu draws the group header above it).</summary>
|
||||
public readonly bool GroupStart;
|
||||
/// <summary>The title plus "##sw" and the window hash in hex: unique, and the same across snapshots.</summary>
|
||||
public readonly string MenuLabel;
|
||||
public readonly string PanelKey;
|
||||
|
||||
public ScriptBarItem(ScriptWindow window, string group, bool groupStart)
|
||||
{
|
||||
Window = window;
|
||||
Group = group;
|
||||
GroupStart = groupStart;
|
||||
// A '##' inside the title would cut the visible text short (and '###' replace the ID).
|
||||
string title = window.Title.Contains("##", StringComparison.Ordinal) ? window.Title.Replace("##", "# #") : window.Title;
|
||||
MenuLabel = title + "##sw" + window.Hash.ToString("X8");
|
||||
PanelKey = window.PanelKey;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ScriptWindowRegistry
|
||||
{
|
||||
// §6.1 limits (Phase 0 starting values).
|
||||
public const int MaxOpsPerWindow = 1500;
|
||||
public const int MaxBytesPerWindow = 64 * 1024;
|
||||
public const int MaxWindowsPerOwner = 32;
|
||||
public const int MaxBytesPerSubmit = 256 * 1024;
|
||||
public const int MaxEventsPerOwner = 1024;
|
||||
/// <summary>Ops replayed per frame across all script windows; windows past it draw a placeholder.</summary>
|
||||
public const int MaxReplayOpsPerFrame = 4000;
|
||||
public const string PanelKeyPrefix = "script:";
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<LoadedPlugin, ScriptWindowOwner> Owners = new(ReferenceEqualityComparer.Instance);
|
||||
/// <summary>Panel key → window, across owners: a key belongs to the first owner that used it.</summary>
|
||||
private static readonly Dictionary<string, ScriptWindow> ByPanelKey = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static long _lastRejectLogTicks;
|
||||
|
||||
// The bar's Scripts menu: a copy-on-write snapshot of the ShowInBar windows, republished
|
||||
// (under Sync) when the window set, a title or a ShowInBar flag changed. AC's thread
|
||||
// reads it without taking Sync.
|
||||
private static ScriptBarItem[] _barItems = Array.Empty<ScriptBarItem>();
|
||||
private static bool _barDirty;
|
||||
|
||||
/// <summary>The Scripts menu's items, grouped (empty = no Scripts button). Any thread.</summary>
|
||||
public static ScriptBarItem[] BarItems => Volatile.Read(ref _barItems);
|
||||
|
||||
// ── Host functions ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>UiSubmit: the owner's complete window set. Pump thread, inside the owner's dispatch.</summary>
|
||||
public static unsafe int Submit(LoadedPlugin plugin, byte* data, int length)
|
||||
{
|
||||
float displayMax = DisplayMax();
|
||||
int rc = DisplayListParser.Parse(data, length, displayMax, out uint ackSeq, out List<ParsedWindow> windows, out string error);
|
||||
if (rc != 0)
|
||||
{
|
||||
// Nothing applied: the previous lists stay; the owner hears why.
|
||||
GetOrAddOwner(plugin).Events.Error(0, $"list refused: {error}");
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
if (now - Interlocked.Read(ref _lastRejectLogTicks) > Stopwatch.Frequency * 5)
|
||||
{
|
||||
Interlocked.Exchange(ref _lastRejectLogTicks, now);
|
||||
RynthLog.UI($"ScriptWindows: {plugin.DisplayName} submit refused ({rc}): {error}");
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
lock (Sync)
|
||||
{
|
||||
ScriptWindowOwner owner = GetOrAddOwnerLocked(plugin);
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (ParsedWindow pw in windows)
|
||||
{
|
||||
seen.Add(pw.Key);
|
||||
string panelKey = PanelKeyPrefix + SanitizeKey(pw.Key);
|
||||
if (!owner.Windows.TryGetValue(pw.Key, out ScriptWindow? w))
|
||||
{
|
||||
// Panel keys ignore case and sanitise '=', ',' and '#', so two keys can meet
|
||||
// on one panel entry, from another owner or from this one ("Hud" and "hud").
|
||||
// Sharing it would let each window open, close and unregister the other's.
|
||||
if (ByPanelKey.TryGetValue(panelKey, out ScriptWindow? other))
|
||||
{
|
||||
owner.Events.Error(pw.Hash, other.Owner != owner
|
||||
? $"window '{pw.Key}' belongs to {other.Owner.Plugin.DisplayName}"
|
||||
: $"window '{pw.Key}' clashes with window '{other.Key}' (window keys ignore case, and '=', ',' and '#' count as '_')");
|
||||
continue;
|
||||
}
|
||||
w = new ScriptWindow(owner, pw.Key, panelKey, pw.Hash);
|
||||
owner.Windows[pw.Key] = w;
|
||||
ByPanelKey[panelKey] = w;
|
||||
Apply(w, pw, ackSeq, isNew: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Apply(w, pw, ackSeq, isNew: false);
|
||||
}
|
||||
}
|
||||
|
||||
// A window missing from the set is closed (the script stopped, or the hud was disposed).
|
||||
List<string>? gone = null;
|
||||
foreach (var kv in owner.Windows)
|
||||
if (!seen.Contains(kv.Key)) (gone ??= new List<string>()).Add(kv.Key);
|
||||
if (gone != null)
|
||||
foreach (string key in gone)
|
||||
RemoveLocked(owner, owner.Windows[key]);
|
||||
PublishBarLocked();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>UiPollEvents. Pump thread, inside the owner's dispatch.</summary>
|
||||
public static unsafe int PollEvents(LoadedPlugin plugin, byte* buffer, int capacity, int* remaining)
|
||||
{
|
||||
ScriptWindowOwner? owner;
|
||||
lock (Sync)
|
||||
{
|
||||
if (Owners.TryGetValue(plugin, out owner))
|
||||
RecheckDeferredLocked(owner);
|
||||
}
|
||||
if (owner == null)
|
||||
{
|
||||
if (remaining != null) *remaining = 0;
|
||||
return 0;
|
||||
}
|
||||
return owner.Events.Drain(buffer, capacity, remaining);
|
||||
}
|
||||
|
||||
/// <summary>UiGetInfo. Any thread.</summary>
|
||||
public static unsafe int GetInfo(UiInfoNative* info)
|
||||
{
|
||||
if (info == null) return 0;
|
||||
uint want = info->Size;
|
||||
if (want < 8) return 0;
|
||||
UiInfoNative full = default;
|
||||
full.Size = (uint)sizeof(UiInfoNative);
|
||||
bool imgui = EngineSettings.EnableImGuiBackend;
|
||||
full.Flags = (imgui ? 1u : 0u) | (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete ? 2u : 0u);
|
||||
full.MaxFormatVersion = DisplayListParser.FormatVersion;
|
||||
full.OpLevel = DisplayListParser.OpLevel;
|
||||
full.MaxOpsPerWindow = MaxOpsPerWindow;
|
||||
full.MaxBytesPerWindow = MaxBytesPerWindow;
|
||||
full.MaxWindowsPerOwner = MaxWindowsPerOwner;
|
||||
full.MaxBytesPerSubmit = MaxBytesPerSubmit;
|
||||
ScriptWindowMetrics.Fill(&full);
|
||||
int n = (int)Math.Min(want, (uint)sizeof(UiInfoNative));
|
||||
full.Size = (uint)n;
|
||||
Buffer.MemoryCopy(&full, info, n, n);
|
||||
return imgui ? n : 0;
|
||||
}
|
||||
|
||||
// ── Owners ───────────────────────────────────────────────────────────
|
||||
|
||||
private static ScriptWindowOwner GetOrAddOwner(LoadedPlugin plugin)
|
||||
{
|
||||
lock (Sync) return GetOrAddOwnerLocked(plugin);
|
||||
}
|
||||
|
||||
private static ScriptWindowOwner GetOrAddOwnerLocked(LoadedPlugin plugin)
|
||||
{
|
||||
if (!Owners.TryGetValue(plugin, out ScriptWindowOwner? owner))
|
||||
Owners[plugin] = owner = new ScriptWindowOwner(plugin);
|
||||
return owner;
|
||||
}
|
||||
|
||||
/// <summary>The plugin unloaded (or failed): its windows close and its queue goes. Pump thread.</summary>
|
||||
public static void DropOwner(LoadedPlugin plugin)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (!Owners.TryGetValue(plugin, out ScriptWindowOwner? owner)) return;
|
||||
foreach (ScriptWindow w in new List<ScriptWindow>(owner.Windows.Values))
|
||||
RemoveLocked(owner, w);
|
||||
Owners.Remove(plugin);
|
||||
PublishBarLocked();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>After each tick: owners whose plugin failed lose their windows.</summary>
|
||||
public static void DropFailedOwners()
|
||||
{
|
||||
List<LoadedPlugin>? failed = null;
|
||||
lock (Sync)
|
||||
{
|
||||
if (Owners.Count == 0) return;
|
||||
foreach (LoadedPlugin p in Owners.Keys)
|
||||
if (p.Failed) (failed ??= new List<LoadedPlugin>()).Add(p);
|
||||
}
|
||||
if (failed == null) return;
|
||||
foreach (LoadedPlugin p in failed)
|
||||
{
|
||||
RynthLog.UI($"ScriptWindows: {p.DisplayName} failed; closing its windows.");
|
||||
DropOwner(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Engine shutdown: everything goes.</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
foreach (ScriptWindowOwner owner in new List<ScriptWindowOwner>(Owners.Values))
|
||||
foreach (ScriptWindow w in new List<ScriptWindow>(owner.Windows.Values))
|
||||
RemoveLocked(owner, w);
|
||||
Owners.Clear();
|
||||
ByPanelKey.Clear();
|
||||
_barDirty = false;
|
||||
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the Scripts menu snapshot when something it shows changed. Caller holds Sync.</summary>
|
||||
private static void PublishBarLocked()
|
||||
{
|
||||
if (!_barDirty) return;
|
||||
_barDirty = false;
|
||||
var rows = new List<(string Group, ScriptWindow W)>();
|
||||
foreach (ScriptWindowOwner o in Owners.Values)
|
||||
foreach (ScriptWindow w in o.Windows.Values)
|
||||
{
|
||||
if ((w.Flags & WindowFlags.ShowInBar) == 0) continue;
|
||||
int slash = w.Key.LastIndexOf('/');
|
||||
string group = slash > 0 ? w.Key[..slash] : o.Plugin.DisplayName;
|
||||
rows.Add((group, w));
|
||||
}
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
|
||||
return;
|
||||
}
|
||||
rows.Sort(static (a, b) =>
|
||||
{
|
||||
int c = string.Compare(a.Group, b.Group, StringComparison.OrdinalIgnoreCase);
|
||||
if (c == 0) c = string.Compare(a.Group, b.Group, StringComparison.Ordinal);
|
||||
if (c == 0) c = string.Compare(a.W.Title, b.W.Title, StringComparison.OrdinalIgnoreCase);
|
||||
return c != 0 ? c : string.Compare(a.W.Key, b.W.Key, StringComparison.Ordinal);
|
||||
});
|
||||
var items = new ScriptBarItem[rows.Count];
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
items[i] = new ScriptBarItem(rows[i].W, rows[i].Group,
|
||||
groupStart: i == 0 || !string.Equals(rows[i].Group, rows[i - 1].Group, StringComparison.Ordinal));
|
||||
Volatile.Write(ref _barItems, items);
|
||||
}
|
||||
|
||||
// ── Windows ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The flag bits that shape the panel spec (a change re-registers the entry).</summary>
|
||||
private const uint SpecFlags = WindowFlags.ChromeNone | WindowFlags.NoBackground
|
||||
| WindowFlags.NoScrollbar | WindowFlags.NoScrollWithMouse;
|
||||
|
||||
private static void Apply(ScriptWindow w, ParsedWindow pw, uint ackSeq, bool isNew)
|
||||
{
|
||||
Vector2? defaultPos = pw.PosIsDefault && !float.IsNaN(pw.RequestPos.X) ? pw.RequestPos : null;
|
||||
bool specChanged = isNew || ((w.Flags ^ pw.Flags) & SpecFlags) != 0
|
||||
|| w.DefaultSize != pw.DefaultSize || w.MinSize != pw.MinSize || w.DefaultPos != defaultPos;
|
||||
bool titleChanged = w.Title != pw.Title;
|
||||
if (isNew || titleChanged || ((w.Flags ^ pw.Flags) & WindowFlags.ShowInBar) != 0)
|
||||
_barDirty = true;
|
||||
w.Flags = pw.Flags;
|
||||
w.Title = pw.Title;
|
||||
w.DefaultSize = pw.DefaultSize;
|
||||
w.MinSize = pw.MinSize;
|
||||
w.RequestSize = pw.RequestSize;
|
||||
w.RequestPos = pw.RequestPos;
|
||||
w.PosIsDefault = pw.PosIsDefault;
|
||||
w.DefaultPos = defaultPos;
|
||||
w.SetError((pw.Flags & WindowFlags.HasError) != 0 ? pw.ErrorText : null);
|
||||
if (pw.List != null) w.Publish(pw.List);
|
||||
|
||||
// DrawPanel reads the entry's spec every frame, so a new spec applies at once.
|
||||
if (specChanged)
|
||||
ImGuiPanelHost.RegisterDynamic(w.PanelKey, w.Title, SpecFor(w), () => new ScriptWindowFace(w));
|
||||
else if (titleChanged)
|
||||
ImGuiPanelHost.SetDisplayTitle(w.PanelKey, w.Title);
|
||||
|
||||
w.LastAckSeq = ackSeq;
|
||||
w.LastListSeq = pw.ListSeq;
|
||||
bool opened = ApplyVisible(w, (pw.Flags & WindowFlags.Visible) != 0, ackSeq);
|
||||
ApplyRequests(w, pw.ListSeq, opened);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The visibility decisions ApplyVisible put off while an open/close was in flight, made
|
||||
/// now from the owner's last submit. Without this a window stayed as the in-flight change
|
||||
/// left it until the owner happened to submit again, which a hud whose picture doesn't
|
||||
/// change never does (e.g. hidden and shown again before AC drew a frame, or while AC was
|
||||
/// minimised and drew none). Pump thread (the owner's poll), under Sync.
|
||||
/// </summary>
|
||||
private static void RecheckDeferredLocked(ScriptWindowOwner owner)
|
||||
{
|
||||
foreach (ScriptWindow w in owner.Windows.Values)
|
||||
{
|
||||
if (!w.VisibilityDeferred || w.Removed) continue;
|
||||
if (ApplyVisible(w, w.SubmittedVisible, w.LastAckSeq))
|
||||
ApplyRequests(w, w.LastListSeq, opened: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The owner's Visible flag, last change wins (§3.3). The player's X, the bar and
|
||||
/// /rc ui open|close change the window locally and queue one Visibility event (the
|
||||
/// face's OnShown/OnHidden); the owner's flag is stale until its AckSeq reaches that
|
||||
/// event's seq, and a stale flag neither opens nor closes. Otherwise the window follows
|
||||
/// the flag; the expect markers keep the owner's own open/close from sending an event.
|
||||
/// While a queued open/close hasn't reached AC's thread yet, nothing is decided: the
|
||||
/// player's X closes locally at once but its event is queued only when the close is
|
||||
/// applied, so a submit in between would otherwise reopen it. The decision is kept
|
||||
/// (VisibilityDeferred) and made at the owner's next poll or submit, whichever comes
|
||||
/// first. Returns true when this call opened the window. Pump thread, under Sync.
|
||||
/// </summary>
|
||||
private static bool ApplyVisible(ScriptWindow w, bool visible, uint ackSeq)
|
||||
{
|
||||
w.SubmittedVisible = visible;
|
||||
w.VisibilityDeferred = false;
|
||||
// In-flight first: AC's thread sets PlayerVisibilitySeq (OnShown/OnHidden) before the
|
||||
// entry stops transitioning, so once it has stopped the stale check below sees the seq.
|
||||
if (ImGuiPanelHost.IsTransitioning(w.PanelKey))
|
||||
{
|
||||
w.VisibilityDeferred = true; // decided at the owner's next poll
|
||||
return false;
|
||||
}
|
||||
if (ackSeq < w.PlayerVisibilitySeq) return false; // stale: the player changed it since
|
||||
bool open = ImGuiPanelHost.IsOpen(w.PanelKey);
|
||||
if (visible && !open)
|
||||
{
|
||||
w.ExpectOpen = true;
|
||||
ImGuiPanelHost.Open(w.PanelKey);
|
||||
return true;
|
||||
}
|
||||
if (!visible && open)
|
||||
{
|
||||
w.ExpectClose = true;
|
||||
ImGuiPanelHost.Close(w.PanelKey);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bar's (or a command's) show/hide: the window opens or closes at once and the
|
||||
/// owner gets a Visibility event with reason 2 (bar/command). Any thread.
|
||||
/// </summary>
|
||||
public static void PlayerSetVisible(ScriptWindow w, bool visible)
|
||||
{
|
||||
if (w.Removed || ImGuiPanelHost.IsOpen(w.PanelKey) == visible) return;
|
||||
w.PendingReason = VisibilityReason.BarOrCommand;
|
||||
if (visible) ImGuiPanelHost.Open(w.PanelKey);
|
||||
else ImGuiPanelHost.Close(w.PanelKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SetNextWindowSize / SetNextWindowPos (§3.2): a request is passed to the panel host
|
||||
/// when its value changed since the last one applied, when the window was re-recorded
|
||||
/// (a new ListSeq), or when this submit opens the window. A NaN value (none) forgets the
|
||||
/// last one. The host applies it on the window's next docked frame, after an open's
|
||||
/// placement from the saved state. Pump thread.
|
||||
/// </summary>
|
||||
private static void ApplyRequests(ScriptWindow w, uint listSeq, bool opened)
|
||||
{
|
||||
Vector2 size = w.RequestSize;
|
||||
if (float.IsNaN(size.X))
|
||||
{
|
||||
w.AppliedRequestSize = new Vector2(float.NaN);
|
||||
}
|
||||
else if (opened || size != w.AppliedRequestSize || listSeq != w.AppliedSizeListSeq)
|
||||
{
|
||||
w.AppliedRequestSize = size;
|
||||
w.AppliedSizeListSeq = listSeq;
|
||||
ImGuiPanelHost.RequestSize(w.PanelKey, size);
|
||||
}
|
||||
|
||||
Vector2 pos = w.RequestPos;
|
||||
if (float.IsNaN(pos.X) || w.PosIsDefault)
|
||||
{
|
||||
// None, or a FirstUseEver default (the spec's DefaultPos), which is not a request.
|
||||
w.AppliedRequestPos = new Vector2(float.NaN);
|
||||
}
|
||||
else if (opened || pos != w.AppliedRequestPos || listSeq != w.AppliedPosListSeq)
|
||||
{
|
||||
w.AppliedRequestPos = pos;
|
||||
w.AppliedPosListSeq = listSeq;
|
||||
ImGuiPanelHost.RequestPos(w.PanelKey, pos);
|
||||
}
|
||||
}
|
||||
|
||||
private static PanelSpec SpecFor(ScriptWindow w)
|
||||
{
|
||||
Vector2 size = w.DefaultSize;
|
||||
if (size.X <= 0) size.X = 300;
|
||||
if (size.Y <= 0) size.Y = 200;
|
||||
Vector2 min = Vector2.Max(w.MinSize, new Vector2(60, 40));
|
||||
uint f = w.Flags;
|
||||
bool none = (f & WindowFlags.ChromeNone) != 0;
|
||||
ImGuiNET.ImGuiWindowFlags body = ImGuiNET.ImGuiWindowFlags.None;
|
||||
if ((f & WindowFlags.NoScrollbar) != 0) body |= ImGuiNET.ImGuiWindowFlags.NoScrollbar;
|
||||
if ((f & WindowFlags.NoScrollWithMouse) != 0) body |= ImGuiNET.ImGuiWindowFlags.NoScrollWithMouse;
|
||||
// ClickThrough stays on the face (IImGuiPanel.ClickThrough), read every frame.
|
||||
// Pop-outs aren't in the MVP (decision 8): no ↗.
|
||||
return new PanelSpec(size, min, none ? PanelChrome.None : PanelChrome.Standard,
|
||||
Background: (f & WindowFlags.NoBackground) != 0 ? 0u : null,
|
||||
NoPopOut: true,
|
||||
BodyFlags: body,
|
||||
DefaultPos: w.DefaultPos);
|
||||
}
|
||||
|
||||
private static void RemoveLocked(ScriptWindowOwner owner, ScriptWindow w)
|
||||
{
|
||||
w.Removed = true;
|
||||
w.SubmittedVisible = false;
|
||||
_barDirty = true;
|
||||
owner.Windows.Remove(w.Key);
|
||||
if (ByPanelKey.TryGetValue(w.PanelKey, out ScriptWindow? cur) && ReferenceEquals(cur, w))
|
||||
ByPanelKey.Remove(w.PanelKey);
|
||||
ImGuiPanelHost.Unregister(w.PanelKey);
|
||||
}
|
||||
|
||||
/// <summary>PanelStateStore rows are "panel.<key>=..." lines: no '=', ',' or control characters.</summary>
|
||||
private static string SanitizeKey(string key)
|
||||
{
|
||||
var sb = new StringBuilder(key.Length);
|
||||
foreach (char c in key) sb.Append(c is '=' or ',' or '#' || char.IsControl(c) ? '_' : c);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static float DisplayMax()
|
||||
{
|
||||
float m = ScriptWindowMetrics.DisplayMax;
|
||||
return m > 0 ? m : 16384f;
|
||||
}
|
||||
|
||||
/// <summary>A line per owner and window, for diagnostics. Any thread.</summary>
|
||||
public static List<string> Describe()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
lock (Sync)
|
||||
{
|
||||
foreach (ScriptWindowOwner o in Owners.Values)
|
||||
foreach (ScriptWindow w in o.Windows.Values)
|
||||
lines.Add($"script window {w.PanelKey}: owner={o.Plugin.DisplayName} visible={w.SubmittedVisible} open={ImGuiPanelHost.IsOpen(w.PanelKey)}"
|
||||
+ $" flags=0x{w.Flags:X3}({DescribeFlags(w.Flags)}) error={(w.ErrorUtf8 != null ? "shown" : "none")}"
|
||||
+ $" ops={w.List.OpCount} listSeq={w.List.ListSeq} playerSeq={w.PlayerVisibilitySeq}");
|
||||
}
|
||||
lines.Add($"script windows: {BarItems.Length} in the bar's Scripts menu");
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static string DescribeFlags(uint f)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
void Add(uint bit, string name) { if ((f & bit) != 0) { if (sb.Length > 0) sb.Append('|'); sb.Append(name); } }
|
||||
Add(WindowFlags.Visible, "Visible");
|
||||
Add(WindowFlags.ShowInBar, "ShowInBar");
|
||||
Add(WindowFlags.ChromeNone, "ChromeNone");
|
||||
Add(WindowFlags.ClickThrough, "ClickThrough");
|
||||
Add(WindowFlags.NoBackground, "NoBackground");
|
||||
Add(WindowFlags.NoScrollbar, "NoScrollbar");
|
||||
Add(WindowFlags.NoScrollWithMouse, "NoScrollWithMouse");
|
||||
Add(WindowFlags.AutoSize, "AutoSize");
|
||||
Add(WindowFlags.NoPopOut, "NoPopOut");
|
||||
Add(WindowFlags.HasError, "HasError");
|
||||
Add(WindowFlags.PosIsDefault, "PosIsDefault");
|
||||
return sb.Length > 0 ? sb.ToString() : "none";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Layout facts for UiGetInfo, taken on AC's thread while a script window
|
||||
/// draws (the panel's font pushed) and published as one snapshot.
|
||||
/// </summary>
|
||||
internal static unsafe class ScriptWindowMetrics
|
||||
{
|
||||
private sealed class Snapshot
|
||||
{
|
||||
public float DisplayW, DisplayH, UiScale, LineH, FrameH, SpacingX, SpacingY, PadX, PadY;
|
||||
public readonly float[] Advance = new float[95];
|
||||
public uint Frame;
|
||||
}
|
||||
|
||||
private static Snapshot? _current;
|
||||
private static long _takenAt;
|
||||
|
||||
public static float DisplayMax
|
||||
{
|
||||
get
|
||||
{
|
||||
Snapshot? s = Volatile.Read(ref _current);
|
||||
return s == null ? 0 : 4f * Math.Max(s.DisplayW, s.DisplayH);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Retakes the snapshot about once a second. AC thread, inside the ImGui frame.</summary>
|
||||
public static void Refresh()
|
||||
{
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
if (_current != null && now - _takenAt < Stopwatch.Frequency) return;
|
||||
_takenAt = now;
|
||||
var io = ImGuiNET.ImGui.GetIO();
|
||||
var style = ImGuiNET.ImGui.GetStyle();
|
||||
var s = new Snapshot
|
||||
{
|
||||
DisplayW = io.DisplaySize.X,
|
||||
DisplayH = io.DisplaySize.Y,
|
||||
UiScale = EngineFrameController.FontScale,
|
||||
LineH = ImGuiNET.ImGui.GetTextLineHeight(),
|
||||
FrameH = ImGuiNET.ImGui.GetFrameHeight(),
|
||||
SpacingX = style.ItemSpacing.X,
|
||||
SpacingY = style.ItemSpacing.Y,
|
||||
PadX = style.FramePadding.X,
|
||||
PadY = style.FramePadding.Y,
|
||||
Frame = (uint)ImGuiNET.ImGui.GetFrameCount(),
|
||||
};
|
||||
byte* one = stackalloc byte[2];
|
||||
for (int i = 0; i < 95; i++)
|
||||
{
|
||||
one[0] = (byte)(' ' + i);
|
||||
one[1] = 0;
|
||||
Vector2 size;
|
||||
ImGuiNET.ImGuiNative.igCalcTextSize(&size, one, one + 1, 0, -1f);
|
||||
s.Advance[i] = size.X;
|
||||
}
|
||||
Volatile.Write(ref _current, s);
|
||||
}
|
||||
|
||||
public static void Fill(UiInfoNative* info)
|
||||
{
|
||||
Snapshot? s = Volatile.Read(ref _current);
|
||||
if (s == null) return;
|
||||
info->DisplayWidth = s.DisplayW;
|
||||
info->DisplayHeight = s.DisplayH;
|
||||
info->UiScale = s.UiScale;
|
||||
info->TextLineHeight = s.LineH;
|
||||
info->FrameHeight = s.FrameH;
|
||||
info->ItemSpacingX = s.SpacingX;
|
||||
info->ItemSpacingY = s.SpacingY;
|
||||
info->FramePaddingX = s.PadX;
|
||||
info->FramePaddingY = s.PadY;
|
||||
for (int i = 0; i < 95; i++) info->AsciiAdvance[i] = s.Advance[i];
|
||||
info->FrameCounter = s.Frame;
|
||||
}
|
||||
}
|
||||
74
src/RynthCore.Engine/UI/TrackerSettings.cs
Normal file
74
src/RynthCore.Engine/UI/TrackerSettings.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/TrackerSettings.cs
|
||||
// The Tracker panel's background opacity, shared by its ImGui and Avalonia
|
||||
// faces: %APPDATA%\RynthCore\rynthtracker_settings.json ({"bgAlpha":0-255}).
|
||||
// Loaded on the engine init worker; saves go through UiBackgroundWriter so
|
||||
// the ImGui face never writes a file from AC's thread.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class TrackerSettings
|
||||
{
|
||||
private static volatile int _bgAlpha = 0xCC; // ~80%
|
||||
private static volatile bool _loaded;
|
||||
private static readonly object LoadSync = new();
|
||||
|
||||
private static string SettingsPath =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthtracker_settings.json");
|
||||
|
||||
/// <summary>Background alpha 0-255.</summary>
|
||||
public static byte BgAlpha
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return (byte)_bgAlpha;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sets the alpha now; <paramref name="save"/> writes the file in the background.</summary>
|
||||
public static void SetBgAlpha(byte alpha, bool save)
|
||||
{
|
||||
EnsureLoaded();
|
||||
_bgAlpha = alpha;
|
||||
if (save)
|
||||
UiBackgroundWriter.Enqueue("tracker settings", Save);
|
||||
}
|
||||
|
||||
public static void EnsureLoaded()
|
||||
{
|
||||
if (_loaded) return;
|
||||
lock (LoadSync)
|
||||
{
|
||||
if (_loaded) return;
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
if (doc.RootElement.TryGetProperty("bgAlpha", out var v))
|
||||
_bgAlpha = Math.Clamp(v.GetInt32(), 0, 255);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
_loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
54
src/RynthCore.Engine/UI/UiBackgroundWriter.cs
Normal file
54
src/RynthCore.Engine/UI/UiBackgroundWriter.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - UI/UiBackgroundWriter.cs
|
||||
// Runs UI persistence (panel_state.txt, per-panel settings files) off the
|
||||
// calling thread, strictly in the order it was queued.
|
||||
//
|
||||
// ImGui panel faces run on AC's render thread, which must not do file I/O
|
||||
// (docs/IMGUI_PARITY_PLAN.md §4.1). Order matters: closing an ImGui face and
|
||||
// then popping the panel out writes the same panel_state row twice, and the
|
||||
// second write must win. One queue, drained by one pool work item at a time.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.UI;
|
||||
|
||||
internal static class UiBackgroundWriter
|
||||
{
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Queue<(string Label, Action Work)> Pending = new();
|
||||
private static bool _draining;
|
||||
|
||||
public static void Enqueue(string label, Action work)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
Pending.Enqueue((label, work));
|
||||
if (_draining) return;
|
||||
_draining = true;
|
||||
}
|
||||
ThreadPool.UnsafeQueueUserWorkItem(static _ => Drain(), null);
|
||||
}
|
||||
|
||||
private static void Drain()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
(string Label, Action Work) item;
|
||||
lock (Sync)
|
||||
{
|
||||
if (Pending.Count == 0)
|
||||
{
|
||||
_draining = false;
|
||||
return;
|
||||
}
|
||||
item = Pending.Dequeue();
|
||||
}
|
||||
|
||||
try { item.Work(); }
|
||||
catch (Exception ex) { RynthLog.UI($"UiBackgroundWriter: '{item.Label}' threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue