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

@ -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 });
}
}
}