RynthSuite as of 2026-10-05 (internal 8b7d487): navigation no longer stalls after doorway turns, faster target and attack, corpses used from a distance and closed after looting, patrol wall clearance, add-to-loot-profile from an item, WCID loot rules, scroll and slayer fixes, release 2026.10.5.1

This commit is contained in:
Tom Bohar 2026-10-05 08:03:08 -04:00
commit 53438c65c1
29 changed files with 3951 additions and 86 deletions

View file

@ -43,6 +43,17 @@ public sealed class LootEditSession
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;
/// <summary>The open .json profile (native format), else null.</summary>
public LootProfile? JsonProfile => _json;
/// <summary>"utl", "json", or empty when nothing is open.</summary>
public string Format => !IsOpen ? string.Empty : _json != null ? "json" : "utl";
/// <summary>Why edits are refused (empty when they aren't).</summary>
public string ReadOnlyReason => _readOnlyReason;
/// <summary>True when InsertAndSave can add a rule: an editable .utl, or a .json profile.</summary>
public bool CanInsert => _utl != null || _json != null;
/// <summary>The last message (what the last command or load did).</summary>
public string Message => _message;
public bool MessageOk => _messageOk;
// =====================================================================
// Load
@ -422,19 +433,7 @@ public sealed class LootEditSession
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);
WriteFile(_path, Encode());
_stamp = FileStamp.Read(_path);
_dirty = false;
_changedOnDisk = false;
@ -446,6 +445,135 @@ public sealed class LootEditSession
}
}
/// <summary>Writes a temp file and swaps it in, the old file kept as .bak.</summary>
private static void WriteFile(string path, byte[] bytes)
{
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);
}
// =====================================================================
// Add one rule and save (the "Add to loot profile" of a clicked item)
// =====================================================================
/// <summary>
/// Inserts <paramref name="rule"/> at <paramref name="index"/> (clamped; the
/// end when out of range) and saves at once, the old file kept as .bak.
/// .utl: through the edited model, refused while there are unsaved edits (so
/// it never saves someone's half-done changes with it) or when the file opens
/// read-only. .json: <paramref name="native"/> is spliced into the file's
/// Rules array as text, so every other byte stays as it was (the JSON writer
/// itself is lossy). Both check before writing that the result reads back
/// with every other rule unchanged; nothing is written when it doesn't.
/// </summary>
public bool InsertAndSave(VTankLootRule rule, LootRule? native, int index)
{
if (!IsOpen) return Fail("No profile open.");
if (_dirty) return Fail($"Unsaved changes in {FileName(_path)}. Save or discard them in the Loot Editor first.");
if (_json != null)
return native == null ? Fail("That rule can't be written in the native format.") : InsertJson(native, index);
if (_utl == null) return Fail(_readOnlyReason);
if (!_stamp.Exists) return Fail($"{FileName(_path)} doesn't exist yet. Save it once in the Loot Editor first.");
List<VTankLootRule> rules = _utl.Rules;
int at = index < 0 || index > rules.Count ? rules.Count : index;
if (_utl.FileVersion < 1) rule.CustomExpression = null;
else rule.CustomExpression ??= string.Empty;
var before = new List<string>(rules.Count);
foreach (VTankLootRule r in rules) before.Add(RuleText(_utl, r));
rules.Insert(at, rule);
string? bad = VerifyUtl(before, at);
if (bad != null)
{
rules.RemoveAt(at);
return Fail("Not added (the profile would not read back the same): " + bad);
}
_dirty = true;
if (!Save())
{
string why = _message;
rules.RemoveAt(at);
_dirty = false;
if (_changedOnDisk)
{
// Someone else wrote the file: show theirs (nothing of ours is pending).
Open(_path, force: true);
return Fail($"Not added: {FileName(_path)} changed on disk; reloaded it. Try again.");
}
return Fail("Not added. " + why);
}
_focus = at;
return Ok($"Added \"{rule.Name}\" at {at + 1} and saved {FileName(_path)} ({RuleCount} rules).");
}
private static string RuleText(VTankLootProfile owner, VTankLootRule r) =>
VTankLootWriter.Serialize(new VTankLootProfile { FileVersion = owner.FileVersion, Rules = { r } });
/// <summary>Null when the model, written and parsed back, has the old rules unchanged and the new one at <paramref name="at"/>.</summary>
private string? VerifyUtl(List<string> before, int at)
{
VTankLootProfile back;
try { back = VTankLootParser.LoadFromText(Decode(Encode(), out _, out _)); }
catch (Exception ex) { return ex.Message; }
if (back.Rules.Count != before.Count + 1) return $"{back.Rules.Count} rules instead of {before.Count + 1}.";
if (!SameSalvage(back.SalvageCombine, _utl!.SalvageCombine)) return "the salvage combine settings changed.";
for (int i = 0, j = 0; i < back.Rules.Count; i++)
{
string text = RuleText(back, back.Rules[i]);
if (i == at)
{
if (text != RuleText(_utl, _utl.Rules[at])) return "the new rule reads back differently.";
continue;
}
if (text != before[j++]) return $"rule {i + 1} would change.";
}
return null;
}
private static bool SameSalvage(SalvageCombineSettings? a, SalvageCombineSettings? b)
{
if (a == null || b == null) return a == null && b == null;
string Text(SalvageCombineSettings s) => VTankLootWriter.Serialize(new VTankLootProfile { FileVersion = 1, SalvageCombine = s });
return Text(a) == Text(b);
}
private bool InsertJson(LootRule native, int index)
{
try
{
byte[] bytes = File.ReadAllBytes(_path);
if (!FileStamp.Of(_path, bytes).SameContent(_stamp))
{
Open(_path, force: true);
return Fail($"{FileName(_path)} changed on disk; reloaded it. Try again.");
}
byte[]? spliced = LootJsonSplice.Insert(bytes, native, index, out int at, out string error);
if (spliced == null) return Fail("Not added: " + error);
WriteFile(_path, spliced);
_json = System.Text.Json.JsonSerializer.Deserialize(Decode(spliced, out _, out _), LootJsonContext.Default.LootProfile) ?? new LootProfile();
_stamp = FileStamp.Read(_path);
_changedOnDisk = false;
_focus = at;
Revision++;
return Ok($"Added \"{native.Name}\" at {at + 1} and saved {FileName(_path)} ({RuleCount} rules).");
}
catch (Exception ex)
{
return Fail($"Not added: {ex.Message}");
}
}
/// <summary>The file's bytes as Save writes them (its own encoding, line endings, BOM).</summary>
public byte[] Encode()
{

View file

@ -41,6 +41,12 @@ public sealed class LootEditState
/// <summary>Profiles in the loot folder, for the picker.</summary>
public List<LootEditFile> Files { get; set; } = new();
public List<LootEditRow> Rules { get; set; } = new();
/// <summary>
/// The "Add to loot profile" popup's rule (item_preview / item_add), or null.
/// Added 2026-10; an older engine ignores it.
/// </summary>
public LootEditItemDraft? ItemDraft { get; set; }
}
public sealed class LootEditFile
@ -103,6 +109,67 @@ public sealed class LootEditCommand
/// <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>item_preview / item_add: the item and the popup's choices (added 2026-10).</summary>
public LootEditItemRequest? Item { get; set; }
}
/// <summary>
/// "Add to loot profile" from a clicked item (added 2026-10): what the popup
/// asks for. item_preview builds the rule into LootEditState.ItemDraft;
/// item_add builds it and adds it to the profile (saved, RynthAi reloads it);
/// item_close drops the draft.
/// </summary>
public sealed class LootEditItemRequest
{
/// <summary>The item; 0 = the item selected in the game.</summary>
public uint ItemId { get; set; }
/// <summary>LootItemMatch: 0 name + class, 1 name only, 2 items like this.</summary>
public int Match { get; set; }
/// <summary>VTank action code (1 Keep, 2 Salvage, 3 Sell, 4 Read, 10 Keep #); 0 = the item's default.</summary>
public int Action { get; set; }
/// <summary>Keep # count; -1 = default (one full stack).</summary>
public int KeepCount { get; set; } = -1;
/// <summary>Empty = the default name ("Keep Copper Pea").</summary>
public string RuleName { get; set; } = string.Empty;
/// <summary>True: the profile open in the Loot Editor; false: the one RynthAi loots with.</summary>
public bool ToOpenProfile { get; set; }
/// <summary>Echoed in the draft so the popup knows the answer is to its latest ask.</summary>
public int Seq { get; set; }
}
/// <summary>The rule an item makes, as the popup shows it, and what happened when it was added.</summary>
public sealed class LootEditItemDraft
{
public int Seq { get; set; }
/// <summary>False: Error says why there is no rule (no item selected, read-only profile...).</summary>
public bool Ok { get; set; }
public string Error { get; set; } = string.Empty;
public uint ItemId { get; set; }
public string ItemName { get; set; } = string.Empty;
public string ClassName { get; set; } = string.Empty;
public bool Stackable { get; set; }
public string TargetPath { get; set; } = string.Empty;
public string TargetFile { get; set; } = string.Empty;
/// <summary>The target is the profile RynthAi loots with.</summary>
public bool TargetInUse { get; set; }
/// <summary>"utl" or "json".</summary>
public string Format { get; set; } = string.Empty;
/// <summary>What was built (the defaults filled in).</summary>
public int Match { get; set; }
public int Action { get; set; }
public int KeepCount { get; set; }
public string RuleName { get; set; } = string.Empty;
public string DefaultRuleName { get; set; } = string.Empty;
/// <summary>The rule in words: name, action, one line per condition (ASCII).</summary>
public List<string> Preview { get; set; } = new();
/// <summary>Where it goes (0-based) among RuleCount rules, and why there.</summary>
public int InsertAt { get; set; } = -1;
public int RuleCount { get; set; }
public string OrderNote { get; set; } = string.Empty;
public List<string> Notes { get; set; } = new();
/// <summary>item_add went through; Message says what was added where.</summary>
public bool Added { get; set; }
public string Message { get; set; } = string.Empty;
}
/// <summary>Names for the face's pickers. Sent once per plugin load.</summary>

View file

@ -0,0 +1,390 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.VTank;
namespace RynthCore.Loot.Editing;
// "Add to loot profile" from a clicked item (2026-10-04): the rule built from
// one item, in the VTank model (the native JSON format gets a converted copy),
// its preview text, and where it goes in the list. Pure data, no AC types:
// RynthAi fills LootItemFacts from its object cache and does the matching.
/// <summary>What RynthAi knows about one item, as plain numbers (no AC or plugin types).</summary>
public sealed class LootItemFacts
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
/// <summary>AcObjectClass (VTank/Decal numbering).</summary>
public int ObjectClass { get; set; }
public int StackSize { get; set; } = 1;
public int MaxStackSize { get; set; } = 1;
/// <summary>Int properties (STypeInt ids, the keys loot rules use). Missing = 0 / unknown.</summary>
public Dictionary<int, int> Ints { get; set; } = new();
/// <summary>Float properties (STypeFloat ids).</summary>
public Dictionary<int, double> Doubles { get; set; } = new();
/// <summary>The item's spell names (empty when none or not identified).</summary>
public List<string> Spells { get; set; } = new();
public bool Stackable => MaxStackSize > 1 || StackSize > 1;
public int Int(int key) => Ints.TryGetValue(key, out int v) ? v : 0;
public double Double(int key) => Doubles.TryGetValue(key, out double v) ? v : 0;
}
/// <summary>How the rule recognises the item.</summary>
public enum LootItemMatch
{
/// <summary>Exact name and object class (the default).</summary>
NameAndClass = 0,
/// <summary>Exact name only.</summary>
Name = 1,
/// <summary>"Items like this": the class plus key properties (material, workmanship, stats, spells); no name.</summary>
Like = 2,
}
public sealed class LootItemRuleOptions
{
public LootItemMatch Match { get; set; } = LootItemMatch.NameAndClass;
/// <summary>Null: the item's default action (Read for scrolls, Keep # for stacks, else Keep).</summary>
public VTankLootAction? Action { get; set; }
/// <summary>Keep # count; null: one full stack.</summary>
public int? KeepCount { get; set; }
/// <summary>Null or blank: "Keep Copper Pea" and the like.</summary>
public string? RuleName { get; set; }
}
/// <summary>A built rule, ready to preview and insert.</summary>
public sealed class LootItemRuleDraft
{
public VTankLootRule Rule { get; init; } = new();
public LootItemMatch Match { get; init; }
public VTankLootAction Action { get; init; }
public int KeepCount { get; init; }
public string DefaultName { get; init; } = string.Empty;
/// <summary>Things the player should know (a broad rule, spells left out...).</summary>
public List<string> Notes { get; init; } = new();
}
public static class LootItemRules
{
// Property ids (STypeInt / STypeFloat, as RynthAi's evaluators read them).
public const int KeyArmorLevel = 28, KeyEquipSlots = 9, KeyDamage = 44, KeyWeaponSkill = 48,
KeyWorkmanship = 105, KeyMaterial = 131, KeyWieldSkill = 159;
public const int KeyElementalDamageMod = 152;
/// <summary>The ratings TotalRatingsGE adds up (same list as both evaluators).</summary>
public static readonly int[] RatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 };
/// <summary>The int properties a "like this" rule can use: what RynthAi reads into LootItemFacts.</summary>
public static readonly int[] IntKeys =
{ KeyArmorLevel, KeyEquipSlots, KeyDamage, KeyWeaponSkill, KeyWorkmanship, KeyMaterial, KeyWieldSkill, 370, 371, 372, 373, 374, 375, 376, 379 };
public static readonly int[] DoubleKeys = { KeyElementalDamageMod };
/// <summary>Spell conditions a "like this" rule takes at most (all must match: more makes it narrower).</summary>
public const int MaxSpells = 4;
/// <summary>Read for spell scrolls, Keep # for anything that stacks, else Keep.</summary>
public static VTankLootAction DefaultAction(LootItemFacts f)
{
if (f.ObjectClass == (int)AcObjectClass.Scroll) return VTankLootAction.Read;
if (f.Stackable) return VTankLootAction.KeepUpTo;
return VTankLootAction.Keep;
}
/// <summary>Keep # default: one full stack (the item's own stack when the maximum isn't known).</summary>
public static int DefaultKeepCount(LootItemFacts f) => Math.Max(1, f.MaxStackSize > 1 ? f.MaxStackSize : f.StackSize);
/// <summary>
/// A name as an exact, case-insensitive regex: ^name$ with the regex
/// metacharacters escaped (spaces left alone, unlike Regex.Escape, so it reads well).
/// </summary>
public static string ExactPattern(string name)
{
var sb = new StringBuilder(name.Length + 8);
sb.Append('^');
foreach (char ch in name)
{
if ("\\*+?|{}[]()^$.#".IndexOf(ch) >= 0) sb.Append('\\');
sb.Append(ch);
}
sb.Append('$');
return sb.ToString();
}
public static string ClassName(int objectClass) =>
Enum.IsDefined(typeof(AcObjectClass), objectClass) ? ((AcObjectClass)objectClass).ToString() : "class " + objectClass.ToString(CultureInfo.InvariantCulture);
/// <summary>"Keep Copper Pea", "Keep 100 Copper Pea", "Salvage like Iron Mace".</summary>
public static string DefaultRuleName(string itemName, VTankLootAction action, int keepCount, LootItemMatch match)
{
string verb = action == VTankLootAction.KeepUpTo
? "Keep " + keepCount.ToString(CultureInfo.InvariantCulture)
: LootRuleText.ActionName(action);
return match == LootItemMatch.Like ? $"{verb} like {itemName}" : $"{verb} {itemName}";
}
/// <summary>Builds the rule. Null (and <paramref name="error"/>) when the item can't make one.</summary>
public static LootItemRuleDraft? Build(LootItemFacts f, LootItemRuleOptions o, out string error)
{
error = string.Empty;
string name = OneLine(f.Name).Trim();
if (name.Length == 0 && o.Match != LootItemMatch.Like)
{
error = "That item has no name yet; try again in a moment.";
return null;
}
VTankLootAction action = o.Action ?? DefaultAction(f);
if (!LootRuleText.IsKnownAction((int)action))
{
error = $"Unknown action {(int)action}.";
return null;
}
int keep = o.KeepCount ?? DefaultKeepCount(f);
if (action == VTankLootAction.KeepUpTo && keep < 0)
{
error = "Keep # needs a count of 0 or more.";
return null;
}
var notes = new List<string>();
var rule = new VTankLootRule
{
CustomExpression = string.Empty,
Action = action,
KeepCount = action == VTankLootAction.KeepUpTo ? keep : null,
};
bool hasClass = f.ObjectClass != (int)AcObjectClass.Unknown;
LootItemMatch match = o.Match;
if (match == LootItemMatch.NameAndClass && !hasClass)
{
match = LootItemMatch.Name;
notes.Add("The item's class isn't known yet, so the rule matches the name only.");
}
switch (match)
{
case LootItemMatch.NameAndClass:
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
rule.Conditions.Add(Cond(VTankNodeTypes.StringValueMatch, ExactPattern(name), "1"));
break;
case LootItemMatch.Name:
rule.Conditions.Add(Cond(VTankNodeTypes.StringValueMatch, ExactPattern(name), "1"));
break;
case LootItemMatch.Like:
if (!hasClass)
{
error = "The item's class isn't known yet; \"items like this\" needs it.";
return null;
}
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
int extra = AddLikeConditions(rule, f, notes);
if (extra == 0)
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
break;
}
string defaultName = DefaultRuleName(name.Length > 0 ? name : ClassName(f.ObjectClass), action, keep, match);
string ruleName = OneLine(o.RuleName).Trim();
rule.Name = ruleName.Length > 0 ? ruleName : defaultName;
return new LootItemRuleDraft { Rule = rule, Match = match, Action = action, KeepCount = keep, DefaultName = defaultName, Notes = notes };
}
/// <summary>The "like this" conditions for the item's kind; how many it added.</summary>
private static int AddLikeConditions(VTankLootRule rule, LootItemFacts f, List<string> notes)
{
int n = rule.Conditions.Count;
var cls = (AcObjectClass)f.ObjectClass;
void LongE(int key) { int v = f.Int(key); if (v != 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key))); }
void LongGE(int key) { int v = f.Int(key); if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); }
void DoubleGE(int key)
{
double v = f.Double(key);
if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyGE, v.ToString("0.####", CultureInfo.InvariantCulture), Num(key)));
}
LongE(KeyMaterial);
LongGE(KeyWorkmanship);
switch (cls)
{
case AcObjectClass.MeleeWeapon:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill);
LongGE(KeyDamage);
break;
case AcObjectClass.MissileWeapon:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill);
break;
case AcObjectClass.WandStaffOrb:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill);
DoubleGE(KeyElementalDamageMod);
break;
case AcObjectClass.Armor:
case AcObjectClass.Clothing:
LongE(KeyEquipSlots);
LongGE(KeyArmorLevel);
break;
case AcObjectClass.Jewelry:
LongE(KeyEquipSlots);
break;
}
int ratings = 0;
foreach (int k in RatingKeys) ratings += Math.Max(0, f.Int(k));
if (ratings > 0) rule.Conditions.Add(Cond(VTankNodeTypes.TotalRatingsGE, Num(ratings)));
int spells = 0;
foreach (string s in f.Spells)
{
string sn = OneLine(s).Trim();
if (sn.Length == 0) continue;
if (spells == MaxSpells)
{
notes.Add($"The item has more than {MaxSpells} spells; the rule checks the first {MaxSpells}.");
break;
}
rule.Conditions.Add(Cond(VTankNodeTypes.SpellNameMatch, ExactPattern(sn)));
spells++;
}
return rule.Conditions.Count - n;
}
private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines);
private static string Num(int v) => v.ToString(CultureInfo.InvariantCulture);
private static string OneLine(string? s) =>
string.IsNullOrEmpty(s) ? string.Empty : s.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
// =====================================================================
// Native (JSON) profiles
// =====================================================================
/// <summary>
/// The rule in the native format. Conditions it has no class for (spells)
/// are left out and named in <paramref name="dropped"/>; null when the rule
/// would end up with none of its conditions (it would match everything).
/// </summary>
public static LootRule? ToNative(VTankLootRule r, List<string> dropped)
{
var rule = new LootRule
{
Name = r.Name,
Enabled = r.Enabled,
Action = r.Action switch
{
VTankLootAction.Sell => LootAction.Sell,
VTankLootAction.Salvage => LootAction.Salvage,
VTankLootAction.Read => LootAction.Read,
VTankLootAction.KeepUpTo => LootAction.KeepUpTo,
_ => LootAction.Keep,
},
KeepCount = r.Action == VTankLootAction.KeepUpTo ? r.KeepCount ?? 0 : 1,
};
int wanted = 0;
foreach (VTankLootCondition c in r.Conditions)
{
if (c.NodeType == VTankNodeTypes.DisabledRule) continue;
wanted++;
LootCondition? n = NativeCondition(c);
if (n != null) rule.Conditions.Add(n);
else dropped.Add(LootRuleText.Condition(c));
}
return wanted > 0 && rule.Conditions.Count == 0 ? null : rule;
}
private static LootCondition? NativeCondition(VTankLootCondition c)
{
IList<string> d = c.DataLines;
int I(int i) => int.Parse(d[i], NumberStyles.Integer, CultureInfo.InvariantCulture);
double D(int i) => double.Parse(d[i], NumberStyles.Float, CultureInfo.InvariantCulture);
try
{
return c.NodeType switch
{
VTankNodeTypes.ObjectClass => new ObjectClassCondition { ObjectClass = (AcObjectClass)I(0) },
VTankNodeTypes.StringValueMatch => new StringValueCondition { Pattern = d[0], Key = I(1) },
VTankNodeTypes.LongValKeyE => new LongValKeyECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyNE => new LongValKeyNECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyGE => new LongValKeyGECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyLE => new LongValKeyLECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyFlagExists => new LongValKeyFlagCondition { FlagValue = I(0), Key = I(1) },
VTankNodeTypes.DoubleValKeyGE => new DoubleValKeyGECondition { Value = D(0), Key = I(1) },
VTankNodeTypes.DoubleValKeyLE => new DoubleValKeyLECondition { Value = D(0), Key = I(1) },
VTankNodeTypes.TotalRatingsGE => new TotalRatingsGECondition { Value = (int)Math.Ceiling(D(0)) },
VTankNodeTypes.MinDamageGE => new MinDamageGECondition { Value = D(0) },
_ => null,
};
}
catch (FormatException) { return null; }
catch (ArgumentOutOfRangeException) { return null; }
}
// =====================================================================
// Preview and placement
// =====================================================================
/// <summary>The rule as the popup shows it: name, action, one line per condition.</summary>
public static List<string> PreviewLines(VTankLootRule r)
{
var lines = new List<string>
{
"Rule: " + r.Name,
"Action: " + (r.Action == VTankLootAction.KeepUpTo
? "Keep # " + (r.KeepCount ?? 0).ToString(CultureInfo.InvariantCulture)
: LootRuleText.ActionName(r.Action)),
};
bool first = true;
foreach (VTankLootCondition c in r.Conditions)
{
if (c.NodeType == VTankNodeTypes.DisabledRule) continue;
lines.Add((first ? "If: " : "and ") + LootRuleText.Condition(c));
first = false;
}
if (first) lines.Add("If: (every item)");
return lines;
}
/// <summary>
/// Where the rule goes: just before the first rule that matches the item now
/// (rules run top to bottom and the first match wins, so this is the latest
/// spot where the new rule still decides the item, and it moves no other
/// rule's items but this item's look-alikes); the end when nothing matches it.
/// <paramref name="matches"/> says whether rule i matches the item.
/// </summary>
public static int ChooseIndex(int ruleCount, Func<int, bool> matches)
{
for (int i = 0; i < ruleCount; i++)
if (matches(i)) return i;
return ruleCount;
}
/// <summary>Same action (and count) and the same conditions in the same order, names aside.</summary>
public static bool SameRule(VTankLootRule a, VTankLootRule b)
{
if (a.Action != b.Action || a.Enabled != b.Enabled) return false;
if (a.Action == VTankLootAction.KeepUpTo && (a.KeepCount ?? 0) != (b.KeepCount ?? 0)) return false;
var ca = Live(a);
var cb = Live(b);
if (ca.Count != cb.Count) return false;
for (int i = 0; i < ca.Count; i++)
{
if (ca[i].NodeType != cb[i].NodeType || ca[i].DataLines.Count != cb[i].DataLines.Count) return false;
for (int j = 0; j < ca[i].DataLines.Count; j++)
if (!string.Equals(ca[i].DataLines[j].Trim(), cb[i].DataLines[j].Trim(), StringComparison.OrdinalIgnoreCase)) return false;
}
return true;
static List<VTankLootCondition> Live(VTankLootRule r) => r.Conditions.FindAll(c => c.NodeType != VTankNodeTypes.DisabledRule);
}
/// <summary>Native rules: same action (and count) and the same conditions, names aside.</summary>
public static bool SameRule(LootRule a, LootRule b)
{
if (a.Action != b.Action || a.Enabled != b.Enabled) return false;
if (a.Action == LootAction.KeepUpTo && a.KeepCount != b.KeepCount) return false;
if (a.Conditions.Count != b.Conditions.Count) return false;
for (int i = 0; i < a.Conditions.Count; i++)
if (!string.Equals(a.Conditions[i].ToString(), b.Conditions[i].ToString(), StringComparison.OrdinalIgnoreCase)) return false;
return true;
}
}

View file

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
namespace RynthCore.Loot.Editing;
/// <summary>
/// Adds one rule to a native (.json) loot profile by splicing its JSON into the
/// file's "Rules" array: every byte outside the insertion stays as it was
/// (LootProfile.Save would rewrite the whole file, and the JSON writer drops
/// what it doesn't know). The result is checked before it is returned: it must
/// load, have one more rule, and serialise exactly like the original once the
/// new rule is taken out again.
/// </summary>
public static class LootJsonSplice
{
/// <summary>
/// The file's bytes with <paramref name="rule"/> inserted at <paramref name="index"/>
/// (the end when out of range; <paramref name="at"/> says where it went), or
/// null with <paramref name="error"/>.
/// </summary>
public static byte[]? Insert(byte[] file, LootRule rule, int index, out int at, out string error)
{
at = -1;
error = string.Empty;
int start = file.Length >= 3 && file[0] == 0xEF && file[1] == 0xBB && file[2] == 0xBF ? 3 : 0;
LootProfile? before;
try
{
// Strict UTF-8: a file that isn't is refused rather than re-encoded.
string text = new UTF8Encoding(false, true).GetString(file, start, file.Length - start);
before = JsonSerializer.Deserialize(text, LootJsonContext.Default.LootProfile);
}
catch (Exception ex)
{
error = "the profile doesn't load as it is (" + ex.Message + ").";
return null;
}
if (before == null) { error = "the profile is empty (null)."; return null; }
if (!FindRules(file, start, out int open, out int close, out List<(int Start, int End)> elements, out error))
return null;
if (elements.Count != before.Rules.Count)
{
error = $"found {elements.Count} rules in the text but {before.Rules.Count} when loaded.";
return null;
}
string nl = Contains(file, start, "\r\n") ? "\r\n" : "\n";
string ruleJson = JsonSerializer.Serialize(rule, LootJsonContext.Default.LootRule).Replace("\r\n", "\n");
at = index < 0 || index > elements.Count ? elements.Count : index;
string insert;
int spliceAt, spliceEnd;
if (elements.Count == 0)
{
// "[]" or "[ ... ]" with only whitespace: replace the inside.
string outer = LineIndent(file, start, open);
string indent = outer + " ";
insert = nl + indent + Reindent(ruleJson, indent, nl) + nl + outer;
spliceAt = open + 1;
spliceEnd = close;
}
else
{
string indent = LineIndent(file, start, elements[0].Start);
if (at < elements.Count)
{
insert = Reindent(ruleJson, indent, nl) + "," + nl + indent;
spliceAt = spliceEnd = elements[at].Start;
}
else
{
insert = "," + nl + indent + Reindent(ruleJson, indent, nl);
spliceAt = spliceEnd = elements[^1].End;
}
}
byte[] add = Encoding.UTF8.GetBytes(insert);
var result = new byte[spliceAt + add.Length + (file.Length - spliceEnd)];
Array.Copy(file, 0, result, 0, spliceAt);
Array.Copy(add, 0, result, spliceAt, add.Length);
Array.Copy(file, spliceEnd, result, spliceAt + add.Length, file.Length - spliceEnd);
// Check: loads, one more rule, the new one where it should be, the rest unchanged.
try
{
LootProfile? after = JsonSerializer.Deserialize(Encoding.UTF8.GetString(result, start, result.Length - start), LootJsonContext.Default.LootProfile);
if (after == null || after.Rules.Count != before.Rules.Count + 1)
{
error = "the result doesn't have exactly one more rule.";
return null;
}
if (JsonSerializer.Serialize(after.Rules[at], LootJsonContext.Default.LootRule) != JsonSerializer.Serialize(rule, LootJsonContext.Default.LootRule))
{
error = "the new rule reads back differently.";
return null;
}
after.Rules.RemoveAt(at);
if (JsonSerializer.Serialize(after, LootJsonContext.Default.LootProfile) != JsonSerializer.Serialize(before, LootJsonContext.Default.LootProfile))
{
error = "another part of the profile would change.";
return null;
}
}
catch (Exception ex)
{
error = "the result doesn't load (" + ex.Message + ").";
return null;
}
return result;
}
/// <summary>Finds the root object's "Rules" array: its brackets and each element's byte range.</summary>
private static bool FindRules(byte[] file, int start, out int open, out int close, out List<(int Start, int End)> elements, out string error)
{
open = close = -1;
elements = new List<(int, int)>();
error = string.Empty;
var reader = new Utf8JsonReader(new ReadOnlySpan<byte>(file, start, file.Length - start));
bool found = false;
try
{
if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) { error = "the file isn't a JSON object."; return false; }
while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
{
if (!reader.ValueTextEquals("Rules"u8))
{
reader.Skip();
continue;
}
if (found) { error = "the file has two \"Rules\" lists."; return false; }
found = true;
if (!reader.Read() || reader.TokenType != JsonTokenType.StartArray) { error = "\"Rules\" isn't a list."; return false; }
open = start + (int)reader.TokenStartIndex;
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
int s = start + (int)reader.TokenStartIndex;
reader.Skip();
elements.Add((s, start + (int)reader.TokenStartIndex + 1));
}
close = start + (int)reader.TokenStartIndex;
}
}
catch (JsonException ex)
{
error = "the file isn't valid JSON (" + ex.Message + ").";
return false;
}
if (!found) { error = "the file has no \"Rules\" list."; return false; }
return true;
}
/// <summary>The spaces/tabs from the start of the line holding <paramref name="pos"/> up to the first other character.</summary>
private static string LineIndent(byte[] file, int start, int pos)
{
int lineStart = pos;
while (lineStart > start && file[lineStart - 1] != (byte)'\n') lineStart--;
int end = lineStart;
while (end < pos && (file[end] == (byte)' ' || file[end] == (byte)'\t')) end++;
return Encoding.ASCII.GetString(file, lineStart, end - lineStart);
}
/// <summary>The serializer's indented JSON (LF) shifted right by <paramref name="indent"/> after its first line.</summary>
private static string Reindent(string json, string indent, string nl) => json.Replace("\n", nl + indent);
private static bool Contains(byte[] file, int start, string ascii)
{
byte[] needle = Encoding.ASCII.GetBytes(ascii);
return new ReadOnlySpan<byte>(file, start, file.Length - start).IndexOf(needle) >= 0;
}
}

View file

@ -40,13 +40,14 @@ public static class LootRuleText
public static readonly (int Id, string Name)[] LongKeys =
{
(5, "EncumbVal"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (45, "DamageType"),
(5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (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"),
(0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id
};
public static readonly (int Id, string Name)[] DoubleKeys =