RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -196,4 +196,6 @@ public enum AcSkillType
Salvaging, Run, Jump, Loyalty, Leadership, Deception,
Healing, Lockpick, Cooking, Fletching, Alchemy, ManaConversion,
AssessCreature, AssessPerson, Summoning,
// Appended, not inserted: the members above keep their values.
MissileWeapons,
}

View file

@ -0,0 +1,636 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using RynthCore.Loot.VTank;
namespace RynthCore.Loot.Editing;
/// <summary>
/// One open loot profile being edited (RynthCore docs/IMGUI_LOOT_EDITOR.md):
/// load, edit commands, validation and a save that never clobbers a file that
/// changed on disk. Pure data and file I/O, no plugin or AC types, so it runs
/// in RynthAi and in the offline tests alike. Not thread-safe: the caller
/// serialises calls (RynthAi's bridge holds a lock).
///
/// .utl files are edited in the VTank model, which keeps every line it parsed,
/// and written back in the file's own encoding, line endings and BOM, so an
/// unedited profile saves byte-identical. A file the model can't reproduce
/// exactly opens read-only, as do .json profiles (their only writer is lossy).
/// </summary>
public sealed class LootEditSession
{
private VTankLootProfile? _utl;
private LootProfile? _json;
private string _path = string.Empty;
private FileStamp _stamp;
private Encoding _encoding = new UTF8Encoding(false);
private bool _bom, _crlf, _finalNewline = true;
private bool _dirty, _changedOnDisk;
private string _readOnlyReason = string.Empty;
private string _message = string.Empty;
private bool _messageOk = true;
private long _messageSeq;
private int _focus = -1;
/// <summary>Bumped on every change a face could show.</summary>
public long Revision { get; private set; } = 1;
public string Path => _path;
public bool IsOpen => _path.Length > 0;
public bool IsDirty => _dirty;
public bool IsReadOnly => _utl == null;
public int RuleCount => Shown?.Rules.Count ?? _json?.Rules.Count ?? 0;
/// <summary>The edited model (null for JSON / nothing open). Tests read it.</summary>
public VTankLootProfile? Profile => _utl;
// =====================================================================
// Load
// =====================================================================
/// <summary>
/// Opens <paramref name="path"/>: a .utl or .json file, or a .utl path that
/// doesn't exist yet (a new, empty profile that Save creates). Unsaved edits
/// block it unless <paramref name="force"/>. False (with a message) on failure.
/// </summary>
public bool Open(string path, bool force = false)
{
path = (path ?? string.Empty).Trim().Trim('"');
if (path.Length == 0) return Fail("No loot profile selected.");
if (_dirty && !force) return Fail($"Unsaved changes in {FileName(_path)}. Save them or discard them first.");
try { path = System.IO.Path.GetFullPath(path); }
catch (Exception ex) { return Fail($"Bad path {path}: {ex.Message}"); }
bool json = path.EndsWith(".json", StringComparison.OrdinalIgnoreCase);
if (!json && !path.EndsWith(".utl", StringComparison.OrdinalIgnoreCase))
return Fail($"{FileName(path)}: not a .utl or .json loot profile.");
try
{
if (!File.Exists(path))
{
if (json) return Fail($"{FileName(path)} not found.");
SetLoaded(path, new VTankLootProfile { FileVersion = 1 }, null, default, readOnlyReason: string.Empty);
return Ok($"New profile. Save creates {FileName(path)}.");
}
byte[] bytes = File.ReadAllBytes(path);
FileStamp stamp = FileStamp.Of(path, bytes);
if (json)
{
LootProfile? jp = System.Text.Json.JsonSerializer.Deserialize(Decode(bytes, out _, out _), LootJsonContext.Default.LootProfile);
SetLoaded(path, null, jp ?? new LootProfile(), stamp,
"JSON profiles are read-only here (saving JSON loses conditions). Use the external editor.");
return Ok($"Opened {FileName(path)} ({RuleCount} rules), read-only.");
}
string text = Decode(bytes, out Encoding encoding, out bool bom);
VTankLootProfile profile = VTankLootParser.LoadFromText(text);
bool finalNewline = text.Length == 0 || text.EndsWith('\n');
string reason = RoundTrips(text, profile, finalNewline) ? string.Empty
: "This file has lines the editor would not write back the same way; it is read-only here so nothing is lost. Use the external editor.";
SetLoaded(path, profile, null, stamp, reason);
_encoding = encoding;
_bom = bom;
_crlf = text.Contains("\r\n", StringComparison.Ordinal);
_finalNewline = finalNewline;
return Ok(reason.Length == 0 ? $"Opened {FileName(path)} ({RuleCount} rules)." : $"Opened {FileName(path)} ({RuleCount} rules), read-only.");
}
catch (Exception ex)
{
return Fail($"Could not open {FileName(path)}: {ex.Message}");
}
}
private void SetLoaded(string path, VTankLootProfile? utl, LootProfile? json, FileStamp stamp, string readOnlyReason)
{
_path = path;
_utl = readOnlyReason.Length == 0 ? utl : null;
_json = json;
_readOnlyUtl = readOnlyReason.Length == 0 ? null : utl;
_stamp = stamp;
_encoding = new UTF8Encoding(false);
_bom = false;
_crlf = false;
_finalNewline = true;
_dirty = false;
_changedOnDisk = false;
_readOnlyReason = readOnlyReason;
_focus = -1;
Revision++;
}
// A .utl opened read-only (it doesn't round-trip): shown, never saved.
private VTankLootProfile? _readOnlyUtl;
private VTankLootProfile? Shown => _utl ?? _readOnlyUtl;
/// <summary>
/// True when writing the parsed profile gives the file's text back exactly,
/// CRLF and a missing final newline aside (Encode restores both).
/// </summary>
private static bool RoundTrips(string text, VTankLootProfile profile, bool finalNewline)
{
string a = Norm(text);
if (!finalNewline) a += "\n";
return string.Equals(a, Norm(VTankLootWriter.Serialize(profile)), StringComparison.Ordinal);
}
private static string Norm(string s) => s.Replace("\r\n", "\n");
/// <summary>UTF-8 when the bytes are valid UTF-8 (BOM noted), else Latin-1, which maps every byte to one char and back.</summary>
internal static string Decode(byte[] bytes, out Encoding encoding, out bool bom)
{
bom = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF;
int start = bom ? 3 : 0;
try
{
string s = new UTF8Encoding(false, true).GetString(bytes, start, bytes.Length - start);
encoding = new UTF8Encoding(false);
return s;
}
catch (DecoderFallbackException)
{
bom = false;
encoding = Encoding.Latin1;
return Encoding.Latin1.GetString(bytes);
}
}
// =====================================================================
// Disk watch
// =====================================================================
/// <summary>
/// Looks at the file on disk (a stat, no read). Changed with no unsaved edits:
/// reload it. Changed under unsaved edits: flag it (Save then needs Force).
/// Returns true when anything changed. Call now and then (every couple of seconds).
/// </summary>
public bool CheckDisk()
{
if (!IsOpen || _changedOnDisk) return false;
FileStamp now;
try { now = FileStamp.Stat(_path); }
catch { return false; }
if (now.SameStat(_stamp)) return false;
if (!_dirty)
{
if (!now.Exists) return false; // deleted under a clean view: keep showing it; Save recreates
string path = _path;
Open(path, force: true);
SetMessage($"{FileName(path)} changed on disk; reloaded ({RuleCount} rules).", ok: true);
return true;
}
_changedOnDisk = true;
SetMessage($"{FileName(_path)} changed on disk since you opened it. Reload (drops your edits) or Save anyway.", ok: false);
return true;
}
// =====================================================================
// Commands
// =====================================================================
/// <summary>What a command did, for the bridge (Saved: hot-reload RynthAi).</summary>
public enum Outcome { Refused, Changed, Saved, Opened }
/// <summary>
/// Applies one command. open and save take the path/flags in the command;
/// the caller resolves an empty open path first. Every call sets the message.
/// </summary>
public Outcome Apply(LootEditCommand cmd)
{
switch (cmd.Op)
{
case "open":
return Open(cmd.Path, cmd.Force) ? Outcome.Opened : Outcome.Refused;
case "reload":
if (!IsOpen) { Fail("No profile open."); return Outcome.Refused; }
return Open(_path, cmd.Force) ? Outcome.Opened : Outcome.Refused;
case "save":
return Save(cmd.Force) ? Outcome.Saved : Outcome.Refused;
}
if (_utl == null)
{
Fail(IsOpen ? _readOnlyReason : "No profile open.");
return Outcome.Refused;
}
List<VTankLootRule> rules = _utl.Rules;
if (cmd.Op == "add")
{
int at = cmd.Index < 0 || cmd.Index >= rules.Count ? rules.Count : cmd.Index + 1;
rules.Insert(at, NewRule("New Rule"));
return Changed($"Added a rule at {at + 1}.", at);
}
if (cmd.Index < 0 || cmd.Index >= rules.Count)
{
Fail("That rule is no longer there. The list has been refreshed.");
return Outcome.Refused;
}
VTankLootRule rule = rules[cmd.Index];
if (cmd.Expect != null && !string.Equals(cmd.Expect, rule.Name, StringComparison.Ordinal))
{
Fail("The list changed under that edit; it was not applied. Try again.");
return Outcome.Refused;
}
switch (cmd.Op)
{
case "set_enabled":
{
bool on = string.Equals(cmd.Value, "true", StringComparison.OrdinalIgnoreCase);
if (rule.Enabled == on) return Changed(string.Empty, cmd.Index, quiet: true);
SetEnabled(rule, on);
return Changed($"{(on ? "Enabled" : "Disabled")} \"{rule.Name}\".", cmd.Index);
}
case "move":
{
int to = Math.Clamp(cmd.To, 0, rules.Count - 1);
if (to == cmd.Index) return Changed(string.Empty, to, quiet: true);
rules.RemoveAt(cmd.Index);
rules.Insert(to, rule);
return Changed($"Moved \"{rule.Name}\" to {to + 1}.", to);
}
case "duplicate":
{
VTankLootRule copy = CloneRule(rule);
copy.Name = rule.Name + " (copy)";
rules.Insert(cmd.Index + 1, copy);
return Changed($"Duplicated \"{rule.Name}\".", cmd.Index + 1);
}
case "delete":
rules.RemoveAt(cmd.Index);
return Changed($"Deleted \"{rule.Name}\".", Math.Min(cmd.Index, rules.Count - 1));
case "rename":
{
// Kept as typed (no trim): real profiles have unnamed rules and trailing spaces.
string name = OneLine(cmd.Value);
rule.Name = name;
return Changed($"Renamed to \"{name}\".", cmd.Index);
}
case "update_rule":
{
if (cmd.Rule == null) { Fail("No rule in the update."); return Outcome.Refused; }
string? error = ApplyRule(rule, cmd.Rule);
if (error != null) { Fail(error); return Outcome.Refused; }
return Changed($"Updated \"{rule.Name}\" (not saved yet).", cmd.Index);
}
}
Fail($"Unknown loot edit command '{cmd.Op}'.");
return Outcome.Refused;
}
private VTankLootRule NewRule(string name) => new()
{
Name = name,
CustomExpression = _utl != null && _utl.FileVersion >= 1 ? string.Empty : null,
Action = VTankLootAction.Keep,
};
private static VTankLootRule CloneRule(VTankLootRule src)
{
var copy = new VTankLootRule
{
Name = src.Name, CustomExpression = src.CustomExpression, Priority = src.Priority,
Action = src.Action, KeepCount = src.KeepCount,
};
foreach (VTankLootCondition c in src.Conditions)
copy.Conditions.Add(new VTankLootCondition(c.NodeType, c.LengthCode, c.DataLines));
return copy;
}
/// <summary>
/// Disabling sets an existing DisabledRule node to "true" where it is (else
/// appends one); enabling removes them, as the SDK and VTank do.
/// </summary>
public static void SetEnabled(VTankLootRule rule, bool enabled)
{
if (enabled)
{
rule.Enabled = true;
return;
}
foreach (VTankLootCondition c in rule.Conditions)
if (c.NodeType == VTankNodeTypes.DisabledRule)
{
if (c.DataLines.Count == 0) c.DataLines.Add("true");
else c.DataLines[0] = "true";
return;
}
rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.DisabledRule, "0", new[] { "true" }));
}
/// <summary>Replaces <paramref name="rule"/> with <paramref name="dto"/> after checking it. Null, or what is wrong.</summary>
private string? ApplyRule(VTankLootRule rule, LootEditRule dto)
{
string name = OneLine(dto.Name); // unnamed rules are common (LootSnobV4 has 152)
if (!LootRuleText.IsKnownAction(dto.Action)) return $"Unknown action {dto.Action}.";
var action = (VTankLootAction)dto.Action;
if (action == VTankLootAction.KeepUpTo && dto.KeepCount < 0) return "Keep # needs a count of 0 or more.";
var conditions = new List<VTankLootCondition>(dto.Conditions.Count);
for (int i = 0; i < dto.Conditions.Count; i++)
{
LootEditCondition c = dto.Conditions[i];
var lines = new List<string>(c.Lines.Count);
foreach (string line in c.Lines) lines.Add(OneLine(line));
int arity = VTankNodeTypes.GetDataLineCount(c.NodeType);
bool unchanged = HasSame(rule, c.NodeType, lines);
if (arity < 0 && !unchanged)
return $"Condition {i + 1}: unknown node type {c.NodeType}.";
if (arity >= 0 && lines.Count != arity)
{
if (lines.Count > arity) return $"Condition {i + 1} ({LootRuleText.NodeName(c.NodeType)}) has {lines.Count} lines; it takes {arity}.";
List<string> defaults = LootRuleText.DefaultLines(c.NodeType);
while (lines.Count < arity) lines.Add(defaults[lines.Count]);
}
if (!unchanged && LootRuleText.EditorFor(c.NodeType).Editor != "raw")
{
string? bad = CheckNumbers(c.NodeType, lines);
if (bad != null) return $"Condition {i + 1} ({LootRuleText.NodeName(c.NodeType)}): {bad}";
}
conditions.Add(new VTankLootCondition(c.NodeType, OneLine(c.LengthCode ?? "0"), lines));
}
rule.Name = name;
rule.Action = action;
rule.KeepCount = action == VTankLootAction.KeepUpTo ? dto.KeepCount : null;
rule.Priority = dto.Priority;
if (rule.CustomExpression != null || _utl!.FileVersion >= 1)
rule.CustomExpression = OneLine(dto.CustomExpression ?? string.Empty);
rule.Conditions = conditions;
if (rule.Enabled != dto.Enabled) SetEnabled(rule, dto.Enabled);
return null;
}
private static bool HasSame(VTankLootRule rule, int nodeType, List<string> lines)
{
foreach (VTankLootCondition c in rule.Conditions)
{
if (c.NodeType != nodeType || c.DataLines.Count != lines.Count) continue;
bool same = true;
for (int i = 0; i < lines.Count && same; i++) same = string.Equals(c.DataLines[i], lines[i], StringComparison.Ordinal);
if (same) return true;
}
return false;
}
private static string? CheckNumbers(int type, List<string> lines)
{
string[] labels = LootRuleText.LineLabels(type);
for (int i = 0; i < lines.Count; i++)
{
if (LootRuleText.IsTextLine(type, i)) continue;
string v = lines[i].Trim();
string label = i < labels.Length ? labels[i] : $"line {i + 1}";
if (LootRuleText.IsIntLine(type, i))
{
if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) return $"{label} must be a whole number (got \"{v}\").";
}
else if (!double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out _))
return $"{label} must be a number (got \"{v}\").";
lines[i] = v;
}
return null;
}
/// <summary>Newlines would break the line-based file: they become spaces.</summary>
private static string OneLine(string? s) =>
string.IsNullOrEmpty(s) ? string.Empty : s.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
// =====================================================================
// Save
// =====================================================================
/// <summary>
/// Writes the profile: refuses when the file changed on disk since it was
/// loaded (unless <paramref name="force"/>), writes a temp file and swaps it
/// in (the old file kept as .bak).
/// </summary>
public bool Save(bool force = false)
{
if (!IsOpen) return Fail("No profile open.");
if (_utl == null) return Fail(_readOnlyReason);
try
{
FileStamp now = FileStamp.Read(_path);
if (!force && !now.SameContent(_stamp))
{
_changedOnDisk = true;
return Fail($"{FileName(_path)} changed on disk since you opened it. Reload (drops your edits) or Save anyway.");
}
byte[] bytes = Encode();
string? dir = System.IO.Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = _path + ".tmp";
File.WriteAllBytes(tmp, bytes);
if (File.Exists(_path))
{
try { File.Replace(tmp, _path, _path + ".bak", ignoreMetadataErrors: true); }
catch (PlatformNotSupportedException) { File.Copy(tmp, _path, overwrite: true); File.Delete(tmp); }
catch (IOException) { File.Copy(_path, _path + ".bak", overwrite: true); File.Copy(tmp, _path, overwrite: true); File.Delete(tmp); }
}
else File.Move(tmp, _path);
_stamp = FileStamp.Read(_path);
_dirty = false;
_changedOnDisk = false;
return Ok($"Saved {FileName(_path)} ({RuleCount} rules).");
}
catch (Exception ex)
{
return Fail($"Save failed: {ex.Message}");
}
}
/// <summary>The file's bytes as Save writes them (its own encoding, line endings, BOM).</summary>
public byte[] Encode()
{
if (_utl == null) return Array.Empty<byte>();
string text = VTankLootWriter.Serialize(_utl);
if (!_finalNewline && text.EndsWith('\n')) text = text.Substring(0, text.Length - 1);
if (_crlf) text = text.Replace("\n", "\r\n");
byte[] body = _encoding.GetBytes(text);
if (!_bom) return body;
byte[] withBom = new byte[body.Length + 3];
withBom[0] = 0xEF; withBom[1] = 0xBB; withBom[2] = 0xBF;
Array.Copy(body, 0, withBom, 3, body.Length);
return withBom;
}
// =====================================================================
// What the face sees
// =====================================================================
/// <summary>The header and one row per rule. <paramref name="inUsePath"/>: RynthAi's loot profile.</summary>
public LootEditState BuildState(string inUsePath, List<LootEditFile>? files)
{
var s = new LootEditState
{
Revision = Revision,
Path = _path,
FileName = FileName(_path),
Format = !IsOpen ? string.Empty : _json != null ? "json" : "utl",
Exists = _stamp.Exists,
ReadOnly = IsOpen && _utl == null,
ReadOnlyReason = _readOnlyReason,
Dirty = _dirty,
ChangedOnDisk = _changedOnDisk,
InUsePath = inUsePath ?? string.Empty,
InUse = IsOpen && SamePath(_path, inUsePath),
Message = _message,
MessageOk = _messageOk,
MessageSeq = _messageSeq,
Focus = _focus,
};
if (files != null) s.Files = files;
if (Shown is VTankLootProfile p)
{
s.Rules.Capacity = p.Rules.Count;
foreach (VTankLootRule r in p.Rules)
s.Rules.Add(new LootEditRow
{
Name = r.Name, Enabled = r.Enabled, Action = (int)r.Action, KeepCount = r.KeepCount ?? 0,
Summary = LootRuleText.Summary(r), Conditions = CountConditions(r),
});
}
else if (_json != null)
{
foreach (LootRule r in _json.Rules)
s.Rules.Add(new LootEditRow
{
Name = r.Name, Enabled = r.Enabled, Action = (int)JsonAction(r.Action), KeepCount = r.KeepCount,
Summary = r.Conditions.Count == 0 ? "Matches every item" : string.Join(" AND ", r.Conditions),
Conditions = r.Conditions.Count,
});
}
return s;
}
private static int CountConditions(VTankLootRule r)
{
int n = 0;
foreach (VTankLootCondition c in r.Conditions) if (c.NodeType != VTankNodeTypes.DisabledRule) n++;
return n;
}
/// <summary>The whole rule at <paramref name="index"/>, or null.</summary>
public LootEditRule? BuildRule(int index)
{
if (Shown is VTankLootProfile p)
{
if (index < 0 || index >= p.Rules.Count) return null;
VTankLootRule r = p.Rules[index];
var dto = new LootEditRule
{
Index = index, Name = r.Name, Enabled = r.Enabled, Action = (int)r.Action, KeepCount = r.KeepCount ?? 0,
Priority = r.Priority, CustomExpression = r.CustomExpression,
};
foreach (VTankLootCondition c in r.Conditions)
dto.Conditions.Add(new LootEditCondition { NodeType = c.NodeType, LengthCode = c.LengthCode, Lines = new List<string>(c.DataLines) });
return dto;
}
if (_json != null && index >= 0 && index < _json.Rules.Count)
{
LootRule r = _json.Rules[index];
var dto = new LootEditRule
{
Index = index, Name = r.Name, Enabled = r.Enabled, Action = (int)JsonAction(r.Action), KeepCount = r.KeepCount,
};
foreach (LootCondition c in r.Conditions)
dto.Conditions.Add(new LootEditCondition { NodeType = -1, Lines = new List<string> { c.ToString() ?? string.Empty } });
return dto;
}
return null;
}
private static VTankLootAction JsonAction(LootAction a) => a switch
{
LootAction.Sell => VTankLootAction.Sell,
LootAction.Salvage => VTankLootAction.Salvage,
LootAction.Read => VTankLootAction.Read,
LootAction.KeepUpTo => VTankLootAction.KeepUpTo,
_ => VTankLootAction.Keep,
};
// =====================================================================
// Helpers
// =====================================================================
public static bool SamePath(string? a, string? b)
{
if (string.IsNullOrWhiteSpace(a) || string.IsNullOrWhiteSpace(b)) return false;
try { return string.Equals(System.IO.Path.GetFullPath(a.Trim().Trim('"')), System.IO.Path.GetFullPath(b.Trim().Trim('"')), StringComparison.OrdinalIgnoreCase); }
catch { return false; }
}
private static string FileName(string path) => path.Length == 0 ? string.Empty : System.IO.Path.GetFileName(path);
private Outcome Changed(string message, int focus, bool quiet = false)
{
if (!quiet)
{
_dirty = true;
_focus = focus;
SetMessage(message, ok: true);
}
return quiet ? Outcome.Refused : Outcome.Changed;
}
private bool Ok(string message)
{
SetMessage(message, ok: true);
return true;
}
private bool Fail(string message)
{
SetMessage(message, ok: false);
return false;
}
private void SetMessage(string message, bool ok)
{
_message = message;
_messageOk = ok;
_messageSeq++;
Revision++;
}
/// <summary>What we know of the file: size and write time (a stat), plus a content hash when read.</summary>
private readonly record struct FileStamp(bool Exists, long Length, DateTime WriteUtc, ulong Hash)
{
public static FileStamp Stat(string path)
{
var fi = new FileInfo(path);
return fi.Exists ? new FileStamp(true, fi.Length, fi.LastWriteTimeUtc, 0) : default;
}
public static FileStamp Read(string path)
{
if (!File.Exists(path)) return default;
return Of(path, File.ReadAllBytes(path));
}
public static FileStamp Of(string path, byte[] bytes)
{
var fi = new FileInfo(path);
return new FileStamp(true, bytes.Length, fi.LastWriteTimeUtc, Fnv(bytes));
}
public bool SameStat(FileStamp other) => Exists == other.Exists && (!Exists || (Length == other.Length && WriteUtc == other.WriteUtc));
public bool SameContent(FileStamp other) => Exists == other.Exists && (!Exists || (Length == other.Length && Hash == other.Hash));
private static ulong Fnv(byte[] bytes)
{
ulong h = 14695981039346656037UL;
foreach (byte b in bytes) { h ^= b; h *= 1099511628211UL; }
return h;
}
}
}

View file

@ -0,0 +1,169 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace RynthCore.Loot.Editing;
// The JSON contract between RynthAi's loot edit bridge and the engine's ImGui
// Loot Editor face (RynthCore docs/IMGUI_LOOT_EDITOR.md). The engine mirrors
// these types in UI\Data\LootEditData.cs; keep the two in step. Strings cross
// the export boundary as UTF-8.
/// <summary>The open profile: header, the rule list (one row per rule) and the last command's result.</summary>
public sealed class LootEditState
{
/// <summary>Changes whenever anything below changes.</summary>
public long Revision { get; set; }
/// <summary>Full path of the open profile; empty when none is open.</summary>
public string Path { get; set; } = string.Empty;
public string FileName { get; set; } = string.Empty;
/// <summary>"utl", "json", or empty.</summary>
public string Format { get; set; } = string.Empty;
/// <summary>False for a new profile that Save will create.</summary>
public bool Exists { get; set; }
public bool ReadOnly { get; set; }
public string ReadOnlyReason { get; set; } = string.Empty;
public bool Dirty { get; set; }
/// <summary>The file changed on disk while there were unsaved edits: Save refuses unless forced.</summary>
public bool ChangedOnDisk { get; set; }
/// <summary>RynthAi's loot profile (what looting uses now).</summary>
public string InUsePath { get; set; } = string.Empty;
public bool InUse { get; set; }
/// <summary>Result of the last command (or load); MessageSeq counts them.</summary>
public string Message { get; set; } = string.Empty;
public bool MessageOk { get; set; } = true;
public long MessageSeq { get; set; }
/// <summary>The rule the last command made or moved (to select it), or -1.</summary>
public int Focus { get; set; } = -1;
/// <summary>Profiles in the loot folder, for the picker.</summary>
public List<LootEditFile> Files { get; set; } = new();
public List<LootEditRow> Rules { get; set; } = new();
}
public sealed class LootEditFile
{
public string Path { get; set; } = string.Empty;
public string Display { get; set; } = string.Empty;
}
/// <summary>One rule in the list.</summary>
public sealed class LootEditRow
{
public string Name { get; set; } = string.Empty;
public bool Enabled { get; set; } = true;
/// <summary>VTank action code: 1 Keep, 2 Salvage, 3 Sell, 4 Read, 10 Keep #.</summary>
public int Action { get; set; }
public int KeepCount { get; set; }
/// <summary>Conditions in words (ASCII), shortened.</summary>
public string Summary { get; set; } = string.Empty;
public int Conditions { get; set; }
}
/// <summary>A whole rule: what the rule view edits and sends back with "update_rule".</summary>
public sealed class LootEditRule
{
public int Index { get; set; } = -1;
public string Name { get; set; } = string.Empty;
public bool Enabled { get; set; } = true;
public int Action { get; set; } = 1;
public int KeepCount { get; set; }
/// <summary>Passed through untouched (Phase 1 does not edit these).</summary>
public int Priority { get; set; }
/// <summary>Null for v0 files, which have no custom expression line.</summary>
public string? CustomExpression { get; set; }
/// <summary>Every condition node in file order, DisabledRule (9999) nodes included.</summary>
public List<LootEditCondition> Conditions { get; set; } = new();
}
public sealed class LootEditCondition
{
/// <summary>VTank node type; -1 for a read-only JSON condition shown as text.</summary>
public int NodeType { get; set; }
/// <summary>The v1 length-code line, kept verbatim ("0" for new conditions).</summary>
public string LengthCode { get; set; } = "0";
/// <summary>The data lines, raw.</summary>
public List<string> Lines { get; set; } = new();
}
/// <summary>An edit from the face. Commands that target a rule carry the name the face saw (Expect).</summary>
public sealed class LootEditCommand
{
/// <summary>open, reload, save, set_enabled, move, add, duplicate, delete, rename, update_rule.</summary>
public string Op { get; set; } = string.Empty;
public int Index { get; set; } = -1;
/// <summary>move: the index the rule ends up at.</summary>
public int To { get; set; } = -1;
public string Value { get; set; } = string.Empty;
public string Path { get; set; } = string.Empty;
/// <summary>The rule's name as the face saw it; a mismatch means the list changed under it.</summary>
public string? Expect { get; set; }
/// <summary>open/reload: discard unsaved edits; save: overwrite a file that changed on disk.</summary>
public bool Force { get; set; }
public LootEditRule? Rule { get; set; }
}
/// <summary>Names for the face's pickers. Sent once per plugin load.</summary>
public sealed class LootEditVocab
{
public List<LootEditName> Actions { get; set; } = new();
public List<LootEditNodeType> NodeTypes { get; set; } = new();
public List<LootEditName> ObjectClasses { get; set; } = new();
public List<LootEditName> LongKeys { get; set; } = new();
public List<LootEditName> DoubleKeys { get; set; } = new();
public List<LootEditName> StringKeys { get; set; } = new();
public List<LootEditName> Skills { get; set; } = new();
/// <summary>
/// Names for long keys' values (WieldSkilltype's skills, MaterialType's
/// materials...), added 2026-10. An older engine ignores this; a newer engine
/// with an older RynthAi gets it empty and keeps the value a text box.
/// </summary>
public List<LootEditValueTable> LongValueTables { get; set; } = new();
}
public sealed class LootEditName
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
/// <summary>What one long key's numbers mean (LootRuleText.ValueTableFor).</summary>
public sealed class LootEditValueTable
{
/// <summary>The long key (e.g. 159 WieldSkilltype).</summary>
public int Key { get; set; }
/// <summary>The value is a set of flags: a named value is one flag (or a common pair).</summary>
public bool Flags { get; set; }
public List<LootEditName> Values { get; set; } = new();
}
public sealed class LootEditNodeType
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
/// <summary>Data lines the node takes.</summary>
public int Lines { get; set; }
public List<string> Labels { get; set; } = new();
public List<string> Defaults { get; set; } = new();
/// <summary>
/// The face's editor: "class" (object class), "keyval" (value, key), "keypattern"
/// (pattern, key), "text" (one string), "value" (one number), "raw" (the lines as text).
/// </summary>
public string Editor { get; set; } = "raw";
/// <summary>For keyval/keypattern: "long", "double", "string" or "skill".</summary>
public string KeyTable { get; set; } = string.Empty;
/// <summary>
/// keyval "long" only: the value is picked by name when the key has a
/// LongValueTables entry (GE/LE/E/NE and buffed GE; not "has flag"). Added 2026-10.
/// </summary>
public bool NamedValues { get; set; }
}
[JsonSourceGenerationOptions(WriteIndented = false, PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(LootEditState))]
[JsonSerializable(typeof(LootEditRule))]
[JsonSerializable(typeof(LootEditCommand))]
[JsonSerializable(typeof(LootEditVocab))]
public sealed partial class LootEditJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,410 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.VTank;
namespace RynthCore.Loot.Editing;
/// <summary>
/// Words for loot rules, in plain ASCII (the in-game font has no ≥): action
/// labels, node type names, one-line condition summaries, and the vocabulary the
/// editor face's pickers show (LootEditVocab).
/// </summary>
public static class LootRuleText
{
/// <summary>The actions in picker order: Keep, Keep #, Salvage, Sell, Read.</summary>
public static readonly VTankLootAction[] Actions =
{
VTankLootAction.Keep, VTankLootAction.KeepUpTo, VTankLootAction.Salvage, VTankLootAction.Sell, VTankLootAction.Read,
};
public static bool IsKnownAction(int code) => Array.IndexOf(Actions, (VTankLootAction)code) >= 0;
public static string ActionName(VTankLootAction a) => a switch
{
VTankLootAction.Keep => "Keep",
VTankLootAction.KeepUpTo => "Keep #",
VTankLootAction.Salvage => "Salvage",
VTankLootAction.Sell => "Sell",
VTankLootAction.Read => "Read",
_ => $"Action {(int)a}",
};
/// <summary>A node type's name, ASCII.</summary>
public static string NodeName(int type) => Ascii(VTankNodeTypes.DisplayName(type));
private static string Ascii(string s) => s.Replace("≥", ">=").Replace("≤", "<=").Replace("≠", "!=");
// ── Key tables (the common ones; unknown ids show as "key N") ──────────
public static readonly (int Id, string Name)[] LongKeys =
{
(5, "EncumbVal"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (45, "DamageType"),
(48, "WeaponSkill"), (54, "MaxDamage"),
(87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"),
(131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"),
(218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"),
(372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"),
(375, "CritDamageResistRating"), (376, "HealBoostRating"), (379, "VitalityRating"),
};
public static readonly (int Id, string Name)[] DoubleKeys =
{
(5, "ApproachDistance"), (22, "DamageVariance"), (29, "WeaponLength"), (62, "WeaponDefense"),
(63, "WeaponOffense"), (152, "ElementalDamageVsMonsters"), (167, "ManaRate"),
};
public static readonly (int Id, string Name)[] StringKeys =
{
(1, "Name"), (5, "Inscription"), (7, "Title"),
};
/// <summary>
/// AC's skill ids (ACE's Skill enum, the retail client's numbering; the same ids
/// AcStubs and RynthLua use), alphabetical so a picker reads easily. Used for the
/// CharacterSkillGE / CharacterBaseSkill key and as the value names of
/// WieldSkilltype (159) and WeaponSkill (48). Retired and unused skills are kept
/// so old items still show a name.
/// </summary>
public static readonly (int Id, string Name)[] Skills =
{
(38, "Alchemy"), (14, "Arcane Lore"), (29, "Armor Tinkering"), (26, "Arms and Armor Repair"),
(27, "Assess Creature"), (19, "Assess Person"), (25, "Awareness"), (1, "Axe"), (2, "Bow"),
(53, "Challenge"), (39, "Cooking"), (31, "Creature Enchantment"), (3, "Crossbow"), (4, "Dagger"),
(20, "Deception"), (52, "Dirty Fighting"), (49, "Dual Wield"), (46, "Finesse Weapons"), (37, "Fletching"),
(42, "Gearcraft"), (21, "Healing"), (44, "Heavy Weapons"), (32, "Item Enchantment"), (18, "Item Tinkering"),
(22, "Jump"), (35, "Leadership"), (33, "Life Magic"), (45, "Light Weapons"), (23, "Lockpick"),
(36, "Loyalty"), (5, "Mace"), (15, "Magic Defense"), (30, "Magic Item Tinkering"), (16, "Mana Conversion"),
(6, "Melee Defense"), (7, "Missile Defense"), (47, "Missile Weapons"), (50, "Recklessness"), (24, "Run"),
(40, "Salvaging"), (48, "Shield"), (8, "Sling"), (51, "Sneak Attack"), (9, "Spear"), (17, "Spellcraft"),
(10, "Staff"), (54, "Summoning"), (11, "Sword"), (12, "Thrown Weapon"), (41, "Two Handed"),
(13, "Unarmed Combat"), (43, "Void Magic"), (34, "War Magic"), (28, "Weapon Tinkering"),
};
// ── Value tables (what a long key's number means) ──────────────────────
/// <summary>WieldRequirements (158): what WieldDifficulty is checked against (ACE's WieldRequirement enum).</summary>
public static readonly (int Id, string Name)[] WieldRequirements =
{
(0, "Invalid"), (1, "Skill"), (2, "Base Skill"), (3, "Attribute"), (4, "Base Attribute"),
(5, "Vital"), (6, "Base Vital"), (7, "Level"), (8, "Training"), (9, "Int Property"),
(10, "Bool Property"), (11, "Creature Type"), (12, "Heritage"),
};
/// <summary>MaterialType (131): ACE's MaterialType enum, in id order (grouped cloth, gems, hides, metals, stone, wood).</summary>
public static readonly (int Id, string Name)[] Materials =
{
(0, "Unknown"), (1, "Ceramic"), (2, "Porcelain"), (3, "Cloth"), (4, "Linen"), (5, "Satin"), (6, "Silk"),
(7, "Velvet"), (8, "Wool"), (9, "Gem"), (10, "Agate"), (11, "Amber"), (12, "Amethyst"), (13, "Aquamarine"),
(14, "Azurite"), (15, "Black Garnet"), (16, "Black Opal"), (17, "Bloodstone"), (18, "Carnelian"),
(19, "Citrine"), (20, "Diamond"), (21, "Emerald"), (22, "Fire Opal"), (23, "Green Garnet"),
(24, "Green Jade"), (25, "Hematite"), (26, "Imperial Topaz"), (27, "Jet"), (28, "Lapis Lazuli"),
(29, "Lavender Jade"), (30, "Malachite"), (31, "Moonstone"), (32, "Onyx"), (33, "Opal"), (34, "Peridot"),
(35, "Red Garnet"), (36, "Red Jade"), (37, "Rose Quartz"), (38, "Ruby"), (39, "Sapphire"),
(40, "Smokey Quartz"), (41, "Sunstone"), (42, "Tiger Eye"), (43, "Tourmaline"), (44, "Turquoise"),
(45, "White Jade"), (46, "White Quartz"), (47, "White Sapphire"), (48, "Yellow Garnet"),
(49, "Yellow Topaz"), (50, "Zircon"), (51, "Ivory"), (52, "Leather"), (53, "Armoredillo Hide"),
(54, "Gromnie Hide"), (55, "Reed Shark Hide"), (56, "Metal"), (57, "Brass"), (58, "Bronze"),
(59, "Copper"), (60, "Gold"), (61, "Iron"), (62, "Pyreal"), (63, "Silver"), (64, "Steel"), (65, "Stone"),
(66, "Alabaster"), (67, "Granite"), (68, "Marble"), (69, "Obsidian"), (70, "Sandstone"),
(71, "Serpentine"), (72, "Wood"), (73, "Ebony"), (74, "Mahogany"), (75, "Oak"), (76, "Pine"), (77, "Teak"),
};
/// <summary>
/// DamageType (45): ACE's DamageType flags, the single flags plus the common
/// slashing/piercing pair. Other combinations stay numbers ("value N").
/// </summary>
public static readonly (int Id, string Name)[] DamageTypes =
{
(0, "Undefined"), (1, "Slashing"), (2, "Piercing"), (3, "Slashing/Piercing"), (4, "Bludgeoning"),
(8, "Cold"), (16, "Fire"), (32, "Acid"), (64, "Electric"), (128, "Health"), (256, "Stamina"),
(512, "Mana"), (1024, "Nether"),
};
/// <summary>
/// The names for a long key's value, or null when the key's value is a plain
/// number. Unknown values are still valid: show them as "value N".
/// </summary>
public static (int Id, string Name)[]? ValueTableFor(int longKey) => longKey switch
{
45 => DamageTypes,
48 => Skills,
131 => Materials,
158 => WieldRequirements,
159 => Skills,
_ => null,
};
/// <summary>True when the long key's value is a set of flags (a named value is one flag or a common pair).</summary>
public static bool ValueTableIsFlags(int longKey) => longKey == 45;
/// <summary>The long keys that have a value table, for the vocabulary.</summary>
public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159 };
/// <summary>
/// True for the conditions whose value is picked by name when the key has a
/// table: LongValKey GE/LE/E/NE and BuffedLongValKeyGE (not "has flag").
/// </summary>
public static bool UsesValueNames(int nodeType) => nodeType is VTankNodeTypes.LongValKeyGE
or VTankNodeTypes.LongValKeyLE or VTankNodeTypes.LongValKeyE or VTankNodeTypes.LongValKeyNE
or VTankNodeTypes.BuffedLongValKeyGE;
/// <summary>
/// A value line as a whole number: "45", " 45 " and "45.0" (a buffed-long value
/// written as a double) all read as 45. False for anything else.
/// </summary>
public static bool TryParseValue(string? raw, out int value)
{
string s = (raw ?? string.Empty).Trim();
if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) return true;
if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)
&& d == Math.Floor(d) && d >= int.MinValue && d <= int.MaxValue)
{
value = (int)d;
return true;
}
value = 0;
return false;
}
/// <summary>The name of a long key's value, or null when the key has no table or the value isn't in it.</summary>
public static string? ValueName(int longKey, string? raw)
{
var table = ValueTableFor(longKey);
if (table == null || !TryParseValue(raw, out int v)) return null;
foreach (var t in table)
if (t.Id == v) return t.Name;
return null;
}
/// <summary>
/// How a picker shows a value: "Light Weapons (45)" when named, "value 45" when
/// not (or the raw text, "value abc", when it isn't a number).
/// </summary>
public static string ValueLabel(int longKey, string? raw)
{
string? name = ValueName(longKey, raw);
if (name != null && TryParseValue(raw, out int v)) return PickerLabel(v, name);
return "value " + (raw ?? string.Empty).Trim();
}
/// <summary>"Name (id)", the way the pickers list a named id.</summary>
public static string PickerLabel(int id, string name) => name + " (" + id.ToString(CultureInfo.InvariantCulture) + ")";
/// <summary>Object classes (Decal/VTank numbering, AcObjectClass).</summary>
public static (int Id, string Name)[] ObjectClasses { get; } = BuildObjectClasses();
private static (int, string)[] BuildObjectClasses()
{
var list = new List<(int, string)>();
foreach (AcObjectClass c in Enum.GetValues<AcObjectClass>())
list.Add(((int)c, c.ToString()));
return list.ToArray();
}
private static string KeyName((int Id, string Name)[] table, string raw)
{
if (int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
foreach (var t in table)
if (t.Id == n) return t.Name;
return "key " + raw.Trim();
}
// ── Editors per node type (what the face shows for a condition) ─────────
/// <summary>The face's editor for a node type; see LootEditNodeType.Editor.</summary>
public static (string Editor, string KeyTable) EditorFor(int type) => type switch
{
VTankNodeTypes.ObjectClass => ("class", ""),
VTankNodeTypes.LongValKeyGE or VTankNodeTypes.LongValKeyLE or VTankNodeTypes.LongValKeyE
or VTankNodeTypes.LongValKeyNE or VTankNodeTypes.LongValKeyFlagExists
or VTankNodeTypes.BuffedLongValKeyGE => ("keyval", "long"),
VTankNodeTypes.DoubleValKeyGE or VTankNodeTypes.DoubleValKeyLE
or VTankNodeTypes.BuffedDoubleValKeyGE => ("keyval", "double"),
VTankNodeTypes.CharacterSkillGE => ("keyval", "skill"),
VTankNodeTypes.StringValueMatch => ("keypattern", "string"),
VTankNodeTypes.SpellNameMatch => ("text", ""),
VTankNodeTypes.DamagePercentGE or VTankNodeTypes.SpellCountGE or VTankNodeTypes.MinDamageGE
or VTankNodeTypes.CharacterMainPackEmptySlotsGE or VTankNodeTypes.CharacterLevelGE
or VTankNodeTypes.CharacterLevelLE or VTankNodeTypes.BuffedMedianDamageGE
or VTankNodeTypes.BuffedMissileDamageGE or VTankNodeTypes.CalcdBuffedTinkedDamageGE
or VTankNodeTypes.TotalRatingsGE => ("value", ""),
_ => ("raw", ""),
};
/// <summary>What each data line holds, in file order.</summary>
public static string[] LineLabels(int type) => type switch
{
VTankNodeTypes.SpellNameMatch => new[] { "Pattern" },
VTankNodeTypes.StringValueMatch => new[] { "Pattern", "Key" },
VTankNodeTypes.LongValKeyLE or VTankNodeTypes.LongValKeyGE or VTankNodeTypes.LongValKeyE
or VTankNodeTypes.LongValKeyNE or VTankNodeTypes.DoubleValKeyLE or VTankNodeTypes.DoubleValKeyGE
or VTankNodeTypes.BuffedLongValKeyGE or VTankNodeTypes.BuffedDoubleValKeyGE => new[] { "Value", "Key" },
VTankNodeTypes.LongValKeyFlagExists => new[] { "Flag", "Key" },
VTankNodeTypes.ObjectClass => new[] { "Class" },
VTankNodeTypes.SpellCountGE => new[] { "Count" },
VTankNodeTypes.DamagePercentGE => new[] { "Percent" },
VTankNodeTypes.MinDamageGE or VTankNodeTypes.BuffedMedianDamageGE or VTankNodeTypes.BuffedMissileDamageGE
or VTankNodeTypes.CalcdBuffedTinkedDamageGE => new[] { "Damage" },
VTankNodeTypes.CharacterLevelGE or VTankNodeTypes.CharacterLevelLE => new[] { "Level" },
VTankNodeTypes.TotalRatingsGE => new[] { "Ratings" },
VTankNodeTypes.SpellMatch => new[] { "Match", "No match", "Count" },
VTankNodeTypes.AnySimilarColor => new[] { "R", "G", "B", "Max diff H", "Max diff SV" },
VTankNodeTypes.SimilarColorArmorType => new[] { "R", "G", "B", "Max diff H", "Max diff SV", "Armor group" },
VTankNodeTypes.SlotSimilarColor => new[] { "R", "G", "B", "Max diff H", "Max diff SV", "Slot" },
VTankNodeTypes.SlotExactPalette => new[] { "Slot", "Palette" },
VTankNodeTypes.CharacterSkillGE => new[] { "Value", "Skill" },
VTankNodeTypes.CharacterMainPackEmptySlotsGE => new[] { "Slots" },
VTankNodeTypes.CharacterBaseSkill => new[] { "Skill", "Min", "Max" },
VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => new[] { "DoT", "Def", "Atk" },
VTankNodeTypes.DisabledRule => new[] { "Disabled" },
_ => Array.Empty<string>(),
};
/// <summary>Data lines for a new condition of this type.</summary>
public static List<string> DefaultLines(int type)
{
int n = Math.Max(0, VTankNodeTypes.GetDataLineCount(type));
var lines = new List<string>(n);
for (int i = 0; i < n; i++) lines.Add(IsTextLine(type, i) ? string.Empty : "0");
if (type == VTankNodeTypes.DisabledRule && n == 1) lines[0] = "true";
if (type == VTankNodeTypes.StringValueMatch) lines[1] = "1"; // Name
if (type == VTankNodeTypes.ObjectClass) lines[0] = ((int)AcObjectClass.MeleeWeapon).ToString(CultureInfo.InvariantCulture);
return lines;
}
/// <summary>True for a line that holds text (a pattern), not a number.</summary>
public static bool IsTextLine(int type, int line) => type switch
{
VTankNodeTypes.SpellNameMatch => line == 0,
VTankNodeTypes.StringValueMatch => line == 0,
VTankNodeTypes.SpellMatch => line <= 1,
VTankNodeTypes.DisabledRule => true,
_ => false,
};
/// <summary>True for a number line that must hold a whole number (else a decimal).</summary>
public static bool IsIntLine(int type, int line) => type switch
{
VTankNodeTypes.DoubleValKeyGE or VTankNodeTypes.DoubleValKeyLE or VTankNodeTypes.BuffedDoubleValKeyGE => line == 1,
VTankNodeTypes.DamagePercentGE or VTankNodeTypes.MinDamageGE or VTankNodeTypes.BuffedMedianDamageGE
or VTankNodeTypes.BuffedMissileDamageGE or VTankNodeTypes.CalcdBuffedTinkedDamageGE
or VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => false,
VTankNodeTypes.AnySimilarColor or VTankNodeTypes.SimilarColorArmorType or VTankNodeTypes.SlotSimilarColor => line <= 2 || line == 5,
_ => true,
};
// ── Summaries ────────────────────────────────────────────────────────
/// <summary>A rule's conditions in words, joined with AND (DisabledRule nodes left out).</summary>
public static string Summary(VTankLootRule rule, int maxLength = 160)
{
var sb = new StringBuilder();
foreach (VTankLootCondition c in rule.Conditions)
{
if (c.NodeType == VTankNodeTypes.DisabledRule) continue;
if (sb.Length > 0) sb.Append(" AND ");
sb.Append(Condition(c));
if (sb.Length > maxLength) break;
}
if (sb.Length == 0) return "Matches every item";
return sb.Length > maxLength ? sb.ToString(0, maxLength - 3) + "..." : sb.ToString();
}
/// <summary>One condition in words.</summary>
public static string Condition(VTankLootCondition c)
{
IList<string> d = c.DataLines;
string G(int i) => i < d.Count ? d[i] : "?";
string Lk(int i) => KeyName(LongKeys, G(i));
string Dk(int i) => KeyName(DoubleKeys, G(i));
string Sk(int i) => KeyName(StringKeys, G(i));
string Skl(int i) => KeyName(Skills, G(i));
string Oc(int i)
{
if (int.TryParse(G(i).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
foreach (var t in ObjectClasses)
if (t.Id == n) return t.Name;
return "class " + G(i);
}
// A long key's value by name when the key has a table ("WieldSkilltype = Light Weapons").
string Lv()
{
if (TryParseValue(G(1), out int key) && ValueName(key, G(0)) is string name) return name;
return G(0);
}
static string Trunc(string s, int n) => s.Length > n ? s.Substring(0, n) + "..." : s;
return c.NodeType switch
{
VTankNodeTypes.ObjectClass => $"Class is {Oc(0)}",
VTankNodeTypes.LongValKeyGE => $"{Lk(1)} >= {Lv()}",
VTankNodeTypes.LongValKeyLE => $"{Lk(1)} <= {Lv()}",
VTankNodeTypes.LongValKeyE => $"{Lk(1)} = {Lv()}",
VTankNodeTypes.LongValKeyNE => $"{Lk(1)} != {Lv()}",
VTankNodeTypes.LongValKeyFlagExists => $"{Lk(1)} has flag {G(0)}",
VTankNodeTypes.DoubleValKeyGE => $"{Dk(1)} >= {G(0)}",
VTankNodeTypes.DoubleValKeyLE => $"{Dk(1)} <= {G(0)}",
VTankNodeTypes.BuffedLongValKeyGE => $"buffed {Lk(1)} >= {Lv()}",
VTankNodeTypes.BuffedDoubleValKeyGE => $"buffed {Dk(1)} >= {G(0)}",
VTankNodeTypes.StringValueMatch => $"{Sk(1)} matches \"{Trunc(G(0), 30)}\"",
VTankNodeTypes.SpellNameMatch => $"spell matches \"{Trunc(G(0), 30)}\"",
VTankNodeTypes.SpellCountGE => $"spell count >= {G(0)}",
VTankNodeTypes.SpellMatch => $">= {G(2)} spells matching \"{Trunc(G(0), 20)}\"",
VTankNodeTypes.MinDamageGE => $"min dmg >= {G(0)}",
VTankNodeTypes.DamagePercentGE => $"dmg% >= {G(0)}",
VTankNodeTypes.TotalRatingsGE => $"total ratings >= {G(0)}",
VTankNodeTypes.BuffedMedianDamageGE => $"median dmg >= {G(0)}",
VTankNodeTypes.BuffedMissileDamageGE => $"missile dmg >= {G(0)}",
VTankNodeTypes.CalcdBuffedTinkedDamageGE => $"tinked dmg >= {G(0)}",
VTankNodeTypes.CharacterLevelGE => $"char level >= {G(0)}",
VTankNodeTypes.CharacterLevelLE => $"char level <= {G(0)}",
VTankNodeTypes.CharacterMainPackEmptySlotsGE => $"pack slots >= {G(0)}",
VTankNodeTypes.CharacterSkillGE => $"{Skl(1)} skill >= {G(0)}",
VTankNodeTypes.CharacterBaseSkill => $"{Skl(0)} base in [{G(1)}, {G(2)}]",
VTankNodeTypes.SlotExactPalette => $"palette slot {G(0)} = {G(1)}",
VTankNodeTypes.AnySimilarColor => "color (any similar)",
VTankNodeTypes.SimilarColorArmorType => "color (armor type)",
VTankNodeTypes.SlotSimilarColor => "color (slot)",
VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => "buffed tinked target melee",
VTankNodeTypes.DisabledRule => "(rule disabled)",
_ => $"node {c.NodeType}",
};
}
// ── Vocabulary for the face ──────────────────────────────────────────
public static LootEditVocab BuildVocab()
{
var v = new LootEditVocab();
foreach (VTankLootAction a in Actions) v.Actions.Add(new LootEditName { Id = (int)a, Name = ActionName(a) });
foreach (int t in VTankNodeTypes.All)
{
(string editor, string table) = EditorFor(t);
v.NodeTypes.Add(new LootEditNodeType
{
Id = t, Name = NodeName(t), Lines = Math.Max(0, VTankNodeTypes.GetDataLineCount(t)),
Labels = new List<string>(LineLabels(t)), Defaults = DefaultLines(t), Editor = editor, KeyTable = table,
NamedValues = UsesValueNames(t),
});
}
Fill(v.ObjectClasses, ObjectClasses);
Fill(v.LongKeys, LongKeys);
Fill(v.DoubleKeys, DoubleKeys);
Fill(v.StringKeys, StringKeys);
Fill(v.Skills, Skills);
foreach (int key in KeysWithValueTables)
{
var vt = new LootEditValueTable { Key = key, Flags = ValueTableIsFlags(key) };
Fill(vt.Values, ValueTableFor(key)!);
v.LongValueTables.Add(vt);
}
return v;
static void Fill(List<LootEditName> into, (int Id, string Name)[] from)
{
foreach (var (id, name) in from) into.Add(new LootEditName { Id = id, Name = name });
}
}
}

View file

@ -1,18 +1,36 @@
// Ported ACE code with a null-returning public API that RynthAi, RynthJuice and
// RynthVision already depend on; annotating it would add warnings in every caller.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.TerrainData;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// AC .dat file reader — ported directly from ACEmulator's DatLoader.
///
/// AC .dat file reader — ported 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
///
/// Lookups walk the on-disk B-tree by key (root → child whose key range holds
/// the id), the way ACE's DatDirectory search does, instead of indexing every
/// entry up front: opening client_cell_1.dat used to read all ~805k entries
/// (1.6-1.9 s and ~55 MB in a 32-bit process). Interior nodes are kept once
/// read and leaves go through a small LRU, so a cold lookup reads one leaf
/// and neighbouring ids (adjacent landblocks) touch the disk once. Full
/// enumeration is still available on demand (<see cref="EnumerateEntries"/>,
/// used by <see cref="GetSampleIds"/>; <see cref="RecordCount"/> walks only
/// the node headers); neither keeps anything.
///
/// Thread-safety: every stream read and cache access holds one lock, so a
/// database can be shared between threads.
/// </summary>
public class DatDatabase : IDisposable
{
@ -29,6 +47,18 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
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
// Deeper than any real dat (805k entries at fan-out 62 is 4 levels);
// stops a corrupt branch pointer from looping forever.
private const int MaxTreeDepth = 16;
// Parsed nodes kept for repeat lookups (~2.5 KB each). Interior nodes
// are few (about 1 in 62: ~220 for client_cell_1.dat) and on every
// search path, so they are all kept once read, which makes a cold
// lookup cost one leaf read. Leaves go through a small LRU; 128 holds
// a 7×7-landblock window many times over.
private const int LeafCacheCapacity = 128;
private const int MaxInteriorNodes = 4096; // safety cap; real dats stay far below
// Header fields
public uint FileType { get; private set; }
public uint BlockSize { get; private set; }
@ -38,15 +68,60 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
public bool IsLoaded { get; private set; }
public string FilePath { get; private set; }
public int RecordCount { get; private set; }
// All files indexed by ObjectId (populated during Open)
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new Dictionary<uint, DatBTreeEntry>();
private int _recordCount = -1;
/// <summary>
/// Number of files in the dat. Counted on first use by walking the
/// B-tree node headers (branch table + entry count, the first block of
/// each node; the entries themselves aren't read), then cached until
/// Close. The old eager index paid a full read of every node at Open.
/// </summary>
public int RecordCount
{
get
{
if (!IsLoaded) return 0;
if (_recordCount < 0)
_recordCount = CountEntries(BTreeRoot, 0);
return _recordCount;
}
}
private int CountEntries(uint offset, int depth)
{
if (offset == 0 || depth >= MaxTreeDepth) return 0;
byte[] head;
lock (_lock) head = ReadDatData(offset, NodeHeaderSize);
if (head == null || head.Length < NodeHeaderSize) return 0;
uint entryCount = BitConverter.ToUInt32(head, BTREE_BRANCH_COUNT * 4);
if (entryCount > BTREE_MAX_ENTRIES) return 0;
int total = (int)entryCount;
if (BitConverter.ToUInt32(head, 0) != 0) // interior node
for (int i = 0; i <= entryCount; i++)
total += CountEntries(BitConverter.ToUInt32(head, i * 4), depth + 1);
return total;
}
// Branch table + entry count: the part of a node CountEntries needs.
private const int NodeHeaderSize = (4 * BTREE_BRANCH_COUNT) + 4; // 252
private sealed class BTreeNode
{
public uint[] Branches;
public DatBTreeEntry[] Entries; // sorted by ObjectId
public bool IsLeaf => Branches[0] == 0;
}
private readonly LruCache<uint, BTreeNode> _leafCache = new LruCache<uint, BTreeNode>(LeafCacheCapacity);
private readonly Dictionary<uint, BTreeNode> _interiorNodes = new Dictionary<uint, BTreeNode>();
public List<string> DiagLog { get; } = new List<string>();
public bool Open(string path)
{
// Re-opening must not leak the previous handle.
Close();
try
{
if (!File.Exists(path))
@ -56,16 +131,15 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
}
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.
// AC keeps its own handles on these files, and whichever of us
// opens second must be compatible with the other: RynthAi opens
// at plugin init (before acclient.exe opens its dats), RynthVision
// and RynthJuice later. We only read, and we allow others to
// read, write and delete-mark the file (FileShare.Delete matters
// when we open first: AC's own open needs delete-rename semantics
// for the patcher, and without it AC fails with "cannot access
// the data files"). RandomAccess hint + 4 KB buffer suit the
// scattered B-tree and block-chain reads.
_stream = new FileStream(
path,
FileMode.Open,
@ -82,14 +156,19 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
return false;
}
// Read the entire B-tree directory and index all files
ReadDirectory(BTreeRoot);
// Validate the root node now so a bad file fails here, not on
// the first lookup.
BTreeNode root;
lock (_lock) root = GetNodeLocked(BTreeRoot);
if (root == null)
{
Log($"Unreadable B-tree root at 0x{BTreeRoot:X8}");
Close();
return false;
}
RecordCount = _allFiles.Count;
IsLoaded = true;
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
Log($"SUCCESS: opened (B-tree searched on demand), BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
return true;
}
catch (Exception ex)
@ -119,17 +198,16 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
BlockSize = reader.ReadUInt32();
FileSize = reader.ReadUInt32();
DataSet = reader.ReadUInt32();
uint dataSubset = reader.ReadUInt32();
uint freeHead = reader.ReadUInt32();
uint freeTail = reader.ReadUInt32();
uint freeCount = reader.ReadUInt32();
reader.ReadUInt32(); // dataSubset
reader.ReadUInt32(); // freeHead
reader.ReadUInt32(); // freeTail
reader.ReadUInt32(); // freeCount
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)
if (BlockSize <= 4 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
{
Log("Invalid header values");
return false;
@ -140,27 +218,25 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
/// <summary>
/// Reads data from the dat file following the block chain.
/// Matches ACE's DatReader.ReadDat() exactly.
///
/// Matches ACE's DatReader.ReadDat().
///
/// 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.
/// If 0, this is the last block. Caller holds _lock.
/// </summary>
private byte[] ReadDatData(uint offset, int size)
{
if (offset + BlockSize > (uint)_stream.Length || size <= 0)
if (_stream == null || (long)offset + BlockSize > _stream.Length || size <= 0)
return null;
byte[] buffer = new byte[size];
Span<byte> addrBuf = stackalloc byte[4];
_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);
if (!ReadFully(addrBuf)) return null;
uint nextAddress = BitConverter.ToUInt32(addrBuf);
int bufferOffset = 0;
int remaining = size;
@ -170,9 +246,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (nextAddress == 0)
{
// Last block — read remaining data directly
int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position));
int toRead = (int)Math.Min(remaining, _stream.Length - _stream.Position);
if (toRead <= 0) break;
_stream.Read(buffer, bufferOffset, toRead);
ReadFully(buffer.AsSpan(bufferOffset, toRead));
remaining = 0;
}
else
@ -180,7 +256,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
// 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);
if (!ReadFully(buffer.AsSpan(bufferOffset, toRead))) break;
bufferOffset += toRead;
remaining -= toRead;
@ -191,8 +267,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
_stream.Seek(nextAddress, SeekOrigin.Begin);
// Read next block's chain pointer
_stream.Read(addrBuf, 0, 4);
nextAddress = BitConverter.ToUInt32(addrBuf, 0);
if (!ReadFully(addrBuf)) break;
nextAddress = BitConverter.ToUInt32(addrBuf);
}
}
}
@ -200,41 +276,38 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
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)
private bool ReadFully(Span<byte> dest)
{
if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length)
return;
// Read the directory header (B-tree node)
byte[] nodeData;
lock (_lock)
while (dest.Length > 0)
{
nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE);
int n = _stream.Read(dest);
if (n <= 0) return false;
dest = dest.Slice(n);
}
return true;
}
/// <summary>Parses the B-tree node at <paramref name="offset"/>. Caller holds _lock.</summary>
private BTreeNode ReadNodeLocked(uint offset)
{
if (_stream == null || offset == 0 || offset >= (uint)_stream.Length)
return null;
byte[] nodeData = ReadDatData(offset, BTREE_NODE_SIZE);
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
return;
return null;
// Parse branches (62 × uint32)
uint[] branches = new uint[BTREE_BRANCH_COUNT];
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
if (entryCount > BTREE_MAX_ENTRIES)
return null; // Invalid node
var 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;
@ -247,32 +320,62 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
};
}
// 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]);
}
}
return new BTreeNode { Branches = branches, Entries = entries };
}
// Add entries to the file index
for (int i = 0; i < entryCount; i++)
/// <summary>Cached node read. Caller holds _lock.</summary>
private BTreeNode GetNodeLocked(uint offset)
{
if (_interiorNodes.TryGetValue(offset, out var node)) return node;
if (_leafCache.TryGet(offset, out node)) return node;
node = ReadNodeLocked(offset);
if (node == null) return null;
if (!node.IsLeaf && _interiorNodes.Count < MaxInteriorNodes)
_interiorNodes[offset] = node;
else
_leafCache.Set(offset, node);
return node;
}
// Index of the first entry whose ObjectId is >= id (entries.Length if none).
private static int LowerBound(DatBTreeEntry[] entries, uint id)
{
int lo = 0, hi = entries.Length;
while (lo < hi)
{
if (entries[i].ObjectId != 0)
_allFiles[entries[i].ObjectId] = entries[i];
int mid = (lo + hi) >> 1;
if (entries[mid].ObjectId < id) lo = mid + 1;
else hi = mid;
}
return lo;
}
/// <summary>
/// Finds a file by ID. O(1) lookup from the pre-built index.
/// Finds a file by ID: descends the B-tree from the root, picking at each
/// node the branch between the two keys that bracket the id.
/// </summary>
public DatBTreeEntry FindFile(uint fileId)
{
if (!IsLoaded) return null;
_allFiles.TryGetValue(fileId, out var entry);
return entry;
if (!IsLoaded || fileId == 0) return null;
lock (_lock)
{
uint offset = BTreeRoot;
for (int depth = 0; depth < MaxTreeDepth && offset != 0; depth++)
{
BTreeNode node = GetNodeLocked(offset);
if (node == null) return null;
DatBTreeEntry[] entries = node.Entries;
int i = LowerBound(entries, fileId);
if (i < entries.Length && entries[i].ObjectId == fileId)
return entries[i];
if (node.IsLeaf || i >= BTREE_BRANCH_COUNT)
return null;
offset = node.Branches[i];
}
}
return null;
}
/// <summary>
@ -280,7 +383,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
/// </summary>
public byte[] ReadFileData(DatBTreeEntry entry)
{
if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null)
if (!IsLoaded || entry == null || entry.FileSize == 0)
return null;
lock (_lock)
@ -296,8 +399,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
}
/// <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.
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock,
/// ascending. A B-tree range search: only the nodes whose key range
/// overlaps the landblock's are read.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
@ -305,25 +409,105 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (!IsLoaded) return cellIds;
uint prefix = landblockKey << 16;
foreach (var id in _allFiles.Keys)
uint lo = prefix | 0x0100;
uint hi = prefix | 0xFFFD;
lock (_lock)
{
if ((id & 0xFFFF0000) != prefix) continue;
uint cell = id & 0xFFFF;
if (cell >= 0x0100 && cell <= 0xFFFD)
cellIds.Add(id);
CollectRangeLocked(BTreeRoot, lo, hi, cellIds, 0);
}
return cellIds;
}
private void CollectRangeLocked(uint offset, uint lo, uint hi, List<uint> output, int depth)
{
if (offset == 0 || depth >= MaxTreeDepth) return;
BTreeNode node = GetNodeLocked(offset);
if (node == null) return;
DatBTreeEntry[] entries = node.Entries;
int count = entries.Length;
// Branch i holds the ids between entries[i-1] and entries[i].
int start = LowerBound(entries, lo);
for (int i = start; i <= count; i++)
{
if (!node.IsLeaf && i < BTREE_BRANCH_COUNT)
CollectRangeLocked(node.Branches[i], lo, hi, output, depth + 1);
if (i == count) break;
uint id = entries[i].ObjectId;
if (id > hi) break;
output.Add(id);
}
}
/// <summary>
/// Returns sample file IDs from the index for diagnostics.
/// Every entry in the dat, in ascending id order, read from the B-tree
/// on demand (nothing is kept afterwards). Walking client_cell_1.dat
/// reads every node, so use it for diagnostics and counts, not lookups.
/// </summary>
public IEnumerable<DatBTreeEntry> EnumerateEntries()
{
if (!IsLoaded) yield break;
// Explicit stack instead of recursion so the lock is only held per
// node read, never across a yield. A frame is "visit branch I, then
// entry I, then move on to I+1".
BTreeNode root = ReadNodeForWalk(BTreeRoot);
if (root == null) yield break;
var stack = new Stack<WalkFrame>();
stack.Push(new WalkFrame(root, 0, false));
while (stack.Count > 0)
{
WalkFrame f = stack.Pop();
if (!f.BranchDone)
{
stack.Push(new WalkFrame(f.Node, f.Index, true));
if (!f.Node.IsLeaf && f.Index < BTREE_BRANCH_COUNT && stack.Count <= MaxTreeDepth)
{
BTreeNode child = ReadNodeForWalk(f.Node.Branches[f.Index]);
if (child != null) stack.Push(new WalkFrame(child, 0, false));
}
continue;
}
if (f.Index < f.Node.Entries.Length)
{
yield return f.Node.Entries[f.Index];
stack.Push(new WalkFrame(f.Node, f.Index + 1, false));
}
}
}
private readonly struct WalkFrame
{
public readonly BTreeNode Node;
public readonly int Index;
public readonly bool BranchDone;
public WalkFrame(BTreeNode node, int index, bool branchDone) { Node = node; Index = index; BranchDone = branchDone; }
}
private BTreeNode ReadNodeForWalk(uint offset)
{
lock (_lock)
{
// Don't churn the lookup cache with a full walk: use a cached
// node if present, otherwise read without caching.
if (_interiorNodes.TryGetValue(offset, out var cached)) return cached;
if (_leafCache.TryGet(offset, out cached)) return cached;
return ReadNodeLocked(offset);
}
}
/// <summary>
/// Returns the lowest file IDs in the dat (in-order walk, stops early),
/// for diagnostics.
/// </summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
foreach (var kvp in _allFiles)
if (maxCount <= 0) return ids;
foreach (var e in EnumerateEntries())
{
ids.Add(kvp.Key);
ids.Add(e.ObjectId);
if (ids.Count >= maxCount) break;
}
return ids;
@ -331,10 +515,15 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
public void Close()
{
_stream?.Dispose();
_stream = null;
IsLoaded = false;
_allFiles.Clear();
lock (_lock)
{
_stream?.Dispose();
_stream = null;
IsLoaded = false;
_recordCount = -1;
_leafCache.Clear();
_interiorNodes.Clear();
}
}
public void Dispose() { Close(); }

View file

@ -0,0 +1,62 @@
using System.Collections.Generic;
namespace RynthCore.TerrainData;
/// <summary>
/// Small fixed-capacity least-recently-used map. Not thread-safe: callers hold
/// their own lock. A hit moves the entry to the front without allocating; only
/// an insert allocates (one list node), and the oldest entry is dropped when
/// the map is full.
/// </summary>
internal sealed class LruCache<TKey, TValue> where TKey : notnull
{
private readonly int _capacity;
private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> _map;
private readonly LinkedList<KeyValuePair<TKey, TValue>> _order = new();
public LruCache(int capacity)
{
_capacity = capacity < 1 ? 1 : capacity;
_map = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(_capacity);
}
public int Count => _map.Count;
public bool TryGet(TKey key, out TValue value)
{
if (_map.TryGetValue(key, out var node))
{
if (node != _order.First)
{
_order.Remove(node);
_order.AddFirst(node);
}
value = node.Value.Value;
return true;
}
value = default!;
return false;
}
public void Set(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var existing))
{
_order.Remove(existing);
_map.Remove(key);
}
else if (_map.Count >= _capacity)
{
var oldest = _order.Last!;
_order.RemoveLast();
_map.Remove(oldest.Value.Key);
}
_map[key] = _order.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
}
public void Clear()
{
_map.Clear();
_order.Clear();
}
}

View file

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting;
@ -30,16 +29,15 @@ public sealed class TerrainSampler : IDisposable
private float[]? _landHeightTable;
private bool _ready;
// Deep-audit finding #6 (2026-06-18): RynthVision's /rv watertypes ->
// InspectTerrain runs synchronously on the Avalonia UI thread and calls
// LoadLandblock, while the same call hits from the AC tick thread hundreds
// of times per Submit via the slope/water overlays. Two threads mutating
// one plain Dictionary (with a periodic Clear() at MaxCache=30) is classic
// bucket-array corruption on whichever thread lands on it — frequently
// AC's own main thread. Guard every access with this gate.
// Parsed landblocks, least-recently-used first out. RynthVision calls
// LoadLandblock only from the plugin pump thread (its engine panels reach
// it through the pump too), but this class is shared, so the cache stays
// behind a lock that is uncontended in that case. The capacity holds a
// whole 7×7-landblock overlay window (radius 24 cells = ±3 landblocks)
// plus headroom, so a tick never evicts what the next tick needs.
private readonly object _cacheGate = new();
private readonly Dictionary<uint, LandblockData?> _cache = new();
private const int MaxCache = 30;
private readonly LruCache<uint, LandblockData?> _cache = new(MaxCache);
private const int MaxCache = 64;
public bool IsReady => _ready;
public string Status { get; private set; } = "uninitialized";
@ -48,11 +46,14 @@ public sealed class TerrainSampler : IDisposable
/// Opens the AC .dat files and loads the land-height table. Idempotent. When
/// acFolderPath is null, uses the running process's directory — inside an
/// injected plugin that's acclient.exe's folder, where the active client's
/// .dat files live.
/// .dat files live. Cheap: the dats' B-trees are searched on demand, so
/// this reads two headers and the RegionDesc record. A failed attempt
/// closes whatever it opened, so calling it again doesn't leak handles.
/// </summary>
public bool Initialize(string? acFolderPath = null)
{
if (_ready) return true;
bool ok = false;
try
{
string? folder = acFolderPath;
@ -89,6 +90,7 @@ public sealed class TerrainSampler : IDisposable
_ready = true;
Status = "ready";
ok = true;
return true;
}
catch (Exception ex)
@ -96,6 +98,15 @@ public sealed class TerrainSampler : IDisposable
Status = ex.Message;
return false;
}
finally
{
if (!ok)
{
_portalDat.Close();
_cellDat.Close();
_landHeightTable = null;
}
}
}
/// <summary>Parsed landblock (heights + terrain words), cached. Null if unavailable.</summary>
@ -104,18 +115,52 @@ public sealed class TerrainSampler : IDisposable
if (!_ready || _landHeightTable == null) return null;
lock (_cacheGate)
{
if (_cache.TryGetValue(landblockKey, out var cached)) return cached;
if (_cache.TryGet(landblockKey, out var cached)) return cached;
}
LandblockData? data = LandblockData.Load(_cellDat, landblockKey, _landHeightTable);
lock (_cacheGate)
{
if (_cache.Count >= MaxCache) _cache.Clear();
_cache[landblockKey] = data;
_cache.Set(landblockKey, data);
}
return data;
}
/// <summary>
/// Terrain Z at landblock-local (lx, ly) in [0, 192], on the triangle AC
/// actually uses for that cell (<see cref="SwToNeCut"/>). Unlike
/// LandblockData.GetTerrainZLocal, which always splits SW→NE, this matches
/// the rendered ground on every cell. Coordinates are clamped to the block.
/// </summary>
public static float GetTerrainZ(LandblockData lb, float lx, float ly)
{
const float block = CellLength * 8f;
if (lx < 0f) lx = 0f; else if (lx > block) lx = block;
if (ly < 0f) ly = 0f; else if (ly > block) ly = block;
int cx = Math.Min((int)(lx / CellLength), 7);
int cy = Math.Min((int)(ly / CellLength), 7);
float u = (lx - cx * CellLength) / CellLength;
float v = (ly - cy * CellLength) / CellLength;
float h00 = lb.GetVertexZ(cx, cy); // SW
float h10 = lb.GetVertexZ(cx + 1, cy); // SE
float h01 = lb.GetVertexZ(cx, cy + 1); // NW
float h11 = lb.GetVertexZ(cx + 1, cy + 1); // NE
if (SwToNeCut(lb.LandblockKey, cx, cy))
{
// SE half (SW,SE,NE) when v <= u, NW half (SW,NE,NW) otherwise.
return v <= u
? h00 + u * (h10 - h00) + v * (h11 - h10)
: h00 + v * (h01 - h00) + u * (h11 - h01);
}
// SW half (SW,SE,NW) when u + v <= 1, NE half (SE,NE,NW) otherwise.
return u + v <= 1f
? h00 + u * (h10 - h00) + v * (h01 - h00)
: h11 + (1f - u) * (h01 - h11) + (1f - v) * (h10 - h11);
}
/// <summary>
/// AC's per-cell diagonal-split PRNG (ACE LandblockStruct.ConstructPolygons /
/// FSplitNESW). When true the cell is cut SW→NE (triangles SW-SE-NE and
@ -266,8 +311,11 @@ public sealed class TerrainSampler : IDisposable
public void Dispose()
{
_ready = false;
_portalDat.Dispose();
_cellDat.Dispose();
_ready = false;
_landHeightTable = null;
lock (_cacheGate) _cache.Clear();
Status = "closed";
}
}