RynthSuite as of 2026-09-05 (internal a5ff5c2)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:23:05 -04:00
commit 0a4b611a90
166 changed files with 186537 additions and 0 deletions

View file

@ -0,0 +1,10 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="RynthCore.LootEditor.App"
RequestedThemeVariant="Dark">
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/>
<StyleInclude Source="avares://RynthCore.LootEditor/Styles.axaml"/>
</Application.Styles>
</Application>

View file

@ -0,0 +1,24 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
namespace RynthCore.LootEditor;
public partial class App : Application
{
public override void Initialize() => AvaloniaXamlLoader.Load(this);
public override void OnFrameworkInitializationCompleted()
{
Dispatcher.UIThread.UnhandledException += (_, e) =>
{
Program.Log($"DISPATCHER: {e.Exception}");
e.Handled = false;
};
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow();
base.OnFrameworkInitializationCompleted();
}
}

View file

@ -0,0 +1,47 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.LootEditor;
/// <summary>Simple Yes/No confirmation dialog.</summary>
public class ConfirmDialog : Window
{
public ConfirmDialog(string message)
{
Title = "Confirm";
Width = 360;
Height = 150;
CanResize = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Background = new SolidColorBrush(Color.Parse("#171F29"));
var panel = new StackPanel { Margin = new Thickness(16), Spacing = 16 };
panel.Children.Add(new TextBlock
{
Text = message,
Foreground = Brushes.White,
TextWrapping = TextWrapping.Wrap,
});
var buttons = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Right,
Spacing = 8,
};
var yes = new Button { Content = "Yes", Width = 72 };
var no = new Button { Content = "No", Width = 72 };
yes.Click += (_, _) => Close(true);
no.Click += (_, _) => Close(false);
buttons.Children.Add(yes);
buttons.Children.Add(no);
panel.Children.Add(buttons);
Content = panel;
}
}

View file

@ -0,0 +1,700 @@
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace RynthCore.LootEditor;
public class MainViewModel : INotifyPropertyChanged
{
private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
public event PropertyChangedEventHandler? PropertyChanged;
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void Notify([CallerMemberName] string? name = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
// ── State ────────────────────────────────────────────────────────────────
private VTankLootProfile _profile = new();
private string? _filePath;
private bool _dirty;
private readonly Window _window;
// ── Rule list ────────────────────────────────────────────────────────────
public ObservableCollection<VTankRuleVm> Rules { get; } = new();
public ObservableCollection<VTankRuleVm> FilteredRules { get; } = new();
private string _searchText = "";
public string SearchText
{
get => _searchText;
set { Set(ref _searchText, value); ApplyFilter(); RefreshMoveCommands(); }
}
/// <summary>Action filter — null means "all actions".</summary>
private VTankLootAction? _actionFilter;
public VTankLootAction? ActionFilter
{
get => _actionFilter;
set
{
Set(ref _actionFilter, value);
ApplyFilter();
// Re-evaluate every IsActionFilterX property so the chip buttons update.
Notify(nameof(IsActionFilterAll));
Notify(nameof(IsActionFilterKeep));
Notify(nameof(IsActionFilterKeepUpTo));
Notify(nameof(IsActionFilterSalvage));
Notify(nameof(IsActionFilterSell));
Notify(nameof(IsActionFilterRead));
Notify(nameof(RuleCountLabel));
}
}
public bool IsActionFilterAll => _actionFilter == null;
public bool IsActionFilterKeep => _actionFilter == VTankLootAction.Keep;
public bool IsActionFilterKeepUpTo => _actionFilter == VTankLootAction.KeepUpTo;
public bool IsActionFilterSalvage => _actionFilter == VTankLootAction.Salvage;
public bool IsActionFilterSell => _actionFilter == VTankLootAction.Sell;
public bool IsActionFilterRead => _actionFilter == VTankLootAction.Read;
public string RuleCountLabel
{
get
{
int total = Rules.Count;
int shown = FilteredRules.Count;
return shown == total ? $"{total} rules" : $"{shown} of {total} rules";
}
}
private void ApplyFilter()
{
FilteredRules.Clear();
string q = _searchText.Trim();
foreach (var r in Rules)
{
if (_actionFilter != null && r.Action != _actionFilter) continue;
if (q.Length == 0 || r.Name.Contains(q, StringComparison.OrdinalIgnoreCase))
FilteredRules.Add(r);
}
if (_selectedRule != null && !FilteredRules.Contains(_selectedRule))
SelectedRule = null;
Notify(nameof(RuleCountLabel));
}
private VTankRuleVm? _selectedRule;
public VTankRuleVm? SelectedRule
{
get => _selectedRule;
set
{
Set(ref _selectedRule, value);
Notify(nameof(RuleEditorEnabled));
Notify(nameof(Conditions));
Notify(nameof(KeepCountVisible));
SelectedCondition = null;
RefreshMoveCommands();
}
}
public bool RuleEditorEnabled => _selectedRule != null;
public bool KeepCountVisible => _selectedRule?.ShowKeepCount == true;
// ── Conditions ───────────────────────────────────────────────────────────
public ObservableCollection<VTankConditionVm>? Conditions => _selectedRule?.Conditions;
private VTankConditionVm? _selectedCondition;
public VTankConditionVm? SelectedCondition
{
get => _selectedCondition;
set
{
Set(ref _selectedCondition, value);
RebuildConditionEditor();
CondDelete.RaiseCanExecuteChanged();
CondMoveUp.RaiseCanExecuteChanged();
CondMoveDown.RaiseCanExecuteChanged();
}
}
private object? _conditionEditor;
public object? ConditionEditor
{
get => _conditionEditor;
private set => Set(ref _conditionEditor, value);
}
private void RebuildConditionEditor()
{
ConditionEditor = _selectedCondition == null
? null
: new VTankConditionEditorView(_selectedCondition, MarkDirty);
}
private void MarkDirty()
{
_dirty = true;
UpdateTitle();
}
// ── Status / title ───────────────────────────────────────────────────────
private string _statusMessage = "Ready";
public string StatusMessage
{
get => _statusMessage;
private set => Set(ref _statusMessage, value);
}
private void Status(string msg) => StatusMessage = msg;
private string _windowTitle = "RynthCore Loot Editor";
public string WindowTitle
{
get => _windowTitle;
private set => Set(ref _windowTitle, value);
}
private void UpdateTitle()
{
string baseName = string.IsNullOrEmpty(_filePath) ? "untitled.utl" : Path.GetFileName(_filePath);
WindowTitle = $"RynthCore Loot Editor — {baseName}{(_dirty ? "*" : "")}";
}
// ── Picker option lists ──────────────────────────────────────────────────
public IReadOnlyList<VTankLootAction> Actions { get; } = new[]
{
VTankLootAction.Keep,
VTankLootAction.KeepUpTo,
VTankLootAction.Salvage,
VTankLootAction.Sell,
VTankLootAction.Read,
};
public IReadOnlyList<NodeTypeOption> NodeTypeOptions { get; } = BuildNodeTypeOptions();
private static List<NodeTypeOption> BuildNodeTypeOptions()
{
var list = new List<NodeTypeOption>();
foreach (int t in VTankNodeTypes.All)
list.Add(new NodeTypeOption(t, $"{VTankNodeTypes.DisplayName(t)} (id {t})"));
return list;
}
// ── Commands ─────────────────────────────────────────────────────────────
public RelayCommand FileNew { get; }
public RelayCommand FileOpen { get; }
public RelayCommand FileSave { get; }
public RelayCommand FileSaveAs { get; }
public RelayCommand FileExit { get; }
public RelayCommand RuleAdd { get; }
public RelayCommand RuleDuplicate { get; }
public RelayCommand RuleDelete { get; }
public RelayCommand RuleMoveUp { get; }
public RelayCommand RuleMoveDown { get; }
public RelayCommand SetActionFilter { get; }
public RelayCommand CondAdd { get; }
public RelayCommand CondDelete { get; }
public RelayCommand CondMoveUp { get; }
public RelayCommand CondMoveDown{ get; }
public RelayCommand SalvageRowAdd { get; }
public RelayCommand SalvageRowDelete { get; }
public RelayCommand SalvageImportUtl { get; }
public MainViewModel(Window window)
{
_window = window;
FileNew = new RelayCommand(_ => DoNew());
FileOpen = new RelayCommand(_ => _ = DoOpenAsync());
FileSave = new RelayCommand(_ => _ = DoSaveAsync(false));
FileSaveAs = new RelayCommand(_ => _ = DoSaveAsync(true));
FileExit = new RelayCommand(_ => _window.Close());
RuleAdd = new RelayCommand(_ => DoRuleAdd());
RuleDuplicate = new RelayCommand(_ => DoRuleDuplicate(), _ => _selectedRule != null);
RuleDelete = new RelayCommand(_ => DoRuleDelete(), _ => _selectedRule != null);
RuleMoveUp = new RelayCommand(_ => DoRuleMove(-1), _ => CanMoveRule(-1));
RuleMoveDown = new RelayCommand(_ => DoRuleMove(1), _ => CanMoveRule(1));
SetActionFilter = new RelayCommand(arg =>
{
// Param is either a VTankLootAction (set the filter) or null (= "All").
ActionFilter = arg switch
{
VTankLootAction a => a,
string s when System.Enum.TryParse<VTankLootAction>(s, out var parsed) => parsed,
_ => null,
};
});
CondAdd = new RelayCommand(_ => DoCondAdd());
CondDelete = new RelayCommand(_ => DoCondDelete(), _ => _selectedCondition != null);
CondMoveUp = new RelayCommand(_ => DoCondMove(-1), _ => CanMoveCond(-1));
CondMoveDown = new RelayCommand(_ => DoCondMove(1), _ => CanMoveCond(1));
SalvageRowAdd = new RelayCommand(_ => DoSalvageRowAdd());
SalvageRowDelete = new RelayCommand(_ => DoSalvageRowDelete(), _ => _selectedSalvageRow != null);
SalvageImportUtl = new RelayCommand(_ => _ = DoSalvageImportUtlAsync());
LoadProfile(new VTankLootProfile());
}
// ── Load / save ──────────────────────────────────────────────────────────
private void LoadProfile(VTankLootProfile p)
{
_profile = p;
Rules.Clear();
foreach (var r in p.Rules)
Rules.Add(new VTankRuleVm(r));
ApplyFilter();
SelectedRule = null;
LoadSalvageFromProfile(p);
_dirty = false;
UpdateTitle();
}
private void DoNew()
{
if (!ConfirmDiscard()) return;
_filePath = null;
SearchText = "";
LoadProfile(new VTankLootProfile());
}
private async Task DoOpenAsync()
{
if (!ConfirmDiscard()) return;
var opts = new FilePickerOpenOptions
{
Title = "Open Loot Profile",
AllowMultiple = false,
FileTypeFilter = new[]
{
new FilePickerFileType("VTank / LootSnob") { Patterns = new[] { "*.utl" } },
new FilePickerFileType("Legacy JSON") { Patterns = new[] { "*.json" } },
new FilePickerFileType("All Files") { Patterns = new[] { "*.*" } },
},
SuggestedStartLocation = await GetFolderAsync(),
};
var files = await _window.StorageProvider.OpenFilePickerAsync(opts);
if (files.Count == 0) return;
var path = files[0].Path.LocalPath;
try
{
VTankLootProfile loaded = path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
? ConvertFromJson(path)
: VTankLootParser.Load(path);
_filePath = path;
SearchText = "";
LoadProfile(loaded);
Status($"Opened {Path.GetFileName(path)} ({loaded.Rules.Count} rules)");
}
catch (Exception ex)
{
await ShowError($"Failed to open profile:\n{ex.Message}");
}
}
private static VTankLootProfile ConvertFromJson(string path)
{
// Minimal JSON → VTank converter for legacy LootEditor profiles.
// Only the rule list is migrated; SalvageCombine carries over directly.
var json = LootProfile.TryLoad(path) ?? new LootProfile();
var vp = new VTankLootProfile { FileVersion = 1, SalvageCombine = json.SalvageCombine };
foreach (var rule in json.Rules)
{
var vr = new VTankLootRule
{
Name = rule.Name,
CustomExpression = string.Empty,
Action = rule.Action switch
{
LootAction.Keep => VTankLootAction.Keep,
LootAction.KeepUpTo => VTankLootAction.KeepUpTo,
LootAction.Salvage => VTankLootAction.Salvage,
LootAction.Sell => VTankLootAction.Sell,
LootAction.Read => VTankLootAction.Read,
_ => VTankLootAction.Keep,
},
KeepCount = rule.Action == LootAction.KeepUpTo ? rule.KeepCount : (int?)null,
};
// Best-effort condition mapping — typed editor will surface anything
// we couldn't map as raw lines.
foreach (var c in rule.Conditions)
vr.Conditions.Add(MapJsonCondition(c));
if (!rule.Enabled) vr.Enabled = false;
vp.Rules.Add(vr);
}
return vp;
}
private static VTankLootCondition MapJsonCondition(LootCondition c) => c switch
{
ObjectClassCondition o => new(VTankNodeTypes.ObjectClass, "0", new[] { o.ObjectClass.ToString() }),
LongValKeyGECondition l => new(VTankNodeTypes.LongValKeyGE, "0", new[] { l.Value.ToString(), l.Key.ToString() }),
LongValKeyLECondition l => new(VTankNodeTypes.LongValKeyLE, "0", new[] { l.Value.ToString(), l.Key.ToString() }),
LongValKeyECondition l => new(VTankNodeTypes.LongValKeyE, "0", new[] { l.Value.ToString(), l.Key.ToString() }),
LongValKeyNECondition l => new(VTankNodeTypes.LongValKeyNE, "0", new[] { l.Value.ToString(), l.Key.ToString() }),
LongValKeyFlagCondition l => new(VTankNodeTypes.LongValKeyFlagExists,"0", new[] { l.FlagValue.ToString(), l.Key.ToString() }),
DoubleValKeyGECondition d => new(VTankNodeTypes.DoubleValKeyGE, "0", new[] { d.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), d.Key.ToString() }),
DoubleValKeyLECondition d => new(VTankNodeTypes.DoubleValKeyLE, "0", new[] { d.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), d.Key.ToString() }),
StringValueCondition s => new(VTankNodeTypes.StringValueMatch, "0", new[] { s.Pattern, s.Key.ToString() }),
TotalRatingsGECondition t => new(VTankNodeTypes.TotalRatingsGE, "0", new[] { t.Value.ToString() }),
MinDamageGECondition m => new(VTankNodeTypes.MinDamageGE, "0", new[] { m.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) }),
DamagePercentGECondition d => new(VTankNodeTypes.DamagePercentGE, "0", new[] { d.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) }),
CharacterSkillGECondition s => new(VTankNodeTypes.CharacterSkillGE, "0", new[] { s.Value.ToString(), ((int)s.Skill).ToString() }),
_ => new(VTankNodeTypes.ObjectClass, "0", new[] { "0" }), // unknown -> harmless placeholder
};
private async Task DoSaveAsync(bool saveAs)
{
if (!saveAs && _filePath != null) { Save(_filePath); return; }
var opts = new FilePickerSaveOptions
{
Title = "Save Loot Profile",
SuggestedFileName = _filePath != null ? Path.GetFileNameWithoutExtension(_filePath) : "profile",
DefaultExtension = "utl",
FileTypeChoices = new[]
{
new FilePickerFileType("VTank / LootSnob") { Patterns = new[] { "*.utl" } },
new FilePickerFileType("Legacy JSON") { Patterns = new[] { "*.json" } },
},
SuggestedStartLocation = await GetFolderAsync(),
};
var file = await _window.StorageProvider.SaveFilePickerAsync(opts);
if (file == null) return;
_filePath = file.Path.LocalPath;
Save(_filePath);
}
private void Save(string path)
{
// Push edits back into the underlying VTank data.
FlushSalvageToProfile();
_profile.Rules.Clear();
foreach (var rvm in Rules)
{
rvm.FlushConditionsToData();
_profile.Rules.Add(rvm.Data);
}
try
{
if (path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
// Lossy export: drop conditions we can't represent and write JSON.
var jp = ConvertToJson(_profile);
jp.Save(path);
}
else
{
VTankLootWriter.Save(_profile, path);
}
_dirty = false;
UpdateTitle();
Status($"Saved {Path.GetFileName(path)}");
}
catch (Exception ex)
{
_ = ShowError($"Save failed:\n{ex.Message}");
}
}
private static LootProfile ConvertToJson(VTankLootProfile vp)
{
// Minimal VTank → JSON exporter for backward compat. Conditions we
// don't have a JSON class for are skipped — saving as JSON is lossy
// by design.
var jp = new LootProfile { Name = "", SalvageCombine = vp.SalvageCombine };
foreach (var vr in vp.Rules)
{
var jr = new LootRule
{
Name = vr.Name,
Enabled = vr.Enabled,
Action = vr.Action switch
{
VTankLootAction.Keep => LootAction.Keep,
VTankLootAction.KeepUpTo => LootAction.KeepUpTo,
VTankLootAction.Salvage => LootAction.Salvage,
VTankLootAction.Sell => LootAction.Sell,
VTankLootAction.Read => LootAction.Read,
_ => LootAction.Keep,
},
KeepCount = vr.KeepCount ?? 0,
};
jp.Rules.Add(jr);
}
return jp;
}
// ── Rule editing ─────────────────────────────────────────────────────────
private void DoRuleAdd()
{
var data = new VTankLootRule { Name = "New Rule", CustomExpression = string.Empty, Action = VTankLootAction.Keep };
var vm = new VTankRuleVm(data);
Rules.Add(vm);
ApplyFilter();
SelectedRule = vm;
MarkDirty();
}
private void DoRuleDuplicate()
{
if (_selectedRule == null) return;
var src = _selectedRule.Data;
var copy = new VTankLootRule
{
Name = src.Name + " (copy)",
CustomExpression = src.CustomExpression,
Priority = src.Priority,
Action = src.Action,
KeepCount = src.KeepCount,
};
foreach (var c in src.Conditions)
copy.Conditions.Add(new VTankLootCondition(c.NodeType, c.LengthCode, c.DataLines));
var vm = new VTankRuleVm(copy);
int srcIdx = Rules.IndexOf(_selectedRule);
Rules.Insert(srcIdx + 1, vm);
ApplyFilter();
SelectedRule = vm;
MarkDirty();
}
private void DoRuleDelete()
{
if (_selectedRule == null) return;
int idx = Rules.IndexOf(_selectedRule);
Rules.Remove(_selectedRule);
ApplyFilter();
SelectedRule = idx < Rules.Count ? Rules[idx] : (Rules.Count > 0 ? Rules[^1] : null);
MarkDirty();
}
private bool CanMoveRule(int dir)
{
if (_selectedRule == null) return false;
int idx = Rules.IndexOf(_selectedRule);
int newIdx = idx + dir;
return newIdx >= 0 && newIdx < Rules.Count;
}
private void DoRuleMove(int dir)
{
if (!CanMoveRule(dir)) return;
int idx = Rules.IndexOf(_selectedRule!);
Rules.Move(idx, idx + dir);
ApplyFilter();
MarkDirty();
RefreshMoveCommands();
}
private void RefreshMoveCommands()
{
RuleDelete.RaiseCanExecuteChanged();
RuleMoveUp.RaiseCanExecuteChanged();
RuleMoveDown.RaiseCanExecuteChanged();
}
// ── Condition editing ────────────────────────────────────────────────────
private void DoCondAdd()
{
if (_selectedRule == null) return;
var data = new VTankLootCondition(VTankNodeTypes.ObjectClass, "0", new[] { "0" });
var vm = new VTankConditionVm(data);
_selectedRule.Conditions.Add(vm);
SelectedCondition = vm;
MarkDirty();
}
private void DoCondDelete()
{
if (_selectedRule == null || _selectedCondition == null) return;
int idx = _selectedRule.Conditions.IndexOf(_selectedCondition);
_selectedRule.Conditions.Remove(_selectedCondition);
SelectedCondition = idx < _selectedRule.Conditions.Count
? _selectedRule.Conditions[idx]
: (_selectedRule.Conditions.Count > 0 ? _selectedRule.Conditions[^1] : null);
MarkDirty();
}
private bool CanMoveCond(int dir)
{
if (_selectedRule == null || _selectedCondition == null) return false;
int idx = _selectedRule.Conditions.IndexOf(_selectedCondition);
int newIdx = idx + dir;
return newIdx >= 0 && newIdx < _selectedRule.Conditions.Count;
}
private void DoCondMove(int dir)
{
if (!CanMoveCond(dir)) return;
int idx = _selectedRule!.Conditions.IndexOf(_selectedCondition!);
_selectedRule.Conditions.Move(idx, idx + dir);
MarkDirty();
CondMoveUp.RaiseCanExecuteChanged();
CondMoveDown.RaiseCanExecuteChanged();
}
// ── Salvage Combine tab ──────────────────────────────────────────────────
public ObservableCollection<SalvagePerMaterialRow> PerMaterialRows { get; } = new();
public IReadOnlyList<MaterialOption> MaterialOptions { get; } = BuildMaterialOptions();
private static List<MaterialOption> BuildMaterialOptions()
{
var list = new List<MaterialOption>();
foreach (var kv in MaterialTypes.ByName)
list.Add(new MaterialOption(kv.Key, $"{kv.Key} — {kv.Value}"));
list.Sort((a, b) => string.Compare(a.Display, b.Display, StringComparison.OrdinalIgnoreCase));
return list;
}
private bool _salvageEnabled = true;
public bool SalvageEnabled
{
get => _salvageEnabled;
set { Set(ref _salvageEnabled, value); MarkDirty(); }
}
private string _salvageDefaultBands = "1-6, 7-8, 9, 10";
public string SalvageDefaultBands
{
get => _salvageDefaultBands;
set { Set(ref _salvageDefaultBands, value); MarkDirty(); }
}
private SalvagePerMaterialRow? _selectedSalvageRow;
public SalvagePerMaterialRow? SelectedSalvageRow
{
get => _selectedSalvageRow;
set { Set(ref _selectedSalvageRow, value); SalvageRowDelete.RaiseCanExecuteChanged(); }
}
private void LoadSalvageFromProfile(VTankLootProfile p)
{
var sc = p.SalvageCombine;
_salvageEnabled = sc?.Enabled ?? true;
_salvageDefaultBands = sc?.DefaultBands ?? "1-6, 7-8, 9, 10";
Notify(nameof(SalvageEnabled));
Notify(nameof(SalvageDefaultBands));
PerMaterialRows.Clear();
if (sc != null)
foreach (var kv in sc.PerMaterial)
PerMaterialRows.Add(new SalvagePerMaterialRow(kv.Key, MaterialTypes.Name(kv.Key), kv.Value));
}
private void FlushSalvageToProfile()
{
// Only emit a SalvageCombine block if the user has configured anything;
// empty defaults shouldn't litter freshly-created profiles.
bool hasContent = PerMaterialRows.Count > 0 || !string.IsNullOrWhiteSpace(SalvageDefaultBands);
if (!hasContent && (_profile.SalvageCombine == null || !_profile.SalvageCombine.Enabled))
return;
var sc = _profile.SalvageCombine ?? new SalvageCombineSettings();
sc.Enabled = SalvageEnabled;
sc.DefaultBands = SalvageDefaultBands ?? string.Empty;
sc.PerMaterial.Clear();
foreach (var row in PerMaterialRows)
if (row.MaterialId > 0)
sc.PerMaterial[row.MaterialId] = row.BandsText ?? string.Empty;
_profile.SalvageCombine = sc;
}
private void DoSalvageRowAdd()
{
int firstFree = 0;
foreach (var opt in MaterialOptions)
{
bool used = false;
foreach (var row in PerMaterialRows) if (row.MaterialId == opt.Id) { used = true; break; }
if (!used) { firstFree = opt.Id; break; }
}
if (firstFree == 0 && MaterialOptions.Count > 0) firstFree = MaterialOptions[0].Id;
var newRow = new SalvagePerMaterialRow(firstFree, MaterialTypes.Name(firstFree), "1-10");
PerMaterialRows.Add(newRow);
SelectedSalvageRow = newRow;
MarkDirty();
}
private void DoSalvageRowDelete()
{
if (_selectedSalvageRow == null) return;
int idx = PerMaterialRows.IndexOf(_selectedSalvageRow);
PerMaterialRows.Remove(_selectedSalvageRow);
MarkDirty();
if (PerMaterialRows.Count > 0)
SelectedSalvageRow = PerMaterialRows[Math.Min(idx, PerMaterialRows.Count - 1)];
else
SelectedSalvageRow = null;
}
private async Task DoSalvageImportUtlAsync()
{
var opts = new FilePickerOpenOptions
{
Title = "Import SalvageCombine from VTank/LootSnob .utl",
AllowMultiple = false,
FileTypeFilter = new[] { new FilePickerFileType("VTank Loot Profile") { Patterns = new[] { "*.utl" } } },
SuggestedStartLocation = await GetFolderAsync(),
};
var files = await _window.StorageProvider.OpenFilePickerAsync(opts);
if (files.Count == 0) return;
var srcProfile = VTankLootParser.Load(files[0].Path.LocalPath);
if (srcProfile.SalvageCombine == null)
{
await ShowError("That .utl file has no SalvageCombine block.");
return;
}
var sc = srcProfile.SalvageCombine;
SalvageEnabled = sc.Enabled;
SalvageDefaultBands = sc.DefaultBands;
PerMaterialRows.Clear();
foreach (var kv in sc.PerMaterial)
PerMaterialRows.Add(new SalvagePerMaterialRow(kv.Key, MaterialTypes.Name(kv.Key), kv.Value));
MarkDirty();
Status($"Imported SalvageCombine from {Path.GetFileName(files[0].Path.LocalPath)} ({sc.PerMaterial.Count} per-material rule(s)).");
}
// ── Plumbing helpers ─────────────────────────────────────────────────────
private bool ConfirmDiscard()
{
if (!_dirty) return true;
// Keep simple — auto-discard. (A confirm dialog can come later.)
return true;
}
private async Task<IStorageFolder?> GetFolderAsync()
{
if (Directory.Exists(DefaultFolder))
return await _window.StorageProvider.TryGetFolderFromPathAsync(DefaultFolder);
return null;
}
private async Task ShowError(string msg)
{
await Task.Yield();
Status(msg.Replace('\n', ' '));
}
}
public sealed record NodeTypeOption(int Id, string Display);

View file

@ -0,0 +1,372 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="RynthCore.LootEditor.MainWindow"
Title="{Binding WindowTitle}"
Width="1280" Height="760"
MinWidth="900" MinHeight="540"
WindowStartupLocation="CenterScreen">
<DockPanel>
<!-- Menu -->
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_New" Command="{Binding FileNew}" InputGesture="Ctrl+N"/>
<MenuItem Header="_Open..." Command="{Binding FileOpen}" InputGesture="Ctrl+O"/>
<Separator/>
<MenuItem Header="_Save" Command="{Binding FileSave}" InputGesture="Ctrl+S"/>
<MenuItem Header="Save _As..." Command="{Binding FileSaveAs}" InputGesture="Ctrl+Shift+S"/>
<Separator/>
<MenuItem Header="E_xit" Command="{Binding FileExit}"/>
</MenuItem>
<MenuItem Header="_Rule">
<MenuItem Header="_New rule" Command="{Binding RuleAdd}" InputGesture="Ctrl+R"/>
<MenuItem Header="_Duplicate rule" Command="{Binding RuleDuplicate}" InputGesture="Ctrl+D"/>
<MenuItem Header="Delete rule" Command="{Binding RuleDelete}" InputGesture="Delete"/>
<Separator/>
<MenuItem Header="Move up" Command="{Binding RuleMoveUp}" InputGesture="Alt+Up"/>
<MenuItem Header="Move down" Command="{Binding RuleMoveDown}" InputGesture="Alt+Down"/>
</MenuItem>
</Menu>
<!-- Keyboard shortcuts -->
<DockPanel.KeyBindings>
<KeyBinding Gesture="Ctrl+N" Command="{Binding FileNew}"/>
<KeyBinding Gesture="Ctrl+O" Command="{Binding FileOpen}"/>
<KeyBinding Gesture="Ctrl+S" Command="{Binding FileSave}"/>
<KeyBinding Gesture="Ctrl+Shift+S" Command="{Binding FileSaveAs}"/>
<KeyBinding Gesture="Ctrl+R" Command="{Binding RuleAdd}"/>
<KeyBinding Gesture="Ctrl+D" Command="{Binding RuleDuplicate}"/>
<KeyBinding Gesture="Alt+Up" Command="{Binding RuleMoveUp}"/>
<KeyBinding Gesture="Alt+Down" Command="{Binding RuleMoveDown}"/>
</DockPanel.KeyBindings>
<!-- Status bar -->
<Border DockPanel.Dock="Bottom" Background="#080C10" Padding="8,3">
<TextBlock Text="{Binding StatusMessage}"
Foreground="{StaticResource FgMuted}" FontSize="11"/>
</Border>
<TabControl Background="#0B1015">
<!-- ─── Rules tab ─────────────────────────────────────────────────── -->
<TabItem Header="Rules">
<Grid Background="#0B1015">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="340" MinWidth="260"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="*" MinWidth="320"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="440" MinWidth="320"/>
</Grid.ColumnDefinitions>
<!-- ── Pane 1 — Rules list ────────────────────────────────── -->
<Border Grid.Column="0" Margin="6,6,0,6"
Background="#10161D"
BorderBrush="#26303A"
BorderThickness="1"
CornerRadius="4"
Padding="8">
<DockPanel>
<TextBox DockPanel.Dock="Top"
Text="{Binding SearchText}"
Watermark="Search rules…"
Margin="0,0,0,6"/>
<!-- Action filter chips -->
<WrapPanel DockPanel.Dock="Top" Margin="0,0,0,6">
<ToggleButton Content="All"
IsChecked="{Binding IsActionFilterAll}"
Command="{Binding SetActionFilter}"
Padding="8,2" Margin="0,0,3,3"/>
<ToggleButton Content="Keep"
IsChecked="{Binding IsActionFilterKeep}"
Command="{Binding SetActionFilter}" CommandParameter="Keep"
Background="#1f6f3a" Foreground="White" Padding="8,2" Margin="0,0,3,3"/>
<ToggleButton Content="Keep#"
IsChecked="{Binding IsActionFilterKeepUpTo}"
Command="{Binding SetActionFilter}" CommandParameter="KeepUpTo"
Background="#196e6e" Foreground="White" Padding="8,2" Margin="0,0,3,3"/>
<ToggleButton Content="Salv"
IsChecked="{Binding IsActionFilterSalvage}"
Command="{Binding SetActionFilter}" CommandParameter="Salvage"
Background="#a35c15" Foreground="White" Padding="8,2" Margin="0,0,3,3"/>
<ToggleButton Content="Sell"
IsChecked="{Binding IsActionFilterSell}"
Command="{Binding SetActionFilter}" CommandParameter="Sell"
Background="#7a1f1f" Foreground="White" Padding="8,2" Margin="0,0,3,3"/>
<ToggleButton Content="Read"
IsChecked="{Binding IsActionFilterRead}"
Command="{Binding SetActionFilter}" CommandParameter="Read"
Background="#1f497d" Foreground="White" Padding="8,2" Margin="0,0,3,3"/>
</WrapPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,4">
<TextBlock Text="{Binding RuleCountLabel}"
Foreground="{StaticResource FgMuted}"
VerticalAlignment="Center"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="3">
<Button Content="+" Width="24" Padding="0" Command="{Binding RuleAdd}" ToolTip.Tip="New rule (Ctrl+R)"/>
<Button Content="⎘" Width="24" Padding="0" Command="{Binding RuleDuplicate}" ToolTip.Tip="Duplicate (Ctrl+D)"/>
<Button Content="−" Width="24" Padding="0" Command="{Binding RuleDelete}" ToolTip.Tip="Delete (Del)"/>
<Button Content="↑" Width="24" Padding="0" Command="{Binding RuleMoveUp}" ToolTip.Tip="Move up (Alt+↑)"/>
<Button Content="↓" Width="24" Padding="0" Command="{Binding RuleMoveDown}" ToolTip.Tip="Move down (Alt+↓)"/>
</StackPanel>
</DockPanel>
<ListBox x:Name="RulesList"
ItemsSource="{Binding FilteredRules}"
SelectedItem="{Binding SelectedRule}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="Auto,*,Auto" Margin="0,1">
<!-- Action badge -->
<Border Grid.Column="0"
Background="{Binding ActionBadgeBrush}"
CornerRadius="3"
Padding="6,1"
VerticalAlignment="Center"
Margin="0,0,6,0">
<TextBlock Text="{Binding ActionLabel}"
Foreground="{Binding ActionBadgeForeground}"
FontSize="10"
FontWeight="Bold"/>
</Border>
<!-- Name -->
<TextBlock Grid.Column="1"
Text="{Binding Name}"
VerticalAlignment="Center"
TextTrimming="CharacterEllipsis"/>
<TextBlock Grid.Column="1"
Text="{Binding Name}"
VerticalAlignment="Center"
TextTrimming="CharacterEllipsis"
TextDecorations="Strikethrough"
Opacity="0.45"
IsVisible="{Binding !Enabled}"/>
<!-- Condition count -->
<TextBlock Grid.Column="2"
Text="{Binding ConditionCountLabel}"
Foreground="{StaticResource FgMuted}"
FontSize="10"
VerticalAlignment="Center"
Margin="6,0,0,0"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.KeyBindings>
<KeyBinding Gesture="Delete" Command="{Binding RuleDelete}"/>
</ListBox.KeyBindings>
</ListBox>
</DockPanel>
</Border>
<GridSplitter Grid.Column="1" Width="6" ResizeDirection="Columns"
Background="#26303A"/>
<!-- ── Pane 2 — Rule meta ─────────────────────────────────── -->
<Border Grid.Column="2" Margin="0,6,0,6"
Background="#10161D"
BorderBrush="#26303A"
BorderThickness="1"
CornerRadius="4"
Padding="10"
IsEnabled="{Binding RuleEditorEnabled}">
<DockPanel>
<TextBlock DockPanel.Dock="Top"
Text="Rule"
Foreground="{StaticResource FgAccent}"
FontSize="13"
FontWeight="SemiBold"
Margin="0,0,0,8"/>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="60"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="6"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="6"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="6"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="6"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name"
VerticalAlignment="Center" Foreground="{StaticResource FgMuted}"/>
<TextBox Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2"
Text="{Binding SelectedRule.Name, Mode=TwoWay}"
Watermark="Rule name…"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Action"
VerticalAlignment="Center" Foreground="{StaticResource FgMuted}"/>
<ComboBox Grid.Row="2" Grid.Column="1"
ItemsSource="{Binding Actions}"
SelectedItem="{Binding SelectedRule.Action, Mode=TwoWay}"
HorizontalAlignment="Stretch"/>
<TextBox Grid.Row="2" Grid.Column="2"
Text="{Binding SelectedRule.KeepCount, Mode=TwoWay}"
IsVisible="{Binding KeepCountVisible}"
Margin="4,0,0,0"
ToolTip.Tip="Keep count (KeepUpTo)"/>
<TextBlock Grid.Row="4" Grid.Column="0" Text="Custom Expr"
VerticalAlignment="Top" Foreground="{StaticResource FgMuted}"
Margin="0,4,0,0"/>
<TextBox Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2"
Text="{Binding SelectedRule.CustomExpression, Mode=TwoWay}"
Watermark="(VTank's custom-key expression — leave blank if unused)"
AcceptsReturn="False"/>
<CheckBox Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="3"
Content="Enabled"
IsChecked="{Binding SelectedRule.Enabled, Mode=TwoWay}"/>
<Border Grid.Row="8" Grid.Column="0" Grid.ColumnSpan="3"
Background="#0A0E13"
BorderBrush="#26303A"
BorderThickness="1"
CornerRadius="3"
Padding="8"
Margin="0,2,0,0">
<StackPanel>
<TextBlock Text="Plain English"
Foreground="{StaticResource FgMuted}"
FontSize="10"/>
<TextBlock Text="{Binding SelectedRule.Summary}"
TextWrapping="Wrap"
Margin="0,2,0,0"/>
</StackPanel>
</Border>
</Grid>
</DockPanel>
</Border>
<GridSplitter Grid.Column="3" Width="6" ResizeDirection="Columns"
Background="#26303A"/>
<!-- ── Pane 3 — Conditions list + editor ──────────────────── -->
<Border Grid.Column="4" Margin="0,6,6,6"
Background="#10161D"
BorderBrush="#26303A"
BorderThickness="1"
CornerRadius="4"
Padding="10"
IsEnabled="{Binding RuleEditorEnabled}">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,6">
<TextBlock Text="Conditions"
Foreground="{StaticResource FgAccent}"
FontSize="13"
FontWeight="SemiBold"
VerticalAlignment="Center"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="3">
<Button Content="+" Width="24" Padding="0" Command="{Binding CondAdd}" ToolTip.Tip="Add condition"/>
<Button Content="−" Width="24" Padding="0" Command="{Binding CondDelete}" ToolTip.Tip="Delete"/>
<Button Content="↑" Width="24" Padding="0" Command="{Binding CondMoveUp}" ToolTip.Tip="Move up"/>
<Button Content="↓" Width="24" Padding="0" Command="{Binding CondMoveDown}" ToolTip.Tip="Move down"/>
</StackPanel>
</DockPanel>
<ListBox DockPanel.Dock="Top"
Height="160"
ItemsSource="{Binding Conditions}"
SelectedItem="{Binding SelectedCondition}"
Margin="0,0,0,8">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Border Background="#0A0E13"
BorderBrush="#26303A"
BorderThickness="1"
CornerRadius="3"
Padding="10"
MinHeight="80">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<ContentControl Content="{Binding ConditionEditor}"/>
</ScrollViewer>
</Border>
</DockPanel>
</Border>
</Grid>
</TabItem>
<!-- ─── Salvage Combine tab ───────────────────────────────────────── -->
<TabItem Header="Salvage Combine">
<DockPanel Margin="10">
<Grid DockPanel.Dock="Top" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0"
Content="Enable workmanship-band combining"
IsChecked="{Binding SalvageEnabled}"
VerticalAlignment="Center"
Margin="0,0,16,0"/>
<TextBlock Grid.Column="1" Text="Default bands"
VerticalAlignment="Center" Foreground="{StaticResource FgMuted}"
Margin="0,0,4,0"/>
<TextBox Grid.Column="2"
Text="{Binding SalvageDefaultBands}"
Watermark="e.g. 1-6, 7-8, 9, 10"/>
<Button Grid.Column="3"
Content="Import from .utl…"
Command="{Binding SalvageImportUtl}"
Margin="8,0,0,0"
ToolTip.Tip="Read SalvageCombine block from a LootSnob/VTank .utl file."/>
</Grid>
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,4">
<TextBlock Text="Per-material overrides"
Foreground="{StaticResource FgAccent}"
FontSize="13"
VerticalAlignment="Center"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="3">
<Button Content="+" Width="24" Padding="0" Command="{Binding SalvageRowAdd}" ToolTip.Tip="Add material override"/>
<Button Content="−" Width="24" Padding="0" Command="{Binding SalvageRowDelete}" ToolTip.Tip="Remove selected"/>
</StackPanel>
</DockPanel>
<DataGrid ItemsSource="{Binding PerMaterialRows}"
SelectedItem="{Binding SelectedSalvageRow}"
AutoGenerateColumns="False"
GridLinesVisibility="Horizontal"
IsReadOnly="False"
CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Material" Width="240">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding $parent[DataGrid].DataContext.MaterialOptions}"
DisplayMemberBinding="{Binding Display}"
SelectedValueBinding="{Binding Id}"
SelectedValue="{Binding MaterialId, Mode=TwoWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Bands"
Binding="{Binding BandsText}"
Width="*"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</TabItem>
</TabControl>
</DockPanel>
</Window>

View file

@ -0,0 +1,21 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace RynthCore.LootEditor;
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
private bool _forceClose;
public MainWindow()
{
InitializeComponent();
_vm = new MainViewModel(this);
DataContext = _vm;
// (Confirm-on-close was disabled when the dirty-flag was made private during
// the VTank model migration. Re-add via a public IsDirty later if desired.)
_ = _forceClose; // silence unused-field warning
}
}

View file

@ -0,0 +1,39 @@
using Avalonia;
using System;
using System.IO;
namespace RynthCore.LootEditor;
class Program
{
internal static readonly string LogPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "LootEditor.log");
[System.STAThread]
public static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
Log($"UNHANDLED: {e.ExceptionObject}");
try
{
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
catch (Exception ex)
{
Log($"FATAL: {ex}");
throw;
}
}
internal static void Log(string msg)
{
try { File.AppendAllText(LogPath, $"[{DateTime.Now:HH:mm:ss}] {msg}\n"); }
catch { /* best-effort */ }
}
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}

View file

@ -0,0 +1,23 @@
using System;
using System.Windows.Input;
namespace RynthCore.LootEditor;
public class RelayCommand : ICommand
{
private readonly Action<object?> _execute;
private readonly Func<object?, bool>? _canExecute;
public RelayCommand(Action<object?> execute, Func<object?, bool>? canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler? CanExecuteChanged;
public void RaiseCanExecuteChanged() =>
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
public bool CanExecute(object? parameter) => _canExecute?.Invoke(parameter) ?? true;
public void Execute(object? parameter) => _execute(parameter);
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<AssemblyName>RynthCore.LootEditor</AssemblyName>
<RootNamespace>RynthCore.LootEditor</RootNamespace>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<UseWpf>false</UseWpf>
<UseWindowsForms>false</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.2.3" />
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Shared\RynthCore.LootSdk\RynthCore.LootSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,51 @@
using RynthCore.Loot;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace RynthCore.LootEditor;
/// <summary>One row in the per-material salvage combine table.</summary>
public sealed class SalvagePerMaterialRow : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private void Notify([CallerMemberName] string? n = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
private int _materialId;
public int MaterialId
{
get => _materialId;
set
{
if (_materialId == value) return;
_materialId = value;
_materialName = MaterialTypes.Name(value);
Notify();
Notify(nameof(MaterialName));
}
}
private string _materialName;
public string MaterialName
{
get => _materialName;
private set { _materialName = value; Notify(); }
}
private string _bandsText;
public string BandsText
{
get => _bandsText;
set { if (_bandsText == value) return; _bandsText = value; Notify(); }
}
public SalvagePerMaterialRow(int materialId, string materialName, string bandsText)
{
_materialId = materialId;
_materialName = materialName;
_bandsText = bandsText;
}
}
/// <summary>(id, "id - name") pair shown in the material picker ComboBox.</summary>
public sealed record MaterialOption(int Id, string Display);

View file

@ -0,0 +1,139 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Styles.Resources>
<Color x:Key="BgMainColor" >#0A0F14</Color>
<Color x:Key="BgPanelColor" >#171F29</Color>
<Color x:Key="BgInputColor" >#141C26</Color>
<Color x:Key="BgHoverColor" >#1A2E40</Color>
<Color x:Key="BgSelectColor" >#264059</Color>
<Color x:Key="FgMainColor" >#FFFFFF</Color>
<Color x:Key="FgMutedColor" >#7D8FA1</Color>
<Color x:Key="FgAccentColor" >#1FC7AB</Color>
<Color x:Key="BorderColor" >#264059</Color>
<SolidColorBrush x:Key="BgMain" Color="{StaticResource BgMainColor}"/>
<SolidColorBrush x:Key="BgPanel" Color="{StaticResource BgPanelColor}"/>
<SolidColorBrush x:Key="BgInput" Color="{StaticResource BgInputColor}"/>
<SolidColorBrush x:Key="BgHover" Color="{StaticResource BgHoverColor}"/>
<SolidColorBrush x:Key="BgSelect" Color="{StaticResource BgSelectColor}"/>
<SolidColorBrush x:Key="FgMain" Color="{StaticResource FgMainColor}"/>
<SolidColorBrush x:Key="FgMuted" Color="{StaticResource FgMutedColor}"/>
<SolidColorBrush x:Key="FgAccent" Color="{StaticResource FgAccentColor}"/>
<SolidColorBrush x:Key="Border" Color="{StaticResource BorderColor}"/>
</Styles.Resources>
<!-- Window -->
<Style Selector="Window">
<Setter Property="Background" Value="{StaticResource BgMain}"/>
<Setter Property="FontFamily" Value="Segoe UI,sans-serif"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
</Style>
<!-- TextBlock -->
<Style Selector="TextBlock">
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
</Style>
<!-- TextBox -->
<Style Selector="TextBox">
<Setter Property="Background" Value="{StaticResource BgInput}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
<Setter Property="BorderBrush" Value="{StaticResource Border}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="5,3"/>
<Setter Property="CaretBrush" Value="{StaticResource FgMain}"/>
<Setter Property="SelectionBrush" Value="{StaticResource BgSelect}"/>
<Setter Property="CornerRadius" Value="3"/>
</Style>
<Style Selector="TextBox:focus /template/ Border#PART_BorderElement">
<Setter Property="BorderBrush" Value="{StaticResource FgAccent}"/>
</Style>
<!-- Button -->
<Style Selector="Button">
<Setter Property="Background" Value="{StaticResource BgPanel}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
<Setter Property="BorderBrush" Value="{StaticResource Border}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="10,3"/>
<Setter Property="CornerRadius" Value="3"/>
<Setter Property="Cursor" Value="Hand"/>
</Style>
<Style Selector="Button:pointerover /template/ ContentPresenter">
<Setter Property="Background" Value="{StaticResource BgHover}"/>
</Style>
<Style Selector="Button:pressed /template/ ContentPresenter">
<Setter Property="Background" Value="{StaticResource BgSelect}"/>
</Style>
<!-- ComboBox -->
<Style Selector="ComboBox">
<Setter Property="Background" Value="{StaticResource BgInput}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
<Setter Property="BorderBrush" Value="{StaticResource Border}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="5,3"/>
<Setter Property="CornerRadius" Value="3"/>
</Style>
<Style Selector="ComboBoxItem">
<Setter Property="Background" Value="{StaticResource BgPanel}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
<Setter Property="Padding" Value="8,4"/>
</Style>
<Style Selector="ComboBoxItem:selected /template/ ContentPresenter">
<Setter Property="Background" Value="{StaticResource BgSelect}"/>
</Style>
<Style Selector="ComboBoxItem:pointerover /template/ ContentPresenter">
<Setter Property="Background" Value="{StaticResource BgHover}"/>
</Style>
<!-- ListBox -->
<Style Selector="ListBox">
<Setter Property="Background" Value="{StaticResource BgMain}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
<Setter Property="BorderBrush" Value="{StaticResource Border}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="CornerRadius" Value="3"/>
</Style>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="8,4"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
</Style>
<Style Selector="ListBoxItem:selected /template/ ContentPresenter">
<Setter Property="Background" Value="{StaticResource BgSelect}"/>
</Style>
<Style Selector="ListBoxItem:pointerover /template/ ContentPresenter">
<Setter Property="Background" Value="{StaticResource BgHover}"/>
</Style>
<!-- CheckBox -->
<Style Selector="CheckBox">
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
</Style>
<!-- Menu -->
<Style Selector="Menu">
<Setter Property="Background" Value="{StaticResource BgPanel}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
</Style>
<Style Selector="MenuItem">
<Setter Property="Background" Value="{StaticResource BgPanel}"/>
<Setter Property="Foreground" Value="{StaticResource FgMain}"/>
</Style>
<Style Selector="MenuItem:pointerover /template/ Border#PART_LayoutRoot">
<Setter Property="Background" Value="{StaticResource BgHover}"/>
</Style>
<Style Selector="Separator">
<Setter Property="Background" Value="{StaticResource Border}"/>
</Style>
<!-- GridSplitter -->
<Style Selector="GridSplitter">
<Setter Property="Background" Value="{StaticResource Border}"/>
</Style>
</Styles>

View file

@ -0,0 +1,435 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.LootEditor;
/// <summary>
/// Per-NodeType typed editors. Each builder reads/writes the underlying
/// VTankConditionVm.Data.DataLines so changes round-trip through the writer.
/// </summary>
internal static class TypedEditors
{
private static readonly IBrush MutedBrush = new SolidColorBrush(Color.Parse("#7A8896"));
// ── ObjectClass ──────────────────────────────────────────────────────────
public static readonly (int Id, string Name)[] ObjectClasses =
{
(0, "Unknown"), (1, "MeleeWeapon"), (2, "Armor"), (3, "Clothing"),
(4, "Jewelry"), (5, "Monster"), (6, "Food"), (7, "Money"),
(8, "Misc"), (9, "MissileWeapon"), (10, "Container"), (11, "Useless"),
(12, "Gem"), (13, "SpellComp"), (14, "Key"), (15, "WandStaffOrb"),
(16, "Portal"), (17, "TradeNote"), (18, "ManaStone"), (19, "Plant"),
(20, "BaseAlchemy"), (21, "BaseCooking"), (22, "BaseFletching"), (23, "Player"),
(24, "Vendor"), (25, "Door"), (26, "Corpse"), (27, "Lifestone"),
(28, "Foci"), (29, "Salvage"), (30, "Ust"), (31, "Bundle"),
(32, "Book"), (33, "Journal"), (34, "Sign"), (35, "Housing"),
(36, "Pack"), (37, "Scroll"), (38, "BaseArmorTinker"), (39, "BaseWeaponTinker"),
(40, "BaseMagicTinker"), (41, "BaseItemTinker"), (50, "Salvage (legacy)"),
};
public static (int Id, string Name)[] ObjectClassesAccess() => ObjectClasses;
public static Control ObjectClassEditor(VTankConditionVm vm, Action onChange)
{
return Row("Object Class",
Combo(ObjectClasses, vm.Data.DataLines, 0, onChange, vm));
}
// ── Long key conditions (LE/GE/E/NE/Flag) ────────────────────────────────
public static Control LongKeyEditor(VTankConditionVm vm, Action onChange, string op)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto")
};
AddCell(grid, Label("Key"), col: 0);
AddCell(grid, KeyCombo(LongKeys, vm.Data.DataLines, 1, onChange, vm), col: 1);
AddCell(grid, Label(op), col: 2);
AddCell(grid, Label("Value"), col: 3);
AddCell(grid, IntBox(vm.Data.DataLines, 0, onChange, vm), col: 4);
return grid;
}
public static Control LongFlagEditor(VTankConditionVm vm, Action onChange)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto")
};
AddCell(grid, Label("Key"), col: 0);
AddCell(grid, KeyCombo(LongKeys, vm.Data.DataLines, 1, onChange, vm), col: 1);
AddCell(grid, Label("has flag"), col: 2);
AddCell(grid, Label("Value"), col: 3);
AddCell(grid, IntBox(vm.Data.DataLines, 0, onChange, vm), col: 4);
return grid;
}
public static Control DoubleKeyEditor(VTankConditionVm vm, Action onChange, string op)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto")
};
AddCell(grid, Label("Key"), col: 0);
AddCell(grid, KeyCombo(DoubleKeys, vm.Data.DataLines, 1, onChange, vm), col: 1);
AddCell(grid, Label(op), col: 2);
AddCell(grid, Label("Value"), col: 3);
AddCell(grid, DoubleBox(vm.Data.DataLines, 0, onChange, vm), col: 4);
return grid;
}
public static Control DoubleKeyAsLongEditor(VTankConditionVm vm, Action onChange, string op)
{
// Buffed-long: the value is stored as a double in slot 0 even though the key indexes a long property.
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto")
};
AddCell(grid, Label("Key (long)"), col: 0);
AddCell(grid, KeyCombo(LongKeys, vm.Data.DataLines, 1, onChange, vm), col: 1);
AddCell(grid, Label(op), col: 2);
AddCell(grid, Label("Value"), col: 3);
AddCell(grid, DoubleBox(vm.Data.DataLines, 0, onChange, vm), col: 4);
return grid;
}
// ── String / spell ───────────────────────────────────────────────────────
public static Control StringValueEditor(VTankConditionVm vm, Action onChange)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto")
};
AddCell(grid, Label("String key"), col: 0);
AddCell(grid, KeyCombo(StringKeys, vm.Data.DataLines, 1, onChange, vm), col: 1);
AddCell(grid, Label("matches"), col: 2);
AddCell(grid, StringBox(vm.Data.DataLines, 0, onChange, vm, "regex pattern"), col: 3);
return grid;
}
public static Control SingleStringEditor(VTankConditionVm vm, Action onChange, string label)
{
return Row(label, StringBox(vm.Data.DataLines, 0, onChange, vm, label));
}
public static Control SpellMatchEditor(VTankConditionVm vm, Action onChange)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto,Auto,Auto"),
};
AddCell(grid, Label("Match regex"), col: 0, row: 0);
AddCell(grid, StringBox(vm.Data.DataLines, 0, onChange, vm), col: 1, row: 0);
AddCell(grid, Label("No-match regex"), col: 0, row: 1);
AddCell(grid, StringBox(vm.Data.DataLines, 1, onChange, vm), col: 1, row: 1);
AddCell(grid, Label("Min count"), col: 0, row: 2);
AddCell(grid, IntBox(vm.Data.DataLines, 2, onChange, vm), col: 1, row: 2);
return grid;
}
// ── Single-value editors ────────────────────────────────────────────────
public static Control SingleIntEditor(VTankConditionVm vm, Action onChange, string label)
=> Row(label, IntBox(vm.Data.DataLines, 0, onChange, vm));
public static Control SingleDoubleEditor(VTankConditionVm vm, Action onChange, string label)
=> Row(label, DoubleBox(vm.Data.DataLines, 0, onChange, vm));
public static Control TwoIntEditor(VTankConditionVm vm, Action onChange, string a, string b)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto"),
};
AddCell(grid, Label(a), col: 0);
AddCell(grid, IntBox(vm.Data.DataLines, 0, onChange, vm), col: 1);
AddCell(grid, Label(b), col: 2);
AddCell(grid, IntBox(vm.Data.DataLines, 1, onChange, vm), col: 3);
return grid;
}
public static Control ThreeDoubleEditor(VTankConditionVm vm, Action onChange, string a, string b, string c)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto,Auto,Auto"),
};
AddCell(grid, Label(a), col: 0, row: 0); AddCell(grid, DoubleBox(vm.Data.DataLines, 0, onChange, vm), col: 1, row: 0);
AddCell(grid, Label(b), col: 0, row: 1); AddCell(grid, DoubleBox(vm.Data.DataLines, 1, onChange, vm), col: 1, row: 1);
AddCell(grid, Label(c), col: 0, row: 2); AddCell(grid, DoubleBox(vm.Data.DataLines, 2, onChange, vm), col: 1, row: 2);
return grid;
}
// ── Skill ────────────────────────────────────────────────────────────────
public static Control SkillGEEditor(VTankConditionVm vm, Action onChange)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto"),
};
AddCell(grid, Label("Skill"), col: 0);
AddCell(grid, KeyCombo(Skills, vm.Data.DataLines, 1, onChange, vm), col: 1);
AddCell(grid, Label("≥"), col: 2);
AddCell(grid, Label("Value"), col: 3);
AddCell(grid, IntBox(vm.Data.DataLines, 0, onChange, vm), col: 4);
return grid;
}
public static Control BaseSkillEditor(VTankConditionVm vm, Action onChange)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*,Auto,*,Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto"),
};
AddCell(grid, Label("Skill"), col: 0);
AddCell(grid, KeyCombo(Skills, vm.Data.DataLines, 0, onChange, vm), col: 1);
AddCell(grid, Label("Min"), col: 2);
AddCell(grid, IntBox(vm.Data.DataLines, 1, onChange, vm), col: 3);
AddCell(grid, Label("Max"), col: 4);
AddCell(grid, IntBox(vm.Data.DataLines, 2, onChange, vm), col: 5);
return grid;
}
// ── Color ────────────────────────────────────────────────────────────────
public static Control ColorEditor(VTankConditionVm vm, Action onChange, bool hasArmorOrSlot, string trailingLabel = "")
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto,Auto,Auto,Auto,Auto,Auto"),
};
AddCell(grid, Label("R"), col: 0, row: 0); AddCell(grid, IntBox(vm.Data.DataLines, 0, onChange, vm), col: 1, row: 0);
AddCell(grid, Label("G"), col: 0, row: 1); AddCell(grid, IntBox(vm.Data.DataLines, 1, onChange, vm), col: 1, row: 1);
AddCell(grid, Label("B"), col: 0, row: 2); AddCell(grid, IntBox(vm.Data.DataLines, 2, onChange, vm), col: 1, row: 2);
AddCell(grid, Label("Max ΔH"), col: 0, row: 3); AddCell(grid, IntBox(vm.Data.DataLines, 3, onChange, vm), col: 1, row: 3);
AddCell(grid, Label("Max ΔSV"), col: 0, row: 4); AddCell(grid, IntBox(vm.Data.DataLines, 4, onChange, vm), col: 1, row: 4);
if (hasArmorOrSlot)
{
AddCell(grid, Label(trailingLabel), col: 0, row: 5);
AddCell(grid, IntBox(vm.Data.DataLines, 5, onChange, vm), col: 1, row: 5);
}
return grid;
}
// ── DisabledRule ─────────────────────────────────────────────────────────
public static Control DisabledRuleEditor(VTankConditionVm vm, Action onChange)
{
EnsureLine(vm, 0, "false");
var cb = new CheckBox
{
Content = "Rule disabled",
IsChecked = string.Equals(vm.Data.DataLines[0].Trim(), "true", StringComparison.OrdinalIgnoreCase),
};
cb.IsCheckedChanged += (_, _) =>
{
string newValue = cb.IsChecked == true ? "true" : "false";
if (vm.Data.DataLines[0] != newValue)
{
vm.Data.DataLines[0] = newValue;
vm.NotifyDataChanged();
onChange();
}
};
return cb;
}
// ── Building blocks ──────────────────────────────────────────────────────
private static Control Row(string label, Control editor)
{
var grid = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*"),
RowDefinitions = RowDefinitions.Parse("Auto"),
};
AddCell(grid, Label(label), col: 0);
AddCell(grid, editor, col: 1);
return grid;
}
private static TextBlock Label(string text) => new()
{
Text = text,
Foreground = MutedBrush,
VerticalAlignment = VerticalAlignment.Center,
};
private static void AddCell(Grid grid, Control c, int col, int row = 0)
{
Grid.SetColumn(c, col);
Grid.SetRow(c, row);
grid.Children.Add(c);
}
private static TextBox IntBox(IList<string> lines, int idx, Action onChange, VTankConditionVm vm)
{
EnsureLine(vm, idx, "0");
var box = new TextBox { Text = lines[idx] };
box.LostFocus += (_, _) => Commit(box, lines, idx, vm, onChange, parseInt: true);
return box;
}
private static TextBox DoubleBox(IList<string> lines, int idx, Action onChange, VTankConditionVm vm)
{
EnsureLine(vm, idx, "0");
var box = new TextBox { Text = lines[idx] };
box.LostFocus += (_, _) => Commit(box, lines, idx, vm, onChange, parseInt: false);
return box;
}
private static TextBox StringBox(IList<string> lines, int idx, Action onChange, VTankConditionVm vm, string? watermark = null)
{
EnsureLine(vm, idx, string.Empty);
var box = new TextBox { Text = lines[idx], Watermark = watermark };
box.LostFocus += (_, _) =>
{
if (lines[idx] != box.Text)
{
lines[idx] = box.Text ?? string.Empty;
vm.NotifyDataChanged();
onChange();
}
};
return box;
}
private static ComboBox KeyCombo((int Id, string Name)[] options, IList<string> lines, int idx, Action onChange, VTankConditionVm vm)
{
EnsureLine(vm, idx, "0");
var combo = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch };
var items = new List<KvOption>();
foreach (var (id, name) in options) items.Add(new KvOption(id, $"{id} — {name}"));
combo.ItemsSource = items;
combo.DisplayMemberBinding = new Avalonia.Data.Binding(nameof(KvOption.Display));
int.TryParse(lines[idx].Trim(), out int currentId);
foreach (var i in items) if (i.Id == currentId) { combo.SelectedItem = i; break; }
combo.SelectionChanged += (_, _) =>
{
if (combo.SelectedItem is KvOption opt && lines[idx] != opt.Id.ToString(CultureInfo.InvariantCulture))
{
lines[idx] = opt.Id.ToString(CultureInfo.InvariantCulture);
vm.NotifyDataChanged();
onChange();
}
};
return combo;
}
private static ComboBox Combo((int Id, string Name)[] options, IList<string> lines, int idx, Action onChange, VTankConditionVm vm)
=> KeyCombo(options, lines, idx, onChange, vm);
private static void Commit(TextBox box, IList<string> lines, int idx, VTankConditionVm vm, Action onChange, bool parseInt)
{
string text = box.Text ?? "0";
if (parseInt)
{
if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v))
text = v.ToString(CultureInfo.InvariantCulture);
else { box.Text = lines[idx]; return; }
}
else
{
if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
text = d.ToString(CultureInfo.InvariantCulture);
else { box.Text = lines[idx]; return; }
}
if (lines[idx] != text)
{
lines[idx] = text;
vm.NotifyDataChanged();
onChange();
}
}
private static void EnsureLine(VTankConditionVm vm, int idx, string defaultValue)
{
while (vm.Data.DataLines.Count <= idx) vm.Data.DataLines.Add(defaultValue);
}
private sealed record KvOption(int Id, string Display);
// ── Reference key tables (subset of AC enums; covers what people usually edit) ──
public static readonly (int Id, string Name)[] LongKeys =
{
(5, "EncumbVal"),
(19, "Value"),
(25, "Level"),
(28, "ArmorLevel"),
(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"),
};
public static readonly (int Id, string Name)[] Skills =
{
(1, "Axe"), (2, "Bow"), (3, "Crossbow"), (4, "Dagger"),
(5, "Mace"), (6, "MeleeDefense"),(7, "MissileDef."), (8, "Sling"),
(9, "Spear"), (10, "Staff"), (11, "Sword"), (12, "ThrownWpn"),
(13, "Unarmed"), (14, "ArcaneLore"), (15, "MagicDefense"),(16, "ManaConv."),
(18, "Item Tinkering"), (19, "Healing"), (20, "Deception"), (21, "Leadership"),
(22, "Lockpick"), (23, "Fletching"), (24, "Alchemy"), (25, "Cooking"),
(26, "Salvaging"), (31, "Creature Ench."), (32, "Item Ench."), (33, "Life Magic"),
(34, "War Magic"), (35, "Loyalty"), (36, "Jump"), (37, "Run"),
(38, "Assess"), (39, "Weapon Tinkering"), (40, "Armor Tinkering"),
(41, "Magic Item Tinkering"), (43, "Two Handed"), (44, "Gearcraft"),
(45, "Void Magic"), (46, "Heavy Weapons"), (47, "Light Weapons"),
(48, "Finesse Weapons"), (49, "Missile Weapons"), (50, "Shield"),
(54, "Dual Wield"), (55, "Recklessness"), (56, "Sneak Attack"),
};
}

View file

@ -0,0 +1,201 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using RynthCore.Loot.VTank;
using System;
using System.Collections.Generic;
namespace RynthCore.LootEditor;
/// <summary>
/// Editor surface for one VTank loot condition. Composed at runtime per
/// condition: a node-type picker on top, then either a typed editor (if we
/// have one for the selected NodeType) or a generic raw-lines editor that
/// guarantees round-trip safety for any node type.
/// </summary>
public sealed class VTankConditionEditorView : ContentControl
{
private readonly VTankConditionVm _vm;
private readonly Action _onChange;
private readonly Brush _muted = new SolidColorBrush(Color.Parse("#7A8896"));
public VTankConditionEditorView(VTankConditionVm vm, Action onChange)
{
_vm = vm;
_onChange = onChange;
Build();
}
private void Build()
{
var stack = new StackPanel { Spacing = 6 };
// ── Node-type picker row ─────────────────────────────────────────────
var typeRow = new Grid
{
ColumnDefinitions = ColumnDefinitions.Parse("Auto,*"),
};
var typeLabel = new TextBlock
{
Text = "Node Type",
VerticalAlignment = VerticalAlignment.Center,
Foreground = _muted,
};
Grid.SetColumn(typeLabel, 0);
typeRow.Children.Add(typeLabel);
var typeCombo = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch };
var options = new List<NodeTypeOption>();
foreach (int t in VTankNodeTypes.All)
options.Add(new NodeTypeOption(t, $"{VTankNodeTypes.DisplayName(t)} (id {t})"));
typeCombo.ItemsSource = options;
typeCombo.DisplayMemberBinding = new Avalonia.Data.Binding(nameof(NodeTypeOption.Display));
typeCombo.SelectedItem = FindOption(options, _vm.NodeType);
typeCombo.SelectionChanged += (_, _) =>
{
if (typeCombo.SelectedItem is NodeTypeOption opt && opt.Id != _vm.NodeType)
{
_vm.NodeType = opt.Id;
EnsureDataLineCount(opt.Id);
_vm.NotifyDataChanged();
_onChange();
// Re-build to swap the typed editor underneath.
Build();
}
};
Grid.SetColumn(typeCombo, 1);
typeRow.Children.Add(typeCombo);
stack.Children.Add(typeRow);
// ── Data lines editor ────────────────────────────────────────────────
EnsureDataLineCount(_vm.NodeType);
var typed = TryBuildTypedEditor(_vm, _onChange);
if (typed != null)
{
stack.Children.Add(typed);
stack.Children.Add(BuildRawHint());
}
else
{
stack.Children.Add(BuildRawEditor());
}
Content = stack;
}
private static NodeTypeOption? FindOption(List<NodeTypeOption> options, int id)
{
foreach (var o in options) if (o.Id == id) return o;
return null;
}
/// <summary>
/// Pads or trims the condition's data lines to match the documented arity
/// for its node type. New lines default to "0".
/// </summary>
private void EnsureDataLineCount(int nodeType)
{
int n = VTankNodeTypes.GetDataLineCount(nodeType);
if (n < 0) return; // unknown — leave as-is so unparsed bytes survive
var d = _vm.Data.DataLines;
while (d.Count < n) d.Add("0");
while (d.Count > n) d.RemoveAt(d.Count - 1);
}
private Control BuildRawEditor()
{
var panel = new StackPanel { Spacing = 4 };
panel.Children.Add(new TextBlock
{
Text = "Data lines (one per row, in VTank's order)",
Foreground = _muted,
FontSize = 11,
});
for (int i = 0; i < _vm.Data.DataLines.Count; i++)
{
int idx = i;
var box = new TextBox { Text = _vm.Data.DataLines[idx], AcceptsReturn = false };
box.LostFocus += (_, _) =>
{
if (_vm.Data.DataLines[idx] != box.Text)
{
_vm.Data.DataLines[idx] = box.Text ?? string.Empty;
_vm.NotifyDataChanged();
_onChange();
}
};
panel.Children.Add(box);
}
// Buttons to grow/shrink the data list — only meaningful for unknown
// node types where we can't infer the arity.
if (VTankNodeTypes.GetDataLineCount(_vm.NodeType) < 0)
{
var btnRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
var add = new Button { Content = "+ line" };
add.Click += (_, _) => { _vm.Data.DataLines.Add(""); _onChange(); Build(); };
var del = new Button { Content = "− line" };
del.Click += (_, _) =>
{
if (_vm.Data.DataLines.Count > 0)
{ _vm.Data.DataLines.RemoveAt(_vm.Data.DataLines.Count - 1); _onChange(); Build(); }
};
btnRow.Children.Add(add); btnRow.Children.Add(del);
panel.Children.Add(btnRow);
}
return panel;
}
private Control BuildRawHint()
{
return new TextBlock
{
Text = "Raw values are stored verbatim; round-trip is preserved.",
Foreground = _muted,
FontSize = 11,
Margin = new Thickness(0, 6, 0, 0),
};
}
// ── Typed editors for known node types ───────────────────────────────────
private static Control? TryBuildTypedEditor(VTankConditionVm vm, Action onChange) => vm.NodeType switch
{
VTankNodeTypes.ObjectClass => TypedEditors.ObjectClassEditor(vm, onChange),
VTankNodeTypes.LongValKeyGE => TypedEditors.LongKeyEditor(vm, onChange, "≥"),
VTankNodeTypes.LongValKeyLE => TypedEditors.LongKeyEditor(vm, onChange, "≤"),
VTankNodeTypes.LongValKeyE => TypedEditors.LongKeyEditor(vm, onChange, "="),
VTankNodeTypes.LongValKeyNE => TypedEditors.LongKeyEditor(vm, onChange, "≠"),
VTankNodeTypes.LongValKeyFlagExists => TypedEditors.LongFlagEditor(vm, onChange),
VTankNodeTypes.DoubleValKeyGE => TypedEditors.DoubleKeyEditor(vm, onChange, "≥"),
VTankNodeTypes.DoubleValKeyLE => TypedEditors.DoubleKeyEditor(vm, onChange, "≤"),
VTankNodeTypes.BuffedLongValKeyGE => TypedEditors.DoubleKeyAsLongEditor(vm, onChange, "≥ (buffed long)"),
VTankNodeTypes.BuffedDoubleValKeyGE => TypedEditors.DoubleKeyEditor(vm, onChange, "≥ (buffed double)"),
VTankNodeTypes.StringValueMatch => TypedEditors.StringValueEditor(vm, onChange),
VTankNodeTypes.SpellNameMatch => TypedEditors.SingleStringEditor(vm, onChange, "Pattern"),
VTankNodeTypes.SpellCountGE => TypedEditors.SingleIntEditor(vm, onChange, "Min count"),
VTankNodeTypes.SpellMatch => TypedEditors.SpellMatchEditor(vm, onChange),
VTankNodeTypes.MinDamageGE => TypedEditors.SingleDoubleEditor(vm, onChange, "Min damage ≥"),
VTankNodeTypes.DamagePercentGE => TypedEditors.SingleDoubleEditor(vm, onChange, "Damage % ≥"),
VTankNodeTypes.TotalRatingsGE => TypedEditors.SingleIntEditor(vm, onChange, "Total ratings ≥"),
VTankNodeTypes.BuffedMedianDamageGE => TypedEditors.SingleDoubleEditor(vm, onChange, "Median damage ≥"),
VTankNodeTypes.BuffedMissileDamageGE => TypedEditors.SingleDoubleEditor(vm, onChange, "Missile damage ≥"),
VTankNodeTypes.CalcdBuffedTinkedDamageGE => TypedEditors.SingleDoubleEditor(vm, onChange, "Tinked damage ≥"),
VTankNodeTypes.CharacterLevelGE => TypedEditors.SingleIntEditor(vm, onChange, "Char level ≥"),
VTankNodeTypes.CharacterLevelLE => TypedEditors.SingleIntEditor(vm, onChange, "Char level ≤"),
VTankNodeTypes.CharacterMainPackEmptySlotsGE=> TypedEditors.SingleIntEditor(vm, onChange, "Pack slots ≥"),
VTankNodeTypes.CharacterSkillGE => TypedEditors.SkillGEEditor(vm, onChange),
VTankNodeTypes.CharacterBaseSkill => TypedEditors.BaseSkillEditor(vm, onChange),
VTankNodeTypes.SlotExactPalette => TypedEditors.TwoIntEditor(vm, onChange, "Slot", "Palette ID"),
VTankNodeTypes.AnySimilarColor => TypedEditors.ColorEditor(vm, onChange, hasArmorOrSlot: false),
VTankNodeTypes.SimilarColorArmorType => TypedEditors.ColorEditor(vm, onChange, hasArmorOrSlot: true, trailingLabel: "Armor group"),
VTankNodeTypes.SlotSimilarColor => TypedEditors.ColorEditor(vm, onChange, hasArmorOrSlot: true, trailingLabel: "Slot"),
VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE
=> TypedEditors.ThreeDoubleEditor(vm, onChange, "Target DoT", "Target melee def", "Target attack"),
VTankNodeTypes.DisabledRule => TypedEditors.DisabledRuleEditor(vm, onChange),
_ => null,
};
}

View file

@ -0,0 +1,292 @@
using Avalonia.Media;
using RynthCore.Loot.VTank;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace RynthCore.LootEditor;
/// <summary>
/// Observable view-model wrapping a VTankLootRule. Edits flow into the
/// underlying data so save reproduces them; INPC drives the Avalonia bindings.
/// </summary>
public sealed class VTankRuleVm : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private void Notify([CallerMemberName] string? n = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
public VTankLootRule Data { get; }
public VTankRuleVm(VTankLootRule data)
{
Data = data;
foreach (var c in data.Conditions)
{
var vm = new VTankConditionVm(c) { OwnerRule = this };
Conditions.Add(vm);
}
Conditions.CollectionChanged += OnConditionsChanged;
}
/// <summary>Called by a child condition VM when its data changed.</summary>
internal void NotifySummaryChanged() => Notify(nameof(Summary));
private void OnConditionsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
// Keep OwnerRule wired so Summary refreshes when descendants edit data.
if (e.NewItems != null)
foreach (var obj in e.NewItems)
if (obj is VTankConditionVm cvm) cvm.OwnerRule = this;
Notify(nameof(ConditionCount));
Notify(nameof(ConditionCountLabel));
Notify(nameof(Summary));
Notify(nameof(Enabled));
}
public string Name
{
get => Data.Name;
set { if (Data.Name == value) return; Data.Name = value; Notify(); }
}
public string CustomExpression
{
get => Data.CustomExpression ?? string.Empty;
set
{
string v = value ?? string.Empty;
if ((Data.CustomExpression ?? string.Empty) == v) return;
Data.CustomExpression = v;
Notify();
}
}
public int Priority
{
get => Data.Priority;
set { if (Data.Priority == value) return; Data.Priority = value; Notify(); }
}
public VTankLootAction Action
{
get => Data.Action;
set
{
if (Data.Action == value) return;
Data.Action = value;
// Maintain the keep-count line invariant: present iff KeepUpTo.
if (value == VTankLootAction.KeepUpTo)
Data.KeepCount ??= 1;
else
Data.KeepCount = null;
Notify();
Notify(nameof(KeepCount));
Notify(nameof(ShowKeepCount));
Notify(nameof(ActionLabel));
Notify(nameof(ActionBadgeBrush));
Notify(nameof(ActionBadgeForeground));
}
}
public string ActionLabel => Data.Action switch
{
VTankLootAction.Keep => "KEEP",
VTankLootAction.KeepUpTo => $"KEEP {Data.KeepCount ?? 0}",
VTankLootAction.Salvage => "SALVAGE",
VTankLootAction.Sell => "SELL",
VTankLootAction.Read => "READ",
_ => "?",
};
public IBrush ActionBadgeBrush => Data.Action switch
{
VTankLootAction.Keep => new SolidColorBrush(Color.Parse("#1f6f3a")), // green
VTankLootAction.KeepUpTo => new SolidColorBrush(Color.Parse("#196e6e")), // teal
VTankLootAction.Salvage => new SolidColorBrush(Color.Parse("#a35c15")), // orange
VTankLootAction.Sell => new SolidColorBrush(Color.Parse("#7a1f1f")), // red
VTankLootAction.Read => new SolidColorBrush(Color.Parse("#1f497d")), // blue
_ => new SolidColorBrush(Color.Parse("#444" )), // gray
};
public IBrush ActionBadgeForeground => new SolidColorBrush(Color.Parse("#FFFFFF"));
public int ConditionCount => Conditions.Count;
public string ConditionCountLabel => ConditionCount == 0
? "always"
: (ConditionCount == 1 ? "1 cond" : $"{ConditionCount} conds");
public int KeepCount
{
get => Data.KeepCount ?? 0;
set
{
if ((Data.KeepCount ?? 0) == value) return;
Data.KeepCount = value;
Notify();
}
}
public bool ShowKeepCount => Data.Action == VTankLootAction.KeepUpTo;
public bool Enabled
{
get => Data.Enabled;
set
{
if (Data.Enabled == value) return;
Data.Enabled = value;
Notify();
// Enabled toggle adds/removes a DisabledRule condition node — keep
// the VM-side condition list in sync so the UI grid updates.
SyncConditionsFromData();
}
}
public ObservableCollection<VTankConditionVm> Conditions { get; } = new();
/// <summary>One-line plain-English description of all conditions.</summary>
public string Summary
{
get
{
if (Conditions.Count == 0) return "Matches every item.";
var sb = new StringBuilder();
for (int i = 0; i < Conditions.Count; i++)
{
if (i > 0) sb.Append(" AND ");
sb.Append(SummarizeCondition(Conditions[i]));
}
return sb.ToString();
}
}
private static string SummarizeCondition(VTankConditionVm c)
{
var d = c.Data.DataLines;
string lk(int i) => LookupName(TypedEditors.LongKeys, Get(d, i));
string dk(int i) => LookupName(TypedEditors.DoubleKeys, Get(d, i));
string sk(int i) => LookupName(TypedEditors.StringKeys, Get(d, i));
string skl(int i) => LookupName(TypedEditors.Skills, Get(d, i));
string oc(int i)
{
if (int.TryParse(Get(d, i), out int n))
foreach (var oct in TypedEditors.ObjectClassesAccess())
if (oct.Id == n) return oct.Name;
return Get(d, i);
}
return c.Data.NodeType switch
{
VTankNodeTypes.ObjectClass => $"Class is {oc(0)}",
VTankNodeTypes.LongValKeyGE => $"{lk(1)} ≥ {Get(d, 0)}",
VTankNodeTypes.LongValKeyLE => $"{lk(1)} ≤ {Get(d, 0)}",
VTankNodeTypes.LongValKeyE => $"{lk(1)} = {Get(d, 0)}",
VTankNodeTypes.LongValKeyNE => $"{lk(1)} ≠ {Get(d, 0)}",
VTankNodeTypes.LongValKeyFlagExists => $"{lk(1)} has flag {Get(d, 0)}",
VTankNodeTypes.DoubleValKeyGE => $"{dk(1)} ≥ {Get(d, 0)}",
VTankNodeTypes.DoubleValKeyLE => $"{dk(1)} ≤ {Get(d, 0)}",
VTankNodeTypes.BuffedLongValKeyGE => $"buffed {lk(1)} ≥ {Get(d, 0)}",
VTankNodeTypes.BuffedDoubleValKeyGE => $"buffed {dk(1)} ≥ {Get(d, 0)}",
VTankNodeTypes.StringValueMatch => $"{sk(1)} matches \"{Trunc(Get(d, 0), 30)}\"",
VTankNodeTypes.SpellNameMatch => $"spell matches \"{Trunc(Get(d, 0), 30)}\"",
VTankNodeTypes.SpellCountGE => $"spell count ≥ {Get(d, 0)}",
VTankNodeTypes.SpellMatch => $"≥{Get(d, 2)} spells matching \"{Trunc(Get(d, 0), 20)}\"",
VTankNodeTypes.MinDamageGE => $"min dmg ≥ {Get(d, 0)}",
VTankNodeTypes.DamagePercentGE => $"dmg% ≥ {Get(d, 0)}",
VTankNodeTypes.TotalRatingsGE => $"total ratings ≥ {Get(d, 0)}",
VTankNodeTypes.BuffedMedianDamageGE => $"median dmg ≥ {Get(d, 0)}",
VTankNodeTypes.BuffedMissileDamageGE => $"missile dmg ≥ {Get(d, 0)}",
VTankNodeTypes.CalcdBuffedTinkedDamageGE => $"tinked dmg ≥ {Get(d, 0)}",
VTankNodeTypes.CharacterLevelGE => $"char level ≥ {Get(d, 0)}",
VTankNodeTypes.CharacterLevelLE => $"char level ≤ {Get(d, 0)}",
VTankNodeTypes.CharacterMainPackEmptySlotsGE=> $"pack slots ≥ {Get(d, 0)}",
VTankNodeTypes.CharacterSkillGE => $"{skl(1)} skill ≥ {Get(d, 0)}",
VTankNodeTypes.CharacterBaseSkill => $"{skl(0)} base in [{Get(d, 1)}, {Get(d, 2)}]",
VTankNodeTypes.SlotExactPalette => $"palette slot {Get(d, 0)} = {Get(d, 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.Data.NodeType}",
};
static string Get(System.Collections.Generic.IList<string> lines, int idx)
=> idx < lines.Count ? lines[idx] : "?";
static string Trunc(string s, int n) => s.Length > n ? s.Substring(0, n) + "…" : s;
static string LookupName((int Id, string Name)[] table, string raw)
{
if (int.TryParse(raw, out int n))
foreach (var t in table)
if (t.Id == n) return t.Name;
return $"key {raw}";
}
}
/// <summary>Re-syncs the VM condition list with the underlying data list.</summary>
public void SyncConditionsFromData()
{
Conditions.Clear();
foreach (var c in Data.Conditions)
Conditions.Add(new VTankConditionVm(c));
}
/// <summary>Push current VM condition order/state back into Data before save.</summary>
public void FlushConditionsToData()
{
Data.Conditions.Clear();
foreach (var vm in Conditions)
Data.Conditions.Add(vm.Data);
}
}
/// <summary>Observable view-model for a single VTankLootCondition.</summary>
public sealed class VTankConditionVm : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private void Notify([CallerMemberName] string? n = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
public VTankLootCondition Data { get; }
public VTankConditionVm(VTankLootCondition data) { Data = data; }
public int NodeType
{
get => Data.NodeType;
set
{
if (Data.NodeType == value) return;
Data.NodeType = value;
Notify();
Notify(nameof(DisplayName));
}
}
public string DisplayName => $"{VTankNodeTypes.DisplayName(Data.NodeType)} {Summarize()}";
/// <summary>One-liner summary of the condition's data for the list view.</summary>
private string Summarize()
{
var d = Data.DataLines;
if (d.Count == 0) return string.Empty;
if (d.Count == 1) return $"= {d[0]}";
// For two-line conditions value/key is the typical shape.
if (d.Count == 2) return $"= {d[0]} (key {d[1]})";
return $"({d.Count} lines)";
}
/// <summary>Force the list-view summary to re-render after a data-line edit.</summary>
public void NotifyDataChanged()
{
Notify(nameof(DisplayName));
OwnerRule?.NotifySummaryChanged();
}
/// <summary>The rule that owns this condition; set by VTankRuleVm at construction.</summary>
internal VTankRuleVm? OwnerRule { get; set; }
}