feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history
Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.
Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
parent
ac0d743e16
commit
4ddbb52eb2
244 changed files with 59710 additions and 3067 deletions
161
src/RynthCore.StatusAgent/AgentConfig.cs
Normal file
161
src/RynthCore.StatusAgent/AgentConfig.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Agent configuration, loaded from %APPDATA%\RynthCore\statusagent.json.
|
||||
/// The agent writes a commented template here on first run and never sends
|
||||
/// anything until <see cref="Endpoint"/> is set to a non-empty URL.
|
||||
/// </summary>
|
||||
internal sealed class AgentConfig
|
||||
{
|
||||
/// <summary>Backend URL the agent POSTs the status payload to. EMPTY = the
|
||||
/// agent never opens a network connection (local print-only mode).</summary>
|
||||
[JsonPropertyName("Endpoint")] public string Endpoint { get; set; } = "";
|
||||
|
||||
/// <summary>Optional auth header sent with each POST (e.g. "Authorization").</summary>
|
||||
[JsonPropertyName("AuthHeaderName")] public string AuthHeaderName { get; set; } = "Authorization";
|
||||
|
||||
/// <summary>Value for <see cref="AuthHeaderName"/> (e.g. "Bearer <token>"). Empty = no header.</summary>
|
||||
[JsonPropertyName("AuthHeaderValue")] public string AuthHeaderValue { get; set; } = "";
|
||||
|
||||
/// <summary>Seconds between status posts.</summary>
|
||||
[JsonPropertyName("IntervalSeconds")] public int IntervalSeconds { get; set; } = 5;
|
||||
|
||||
/// <summary>HTTP request timeout in seconds.</summary>
|
||||
[JsonPropertyName("TimeoutSeconds")] public int TimeoutSeconds { get; set; } = 15;
|
||||
|
||||
/// <summary>Directory holding the engine's per-client status files.</summary>
|
||||
[JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = @"C:\Games\RynthCore\Logs\status";
|
||||
|
||||
/// <summary>Directory holding per-client RynthCore.<pid>.log files (heartbeat fallback).</summary>
|
||||
[JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = @"C:\Games\RynthCore\Logs";
|
||||
|
||||
/// <summary>When true and no status file exists for a running client, derive
|
||||
/// basic status from that client's heartbeat log line. Lets the agent work
|
||||
/// even if EnableStatusExport is off (you just don't get bot/macro detail).</summary>
|
||||
[JsonPropertyName("UseHeartbeatLogFallback")] public bool UseHeartbeatLogFallback { get; set; } = true;
|
||||
|
||||
/// <summary>A live-PID client whose snapshot is older than this is reported "hung".</summary>
|
||||
[JsonPropertyName("StaleAfterSeconds")] public int StaleAfterSeconds { get; set; } = 12;
|
||||
|
||||
/// <summary>A dead-PID status file older than this is reported once then deleted.</summary>
|
||||
[JsonPropertyName("DropDeadAfterSeconds")] public int DropDeadAfterSeconds { get; set; } = 300;
|
||||
|
||||
/// <summary>Label for this machine in the payload. Empty = use the machine name.</summary>
|
||||
[JsonPropertyName("Host")] public string Host { get; set; } = "";
|
||||
|
||||
// ── Pull delivery: let an app fetch status instead of (or as well as) POST ──
|
||||
|
||||
/// <summary>When true, the agent serves the latest status at GET /status on
|
||||
/// <see cref="ServePrefix"/> so an app can pull it with no backend. Default
|
||||
/// false — no socket is opened unless you turn this on.</summary>
|
||||
[JsonPropertyName("ServeHttp")] public bool ServeHttp { get; set; } = false;
|
||||
|
||||
/// <summary>HttpListener prefix to serve on. 127.0.0.1 = this PC only (no
|
||||
/// admin needed). Use http://+:8740/ for LAN/Tailscale (needs a one-time
|
||||
/// netsh urlacl or running elevated). Must end in '/'.</summary>
|
||||
[JsonPropertyName("ServePrefix")] public string ServePrefix { get; set; } = "http://127.0.0.1:8740/";
|
||||
|
||||
/// <summary>Shared secret, required when <see cref="ServeHttp"/> is on: every route but
|
||||
/// /healthz needs <c>Authorization: Bearer <token></c> or <c>?token=</c>. Empty =
|
||||
/// the server stays off, on any bind (it can stream the screens and click in them).</summary>
|
||||
[JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = "";
|
||||
|
||||
/// <summary>When true, also write the latest rollup to
|
||||
/// Logs\status\aggregate.json — handy for file-sync delivery or debugging.</summary>
|
||||
[JsonPropertyName("WriteAggregateFile")] public bool WriteAggregateFile { get; set; } = true;
|
||||
|
||||
/// <summary>When true, the agent accepts <c>POST /command</c> and writes a command file the
|
||||
/// RynthAi plugin polls + applies (toggle nav/combat, start/stop, switch profile, clear busy).
|
||||
/// Default FALSE — read-only unless you opt in. POST honours <see cref="ServeToken"/> like GET.
|
||||
/// Commands are written under <see cref="StatusDirectory"/>\commands.</summary>
|
||||
[JsonPropertyName("EnableRemoteControl")] public bool EnableRemoteControl { get; set; } = false;
|
||||
|
||||
/// <summary>When true, the agent serves a live screen capture of an AC client window:
|
||||
/// <c>GET /stream?pid=N</c> (MJPEG) and <c>GET /frame?pid=N</c> (single JPEG). Captures the
|
||||
/// window's on-screen rectangle ONLY while a client is connected — no cost otherwise. Default
|
||||
/// FALSE. Honours <see cref="ServeToken"/>. Only captures windows that are actually rendering
|
||||
/// (visible/restored — a minimized client has no frame).</summary>
|
||||
[JsonPropertyName("EnableScreenStream")] public bool EnableScreenStream { get; set; } = false;
|
||||
|
||||
/// <summary>JPEG quality (1–100) and target frame interval (ms) for the screen stream.</summary>
|
||||
[JsonPropertyName("StreamQuality")] public int StreamQuality { get; set; } = 55;
|
||||
[JsonPropertyName("StreamIntervalMs")] public int StreamIntervalMs { get; set; } = 400;
|
||||
|
||||
/// <summary>HD video mode (WebRTC H.264). Opt-in, default FALSE. Adds POST /webrtc/offer + /webrtc/stop
|
||||
/// (token-gated); captures+encodes a pid's window ONLY while a viewer is connected. Heavier than the
|
||||
/// MJPEG stream (a per-pid ffmpeg encoder) — leave off unless you want the low-latency "HD" view.</summary>
|
||||
[JsonPropertyName("EnableVideoStream")] public bool EnableVideoStream { get; set; } = false;
|
||||
/// <summary>HD video (ddagrab GPU capture): cap width (0 = native window size — sharper; lower it,
|
||||
/// e.g. 1280, to favour hitting 60fps on a slower CPU), nominal fps, and target bitrate (kbps).</summary>
|
||||
[JsonPropertyName("VideoMaxWidth")] public int VideoMaxWidth { get; set; } = 0; // 0 = native (VideoToolbox has no level cap)
|
||||
[JsonPropertyName("VideoFps")] public int VideoFps { get; set; } = 60;
|
||||
[JsonPropertyName("VideoBitrateKbps")] public int VideoBitrateKbps { get; set; } = 12000;
|
||||
|
||||
/// <summary>portal.dat used to decode item icons for GET /icon (read-only inventory viewer). Defaults to
|
||||
/// the RynthCore client's private copy. If the file is absent (e.g. an agent running off the game box)
|
||||
/// /icon 404s and the app falls back to text rows — no other feature is affected.</summary>
|
||||
[JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_portal.dat";
|
||||
|
||||
/// <summary>Directory of RynthAi's baked dungeon floor-plan maps ({landblock:X8}_{layer}.bin), served as
|
||||
/// PNGs via GET /map for the app's dungeon-map viewer. If the folder is absent (agent off the game box)
|
||||
/// /maps returns an empty list and /map 404s — no other feature is affected.</summary>
|
||||
[JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
|
||||
public static string DefaultConfigPath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "statusagent.json");
|
||||
|
||||
// Indented, trim-safe context just for writing the human-edited template.
|
||||
private static readonly AgentJsonContext IndentedContext =
|
||||
new(new JsonSerializerOptions { WriteIndented = true });
|
||||
|
||||
/// <summary>
|
||||
/// Load config from <paramref name="path"/>, creating a default template if
|
||||
/// it doesn't exist. <paramref name="created"/> is set true when a fresh
|
||||
/// template was written, so the caller can tell the user where it lives.
|
||||
/// </summary>
|
||||
public static AgentConfig LoadOrCreate(string path, out bool created)
|
||||
{
|
||||
created = false;
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
string json = File.ReadAllText(path);
|
||||
AgentConfig? cfg = JsonSerializer.Deserialize(json, AgentJsonContext.Default.AgentConfig);
|
||||
if (cfg != null) return cfg;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Warn($"Failed to read config '{path}' ({ex.Message}); using defaults.");
|
||||
return new AgentConfig();
|
||||
}
|
||||
|
||||
var fresh = new AgentConfig();
|
||||
try
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (dir != null) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(fresh, IndentedContext.AgentConfig));
|
||||
created = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Warn($"Could not write template config '{path}' ({ex.Message}).");
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
public string EffectiveHost =>
|
||||
string.IsNullOrWhiteSpace(Host) ? SafeMachineName() : Host;
|
||||
|
||||
private static string SafeMachineName()
|
||||
{
|
||||
try { return Environment.MachineName; }
|
||||
catch { return "unknown"; }
|
||||
}
|
||||
}
|
||||
41
src/RynthCore.StatusAgent/AgentLog.cs
Normal file
41
src/RynthCore.StatusAgent/AgentLog.cs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>Tiny console + file logger. Best-effort; never throws.</summary>
|
||||
internal static class AgentLog
|
||||
{
|
||||
private static string? _logFile;
|
||||
private static readonly object Gate = new();
|
||||
public static bool Verbose;
|
||||
|
||||
public static void Init(string logDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDirectory);
|
||||
_logFile = Path.Combine(logDirectory, "StatusAgent.log");
|
||||
}
|
||||
catch { _logFile = null; }
|
||||
}
|
||||
|
||||
public static void Info(string msg) => Write("INF", msg);
|
||||
public static void Warn(string msg) => Write("WRN", msg);
|
||||
public static void Error(string msg) => Write("ERR", msg);
|
||||
|
||||
public static void Debug(string msg)
|
||||
{
|
||||
if (Verbose) Write("DBG", msg);
|
||||
}
|
||||
|
||||
private static void Write(string level, string msg)
|
||||
{
|
||||
string line = $"[{DateTime.Now:HH:mm:ss.fff}] [{level}] {msg}";
|
||||
lock (Gate)
|
||||
{
|
||||
try { Console.WriteLine(line); } catch { }
|
||||
if (_logFile != null)
|
||||
{
|
||||
try { File.AppendAllText(_logFile, line + Environment.NewLine); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
77
src/RynthCore.StatusAgent/BackendPublisher.cs
Normal file
77
src/RynthCore.StatusAgent/BackendPublisher.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// POSTs the aggregate payload to the user-configured endpoint. If no endpoint
|
||||
/// is configured it does nothing — the agent never opens a connection on its
|
||||
/// own. Retries a few times with backoff on transient failures.
|
||||
/// </summary>
|
||||
internal sealed class BackendPublisher : IDisposable
|
||||
{
|
||||
private readonly AgentConfig _cfg;
|
||||
private readonly HttpClient _http;
|
||||
private readonly bool _enabled;
|
||||
|
||||
public bool Enabled => _enabled;
|
||||
|
||||
public BackendPublisher(AgentConfig cfg)
|
||||
{
|
||||
_cfg = cfg;
|
||||
_enabled = !string.IsNullOrWhiteSpace(cfg.Endpoint);
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(Math.Max(1, cfg.TimeoutSeconds)) };
|
||||
}
|
||||
|
||||
public async Task<bool> PublishAsync(byte[] jsonUtf8, int clientCount, CancellationToken ct)
|
||||
{
|
||||
if (!_enabled)
|
||||
return false;
|
||||
|
||||
const int maxAttempts = 3;
|
||||
for (int attempt = 1; attempt <= maxAttempts; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Post, _cfg.Endpoint)
|
||||
{
|
||||
Content = new ByteArrayContent(jsonUtf8)
|
||||
};
|
||||
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
|
||||
if (!string.IsNullOrWhiteSpace(_cfg.AuthHeaderName) &&
|
||||
!string.IsNullOrWhiteSpace(_cfg.AuthHeaderValue))
|
||||
{
|
||||
req.Headers.TryAddWithoutValidation(_cfg.AuthHeaderName, _cfg.AuthHeaderValue);
|
||||
}
|
||||
|
||||
using HttpResponseMessage resp = await _http.SendAsync(req, ct).ConfigureAwait(false);
|
||||
if (resp.IsSuccessStatusCode)
|
||||
{
|
||||
AgentLog.Debug($"POST {(int)resp.StatusCode} {resp.ReasonPhrase} ({clientCount} clients).");
|
||||
return true;
|
||||
}
|
||||
|
||||
AgentLog.Warn($"POST attempt {attempt}/{maxAttempts} -> HTTP {(int)resp.StatusCode} {resp.ReasonPhrase}.");
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Warn($"POST attempt {attempt}/{maxAttempts} failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
|
||||
if (attempt < maxAttempts)
|
||||
{
|
||||
try { await Task.Delay(TimeSpan.FromSeconds(2 * attempt), ct).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { throw; }
|
||||
}
|
||||
}
|
||||
|
||||
AgentLog.Error("POST failed after all retries; will try again next cycle.");
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Dispose() => _http.Dispose();
|
||||
}
|
||||
395
src/RynthCore.StatusAgent/Dat/DatDatabase.cs
Normal file
395
src/RynthCore.StatusAgent/Dat/DatDatabase.cs
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore2.TerrainData;
|
||||
|
||||
/// <summary>
|
||||
/// AC .dat file reader — ported directly from ACEmulator's DatLoader.
|
||||
///
|
||||
/// Key format details (from ACE source):
|
||||
/// - Header at file offset 0x140
|
||||
/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset)
|
||||
/// Remaining (BlockSize - 4) bytes = data
|
||||
/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total
|
||||
/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets
|
||||
/// </summary>
|
||||
public class DatDatabase : IDisposable
|
||||
{
|
||||
private FileStream? _stream;
|
||||
private readonly object _lock = new();
|
||||
|
||||
private const uint DAT_HEADER_OFFSET = 0x140;
|
||||
|
||||
// B-tree geometry (from ACE DatDirectoryHeader.cs):
|
||||
// 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes
|
||||
// ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716
|
||||
private const int BTREE_BRANCH_COUNT = 0x3E; // 62
|
||||
private const int BTREE_MAX_ENTRIES = 0x3D; // 61
|
||||
private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32
|
||||
private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716
|
||||
|
||||
/// <summary>Dat header FileType field.</summary>
|
||||
public uint FileType { get; private set; }
|
||||
/// <summary>Block size in bytes (typical: 1024).</summary>
|
||||
public uint BlockSize { get; private set; }
|
||||
/// <summary>Total file size from header.</summary>
|
||||
public uint FileSize { get; private set; }
|
||||
/// <summary>DataSet field from header.</summary>
|
||||
public uint DataSet { get; private set; }
|
||||
/// <summary>Byte offset of the root B-tree node.</summary>
|
||||
public uint BTreeRoot { get; private set; }
|
||||
|
||||
/// <summary>True once <see cref="Open"/> completes successfully.</summary>
|
||||
public bool IsLoaded { get; private set; }
|
||||
/// <summary>Source file path passed to <see cref="Open"/>.</summary>
|
||||
public string? FilePath { get; private set; }
|
||||
/// <summary>Number of files indexed from the B-tree.</summary>
|
||||
public int RecordCount { get; private set; }
|
||||
|
||||
// All files indexed by ObjectId (populated during Open)
|
||||
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new();
|
||||
|
||||
/// <summary>Most-recent diagnostic messages (capped at 100).</summary>
|
||||
public List<string> DiagLog { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Opens the .dat file at <paramref name="path"/> for read-only random access and
|
||||
/// indexes every entry in the B-tree. Returns false on any failure.
|
||||
/// </summary>
|
||||
public bool Open(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Log($"File not found: {path}");
|
||||
return false;
|
||||
}
|
||||
|
||||
FilePath = path;
|
||||
// Plugin init runs *before* acclient.exe opens its own DAT files,
|
||||
// so our handle is the first one Windows sees on the file. Our
|
||||
// share-mode dictates what AC's subsequent open can request — if
|
||||
// we omit FileShare.Delete, AC's open (which needs delete-rename
|
||||
// semantics for DDD/patcher) fails with a sharing violation and
|
||||
// the AC client errors out with "cannot access the data files."
|
||||
//
|
||||
// FileShare.ReadWrite | FileShare.Delete = permit other openers
|
||||
// to read, write, and delete-mark the file. RandomAccess hint +
|
||||
// 4 KB buffer keeps the .dat B-tree reads efficient.
|
||||
_stream = new FileStream(
|
||||
path,
|
||||
FileMode.Open,
|
||||
FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete,
|
||||
bufferSize: 4096,
|
||||
options: FileOptions.RandomAccess);
|
||||
|
||||
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
|
||||
|
||||
if (!ReadHeader())
|
||||
{
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read the entire B-tree directory and index all files
|
||||
ReadDirectory(BTreeRoot);
|
||||
|
||||
RecordCount = _allFiles.Count;
|
||||
IsLoaded = true;
|
||||
|
||||
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error: {ex.Message}");
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the dat header from offset 0x140.
|
||||
/// Format matches ACE's DatDatabaseHeader.Unpack().
|
||||
/// </summary>
|
||||
private bool ReadHeader()
|
||||
{
|
||||
if (_stream == null) return false;
|
||||
if (_stream.Length < DAT_HEADER_OFFSET + 64)
|
||||
{
|
||||
Log("File too small");
|
||||
return false;
|
||||
}
|
||||
|
||||
_stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin);
|
||||
using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true))
|
||||
{
|
||||
FileType = reader.ReadUInt32();
|
||||
BlockSize = reader.ReadUInt32();
|
||||
FileSize = reader.ReadUInt32();
|
||||
DataSet = reader.ReadUInt32();
|
||||
_ = reader.ReadUInt32(); // dataSubset (unused)
|
||||
|
||||
_ = reader.ReadUInt32(); // freeHead (unused)
|
||||
_ = reader.ReadUInt32(); // freeTail (unused)
|
||||
_ = reader.ReadUInt32(); // freeCount (unused)
|
||||
BTreeRoot = reader.ReadUInt32();
|
||||
}
|
||||
|
||||
Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}");
|
||||
|
||||
if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
|
||||
{
|
||||
Log("Invalid header values");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads data from the dat file following the block chain.
|
||||
/// Matches ACE's DatReader.ReadDat() exactly.
|
||||
///
|
||||
/// Block format:
|
||||
/// [4 bytes: next block address] [BlockSize - 4 bytes: data]
|
||||
///
|
||||
/// The FIRST 4 bytes of each block are the chain pointer (next block address).
|
||||
/// If 0, this is the last block.
|
||||
/// </summary>
|
||||
private byte[]? ReadDatData(uint offset, int size)
|
||||
{
|
||||
if (_stream == null) return null;
|
||||
if (offset + BlockSize > (uint)_stream.Length || size <= 0)
|
||||
return null;
|
||||
|
||||
byte[] buffer = new byte[size];
|
||||
|
||||
_stream.Seek(offset, SeekOrigin.Begin);
|
||||
|
||||
// Read first 4 bytes = next block address
|
||||
byte[] addrBuf = new byte[4];
|
||||
_ = _stream.Read(addrBuf, 0, 4);
|
||||
uint nextAddress = BitConverter.ToUInt32(addrBuf, 0);
|
||||
|
||||
int bufferOffset = 0;
|
||||
int remaining = size;
|
||||
|
||||
while (remaining > 0)
|
||||
{
|
||||
if (nextAddress == 0)
|
||||
{
|
||||
// Last block — read remaining data directly
|
||||
int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position));
|
||||
if (toRead <= 0) break;
|
||||
_ = _stream.Read(buffer, bufferOffset, toRead);
|
||||
remaining = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Read data portion of this block (BlockSize - 4 bytes)
|
||||
int dataInBlock = (int)BlockSize - 4;
|
||||
int toRead = Math.Min(dataInBlock, remaining);
|
||||
_ = _stream.Read(buffer, bufferOffset, toRead);
|
||||
bufferOffset += toRead;
|
||||
remaining -= toRead;
|
||||
|
||||
if (remaining > 0)
|
||||
{
|
||||
// Follow chain to next block
|
||||
if (nextAddress >= (uint)_stream.Length) break;
|
||||
_stream.Seek(nextAddress, SeekOrigin.Begin);
|
||||
|
||||
// Read next block's chain pointer
|
||||
_ = _stream.Read(addrBuf, 0, 4);
|
||||
nextAddress = BitConverter.ToUInt32(addrBuf, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively reads the B-tree directory and indexes all files.
|
||||
/// Matches ACE's DatDirectory.Read() + AddFilesToList().
|
||||
/// </summary>
|
||||
private void ReadDirectory(uint sectorOffset)
|
||||
{
|
||||
if (_stream == null) return;
|
||||
if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length)
|
||||
return;
|
||||
|
||||
// Read the directory header (B-tree node)
|
||||
byte[]? nodeData;
|
||||
lock (_lock)
|
||||
{
|
||||
nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE);
|
||||
}
|
||||
|
||||
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
|
||||
return;
|
||||
|
||||
// Parse branches (62 × uint32)
|
||||
uint[] branches = new uint[BTREE_BRANCH_COUNT];
|
||||
for (int i = 0; i < BTREE_BRANCH_COUNT; i++)
|
||||
branches[i] = BitConverter.ToUInt32(nodeData, i * 4);
|
||||
|
||||
// Parse entry count
|
||||
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
|
||||
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
|
||||
|
||||
if (entryCount > BTREE_MAX_ENTRIES)
|
||||
return; // Invalid node
|
||||
|
||||
// Parse entries
|
||||
int entriesOffset = countOffset + 4; // 252
|
||||
var entries = new DatBTreeEntry[entryCount];
|
||||
|
||||
for (int i = 0; i < entryCount; i++)
|
||||
{
|
||||
int eOff = entriesOffset + i * BTREE_ENTRY_SIZE;
|
||||
entries[i] = new DatBTreeEntry
|
||||
{
|
||||
BitFlags = BitConverter.ToUInt32(nodeData, eOff),
|
||||
ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4),
|
||||
FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8),
|
||||
FileSize = BitConverter.ToUInt32(nodeData, eOff + 12),
|
||||
};
|
||||
}
|
||||
|
||||
// Recurse into child directories (if branches[0] != 0, node has children)
|
||||
if (branches[0] != 0)
|
||||
{
|
||||
for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++)
|
||||
{
|
||||
if (branches[i] != 0)
|
||||
ReadDirectory(branches[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add entries to the file index
|
||||
for (int i = 0; i < entryCount; i++)
|
||||
{
|
||||
if (entries[i].ObjectId != 0)
|
||||
_allFiles[entries[i].ObjectId] = entries[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a file by ID. O(1) lookup from the pre-built index.
|
||||
/// </summary>
|
||||
public DatBTreeEntry? FindFile(uint fileId)
|
||||
{
|
||||
if (!IsLoaded) return null;
|
||||
_allFiles.TryGetValue(fileId, out var entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads file data for a given entry.
|
||||
/// </summary>
|
||||
public byte[]? ReadFileData(DatBTreeEntry? entry)
|
||||
{
|
||||
if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null)
|
||||
return null;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
return ReadDatData(entry.FileOffset, (int)entry.FileSize);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Convenience: find by id then read.</summary>
|
||||
public byte[]? GetFileData(uint fileId)
|
||||
{
|
||||
var entry = FindFile(fileId);
|
||||
return entry != null ? ReadFileData(entry) : null;
|
||||
}
|
||||
|
||||
/// <summary>Returns (fileId, storedSize) for every indexed file whose id is in [lo, hi], sorted by size desc.</summary>
|
||||
public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi)
|
||||
{
|
||||
var list = new List<(uint, uint)>();
|
||||
if (!IsLoaded) return list;
|
||||
foreach (var kv in _allFiles)
|
||||
if (kv.Key >= lo && kv.Key <= hi)
|
||||
list.Add((kv.Key, kv.Value.FileSize));
|
||||
list.Sort((a, b) => b.Item2.CompareTo(a.Item2));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock from the dat index.
|
||||
/// This avoids the sequential scan gap cutoff that misses cells in large dungeons.
|
||||
/// </summary>
|
||||
public List<uint> GetLandblockCellIds(uint landblockKey)
|
||||
{
|
||||
var cellIds = new List<uint>();
|
||||
if (!IsLoaded) return cellIds;
|
||||
|
||||
uint prefix = landblockKey << 16;
|
||||
foreach (var id in _allFiles.Keys)
|
||||
{
|
||||
if ((id & 0xFFFF0000) != prefix) continue;
|
||||
uint cell = id & 0xFFFF;
|
||||
if (cell >= 0x0100 && cell <= 0xFFFD)
|
||||
cellIds.Add(id);
|
||||
}
|
||||
return cellIds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns sample file IDs from the index for diagnostics.
|
||||
/// </summary>
|
||||
public List<uint> GetSampleIds(int maxCount = 20)
|
||||
{
|
||||
var ids = new List<uint>();
|
||||
foreach (var kvp in _allFiles)
|
||||
{
|
||||
ids.Add(kvp.Key);
|
||||
if (ids.Count >= maxCount) break;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <summary>Closes the underlying file handle and clears the index.</summary>
|
||||
public void Close()
|
||||
{
|
||||
_stream?.Dispose();
|
||||
_stream = null;
|
||||
IsLoaded = false;
|
||||
_allFiles.Clear();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
Close();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private void Log(string msg)
|
||||
{
|
||||
string line = $"[DatDB] {msg}";
|
||||
System.Diagnostics.Debug.WriteLine(line);
|
||||
if (DiagLog.Count < 100) DiagLog.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Indexed B-tree entry for one file inside a .dat archive.</summary>
|
||||
public class DatBTreeEntry
|
||||
{
|
||||
/// <summary>Raw flag bits from the B-tree.</summary>
|
||||
public uint BitFlags { get; set; }
|
||||
/// <summary>Object ID (the file's key in the B-tree).</summary>
|
||||
public uint ObjectId { get; set; }
|
||||
/// <summary>Byte offset of the first block of the file's chain.</summary>
|
||||
public uint FileOffset { get; set; }
|
||||
/// <summary>Logical file size in bytes.</summary>
|
||||
public uint FileSize { get; set; }
|
||||
}
|
||||
442
src/RynthCore.StatusAgent/Dat/DxtUtil.cs
Normal file
442
src/RynthCore.StatusAgent/Dat/DxtUtil.cs
Normal file
|
|
@ -0,0 +1,442 @@
|
|||
// #region License
|
||||
// /*
|
||||
// Microsoft Public License (Ms-PL)
|
||||
// MonoGame - Copyright © 2009 The MonoGame Team
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
|
||||
// accept the license, do not use the software.
|
||||
//
|
||||
// 1. Definitions
|
||||
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
|
||||
// U.S. copyright law.
|
||||
//
|
||||
// A "contribution" is the original software, or any additions or changes to the software.
|
||||
// A "contributor" is any person that distributes its contribution under this license.
|
||||
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
|
||||
//
|
||||
// 2. Grant of Rights
|
||||
// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
|
||||
// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
|
||||
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
|
||||
// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
|
||||
//
|
||||
// 3. Conditions and Limitations
|
||||
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
|
||||
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
|
||||
// your patent license from such contributor to the software ends automatically.
|
||||
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
|
||||
// notices that are present in the software.
|
||||
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
|
||||
// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
|
||||
// code form, you may only do so under a license that complies with this license.
|
||||
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
|
||||
// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
|
||||
// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
|
||||
// purpose and non-infringement.
|
||||
// */
|
||||
// #endregion License
|
||||
//
|
||||
|
||||
namespace ACE.DatLoader
|
||||
{
|
||||
using System.IO;
|
||||
|
||||
public static class DxtUtil
|
||||
{
|
||||
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
|
||||
{
|
||||
using (MemoryStream imageStream = new MemoryStream(imageData))
|
||||
return DecompressDxt1(imageStream, width, height);
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
|
||||
{
|
||||
byte[] imageData = new byte[width * height * 4];
|
||||
|
||||
using (BinaryReader imageReader = new BinaryReader(imageStream))
|
||||
{
|
||||
int blockCountX = (width + 3) / 4;
|
||||
int blockCountY = (height + 3) / 4;
|
||||
|
||||
for (int y = 0; y < blockCountY; y++)
|
||||
{
|
||||
for (int x = 0; x < blockCountX; x++)
|
||||
{
|
||||
DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return imageData;
|
||||
}
|
||||
|
||||
private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
|
||||
{
|
||||
ushort c0 = imageReader.ReadUInt16();
|
||||
ushort c1 = imageReader.ReadUInt16();
|
||||
|
||||
byte r0, g0, b0;
|
||||
byte r1, g1, b1;
|
||||
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
|
||||
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
|
||||
|
||||
uint lookupTable = imageReader.ReadUInt32();
|
||||
|
||||
for (int blockY = 0; blockY < 4; blockY++)
|
||||
{
|
||||
for (int blockX = 0; blockX < 4; blockX++)
|
||||
{
|
||||
byte r = 0, g = 0, b = 0, a = 255;
|
||||
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
|
||||
|
||||
if (c0 > c1)
|
||||
{
|
||||
switch (index)
|
||||
{
|
||||
case 0:
|
||||
r = r0;
|
||||
g = g0;
|
||||
b = b0;
|
||||
break;
|
||||
case 1:
|
||||
r = r1;
|
||||
g = g1;
|
||||
b = b1;
|
||||
break;
|
||||
case 2:
|
||||
r = (byte)((2 * r0 + r1) / 3);
|
||||
g = (byte)((2 * g0 + g1) / 3);
|
||||
b = (byte)((2 * b0 + b1) / 3);
|
||||
break;
|
||||
case 3:
|
||||
r = (byte)((r0 + 2 * r1) / 3);
|
||||
g = (byte)((g0 + 2 * g1) / 3);
|
||||
b = (byte)((b0 + 2 * b1) / 3);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (index)
|
||||
{
|
||||
case 0:
|
||||
r = r0;
|
||||
g = g0;
|
||||
b = b0;
|
||||
break;
|
||||
case 1:
|
||||
r = r1;
|
||||
g = g1;
|
||||
b = b1;
|
||||
break;
|
||||
case 2:
|
||||
r = (byte)((r0 + r1) / 2);
|
||||
g = (byte)((g0 + g1) / 2);
|
||||
b = (byte)((b0 + b1) / 2);
|
||||
break;
|
||||
case 3:
|
||||
r = 0;
|
||||
g = 0;
|
||||
b = 0;
|
||||
a = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int px = (x << 2) + blockX;
|
||||
int py = (y << 2) + blockY;
|
||||
if ((px < width) && (py < height))
|
||||
{
|
||||
int offset = ((py * width) + px) << 2;
|
||||
imageData[offset] = r;
|
||||
imageData[offset + 1] = g;
|
||||
imageData[offset + 2] = b;
|
||||
imageData[offset + 3] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
|
||||
{
|
||||
using (MemoryStream imageStream = new MemoryStream(imageData))
|
||||
return DecompressDxt3(imageStream, width, height);
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
|
||||
{
|
||||
byte[] imageData = new byte[width * height * 4];
|
||||
|
||||
using (BinaryReader imageReader = new BinaryReader(imageStream))
|
||||
{
|
||||
int blockCountX = (width + 3) / 4;
|
||||
int blockCountY = (height + 3) / 4;
|
||||
|
||||
for (int y = 0; y < blockCountY; y++)
|
||||
{
|
||||
for (int x = 0; x < blockCountX; x++)
|
||||
{
|
||||
DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return imageData;
|
||||
}
|
||||
|
||||
private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
|
||||
{
|
||||
byte a0 = imageReader.ReadByte();
|
||||
byte a1 = imageReader.ReadByte();
|
||||
byte a2 = imageReader.ReadByte();
|
||||
byte a3 = imageReader.ReadByte();
|
||||
byte a4 = imageReader.ReadByte();
|
||||
byte a5 = imageReader.ReadByte();
|
||||
byte a6 = imageReader.ReadByte();
|
||||
byte a7 = imageReader.ReadByte();
|
||||
|
||||
ushort c0 = imageReader.ReadUInt16();
|
||||
ushort c1 = imageReader.ReadUInt16();
|
||||
|
||||
byte r0, g0, b0;
|
||||
byte r1, g1, b1;
|
||||
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
|
||||
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
|
||||
|
||||
uint lookupTable = imageReader.ReadUInt32();
|
||||
|
||||
int alphaIndex = 0;
|
||||
for (int blockY = 0; blockY < 4; blockY++)
|
||||
{
|
||||
for (int blockX = 0; blockX < 4; blockX++)
|
||||
{
|
||||
byte r = 0, g = 0, b = 0, a = 0;
|
||||
|
||||
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
|
||||
|
||||
switch (alphaIndex)
|
||||
{
|
||||
case 0:
|
||||
a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4));
|
||||
break;
|
||||
case 1:
|
||||
a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4));
|
||||
break;
|
||||
case 2:
|
||||
a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4));
|
||||
break;
|
||||
case 3:
|
||||
a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4));
|
||||
break;
|
||||
case 4:
|
||||
a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4));
|
||||
break;
|
||||
case 5:
|
||||
a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4));
|
||||
break;
|
||||
case 6:
|
||||
a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4));
|
||||
break;
|
||||
case 7:
|
||||
a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4));
|
||||
break;
|
||||
case 8:
|
||||
a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4));
|
||||
break;
|
||||
case 9:
|
||||
a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4));
|
||||
break;
|
||||
case 10:
|
||||
a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4));
|
||||
break;
|
||||
case 11:
|
||||
a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4));
|
||||
break;
|
||||
case 12:
|
||||
a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4));
|
||||
break;
|
||||
case 13:
|
||||
a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4));
|
||||
break;
|
||||
case 14:
|
||||
a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4));
|
||||
break;
|
||||
case 15:
|
||||
a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4));
|
||||
break;
|
||||
}
|
||||
++alphaIndex;
|
||||
|
||||
switch (index)
|
||||
{
|
||||
case 0:
|
||||
r = r0;
|
||||
g = g0;
|
||||
b = b0;
|
||||
break;
|
||||
case 1:
|
||||
r = r1;
|
||||
g = g1;
|
||||
b = b1;
|
||||
break;
|
||||
case 2:
|
||||
r = (byte)((2 * r0 + r1) / 3);
|
||||
g = (byte)((2 * g0 + g1) / 3);
|
||||
b = (byte)((2 * b0 + b1) / 3);
|
||||
break;
|
||||
case 3:
|
||||
r = (byte)((r0 + 2 * r1) / 3);
|
||||
g = (byte)((g0 + 2 * g1) / 3);
|
||||
b = (byte)((b0 + 2 * b1) / 3);
|
||||
break;
|
||||
}
|
||||
|
||||
int px = (x << 2) + blockX;
|
||||
int py = (y << 2) + blockY;
|
||||
if ((px < width) && (py < height))
|
||||
{
|
||||
int offset = ((py * width) + px) << 2;
|
||||
imageData[offset] = r;
|
||||
imageData[offset + 1] = g;
|
||||
imageData[offset + 2] = b;
|
||||
imageData[offset + 3] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height)
|
||||
{
|
||||
using (MemoryStream imageStream = new MemoryStream(imageData))
|
||||
return DecompressDxt5(imageStream, width, height);
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height)
|
||||
{
|
||||
byte[] imageData = new byte[width * height * 4];
|
||||
|
||||
using (BinaryReader imageReader = new BinaryReader(imageStream))
|
||||
{
|
||||
int blockCountX = (width + 3) / 4;
|
||||
int blockCountY = (height + 3) / 4;
|
||||
|
||||
for (int y = 0; y < blockCountY; y++)
|
||||
{
|
||||
for (int x = 0; x < blockCountX; x++)
|
||||
{
|
||||
DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return imageData;
|
||||
}
|
||||
|
||||
private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
|
||||
{
|
||||
byte alpha0 = imageReader.ReadByte();
|
||||
byte alpha1 = imageReader.ReadByte();
|
||||
|
||||
ulong alphaMask = (ulong)imageReader.ReadByte();
|
||||
alphaMask += (ulong)imageReader.ReadByte() << 8;
|
||||
alphaMask += (ulong)imageReader.ReadByte() << 16;
|
||||
alphaMask += (ulong)imageReader.ReadByte() << 24;
|
||||
alphaMask += (ulong)imageReader.ReadByte() << 32;
|
||||
alphaMask += (ulong)imageReader.ReadByte() << 40;
|
||||
|
||||
ushort c0 = imageReader.ReadUInt16();
|
||||
ushort c1 = imageReader.ReadUInt16();
|
||||
|
||||
byte r0, g0, b0;
|
||||
byte r1, g1, b1;
|
||||
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
|
||||
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
|
||||
|
||||
uint lookupTable = imageReader.ReadUInt32();
|
||||
|
||||
for (int blockY = 0; blockY < 4; blockY++)
|
||||
{
|
||||
for (int blockX = 0; blockX < 4; blockX++)
|
||||
{
|
||||
byte r = 0, g = 0, b = 0, a = 255;
|
||||
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
|
||||
|
||||
uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07);
|
||||
if (alphaIndex == 0)
|
||||
{
|
||||
a = alpha0;
|
||||
}
|
||||
else if (alphaIndex == 1)
|
||||
{
|
||||
a = alpha1;
|
||||
}
|
||||
else if (alpha0 > alpha1)
|
||||
{
|
||||
a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7);
|
||||
}
|
||||
else if (alphaIndex == 6)
|
||||
{
|
||||
a = 0;
|
||||
}
|
||||
else if (alphaIndex == 7)
|
||||
{
|
||||
a = 0xff;
|
||||
}
|
||||
else
|
||||
{
|
||||
a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5);
|
||||
}
|
||||
|
||||
switch (index)
|
||||
{
|
||||
case 0:
|
||||
r = r0;
|
||||
g = g0;
|
||||
b = b0;
|
||||
break;
|
||||
case 1:
|
||||
r = r1;
|
||||
g = g1;
|
||||
b = b1;
|
||||
break;
|
||||
case 2:
|
||||
r = (byte)((2 * r0 + r1) / 3);
|
||||
g = (byte)((2 * g0 + g1) / 3);
|
||||
b = (byte)((2 * b0 + b1) / 3);
|
||||
break;
|
||||
case 3:
|
||||
r = (byte)((r0 + 2 * r1) / 3);
|
||||
g = (byte)((g0 + 2 * g1) / 3);
|
||||
b = (byte)((b0 + 2 * b1) / 3);
|
||||
break;
|
||||
}
|
||||
|
||||
int px = (x << 2) + blockX;
|
||||
int py = (y << 2) + blockY;
|
||||
if ((px < width) && (py < height))
|
||||
{
|
||||
int offset = ((py * width) + px) << 2;
|
||||
imageData[offset] = r;
|
||||
imageData[offset + 1] = g;
|
||||
imageData[offset + 2] = b;
|
||||
imageData[offset + 3] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b)
|
||||
{
|
||||
int temp;
|
||||
|
||||
temp = (color >> 11) * 255 + 16;
|
||||
r = (byte)((temp / 32 + temp) / 32);
|
||||
temp = ((color & 0x07E0) >> 5) * 255 + 32;
|
||||
g = (byte)((temp / 64 + temp) / 64);
|
||||
temp = (color & 0x001F) * 255 + 16;
|
||||
b = (byte)((temp / 32 + temp) / 32);
|
||||
}
|
||||
}
|
||||
}
|
||||
115
src/RynthCore.StatusAgent/Dat/IconDecoder.cs
Normal file
115
src/RynthCore.StatusAgent/Dat/IconDecoder.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
using ACE.DatLoader;
|
||||
using RynthCore2.TerrainData;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes an AC item ICON to RGBA pixels. An item's icon DID (PWD _iconID, range 0x06xxxxxx) points
|
||||
/// straight at a 0x06 Texture in portal.dat, so this is the Texture path only — trimmed from
|
||||
/// AcClientReborn's AcTextureDecoder (no Surface/SurfaceTexture/clothing). Format byte-layout + the
|
||||
/// format constants are ported verbatim from ACEmulator's DatLoader.
|
||||
/// </summary>
|
||||
internal sealed class IconDecoder
|
||||
{
|
||||
private readonly DatDatabase _portal;
|
||||
public IconDecoder(DatDatabase portal) { _portal = portal; }
|
||||
|
||||
/// <summary>Decoded RGBA bitmap (Pixels = w*h*4, bytes in R,G,B,A order).</summary>
|
||||
public sealed class Rgba
|
||||
{
|
||||
public int Width;
|
||||
public int Height;
|
||||
public byte[] Pixels = System.Array.Empty<byte>();
|
||||
}
|
||||
|
||||
// Palette (0x04): Id(u32), Colors(List<uint>: i32 count + u32[] ARGB).
|
||||
private uint[]? LoadPalette(uint paletteId)
|
||||
{
|
||||
byte[]? data = _portal.GetFileData(paletteId);
|
||||
if (data == null || data.Length < 8) return null;
|
||||
using var ms = new MemoryStream(data);
|
||||
using var r = new BinaryReader(ms);
|
||||
r.ReadUInt32();
|
||||
int n = r.ReadInt32();
|
||||
if (n <= 0 || n > 100000) return null;
|
||||
var pal = new uint[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (ms.Position + 4 > ms.Length) { System.Array.Resize(ref pal, i); break; }
|
||||
pal[i] = r.ReadUInt32();
|
||||
}
|
||||
return pal;
|
||||
}
|
||||
|
||||
// Texture (0x06): Id(u32),Unknown(i32),Width(i32),Height(i32),Format(u32),Length(i32),Source[Length],
|
||||
// if INDEX16/P8: DefaultPaletteId(u32).
|
||||
public Rgba? Decode(uint textureId)
|
||||
{
|
||||
byte[]? data = _portal.GetFileData(textureId);
|
||||
if (data == null || data.Length < 24) return null;
|
||||
using var ms = new MemoryStream(data);
|
||||
using var r = new BinaryReader(ms);
|
||||
r.ReadUInt32(); r.ReadInt32();
|
||||
int w = r.ReadInt32(), h = r.ReadInt32();
|
||||
uint fmt = r.ReadUInt32();
|
||||
int len = r.ReadInt32();
|
||||
if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || len < 0 || ms.Position + len > ms.Length) return null;
|
||||
byte[] src = r.ReadBytes(len);
|
||||
uint defPal = 0;
|
||||
if (fmt == 101 /*INDEX16*/ || fmt == 41 /*P8*/) { if (ms.Position + 4 <= ms.Length) defPal = r.ReadUInt32(); }
|
||||
|
||||
var rgba = new byte[w * h * 4];
|
||||
void Px(int i, int rr, int gg, int bb, int aa) { int o = i * 4; rgba[o] = (byte)rr; rgba[o + 1] = (byte)gg; rgba[o + 2] = (byte)bb; rgba[o + 3] = (byte)aa; }
|
||||
|
||||
switch (fmt)
|
||||
{
|
||||
case 827611204: return Wrap(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1
|
||||
case 861165636: return Wrap(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3
|
||||
case 894720068: return Wrap(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5
|
||||
case 20: // R8G8B8 (stored B,G,R)
|
||||
for (int i = 0; i < w * h && 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 < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
|
||||
break;
|
||||
case 21: // A8R8G8B8
|
||||
case 22: // X8R8G8B8
|
||||
for (int i = 0; i < w * h && i * 4 + 3 < src.Length; i++)
|
||||
{ int b = src[i * 4], g = src[i * 4 + 1], rr = src[i * 4 + 2], a = fmt == 22 ? 255 : src[i * 4 + 3]; Px(i, rr, g, b, a); }
|
||||
break;
|
||||
case 23: // R5G6B5
|
||||
for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++)
|
||||
{ ushort v = (ushort)(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 < w * h && i * 2 + 1 < src.Length; i++)
|
||||
{ ushort v = (ushort)(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 < w * h && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255);
|
||||
break;
|
||||
case 101: // INDEX16
|
||||
case 41: // P8
|
||||
{
|
||||
uint[]? pal = LoadPalette(defPal);
|
||||
if (pal == null || pal.Length == 0) return null;
|
||||
bool p8 = fmt == 41;
|
||||
for (int i = 0; i < w * h; i++)
|
||||
{
|
||||
int idx;
|
||||
if (p8) { if (i >= src.Length) break; idx = src[i]; }
|
||||
else { if (i * 2 + 1 >= src.Length) break; idx = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); }
|
||||
uint cc = pal[idx % pal.Length];
|
||||
Px(i, (int)((cc >> 16) & 0xFF), (int)((cc >> 8) & 0xFF), (int)(cc & 0xFF), (int)((cc >> 24) & 0xFF));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return null; // unhandled format
|
||||
}
|
||||
return new Rgba { Width = w, Height = h, Pixels = rgba };
|
||||
}
|
||||
|
||||
private static Rgba Wrap(byte[] rgba, int w, int h) => new Rgba { Width = w, Height = h, Pixels = rgba }; // DxtUtil already RGBA
|
||||
}
|
||||
125
src/RynthCore.StatusAgent/IconService.cs
Normal file
125
src/RynthCore.StatusAgent/IconService.cs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore2.TerrainData;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Serves item-icon PNGs decoded on-demand from portal.dat (for the read-only inventory viewer).
|
||||
/// Lazy-opens the dat on the first request and caches each decoded PNG by DID (icons are immutable),
|
||||
/// so each unique icon is decoded once per agent lifetime. Thread-safe. Returns null whenever icons
|
||||
/// are unavailable — no dat file (e.g. an agent running off the game box), an undecodable DID, or a
|
||||
/// decode error — so the endpoint 404s and the app falls back to a text/glyph row.
|
||||
/// </summary>
|
||||
internal sealed class IconService : IDisposable
|
||||
{
|
||||
private readonly string _datPath;
|
||||
private readonly object _openLock = new();
|
||||
private DatDatabase? _portal;
|
||||
private IconDecoder? _decoder;
|
||||
private bool _openFailed;
|
||||
|
||||
// Decoded PNG by DID. Icons never change, so this only grows; bounded by a simple cap (a full char's
|
||||
// worth of icons is ~hundreds, so the cap is never realistically hit — it's just a runaway guard).
|
||||
private readonly ConcurrentDictionary<uint, byte[]> _cache = new();
|
||||
private const int CacheCap = 4000;
|
||||
|
||||
public IconService(string datPath) => _datPath = datPath;
|
||||
|
||||
private bool EnsureOpen()
|
||||
{
|
||||
if (_portal != null) return true;
|
||||
if (_openFailed) return false;
|
||||
lock (_openLock)
|
||||
{
|
||||
if (_portal != null) return true;
|
||||
if (_openFailed) return false;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_datPath))
|
||||
{
|
||||
_openFailed = true;
|
||||
AgentLog.Warn($"[icon] portal.dat not found at '{_datPath}' — icons disabled (set IconDatPath in statusagent.json).");
|
||||
return false;
|
||||
}
|
||||
var db = new DatDatabase();
|
||||
if (!db.Open(_datPath))
|
||||
{
|
||||
db.Dispose();
|
||||
_openFailed = true;
|
||||
AgentLog.Warn($"[icon] failed to open portal.dat at '{_datPath}'.");
|
||||
return false;
|
||||
}
|
||||
_decoder = new IconDecoder(db);
|
||||
_portal = db;
|
||||
AgentLog.Info($"[icon] portal.dat opened: {_datPath} ({db.RecordCount:N0} files indexed).");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_openFailed = true;
|
||||
AgentLog.Warn($"[icon] open error: {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the PNG bytes for an icon DID (0x06xxxxxx), or null if unavailable/undecodable.</summary>
|
||||
public byte[]? GetPng(uint did)
|
||||
{
|
||||
if (did == 0) return null;
|
||||
if (_cache.TryGetValue(did, out var cached)) return cached;
|
||||
if (!EnsureOpen() || _decoder == null) return null;
|
||||
try
|
||||
{
|
||||
var img = _decoder.Decode(did);
|
||||
if (img == null || img.Pixels.Length == 0 || img.Width <= 0 || img.Height <= 0)
|
||||
return null;
|
||||
byte[] png = RgbaToPng(img.Pixels, img.Width, img.Height);
|
||||
if (_cache.Count > CacheCap) _cache.Clear();
|
||||
_cache[did] = png;
|
||||
return png;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Debug($"[icon] decode 0x{did:X8} failed: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// RGBA (R,G,B,A) -> PNG via System.Drawing (already referenced for the screen JPEG path; Windows-only,
|
||||
/// and the agent is net*-windows). Format32bppArgb is BGRA in memory, so swizzle R<->B on copy.
|
||||
private static byte[] RgbaToPng(byte[] rgba, int w, int h)
|
||||
{
|
||||
using var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb);
|
||||
var bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
|
||||
try
|
||||
{
|
||||
byte[] row = new byte[w * 4];
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
int s = (y * w + x) * 4, d = x * 4;
|
||||
row[d] = rgba[s + 2]; // B
|
||||
row[d + 1] = rgba[s + 1]; // G
|
||||
row[d + 2] = rgba[s]; // R
|
||||
row[d + 3] = rgba[s + 3]; // A
|
||||
}
|
||||
Marshal.Copy(row, 0, bd.Scan0 + y * bd.Stride, w * 4);
|
||||
}
|
||||
}
|
||||
finally { bmp.UnlockBits(bd); }
|
||||
using var ms = new MemoryStream();
|
||||
bmp.Save(ms, ImageFormat.Png);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { _portal?.Dispose(); } catch { }
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
784
src/RynthCore.StatusAgent/LocalStatusServer.cs
Normal file
784
src/RynthCore.StatusAgent/LocalStatusServer.cs
Normal file
|
|
@ -0,0 +1,784 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in (default OFF) read-only HTTP endpoint so an app can PULL the latest
|
||||
/// status with no backend. Serves the most recent aggregate JSON at GET /status
|
||||
/// (and /, /status.json); GET /healthz returns "ok". Only listens when
|
||||
/// <see cref="AgentConfig.ServeHttp"/> is true — nothing is opened otherwise.
|
||||
/// </summary>
|
||||
internal sealed class LocalStatusServer : IDisposable
|
||||
{
|
||||
private readonly HttpListener _listener = new();
|
||||
private readonly string? _token;
|
||||
private readonly string _prefix;
|
||||
private readonly string? _commandDir; // null = remote control disabled (no POST /command)
|
||||
private readonly bool _enableStream; // GET /frame + /stream (screen capture)
|
||||
private readonly int _streamQuality;
|
||||
private readonly int _streamIntervalMs;
|
||||
private readonly WebRtcVideoService? _video; // POST /webrtc/* (HD WebRTC mode; same-LAN); null = disabled
|
||||
private readonly VideoSocketService? _videoSocket; // GET /video (WS, H.264 client-server; works remotely)
|
||||
private readonly RunArchive? _runArchive; // GET /runs (per-session play history); null = disabled
|
||||
private readonly string? _statusDir; // GET /inventory reads RynthCore.<pid>.inventory.json from here
|
||||
private readonly IconService? _icons; // GET /icon?did=N (portal.dat → PNG); null = disabled
|
||||
private readonly MapService? _maps; // GET /maps + /map?lb&layer (baked dungeon .bin → PNG); null = disabled
|
||||
private volatile byte[] _latest =
|
||||
Encoding.UTF8.GetBytes("{\"schema\":\"rynthcore.status-agent/1\",\"clientCount\":0,\"clients\":[]}");
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _loop;
|
||||
// Connected /statusfeed push clients — each value is a per-socket wake signal. UpdateLatest pulses
|
||||
// them all; each socket's loop then sends the freshest _latest (coalescing rapid updates).
|
||||
private readonly ConcurrentDictionary<Guid, SemaphoreSlim> _feedSignals = new();
|
||||
private const int FeedKeepAliveMs = 20000; // re-send _latest at least this often (keepalive + missed-pulse cover)
|
||||
|
||||
public bool Running { get; private set; }
|
||||
|
||||
public LocalStatusServer(string prefix, string? token, string? commandDir = null,
|
||||
bool enableStream = false, int streamQuality = 55, int streamIntervalMs = 400,
|
||||
WebRtcVideoService? video = null, VideoSocketService? videoSocket = null,
|
||||
RunArchive? runArchive = null, string? statusDirectory = null,
|
||||
IconService? icons = null, MapService? maps = null)
|
||||
{
|
||||
_prefix = prefix.EndsWith('/') ? prefix : prefix + "/";
|
||||
_token = string.IsNullOrWhiteSpace(token) ? null : token;
|
||||
_commandDir = string.IsNullOrWhiteSpace(commandDir) ? null : commandDir;
|
||||
_enableStream = enableStream;
|
||||
_streamQuality = Math.Clamp(streamQuality, 1, 100);
|
||||
_streamIntervalMs = Math.Clamp(streamIntervalMs, 100, 2000);
|
||||
_video = video;
|
||||
_videoSocket = videoSocket;
|
||||
_runArchive = runArchive;
|
||||
_statusDir = string.IsNullOrWhiteSpace(statusDirectory) ? null : statusDirectory;
|
||||
_icons = icons;
|
||||
_maps = maps;
|
||||
_listener.Prefixes.Add(_prefix);
|
||||
}
|
||||
|
||||
/// <summary>Replace the payload future requests return AND push it to any connected /statusfeed
|
||||
/// sockets (thread-safe).</summary>
|
||||
public void UpdateLatest(byte[] jsonUtf8)
|
||||
{
|
||||
_latest = jsonUtf8;
|
||||
// Pulse every feed loop; each sends the freshest _latest when it wakes (so rapid updates coalesce
|
||||
// and a slow client can't back up the agent). A SemaphoreSlim(1,1) means extra pulses are no-ops.
|
||||
foreach (var kv in _feedSignals)
|
||||
{
|
||||
try { if (kv.Value.CurrentCount == 0) kv.Value.Release(); } catch (SemaphoreFullException) { }
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryStart(out string error)
|
||||
{
|
||||
// Never serve without a token, loopback included: every route but /healthz is behind it.
|
||||
if (_token == null)
|
||||
{
|
||||
error = "no ServeToken set";
|
||||
Running = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_listener.Start();
|
||||
_cts = new CancellationTokenSource();
|
||||
_loop = Task.Run(() => AcceptLoopAsync(_cts.Token));
|
||||
Running = true;
|
||||
error = "";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
Running = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested && _listener.IsListening)
|
||||
{
|
||||
HttpListenerContext ctx;
|
||||
try { ctx = await _listener.GetContextAsync().ConfigureAwait(false); }
|
||||
catch { break; } // listener stopped / disposed
|
||||
_ = Task.Run(() => Handle(ctx));
|
||||
}
|
||||
}
|
||||
|
||||
private void Handle(HttpListenerContext ctx)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpListenerRequest req = ctx.Request;
|
||||
HttpListenerResponse res = ctx.Response;
|
||||
res.Headers["Access-Control-Allow-Origin"] = "*";
|
||||
string path = req.Url?.AbsolutePath?.TrimEnd('/').ToLowerInvariant() ?? "";
|
||||
string method = req.HttpMethod ?? "GET";
|
||||
|
||||
// Diagnostic: log every /webrtc request + every CORS preflight, at the door (before any
|
||||
// auth/route processing), so we can see whether the app's offer POST even reaches us.
|
||||
if (path.StartsWith("/webrtc") || string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase))
|
||||
AgentLog.Info($"[video] HTTP {method} {path} ua=\"{req.UserAgent}\"");
|
||||
|
||||
// CORS preflight for the POST /command path (a browser-hosted client may send it).
|
||||
if (string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
res.Headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
|
||||
res.Headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type";
|
||||
Write(res, 204, "text/plain", Array.Empty<byte>());
|
||||
return;
|
||||
}
|
||||
|
||||
if (path == "/healthz")
|
||||
{
|
||||
Write(res, 200, "text/plain", "ok"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Screen stream: GET /frame?pid=N (single JPEG) or /stream?pid=N (MJPEG) ──
|
||||
if (path == "/frame" || path == "/stream")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (!_enableStream)
|
||||
{
|
||||
Write(res, 503, "application/json", "{\"error\":\"screen stream disabled\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
int pid = int.TryParse(req.QueryString["pid"], out int p) ? p : 0;
|
||||
if (pid <= 0)
|
||||
{
|
||||
Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
int quality = ClampQuery(req, "q", _streamQuality, 1, 100);
|
||||
int maxWidth = ClampQuery(req, "w", 0, 0, 4096); // 0 = native size
|
||||
int fps = ClampQuery(req, "fps", 0, 0, 30);
|
||||
int intervalMs = fps > 0 ? Math.Clamp(1000 / fps, 33, 2000) : _streamIntervalMs;
|
||||
if (path == "/frame") HandleFrame(res, pid, quality, maxWidth);
|
||||
else HandleStream(res, pid, quality, maxWidth, intervalMs);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── HD video (WebSocket H.264, client-server, works remotely): GET /video?pid=N (ws upgrade) ──
|
||||
if (path == "/video")
|
||||
{
|
||||
if (_token != null && !Authorized(req)) { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
if (_videoSocket == null) { Write(res, 503, "application/json", "{\"error\":\"video stream disabled\"}"u8.ToArray()); return; }
|
||||
int vpid = int.TryParse(req.QueryString["pid"], out int vv) ? vv : 0;
|
||||
if (vpid <= 0) { Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; }
|
||||
if (!req.IsWebSocketRequest) { Write(res, 426, "application/json", "{\"error\":\"websocket required\"}"u8.ToArray()); return; }
|
||||
AgentLog.Info($"[vsock] HTTP WS /video pid={vpid} ua=\"{req.UserAgent}\"");
|
||||
_ = HandleVideoSocketAsync(ctx, vpid);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Status push (WebSocket): GET /statusfeed — push the latest aggregate on every change ──
|
||||
if (path == "/statusfeed")
|
||||
{
|
||||
if (_token != null && !Authorized(req)) { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
if (!req.IsWebSocketRequest) { Write(res, 426, "application/json", "{\"error\":\"websocket required\"}"u8.ToArray()); return; }
|
||||
AgentLog.Info($"[feed] WS /statusfeed ua=\"{req.UserAgent}\"");
|
||||
_ = HandleStatusFeedAsync(ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── HD video (WebRTC): POST /webrtc/offer?pid=N {sdp} -> {sdp:answer}; POST /webrtc/stop?pid=N ──
|
||||
if (path == "/webrtc/offer" || path == "/webrtc/stop" || path == "/webrtc/clientlog")
|
||||
{
|
||||
if (!string.Equals(method, "POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_video == null)
|
||||
{
|
||||
Write(res, 503, "application/json", "{\"error\":\"video stream disabled\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
int pid = int.TryParse(req.QueryString["pid"], out int vp) ? vp : 0;
|
||||
if (pid <= 0)
|
||||
{
|
||||
Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (path == "/webrtc/stop") { _video.Stop(pid); Write(res, 200, "application/json", "{\"ok\":true}"u8.ToArray()); return; }
|
||||
if (path == "/webrtc/clientlog") // diagnostic: WKWebView reports its WebRTC errors/states here
|
||||
{
|
||||
try { using var sr = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8); AgentLog.Info($"[video] CLIENT pid={pid}: {sr.ReadToEnd()}"); } catch { }
|
||||
Write(res, 200, "application/json", "{\"ok\":true}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
HandleWebRtcOffer(req, res, pid);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Remote control: POST /command writes a command file the engine-plugin polls ──
|
||||
if (path == "/command")
|
||||
{
|
||||
if (!string.Equals(method, "POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_commandDir == null)
|
||||
{
|
||||
Write(res, 503, "application/json", "{\"error\":\"remote control disabled\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
HandleCommand(req, res);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Run history: GET /runs — per-session play stats (kills/XP/etc.), newest first ──
|
||||
if (path == "/runs" || path == "/runs.json")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
byte[] runs = _runArchive?.BuildJsonBytes()
|
||||
?? "{\"schema\":\"rynthcore.runs/1\",\"count\":0,\"runs\":[]}"u8.ToArray();
|
||||
Write(res, 200, "application/json", runs);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Dungeon maps: GET /maps — list baked floor-plan maps (landblock + layer + raster bounds) ──
|
||||
if (path == "/maps" || path == "/maps.json")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
var entries = _maps?.List() ?? (IReadOnlyList<MapService.MapEntry>)Array.Empty<MapService.MapEntry>();
|
||||
var payload = new MapsListPayload { Count = entries.Count };
|
||||
foreach (var e in entries)
|
||||
payload.Maps.Add(new MapEntryDto
|
||||
{
|
||||
Landblock = e.Landblock.ToString("X8"),
|
||||
Layer = e.Layer, Bytes = e.Bytes, Mtime = e.MtimeUtc,
|
||||
W = e.W, H = e.H, XMin = e.XMin, YMin = e.YMin,
|
||||
Name = "Dungeon " + (e.Landblock & 0xFFFF).ToString("X4"),
|
||||
});
|
||||
Write(res, 200, "application/json",
|
||||
JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.MapsListPayload));
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Inventory: GET /inventory?pid=N — that client's full read-only inventory (icons/slots/appraisal) ──
|
||||
if (path == "/inventory" || path == "/inventory.json")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
int ipid = int.TryParse(req.QueryString["pid"], out int ip) ? ip : 0;
|
||||
if (ipid <= 0)
|
||||
{
|
||||
Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
// Serve the plugin-written file verbatim (already in the app's schema); empty payload if
|
||||
// that client isn't exporting inventory yet, so the app can always parse a response.
|
||||
Write(res, 200, "application/json", ReadInventoryBytes(ipid));
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Settings: GET /settings?pid=N — that client's full advanced-settings bridge (for the Control form) ──
|
||||
if (path == "/settings" || path == "/settings.json")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
int spid = int.TryParse(req.QueryString["pid"], out int sp) ? sp : 0;
|
||||
if (spid <= 0)
|
||||
{ Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; }
|
||||
Write(res, 200, "application/json", ReadSettingsBytes(spid));
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Item icon: GET /icon?did=N — decode a portal.dat texture to PNG (read-only inventory view) ──
|
||||
if (path == "/icon")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
uint did = uint.TryParse(req.QueryString["did"], out uint dv) ? dv : 0u;
|
||||
if (did == 0)
|
||||
{
|
||||
Write(res, 400, "application/json", "{\"error\":\"did required\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
// Icons are immutable per DID → strong ETag + long immutable cache; honour If-None-Match.
|
||||
string etag = "\"" + did.ToString("X8") + "\"";
|
||||
if (string.Equals(req.Headers["If-None-Match"], etag, StringComparison.Ordinal))
|
||||
{
|
||||
res.Headers["ETag"] = etag;
|
||||
Write(res, 304, "image/png", Array.Empty<byte>());
|
||||
return;
|
||||
}
|
||||
byte[]? png = _icons?.GetPng(did);
|
||||
if (png == null)
|
||||
{
|
||||
Write(res, 404, "application/json", "{\"error\":\"icon unavailable\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
res.Headers["Cache-Control"] = "public, max-age=31536000, immutable";
|
||||
res.Headers["ETag"] = etag;
|
||||
Write(res, 200, "image/png", png);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Dungeon map image: GET /map?lb=XXXXXXXX&layer=N — baked .bin re-encoded to PNG ──
|
||||
if (path == "/map")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
if (!uint.TryParse(req.QueryString["lb"], System.Globalization.NumberStyles.HexNumber,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out uint lb)
|
||||
|| !int.TryParse(req.QueryString["layer"], out int layer))
|
||||
{ Write(res, 400, "application/json", "{\"error\":\"lb (hex) and layer required\"}"u8.ToArray()); return; }
|
||||
var r = _maps?.GetPng(lb, layer);
|
||||
if (r == null)
|
||||
{ Write(res, 404, "application/json", "{\"error\":\"map unavailable\"}"u8.ToArray()); return; }
|
||||
var (mapPng, meta) = r.Value;
|
||||
// Re-baked as the bot explores, so the ETag tracks file mtime+size (NOT immutable like /icon).
|
||||
string mapEtag = "\"" + meta.MtimeUtc.Ticks + "-" + meta.Bytes + "\"";
|
||||
if (string.Equals(req.Headers["If-None-Match"], mapEtag, StringComparison.Ordinal))
|
||||
{ res.Headers["ETag"] = mapEtag; Write(res, 304, "image/png", Array.Empty<byte>()); return; }
|
||||
res.Headers["Cache-Control"] = "public, max-age=60";
|
||||
res.Headers["ETag"] = mapEtag;
|
||||
res.Headers["X-Map-XMin"] = meta.XMin.ToString();
|
||||
res.Headers["X-Map-YMin"] = meta.YMin.ToString();
|
||||
res.Headers["X-Map-W"] = meta.W.ToString();
|
||||
res.Headers["X-Map-H"] = meta.H.ToString();
|
||||
Write(res, 200, "image/png", mapPng);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (path is not ("" or "/status" or "/status.json"))
|
||||
{
|
||||
Write(res, 404, "application/json", "{\"error\":\"not found\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
if (_token != null && !Authorized(req))
|
||||
{
|
||||
Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
|
||||
Write(res, 200, "application/json", _latest);
|
||||
}
|
||||
catch { /* a broken client connection must not take the agent down */ }
|
||||
}
|
||||
|
||||
// Plugin actions (written as a command file the plugin polls). "closeClient" is handled by the
|
||||
// agent directly (process kill), not the plugin — see HandleCommand.
|
||||
private static readonly HashSet<string> KnownActions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"macro", "combat", "buffing", "navigation", "looting", "meta",
|
||||
"navProfile", "lootProfile", "metaProfile", "settingsProfile",
|
||||
"forceRebuff", "cancelRebuff", "clearBusy", "hideUi", "sendChat",
|
||||
"moveStart", "moveStop",
|
||||
"setSetting", // change ONE advanced setting (value = {"key":..,"value":..}); RynthAi clamps + persists
|
||||
"click", // mouse click in the stream (value = {"u":..,"v":..,"button":..}); handled by the agent (PostMessage)
|
||||
|
||||
"assess", // request an Assess/Identify of one item (value = item id) — fills inventory appraisal
|
||||
"closeClient",
|
||||
};
|
||||
|
||||
private void HandleCommand(HttpListenerRequest req, HttpListenerResponse res)
|
||||
{
|
||||
try
|
||||
{
|
||||
string body;
|
||||
using (var reader = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8))
|
||||
body = reader.ReadToEnd();
|
||||
|
||||
int pid; string action; string value;
|
||||
using (var doc = JsonDocument.Parse(body))
|
||||
{
|
||||
var root = doc.RootElement;
|
||||
pid = root.TryGetProperty("pid", out var p) && p.TryGetInt32(out int pv) ? pv : 0;
|
||||
action = root.TryGetProperty("action", out var a) && a.ValueKind == JsonValueKind.String
|
||||
? (a.GetString() ?? "") : "";
|
||||
value = root.TryGetProperty("value", out var v)
|
||||
? (v.ValueKind == JsonValueKind.String ? (v.GetString() ?? "") : v.ToString()) : "";
|
||||
}
|
||||
|
||||
if (pid <= 0 || string.IsNullOrEmpty(action) || !KnownActions.Contains(action))
|
||||
{
|
||||
Write(res, 400, "application/json", "{\"error\":\"bad command\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
|
||||
// Close-client is an AGENT action (kill the process), not a plugin command — handle + return.
|
||||
if (string.Equals(action, "closeClient", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
CloseClient(pid);
|
||||
Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
|
||||
// Click is an AGENT action too: PostMessage a mouse click straight to the acclient window at the
|
||||
// tapped point. value = {"u":0..1,"v":0..1,"button":"left"|"right"} normalized to the client area.
|
||||
if (string.Equals(action, "click", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
double u = 0, v = 0; string button = "left";
|
||||
try
|
||||
{
|
||||
using var vd = JsonDocument.Parse(string.IsNullOrWhiteSpace(value) ? "{}" : value);
|
||||
var vr = vd.RootElement;
|
||||
if (vr.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (vr.TryGetProperty("u", out var ue) && ue.ValueKind == JsonValueKind.Number) u = ue.GetDouble();
|
||||
if (vr.TryGetProperty("v", out var vv) && vv.ValueKind == JsonValueKind.Number) v = vv.GetDouble();
|
||||
if (vr.TryGetProperty("button", out var be) && be.ValueKind == JsonValueKind.String) button = be.GetString() ?? "left";
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
bool clicked = ScreenCapture.TryClick(pid, u, v, button);
|
||||
Write(res, clicked ? 202 : 503, "application/json",
|
||||
clicked ? "{\"ok\":true}"u8.ToArray() : "{\"error\":\"click failed (window missing or minimized)\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_commandDir!);
|
||||
PruneStaleCommands();
|
||||
|
||||
// Ticks-prefixed name so the plugin applies commands in submit order; guid avoids collisions.
|
||||
string name = $"RynthCore.{pid}.{DateTime.UtcNow.Ticks:D19}-{Guid.NewGuid():N}.cmd.json";
|
||||
string dest = Path.Combine(_commandDir!, name);
|
||||
string tmp = dest + ".tmp";
|
||||
string payload = JsonSerializer.Serialize(
|
||||
new CommandFile { Pid = pid, Action = action, Value = value, Ts = DateTimeOffset.UtcNow },
|
||||
AgentJsonContext.Default.CommandFile);
|
||||
File.WriteAllText(tmp, payload, Encoding.UTF8);
|
||||
File.Move(tmp, dest, overwrite: true);
|
||||
|
||||
AgentLog.Info($"command queued: pid={pid} {action}={value}");
|
||||
Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Warn($"POST /command failed: {ex.GetType().Name}: {ex.Message}");
|
||||
Write(res, 400, "application/json", "{\"error\":\"invalid request\"}"u8.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
// Drop any command file a client never consumed within 60s (e.g. issued to a box that's now down).
|
||||
private void PruneStaleCommands()
|
||||
{
|
||||
try
|
||||
{
|
||||
DateTime cutoff = DateTime.UtcNow.AddSeconds(-60);
|
||||
foreach (string f in Directory.GetFiles(_commandDir!, "*.cmd.json"))
|
||||
{
|
||||
try { if (File.GetLastWriteTimeUtc(f) < cutoff) File.Delete(f); } catch { }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// Close one AC client: try a graceful WM_CLOSE first (clean logout / save), and hard-kill after a
|
||||
/// few seconds if it's still alive (covers a hung client whose message loop is wedged).
|
||||
private static void CloseClient(int pid)
|
||||
{
|
||||
try
|
||||
{
|
||||
var proc = System.Diagnostics.Process.GetProcessById(pid);
|
||||
// Defence-in-depth for a destructive op: only ever close an AC client, never some other
|
||||
// process if a stale pid were somehow recycled between the feed and this call.
|
||||
if (!string.Equals(proc.ProcessName, "acclient", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
AgentLog.Warn($"close client pid={pid} refused: not an acclient process ({proc.ProcessName}).");
|
||||
try { proc.Dispose(); } catch { }
|
||||
return;
|
||||
}
|
||||
try { proc.CloseMainWindow(); } catch { }
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try { await Task.Delay(6000); if (!proc.HasExited) proc.Kill(); } catch { }
|
||||
finally { try { proc.Dispose(); } catch { } }
|
||||
});
|
||||
AgentLog.Info($"close client requested: pid={pid} (graceful, kill fallback in 6s)");
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Warn($"close client pid={pid} failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
private static readonly byte[] EmptyInventory =
|
||||
"{\"schema\":\"rynthcore.inventory/1\",\"version\":0,\"itemCount\":0,\"containers\":[],\"items\":[]}"u8.ToArray();
|
||||
|
||||
/// Read RynthCore.<pid>.inventory.json (written atomically by the RynthRemote plugin) and return its
|
||||
/// bytes. Returns an empty-but-valid payload when the file is absent (client not exporting yet) or on
|
||||
/// any read error — so the app always gets parseable JSON. The plugin's atomic write means a concurrent
|
||||
/// read never sees a torn file.
|
||||
private byte[] ReadInventoryBytes(int pid)
|
||||
{
|
||||
if (_statusDir == null) return EmptyInventory;
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.inventory.json");
|
||||
if (!File.Exists(path)) return EmptyInventory;
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
return bytes.Length >= 2 ? bytes : EmptyInventory;
|
||||
}
|
||||
catch { return EmptyInventory; }
|
||||
}
|
||||
|
||||
/// Read RynthCore.<pid>.settings.json (written atomically by the RynthRemote plugin = RynthAi's advanced
|
||||
/// settings bridge). Returns an empty object when absent/unreadable so the app always parses valid JSON.
|
||||
private byte[] ReadSettingsBytes(int pid)
|
||||
{
|
||||
if (_statusDir == null) return "{}"u8.ToArray();
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.settings.json");
|
||||
if (!File.Exists(path)) return "{}"u8.ToArray();
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
return bytes.Length >= 2 ? bytes : "{}"u8.ToArray();
|
||||
}
|
||||
catch { return "{}"u8.ToArray(); }
|
||||
}
|
||||
|
||||
private static int ClampQuery(HttpListenerRequest req, string key, int def, int lo, int hi)
|
||||
=> int.TryParse(req.QueryString[key], out int v) ? Math.Clamp(v, lo, hi) : def;
|
||||
|
||||
private void HandleFrame(HttpListenerResponse res, int pid, int quality, int maxWidth)
|
||||
{
|
||||
var r = ScreenCapture.TryCaptureJpeg(pid, quality, maxWidth, out byte[] jpeg);
|
||||
if (r == ScreenCapture.Result.Ok)
|
||||
Write(res, 200, "image/jpeg", jpeg);
|
||||
else
|
||||
Write(res, 503, "application/json",
|
||||
Encoding.ASCII.GetBytes($"{{\"error\":\"{r.ToString().ToLowerInvariant()}\"}}"));
|
||||
}
|
||||
|
||||
private static readonly byte[] CrLf = { 13, 10 };
|
||||
|
||||
/// MJPEG: push JPEG frames as multipart/x-mixed-replace until the client disconnects (the <img>
|
||||
/// is removed app-side) or the window closes. Capture only happens while a client is connected.
|
||||
private void HandleStream(HttpListenerResponse res, int pid, int quality, int maxWidth, int intervalMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
res.StatusCode = 200;
|
||||
res.SendChunked = true;
|
||||
res.ContentType = "multipart/x-mixed-replace; boundary=frame";
|
||||
res.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
|
||||
var os = res.OutputStream;
|
||||
int misses = 0;
|
||||
var sw = new System.Diagnostics.Stopwatch();
|
||||
while (true)
|
||||
{
|
||||
sw.Restart();
|
||||
var r = ScreenCapture.TryCaptureJpeg(pid, quality, maxWidth, out byte[] jpeg);
|
||||
if (r != ScreenCapture.Result.Ok)
|
||||
{
|
||||
// window gone for a while -> end the stream; minimized/transient -> wait + retry.
|
||||
if (r == ScreenCapture.Result.NotFound && ++misses > 6) break;
|
||||
Thread.Sleep(500);
|
||||
continue;
|
||||
}
|
||||
misses = 0;
|
||||
byte[] header = Encoding.ASCII.GetBytes(
|
||||
$"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: {jpeg.Length}\r\n\r\n");
|
||||
os.Write(header, 0, header.Length);
|
||||
os.Write(jpeg, 0, jpeg.Length);
|
||||
os.Write(CrLf, 0, CrLf.Length);
|
||||
os.Flush(); // throws once the client (phone) disconnects
|
||||
// Pace to the TARGET interval: sleep only the time left after capture+encode+send, so the
|
||||
// achieved fps actually hits the target (up to the encode ceiling) instead of interval+capture.
|
||||
int left = intervalMs - (int)sw.ElapsedMilliseconds;
|
||||
if (left > 1) Thread.Sleep(left);
|
||||
}
|
||||
}
|
||||
catch { /* client disconnected / write failed — stop capturing for this stream */ }
|
||||
finally { try { res.OutputStream.Close(); } catch { } }
|
||||
}
|
||||
|
||||
private async Task HandleVideoSocketAsync(HttpListenerContext ctx, int pid)
|
||||
{
|
||||
HttpListenerWebSocketContext wsCtx;
|
||||
try { wsCtx = await ctx.AcceptWebSocketAsync(null); }
|
||||
catch (Exception ex) { AgentLog.Warn($"[vsock] ws accept failed pid {pid}: {ex.Message}"); try { ctx.Response.StatusCode = 500; ctx.Response.Close(); } catch { } return; }
|
||||
using var cts = new CancellationTokenSource();
|
||||
try { await _videoSocket!.StreamAsync(wsCtx.WebSocket, pid, cts.Token); }
|
||||
catch (Exception ex) { AgentLog.Debug($"[vsock] pid {pid}: {ex.Message}"); }
|
||||
finally { try { wsCtx.WebSocket.Dispose(); } catch { } }
|
||||
}
|
||||
|
||||
/// One /statusfeed client: send the current snapshot on connect, then push the freshest _latest
|
||||
/// whenever UpdateLatest pulses us (and at least every FeedKeepAliveMs). Sends are serial on this
|
||||
/// socket (no overlap); a slow/dead client only affects its own loop. The agent's shutdown token
|
||||
/// ends every feed loop on Dispose.
|
||||
private async Task HandleStatusFeedAsync(HttpListenerContext ctx)
|
||||
{
|
||||
HttpListenerWebSocketContext wsCtx;
|
||||
try { wsCtx = await ctx.AcceptWebSocketAsync(null); }
|
||||
catch (Exception ex) { AgentLog.Warn($"[feed] ws accept failed: {ex.Message}"); try { ctx.Response.StatusCode = 500; ctx.Response.Close(); } catch { } return; }
|
||||
|
||||
WebSocket ws = wsCtx.WebSocket;
|
||||
CancellationToken ct = _cts?.Token ?? CancellationToken.None;
|
||||
var id = Guid.NewGuid();
|
||||
var signal = new SemaphoreSlim(1, 1); // start signaled -> push the current snapshot immediately on connect
|
||||
_feedSignals[id] = signal;
|
||||
AgentLog.Info($"[feed] client connected ({_feedSignals.Count} total).");
|
||||
try
|
||||
{
|
||||
Task recv = DrainReceiveAsync(ws, ct); // background: notice the client closing
|
||||
while (ws.State == WebSocketState.Open && !recv.IsCompleted)
|
||||
{
|
||||
await signal.WaitAsync(FeedKeepAliveMs, ct); // wake on a pulse, the keepalive timeout, or shutdown
|
||||
if (ws.State != WebSocketState.Open) break;
|
||||
byte[] snapshot = _latest; // freshest at send time (coalesces missed pulses)
|
||||
await ws.SendAsync(new ArraySegment<byte>(snapshot), WebSocketMessageType.Text, endOfMessage: true, ct);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { /* agent stopping */ }
|
||||
catch { /* client gone / send failed */ }
|
||||
finally
|
||||
{
|
||||
_feedSignals.TryRemove(id, out _);
|
||||
try { signal.Dispose(); } catch { }
|
||||
try { ws.Dispose(); } catch { }
|
||||
AgentLog.Info($"[feed] client disconnected ({_feedSignals.Count} total).");
|
||||
}
|
||||
}
|
||||
|
||||
// Pump the receive side so we notice a client close/ping; payloads are ignored (the feed is server->client).
|
||||
private static async Task DrainReceiveAsync(WebSocket ws, CancellationToken ct)
|
||||
{
|
||||
var buf = new byte[256];
|
||||
try
|
||||
{
|
||||
while (ws.State == WebSocketState.Open)
|
||||
{
|
||||
WebSocketReceiveResult r = await ws.ReceiveAsync(new ArraySegment<byte>(buf), ct);
|
||||
if (r.MessageType == WebSocketMessageType.Close) break;
|
||||
}
|
||||
}
|
||||
catch { /* socket closed / cancelled */ }
|
||||
}
|
||||
|
||||
private void HandleWebRtcOffer(HttpListenerRequest req, HttpListenerResponse res, int pid)
|
||||
{
|
||||
string body;
|
||||
using (var sr = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8))
|
||||
body = sr.ReadToEnd();
|
||||
string? offer = null;
|
||||
try { offer = JsonDocument.Parse(body).RootElement.GetProperty("sdp").GetString(); } catch { }
|
||||
if (string.IsNullOrEmpty(offer))
|
||||
{
|
||||
Write(res, 400, "application/json", "{\"error\":\"sdp required\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
// Diagnostic: confirm the offer arrived + from which client (Safari vs Chrome), and what H.264
|
||||
// profile-level-id(s) it can RECEIVE.
|
||||
AgentLog.Info($"[video] OFFER pid={pid} ua=\"{req.UserAgent}\"");
|
||||
foreach (var ln in offer.Split('\n'))
|
||||
if (ln.StartsWith("m=video", StringComparison.Ordinal) || ln.Contains("profile-level-id", StringComparison.OrdinalIgnoreCase) || ln.Contains("candidate", StringComparison.OrdinalIgnoreCase))
|
||||
AgentLog.Info($"[video] offer> {ln.Trim()}");
|
||||
string? answer;
|
||||
try { answer = _video!.CreateAnswerAsync(pid, offer).GetAwaiter().GetResult(); }
|
||||
catch (Exception ex) { AgentLog.Warn($"[video] offer failed pid {pid}: {ex.Message}"); answer = null; }
|
||||
if (answer == null)
|
||||
{
|
||||
Write(res, 409, "application/json", "{\"error\":\"no renderable window for that pid (minimized?) or negotiation failed\"}"u8.ToArray());
|
||||
return;
|
||||
}
|
||||
// Diagnostic: log the answer's H.264 negotiation so we can compare payload type + profile-level-id
|
||||
// against the client's offer (a mismatch makes Safari reject setRemoteDescription -> black).
|
||||
foreach (var ln in answer.Split('\n'))
|
||||
if (ln.StartsWith("m=video", StringComparison.Ordinal) || ln.Contains("profile-level-id", StringComparison.OrdinalIgnoreCase) || (ln.Contains("rtpmap", StringComparison.OrdinalIgnoreCase) && ln.Contains("H264", StringComparison.OrdinalIgnoreCase)))
|
||||
AgentLog.Info($"[video] answer> {ln.Trim()}");
|
||||
Write(res, 200, "application/json", JsonSerializer.SerializeToUtf8Bytes(new { sdp = answer }));
|
||||
}
|
||||
|
||||
private bool Authorized(HttpListenerRequest req)
|
||||
{
|
||||
string? header = req.Headers["Authorization"];
|
||||
if (header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) &&
|
||||
TokenMatches(header.Substring("Bearer ".Length).Trim()))
|
||||
return true;
|
||||
|
||||
string? q = req.QueryString["token"];
|
||||
return q != null && TokenMatches(q);
|
||||
}
|
||||
|
||||
private bool TokenMatches(string candidate)
|
||||
=> _token != null && CryptographicOperations.FixedTimeEquals(
|
||||
Encoding.UTF8.GetBytes(candidate), Encoding.UTF8.GetBytes(_token));
|
||||
|
||||
private static void Write(HttpListenerResponse res, int status, string contentType, byte[] body)
|
||||
{
|
||||
try
|
||||
{
|
||||
res.StatusCode = status;
|
||||
res.ContentType = contentType;
|
||||
res.ContentLength64 = body.Length;
|
||||
res.OutputStream.Write(body, 0, body.Length);
|
||||
}
|
||||
finally { try { res.OutputStream.Close(); } catch { } }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { _cts?.Cancel(); } catch { }
|
||||
try { if (_listener.IsListening) _listener.Stop(); } catch { }
|
||||
try { _listener.Close(); } catch { }
|
||||
try { _loop?.Wait(500); } catch { }
|
||||
Running = false;
|
||||
}
|
||||
}
|
||||
123
src/RynthCore.StatusAgent/MapService.cs
Normal file
123
src/RynthCore.StatusAgent/MapService.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Serves baked dungeon floor-plan PNGs from RynthAi's on-disk maps
|
||||
/// (default C:\Games\RynthSuite\RynthAi\Maps\{landblock:X8}_{layer}.bin). Each .bin is a FINISHED
|
||||
/// top-down raster (20-byte header [Magic, xMin, yMin, w, h] + w*h ARGB uint32 pixels, 0.5 world-units
|
||||
/// /pixel, row 0 = northernmost) written as a side-effect of the in-game D3D9 bake. The agent only
|
||||
/// RE-ENCODES the already-baked pixels to PNG — it cannot generate a map (the DAT decoder lives in the
|
||||
/// plugin). Reads are mid-write tolerant (the bake uses FileMode.Create with no temp+rename) and return
|
||||
/// null on any problem so the endpoint 404s. Windows-only (System.Drawing), same as IconService.
|
||||
/// </summary>
|
||||
internal sealed partial class MapService
|
||||
{
|
||||
private const uint Magic = 0x524D5458u; // "XTMR" — must match DungeonMapTexture.cs
|
||||
private const int MaxDim = 8192;
|
||||
|
||||
private readonly string _mapsDir;
|
||||
// PNG cache keyed by (landblock,layer). The value remembers the (mtime,size) it was built from, so a
|
||||
// re-bake (the map grows as the bot explores) is detected and the PNG is rebuilt.
|
||||
private readonly ConcurrentDictionary<(uint Lb, int Layer), (DateTime Mtime, long Bytes, byte[] Png)> _cache = new();
|
||||
|
||||
public MapService(string mapsDir) => _mapsDir = mapsDir;
|
||||
|
||||
[GeneratedRegex(@"^([0-9A-Fa-f]{8})_(\d+)\.bin$")]
|
||||
private static partial Regex FileRx();
|
||||
|
||||
internal sealed record MapEntry(uint Landblock, int Layer, long Bytes, DateTime MtimeUtc, int W, int H, int XMin, int YMin);
|
||||
|
||||
/// <summary>Enumerate every readable .bin map (header parsed for bounds). Never throws.</summary>
|
||||
public IReadOnlyList<MapEntry> List()
|
||||
{
|
||||
var list = new List<MapEntry>();
|
||||
string[] files;
|
||||
try { files = Directory.GetFiles(_mapsDir, "*.bin"); }
|
||||
catch { return list; }
|
||||
foreach (string path in files)
|
||||
{
|
||||
Match m = FileRx().Match(Path.GetFileName(path));
|
||||
if (!m.Success) continue;
|
||||
if (!uint.TryParse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb)) continue;
|
||||
if (!int.TryParse(m.Groups[2].Value, out int layer)) continue;
|
||||
if (TryReadHeader(path, out int w, out int h, out int xMin, out int yMin, out long len, out DateTime mtime))
|
||||
list.Add(new MapEntry(lb, layer, len, mtime, w, h, xMin, yMin));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Decode one .bin to PNG (+ its metadata), or null if unavailable / partial / corrupt.</summary>
|
||||
public (byte[] Png, MapEntry Meta)? GetPng(uint lb, int layer)
|
||||
{
|
||||
string path = Path.Combine(_mapsDir, $"{lb:X8}_{layer}.bin");
|
||||
if (!TryReadHeader(path, out int w, out int h, out int xMin, out int yMin, out long len, out DateTime mtime))
|
||||
return null;
|
||||
var meta = new MapEntry(lb, layer, len, mtime, w, h, xMin, yMin);
|
||||
var key = (lb, layer);
|
||||
if (_cache.TryGetValue(key, out var c) && c.Mtime == mtime && c.Bytes == len)
|
||||
return (c.Png, meta);
|
||||
try
|
||||
{
|
||||
byte[] raw = new byte[(long)w * h * 4];
|
||||
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
if (fs.Length < 20L + raw.Length) return null; // pixels not fully written yet (mid-bake)
|
||||
fs.Seek(20, SeekOrigin.Begin);
|
||||
int off = 0;
|
||||
while (off < raw.Length)
|
||||
{
|
||||
int got = fs.Read(raw, off, raw.Length - off);
|
||||
if (got <= 0) return null;
|
||||
off += got;
|
||||
}
|
||||
}
|
||||
byte[] png = BgraBytesToPng(raw, w, h);
|
||||
_cache[key] = (mtime, len, png);
|
||||
return (png, meta);
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static bool TryReadHeader(string path, out int w, out int h, out int xMin, out int yMin, out long len, out DateTime mtime)
|
||||
{
|
||||
w = h = xMin = yMin = 0; len = 0; mtime = default;
|
||||
try
|
||||
{
|
||||
var fi = new FileInfo(path);
|
||||
if (!fi.Exists || fi.Length < 20) return false;
|
||||
len = fi.Length; mtime = fi.LastWriteTimeUtc;
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var br = new BinaryReader(fs);
|
||||
if (br.ReadUInt32() != Magic) return false;
|
||||
xMin = br.ReadInt32(); yMin = br.ReadInt32(); w = br.ReadInt32(); h = br.ReadInt32();
|
||||
if (w < 1 || w > MaxDim || h < 1 || h > MaxDim) { w = h = 0; return false; }
|
||||
if (len < 20L + (long)w * h * 4) { w = h = 0; return false; } // header present but pixels not yet
|
||||
return true;
|
||||
}
|
||||
catch { w = h = 0; return false; }
|
||||
}
|
||||
|
||||
/// The .bin packs each pixel as ARGB uint32 (A<<24|R<<16|G<<8|B); on little-endian that is byte
|
||||
/// order B,G,R,A == Format32bppArgb's in-memory layout, so copy the raw bytes verbatim — NO R<->B
|
||||
/// swizzle (unlike IconService.RgbaToPng, whose input is RGBA). Row 0 = north = PNG top (correct).
|
||||
private static byte[] BgraBytesToPng(byte[] bgra, int w, int h)
|
||||
{
|
||||
using var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb);
|
||||
var bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
|
||||
try
|
||||
{
|
||||
for (int y = 0; y < h; y++)
|
||||
Marshal.Copy(bgra, y * w * 4, bd.Scan0 + y * bd.Stride, w * 4);
|
||||
}
|
||||
finally { bmp.UnlockBits(bd); }
|
||||
using var ms = new MemoryStream();
|
||||
bmp.Save(ms, ImageFormat.Png);
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
323
src/RynthCore.StatusAgent/Models.cs
Normal file
323
src/RynthCore.StatusAgent/Models.cs
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
// ── Incoming: the per-client status file the engine writes ──────────────────
|
||||
|
||||
/// <summary>Mirror of the engine's <c>rynthcore.client-status/1</c> file.</summary>
|
||||
internal sealed class StatusFileModel
|
||||
{
|
||||
[JsonPropertyName("schema")] public string Schema { get; set; } = "";
|
||||
[JsonPropertyName("ts")] public DateTimeOffset Ts { get; set; }
|
||||
[JsonPropertyName("host")] public string Host { get; set; } = "";
|
||||
[JsonPropertyName("pid")] public int Pid { get; set; }
|
||||
[JsonPropertyName("account")] public string Account { get; set; } = "";
|
||||
[JsonPropertyName("character")] public string Character { get; set; } = "";
|
||||
[JsonPropertyName("server")] public string Server { get; set; } = "";
|
||||
[JsonPropertyName("uptimeSec")] public long UptimeSec { get; set; }
|
||||
[JsonPropertyName("fps")] public int Fps { get; set; }
|
||||
[JsonPropertyName("pluginTicksPerSec")] public int PluginTicksPerSec { get; set; }
|
||||
[JsonPropertyName("workingSetMB")] public long WorkingSetMB { get; set; }
|
||||
[JsonPropertyName("inWorld")] public bool InWorld { get; set; }
|
||||
[JsonPropertyName("queueDropped")] public long QueueDropped { get; set; }
|
||||
[JsonPropertyName("reconciles")] public long Reconciles { get; set; }
|
||||
[JsonPropertyName("forceClears")] public long ForceClears { get; set; }
|
||||
// Player stats written by the engine (PrefetchPlayerStats) — top-level, not in the bot blob,
|
||||
// because the off-thread plugin pump can't read them. kills/hour stays bot-derived below.
|
||||
[JsonPropertyName("deaths")] public int Deaths { get; set; }
|
||||
[JsonPropertyName("deathsSession")] public int DeathsSession { get; set; }
|
||||
[JsonPropertyName("vitaePct")] public double VitaePct { get; set; }
|
||||
[JsonPropertyName("xpPerHour")] public double XpPerHour { get; set; }
|
||||
[JsonPropertyName("luminancePerHour")] public double LuminancePerHour { get; set; }
|
||||
[JsonPropertyName("xpSession")] public long XpSession { get; set; }
|
||||
[JsonPropertyName("burdenPct")] public double BurdenPct { get; set; }
|
||||
[JsonPropertyName("area")] public string Area { get; set; } = "";
|
||||
[JsonPropertyName("landblock")] public string Landblock { get; set; } = ""; // [status-export] live map-dot
|
||||
[JsonPropertyName("indoor")] public bool Indoor { get; set; }
|
||||
[JsonPropertyName("wx")] public double Wx { get; set; }
|
||||
[JsonPropertyName("wy")] public double Wy { get; set; }
|
||||
[JsonPropertyName("pz")] public double Pz { get; set; }
|
||||
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
|
||||
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
|
||||
[JsonPropertyName("bot")] public BotSnapshot? Bot { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The subset of the RynthAi snapshot the agent surfaces.</summary>
|
||||
internal sealed class BotSnapshot
|
||||
{
|
||||
[JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; }
|
||||
[JsonPropertyName("currentState")] public string CurrentState { get; set; } = "";
|
||||
[JsonPropertyName("botAction")] public string BotAction { get; set; } = "";
|
||||
[JsonPropertyName("selectedProfile")] public string SelectedProfile { get; set; } = "";
|
||||
[JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = "";
|
||||
[JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = "";
|
||||
[JsonPropertyName("currentMetaName")] public string CurrentMetaName { 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; }
|
||||
// Profile lists + current selection, so a remote client can offer a profile picker.
|
||||
[JsonPropertyName("navProfiles")] public List<string>? NavProfiles { get; set; }
|
||||
[JsonPropertyName("lootProfiles")] public List<string>? LootProfiles { get; set; }
|
||||
[JsonPropertyName("metaProfiles")] public List<string>? MetaProfiles { get; set; }
|
||||
[JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; } = -1;
|
||||
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } = -1;
|
||||
[JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; } = -1;
|
||||
[JsonPropertyName("targetLabel")] public string TargetLabel { 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("killsPerHour")] public double KillsPerHour { get; set; }
|
||||
[JsonPropertyName("sessionKills")] public int SessionKills { get; set; }
|
||||
[JsonPropertyName("secsSinceLastKill")] public int SecsSinceLastKill { get; set; } = -1;
|
||||
[JsonPropertyName("freeSlots")] public int FreeSlots { get; set; } = -1;
|
||||
[JsonPropertyName("uiHidden")] public bool UiHidden { get; set; }
|
||||
[JsonPropertyName("isMinimized")] public bool IsMinimized { get; set; }
|
||||
[JsonPropertyName("scarabs")] public int Scarabs { get; set; } = -1;
|
||||
[JsonPropertyName("tapers")] public int Tapers { get; set; } = -1;
|
||||
[JsonPropertyName("scarabsByType")] public List<ScarabCount>? ScarabsByType { get; set; }
|
||||
[JsonPropertyName("equipment")] public List<EquipItem>? Equipment { get; set; }
|
||||
// D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning).
|
||||
[JsonPropertyName("scanTotal")] public int ScanTotal { get; set; } = -1;
|
||||
[JsonPropertyName("scanRing")] public int ScanRing { get; set; } = -1;
|
||||
[JsonPropertyName("scanPossible")] public int ScanPossible { get; set; } = -1;
|
||||
[JsonPropertyName("scanLosBlocked")] public int ScanLosBlocked { get; set; } = -1;
|
||||
[JsonPropertyName("sessionAttackCasts")] public int SessionAttackCasts { get; set; }
|
||||
[JsonPropertyName("castsSinceLastKill")] public int CastsSinceLastKill { get; set; }
|
||||
[JsonPropertyName("castsPerKill")] public double CastsPerKill { get; set; }
|
||||
[JsonPropertyName("recentChat")] public List<ChatLine>? RecentChat { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One scarab tier and its inventory count.</summary>
|
||||
internal sealed class ScarabCount
|
||||
{
|
||||
[JsonPropertyName("name")] public string Name { get; set; } = "";
|
||||
[JsonPropertyName("count")] public int Count { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One captured chat line: text + AC chat-type (for colouring).</summary>
|
||||
internal sealed class ChatLine
|
||||
{
|
||||
[JsonPropertyName("t")] public string Text { get; set; } = "";
|
||||
[JsonPropertyName("c")] public int Type { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One worn/wielded item with its full appraisal (Assess/Identify data).</summary>
|
||||
internal sealed class EquipItem
|
||||
{
|
||||
[JsonPropertyName("name")] public string Name { get; set; } = "";
|
||||
[JsonPropertyName("id")] public uint Id { get; set; }
|
||||
[JsonPropertyName("slot")] public int Slot { get; set; }
|
||||
[JsonPropertyName("armorLevel")] public int ArmorLevel { get; set; }
|
||||
[JsonPropertyName("resist")] public List<double>? Resist { get; set; } // 7: slash,pierce,bludge,cold,fire,acid,electric
|
||||
[JsonPropertyName("value")] public int Value { get; set; }
|
||||
[JsonPropertyName("burden")] public int Burden { get; set; }
|
||||
[JsonPropertyName("workmanship")] public int Workmanship { get; set; }
|
||||
[JsonPropertyName("material")] public int Material { get; set; }
|
||||
[JsonPropertyName("maxMana")] public int MaxMana { get; set; }
|
||||
[JsonPropertyName("curMana")] public int CurMana { get; set; }
|
||||
[JsonPropertyName("damage")] public int Damage { get; set; }
|
||||
[JsonPropertyName("damageType")] public int DamageType { get; set; }
|
||||
[JsonPropertyName("weaponDef")] public double WeaponDef { get; set; }
|
||||
[JsonPropertyName("missileDef")] public double MissileDef { get; set; }
|
||||
[JsonPropertyName("magicDef")] public double MagicDef { get; set; }
|
||||
[JsonPropertyName("variance")] public double Variance { get; set; }
|
||||
[JsonPropertyName("elementalMod")]public double ElementalMod { get; set; }
|
||||
[JsonPropertyName("spells")] public List<string>? Spells { get; set; }
|
||||
[JsonPropertyName("longDesc")] public string? LongDesc { get; set; }
|
||||
}
|
||||
|
||||
// ── Outgoing: the rolled-up payload posted to the user's backend ────────────
|
||||
|
||||
internal sealed class Vitals
|
||||
{
|
||||
[JsonPropertyName("hp")] public uint Hp { get; set; }
|
||||
[JsonPropertyName("maxHp")] public uint MaxHp { get; set; }
|
||||
[JsonPropertyName("st")] public uint St { get; set; }
|
||||
[JsonPropertyName("maxSt")] public uint MaxSt { get; set; }
|
||||
[JsonPropertyName("mn")] public uint Mn { get; set; }
|
||||
[JsonPropertyName("maxMn")] public uint MaxMn { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One client's derived status, as the phone app consumes it.</summary>
|
||||
internal sealed class ClientStatus
|
||||
{
|
||||
[JsonPropertyName("pid")] public int Pid { get; set; }
|
||||
[JsonPropertyName("host")] public string Host { get; set; } = "";
|
||||
[JsonPropertyName("account")] public string Account { get; set; } = "";
|
||||
[JsonPropertyName("character")] public string Character { get; set; } = "";
|
||||
[JsonPropertyName("server")] public string Server { get; set; } = "";
|
||||
|
||||
/// <summary>running | botting | idle | loading | wedged | hung | dead.</summary>
|
||||
[JsonPropertyName("state")] public string State { get; set; } = "unknown";
|
||||
[JsonPropertyName("healthy")] public bool Healthy { get; set; }
|
||||
/// <summary>Seconds since this client's snapshot was last refreshed.</summary>
|
||||
[JsonPropertyName("ageSec")] public double AgeSec { get; set; }
|
||||
/// <summary>"status-file" (rich) or "heartbeat-log" (basic fallback).</summary>
|
||||
[JsonPropertyName("source")] public string Source { get; set; } = "";
|
||||
|
||||
[JsonPropertyName("uptimeSec")] public long UptimeSec { get; set; }
|
||||
[JsonPropertyName("fps")] public int Fps { get; set; }
|
||||
[JsonPropertyName("pluginTicksPerSec")] public int PluginTicksPerSec { get; set; }
|
||||
[JsonPropertyName("workingSetMB")] public long WorkingSetMB { get; set; }
|
||||
[JsonPropertyName("inWorld")] public bool InWorld { get; set; }
|
||||
|
||||
[JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; }
|
||||
[JsonPropertyName("currentState")] public string CurrentState { get; set; } = "";
|
||||
[JsonPropertyName("botAction")] public string BotAction { get; set; } = "";
|
||||
[JsonPropertyName("profile")] public string Profile { get; set; } = "";
|
||||
[JsonPropertyName("navProfile")] public string NavProfile { get; set; } = "";
|
||||
[JsonPropertyName("lootProfile")] public string LootProfile { get; set; } = "";
|
||||
[JsonPropertyName("metaProfile")] public string MetaProfile { get; set; } = "";
|
||||
[JsonPropertyName("target")] public string Target { get; set; } = "";
|
||||
|
||||
// Control state (status-file clients): the five subsystem flags + profile lists/selection,
|
||||
// so a remote client can show the current switch positions and offer a profile picker.
|
||||
[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("navProfiles")] public List<string>? NavProfiles { get; set; }
|
||||
[JsonPropertyName("lootProfiles")] public List<string>? LootProfiles { get; set; }
|
||||
[JsonPropertyName("metaProfiles")] public List<string>? MetaProfiles { get; set; }
|
||||
[JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; } = -1;
|
||||
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } = -1;
|
||||
[JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; } = -1;
|
||||
[JsonPropertyName("player")] public Vitals? Player { get; set; }
|
||||
|
||||
[JsonPropertyName("queueDropped")] public long QueueDropped { get; set; }
|
||||
[JsonPropertyName("reconciles")] public long Reconciles { get; set; }
|
||||
[JsonPropertyName("forceClears")] public long ForceClears { get; set; }
|
||||
|
||||
[JsonPropertyName("deaths")] public int Deaths { get; set; }
|
||||
[JsonPropertyName("deathsSession")] public int DeathsSession { get; set; }
|
||||
[JsonPropertyName("vitaePct")] public double VitaePct { get; set; }
|
||||
[JsonPropertyName("killsPerHour")] public double KillsPerHour { get; set; }
|
||||
[JsonPropertyName("xpPerHour")] public double XpPerHour { get; set; }
|
||||
[JsonPropertyName("luminancePerHour")] public double LuminancePerHour { get; set; }
|
||||
[JsonPropertyName("xpSession")] public long XpSession { get; set; }
|
||||
[JsonPropertyName("burdenPct")] public double BurdenPct { get; set; }
|
||||
[JsonPropertyName("area")] public string Area { get; set; } = "";
|
||||
[JsonPropertyName("landblock")] public string Landblock { get; set; } = ""; // [status-export] live map-dot
|
||||
[JsonPropertyName("indoor")] public bool Indoor { get; set; }
|
||||
[JsonPropertyName("wx")] public double Wx { get; set; }
|
||||
[JsonPropertyName("wy")] public double Wy { get; set; }
|
||||
[JsonPropertyName("pz")] public double Pz { get; set; }
|
||||
[JsonPropertyName("sessionKills")] public int SessionKills { get; set; }
|
||||
[JsonPropertyName("secsSinceLastKill")] public int SecsSinceLastKill { get; set; } = -1;
|
||||
[JsonPropertyName("freeSlots")] public int FreeSlots { get; set; } = -1;
|
||||
[JsonPropertyName("uiHidden")] public bool UiHidden { get; set; }
|
||||
[JsonPropertyName("isMinimized")] public bool IsMinimized { get; set; }
|
||||
[JsonPropertyName("scarabs")] public int Scarabs { get; set; } = -1;
|
||||
[JsonPropertyName("tapers")] public int Tapers { get; set; } = -1;
|
||||
[JsonPropertyName("scarabsByType")] public List<ScarabCount>? ScarabsByType { get; set; }
|
||||
[JsonPropertyName("equipment")] public List<EquipItem>? Equipment { get; set; }
|
||||
// D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning).
|
||||
[JsonPropertyName("scanTotal")] public int ScanTotal { get; set; } = -1;
|
||||
[JsonPropertyName("scanRing")] public int ScanRing { get; set; } = -1;
|
||||
[JsonPropertyName("scanPossible")] public int ScanPossible { get; set; } = -1;
|
||||
[JsonPropertyName("scanLosBlocked")] public int ScanLosBlocked { get; set; } = -1;
|
||||
[JsonPropertyName("sessionAttackCasts")] public int SessionAttackCasts { get; set; }
|
||||
[JsonPropertyName("castsSinceLastKill")] public int CastsSinceLastKill { get; set; }
|
||||
[JsonPropertyName("castsPerKill")] public double CastsPerKill { get; set; }
|
||||
[JsonPropertyName("recentChat")] public List<ChatLine>? RecentChat { get; set; }
|
||||
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
|
||||
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
|
||||
}
|
||||
|
||||
internal sealed class AggregatePayload
|
||||
{
|
||||
[JsonPropertyName("schema")] public string Schema { get; set; } = "rynthcore.status-agent/1";
|
||||
[JsonPropertyName("host")] public string Host { get; set; } = "";
|
||||
[JsonPropertyName("agentVersion")] public string AgentVersion { get; set; } = "";
|
||||
[JsonPropertyName("generatedAtUtc")] public DateTimeOffset GeneratedAtUtc { get; set; }
|
||||
[JsonPropertyName("clientCount")] public int ClientCount { get; set; }
|
||||
[JsonPropertyName("clients")] public List<ClientStatus> Clients { get; set; } = new();
|
||||
}
|
||||
|
||||
// ── Run archive: one finished (or in-progress) play session per client ──────
|
||||
|
||||
/// <summary>One AC client session — login→exit — with its final/last stats. The agent captures these
|
||||
/// as clients exit (or restart), so the player can review how past runs did. Schema "rynthcore.runs/1".</summary>
|
||||
internal sealed class RunRecord
|
||||
{
|
||||
/// <summary>Stable per-session id: "<pid>-<startUnixSec>".</summary>
|
||||
[JsonPropertyName("runId")] public string RunId { get; set; } = "";
|
||||
[JsonPropertyName("pid")] public int Pid { get; set; }
|
||||
[JsonPropertyName("account")] public string Account { get; set; } = "";
|
||||
[JsonPropertyName("character")] public string Character { get; set; } = "";
|
||||
[JsonPropertyName("server")] public string Server { get; set; } = "";
|
||||
[JsonPropertyName("startUtc")] public DateTimeOffset StartUtc { get; set; }
|
||||
/// <summary>Null while the run is still in progress.</summary>
|
||||
[JsonPropertyName("endUtc")] public DateTimeOffset? EndUtc { get; set; }
|
||||
[JsonPropertyName("durationSec")] public long DurationSec { get; set; }
|
||||
[JsonPropertyName("kills")] public int Kills { get; set; }
|
||||
[JsonPropertyName("killsPerHour")] public double KillsPerHour { get; set; }
|
||||
/// <summary>Offensive attack casts per kill over the run — climbs when casts land no damage.</summary>
|
||||
[JsonPropertyName("castsPerKill")] public double CastsPerKill { get; set; }
|
||||
[JsonPropertyName("xp")] public long Xp { get; set; }
|
||||
[JsonPropertyName("xpPerHour")] public double XpPerHour { get; set; }
|
||||
[JsonPropertyName("luminancePerHour")] public double LuminancePerHour { get; set; }
|
||||
/// <summary>Deaths during this session (not all-time).</summary>
|
||||
[JsonPropertyName("deaths")] public int Deaths { get; set; }
|
||||
[JsonPropertyName("vitaePct")] public double VitaePct { get; set; }
|
||||
[JsonPropertyName("area")] public string Area { get; set; } = "";
|
||||
/// <summary>True for the live, not-yet-finished run (shown at the top, updates each cycle).</summary>
|
||||
[JsonPropertyName("ongoing")] public bool Ongoing { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The /runs payload: finished runs (newest first), with any in-progress run marked ongoing.</summary>
|
||||
internal sealed class RunsPayload
|
||||
{
|
||||
[JsonPropertyName("schema")] public string Schema { get; set; } = "rynthcore.runs/1";
|
||||
[JsonPropertyName("host")] public string Host { get; set; } = "";
|
||||
[JsonPropertyName("generatedAtUtc")] public DateTimeOffset GeneratedAtUtc { get; set; }
|
||||
[JsonPropertyName("count")] public int Count { get; set; }
|
||||
[JsonPropertyName("runs")] public List<RunRecord> Runs { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>One baked dungeon floor-plan map available via GET /map (landblock + Z-layer + raster bounds).</summary>
|
||||
internal sealed class MapEntryDto
|
||||
{
|
||||
[JsonPropertyName("landblock")] public string Landblock { get; set; } = ""; // "0000002B" (matches the .bin filename)
|
||||
[JsonPropertyName("layer")] public int Layer { get; set; }
|
||||
[JsonPropertyName("bytes")] public long Bytes { get; set; }
|
||||
[JsonPropertyName("mtime")] public DateTimeOffset Mtime { get; set; }
|
||||
[JsonPropertyName("w")] public int W { get; set; }
|
||||
[JsonPropertyName("h")] public int H { get; set; }
|
||||
[JsonPropertyName("xMin")] public int XMin { get; set; } // grid-cell units, ABSOLUTE world frame
|
||||
[JsonPropertyName("yMin")] public int YMin { get; set; }
|
||||
[JsonPropertyName("name")] public string Name { get; set; } = ""; // friendly label (hex for now)
|
||||
}
|
||||
|
||||
/// <summary>The /maps payload: every baked dungeon floor-plan the agent can serve.</summary>
|
||||
internal sealed class MapsListPayload
|
||||
{
|
||||
[JsonPropertyName("schema")] public string Schema { get; set; } = "rynthcore.maps/1";
|
||||
[JsonPropertyName("count")] public int Count { get; set; }
|
||||
[JsonPropertyName("maps")] public List<MapEntryDto> Maps { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>A remote-control command the agent writes for the plugin to poll + apply.</summary>
|
||||
internal sealed class CommandFile
|
||||
{
|
||||
[JsonPropertyName("schema")] public string Schema { get; set; } = "rynthcore.command/1";
|
||||
[JsonPropertyName("pid")] public int Pid { get; set; }
|
||||
[JsonPropertyName("action")] public string Action { get; set; } = "";
|
||||
[JsonPropertyName("value")] public string Value { get; set; } = "";
|
||||
[JsonPropertyName("ts")] public DateTimeOffset Ts { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.Never)]
|
||||
[JsonSerializable(typeof(StatusFileModel))]
|
||||
[JsonSerializable(typeof(AggregatePayload))]
|
||||
[JsonSerializable(typeof(AgentConfig))]
|
||||
[JsonSerializable(typeof(CommandFile))]
|
||||
[JsonSerializable(typeof(RunsPayload))]
|
||||
[JsonSerializable(typeof(MapsListPayload))]
|
||||
internal sealed partial class AgentJsonContext : JsonSerializerContext { }
|
||||
293
src/RynthCore.StatusAgent/Program.cs
Normal file
293
src/RynthCore.StatusAgent/Program.cs
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using RynthCore.StatusAgent;
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// RynthCore.StatusAgent — optional, runs on the operator's own PC.
|
||||
//
|
||||
// Reads the LOCAL per-client status files RynthCore writes and forwards a
|
||||
// rolled-up status payload to a USER-CONFIGURED endpoint. Sends nothing until
|
||||
// you put an "Endpoint" URL in %APPDATA%\RynthCore\statusagent.json.
|
||||
//
|
||||
// Flags:
|
||||
// --once run a single cycle and exit (handy for testing)
|
||||
// --dry-run read + print, never POST (even if an endpoint is set)
|
||||
// --config PATH use an alternate config file
|
||||
// --interval N override the post interval (seconds)
|
||||
// --verbose verbose logging
|
||||
// --help show this help
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
var opts = CliOptions.Parse(args);
|
||||
if (opts.ShowHelp)
|
||||
{
|
||||
CliOptions.PrintHelp();
|
||||
return 0;
|
||||
}
|
||||
|
||||
string configPath = opts.ConfigPath ?? AgentConfig.DefaultConfigPath;
|
||||
AgentConfig cfg = AgentConfig.LoadOrCreate(configPath, out bool created);
|
||||
if (opts.IntervalOverride is int iv && iv > 0) cfg.IntervalSeconds = iv;
|
||||
|
||||
AgentLog.Verbose = opts.Verbose;
|
||||
AgentLog.Init(cfg.LogDirectory);
|
||||
|
||||
string version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "1.0.0";
|
||||
AgentLog.Info($"RynthCore.StatusAgent v{version} starting.");
|
||||
AgentLog.Info($"Config: {configPath}");
|
||||
AgentLog.Info($"Status dir: {cfg.StatusDirectory}");
|
||||
|
||||
// Per-session run history (kills/XP/etc.), captured as clients exit. Persisted to runs.json so it
|
||||
// survives agent restarts; served at GET /runs for the app's Archive tab.
|
||||
var runArchive = new RunArchive(Path.Combine(cfg.StatusDirectory, "runs.json"), cfg.EffectiveHost);
|
||||
|
||||
if (created)
|
||||
{
|
||||
AgentLog.Info("A fresh config template was written. The agent will run in");
|
||||
AgentLog.Info("LOCAL PRINT-ONLY mode (no network) until you set \"Endpoint\".");
|
||||
}
|
||||
|
||||
using var publisher = new BackendPublisher(cfg);
|
||||
if (publisher.Enabled)
|
||||
AgentLog.Info($"Forwarding to endpoint: {cfg.Endpoint} every {cfg.IntervalSeconds}s.");
|
||||
else
|
||||
AgentLog.Info("No endpoint configured -> LOCAL PRINT-ONLY mode (nothing is sent anywhere).");
|
||||
|
||||
// Opt-in pull endpoint: an app can fetch status with no backend.
|
||||
LocalStatusServer? server = null;
|
||||
WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally
|
||||
IconService? icons = null; // item-icon decoder (GET /icon); disposed in finally
|
||||
if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken))
|
||||
{
|
||||
// Same rule as DrakBot's remote: no token, no server, loopback included. The server can show
|
||||
// the game screens, click in them and close clients.
|
||||
AgentLog.Warn("ServeHttp is on but ServeToken is empty, so the status server stays off.");
|
||||
AgentLog.Warn($"Set \"ServeToken\" in {configPath} and restart the agent. Use the same token as your");
|
||||
AgentLog.Warn("DrakBot remote and one DrakRemote entry shows both.");
|
||||
}
|
||||
else if (cfg.ServeHttp)
|
||||
{
|
||||
string? commandDir = cfg.EnableRemoteControl ? Path.Combine(cfg.StatusDirectory, "commands") : null;
|
||||
VideoSocketService? videoSocket = null;
|
||||
if (cfg.EnableVideoStream)
|
||||
{
|
||||
video = new WebRtcVideoService(cfg.VideoMaxWidth, cfg.VideoFps, cfg.VideoBitrateKbps);
|
||||
videoSocket = new VideoSocketService(cfg.VideoMaxWidth, cfg.VideoFps, cfg.VideoBitrateKbps);
|
||||
}
|
||||
// Item-icon decoder (lazy-opens portal.dat on the first /icon request; harmless if the file is absent).
|
||||
icons = new IconService(cfg.IconDatPath);
|
||||
// Dungeon floor-plan maps (re-encodes RynthAi's baked .bin rasters to PNG; harmless if the folder is absent).
|
||||
MapService maps = new MapService(cfg.MapsDirectory);
|
||||
server = new LocalStatusServer(cfg.ServePrefix, cfg.ServeToken, commandDir,
|
||||
cfg.EnableScreenStream, cfg.StreamQuality, cfg.StreamIntervalMs, video, videoSocket,
|
||||
runArchive, cfg.StatusDirectory, icons, maps);
|
||||
if (server.TryStart(out string serveErr))
|
||||
{
|
||||
AgentLog.Info($"Serving status at {cfg.ServePrefix}status (GET){(string.IsNullOrEmpty(cfg.ServeToken) ? "" : ", token required")}.");
|
||||
if (commandDir != null)
|
||||
AgentLog.Info($"Remote control ENABLED: POST {cfg.ServePrefix}command -> {commandDir}.");
|
||||
if (cfg.EnableScreenStream)
|
||||
AgentLog.Info($"Screen stream ENABLED: GET {cfg.ServePrefix}stream?pid=N (MJPEG) / frame?pid=N.");
|
||||
if (cfg.EnableVideoStream)
|
||||
AgentLog.Info($"HD video ENABLED: GET {cfg.ServePrefix}video?pid=N (WS H.264 client-server) + POST webrtc/offer (same-LAN). {(cfg.VideoMaxWidth == 0 ? "native" : cfg.VideoMaxWidth + "w")}@{cfg.VideoFps}fps.");
|
||||
}
|
||||
else
|
||||
{
|
||||
AgentLog.Warn($"Could not start status server on {cfg.ServePrefix} ({serveErr}).");
|
||||
AgentLog.Warn("For a LAN/Tailscale bind (http://+:PORT/) run elevated once, or add a netsh urlacl.");
|
||||
server.Dispose();
|
||||
server = null;
|
||||
}
|
||||
}
|
||||
|
||||
string aggregatePath = Path.Combine(cfg.StatusDirectory, "aggregate.json");
|
||||
|
||||
if (opts.DryRun)
|
||||
AgentLog.Info("--dry-run: status will be printed but never POSTed.");
|
||||
|
||||
// Ctrl+C / SIGTERM -> graceful stop. Not disposed: ProcessExit fires during
|
||||
// shutdown and would otherwise hit a disposed CTS (ObjectDisposedException ->
|
||||
// nonzero exit). The process is ending anyway, so there's nothing to leak.
|
||||
var cts = new CancellationTokenSource();
|
||||
Console.CancelKeyPress += (_, e) => { e.Cancel = true; try { cts.Cancel(); } catch (ObjectDisposedException) { } };
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { cts.Cancel(); } catch (ObjectDisposedException) { } };
|
||||
|
||||
// ── Event-driven status pump ────────────────────────────────────────────────
|
||||
// A FileSystemWatcher on the status dir wakes the loop within ~DebounceMs of a client writing its
|
||||
// snapshot, instead of waiting a fixed poll. IntervalSeconds is now the SAFETY FALLBACK (the max time
|
||||
// between cycles when no file events arrive) — it still drives the time-based work: dead-PID liveness +
|
||||
// DropDeadAfterSeconds pruning and the heartbeat-log fallback. Net: phone-visible status latency drops
|
||||
// from up to IntervalSeconds to ~DebounceMs after the write. Agent-side only — no game-client risk.
|
||||
const int DebounceMs = 50;
|
||||
int fallbackMs = Math.Max(1, cfg.IntervalSeconds) * 1000;
|
||||
using var dirty = new SemaphoreSlim(0, 1);
|
||||
FileSystemWatcher? watcher = opts.Once ? null : TryArmStatusWatcher(cfg.StatusDirectory, dirty);
|
||||
|
||||
try
|
||||
{
|
||||
do
|
||||
{
|
||||
try { await RunCycleAsync(); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (Exception ex) { AgentLog.Error($"cycle failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
if (opts.Once) break;
|
||||
|
||||
try
|
||||
{
|
||||
// Wake on a status-file change OR the safety-fallback interval, then debounce the burst of
|
||||
// events that one atomic write (tmp create + rename + size change) produces into a single cycle.
|
||||
await dirty.WaitAsync(fallbackMs, cts.Token);
|
||||
await Task.Delay(DebounceMs, cts.Token);
|
||||
while (dirty.Wait(0)) { } // drain extra signals accrued during the debounce window
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
}
|
||||
while (!cts.IsCancellationRequested);
|
||||
}
|
||||
finally
|
||||
{
|
||||
watcher?.Dispose();
|
||||
server?.Dispose();
|
||||
video?.Dispose();
|
||||
icons?.Dispose();
|
||||
AgentLog.Info("RynthCore.StatusAgent stopped.");
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
// One status cycle: read all client status, roll it up, and serve / file / POST it.
|
||||
async Task RunCycleAsync()
|
||||
{
|
||||
List<ClientStatus> clients = StatusReader.ReadAll(cfg);
|
||||
runArchive.Observe(clients); // fold this cycle into per-session run history (started/updated/finished)
|
||||
var payload = new AggregatePayload
|
||||
{
|
||||
Host = cfg.EffectiveHost,
|
||||
AgentVersion = version,
|
||||
GeneratedAtUtc = DateTimeOffset.UtcNow,
|
||||
ClientCount = clients.Count,
|
||||
Clients = clients,
|
||||
};
|
||||
|
||||
// Serialize once; reuse the bytes for serve / file / POST.
|
||||
byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.AggregatePayload);
|
||||
|
||||
AgentLog.Info(Summarize(clients));
|
||||
if (opts.Verbose)
|
||||
AgentLog.Debug(System.Text.Encoding.UTF8.GetString(bytes));
|
||||
|
||||
server?.UpdateLatest(bytes);
|
||||
|
||||
if (cfg.WriteAggregateFile)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(cfg.StatusDirectory);
|
||||
File.WriteAllBytes(aggregatePath, bytes);
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Debug($"aggregate.json write failed: {ex.Message}"); }
|
||||
}
|
||||
|
||||
if (publisher.Enabled && !opts.DryRun)
|
||||
await publisher.PublishAsync(bytes, payload.ClientCount, cts.Token);
|
||||
}
|
||||
|
||||
// Arm a FileSystemWatcher that pulses `signal` whenever a per-client status file lands. Returns null
|
||||
// (and the loop falls back to interval polling) if the watcher can't be created.
|
||||
static FileSystemWatcher? TryArmStatusWatcher(string statusDir, SemaphoreSlim signal)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(statusDir); // ensure it exists so the watcher can arm (the engine creates it too)
|
||||
var w = new FileSystemWatcher(statusDir, "RynthCore.*.status.json")
|
||||
{
|
||||
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size,
|
||||
InternalBufferSize = 64 * 1024,
|
||||
};
|
||||
// FSW dispatches events sequentially on its own thread; a SemaphoreSlim(0,1) coalesces a burst
|
||||
// into one pending signal (extra Releases are swallowed).
|
||||
void Pulse(object? _, FileSystemEventArgs __) { try { if (signal.CurrentCount == 0) signal.Release(); } catch (SemaphoreFullException) { } }
|
||||
w.Created += Pulse;
|
||||
w.Changed += Pulse;
|
||||
w.Deleted += Pulse;
|
||||
w.Renamed += (_, __) => { try { if (signal.CurrentCount == 0) signal.Release(); } catch (SemaphoreFullException) { } };
|
||||
w.EnableRaisingEvents = true;
|
||||
AgentLog.Info($"Status watcher armed on {statusDir} (event-driven; IntervalSeconds is the safety fallback).");
|
||||
return w;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Warn($"Status watcher unavailable ({ex.GetType().Name}: {ex.Message}); falling back to interval polling.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static string Summarize(List<ClientStatus> clients)
|
||||
{
|
||||
if (clients.Count == 0)
|
||||
return "no RynthCore clients detected.";
|
||||
|
||||
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (ClientStatus c in clients)
|
||||
counts[c.State] = counts.GetValueOrDefault(c.State) + 1;
|
||||
|
||||
string breakdown = string.Join(", ", counts.OrderBy(kv => kv.Key).Select(kv => $"{kv.Value} {kv.Key}"));
|
||||
string detail = string.Join(" | ", clients.Select(c =>
|
||||
{
|
||||
string who = !string.IsNullOrEmpty(c.Character) ? c.Character : $"pid {c.Pid}";
|
||||
return $"{who}: {c.State} (fps {c.Fps}, plug {c.PluginTicksPerSec}/s)";
|
||||
}));
|
||||
return $"{clients.Count} client(s) [{breakdown}] -> {detail}";
|
||||
}
|
||||
|
||||
internal sealed class CliOptions
|
||||
{
|
||||
public bool Once;
|
||||
public bool DryRun;
|
||||
public bool Verbose;
|
||||
public bool ShowHelp;
|
||||
public string? ConfigPath;
|
||||
public int? IntervalOverride;
|
||||
|
||||
public static CliOptions Parse(string[] args)
|
||||
{
|
||||
var o = new CliOptions();
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
switch (args[i].ToLowerInvariant())
|
||||
{
|
||||
case "--once": o.Once = true; break;
|
||||
case "--dry-run": o.DryRun = true; break;
|
||||
case "--verbose": o.Verbose = true; break;
|
||||
case "-h":
|
||||
case "--help": o.ShowHelp = true; break;
|
||||
case "--config": if (i + 1 < args.Length) o.ConfigPath = args[++i]; break;
|
||||
case "--interval":
|
||||
if (i + 1 < args.Length && int.TryParse(args[++i], out int n)) o.IntervalOverride = n;
|
||||
break;
|
||||
default:
|
||||
Console.WriteLine($"Unknown argument: {args[i]}");
|
||||
o.ShowHelp = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
public static void PrintHelp()
|
||||
{
|
||||
Console.WriteLine("RynthCore.StatusAgent — forwards local RynthCore client status to your endpoint.");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Usage: RynthCore.StatusAgent [options]");
|
||||
Console.WriteLine(" --once run one cycle and exit");
|
||||
Console.WriteLine(" --dry-run read + print, never POST");
|
||||
Console.WriteLine(" --config PATH alternate config file");
|
||||
Console.WriteLine(" --interval N override post interval (seconds)");
|
||||
Console.WriteLine(" --verbose verbose logging (prints full payload)");
|
||||
Console.WriteLine(" --help show this help");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"Config: {AgentConfig.DefaultConfigPath}");
|
||||
Console.WriteLine("Nothing is sent until you set \"Endpoint\" in the config.");
|
||||
}
|
||||
}
|
||||
22
src/RynthCore.StatusAgent/README.md
Normal file
22
src/RynthCore.StatusAgent/README.md
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# RynthCore.StatusAgent
|
||||
|
||||
Optional, operator-side console app. Reads the **local** per-client status files
|
||||
RynthCore writes (when `EnableStatusExport` is on) and forwards a rolled-up
|
||||
status payload to **a URL you configure**, so an external app (e.g. a phone
|
||||
dashboard) can show whether your clients are running and actively botting.
|
||||
|
||||
- Runs on **your** PC only. Not injected into the game. Not in the installer.
|
||||
- Three opt-in delivery modes — **push** (POST to your `Endpoint`), **pull**
|
||||
(`ServeHttp: true` → app fetches `GET http://<pc>:8740/status`, no backend
|
||||
needed; pairs well with Tailscale), or **file sync** (`aggregate.json`).
|
||||
- Idle by default: with no `Endpoint` and `ServeHttp: false` it only reads +
|
||||
prints locally and opens no socket.
|
||||
- The engine half never networks — it only writes local files.
|
||||
|
||||
Full setup, the backend payload contract, the client `state` table, and removal
|
||||
steps live in [`docs/STATUS_AGENT.md`](../../docs/STATUS_AGENT.md).
|
||||
|
||||
```powershell
|
||||
dotnet publish .\RynthCore.StatusAgent.csproj -c Release
|
||||
.\bin\Release\net10.0-windows\RynthCore.StatusAgent.exe --once --dry-run # smoke test
|
||||
```
|
||||
251
src/RynthCore.StatusAgent/RunArchive.cs
Normal file
251
src/RynthCore.StatusAgent/RunArchive.cs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Records each AC client's play session (login → exit) so the player can review how past runs did
|
||||
/// (kills, kills/hr, XP, deaths, …). Fed one snapshot list per agent cycle via <see cref="Observe"/>;
|
||||
/// a run is finalised when its client reports "dead", relaunches (uptime resets), or vanishes from the
|
||||
/// feed for longer than the grace window. Finished runs persist to <c>runs.json</c> so the history
|
||||
/// survives agent restarts. Agent-side only — the game client is never touched.
|
||||
/// </summary>
|
||||
internal sealed class RunArchive
|
||||
{
|
||||
// A run must drop its uptime by more than this to count as a relaunch (vs. normal jitter / a clock skew).
|
||||
private const int RestartSlackSec = 120;
|
||||
// A pid missing from the feed this long is treated as finished (covers a transient unreadable-file blip
|
||||
// without losing the run; a clean exit usually finalises sooner via the explicit "dead" state).
|
||||
private const int GoneGraceSec = 60;
|
||||
// Only keep a finished run that actually did something — filters brief loads / instant relaunches.
|
||||
private const int MinKeepSec = 120;
|
||||
|
||||
private readonly string _runsPath;
|
||||
private readonly string _host;
|
||||
private readonly int _maxRuns;
|
||||
private readonly object _lock = new();
|
||||
|
||||
// In-progress runs, keyed by pid. Finished runs, newest first.
|
||||
private readonly Dictionary<int, LiveRun> _live = new();
|
||||
private readonly List<RunRecord> _finished = new();
|
||||
|
||||
public RunArchive(string runsPath, string host, int maxRuns = 1000)
|
||||
{
|
||||
_runsPath = runsPath;
|
||||
_host = host;
|
||||
_maxRuns = Math.Max(1, maxRuns);
|
||||
LoadFromDisk();
|
||||
}
|
||||
|
||||
/// <summary>One agent cycle's worth of client snapshots. Starts/updates/finalises runs accordingly.</summary>
|
||||
public void Observe(List<ClientStatus> clients)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
bool dirty = false;
|
||||
lock (_lock)
|
||||
{
|
||||
var seen = new HashSet<int>();
|
||||
foreach (ClientStatus c in clients)
|
||||
{
|
||||
seen.Add(c.Pid);
|
||||
bool rich = string.Equals(c.Source, "status-file", StringComparison.Ordinal);
|
||||
bool dead = string.Equals(c.State, "dead", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_live.TryGetValue(c.Pid, out LiveRun? run);
|
||||
|
||||
// Relaunch reusing the same pid: uptime fell well below the max we've seen → close the old run.
|
||||
if (run != null && rich && c.UptimeSec + RestartSlackSec < run.MaxUptimeSec)
|
||||
{
|
||||
dirty |= Finalize(run, now);
|
||||
_live.Remove(c.Pid);
|
||||
run = null;
|
||||
}
|
||||
|
||||
if (run == null)
|
||||
{
|
||||
// Only a live, rich client (real bot stats) starts a run. A bare heartbeat-log client or a
|
||||
// already-dead one never opens one — that would archive an empty session.
|
||||
if (!rich || dead) continue;
|
||||
run = NewRun(c, now);
|
||||
_live[c.Pid] = run;
|
||||
}
|
||||
|
||||
run.LastSeenUtc = now;
|
||||
if (rich) run.Update(c);
|
||||
|
||||
if (dead)
|
||||
{
|
||||
dirty |= Finalize(run, now);
|
||||
_live.Remove(c.Pid);
|
||||
}
|
||||
}
|
||||
|
||||
// Finalise runs whose client dropped out of the feed entirely (clean exit we never saw flagged
|
||||
// "dead", a relaunch to a new pid, or the status file pruned) once past the grace window.
|
||||
foreach (var kv in _live.ToArray())
|
||||
{
|
||||
if (seen.Contains(kv.Key)) continue;
|
||||
if ((now - kv.Value.LastSeenUtc).TotalSeconds >= GoneGraceSec)
|
||||
{
|
||||
dirty |= Finalize(kv.Value, now);
|
||||
_live.Remove(kv.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dirty) Persist();
|
||||
}
|
||||
|
||||
/// <summary>The /runs payload bytes: in-progress runs (ongoing, newest first) then finished runs.</summary>
|
||||
public byte[] BuildJsonBytes()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var runs = new List<RunRecord>(_live.Count + _finished.Count);
|
||||
foreach (LiveRun lr in _live.Values.OrderByDescending(r => r.StartUtc))
|
||||
runs.Add(lr.ToRecord(ongoing: true, endUtc: null, now: DateTimeOffset.UtcNow));
|
||||
runs.AddRange(_finished); // already newest-first
|
||||
|
||||
var payload = new RunsPayload
|
||||
{
|
||||
Host = _host,
|
||||
GeneratedAtUtc = DateTimeOffset.UtcNow,
|
||||
Count = runs.Count,
|
||||
Runs = runs,
|
||||
};
|
||||
return JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.RunsPayload);
|
||||
}
|
||||
}
|
||||
|
||||
// ── internals ───────────────────────────────────────────────────────────
|
||||
|
||||
private static LiveRun NewRun(ClientStatus c, DateTimeOffset now)
|
||||
{
|
||||
// uptimeSec is the AC client's own session length, so now-uptime is the true login time even if the
|
||||
// agent started mid-session. Clamp non-negative for a bogus/zero uptime.
|
||||
var start = now - TimeSpan.FromSeconds(Math.Max(0, c.UptimeSec));
|
||||
var run = new LiveRun
|
||||
{
|
||||
Pid = c.Pid,
|
||||
StartUtc = start,
|
||||
RunId = $"{c.Pid}-{start.ToUnixTimeSeconds()}",
|
||||
};
|
||||
run.Update(c);
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>Append a finished run if it's worth keeping. Returns true if the archive changed.</summary>
|
||||
private bool Finalize(LiveRun run, DateTimeOffset now)
|
||||
{
|
||||
long duration = Math.Max(run.MaxUptimeSec, (long)(now - run.StartUtc).TotalSeconds);
|
||||
if (run.Kills <= 0 && run.Xp <= 0 && duration < MinKeepSec)
|
||||
return false; // brief, fruitless session — not worth archiving
|
||||
|
||||
_finished.Insert(0, run.ToRecord(ongoing: false, endUtc: now, now: now));
|
||||
if (_finished.Count > _maxRuns)
|
||||
_finished.RemoveRange(_maxRuns, _finished.Count - _maxRuns);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Persist()
|
||||
{
|
||||
try
|
||||
{
|
||||
var payload = new RunsPayload
|
||||
{
|
||||
Host = _host,
|
||||
GeneratedAtUtc = DateTimeOffset.UtcNow,
|
||||
Count = _finished.Count,
|
||||
Runs = _finished, // persist finished runs only; ongoing ones rebuild from the live feed
|
||||
};
|
||||
byte[] bytes;
|
||||
lock (_lock) bytes = JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.RunsPayload);
|
||||
|
||||
string? dir = Path.GetDirectoryName(_runsPath);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
string tmp = _runsPath + ".tmp";
|
||||
File.WriteAllBytes(tmp, bytes); // UTF-8, no BOM
|
||||
File.Move(tmp, _runsPath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Debug($"runs.json write failed: {ex.Message}"); }
|
||||
}
|
||||
|
||||
private void LoadFromDisk()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_runsPath)) return;
|
||||
var payload = JsonSerializer.Deserialize(File.ReadAllText(_runsPath), AgentJsonContext.Default.RunsPayload);
|
||||
if (payload?.Runs == null) return;
|
||||
lock (_lock)
|
||||
{
|
||||
_finished.Clear();
|
||||
foreach (RunRecord r in payload.Runs.Where(r => !r.Ongoing).Take(_maxRuns))
|
||||
_finished.Add(r);
|
||||
}
|
||||
AgentLog.Info($"Run archive: loaded {_finished.Count} past run(s) from {_runsPath}.");
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Warn($"runs.json load failed ({ex.GetType().Name}: {ex.Message}); starting empty."); }
|
||||
}
|
||||
|
||||
/// <summary>Mutable in-progress run; the last snapshot wins for each field.</summary>
|
||||
private sealed class LiveRun
|
||||
{
|
||||
public int Pid;
|
||||
public string RunId = "";
|
||||
public DateTimeOffset StartUtc;
|
||||
public DateTimeOffset LastSeenUtc;
|
||||
public long MaxUptimeSec;
|
||||
|
||||
public string Account = "";
|
||||
public string Character = "";
|
||||
public string Server = "";
|
||||
public int Kills;
|
||||
public double KillsPerHour;
|
||||
public double CastsPerKill; // D6: latest offensive casts-per-kill seen this run
|
||||
public long Xp;
|
||||
public double XpPerHour;
|
||||
public double LuminancePerHour;
|
||||
public int Deaths;
|
||||
public double VitaePct;
|
||||
public string Area = "";
|
||||
|
||||
public void Update(ClientStatus c)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(c.Account)) Account = c.Account;
|
||||
if (!string.IsNullOrEmpty(c.Character)) Character = c.Character;
|
||||
if (!string.IsNullOrEmpty(c.Server)) Server = c.Server;
|
||||
if (!string.IsNullOrEmpty(c.Area)) Area = c.Area;
|
||||
// Counters only ever grow within a session; guard against a transient 0 read clobbering the total.
|
||||
if (c.SessionKills > Kills) Kills = c.SessionKills;
|
||||
if (c.XpSession > Xp) Xp = c.XpSession;
|
||||
if (c.DeathsSession > Deaths) Deaths = c.DeathsSession;
|
||||
if (c.KillsPerHour > 0) KillsPerHour = c.KillsPerHour;
|
||||
if (c.CastsPerKill > 0) CastsPerKill = c.CastsPerKill; // latest non-zero; an orphan run trends this up
|
||||
if (c.XpPerHour > 0) XpPerHour = c.XpPerHour;
|
||||
if (c.LuminancePerHour > 0) LuminancePerHour = c.LuminancePerHour;
|
||||
if (c.VitaePct > 0) VitaePct = c.VitaePct;
|
||||
if (c.UptimeSec > MaxUptimeSec) MaxUptimeSec = c.UptimeSec;
|
||||
}
|
||||
|
||||
public RunRecord ToRecord(bool ongoing, DateTimeOffset? endUtc, DateTimeOffset now) => new()
|
||||
{
|
||||
RunId = RunId,
|
||||
Pid = Pid,
|
||||
Account = Account,
|
||||
Character = Character,
|
||||
Server = Server,
|
||||
StartUtc = StartUtc,
|
||||
EndUtc = endUtc,
|
||||
DurationSec = Math.Max(MaxUptimeSec, (long)(now - StartUtc).TotalSeconds),
|
||||
Kills = Kills,
|
||||
KillsPerHour = KillsPerHour,
|
||||
CastsPerKill = CastsPerKill,
|
||||
Xp = Xp,
|
||||
XpPerHour = XpPerHour,
|
||||
LuminancePerHour = LuminancePerHour,
|
||||
Deaths = Deaths,
|
||||
VitaePct = VitaePct,
|
||||
Area = Area,
|
||||
Ongoing = ongoing,
|
||||
};
|
||||
}
|
||||
}
|
||||
33
src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj
Normal file
33
src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
RynthCore.StatusAgent — OPTIONAL, runs on the operator's own PC only.
|
||||
|
||||
Reads the LOCAL per-client status files the engine writes (when the user
|
||||
opts in via EnableStatusExport) and forwards a rolled-up status payload to
|
||||
a USER-CONFIGURED endpoint. It is NOT injected into acclient.exe, NOT part
|
||||
of the installer, and sends nothing until an Endpoint URL is set in
|
||||
%APPDATA%\RynthCore\statusagent.json. Delete this project folder + its .sln
|
||||
entry to remove it entirely.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Platforms>AnyCPU</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>RynthCore.StatusAgent</RootNamespace>
|
||||
<AssemblyName>RynthCore.StatusAgent</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<Version>1.0.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Screen-stream capture (GDI BitBlt + JPEG encode). Windows-only; the agent is net*-windows. -->
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.0" />
|
||||
<!-- WebRTC HD video mode: pure-managed RTCPeerConnection + H.264 RTP packetisation (proven in the spike).
|
||||
10.0.14 is the floor: it fixes GHSA-jwjp-4649-v8jp (SCTP SACK) and GHSA-28gm-jrmw-xx93 (RTP/STUN). -->
|
||||
<PackageReference Include="SIPSorcery" Version="10.0.14" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
214
src/RynthCore.StatusAgent/ScreenCapture.cs
Normal file
214
src/RynthCore.StatusAgent/ScreenCapture.cs
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Captures an AC client window's on-screen rectangle as a JPEG. Out-of-process (GDI BitBlt of the
|
||||
/// composited desktop), so the game/engine is never touched. Only works on a window that's actually
|
||||
/// rendering — a minimized client has no frame. Captures whatever is on top of the window too, so
|
||||
/// docked overlays show; undocked panels (separate windows elsewhere) don't.
|
||||
/// </summary>
|
||||
internal static class ScreenCapture
|
||||
{
|
||||
public enum Result { Ok, NotFound, Minimized, Error }
|
||||
|
||||
private static bool _dpiSet;
|
||||
private static void EnsureDpiAware()
|
||||
{
|
||||
if (_dpiSet) return;
|
||||
_dpiSet = true;
|
||||
try { if (SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)) return; } catch { }
|
||||
try { SetProcessDPIAware(); } catch { }
|
||||
}
|
||||
|
||||
/// <param name="maxWidth">If >0 and wider, downscale to this width (preserve aspect) before encoding.</param>
|
||||
/// Uses PrintWindow(PW_RENDERFULLCONTENT) so it captures the window's OWN content regardless of what's
|
||||
/// on top of it (a foreground app over the client no longer leaks into the frame). Cropped to the
|
||||
/// client area (no title bar). Separate overlay windows (Avalonia panels) are NOT included — by design.
|
||||
public static Result TryCaptureJpeg(int pid, int quality, int maxWidth, out byte[] jpeg)
|
||||
{
|
||||
jpeg = Array.Empty<byte>();
|
||||
EnsureDpiAware();
|
||||
if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized))
|
||||
return minimized ? Result.Minimized : Result.NotFound;
|
||||
try
|
||||
{
|
||||
if (!GetWindowRect(hwnd, out RECT wr)) return Result.Error;
|
||||
int ww = wr.Right - wr.Left, wh = wr.Bottom - wr.Top;
|
||||
if (ww < 8 || wh < 8) return Result.Error;
|
||||
|
||||
using var full = new Bitmap(ww, wh, PixelFormat.Format24bppRgb);
|
||||
bool ok;
|
||||
using (var g = Graphics.FromImage(full))
|
||||
{
|
||||
IntPtr hdc = g.GetHdc();
|
||||
ok = PrintWindow(hwnd, hdc, PW_RENDERFULLCONTENT);
|
||||
g.ReleaseHdc(hdc);
|
||||
}
|
||||
if (!ok) return Result.Error;
|
||||
|
||||
// Crop the title bar / borders away (client area only) for a clean view.
|
||||
Bitmap img = full;
|
||||
Rectangle crop = ClientCrop(hwnd, wr, ww, wh);
|
||||
if (crop.Width >= 8 && crop.Height >= 8 && (crop.Width < ww || crop.Height < wh))
|
||||
img = full.Clone(crop, full.PixelFormat);
|
||||
try
|
||||
{
|
||||
if (maxWidth > 0 && img.Width > maxWidth)
|
||||
{
|
||||
int dw = maxWidth, dh = Math.Max(1, (int)Math.Round(img.Height * (maxWidth / (double)img.Width)));
|
||||
using var scaled = new Bitmap(dw, dh, PixelFormat.Format24bppRgb);
|
||||
using (var g = Graphics.FromImage(scaled))
|
||||
{
|
||||
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
|
||||
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
|
||||
g.DrawImage(img, 0, 0, dw, dh);
|
||||
}
|
||||
jpeg = EncodeJpeg(scaled, quality);
|
||||
}
|
||||
else jpeg = EncodeJpeg(img, quality);
|
||||
}
|
||||
finally { if (!ReferenceEquals(img, full)) img.Dispose(); }
|
||||
return Result.Ok;
|
||||
}
|
||||
catch { return Result.Error; }
|
||||
}
|
||||
|
||||
/// The client-area rectangle within the full-window bitmap (0,0 = window top-left).
|
||||
private static Rectangle ClientCrop(IntPtr hwnd, RECT wr, int ww, int wh)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (GetClientRect(hwnd, out RECT cr))
|
||||
{
|
||||
POINT origin = default;
|
||||
if (ClientToScreen(hwnd, ref origin))
|
||||
{
|
||||
int ox = origin.X - wr.Left, oy = origin.Y - wr.Top;
|
||||
int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top;
|
||||
if (ox >= 0 && oy >= 0 && cw > 0 && ch > 0 && ox + cw <= ww && oy + ch <= wh)
|
||||
return new Rectangle(ox, oy, cw, ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return new Rectangle(0, 0, ww, wh);
|
||||
}
|
||||
|
||||
private static ImageCodecInfo? _jpegEncoder;
|
||||
private static byte[] EncodeJpeg(Bitmap bmp, int quality)
|
||||
{
|
||||
_jpegEncoder ??= Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.FormatID == ImageFormat.Jpeg.Guid)
|
||||
?? throw new InvalidOperationException("no jpeg encoder");
|
||||
using var ep = new EncoderParameters(1);
|
||||
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Clamp(quality, 1, 100));
|
||||
using var ms = new MemoryStream();
|
||||
bmp.Save(ms, _jpegEncoder, ep);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
/// True when the client's game window exists but is minimized (so capture would only get black).
|
||||
public static bool IsClientMinimized(int pid)
|
||||
{
|
||||
EnsureDpiAware();
|
||||
TryFindWindow(pid, out _, out bool minimized);
|
||||
return minimized;
|
||||
}
|
||||
|
||||
/// PostMessage a mouse click to the acclient window at normalized (u,v) of its CLIENT area — the exact
|
||||
/// area the stream captures. acclient reads clicks from window messages (verified in the decompile:
|
||||
/// Device::WndProc dispatches WM_LBUTTONDOWN/etc by lParam, never GetCursorPos), so this drives both the
|
||||
/// 2D UI and 3D-world hit-test WITHOUT moving the real cursor or stealing focus, even when the window is
|
||||
/// backgrounded/occluded — multibox-safe. Returns false if the window is missing or minimized.
|
||||
public static bool TryClick(int pid, double u, double v, string? button)
|
||||
{
|
||||
EnsureDpiAware();
|
||||
if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || minimized || hwnd == IntPtr.Zero) return false;
|
||||
if (!GetClientRect(hwnd, out RECT cr)) return false;
|
||||
int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top;
|
||||
if (cw < 2 || ch < 2) return false;
|
||||
int x = (int)Math.Round(Math.Clamp(u, 0, 1) * (cw - 1));
|
||||
int y = (int)Math.Round(Math.Clamp(v, 0, 1) * (ch - 1));
|
||||
IntPtr lParam = (IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
|
||||
bool right = string.Equals(button, "right", StringComparison.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
|
||||
PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, (IntPtr)(right ? 0x0002 : 0x0001), lParam);
|
||||
System.Threading.Thread.Sleep(80); // brief down→up so AC registers a click, not a drag
|
||||
PostMessage(hwnd, right ? WM_RBUTTONUP : WM_LBUTTONUP, IntPtr.Zero, lParam);
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// Pick the game window for this pid: the largest visible, non-minimized acclient-class window. The
|
||||
/// acclient (D3D9) window is the only one worth capturing — the process's other top-level windows are
|
||||
/// the separate Avalonia overlay panels (excluded by design). Crucially, if the acclient window is
|
||||
/// MINIMIZED we report minimized=true rather than falling back to a non-game window and capturing a
|
||||
/// black frame (the old bug). Falls back to the largest visible window only when the pid has no
|
||||
/// acclient-class window at all (defensive — keeps capture working if the class ever differs).
|
||||
private static bool TryFindWindow(int pid, out IntPtr best, out bool minimized)
|
||||
{
|
||||
IntPtr acWin = IntPtr.Zero; long acArea = 0; // best non-minimized acclient window
|
||||
IntPtr anyWin = IntPtr.Zero; long anyArea = 0; // best non-minimized window of any class (fallback)
|
||||
bool acMinimized = false; // an acclient window exists but is minimized
|
||||
var sb = new StringBuilder(64);
|
||||
EnumWindows((h, l) =>
|
||||
{
|
||||
if (GetWindowThreadProcessId(h, out uint wpid) == 0 || wpid != (uint)pid) return true;
|
||||
if (!IsWindowVisible(h)) return true;
|
||||
sb.Clear();
|
||||
GetClassName(h, sb, sb.Capacity);
|
||||
bool isAc = sb.ToString().IndexOf("acclient", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
if (IsIconic(h)) { if (isAc) acMinimized = true; return true; }
|
||||
if (!GetWindowRect(h, out RECT r)) return true;
|
||||
long area = (long)Math.Max(0, r.Right - r.Left) * Math.Max(0, r.Bottom - r.Top);
|
||||
if (area < 64) return true;
|
||||
if (isAc) { if (area > acArea) { acArea = area; acWin = h; } }
|
||||
else if (area > anyArea) { anyArea = area; anyWin = h; }
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
if (acWin != IntPtr.Zero) { best = acWin; minimized = false; return true; } // got the game window
|
||||
if (acMinimized) { best = IntPtr.Zero; minimized = true; return false; } // game window is minimized
|
||||
best = anyWin; minimized = false; return anyWin != IntPtr.Zero; // no acclient window at all
|
||||
}
|
||||
|
||||
private static bool TryGetBounds(IntPtr hwnd, out int x, out int y, out int w, out int h)
|
||||
{
|
||||
x = y = w = h = 0;
|
||||
// DWM extended frame bounds = the visible rect (excludes the invisible resize border on Win10+).
|
||||
if (DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, out RECT r, Marshal.SizeOf<RECT>()) != 0)
|
||||
{
|
||||
if (!GetWindowRect(hwnd, out r)) return false;
|
||||
}
|
||||
x = r.Left; y = r.Top; w = r.Right - r.Left; h = r.Bottom - r.Top;
|
||||
return w > 0 && h > 0;
|
||||
}
|
||||
|
||||
// ── P/Invoke ────────────────────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
|
||||
[DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint nFlags);
|
||||
private const uint PW_RENDERFULLCONTENT = 0x00000002; // capture D3D/GPU content (Win8.1+)
|
||||
[DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r);
|
||||
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
|
||||
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205;
|
||||
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p);
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
[DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);
|
||||
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
|
||||
[DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hWnd, StringBuilder s, int max);
|
||||
[DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, out RECT r);
|
||||
[DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr hWnd, int attr, out RECT r, int size);
|
||||
private const int DWMWA_EXTENDED_FRAME_BOUNDS = 9;
|
||||
[DllImport("user32.dll")] private static extern bool SetProcessDPIAware();
|
||||
[DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(IntPtr ctx);
|
||||
private static readonly IntPtr DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = new(-4);
|
||||
}
|
||||
294
src/RynthCore.StatusAgent/StatusReader.cs
Normal file
294
src/RynthCore.StatusAgent/StatusReader.cs
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the per-client status list from the engine's local status files
|
||||
/// (rich) and, as a fallback, the per-client heartbeat logs (basic).
|
||||
/// </summary>
|
||||
internal static partial class StatusReader
|
||||
{
|
||||
[GeneratedRegex(@"^RynthCore\.(\d+)\.log$", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex LogNameRegex();
|
||||
|
||||
[GeneratedRegex(@"hb #\d+ up=(\d+)s fps=(-?\d+) plug=(-?\d+)/s ws=(\d+)MB login=(\d+)")]
|
||||
private static partial Regex HeartbeatRegex();
|
||||
|
||||
public static List<ClientStatus> ReadAll(AgentConfig cfg)
|
||||
{
|
||||
var clients = new List<ClientStatus>();
|
||||
var seenPids = new HashSet<int>();
|
||||
|
||||
ReadStatusFiles(cfg, clients, seenPids);
|
||||
|
||||
if (cfg.UseHeartbeatLogFallback)
|
||||
ReadHeartbeatLogs(cfg, clients, seenPids);
|
||||
|
||||
clients.Sort((a, b) => a.Pid.CompareTo(b.Pid));
|
||||
return clients;
|
||||
}
|
||||
|
||||
// ── Rich source: per-client status JSON files ───────────────────────────
|
||||
|
||||
private static void ReadStatusFiles(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids)
|
||||
{
|
||||
string dir = cfg.StatusDirectory;
|
||||
if (!Directory.Exists(dir))
|
||||
return;
|
||||
|
||||
foreach (string path in SafeEnumerate(dir, "RynthCore.*.status.json"))
|
||||
{
|
||||
int pid = ParsePidFromName(Path.GetFileName(path), ".status.json");
|
||||
if (pid <= 0) continue;
|
||||
|
||||
StatusFileModel? model;
|
||||
try
|
||||
{
|
||||
model = JsonSerializer.Deserialize(File.ReadAllText(path), AgentJsonContext.Default.StatusFileModel);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Debug($"status file '{path}' unreadable: {ex.Message}");
|
||||
continue;
|
||||
}
|
||||
if (model == null) continue;
|
||||
|
||||
double ageSec = AgeSeconds(model.Ts, path);
|
||||
bool alive = IsAcClientAlive(pid);
|
||||
|
||||
// Dead client: report it once (so the phone shows the stop), then
|
||||
// retire the stale file so it doesn't linger forever.
|
||||
if (!alive && ageSec > cfg.DropDeadAfterSeconds)
|
||||
{
|
||||
try { File.Delete(path); } catch { }
|
||||
continue;
|
||||
}
|
||||
|
||||
bool stale = alive && ageSec > cfg.StaleAfterSeconds;
|
||||
(string state, bool healthy) = Classify(
|
||||
alive, stale, model.InWorld, model.Fps,
|
||||
hasBot: model.Bot != null,
|
||||
macroRunning: model.Bot?.MacroRunning ?? false,
|
||||
pps: model.PluginTicksPerSec);
|
||||
|
||||
var cs = new ClientStatus
|
||||
{
|
||||
Pid = pid,
|
||||
Host = string.IsNullOrEmpty(model.Host) ? cfg.EffectiveHost : model.Host,
|
||||
Account = model.Account,
|
||||
Character = model.Character,
|
||||
Server = model.Server,
|
||||
State = state,
|
||||
Healthy = healthy,
|
||||
AgeSec = Math.Round(ageSec, 1),
|
||||
Source = "status-file",
|
||||
UptimeSec = model.UptimeSec,
|
||||
Fps = model.Fps,
|
||||
PluginTicksPerSec = model.PluginTicksPerSec,
|
||||
WorkingSetMB = model.WorkingSetMB,
|
||||
InWorld = model.InWorld,
|
||||
QueueDropped = model.QueueDropped,
|
||||
Reconciles = model.Reconciles,
|
||||
ForceClears = model.ForceClears,
|
||||
};
|
||||
|
||||
if (model.Bot is { } bot)
|
||||
{
|
||||
cs.MacroRunning = bot.MacroRunning;
|
||||
cs.CurrentState = bot.CurrentState;
|
||||
cs.BotAction = bot.BotAction;
|
||||
cs.Profile = bot.SelectedProfile;
|
||||
cs.NavProfile = bot.CurrentNavName;
|
||||
cs.LootProfile = bot.CurrentLootName;
|
||||
cs.MetaProfile = bot.CurrentMetaName;
|
||||
cs.Target = bot.TargetLabel;
|
||||
cs.Player = new Vitals
|
||||
{
|
||||
Hp = bot.PlayerHealth, MaxHp = bot.PlayerMaxHealth,
|
||||
St = bot.PlayerStamina, MaxSt = bot.PlayerMaxStamina,
|
||||
Mn = bot.PlayerMana, MaxMn = bot.PlayerMaxMana,
|
||||
};
|
||||
cs.KillsPerHour = bot.KillsPerHour; // bot-derived (kill counter)
|
||||
cs.SessionKills = bot.SessionKills;
|
||||
cs.SecsSinceLastKill = bot.SecsSinceLastKill;
|
||||
cs.FreeSlots = bot.FreeSlots;
|
||||
cs.ScanTotal = bot.ScanTotal; // D2 three-tier target telemetry
|
||||
cs.ScanRing = bot.ScanRing;
|
||||
cs.ScanPossible = bot.ScanPossible;
|
||||
cs.ScanLosBlocked = bot.ScanLosBlocked;
|
||||
cs.SessionAttackCasts = bot.SessionAttackCasts; // D6 attack-cast/kill ratio
|
||||
cs.CastsSinceLastKill = bot.CastsSinceLastKill;
|
||||
cs.CastsPerKill = bot.CastsPerKill;
|
||||
cs.UiHidden = bot.UiHidden;
|
||||
cs.Scarabs = bot.Scarabs;
|
||||
cs.Tapers = bot.Tapers;
|
||||
cs.ScarabsByType = bot.ScarabsByType;
|
||||
cs.Equipment = bot.Equipment;
|
||||
cs.RecentChat = bot.RecentChat;
|
||||
cs.CombatEnabled = bot.CombatEnabled;
|
||||
cs.BuffingEnabled = bot.BuffingEnabled;
|
||||
cs.NavigationEnabled = bot.NavigationEnabled;
|
||||
cs.LootingEnabled = bot.LootingEnabled;
|
||||
cs.MetaEnabled = bot.MetaEnabled;
|
||||
cs.NavProfiles = bot.NavProfiles;
|
||||
cs.LootProfiles = bot.LootProfiles;
|
||||
cs.MetaProfiles = bot.MetaProfiles;
|
||||
cs.SelectedNavIdx = bot.SelectedNavIdx;
|
||||
cs.SelectedLootIdx = bot.SelectedLootIdx;
|
||||
cs.SelectedMetaIdx = bot.SelectedMetaIdx;
|
||||
}
|
||||
// Engine-written player stats live at the top level of the status file, not in bot.
|
||||
cs.Deaths = model.Deaths;
|
||||
cs.DeathsSession = model.DeathsSession;
|
||||
cs.VitaePct = model.VitaePct;
|
||||
cs.XpPerHour = model.XpPerHour;
|
||||
cs.LuminancePerHour = model.LuminancePerHour;
|
||||
cs.XpSession = model.XpSession;
|
||||
cs.BurdenPct = model.BurdenPct;
|
||||
cs.Area = model.Area;
|
||||
cs.Landblock = model.Landblock; cs.Indoor = model.Indoor; // [status-export] live map-dot
|
||||
cs.Wx = model.Wx; cs.Wy = model.Wy; cs.Pz = model.Pz;
|
||||
cs.LastIssue = model.LastIssue;
|
||||
cs.LastIssueAgeSec = model.LastIssueAgeSec;
|
||||
// Window state (for the app to show a "minimized — restore on PC" placeholder instead of a
|
||||
// black stream). A minimized D3D9 window can't be captured by anything; flag it proactively.
|
||||
try { cs.IsMinimized = alive && ScreenCapture.IsClientMinimized(pid); } catch { }
|
||||
|
||||
clients.Add(cs);
|
||||
seenPids.Add(pid);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Basic fallback: tail each per-client heartbeat log ──────────────────
|
||||
|
||||
private static void ReadHeartbeatLogs(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids)
|
||||
{
|
||||
string dir = cfg.LogDirectory;
|
||||
if (!Directory.Exists(dir))
|
||||
return;
|
||||
|
||||
foreach (string path in SafeEnumerate(dir, "RynthCore.*.log"))
|
||||
{
|
||||
Match m = LogNameRegex().Match(Path.GetFileName(path));
|
||||
if (!m.Success) continue;
|
||||
if (!int.TryParse(m.Groups[1].Value, out int pid)) continue;
|
||||
if (seenPids.Contains(pid)) continue; // status file already covered it
|
||||
if (!IsAcClientAlive(pid)) continue; // only living clients via the log path
|
||||
|
||||
string? hb = TailFindHeartbeat(path);
|
||||
if (hb == null) continue;
|
||||
Match h = HeartbeatRegex().Match(hb);
|
||||
if (!h.Success) continue;
|
||||
|
||||
long uptime = ParseLong(h.Groups[1].Value);
|
||||
int fps = ParseInt(h.Groups[2].Value);
|
||||
int pps = ParseInt(h.Groups[3].Value);
|
||||
long ws = ParseLong(h.Groups[4].Value);
|
||||
bool inWorld = h.Groups[5].Value == "1";
|
||||
|
||||
double ageSec = AgeSeconds(default, path); // log mtime
|
||||
bool stale = ageSec > cfg.StaleAfterSeconds;
|
||||
(string state, bool healthy) = Classify(
|
||||
pidAlive: true, stale: stale, inWorld: inWorld, fps: fps,
|
||||
hasBot: false, macroRunning: false, pps: pps);
|
||||
|
||||
clients.Add(new ClientStatus
|
||||
{
|
||||
Pid = pid,
|
||||
Host = cfg.EffectiveHost,
|
||||
State = state,
|
||||
Healthy = healthy,
|
||||
AgeSec = Math.Round(ageSec, 1),
|
||||
Source = "heartbeat-log",
|
||||
UptimeSec = uptime,
|
||||
Fps = fps,
|
||||
PluginTicksPerSec = pps,
|
||||
WorkingSetMB = ws,
|
||||
InWorld = inWorld,
|
||||
});
|
||||
seenPids.Add(pid);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// State machine shared by both sources. "running" = in-world and rendering
|
||||
/// but bot/macro state unknown (heartbeat-log path); the richer status-file
|
||||
/// path resolves further into idle / botting / wedged.
|
||||
/// </summary>
|
||||
public static (string state, bool healthy) Classify(
|
||||
bool pidAlive, bool stale, bool inWorld, int fps, bool hasBot, bool macroRunning, int pps)
|
||||
{
|
||||
if (!pidAlive) return ("dead", false);
|
||||
if (stale) return ("hung", false); // process up but snapshot frozen
|
||||
if (!inWorld) return ("loading", true); // login / char-select
|
||||
if (fps <= 0) return ("hung", false); // render thread dead
|
||||
if (!hasBot) return ("running", true); // in-world, botting unknown
|
||||
if (!macroRunning) return ("idle", true);
|
||||
if (pps <= 0) return ("wedged", false); // macro on but pump stalled
|
||||
return ("botting", true);
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static IEnumerable<string> SafeEnumerate(string dir, string pattern)
|
||||
{
|
||||
try { return Directory.GetFiles(dir, pattern); }
|
||||
catch { return Array.Empty<string>(); }
|
||||
}
|
||||
|
||||
private static int ParsePidFromName(string fileName, string suffix)
|
||||
{
|
||||
// RynthCore.<pid>.status.json
|
||||
if (!fileName.StartsWith("RynthCore.", StringComparison.OrdinalIgnoreCase)) return -1;
|
||||
if (!fileName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) return -1;
|
||||
string mid = fileName.Substring("RynthCore.".Length, fileName.Length - "RynthCore.".Length - suffix.Length);
|
||||
return int.TryParse(mid, out int pid) ? pid : -1;
|
||||
}
|
||||
|
||||
private static double AgeSeconds(DateTimeOffset ts, string path)
|
||||
{
|
||||
if (ts > DateTimeOffset.UnixEpoch)
|
||||
return Math.Max(0, (DateTimeOffset.UtcNow - ts).TotalSeconds);
|
||||
try { return Math.Max(0, (DateTime.UtcNow - File.GetLastWriteTimeUtc(path)).TotalSeconds); }
|
||||
catch { return double.MaxValue; }
|
||||
}
|
||||
|
||||
private static bool IsAcClientAlive(int pid)
|
||||
{
|
||||
try
|
||||
{
|
||||
using Process p = Process.GetProcessById(pid);
|
||||
// Guard against PID reuse: a recycled PID owned by some other process
|
||||
// must not read as a live AC client.
|
||||
return p.ProcessName.Contains("acclient", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch { return false; } // ArgumentException = no such process
|
||||
}
|
||||
|
||||
private static string? TailFindHeartbeat(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
int take = (int)Math.Min(fs.Length, 16 * 1024);
|
||||
fs.Seek(-take, SeekOrigin.End);
|
||||
byte[] buf = new byte[take];
|
||||
int read = fs.Read(buf, 0, take);
|
||||
string tail = Encoding.UTF8.GetString(buf, 0, read);
|
||||
string[] lines = tail.Split('\n');
|
||||
for (int i = lines.Length - 1; i >= 0; i--)
|
||||
{
|
||||
if (lines[i].Contains("hb #", StringComparison.Ordinal))
|
||||
return lines[i];
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int ParseInt(string s) => int.TryParse(s, out int v) ? v : 0;
|
||||
private static long ParseLong(string s) => long.TryParse(s, out long v) ? v : 0;
|
||||
}
|
||||
169
src/RynthCore.StatusAgent/VideoCapture.cs
Normal file
169
src/RynthCore.StatusAgent/VideoCapture.cs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// PrintWindow(PW_RENDERFULLCONTENT) capture of an AC client window as a fixed-size BGR24 frame, for
|
||||
/// piping straight into ffmpeg's rawvideo input. Same occlusion-proof, D3D-capable path ScreenCapture
|
||||
/// uses for the MJPEG feed (gdigrab returns black for the D3D9 client); this variant skips JPEG and
|
||||
/// emits raw bytes for the H.264 encoder. ~15-20fps ceiling (PrintWindow cost) — WGC replaces it later.
|
||||
internal sealed class VideoCapture
|
||||
{
|
||||
public int Width { get; private set; }
|
||||
public int Height { get; private set; }
|
||||
private IntPtr _hwnd;
|
||||
|
||||
/// Resolve the window for a pid and lock in an even, capped target size (h264 needs even dims).
|
||||
public static VideoCapture? Open(int pid, int maxWidth)
|
||||
{
|
||||
EnsureDpiAware();
|
||||
if (!TryFindWindow(pid, out IntPtr hwnd)) return null;
|
||||
if (!GetClientSize(hwnd, out int cw, out int ch) || cw < 16 || ch < 16) return null;
|
||||
|
||||
int w = cw, h = ch;
|
||||
if (maxWidth > 0 && w > maxWidth) { h = (int)Math.Round(h * (maxWidth / (double)w)); w = maxWidth; }
|
||||
w &= ~1; h &= ~1;
|
||||
return new VideoCapture { _hwnd = hwnd, Width = w, Height = h };
|
||||
}
|
||||
|
||||
/// Capture one frame as tightly-packed BGR24 (Width*Height*3 bytes). False if unrenderable this tick.
|
||||
public bool TryGrab(out byte[] bgr)
|
||||
{
|
||||
bgr = Array.Empty<byte>();
|
||||
if (!GetWindowRect(_hwnd, out RECT wr)) return false;
|
||||
int ww = wr.Right - wr.Left, wh = wr.Bottom - wr.Top;
|
||||
if (ww < 8 || wh < 8) return false;
|
||||
try
|
||||
{
|
||||
using var full = new Bitmap(ww, wh, PixelFormat.Format24bppRgb);
|
||||
bool ok;
|
||||
using (var g = Graphics.FromImage(full))
|
||||
{
|
||||
IntPtr hdc = g.GetHdc();
|
||||
ok = PrintWindow(_hwnd, hdc, PW_RENDERFULLCONTENT);
|
||||
g.ReleaseHdc(hdc);
|
||||
}
|
||||
if (!ok) return false;
|
||||
|
||||
Rectangle crop = ClientCrop(_hwnd, wr, ww, wh);
|
||||
using var target = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
|
||||
using (var g = Graphics.FromImage(target))
|
||||
{
|
||||
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
|
||||
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
|
||||
g.DrawImage(full, new Rectangle(0, 0, Width, Height), crop, GraphicsUnit.Pixel);
|
||||
}
|
||||
bgr = PackBgr(target);
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private static byte[] PackBgr(Bitmap bmp)
|
||||
{
|
||||
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
|
||||
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
|
||||
try
|
||||
{
|
||||
int rowBytes = bmp.Width * 3;
|
||||
var outBuf = new byte[rowBytes * bmp.Height];
|
||||
for (int y = 0; y < bmp.Height; y++)
|
||||
Marshal.Copy(data.Scan0 + y * data.Stride, outBuf, y * rowBytes, rowBytes);
|
||||
return outBuf;
|
||||
}
|
||||
finally { bmp.UnlockBits(data); }
|
||||
}
|
||||
|
||||
private static bool GetClientSize(IntPtr hwnd, out int w, out int h)
|
||||
{
|
||||
w = h = 0;
|
||||
if (!GetClientRect(hwnd, out RECT cr)) return false;
|
||||
w = cr.Right - cr.Left; h = cr.Bottom - cr.Top;
|
||||
return w > 0 && h > 0;
|
||||
}
|
||||
|
||||
/// A pid's client area in SCREEN coords + even dims, for ffmpeg ddagrab (GPU Desktop Duplication).
|
||||
/// False if no renderable window. Used by the HD/WebRTC path; the MJPEG path stays on PrintWindow.
|
||||
public static bool TryGetClientScreenRect(int pid, out int x, out int y, out int w, out int h)
|
||||
{
|
||||
x = y = w = h = 0;
|
||||
EnsureDpiAware();
|
||||
if (!TryFindWindow(pid, out IntPtr hwnd)) return false;
|
||||
if (!GetClientRect(hwnd, out RECT cr)) return false;
|
||||
POINT origin = default;
|
||||
if (!ClientToScreen(hwnd, ref origin)) return false;
|
||||
x = origin.X; y = origin.Y;
|
||||
w = (cr.Right - cr.Left) & ~1; h = (cr.Bottom - cr.Top) & ~1;
|
||||
return w >= 16 && h >= 16;
|
||||
}
|
||||
|
||||
private static Rectangle ClientCrop(IntPtr hwnd, RECT wr, int ww, int wh)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (GetClientRect(hwnd, out RECT cr))
|
||||
{
|
||||
POINT origin = default;
|
||||
if (ClientToScreen(hwnd, ref origin))
|
||||
{
|
||||
int ox = origin.X - wr.Left, oy = origin.Y - wr.Top;
|
||||
int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top;
|
||||
if (ox >= 0 && oy >= 0 && cw > 0 && ch > 0 && ox + cw <= ww && oy + ch <= wh)
|
||||
return new Rectangle(ox, oy, cw, ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return new Rectangle(0, 0, ww, wh);
|
||||
}
|
||||
|
||||
private static bool TryFindWindow(int pid, out IntPtr best)
|
||||
{
|
||||
IntPtr found = IntPtr.Zero;
|
||||
long bestScore = 0;
|
||||
var sb = new StringBuilder(64);
|
||||
EnumWindows((h, l) =>
|
||||
{
|
||||
if (GetWindowThreadProcessId(h, out uint wpid) == 0 || wpid != (uint)pid) return true;
|
||||
if (!IsWindowVisible(h) || IsIconic(h)) return true;
|
||||
if (!GetWindowRect(h, out RECT r)) return true;
|
||||
long area = (long)Math.Max(0, r.Right - r.Left) * Math.Max(0, r.Bottom - r.Top);
|
||||
if (area < 64) return true;
|
||||
sb.Clear();
|
||||
GetClassName(h, sb, sb.Capacity);
|
||||
bool isAc = sb.ToString().IndexOf("acclient", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
long score = isAc ? area + 4_000_000_000 : area;
|
||||
if (score > bestScore) { bestScore = score; found = h; }
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
best = found;
|
||||
return found != IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static bool _dpiSet;
|
||||
private static void EnsureDpiAware()
|
||||
{
|
||||
if (_dpiSet) return;
|
||||
_dpiSet = true;
|
||||
try { if (SetProcessDpiAwarenessContext(new IntPtr(-4))) return; } catch { }
|
||||
try { SetProcessDPIAware(); } catch { }
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
|
||||
private const uint PW_RENDERFULLCONTENT = 0x00000002;
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
[DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint nFlags);
|
||||
[DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r);
|
||||
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p);
|
||||
[DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);
|
||||
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
|
||||
[DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hWnd, StringBuilder s, int max);
|
||||
[DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, out RECT r);
|
||||
[DllImport("user32.dll")] private static extern bool SetProcessDPIAware();
|
||||
[DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(IntPtr ctx);
|
||||
}
|
||||
118
src/RynthCore.StatusAgent/VideoSocketService.cs
Normal file
118
src/RynthCore.StatusAgent/VideoSocketService.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
using System.Diagnostics;
|
||||
using System.Net.WebSockets;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// HD video, take 2 — CLIENT-SERVER over a WebSocket (not WebRTC). The app opens ws://<agent>/video?pid=N
|
||||
/// (routes over Tailscale exactly like the MJPEG/status HTTP, so it works REMOTELY with no ICE/NAT/mDNS),
|
||||
/// and the agent streams H.264 which the app decodes natively (VideoToolbox / AVSampleBufferDisplayLayer)
|
||||
/// — no level/profile limits, so true 60fps at native size.
|
||||
///
|
||||
/// Wire format: the raw H.264 Annex-B byte stream (AUD-delimited, SPS/PPS repeated in-band before each
|
||||
/// IDR), forwarded as binary WebSocket messages exactly as ffmpeg emits it. The client reassembles the
|
||||
/// byte stream and does all NAL/AU parsing + AVCC conversion (it needs an Annex-B parser anyway). Keeping
|
||||
/// the agent a dumb pipe avoids fragile server-side NAL rewriting.
|
||||
/// </summary>
|
||||
internal sealed class VideoSocketService
|
||||
{
|
||||
private readonly int _maxWidth, _fps, _bitrateKbps;
|
||||
|
||||
public VideoSocketService(int maxWidth, int fps, int bitrateKbps)
|
||||
{
|
||||
_maxWidth = maxWidth <= 0 ? 0 : Math.Clamp(maxWidth, 320, 3840);
|
||||
_fps = Math.Clamp(fps, 10, 60);
|
||||
_bitrateKbps = Math.Clamp(bitrateKbps, 1000, 40000);
|
||||
}
|
||||
|
||||
/// Stream H.264 to one connected WebSocket client until it closes or the window goes away.
|
||||
/// Capture is PrintWindow(PW_RENDERFULLCONTENT) — occlusion-proof + by-HWND, so it always captures
|
||||
/// THAT client's content regardless of position/z-order (ddagrab grabbed a screen region → the
|
||||
/// desktop when the window wasn't on top). ~15-20fps ceiling; WGC is the future 60fps upgrade.
|
||||
public async Task StreamAsync(WebSocket ws, int pid, CancellationToken ct)
|
||||
{
|
||||
var cap = VideoCapture.Open(pid, _maxWidth);
|
||||
if (cap is null)
|
||||
{
|
||||
AgentLog.Info($"[vsock] pid {pid}: no renderable window");
|
||||
try { await ws.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "no window", ct); } catch { }
|
||||
return;
|
||||
}
|
||||
|
||||
// Short keyframe interval (~0.5s at the real PrintWindow rate) so the client's drop-to-live flush
|
||||
// resyncs almost instantly. Trades a little bitrate for control responsiveness — HD is the Wi-Fi/fps
|
||||
// tier anyway (Saver is the data-saver).
|
||||
int gop = Math.Max(6, _fps / 6);
|
||||
// PrintWindow frames piped in as raw BGR; libx264 (NVENC needs driver 570+). High profile is fine —
|
||||
// VideoToolbox has no level limit. Annex-B (AUD-delimited) on stdout. Low-latency flags: nobuffer +
|
||||
// no input probe (we declare the format) kill input buffering; max_delay 0 + flush_packets 1 stop the
|
||||
// muxer from holding packets, so each frame ships the instant it's encoded.
|
||||
string ffArgs =
|
||||
$"-hide_banner -loglevel error -fflags nobuffer -probesize 32 -analyzeduration 0 " +
|
||||
$"-f rawvideo -pixel_format bgr24 " +
|
||||
$"-video_size {cap.Width}x{cap.Height} -framerate {_fps} -use_wallclock_as_timestamps 1 -i - " +
|
||||
$"-an -pix_fmt yuv420p -c:v libx264 -profile:v high -preset ultrafast -tune zerolatency " +
|
||||
$"-b:v {_bitrateKbps}k -x264-params repeat-headers=1:bframes=0 -g {gop} -bf 0 " +
|
||||
$"-max_delay 0 -flush_packets 1 -bsf:v h264_metadata=aud=insert -f h264 -";
|
||||
|
||||
Process? ff;
|
||||
try { ff = Process.Start(new ProcessStartInfo("ffmpeg", ffArgs)
|
||||
{ RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }); }
|
||||
catch (Exception ex) { AgentLog.Warn($"[vsock] ffmpeg start failed pid {pid}: {ex.Message}"); try { await ws.CloseAsync(WebSocketCloseStatus.InternalServerError, "encode failed", ct); } catch { } return; }
|
||||
if (ff is null) { try { await ws.CloseAsync(WebSocketCloseStatus.InternalServerError, "encode failed", ct); } catch { } return; }
|
||||
ff.ErrorDataReceived += (_, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) AgentLog.Debug($"[vsock ff {pid}] {e.Data}"); };
|
||||
ff.BeginErrorReadLine();
|
||||
AgentLog.Info($"[vsock] pid {pid} PrintWindow {cap.Width}x{cap.Height} @{_fps}fps H264/WebSocket");
|
||||
|
||||
var capTask = Task.Run(() => CapturePump(cap, ff!.StandardInput.BaseStream, ct), ct);
|
||||
try
|
||||
{
|
||||
await PumpAsync(ff.StandardOutput.BaseStream, ws, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Debug($"[vsock] pid {pid} pump ended: {ex.Message}"); }
|
||||
finally
|
||||
{
|
||||
try { ff.Kill(true); } catch { }
|
||||
try { ff.WaitForExit(1500); } catch { }
|
||||
try { ff.Dispose(); } catch { }
|
||||
try { await capTask.ConfigureAwait(false); } catch { }
|
||||
AgentLog.Info($"[vsock] pid {pid} stopped");
|
||||
}
|
||||
}
|
||||
|
||||
// Grab PrintWindow frames at ~_fps and feed tightly-packed BGR24 into ffmpeg's stdin; close stdin on exit.
|
||||
private void CapturePump(VideoCapture cap, Stream ffStdin, CancellationToken ct)
|
||||
{
|
||||
int frameMs = Math.Max(1, 1000 / _fps);
|
||||
var sw = Stopwatch.StartNew();
|
||||
long next = 0;
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
if (cap.TryGrab(out byte[] bgr))
|
||||
{
|
||||
try { ffStdin.Write(bgr, 0, bgr.Length); ffStdin.Flush(); } catch { break; }
|
||||
}
|
||||
next += frameMs;
|
||||
long wait = next - sw.ElapsedMilliseconds;
|
||||
if (wait > 1) Thread.Sleep((int)wait);
|
||||
else if (wait < -200) next = sw.ElapsedMilliseconds;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
try { ffStdin.Close(); } catch { }
|
||||
}
|
||||
|
||||
// Dumb pipe: forward ffmpeg's raw Annex-B stdout to the WebSocket in chunks. The client parses it.
|
||||
private async Task PumpAsync(Stream stdout, WebSocket ws, CancellationToken ct)
|
||||
{
|
||||
var chunk = new byte[32768];
|
||||
int read;
|
||||
while (!ct.IsCancellationRequested && ws.State == WebSocketState.Open &&
|
||||
(read = await stdout.ReadAsync(chunk.AsMemory(0, chunk.Length), ct).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
await ws.SendAsync(chunk.AsMemory(0, read), WebSocketMessageType.Binary, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
316
src/RynthCore.StatusAgent/WebRtcVideoService.cs
Normal file
316
src/RynthCore.StatusAgent/WebRtcVideoService.cs
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
using System.Diagnostics;
|
||||
using SIPSorcery.Net;
|
||||
using SIPSorceryMedia.Abstractions;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// HD video mode: streams an AC client window to the app over WebRTC (H.264). The HD path uses ffmpeg
|
||||
/// ddagrab (GPU Desktop Duplication) on the window's screen region — 60fps-class, captures D3D content,
|
||||
/// best for the foreground "play" window (it's monitor-region capture, so occlusion-prone; the MJPEG
|
||||
/// presets stay on occlusion-proof PrintWindow for background glancing). Out-of-process (the agent),
|
||||
/// so the game is never touched. Opt-in: only constructed when AgentConfig.EnableVideoStream is set.
|
||||
///
|
||||
/// libx264 because the installed NVIDIA driver (560.94) predates ffmpeg's NVENC requirement (570+);
|
||||
/// swapping to h264_nvenc (driver update) or a Media Foundation MFT is a drop-in encoder change later.
|
||||
/// A short GOP gives fast recovery after loss; true on-demand keyframes (PLI) come with NVENC/MF.
|
||||
/// </summary>
|
||||
internal sealed class WebRtcVideoService : IDisposable
|
||||
{
|
||||
private readonly int _maxWidth, _fps, _bitrateKbps;
|
||||
private readonly Dictionary<int, PidSession> _sessions = new();
|
||||
private readonly object _lock = new();
|
||||
private bool _disposed;
|
||||
|
||||
public WebRtcVideoService(int maxWidth, int fps, int bitrateKbps)
|
||||
{
|
||||
_maxWidth = maxWidth <= 0 ? 0 : Math.Clamp(maxWidth, 320, 3840); // 0 = native window size
|
||||
_fps = Math.Clamp(fps, 10, 60);
|
||||
_bitrateKbps = Math.Clamp(bitrateKbps, 1000, 40000);
|
||||
}
|
||||
|
||||
/// Accept a browser's SDP offer for a pid, (lazily) start ddagrab+encode, and return the answer SDP.
|
||||
/// Null = no renderable window for that pid (minimized / wrong pid) or a negotiation failure.
|
||||
public async Task<string?> CreateAnswerAsync(int pid, string offerSdp)
|
||||
{
|
||||
PidSession session;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed) return null;
|
||||
// Replace a torn-down session (last-viewer teardown can race a re-offer); never hand back a dead one.
|
||||
if (!_sessions.TryGetValue(pid, out session!) || session.IsDead)
|
||||
{
|
||||
session?.Dispose();
|
||||
session = new PidSession(pid, _maxWidth, _fps, _bitrateKbps);
|
||||
_sessions[pid] = session;
|
||||
}
|
||||
}
|
||||
if (!await session.EnsureStartedAsync()) { RemoveIfCurrent(pid, session); return null; }
|
||||
return await session.AddPeerAsync(offerSdp, () => RemoveIfCurrent(pid, session));
|
||||
}
|
||||
|
||||
public void Stop(int pid)
|
||||
{
|
||||
PidSession? s;
|
||||
lock (_lock) { _sessions.Remove(pid, out s); }
|
||||
s?.Dispose();
|
||||
}
|
||||
|
||||
// Identity-checked removal: only evict the map entry if it's still THIS session (a newer one may
|
||||
// have replaced it). Prevents deleting a freshly-started session and orphaning its ffmpeg.
|
||||
private void RemoveIfCurrent(int pid, PidSession s)
|
||||
{
|
||||
lock (_lock) { if (_sessions.TryGetValue(pid, out var cur) && ReferenceEquals(cur, s)) _sessions.Remove(pid); }
|
||||
s.Dispose();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
List<PidSession> all;
|
||||
lock (_lock) { _disposed = true; all = _sessions.Values.ToList(); _sessions.Clear(); }
|
||||
foreach (var s in all) s.Dispose();
|
||||
}
|
||||
|
||||
// ── One pid's ddagrab encode + viewers ───────────────────────────────────────────────────────
|
||||
private sealed class PidSession : IDisposable
|
||||
{
|
||||
private readonly int _pid, _maxWidth, _fps, _bitrateKbps;
|
||||
private readonly List<RTCPeerConnection> _peers = new();
|
||||
private readonly object _peerLock = new();
|
||||
private readonly SemaphoreSlim _startGate = new(1, 1);
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly Stopwatch _clock = Stopwatch.StartNew();
|
||||
private Process? _ff;
|
||||
private VideoCapture? _cap;
|
||||
private Action? _onEmpty;
|
||||
private volatile bool _started, _dead;
|
||||
private long _lastSendMs;
|
||||
|
||||
public bool IsDead => _dead;
|
||||
|
||||
public PidSession(int pid, int maxWidth, int fps, int bitrateKbps)
|
||||
{ _pid = pid; _maxWidth = maxWidth; _fps = fps; _bitrateKbps = bitrateKbps; }
|
||||
|
||||
/// Start ddagrab+ffmpeg once. False if no window. Process.Start runs under a per-session gate
|
||||
/// (not the service lock), so a slow spawn never blocks other pids.
|
||||
public async Task<bool> EnsureStartedAsync()
|
||||
{
|
||||
if (_started) return !_dead;
|
||||
await _startGate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_started) return !_dead;
|
||||
if (_dead) return false;
|
||||
if (!StartFfmpegLocked()) return false;
|
||||
_started = true;
|
||||
return true;
|
||||
}
|
||||
finally { _startGate.Release(); }
|
||||
}
|
||||
|
||||
// Start PrintWindow capture -> ffmpeg rawvideo (libx264 Baseline, the config proven to decode on the
|
||||
// user's iPhone Safari). Occlusion-proof + move-proof (capture is by-HWND, not screen region) so no
|
||||
// watcher needed. ddagrab/60fps was a separate experiment that Safari rejected — reverted here.
|
||||
private bool StartFfmpegLocked()
|
||||
{
|
||||
var cap = VideoCapture.Open(_pid, _maxWidth);
|
||||
if (cap is null) return false;
|
||||
int gop = Math.Max(8, _fps / 2);
|
||||
string ffArgs =
|
||||
$"-hide_banner -loglevel error -f rawvideo -pixel_format bgr24 " +
|
||||
$"-video_size {cap.Width}x{cap.Height} -framerate {_fps} -use_wallclock_as_timestamps 1 -i - " +
|
||||
$"-an -pix_fmt yuv420p -c:v libx264 -profile:v baseline -preset ultrafast -tune zerolatency " +
|
||||
$"-b:v {_bitrateKbps}k -x264-params repeat-headers=1:bframes=0 -g {gop} -bf 0 " +
|
||||
$"-bsf:v h264_metadata=aud=insert -f h264 -";
|
||||
|
||||
Process? ff;
|
||||
try { ff = Process.Start(new ProcessStartInfo("ffmpeg", ffArgs)
|
||||
{ RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }); }
|
||||
catch (Exception ex) { AgentLog.Warn($"[video] ffmpeg start failed pid {_pid}: {ex.Message}"); return false; }
|
||||
if (ff is null) return false;
|
||||
|
||||
ff.ErrorDataReceived += (_, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) AgentLog.Debug($"[video ff {_pid}] {e.Data}"); };
|
||||
ff.BeginErrorReadLine();
|
||||
_cap = cap; _ff = ff;
|
||||
AgentLog.Info($"[video] pid {_pid} PrintWindow {cap.Width}x{cap.Height} @{_fps}fps libx264 (Safari-proven)");
|
||||
var stdin = ff.StandardInput.BaseStream;
|
||||
var stdout = ff.StandardOutput.BaseStream;
|
||||
_ = Task.Run(() => CapturePump(cap, stdin, ff));
|
||||
_ = Task.Run(() => ReadAccessUnits(stdout, ff));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Grab PrintWindow frames at ~_fps and feed tightly-packed BGR24 into ffmpeg's stdin. Bound to the
|
||||
// ffmpeg instance that owns this pump so a teardown's pump exits cleanly. Closes stdin on exit (EOF).
|
||||
private void CapturePump(VideoCapture cap, Stream stdin, Process owner)
|
||||
{
|
||||
int frameMs = Math.Max(1, 1000 / _fps);
|
||||
var sw = Stopwatch.StartNew();
|
||||
long next = 0;
|
||||
int fails = 0;
|
||||
try
|
||||
{
|
||||
while (!_dead && ReferenceEquals(_ff, owner))
|
||||
{
|
||||
if (cap.TryGrab(out byte[] bgr))
|
||||
{
|
||||
fails = 0;
|
||||
try { stdin.Write(bgr, 0, bgr.Length); stdin.Flush(); } catch { break; } // ffmpeg gone
|
||||
}
|
||||
else if (++fails > 90) { AgentLog.Info($"[video] pid {_pid} capture failing — retiring"); Retire(); break; }
|
||||
next += frameMs;
|
||||
long wait = next - sw.ElapsedMilliseconds;
|
||||
if (wait > 1) Thread.Sleep((int)wait);
|
||||
else if (wait < -200) next = sw.ElapsedMilliseconds;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
try { stdin.Close(); } catch { }
|
||||
}
|
||||
|
||||
public async Task<string?> AddPeerAsync(string offerSdp, Action onEmpty)
|
||||
{
|
||||
_onEmpty = onEmpty;
|
||||
var pc = new RTCPeerConnection(new RTCConfiguration()); // host candidates only (Tailscale, no TURN)
|
||||
// Level 3.1 (42e01f) = the config Safari is PROVEN to accept (it only decodes up to the level it
|
||||
// offered; answering above → BLACK). 720p30 is exactly Level 3.1's ceiling (3600 MBs * 30).
|
||||
var h264 = new SDPAudioVideoMediaFormat(SDPMediaTypesEnum.video, 96, "H264", 90000, 0,
|
||||
"packetization-mode=1;profile-level-id=42e01f");
|
||||
var track = new MediaStreamTrack(SDPMediaTypesEnum.video, false,
|
||||
new List<SDPAudioVideoMediaFormat> { h264 }, MediaStreamStatusEnum.SendOnly);
|
||||
pc.addTrack(track);
|
||||
pc.onconnectionstatechange += (state) =>
|
||||
{
|
||||
AgentLog.Info($"[video] pid {_pid} pc state: {state}");
|
||||
if (state is RTCPeerConnectionState.failed or RTCPeerConnectionState.closed or RTCPeerConnectionState.disconnected)
|
||||
RemovePeer(pc);
|
||||
};
|
||||
pc.oniceconnectionstatechange += (s) => AgentLog.Info($"[video] pid {_pid} ice: {s}");
|
||||
pc.OnRtcpBye += (_) => RemovePeer(pc);
|
||||
|
||||
try
|
||||
{
|
||||
pc.setRemoteDescription(new RTCSessionDescriptionInit { type = RTCSdpType.offer, sdp = offerSdp });
|
||||
var answer = pc.createAnswer(null);
|
||||
await pc.setLocalDescription(answer);
|
||||
for (int i = 0; i < 20 && pc.iceGatheringState != RTCIceGatheringState.complete; i++)
|
||||
await Task.Delay(50);
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Warn($"[video] negotiate failed pid {_pid}: {ex.Message}"); pc.Close("negotiate failed"); return null; }
|
||||
|
||||
lock (_peerLock) _peers.Add(pc);
|
||||
return pc.localDescription.sdp.ToString();
|
||||
}
|
||||
|
||||
private void RemovePeer(RTCPeerConnection pc)
|
||||
{
|
||||
bool empty;
|
||||
lock (_peerLock) { _peers.Remove(pc); empty = _peers.Count == 0; }
|
||||
try { pc.Close("peer gone"); } catch { }
|
||||
if (empty)
|
||||
{
|
||||
AgentLog.Info($"[video] last viewer left pid {_pid} — stopping ddagrab/encode");
|
||||
Retire();
|
||||
}
|
||||
}
|
||||
|
||||
// Retire = mark dead, stop the watcher + ffmpeg, and ask the service to drop us (identity-checked).
|
||||
private void Retire()
|
||||
{
|
||||
MarkDead();
|
||||
_onEmpty?.Invoke();
|
||||
}
|
||||
|
||||
private void MarkDead()
|
||||
{
|
||||
if (_dead) return;
|
||||
_dead = true;
|
||||
try { _cts.Cancel(); } catch { }
|
||||
StopFfmpeg();
|
||||
}
|
||||
|
||||
// Kill ffmpeg and CONFIRM it died (don't drop the handle on a swallowed Kill — that's how orphans happen).
|
||||
private void StopFfmpeg()
|
||||
{
|
||||
_cap = null;
|
||||
Process? ff = Interlocked.Exchange(ref _ff, null);
|
||||
if (ff is null) return;
|
||||
try { ff.Kill(true); } catch (Exception ex) { AgentLog.Debug($"[video] kill pid {_pid}: {ex.Message}"); }
|
||||
try { ff.WaitForExit(1500); } catch { }
|
||||
try { ff.Dispose(); } catch { }
|
||||
}
|
||||
|
||||
// ffmpeg raw H.264 (AUD-delimited) -> one access unit per SendVideo, wall-clock paced timestamps.
|
||||
// Bound to the ffmpeg instance that produced this stream, so a restart's old pump exits cleanly.
|
||||
private void ReadAccessUnits(Stream stdout, Process owner)
|
||||
{
|
||||
var acc = new List<byte>(1 << 18);
|
||||
var au = new MemoryStream();
|
||||
var chunk = new byte[65536];
|
||||
int read;
|
||||
try
|
||||
{
|
||||
while (!_dead && ReferenceEquals(_ff, owner) && (read = stdout.Read(chunk, 0, chunk.Length)) > 0)
|
||||
{
|
||||
for (int i = 0; i < read; i++) acc.Add(chunk[i]);
|
||||
var starts = FindStartCodes(acc);
|
||||
if (starts.Count < 2) continue;
|
||||
int last = starts.Count - 1;
|
||||
for (int k = 0; k < last; k++) EmitNal(acc, starts[k], starts[k + 1], au);
|
||||
acc.RemoveRange(0, starts[last]);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
if (ReferenceEquals(_ff, owner)) FlushAu(au);
|
||||
}
|
||||
|
||||
private static List<int> FindStartCodes(List<byte> a)
|
||||
{
|
||||
var idx = new List<int>();
|
||||
for (int i = 0; i + 2 < a.Count; i++)
|
||||
if (a[i] == 0 && a[i + 1] == 0 && a[i + 2] == 1) { idx.Add(i > 0 && a[i - 1] == 0 ? i - 1 : i); i += 2; }
|
||||
return idx;
|
||||
}
|
||||
|
||||
private void EmitNal(List<byte> acc, int from, int to, MemoryStream au)
|
||||
{
|
||||
int p = from;
|
||||
while (p + 2 < to && !(acc[p] == 0 && acc[p + 1] == 0 && acc[p + 2] == 1)) p++;
|
||||
int hdr = p + 3;
|
||||
if (hdr >= to) return;
|
||||
int type = acc[hdr] & 0x1F;
|
||||
if (type == 9 && au.Length > 0) FlushAu(au);
|
||||
for (int i = from; i < to; i++) au.WriteByte(acc[i]);
|
||||
}
|
||||
|
||||
private void FlushAu(MemoryStream au)
|
||||
{
|
||||
if (au.Length == 0) return;
|
||||
byte[] sample = au.ToArray();
|
||||
au.SetLength(0);
|
||||
|
||||
long now = _clock.ElapsedMilliseconds;
|
||||
uint dur = _lastSendMs == 0 ? (uint)(90000 / _fps)
|
||||
: (uint)Math.Clamp((now - _lastSendMs) * 90, 900, 90000);
|
||||
_lastSendMs = now;
|
||||
|
||||
List<RTCPeerConnection> snapshot;
|
||||
lock (_peerLock) snapshot = new List<RTCPeerConnection>(_peers);
|
||||
foreach (var pc in snapshot)
|
||||
{
|
||||
if (pc.connectionState != RTCPeerConnectionState.connected) continue;
|
||||
try { pc.SendVideo(dur, sample); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
List<RTCPeerConnection> peers;
|
||||
lock (_peerLock) { peers = _peers.ToList(); _peers.Clear(); }
|
||||
foreach (var pc in peers) { try { pc.Close("session disposed"); } catch { } }
|
||||
MarkDead();
|
||||
try { _startGate.Dispose(); } catch { }
|
||||
try { _cts.Dispose(); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue