RynthSuite/Plugins/RynthCore.Plugin.RynthDefective/Appraisal/AppraisalText.cs

643 lines
35 KiB
C#

// ============================================================================
// RynthDefective - Appraisal/AppraisalText.cs
// What the Appraisal window says about an object (2026-11-28: all the data,
// roughly in the retail layout): the retail examine panel's
// lines in its order and words where retail has them ("Value:", "Damage:
// 25 - 50, Slashing", "Bonus to Melee Defense: +15%.", "Spellcraft: 400.",
// "Wield requires Heavy Weapons 400", ...), grouped under small headings, and
// every property the engine holds at the end (the "All properties" list).
//
// Pure: an AppraisalInput (the engine's ObjectProperties dictionaries, the
// creature's vitals and attributes, a spell name lookup) in, an AppraisalDoc
// out. The tests run it (Tools/RynthDefective.Tests).
//
// Property ids are ACE's (PropertyInt/Float/String/Bool/DataId); the name
// tables are RynthAi's (MagItemInfoTables, PropertyNames, linked in).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.Plugin.RynthAi.Meta;
namespace RynthCore.Plugin.RynthDefective.Appraisal;
/// <summary>How a line is coloured.</summary>
internal enum AppraiseTone { Text, Dim, Good, Bad, Magic, Gold }
internal readonly record struct AppraiseLine(string Text, AppraiseTone Tone = AppraiseTone.Text);
internal sealed class AppraiseSection
{
public AppraiseSection(string title) { Title = title; }
public string Title { get; }
public List<AppraiseLine> Lines { get; } = new();
public void Add(string text, AppraiseTone tone = AppraiseTone.Text) { if (text.Length > 0) Lines.Add(new AppraiseLine(text, tone)); }
}
/// <summary>A bar under the name: a creature's Health / Stamina / Mana, an item's mana. Max 0 = only the ratio is known.</summary>
internal readonly record struct AppraiseBar(string Label, uint Current, uint Max, float Ratio, AppraiseBarKind Kind);
internal enum AppraiseBarKind { Health, Stamina, Mana }
/// <summary>One raw property for the "All properties" list.</summary>
internal readonly record struct AppraiseRaw(string Kind, uint Key, string Name, string Value);
internal sealed class AppraisalDoc
{
public uint Id { get; init; }
public string Name { get; init; } = string.Empty;
/// <summary>What it is, under the name: "Heavy Weapons (Sword)", "Level 112 Olthoi", "Jewelry".</summary>
public string Kind { get; init; } = string.Empty;
/// <summary>The short facts beside the picture: Value, Burden, a stack, uses.</summary>
public List<(string Label, string Value)> Facts { get; } = new();
public List<AppraiseBar> Bars { get; } = new();
/// <summary>A creature's six attributes (Strength .. Self), when assessed; empty otherwise.</summary>
public List<(string Label, uint Value, bool Buffed, bool Up)> Attributes { get; } = new();
public List<AppraiseSection> Sections { get; } = new();
public string Description { get; init; } = string.Empty;
public List<AppraiseRaw> Raw { get; } = new();
public bool Identified { get; init; }
public bool IsCreature { get; init; }
/// <summary>The whole appraisal as text (the window's Copy).</summary>
public string ToText()
{
var sb = new StringBuilder();
sb.AppendLine(Name);
if (Kind.Length > 0) sb.AppendLine(Kind);
foreach (var (label, value) in Facts) sb.AppendLine(label + ": " + value);
foreach (var b in Bars)
sb.AppendLine(b.Max > 0 ? $"{b.Label}: {b.Current:N0} / {b.Max:N0}" : $"{b.Label}: {MathF.Round(b.Ratio * 100f):0}%");
foreach (var a in Attributes) sb.AppendLine($"{a.Label}: {a.Value}");
foreach (var s in Sections)
{
sb.AppendLine().AppendLine(s.Title);
foreach (var l in s.Lines) sb.AppendLine(" " + l.Text);
}
if (Description.Length > 0) sb.AppendLine().AppendLine(Description);
return sb.ToString();
}
}
/// <summary>What the builder reads: the engine's view of the object.</summary>
internal sealed class AppraisalInput
{
public uint Id;
public string Name = string.Empty;
/// <summary>The ItemType flags (TryGetItemType) when the properties have none.</summary>
public uint ItemType;
public bool Identified;
public bool IsPlayer;
public Dictionary<uint, int> Ints = new();
public Dictionary<uint, long> Int64s = new();
public Dictionary<uint, bool> Bools = new();
public Dictionary<uint, double> Floats = new();
public Dictionary<uint, string> Strings = new();
public Dictionary<uint, uint> DataIds = new();
public Dictionary<uint, uint> InstanceIds = new();
public List<uint> Spells = new();
/// <summary>Health, Stamina, Mana (current, max) from the last assess; null none.</summary>
public (uint H, uint HMax, uint S, uint SMax, uint M, uint MMax)? Vitals;
/// <summary>The server's last health ratio for it, -1 none.</summary>
public float HealthRatio = -1f;
/// <summary>Strength, Endurance, Quickness, Coordination, Focus, Self; null not assessed.</summary>
public uint[]? Attributes;
public uint EnchantBits;
public Func<uint, string> SpellName = id => "Spell " + id.ToString(CultureInfo.InvariantCulture);
}
internal static class AppraisalText
{
// ── ACE property ids ─────────────────────────────────────────────────────
private const uint IItemType = 1, ICreatureType = 2, IClothingPriority = 4, IBurden = 5, IItemsCapacity = 6,
IContainersCapacity = 7, IValidLocations = 9, IMaxStack = 11, IStack = 12, IRareId = 17, IValue = 19, ILevel = 25,
IArmorLevel = 28, IAllegianceRank = 30, IBonded = 33, IResistMagic = 36, INumDeaths = 43, IDamage = 44,
IDamageType = 45, IWeaponSkill = 48, IWeaponTime = 49, IAmmoType = 50, IMinLevel = 86, IMaxLevel = 87,
ILockpickMod = 88, IBoostValue = 90, IMaxStructure = 91, IStructure = 92, IWorkmanship = 105, ISpellcraft = 106,
ICurMana = 107, IMaxMana = 108, IArcaneLore = 109, IAllegianceRankLimit = 110, IGender = 113, IAttuned = 114,
ISkillLevelLimit = 115, IMaterial = 131, IPkStatus = 134, ISlayerType = 166, INumItemsInMaterial = 170,
ITinkered = 171, IImbued = 179, IHeritage = 188, IElementalBonus = 204, ISet = 265, IRemainingLifespan = 268,
IUnique = 279, ICleaving = 292, IItemMaxLevel = 319, IWeaponType = 353, IUseRequiresLevel = 369;
private static readonly uint[] WieldReq = { 158, 270, 273, 276 }, WieldSkill = { 159, 271, 274, 277 }, WieldDiff = { 160, 272, 275, 278 };
private static readonly uint[] MoreImbues = { 303, 304, 305, 306 };
private const uint FManaRate = 5, FDamageVariance = 22, FWeaponDefense = 29, FWeaponOffense = 62, FDamageMod = 63,
FHealkitMod = 100, FSlayerBonus = 138, FManaConversion = 144, FMissileDefense = 149, FMagicDefense = 150,
FElementalMod = 152, FArmorVsNether = 165;
private static readonly (uint Key, string Name)[] ArmorMods =
{
(13, "Slashing"), (14, "Piercing"), (15, "Bludgeoning"), (16, "Cold"), (17, "Fire"), (18, "Acid"), (19, "Electric"), (FArmorVsNether, "Nether"),
};
private const uint SName = 1, STitle = 2, STemplate = 5, SInscription = 7, SScribe = 8, SFellowship = 10, SMonarch = 11,
SUse = 14, SShortDesc = 15, SLongDesc = 16, SCraftsman = 25, SPortalDest = 38, STinker = 39, SImbuer = 40,
SDateOfBirth = 43, SAllegiance = 47, SPlating = 52;
private const uint BRetained = 91, BIvoryable = 99, BDyable = 100, BUnlimitedUse = 63, BLocked = 3, BInscribable = 22;
private const uint DSpell = 28, DSkillLimit = 37, DSpecializedOnly = 41, DProcSpell = 55;
private const uint TypeMelee = 0x1, TypeArmor = 0x2, TypeClothing = 0x4, TypeJewelry = 0x8, TypeCreature = 0x10,
TypeMissile = 0x100, TypeContainer = 0x200, TypeCaster = 0x8000, TypePortal = 0x10000, TypeManaStone = 0x80000;
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
public static AppraisalDoc Build(AppraisalInput o)
{
int type = I(o, IItemType, (int)o.ItemType);
uint t = unchecked((uint)type);
bool creature = (t & TypeCreature) != 0 || o.IsPlayer || o.Attributes != null || o.Vitals != null;
string name = S(o, SName, o.Name);
if (name.Length == 0) name = $"0x{o.Id:X8}";
var doc = new AppraisalDoc
{
Id = o.Id,
Name = name,
Kind = creature ? CreatureKind(o) : ItemKind(o, t),
Description = S(o, SLongDesc, S(o, SShortDesc, "")),
Identified = o.Identified,
IsCreature = creature,
};
if (creature) CreatureBody(o, doc);
else ItemBody(o, t, doc);
Raw(o, doc);
return doc;
}
// ── Creatures and players ─────────────────────────────────────────────────
private static string CreatureKind(AppraisalInput o)
{
var parts = new List<string>(3);
int level = I(o, ILevel, 0);
if (level > 0) parts.Add("Level " + level.ToString(Inv));
if (o.IsPlayer)
{
string heritage = Heritage(I(o, IHeritage, 0));
string gender = I(o, IGender, 0) switch { 1 => "Male", 2 => "Female", _ => "" };
string who = (heritage + " " + gender).Trim();
if (who.Length > 0) parts.Add(who);
}
else if (MagItemInfoTables.CreatureTypeName(I(o, ICreatureType, 0)) is { } kind) parts.Add(kind);
return string.Join(" · ", parts);
}
private static readonly string[] AttributeNames = { "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" };
private static void CreatureBody(AppraisalInput o, AppraisalDoc doc)
{
if (o.Vitals is { } v && v.HMax > 0)
{
doc.Bars.Add(new AppraiseBar("Health", v.H, v.HMax, Ratio(v.H, v.HMax, o.HealthRatio), AppraiseBarKind.Health));
if (v.SMax > 0) doc.Bars.Add(new AppraiseBar("Stamina", v.S, v.SMax, v.S / (float)v.SMax, AppraiseBarKind.Stamina));
if (v.MMax > 0) doc.Bars.Add(new AppraiseBar("Mana", v.M, v.MMax, v.M / (float)v.MMax, AppraiseBarKind.Mana));
}
else if (o.HealthRatio >= 0f)
doc.Bars.Add(new AppraiseBar("Health", 0, 0, o.HealthRatio, AppraiseBarKind.Health));
if (o.Attributes is { Length: >= 6 } a)
for (int i = 0; i < 6; i++)
{
bool buffed = (o.EnchantBits & (1u << i)) != 0, up = (o.EnchantBits & (1u << (16 + i))) != 0;
doc.Attributes.Add((AttributeNames[i], a[i], buffed, up));
}
var who = new AppraiseSection(o.IsPlayer ? "Character" : "Creature");
if (o.IsPlayer)
{
who.Add(S(o, STitle, "") is { Length: > 0 } title ? "Title: " + title : "");
who.Add(S(o, STemplate, "") is { Length: > 0 } tpl ? "Template: " + tpl : "");
who.Add(PkStatus(I(o, IPkStatus, 0)));
who.Add(S(o, SAllegiance, "") is { Length: > 0 } al ? "Allegiance: " + al : "");
who.Add(S(o, SMonarch, "") is { Length: > 0 } mon ? "Monarch: " + mon : "");
who.Add(I(o, IAllegianceRank, 0) is > 0 and var rank ? "Rank: " + rank.ToString(Inv) : "");
who.Add(S(o, SFellowship, "") is { Length: > 0 } fel ? "Fellowship: " + fel : "");
who.Add(I(o, INumDeaths, 0) is > 0 and var deaths ? "Deaths: " + deaths.ToString("N0", Inv) : "", AppraiseTone.Dim);
who.Add(S(o, SDateOfBirth, "") is { Length: > 0 } dob ? "Born: " + dob : "", AppraiseTone.Dim);
}
else
{
if (MagItemInfoTables.CreatureTypeName(I(o, ICreatureType, 0)) is { } kind) who.Add("Type: " + kind);
if (o.Attributes == null && o.Identified)
who.Add("Your assess failed: only its health is known.", AppraiseTone.Dim);
}
if (who.Lines.Count > 0) doc.Sections.Add(who);
if (!o.Identified)
doc.Sections.Add(Note("Not assessed yet: asked the server."));
}
// ── Items ─────────────────────────────────────────────────────────────────
private static string ItemKind(AppraisalInput o, uint t)
{
if ((t & (TypeMelee | TypeMissile | TypeCaster)) != 0)
{
string skill = Skill(I(o, IWeaponSkill, 0));
string mastery = MagItemInfoTables.Masteries.TryGetValue(I(o, IWeaponType, 0), out string? m) ? m : "";
if ((t & TypeCaster) != 0) return "Caster" + (mastery.Length > 0 && mastery != "Wand" ? " (" + mastery + ")" : "");
if (skill.Length > 0) return mastery.Length > 0 ? $"{skill} ({mastery})" : skill;
return (t & TypeMissile) != 0 ? "Missile weapon" : "Melee weapon";
}
if ((t & TypeArmor) != 0) return (I(o, IValidLocations, 0) & 0x200000) != 0 ? "Shield" : "Armor";
if ((t & TypeClothing) != 0) return "Clothing";
if ((t & TypeJewelry) != 0) return "Jewelry";
if ((t & TypePortal) != 0) return "Portal";
if ((t & TypeContainer) != 0) return "Container";
if ((t & TypeManaStone) != 0) return "Mana stone";
return MagItemInfoTables.Materials.TryGetValue(I(o, IMaterial, 0), out string? mat) && I(o, INumItemsInMaterial, 0) > 0
? "Salvage (" + mat + ")" : "";
}
private static void ItemBody(AppraisalInput o, uint t, AppraisalDoc doc)
{
// The facts beside the picture.
if (Has(o, IValue)) doc.Facts.Add(("Value", I(o, IValue, 0).ToString("N0", Inv)));
if (Has(o, IBurden)) doc.Facts.Add(("Burden", I(o, IBurden, 0).ToString("N0", Inv)));
int stack = I(o, IStack, 0), maxStack = I(o, IMaxStack, 0);
if (stack > 1 || maxStack > 1) doc.Facts.Add(("Stack", maxStack > 1 ? $"{stack:N0} / {maxStack:N0}" : stack.ToString("N0", Inv)));
int uses = I(o, IStructure, -1), maxUses = I(o, IMaxStructure, 0);
if (maxUses > 0 && uses >= 0) doc.Facts.Add(("Uses", $"{uses:N0} / {maxUses:N0}"));
else if (B(o, BUnlimitedUse)) doc.Facts.Add(("Uses", "unlimited"));
int maxMana = I(o, IMaxMana, 0);
if (maxMana > 0)
{
int cur = Math.Clamp(I(o, ICurMana, 0), 0, maxMana);
doc.Bars.Add(new AppraiseBar("Mana", (uint)cur, (uint)maxMana, cur / (float)maxMana, AppraiseBarKind.Mana));
}
Combat(o, t, doc);
Armor(o, t, doc);
Magic(o, doc);
Requirements(o, doc);
Properties(o, doc);
if (!o.Identified)
doc.Sections.Add(Note("Not appraised yet: asked the server. Only what the client saw is shown."));
}
private static void Combat(AppraisalInput o, uint t, AppraisalDoc doc)
{
bool melee = (t & TypeMelee) != 0, missile = (t & TypeMissile) != 0, caster = (t & TypeCaster) != 0;
bool anyDefense = HasF(o, FWeaponDefense) || HasF(o, FMissileDefense) || HasF(o, FMagicDefense);
if (!melee && !missile && !caster && !anyDefense) return;
var s = new AppraiseSection(caster ? "Caster" : "Weapon");
string skill = Skill(I(o, IWeaponSkill, 0));
if (skill.Length > 0 && !caster)
{
string mastery = MagItemInfoTables.Masteries.TryGetValue(I(o, IWeaponType, 0), out string? m) ? " (" + m + ")" : "";
s.Add("Skill: " + skill + mastery);
}
string dtype = DamageTypes(I(o, IDamageType, 0));
if (melee && Has(o, IDamage))
{
double max = I(o, IDamage, 0), variance = F(o, FDamageVariance, 0);
double min = max * (1 - variance);
s.Add($"Damage: {Num(min)} - {Num(max)}{(dtype.Length > 0 ? ", " + dtype : "")}");
}
if (missile)
{
if (HasF(o, FDamageMod)) s.Add($"Damage Modifier: {Pct(F(o, FDamageMod, 1) - 1)}.");
if (I(o, IElementalBonus, 0) is > 0 and var eb) s.Add($"Elemental Damage Bonus: {eb.ToString(Inv)}{(dtype.Length > 0 ? ", " + dtype : "")}.");
string ammo = I(o, IAmmoType, 0) switch { 1 => "arrows", 2 => "quarrels", 4 => "atlatl darts", _ => "" };
if (ammo.Length > 0) s.Add($"Uses {ammo} as ammunition.", AppraiseTone.Dim);
}
if ((melee || missile) && Has(o, IWeaponTime))
{
int speed = I(o, IWeaponTime, 0);
s.Add($"Speed: {SpeedName(speed)} ({speed.ToString(Inv)})");
}
if (HasF(o, FWeaponOffense) && Math.Abs(F(o, FWeaponOffense, 1) - 1) > 1e-6)
s.Add($"Bonus to Attack Skill: {Pct(F(o, FWeaponOffense, 1) - 1)}.", AppraiseTone.Good);
if (caster && HasF(o, FManaConversion) && F(o, FManaConversion, 0) > 1e-6)
s.Add($"Bonus to Mana Conversion: {Pct(F(o, FManaConversion, 0))}.", AppraiseTone.Good);
if (caster && HasF(o, FElementalMod) && F(o, FElementalMod, 1) > 1 + 1e-6)
{
double b = F(o, FElementalMod, 1) - 1;
string element = dtype.Length > 0 ? dtype : "all";
s.Add($"Damage bonus for {element} spells: {Pct(b)} vs. Monsters, {Pct(b / 4)} vs. Players.", AppraiseTone.Good);
}
if (HasF(o, FWeaponDefense) && Math.Abs(F(o, FWeaponDefense, 1) - 1) > 1e-6)
s.Add($"Bonus to Melee Defense: {Pct(F(o, FWeaponDefense, 1) - 1)}.", AppraiseTone.Good);
if (HasF(o, FMissileDefense) && Math.Abs(F(o, FMissileDefense, 1) - 1) > 1e-6)
s.Add($"Bonus to Missile Defense: {Pct(F(o, FMissileDefense, 1) - 1)}.", AppraiseTone.Good);
if (HasF(o, FMagicDefense) && Math.Abs(F(o, FMagicDefense, 1) - 1) > 1e-6)
s.Add($"Bonus to Magic Defense: {Pct(F(o, FMagicDefense, 1) - 1)}.", AppraiseTone.Good);
if (MagItemInfoTables.CreatureTypeName(I(o, ISlayerType, 0)) is { } slayer)
s.Add($"Slayer: {slayer}{(HasF(o, FSlayerBonus) ? $" (x{F(o, FSlayerBonus, 1).ToString("0.##", Inv)} damage)" : "")}", AppraiseTone.Good);
if (I(o, ICleaving, 0) is > 1 and var cleave) s.Add($"Cleaving: hits up to {cleave.ToString(Inv)} enemies.", AppraiseTone.Good);
string imbues = Imbues(o);
if (imbues.Length > 0) s.Add("Imbued: " + imbues, AppraiseTone.Good);
if (s.Lines.Count > 0) doc.Sections.Add(s);
}
private static void Armor(AppraisalInput o, uint t, AppraisalDoc doc)
{
if (!Has(o, IArmorLevel) && (t & (TypeArmor | TypeClothing)) == 0) return;
var s = new AppraiseSection("Armor");
int al = I(o, IArmorLevel, 0);
if (Has(o, IArmorLevel)) s.Add("Armor Level: " + al.ToString("N0", Inv));
if (al > 0)
foreach (var (key, label) in ArmorMods)
{
if (!HasF(o, key)) continue;
double mod = F(o, key, 1);
s.Add($"{label}: {ProtectionName(mod)} ({Math.Round(al * mod).ToString("N0", Inv)})", mod >= 1.2 ? AppraiseTone.Good : mod < 0.8 ? AppraiseTone.Bad : AppraiseTone.Text);
}
string covers = Coverage(I(o, IClothingPriority, 0));
if (covers.Length > 0) s.Add("Covers: " + covers, AppraiseTone.Dim);
if (s.Lines.Count > 0) doc.Sections.Add(s);
}
private static void Magic(AppraisalInput o, AppraisalDoc doc)
{
var s = new AppraiseSection("Magic");
if (o.Spells.Count > 0)
{
var names = new List<string>(o.Spells.Count);
foreach (uint id in o.Spells) names.Add(o.SpellName(id));
s.Add("Spells: " + string.Join(", ", names), AppraiseTone.Magic);
}
if (o.DataIds.TryGetValue(DSpell, out uint spell) && spell != 0 && !o.Spells.Contains(spell))
s.Add("Spell: " + o.SpellName(spell), AppraiseTone.Magic);
if (o.DataIds.TryGetValue(DProcSpell, out uint proc) && proc != 0)
s.Add("Casts on a hit: " + o.SpellName(proc), AppraiseTone.Magic);
int maxMana = I(o, IMaxMana, 0);
if (maxMana > 0) s.Add($"Mana: {Math.Clamp(I(o, ICurMana, 0), 0, maxMana):N0} / {maxMana:N0}");
double rate = F(o, FManaRate, 0);
if (rate < -1e-9)
{
double seconds = -1 / rate;
s.Add($"Mana Cost: 1 point per {Num(seconds)} seconds.", AppraiseTone.Dim);
}
if (I(o, ISpellcraft, 0) is > 0 and var sc) s.Add($"Spellcraft: {sc.ToString(Inv)}.");
if (s.Lines.Count > 0) doc.Sections.Add(s);
}
private static void Requirements(AppraisalInput o, AppraisalDoc doc)
{
var s = new AppraiseSection("Requirements");
for (int i = 0; i < WieldReq.Length; i++)
{
int req = I(o, WieldReq[i], 0);
if (req == 0) continue;
int what = I(o, WieldSkill[i], 0), diff = I(o, WieldDiff[i], 0);
s.Add(WieldLine(req, what, diff));
}
if (I(o, IArcaneLore, 0) is > 0 and var lore) s.Add($"Activation requires Arcane Lore: {lore.ToString(Inv)}");
if (o.DataIds.TryGetValue(DSkillLimit, out uint sk) && sk != 0)
{
int level = I(o, ISkillLevelLimit, 0);
s.Add($"Activation requires {Skill((int)sk)}{(level > 0 ? ": " + level.ToString(Inv) : "")}");
}
if (o.DataIds.TryGetValue(DSpecializedOnly, out uint spec) && spec != 0)
s.Add($"Activation requires specialized {Skill((int)spec)}");
if (I(o, IAllegianceRankLimit, 0) is > 0 and var rank) s.Add($"Activation requires Allegiance Rank: {rank.ToString(Inv)}");
if (I(o, IUseRequiresLevel, 0) is > 0 and var ul) s.Add($"Use requires level {ul.ToString(Inv)}");
int min = I(o, IMinLevel, 0), max = I(o, IMaxLevel, 0);
if (min > 0 && max > 0) s.Add($"Restricted to characters of levels {min.ToString(Inv)} to {max.ToString(Inv)}.");
else if (min > 0) s.Add($"Restricted to characters of level {min.ToString(Inv)} or greater.");
else if (max > 0) s.Add($"Restricted to characters of level {max.ToString(Inv)} or below.");
if (S(o, SPortalDest, "") is { Length: > 0 } dest) s.Add("Destination: " + dest);
if (s.Lines.Count > 0) doc.Sections.Add(s);
}
private static void Properties(AppraisalInput o, AppraisalDoc doc)
{
var s = new AppraiseSection("Properties");
int work = I(o, IWorkmanship, 0), items = I(o, INumItemsInMaterial, 0);
string material = MagItemInfoTables.Materials.TryGetValue(I(o, IMaterial, 0), out string? mat) ? mat : "";
if (work > 0 && items > 0)
s.Add($"Workmanship: {(work / (double)items).ToString("0.00", Inv)} (salvaged from {items.ToString(Inv)} item{(items == 1 ? "" : "s")})");
else if (work > 0) s.Add($"Workmanship: {WorkmanshipName(work)} ({work.ToString(Inv)})");
if (material.Length > 0) s.Add("Material: " + material);
if (MagItemInfoTables.EquipmentSets.TryGetValue(I(o, ISet, 0), out string? set)) s.Add("Set: " + set, AppraiseTone.Gold);
// Ratings (gear): "Damage Rating +3".
var ratings = new List<string>();
foreach (var (key, label) in Ratings)
if (I(o, key, 0) is > 0 and var r) ratings.Add($"{label} +{r.ToString(Inv)}");
if (ratings.Count > 0) s.Add("Ratings: " + string.Join(", ", ratings), AppraiseTone.Good);
if (I(o, IItemMaxLevel, 0) is > 0 and var maxLevel) s.Add($"Item levels: up to {maxLevel.ToString(Inv)}", AppraiseTone.Dim);
if (I(o, ITinkered, 0) is > 0 and var tinkered) s.Add($"This item has been tinkered {tinkered.ToString(Inv)} time{(tinkered == 1 ? "" : "s")}.");
if (S(o, SImbuer, "") is { Length: > 0 } imbuer) s.Add("Imbued by " + imbuer + ".", AppraiseTone.Dim);
if (S(o, STinker, "") is { Length: > 0 } tinker) s.Add("Last tinkered by " + tinker + ".", AppraiseTone.Dim);
if (S(o, SCraftsman, "") is { Length: > 0 } maker) s.Add("Created by " + maker + ".", AppraiseTone.Dim);
if (S(o, SPlating, "") is { Length: > 0 } plating) s.Add("Plating: " + plating, AppraiseTone.Dim);
var flags = new List<string>();
switch (I(o, IBonded, 0))
{
case 1: flags.Add("Bonded"); break;
case -1: flags.Add("Dropped on death"); break;
case -2: flags.Add("Destroyed on death"); break;
}
if (I(o, IAttuned, 0) == 1) flags.Add("Attuned (can't be given)");
if (B(o, BRetained)) flags.Add("Retained");
if (I(o, IResistMagic, 0) >= 9999) flags.Add("Unenchantable");
if (B(o, BIvoryable)) flags.Add("Ivoryable");
if (B(o, BDyable)) flags.Add("Dyeable");
if (B(o, BLocked)) flags.Add("Locked");
if (B(o, BInscribable)) flags.Add("Inscribable");
if (I(o, IUnique, 0) is > 0 and var unique) flags.Add($"Unique (carry {unique.ToString(Inv)})");
if (flags.Count > 0) s.Add("Properties: " + string.Join(", ", flags));
if (I(o, IRareId, 0) is > 0 and var rare) s.Add($"Rare #{rare.ToString(Inv)}", AppraiseTone.Gold);
if (I(o, IRemainingLifespan, 0) is > 0 and var life) s.Add("Time left: " + Duration(life), AppraiseTone.Bad);
if (I(o, ILockpickMod, 0) is > 0 and var pick) s.Add($"Bonus to Lockpick Skill: +{pick.ToString(Inv)}", AppraiseTone.Good);
if (HasF(o, FHealkitMod) && F(o, FHealkitMod, 1) > 1 + 1e-6) s.Add($"Bonus to Healing Skill: {Pct(F(o, FHealkitMod, 1) - 1)}", AppraiseTone.Good);
if (I(o, IBoostValue, 0) is var boost && boost != 0) s.Add($"Restores {Math.Abs(boost).ToString("N0", Inv)} points.", AppraiseTone.Good);
if (I(o, IItemsCapacity, 0) is > 0 and var cap)
s.Add($"Holds {cap.ToString(Inv)} items{(I(o, IContainersCapacity, 0) is > 0 and var packs ? $" and {packs.ToString(Inv)} packs" : "")}.", AppraiseTone.Dim);
if (S(o, SInscription, "") is { Length: > 0 } ins)
s.Add($"Inscription: \"{ins}\"{(S(o, SScribe, "") is { Length: > 0 } scribe ? " - " + scribe : "")}", AppraiseTone.Dim);
if (S(o, SUse, "") is { Length: > 0 } use) s.Add(use, AppraiseTone.Dim);
if (s.Lines.Count > 0) doc.Sections.Add(s);
}
private static readonly (uint Key, string Label)[] Ratings =
{
(370, "Damage"), (371, "Damage Resist"), (372, "Crit"), (373, "Crit Resist"), (374, "Crit Damage"),
(375, "Crit Damage Resist"), (376, "Healing Boost"), (377, "Nether Resist"), (378, "Life Resist"),
(379, "Max Health"), (383, "PK Damage"), (384, "PK Damage Resist"), (388, "Overpower"), (389, "Overpower Resist"),
};
// ── All properties ────────────────────────────────────────────────────────
private static void Raw(AppraisalInput o, AppraisalDoc doc)
{
foreach (var kv in Sorted(o.Ints)) doc.Raw.Add(new("Int", kv.Key, PropertyNames.GetIntName(kv.Key) ?? "?", kv.Value.ToString(Inv)));
foreach (var kv in Sorted(o.Int64s)) doc.Raw.Add(new("Int64", kv.Key, PropertyNames.GetInt64Name(kv.Key) ?? "?", kv.Value.ToString(Inv)));
foreach (var kv in Sorted(o.Floats)) doc.Raw.Add(new("Float", kv.Key, PropertyNames.GetFloatName(kv.Key) ?? "?", kv.Value.ToString("0.#####", Inv)));
foreach (var kv in Sorted(o.Bools)) doc.Raw.Add(new("Bool", kv.Key, PropertyNames.GetBoolName(kv.Key) ?? "?", kv.Value ? "true" : "false"));
foreach (var kv in Sorted(o.Strings)) doc.Raw.Add(new("String", kv.Key, PropertyNames.GetStringName(kv.Key) ?? "?", kv.Value));
foreach (var kv in Sorted(o.DataIds)) doc.Raw.Add(new("DataId", kv.Key, PropertyNames.GetDataIdName(kv.Key) ?? "?", $"0x{kv.Value:X8}"));
foreach (var kv in Sorted(o.InstanceIds)) doc.Raw.Add(new("InstanceId", kv.Key, PropertyNames.GetInstanceIdName(kv.Key) ?? "?", $"0x{kv.Value:X8}"));
for (int i = 0; i < o.Spells.Count; i++) doc.Raw.Add(new("Spell", o.Spells[i], o.SpellName(o.Spells[i]), o.Spells[i].ToString(Inv)));
}
private static List<KeyValuePair<uint, T>> Sorted<T>(Dictionary<uint, T> d)
{
var l = new List<KeyValuePair<uint, T>>(d);
l.Sort((a, b) => a.Key.CompareTo(b.Key));
return l;
}
// ── Wording ───────────────────────────────────────────────────────────────
/// <summary>"Wield requires Heavy Weapons 400", "... Strength 200", "... level 180", "... specialized Sword", "... Aluvian race".</summary>
internal static string WieldLine(int req, int what, int diff) => req switch
{
1 or 2 => $"Wield requires {(req == 2 ? "base " : "")}{Skill(what)} {diff.ToString(Inv)}",
3 or 4 => $"Wield requires {(req == 4 ? "base " : "")}{Attribute(what)} {diff.ToString(Inv)}",
5 or 6 => $"Wield requires {(req == 6 ? "base " : "")}{Vital(what)} {diff.ToString(Inv)}",
7 => $"Wield requires level {diff.ToString(Inv)}",
8 => $"Wield requires {(diff >= 3 ? "specialized" : "trained")} {Skill(what)}",
11 => $"Wield requires {MagItemInfoTables.CreatureTypeName(diff) ?? "creature " + diff.ToString(Inv)} type",
12 => $"Wield requires {Heritage(diff)} race",
_ => $"Wield requires {PropertyNames.GetIntName((uint)what) ?? "property " + what.ToString(Inv)} {diff.ToString(Inv)}",
};
private static string Skill(int id) => id > 0 && MagItemInfoTables.Skills.TryGetValue(id, out string? s) ? s : id > 0 ? "skill " + id.ToString(Inv) : "";
private static string Attribute(int id) => id switch
{
1 => "Strength", 2 => "Endurance", 3 => "Quickness", 4 => "Coordination", 5 => "Focus", 6 => "Self", _ => "attribute " + id.ToString(Inv),
};
private static string Vital(int id) => id switch
{
1 or 2 => "Health", 3 or 4 => "Stamina", 5 or 6 => "Mana", _ => "vital " + id.ToString(Inv),
};
private static string Heritage(int id) => id switch
{
1 => "Aluvian", 2 => "Gharu'ndim", 3 => "Sho", 4 => "Viamontian", 5 => "Umbraen", 6 => "Gear Knight", 7 => "Tumerok",
8 => "Lugian", 9 => "Empyrean", 10 => "Penumbraen", 11 => "Undead", 12 => "Olthoi", 13 => "Olthoi", _ => "",
};
private static string PkStatus(int status) => status switch
{
0x04 => "Player Killer",
0x40 => "PK Lite",
0x02 or 0x01 => "Non-Player Killer",
_ => "",
};
internal static string SpeedName(int speed) => speed switch
{
< 11 => "Very Fast",
< 31 => "Fast",
< 50 => "Average",
< 80 => "Slow",
_ => "Very Slow",
};
internal static string ProtectionName(double mod) => mod switch
{
< 0.4 => "Poor",
< 0.8 => "Below Average",
< 1.2 => "Average",
< 1.6 => "Above Average",
< 2.0 => "Excellent",
_ => "Superb",
};
internal static string WorkmanshipName(int w) => w switch
{
1 => "Poorly crafted", 2 => "Well-crafted", 3 => "Finely crafted", 4 => "Exquisitely crafted", 5 => "Magnificent",
6 => "Nearly flawless", 7 => "Flawless", 8 => "Utterly flawless", 9 => "Incomparable", 10 => "Priceless", _ => "",
};
/// <summary>DamageType flags as retail words: "Slashing/Piercing", "Fire".</summary>
internal static string DamageTypes(int flags)
{
if (flags <= 0) return string.Empty;
var parts = new List<string>(2);
if ((flags & 0x001) != 0) parts.Add("Slashing");
if ((flags & 0x002) != 0) parts.Add("Piercing");
if ((flags & 0x004) != 0) parts.Add("Bludgeoning");
if ((flags & 0x008) != 0) parts.Add("Cold");
if ((flags & 0x010) != 0) parts.Add("Fire");
if ((flags & 0x020) != 0) parts.Add("Acid");
if ((flags & 0x040) != 0) parts.Add("Electric");
if ((flags & 0x400) != 0) parts.Add("Nether");
return string.Join("/", parts);
}
/// <summary>ClothingPriority (CoverageMask) as body parts, outer layers first: "Chest, Abdomen, Upper Arms".</summary>
internal static string Coverage(int mask)
{
if (mask <= 0) return string.Empty;
var parts = new List<string>();
void Part(int bits, string name) { if ((mask & bits) != 0 && !parts.Contains(name)) parts.Add(name); }
Part(0x4000, "Head");
Part(0x0400 | 0x0008, "Chest");
Part(0x0800 | 0x0010, "Abdomen");
Part(0x1000 | 0x0020, "Upper Arms");
Part(0x2000 | 0x0040, "Lower Arms");
Part(0x8000, "Hands");
Part(0x0100 | 0x0002, "Upper Legs");
Part(0x0200 | 0x0004, "Lower Legs");
Part(0x10000, "Feet");
return string.Join(", ", parts);
}
private static string Imbues(AppraisalInput o)
{
int bits = I(o, IImbued, 0);
foreach (uint k in MoreImbues) bits |= I(o, k, 0);
if (bits == 0) return string.Empty;
var parts = new List<string>();
void Bit(int b, string name) { if ((bits & b) != 0) parts.Add(name); }
Bit(0x1, "Critical Strike"); Bit(0x2, "Crippling Blow"); Bit(0x4, "Armor Rending"); Bit(0x8, "Slash Rending");
Bit(0x10, "Pierce Rending"); Bit(0x20, "Bludgeon Rending"); Bit(0x40, "Acid Rending"); Bit(0x80, "Cold Rending");
Bit(0x100, "Lightning Rending"); Bit(0x200, "Fire Rending"); Bit(0x400, "Melee Defense"); Bit(0x800, "Missile Defense");
Bit(0x1000, "Magic Defense"); Bit(0x2000, "Spellbook"); Bit(0x4000, "Nether Rending");
return string.Join(", ", parts);
}
private static string Duration(int seconds)
{
var t = TimeSpan.FromSeconds(seconds);
if (t.TotalDays >= 1) return $"{(int)t.TotalDays}d {t.Hours}h";
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m";
return $"{t.Minutes}m {t.Seconds}s";
}
private static AppraiseSection Note(string text)
{
var s = new AppraiseSection("");
s.Add(text, AppraiseTone.Dim);
return s;
}
private static float Ratio(uint cur, uint max, float serverRatio) =>
serverRatio >= 0f ? serverRatio : max > 0 ? Math.Clamp(cur / (float)max, 0f, 1f) : 0f;
/// <summary>A fraction as retail's signed percent: 0.12 -> "+12%", -0.05 -> "-5%", 0.0375 -> "+3.75%".</summary>
internal static string Pct(double fraction)
{
double p = fraction * 100.0;
string s = Math.Abs(p - Math.Round(p)) < 0.005 ? Math.Round(p).ToString("0", Inv) : p.ToString("0.##", Inv);
return (p >= 0 ? "+" : "") + s + "%";
}
private static string Num(double v) => Math.Abs(v - Math.Round(v)) < 0.05 ? Math.Round(v).ToString("0", Inv) : v.ToString("0.#", Inv);
private static bool Has(AppraisalInput o, uint intKey) => o.Ints.ContainsKey(intKey);
private static bool HasF(AppraisalInput o, uint floatKey) => o.Floats.ContainsKey(floatKey);
private static int I(AppraisalInput o, uint key, int fallback) => o.Ints.TryGetValue(key, out int v) ? v : fallback;
private static double F(AppraisalInput o, uint key, double fallback) => o.Floats.TryGetValue(key, out double v) ? v : fallback;
private static bool B(AppraisalInput o, uint key) => o.Bools.TryGetValue(key, out bool v) && v;
private static string S(AppraisalInput o, uint key, string fallback) => o.Strings.TryGetValue(key, out string? v) && v.Length > 0 ? v : fallback;
}