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

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

View file

@ -0,0 +1,265 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>A board in Aelrynth's /top overview.</summary>
internal sealed class AelrynthBoardSummary
{
public string Key = "", Title = "", Leader = "", Value = "";
}
/// <summary>Your standing on one board ("/top me").</summary>
internal sealed class AelrynthStanding
{
public string Title = "";
public int Rank;
public int Of;
public string Value = "";
}
/// <summary>A line of the "/trial" overview: a dungeon's record, yours and this week's best.</summary>
internal sealed class TrialDungeon
{
public string Name = "", Landblock = "", Record = "", You = "", Week = "";
}
/// <summary>
/// Aelrynth's leaderboards (tag Aelrynth), read from the replies of the server's own commands
/// (ACEPublic Mods: Aeshnidae.Leaderboard /top, Aeshnidae.Trials /trial; one Broadcast line
/// each, numbers with thousands separators). Formats (Commands.cs):
/// /top "Leaderboards - N characters, refreshed X. /top &lt;board&gt; ..."
/// then " key Title: Leader, value" (or ": nobody yet")
/// /top &lt;board&gt; "Title - top K of N[, counted since ...][, per account]:"
/// then " r. Name value[ extra][ &lt;- you]", " ... you: #r with v", " nobody yet."
/// /top me "Name on the boards:" then " Title #r of N, value" or " Title -"
/// /trial a few intro lines, then " Dungeon (LLLL): records | you: ... | this week: ..."
/// /trial &lt;dungeon&gt; "Dungeon (LLLL) - top 10, best per character, any tier:"
/// then " r. m:ss Name (tier T, K kills, d MMM)" and " records per tier/you/this week" lines
/// Entry lines only count right after their header (within a few seconds), so ordinary chat
/// can't add rows. The two commands share /top with ConquestAC's very different reply, which is
/// why each parser only runs on its own server.
/// </summary>
internal sealed class AelrynthBoards
{
private const long BlockMs = 4000;
private static readonly Regex OverviewHeader = new(@"^\s*Leaderboards - ([\d,]+) characters, refreshed (.+?)\.\s");
private static readonly Regex OverviewEntry = new(@"^\s*(\S+)\s+(.+?): (?:(.+), ([\d,]+)|nobody yet)\s*$");
private static readonly Regex BoardHeader = new(@"^\s*(.+?) - top (\d+) of (\d+)(.*):\s*$");
private static readonly Regex BoardEntry = new(@"^\s*(\d+)\.\s+(.+?)\s+([\d,]+)(?:\s{2,}(?!<-)(.+?))?(\s{2,}<- you)?\s*$");
private static readonly Regex BoardYouBelow = new(@"^\s*\.\.\.\s+you: #(\d+) with ([\d,]+)\s*$");
private static readonly Regex MeHeader = new(@"^\s*(.+?) on the boards:\s*$");
private static readonly Regex MeEntry = new(@"^\s*(.+?)\s+#(\d+) of (\d+), ([\d,]+)\s*$");
private static readonly Regex MeNone = new(@"^\s*(.+?)\s+-\s*$");
private static readonly Regex OneMe = new(@"^\s*(.+?): you are #(\d+) of (\d+) with ([\d,]+)");
private static readonly Regex TopError = new(@"^\s*(?:No board called '|Leaderboards are unavailable|The boards are still being built)");
private static readonly Regex TrialDungeonLine = new(@"^\s*(.+?) \(([0-9A-Fa-f]{4})\): (.+?) \| you: (.+?) \| this week: (.+?)\s*$");
private static readonly Regex TrialBoardHeader = new(@"^\s*(.+?) \(([0-9A-Fa-f]{4})\) - top 10, best per character, any tier:\s*$");
private static readonly Regex TrialEntry = new(@"^\s*(\d+)\.\s+(\d+:\d{2}(?::\d{2})?)\s+(.+?) \((.+)\)\s*$");
private static readonly Regex TrialNote = new(@"^\s*(?:records per tier|you|this week \([^)]*\)):\s");
private static readonly Regex TrialError = new(@"^\s*(?:No Trial matches '|The Trials are switched off|The Trials could not be read)");
private static readonly Regex TrialIntro = new(@"^\s*Trials - a fresh personal copy of a listed dungeon");
private static readonly Regex TrialExtra = new(@"^\s*(?:your next attempt here: in \d+ min|running now: .+|Trophy: the week's fastest clear .+)$");
private enum Block { None, Overview, Board, Me, TrialList, TrialBoard }
public readonly List<AelrynthBoardSummary> Overview = new();
public string OverviewNote = "";
public string BoardTitle = "", BoardNote = "";
public readonly List<BoardRow> BoardRows = new();
public string BoardYou = "";
public readonly List<AelrynthStanding> Standings = new();
public readonly List<TrialDungeon> Trials = new();
public readonly List<string> TrialLines = new();
public string TrialBoardTitle = "";
public readonly List<BoardRow> TrialRows = new();
public readonly List<string> TrialNotes = new();
public string LastError = "";
public int Revision { get; private set; }
private Block _block;
private long _blockMs;
private readonly ChatRequest _topReq = new(), _trialReq = new();
public void Clear()
{
Overview.Clear(); BoardRows.Clear(); Standings.Clear(); Trials.Clear(); TrialLines.Clear(); TrialRows.Clear(); TrialNotes.Clear();
OverviewNote = BoardTitle = BoardNote = BoardYou = TrialBoardTitle = LastError = "";
_block = Block.None;
Revision++;
}
public string RequestTop(string arg, long now)
{
_topReq.Sent(now);
LastError = "";
if (string.IsNullOrWhiteSpace(arg)) { BoardTitle = ""; BoardRows.Clear(); }
return string.IsNullOrWhiteSpace(arg) ? "/top" : "/top " + arg.Trim();
}
public string RequestTrial(string arg, long now)
{
_trialReq.Sent(now);
LastError = "";
return string.IsNullOrWhiteSpace(arg) ? "/trial" : "/trial " + arg.Trim();
}
private bool InBlock(Block b, long now) => _block == b && now - _blockMs < BlockMs;
private void Start(Block b, long now) { _block = b; _blockMs = now; }
/// <summary>A chat line: true when it was a leaderboard reply; <paramref name="ours"/> = it answers RynthOracle's request.</summary>
public bool OnChatLine(string text, long now, out bool ours)
{
ours = false;
Match m;
if ((m = OverviewHeader.Match(text)).Success)
{
Overview.Clear();
OverviewNote = $"{m.Groups[1].Value} characters, refreshed {m.Groups[2].Value}";
Start(Block.Overview, now);
return Mine(_topReq, now, out ours);
}
if ((m = TrialBoardHeader.Match(text)).Success)
{
TrialBoardTitle = $"{m.Groups[1].Value} ({m.Groups[2].Value.ToUpperInvariant()})";
TrialRows.Clear();
TrialNotes.Clear();
Start(Block.TrialBoard, now);
return Mine(_trialReq, now, out ours);
}
if ((m = BoardHeader.Match(text)).Success && !text.Contains(" on the boards", StringComparison.Ordinal))
{
BoardTitle = m.Groups[1].Value.Trim();
BoardNote = $"top {m.Groups[2].Value} of {m.Groups[3].Value}{m.Groups[4].Value}";
BoardRows.Clear();
BoardYou = "";
Start(Block.Board, now);
return Mine(_topReq, now, out ours);
}
if ((m = MeHeader.Match(text)).Success)
{
Standings.Clear();
Start(Block.Me, now);
return Mine(_topReq, now, out ours);
}
if ((m = OneMe.Match(text)).Success)
{
BoardYou = $"{m.Groups[1].Value}: #{m.Groups[2].Value} of {m.Groups[3].Value} with {m.Groups[4].Value}";
return Mine(_topReq, now, out ours);
}
if (TopError.IsMatch(text))
{
LastError = text.Trim();
return Mine(_topReq, now, out ours);
}
if (TrialError.IsMatch(text))
{
LastError = text.Trim();
return Mine(_trialReq, now, out ours);
}
if ((m = TrialDungeonLine.Match(text)).Success)
{
if (!InBlock(Block.TrialList, now)) { Trials.Clear(); TrialLines.Clear(); }
Trials.Add(new TrialDungeon
{
Name = m.Groups[1].Value.Trim(), Landblock = m.Groups[2].Value.ToUpperInvariant(),
Record = m.Groups[3].Value.Trim(), You = m.Groups[4].Value.Trim(), Week = m.Groups[5].Value.Trim(),
});
Start(Block.TrialList, now);
return Mine(_trialReq, now, out ours);
}
if (InBlock(Block.Overview, now) && (m = OverviewEntry.Match(text)).Success)
{
Overview.Add(new AelrynthBoardSummary
{
Key = m.Groups[1].Value, Title = m.Groups[2].Value.Trim(),
Leader = m.Groups[3].Success ? m.Groups[3].Value.Trim() : "nobody yet",
Value = m.Groups[4].Success ? m.Groups[4].Value : "",
});
_blockMs = now;
return Mine(_topReq, now, out ours);
}
if (InBlock(Block.Board, now))
{
if ((m = BoardEntry.Match(text)).Success)
{
int.TryParse(m.Groups[1].Value, out int rank);
BoardRows.Add(new BoardRow
{
Rank = rank, Name = m.Groups[2].Value.Trim(), Value = m.Groups[3].Value,
Extra = m.Groups[4].Success ? m.Groups[4].Value.Trim() : "", IsYou = m.Groups[5].Success,
});
_blockMs = now;
return Mine(_topReq, now, out ours);
}
if ((m = BoardYouBelow.Match(text)).Success)
{
BoardYou = $"you: #{m.Groups[1].Value} with {m.Groups[2].Value}";
return Mine(_topReq, now, out ours);
}
if (text.Trim() == "nobody yet.") return Mine(_topReq, now, out ours);
}
if (InBlock(Block.Me, now))
{
if ((m = MeEntry.Match(text)).Success)
{
int.TryParse(m.Groups[2].Value, out int r);
int.TryParse(m.Groups[3].Value, out int of);
Standings.Add(new AelrynthStanding { Title = m.Groups[1].Value.Trim(), Rank = r, Of = of, Value = m.Groups[4].Value });
_blockMs = now;
return Mine(_topReq, now, out ours);
}
if ((m = MeNone.Match(text)).Success)
{
Standings.Add(new AelrynthStanding { Title = m.Groups[1].Value.Trim() });
_blockMs = now;
return Mine(_topReq, now, out ours);
}
}
if (InBlock(Block.TrialBoard, now))
{
if ((m = TrialEntry.Match(text)).Success)
{
int.TryParse(m.Groups[1].Value, out int rank);
TrialRows.Add(new BoardRow { Rank = rank, Value = m.Groups[2].Value, Name = m.Groups[3].Value.Trim(), Extra = m.Groups[4].Value.Trim() });
_blockMs = now;
return Mine(_trialReq, now, out ours);
}
if (TrialNote.IsMatch(text) || text.Trim() == "no clear yet")
{
TrialNotes.Add(text.Trim());
_blockMs = now;
return Mine(_trialReq, now, out ours);
}
}
// The rest of a /trial overview: the intro, "next attempt", "running now" and trophy lines.
if (TrialIntro.IsMatch(text))
{
Trials.Clear();
TrialLines.Clear();
TrialLines.Add(text.Trim());
Start(Block.TrialList, now);
return Mine(_trialReq, now, out ours);
}
if (InBlock(Block.TrialList, now) && TrialExtra.IsMatch(text))
{
TrialLines.Add(text.Trim());
_blockMs = now;
return Mine(_trialReq, now, out ours);
}
return false;
}
private bool Mine(ChatRequest req, long now, out bool ours)
{
ours = req.Awaiting(now);
req.Extend(now);
Revision++;
return true;
}
}

View file

@ -0,0 +1,168 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// One row of augmentations.csv: an XP augmentation (bought with experience) or a luminance
/// aura. Id is the PropertyInt that counts it, or a negative marker for the special rows
/// (upstream's scheme: -1 innate attributes, -2 innate resistances, -3 Asheron's Lesser
/// Benediction, -4..-8 luminance seers, -333..-336 the Falatacot/Dericost auras); 0 = a heading.
/// </summary>
internal sealed class Augmentation
{
public string Name = "";
public string Category = "";
public int Id;
public string Effect = "";
public string Cost = "";
public int TimesTotal;
public string Flag = "";
public string Url = "";
public string Hint = "";
private static readonly int[] InnateAttributeIds = { 218, 219, 220, 221, 222, 223 };
private static readonly int[] InnateResistanceIds = { 240, 241, 242, 243, 244, 245, 246 };
public bool IsHeading => Id == 0;
public bool IsXp => Category == "XP";
public bool IsLuminance => Category == "Luminance";
private bool IsInnateAttributes => Id == -1;
private bool IsInnateResistances => Id == -2;
private bool IsBenediction => Id == -3;
private bool IsSeer => Id <= -4 && Id >= -8;
private bool IsInnateAttribute => InnateAttributeIds.Contains(Id);
private bool IsInnateResistance => InnateResistanceIds.Contains(Id);
private bool IsLumSpecialization => Id <= -333 && Id >= -336;
/// <summary>The seers and the Falatacot/Dericost auras need a quest flag first (any solve).</summary>
public bool IsQuestComplete(QuestFlagStore flags) =>
Flag.Length > 0 && flags.TryGet(Flag, out QuestFlag q) && q.Solves > 0;
public int Times(Func<uint, int> prop, QuestFlagStore flags)
{
if (Flag.Length > 0 && !IsQuestComplete(flags)) return 0;
if (IsInnateAttributes) return InnateAttributeIds.Sum(id => prop((uint)id));
if (IsInnateResistances) return InnateResistanceIds.Sum(id => prop((uint)id));
if (IsBenediction) return 0; // upstream counts the item in inventory; not ported (see IsUnknown)
if (IsLumSpecialization) return Math.Max(prop((uint)Math.Abs(Id)) - 5, 0);
if (Id <= 0) return 0;
return Math.Min(prop((uint)Id), TimesTotal);
}
/// <summary>Rows RynthOracle can't read (Asheron's Lesser Benediction is an item, not a property).</summary>
public bool IsUnknown => IsBenediction;
public bool IsComplete(Func<uint, int> prop, QuestFlagStore flags)
{
if (TimesTotal == 0) return false;
if (IsInnateAttribute) return InnateAttributeIds.Sum(id => prop((uint)id)) >= 10;
if (IsInnateResistance) return InnateResistanceIds.Sum(id => prop((uint)id)) >= 2;
if (IsSeer) return IsQuestComplete(flags);
return Times(prop, flags) >= TimesTotal;
}
public string Text(Func<uint, int> prop, QuestFlagStore flags)
{
if (IsSeer) return "";
int t = Times(prop, flags);
if (TimesTotal == 0 || IsInnateAttribute || IsInnateResistance) return t.ToString();
return $"{t}/{TimesTotal}";
}
/// <summary>The next aura's cost in luminance (upstream's formula); blank when maxed or locked.</summary>
public string CostText(Func<uint, int> prop, QuestFlagStore flags)
{
if (IsXp) return Cost;
if (Id == 0 || IsSeer) return "";
int t = Times(prop, flags);
if (t >= TimesTotal) return "";
if (Flag.Length > 0 && !IsQuestComplete(flags)) return "";
if (Id == 365) return (100 + t * 100) + "k"; // World
if (Id == 344 || IsLumSpecialization) return (350 + t * 50) + "k"; // Specialization
return (100 + t * 50) + "k";
}
/// <summary>Luminance spent on this aura so far.</summary>
public long LuminanceSpent(Func<uint, int> prop, QuestFlagStore flags)
{
long t = Times(prop, flags);
if (t == 0) return 0;
if (Id == 365) return 100_000 * t * (t + 1) / 2;
if (Id == 344 || IsLumSpecialization) return t * (700_000 + (t - 1) * 50_000) / 2;
return t * (200_000 + (t - 1) * 50_000) / 2;
}
}
/// <summary>An aug-gem quest from augquests.csv (its timer is the flag's).</summary>
internal sealed class AugQuest
{
public string Name = "";
public string Flag = "";
public string Url = "";
public string Hint = "";
}
internal static class AugmentationList
{
/// <summary>All luminance auras maxed (upstream's figure).</summary>
public const long TotalLuminance = 19_000_000;
public static List<Augmentation> All { get; } = Load();
public static List<AugQuest> Quests { get; } = LoadQuests();
private static List<Augmentation> Load()
{
var list = new List<Augmentation>();
using StreamReader r = Csv.OpenEmbedded("augmentations.csv");
r.ReadLine(); // Name,Category,Id,Effect,Cost,Times,Flag,Url,Hint
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
list.Add(new Augmentation
{
Name = Csv.Field(f, 0),
Category = Csv.Field(f, 1),
Id = int.TryParse(Csv.Field(f, 2), out int id) ? id : 0,
Effect = Csv.Field(f, 3),
Cost = Csv.Field(f, 4),
TimesTotal = int.TryParse(Csv.Field(f, 5), out int t) ? t : 0,
Flag = Csv.Field(f, 6).ToLowerInvariant(),
Url = Csv.Field(f, 7),
Hint = Csv.Field(f, 8),
});
}
return list;
}
private static List<AugQuest> LoadQuests()
{
var list = new List<AugQuest>();
using StreamReader r = Csv.OpenEmbedded("augquests.csv");
r.ReadLine(); // Name,QuestFlag,Url,Hint
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
list.Add(new AugQuest
{
Name = Csv.Field(f, 0),
Flag = Csv.Field(f, 1).ToLowerInvariant(),
Url = Csv.Field(f, 2),
Hint = Csv.Field(f, 3),
});
}
return list;
}
public static long TotalLuminanceSpent(Func<uint, int> prop, QuestFlagStore flags) =>
All.Where(a => a.IsLuminance).Sum(a => a.LuminanceSpent(prop, flags));
public static Func<uint, int> PlayerProps(RynthCoreHost host, CharacterSnapshot c) => id => c.Int(host, id);
}

View file

@ -0,0 +1,196 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>An enchantment on the player: remaining seconds (double.PositiveInfinity = no timer).</summary>
internal readonly record struct ActiveEnchantment(uint SpellId, string Name, double Remaining, double Duration, bool Debuff);
internal readonly record struct SkillValue(bool Known, int Current, int Training);
/// <summary>
/// The player's state as the views need it, read from the engine on the pump thread (player
/// properties, skills, the enchantment snapshot). Rebuilt about once a second while a window
/// that shows it is open.
/// </summary>
internal sealed class CharacterSnapshot
{
// PropertyInt (ACE)
public const uint IntAvailableSkillCredits = 24;
public const uint IntLevel = 25;
public const uint IntNumDeaths = 43;
public const uint IntSocietyCelhan = 287;
public const uint IntSocietyEldweb = 288;
public const uint IntSocietyRadblo = 289;
public const uint IntAugSkilledMagic = 302; // Master of the Five Fold Path
public const uint IntAugJackOfAllTrades = 326;
public const uint IntLumAugSkilledSpec = 344; // Aura of Specialization
public const uint IntLumAugAllSkills = 365; // Aura of the World
public const uint IntEnlightenment = 390;
// PropertyInt64 (ACE)
public const uint QuadTotalExperience = 1;
public const uint QuadAvailableExperience = 2;
public const uint QuadAvailableLuminance = 6;
public const uint QuadMaximumLuminance = 7;
// Skills (ACE Skill)
public const uint SkillMeleeDefense = 6;
public const uint SkillLockpick = 23;
public const uint SkillLifeMagic = 33;
public const uint SkillVoidMagic = 43;
public const uint SkillSummoning = 54;
public bool Valid;
public uint PlayerId;
public string Name = "";
public int Level;
public long TotalXp, UnassignedXp, Luminance, MaxLuminance;
public int SkillCredits, Deaths, Enlightenment;
public int VitaePercent;
public SkillValue Lockpick, Life, MeleeDefense, Summoning, VoidMagic;
public readonly List<ActiveEnchantment> Enchantments = new();
public double ServerTime;
private readonly Dictionary<uint, int> _ints = new();
private uint[] _spellIds = new uint[512];
private double[] _expiry = new double[512];
/// <summary>A PropertyInt on the player (0 when the client doesn't have it), cached per read.</summary>
public int Int(RynthCoreHost host, uint id)
{
if (_ints.TryGetValue(id, out int v)) return v;
v = PlayerId != 0 && host.TryGetObjectIntProperty(PlayerId, id, out int x) ? x : 0;
_ints[id] = v;
return v;
}
public void Read(RynthCoreHost host)
{
_ints.Clear();
PlayerId = host.GetPlayerId();
Valid = PlayerId != 0;
if (!Valid) return;
Name = host.TryGetObjectName(PlayerId, out string n) ? n : "";
Level = Int(host, IntLevel);
SkillCredits = Int(host, IntAvailableSkillCredits);
Deaths = Int(host, IntNumDeaths);
Enlightenment = Int(host, IntEnlightenment);
TotalXp = Quad(host, QuadTotalExperience);
UnassignedXp = Quad(host, QuadAvailableExperience);
Luminance = Quad(host, QuadAvailableLuminance);
MaxLuminance = Quad(host, QuadMaximumLuminance);
float vitae = host.HasGetVitae ? host.GetVitae(PlayerId) : 1f;
VitaePercent = vitae > 0f && vitae < 1f ? (int)Math.Round((1f - vitae) * 100f) : 0;
ReadEnchantments(host);
bool cis = HasEnchantment(SpellIds.CloakedInSkill);
Lockpick = Skill(host, SkillLockpick, cis);
Life = Skill(host, SkillLifeMagic, cis);
MeleeDefense = Skill(host, SkillMeleeDefense, cis);
Summoning = Skill(host, SkillSummoning, cis);
VoidMagic = Skill(host, SkillVoidMagic, cis);
}
private long Quad(RynthCoreHost host, uint id) =>
host.HasGetObjectQuadProperty && host.TryGetObjectQuadProperty(PlayerId, id, out long v) ? v : 0;
private void ReadEnchantments(RynthCoreHost host)
{
Enchantments.Clear();
if (!host.HasReadPlayerEnchantments) return;
ServerTime = host.HasGetServerTime ? host.GetServerTime() : 0;
int count = host.ReadPlayerEnchantments(_spellIds, _expiry, _spellIds.Length);
for (int i = 0; i < count && i < _spellIds.Length; i++)
{
uint id = _spellIds[i];
double exp = _expiry[i];
SpellTable.TryGet(id, out SpellInfo info);
// No timer: a negative or absurd expiry (item-style and permanent enchantments).
double remaining = exp <= 0 || ServerTime <= 0 || exp - ServerTime > 3.0e7
? double.PositiveInfinity
: exp - ServerTime;
if (remaining <= 0) continue;
Enchantments.Add(new ActiveEnchantment(id, info.Name ?? $"Spell {id}", remaining, info.Duration, info.IsDebuff));
}
}
public bool HasEnchantment(uint spellId)
{
foreach (ActiveEnchantment e in Enchantments)
if (e.SpellId == spellId) return true;
return false;
}
/// <summary>
/// The skill as the server computes it: the client's buffed value plus what the client
/// doesn't count (Five Fold Path for Life, Aura of the World, Jack of All Trades, Aura of
/// Specialization, enlightenment, Cloaked in Skill), less an approximation of vitae.
/// Upstream's rules, unchanged.
/// </summary>
private SkillValue Skill(RynthCoreHost host, uint skill, bool cis)
{
if (!host.TryGetObjectSkill(PlayerId, skill, out int buffed, out int training))
return default;
bool trained = training == 2, specialized = training == 3;
if (!trained && !specialized) return new SkillValue(false, buffed, training);
int value = buffed;
if (skill == SkillLifeMagic) value += Int(host, IntAugSkilledMagic) * 10;
value += Int(host, IntLumAugAllSkills);
if (VitaePercent > 0)
value -= (int)Math.Round(value * (VitaePercent / 100.0)) - ((int)Math.Ceiling(VitaePercent / 2.0) + 1);
value += Int(host, IntAugJackOfAllTrades) * 5;
if (specialized) value += Int(host, IntLumAugSkilledSpec) * 2;
value += Enlightenment;
if (cis) value += 20;
return new SkillValue(true, value, training);
}
// ── Levels (retail table, cumulative XP to reach each level) ───────────
private static readonly long[] LevelXp =
{
0, 0, 1000, 2777, 5697, 10248, 17031, 26784, 40391, 58895, 83511,
115645, 156898, 209088, 274259, 354692, 452925, 571762, 714286, 883872, 1084206,
1319289, 1593459, 1911400, 2278153, 2699136, 3180153, 3727407, 4347513, 5047517, 5834900,
6717600, 7704021, 8803044, 10024047, 11376914, 12872048, 14520384, 16333408, 18323161, 20502261,
22883912, 25481915, 28310688, 31385275, 34721359, 38335275, 42244029, 46465302, 51017472, 55919623,
61191556, 66853809, 72927666, 79435170, 86399136, 93843170, 101791673, 110269863, 119303784, 128920317,
139147200, 150013037, 161547311, 173780397, 186743581, 200469064, 214989984, 230340425, 246555428, 263671011,
281724178, 300752932, 320796288, 341894292, 364088025, 387419625, 411932296, 437670319, 464679072, 493005039,
522695823, 553800159, 586367933, 620450186, 656099136, 693368187, 732311940, 772986213, 815448050, 859755734,
905968800, 954148054, 1004355577, 1056654747, 1111110248, 1167788081, 1226755584, 1288081441, 1351835695, 1418089761,
1486916445, 1558389948, 1632585888, 1709581309, 1789454692, 1872285975, 1958156562, 2047149336, 2139348672, 2234840456,
2333712089, 2436052509, 2541952200, 2651503203, 2764799136, 2881935203, 3003008207, 3128116563, 3257360317, 3390841150,
3528662400, 3670929071, 3817747844, 3969227097, 4125476914, 4286609098, 4452737184, 4623976457, 4800443961, 4982258511,
5169540711, 5362412965, 5560999488, 5765426325, 5975821358, 6192314325, 6415036828, 6644122352, 6879706272, 7121925872,
7370920356, 7626830859, 7889800466, 8159974219, 8437499136, 8722524219, 9015200473, 9315680913, 9624120583, 9940676567,
10265508000, 10598776087, 10940644110, 11291277447, 11650843580, 12019512114, 12397454784, 12784845474, 13181860228, 13588677261,
14005476978, 14432441981, 14869757088, 15317609341, 15776188025, 16245684675, 16726293095, 17218209369, 17721631872, 18236761289,
18763800622, 19302955209, 19854432732, 20418443236, 20995199136, 21584915236, 22187808740, 22804099263, 23434008850, 24077761983,
24735585600, 25407709103, 26094364377, 26795785797, 27512210247, 28243877131, 28991028384, 29753908491, 30532764494, 31327846011,
32139405244, 32967696998, 33812978688, 34675510358, 35555554692, 36453377025, 37369245362, 38303430385, 39256205472, 40227846705,
41218632889, 42228845559, 43258768999, 44308690253, 45378899136, 46469688253, 47581353006, 48714191613, 49868505116, 51044597400,
52242775200, 53463348120, 54706628644, 55972932147, 57262576914, 58575884147, 59913177984, 61274785507, 62661036761, 64072264761,
65508805511, 66970998015, 68459184288, 69973709375, 71514921358, 73083171375, 74678813628, 76302205402, 77953707072, 79633682122,
81342497156, 83080521909, 84848129266, 86645695269, 88473599136, 90332223269, 92221953273, 94143177963, 96096289383, 98081682817,
100099756800, 102150913137, 104235556910, 106354096497, 108506943580, 110694513164, 112917223584, 115175496524, 117469757028, 119800433511,
122167957778, 124572765031, 127015293888, 129495986391, 132015288025, 134573647725, 137171517895, 139809354419, 142487616672, 145206767539,
147967273422, 150769604259, 153614233532, 156501638286, 159432299136, 162406700286, 165425329540, 168488678313, 171597241650, 174751518233,
177952010400, 181199224153, 184493669177, 187835858847, 191226310247,
};
public const int MaxLevel = 275;
/// <summary>XP still needed for the next level, and the fraction of this level done; (0, 1) at 275 and above.</summary>
public (long ToNext, float Fraction) LevelProgress()
{
if (Level <= 0 || Level >= MaxLevel) return (0, 1f);
long start = LevelXp[Level], next = LevelXp[Level + 1];
long toNext = Math.Max(0, next - TotalXp);
float frac = next > start ? (float)Math.Clamp((double)(TotalXp - start) / (next - start), 0, 1) : 1f;
return (toNext, frac);
}
}

View file

@ -0,0 +1,24 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// RynthOracle sent a server command and expects its reply for a few seconds, so the chat
/// handler can tell its own reply from the same command typed by hand (only ours may be hidden).
/// A time window, as upstream: these replies carry nothing tying them to the request. Each line
/// of the reply extends it, so a long reply stays ours to its end.
/// </summary>
internal sealed class ChatRequest
{
private const long WindowMs = 5000;
private long _untilMs;
public void Sent(long nowMs) => _untilMs = nowMs + WindowMs;
public void Clear() => _untilMs = 0;
public bool Awaiting(long nowMs) => nowMs < _untilMs;
/// <summary>A reply line arrived: keep the window open a little longer.</summary>
public void Extend(long nowMs)
{
if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs;
}
}

View file

@ -0,0 +1,426 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>A labelled value from a server reply ("Pyreals" = "1,039,678,533 (4,158 MMDs)").</summary>
internal sealed class NamedValue
{
public string Name = "";
public string Value = "";
}
/// <summary>One of ConquestAC's advanced augmentations (counts from "/augs").</summary>
internal sealed class ConquestAug
{
public readonly string Name;
public readonly int CoinCost;
public readonly double LumBase, LumPercent;
public int Count;
public ConquestAug(string name, int coinCost, double lumBase, double lumPercent)
{
Name = name; CoinCost = coinCost; LumBase = lumBase; LumPercent = lumPercent;
}
/// <summary>The next purchase's luminance (Conquest-ACE's tiered cost, as upstream mirrors it).</summary>
public long NextLuminanceCost()
{
long idx = Count;
(double tierBase, long pos) = idx >= 65 ? (LumBase * 30.0, idx - 65)
: idx >= 60 ? (LumBase * 12.0, idx - 60)
: idx >= 30 ? (LumBase * 4.8, idx - 30)
: idx >= 15 ? (LumBase * 2.4, idx - 15)
: (LumBase, idx);
// The server truncates to long; the epsilon keeps 6,229,499.9999 (binary floating point) at the
// confirmed in-game 6,229,500 (Creature at 25).
return (long)(tierBase * (1.0 + pos * LumPercent) + 1e-6);
}
public string NextCostText() =>
$"{CoinCost} coins, {(NextLuminanceCost() / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture)}M lum";
private double ResistPercent()
{
const double MaxBonus = 0.32, LinearRate = 0.003, Tuning = 0.0034597;
const int LinearCap = 10;
if (Count <= 0) return 0.0;
double bonus = Count <= LinearCap
? Count * LinearRate
: LinearCap * LinearRate + (MaxBonus - LinearCap * LinearRate) * (1.0 - Math.Pow(1.0 - Tuning, Count - LinearCap));
return Math.Min(bonus, MaxBonus) * 100.0;
}
/// <summary>The effect at the current count (upstream's reading of the Conquest-ACE source).</summary>
public string Effect() => Name switch
{
"Creature" => $"+{Count} to creature buffs, -{Count} to debuffs",
"Item" => $"+{Count}% attack/melee, +{Count * 0.5:0.#} blood/spirit, +{Count} AL",
"Life" => $"+{ResistPercent():0.##}% prot, +{ResistPercent():0.##}% vuln, +{Count * 0.10:0.##} regen, +{Count / 10} surge rating",
"War" => $"+{Count * 2}% war magic potency",
"Void" => $"+{Count * 1.5:0.##}% void magic potency",
"Melee" => $"+{Count} melee damage, +{Count * 1.5:0.#}% crit damage",
"Missile" => $"+{Count} missile damage, +{Count * 1.5:0.#}% crit damage",
"Duration" => $"+{Count * 5}% spell duration",
"Specialization" => $"+{Count} skill spec cap (now {70 + Count})",
_ => "",
};
}
/// <summary>A fellowship from "/fship list".</summary>
internal sealed class ConquestFellowship
{
public string Name = "", Leader = "", Members = "", Location = "";
public int MemberCount
{
get
{
int slash = Members.IndexOf('/');
return int.TryParse(slash >= 0 ? Members[..slash] : Members, out int n) ? n : 0;
}
}
}
/// <summary>A row of a leaderboard.</summary>
internal sealed class BoardRow
{
public int Rank;
public string Name = "";
public string Value = "";
public string Extra = "";
public bool IsYou;
}
/// <summary>One of ConquestAC's /top boards.</summary>
internal sealed class ConquestBoard
{
public readonly string Key, Label, Header;
public readonly List<BoardRow> Rows = new();
public BoardRow? You;
public DateTime UpdatedUtc = DateTime.MinValue;
public ConquestBoard(string key, string label, string header) { Key = key; Label = label; Header = header; }
public string Command => "/top " + Key;
}
/// <summary>
/// Everything ConquestAC-only (tag Conquest): bank balances and bank commands ("/b", "/bank"),
/// advanced augmentations ("/augs"), enlightenment augmentations ("/enl augs"), the XP bonus
/// breakdown ("/bonus"), fellowships looking for members ("/fship list"), the /top boards, and
/// the void damage-over-time duration scaling. The plugin only feeds it chat and only shows it
/// while the server is ConquestAC; every reply regex is anchored at the start of the line (after
/// an optional chat timestamp), as upstream does, so a pasted copy in a chat channel can't
/// overwrite your values.
/// </summary>
internal sealed class ConquestData
{
private const string Ts = @"^\s*(?:\[[^\]]*\][\s:]*)?";
// /b balances
private static readonly Regex BankLine = new(Ts + @"\[BANK\]\s+(.+?):\s*(.*\S)\s*$");
private static readonly Regex BankChrome = new(Ts + @"\[BANK\]\s+[^:]*:\s*$");
private static readonly Regex EventToken = new(@"Event Tokens \[(.+?)\]");
private static readonly Regex DepositReply = new(Ts + @"(?:No .+? (?:found|available) to deposit|Deposited\b.*)\s*$", RegexOptions.IgnoreCase);
// /augs
private static readonly Regex AugLine = new(Ts + @"(Creature|Item|Life|War|Void|Duration|Specialization|Melee|Missile):\s*([\d,]+)\b");
private static readonly Regex AugChrome = new(Ts + @"(?:-{3,}|Advanced Augmentation Levels:|Use /aug info for per-level effect details\.)\s*$", RegexOptions.IgnoreCase);
// /enl augs
private static readonly Regex EnlLine = new(Ts + @"([A-Za-z][A-Za-z '\-]*?):\s*(([\d,]+)\s*\(\s*[\d,]+\s+max\s*\))\s*$");
private static readonly Regex EnlChrome = new(Ts + @"Enlightenment Augmentations:\s*$");
// /bonus
private static readonly Regex BonusLine = new(Ts + @"(Quest|Enlightenment|PK Dungeon|Augmentation|Equipment|Total) Bonus(?:\s*\(([^)]+)\))?:\s*(.+\S)\s*$");
private static readonly Regex BonusChrome = new(Ts + @"={2,}\s*XP Bonuses\s*={2,}\s*$");
// /fship list
private static readonly Regex FshipHeader = new(Ts + @"Fellowships looking for members");
private static readonly Regex FshipLine = new(Ts + @"-\s+(.+?)\s+\(Leader:\s+(.+?)\)\s+\[(\d+/\d+)\](?:\s+@\s+(.+?))?\s*$");
// /top
private static readonly Regex TopHeader = new(Ts + @"Top\s+(\d+)\s+Players?\s+by\s+(.+?):\s*$");
private static readonly Regex TopEntry = new(Ts + @"(\d+):\s+([\d,]+)\s+-\s+(.+?)\s*$");
private static readonly Regex TopSeparator = new(Ts + @"\.\.\.\s*$");
private static readonly string[] EnlOrder =
{
"Damage", "Damage Reduction", "Crit Damage", "Crit Damage Reduction", "Imbue", "Salvage", "Skill Credits",
"Stamina Benediction", "Mana Benediction", "Cleave", "Arrow Split", "Spell Chain", "Aetheria Surge", "Void Contagion",
};
private static readonly Dictionary<string, string> EnlCosts = new(StringComparer.OrdinalIgnoreCase)
{
["Cleave"] = "1 Pristine Token", ["Arrow Split"] = "1 Pristine Token", ["Spell Chain"] = "1 Pristine Token",
["Aetheria Surge"] = "1 Pristine Token", ["Void Contagion"] = "1 Pristine Token",
["Damage"] = "2 Tokens", ["Damage Reduction"] = "2 Tokens", ["Crit Damage"] = "2 Tokens",
["Crit Damage Reduction"] = "2 Tokens", ["Imbue"] = "2 Tokens", ["Salvage"] = "2 Tokens",
["Skill Credits"] = "4 Tokens", ["Stamina Benediction"] = "4 Tokens", ["Mana Benediction"] = "4 Tokens",
};
public const int PyrealsPerMmd = 250_000;
public readonly List<NamedValue> Bank = new();
public readonly List<ConquestAug> Augs = new()
{
new("Creature", 25, 2_500_000, 0.003825), new("Item", 100, 3_000_000, 0.006825), new("Life", 75, 2_500_000, 0.0095),
new("War", 50, 1_750_000, 0.00425), new("Void", 50, 1_800_000, 0.00425), new("Duration", 30, 1_400_000, 0.00625),
new("Specialization", 125, 3_000_000, 0.02), new("Melee", 50, 1_750_000, 0.00425), new("Missile", 50, 1_750_000, 0.00425),
};
public List<NamedValue> EnlAugs { get; private set; } = new();
public readonly List<NamedValue> Bonuses = new()
{
new() { Name = "Quest" }, new() { Name = "Enlightenment" }, new() { Name = "PK Dungeon" }, new() { Name = "Augmentation" },
new() { Name = "Equipment" }, new() { Name = "Total (Kills)" }, new() { Name = "Total (Quest/Lum)" },
};
public readonly List<ConquestFellowship> Fellowships = new();
public readonly List<ConquestBoard> Boards = new()
{
new("augs", "Augs", "Total Augmentations"), new("deaths", "Deaths", "Deaths"), new("enl", "Enlightens", "Enlightenment"),
new("level", "Levels", "Level"), new("lum", "Luminance", "Banked Luminance"), new("bank", "Pyreals", "Banked Pyreals"),
new("qb", "QB", "Quest Bonus"), new("titles", "Titles", "Titles"),
};
public DateTime BankUtc = DateTime.MinValue, AugsUtc = DateTime.MinValue, EnlUtc = DateTime.MinValue,
BonusUtc = DateTime.MinValue, FshipUtc = DateTime.MinValue;
public int Revision { get; private set; }
private readonly ChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(),
_topReq = new(), _depositReq = new();
private ConquestBoard? _collecting;
private long _collectingMs;
private int _collectingExpected = int.MaxValue;
private bool _collectingCleared;
public static string EnlCost(string name) => EnlCosts.TryGetValue(name, out string? c) ? c : "";
public int AugTotal => Augs.Sum(a => a.Count);
public int DurationAugs => Augs.First(a => a.Name == "Duration").Count;
public void Clear()
{
Bank.Clear();
foreach (ConquestAug a in Augs) a.Count = 0;
EnlAugs = new List<NamedValue>();
foreach (NamedValue b in Bonuses) b.Value = "";
Fellowships.Clear();
foreach (ConquestBoard b in Boards) { b.Rows.Clear(); b.You = null; b.UpdatedUtc = DateTime.MinValue; }
BankUtc = AugsUtc = EnlUtc = BonusUtc = FshipUtc = DateTime.MinValue;
_collecting = null;
Revision++;
}
// ── Requests (the plugin sends the command; each returns the command text) ──
public string RequestBank(long now) { _bankReq.Sent(now); return "/b"; }
public string RequestAugs(long now) { _augReq.Sent(now); return "/augs"; }
public string RequestEnl(long now) { _enlReq.Sent(now); return "/enl augs"; }
public string RequestBonus(long now) { _bonusReq.Sent(now); return "/bonus"; }
public string RequestFships(long now) { _fshipReq.Sent(now); Fellowships.Clear(); Revision++; return "/fship list"; }
public string RequestBoard(ConquestBoard board, long now)
{
_topReq.Sent(now);
Open(board, now);
return "/top " + board.Key;
}
/// <summary>An automatic deposit: its reply is ours to hide.</summary>
public string AutoDeposit(long now) { _depositReq.Sent(now); return "/bank deposit"; }
/// <summary>
/// A chat line: true when it was a reply this module reads; <paramref name="ours"/> = it
/// answers a request RynthOracle sent (eligible to be hidden).
/// </summary>
public bool OnChatLine(string text, long now, out bool ours)
{
ours = false;
Match m;
if (_depositReq.Awaiting(now) && DepositReply.IsMatch(text)) { ours = true; _depositReq.Extend(now); return true; }
if ((m = BankLine.Match(text)).Success)
{
string name = EventToken.Replace(m.Groups[1].Value.Trim(), "$1");
string value = m.Groups[2].Value.Trim();
if (name == "Pyreals" && long.TryParse(value.Replace(",", ""), out long py))
value += $" ({(py / PyrealsPerMmd).ToString("N0", CultureInfo.InvariantCulture)} MMDs)";
NamedValue? e = Bank.FirstOrDefault(b => b.Name == name);
if (e != null) e.Value = value; else Bank.Add(new NamedValue { Name = name, Value = value });
BankUtc = DateTime.UtcNow;
return Done(_bankReq, now, out ours);
}
if (_bankReq.Awaiting(now) && BankChrome.IsMatch(text)) return Done(_bankReq, now, out ours);
if ((m = AugLine.Match(text)).Success)
{
ConquestAug? a = Augs.FirstOrDefault(x => x.Name == m.Groups[1].Value);
if (a != null && int.TryParse(m.Groups[2].Value.Replace(",", ""), out int c)) a.Count = c;
AugsUtc = DateTime.UtcNow;
return Done(_augReq, now, out ours);
}
if (_augReq.Awaiting(now) && AugChrome.IsMatch(text)) return Done(_augReq, now, out ours);
if (EnlChrome.IsMatch(text))
{
EnlAugs = new List<NamedValue>();
return Done(_enlReq, now, out ours);
}
if ((m = EnlLine.Match(text)).Success)
{
// "Label: N (M max)" is specific to the "/enl augs" reply (its header starts a fresh list).
string name = m.Groups[1].Value.Trim();
var list = new List<NamedValue>(EnlAugs.Where(x => x.Name != name)) { new() { Name = name, Value = m.Groups[2].Value.Trim() } };
list.Sort((x, y) => Rank(x.Name).CompareTo(Rank(y.Name)));
EnlAugs = list;
EnlUtc = DateTime.UtcNow;
return Done(_enlReq, now, out ours);
}
if ((m = BonusLine.Match(text)).Success)
{
string q = m.Groups[2].Value.Trim();
string name = q.Length > 0 ? $"{m.Groups[1].Value} ({q})" : m.Groups[1].Value;
NamedValue? b = Bonuses.FirstOrDefault(x => x.Name == name);
if (b != null) b.Value = m.Groups[3].Value.Trim();
BonusUtc = DateTime.UtcNow;
return Done(_bonusReq, now, out ours);
}
if (_bonusReq.Awaiting(now) && BonusChrome.IsMatch(text)) return Done(_bonusReq, now, out ours);
if (FshipHeader.IsMatch(text))
{
if (!_fshipReq.Awaiting(now)) Fellowships.Clear();
FshipUtc = DateTime.UtcNow;
return Done(_fshipReq, now, out ours);
}
if ((m = FshipLine.Match(text)).Success)
{
Fellowships.Add(new ConquestFellowship
{
Name = m.Groups[1].Value.Trim(), Leader = m.Groups[2].Value.Trim(), Members = m.Groups[3].Value.Trim(),
Location = m.Groups[4].Success ? m.Groups[4].Value.Trim() : "",
});
FshipUtc = DateTime.UtcNow;
return Done(_fshipReq, now, out ours);
}
if ((m = TopHeader.Match(text)).Success)
{
ConquestBoard? board = Active(now) ?? Boards.FirstOrDefault(b => b.Header.Equals(m.Groups[2].Value.Trim(), StringComparison.OrdinalIgnoreCase));
if (board == null) return false;
Open(board, now);
ClearOnce();
_collectingExpected = int.TryParse(m.Groups[1].Value, out int n) ? n : int.MaxValue;
return Done(_topReq, now, out ours);
}
if ((m = TopEntry.Match(text)).Success && Active(now) is ConquestBoard cb)
{
ClearOnce();
int.TryParse(m.Groups[1].Value, out int rank);
string name = m.Groups[3].Value.Trim();
var row = new BoardRow { Rank = rank, Value = m.Groups[2].Value.Trim(), Name = name };
if (name.EndsWith("(You)", StringComparison.OrdinalIgnoreCase))
{
row.IsYou = true;
row.Name = name[..^5].Trim();
cb.You = row;
}
if (rank <= _collectingExpected && cb.Rows.All(r => r.Rank != rank)) cb.Rows.Add(row);
cb.Rows.Sort((x, y) => x.Rank.CompareTo(y.Rank));
cb.UpdatedUtc = DateTime.UtcNow;
_collectingMs = now;
return Done(_topReq, now, out ours);
}
if (Active(now) != null && TopSeparator.IsMatch(text)) return Done(_topReq, now, out ours);
return false;
}
private bool Done(ChatRequest req, long now, out bool ours)
{
ours = req.Awaiting(now);
req.Extend(now);
Revision++;
return true;
}
private static int Rank(string name)
{
int i = Array.FindIndex(EnlOrder, n => n.Equals(name, StringComparison.OrdinalIgnoreCase));
return i < 0 ? EnlOrder.Length : i;
}
private void Open(ConquestBoard board, long now)
{
if (_collecting == board && now - _collectingMs < 15_000) return;
_collecting = board;
_collectingMs = now;
_collectingExpected = int.MaxValue;
_collectingCleared = false;
}
private ConquestBoard? Active(long now) => _collecting != null && now - _collectingMs < 15_000 ? _collecting : null;
private void ClearOnce()
{
if (_collectingCleared || _collecting == null) return;
_collecting.Rows.Clear();
_collecting.You = null;
_collectingCleared = true;
}
// ── Bank commands (Conquest-ACE's /bank; tokens are its one-letter currency codes) ──
public sealed record Currency(string Label, string Token, long Multiplier = 1, long Max = long.MaxValue);
public static readonly Currency[] Withdrawable =
{
new("Conquest Coins", "c"), new("Event Tokens", "e"), new("Legendary Keys", "k"), new("Pyreals", "p"),
new("Soul Fragments", "s"), new("MMD Notes (250k)", "n"), new("MM Notes (200k)", "n MM"), new("M Notes (100k)", "n M"),
new("D Notes (50k)", "n D"), new("C Notes (10k)", "n C"), new("L Notes (5k)", "n L"), new("X Notes (1k)", "n X"),
new("V Notes (500)", "n V"), new("I Notes (100)", "n I"),
};
public const int DefaultWithdraw = 5; // MMD notes
public static readonly Currency[] Transferable =
{
new("Legendary Keys", "k"), new("Luminance", "l"), new("MMD Notes (250k)", "p", 250_000, 1_000), new("Pyreals", "p"),
};
public const int DefaultTransfer = 1; // Luminance
/// <summary>"/bank withdraw &lt;token&gt; &lt;n&gt;", or null when the amount isn't a whole number above 0.</summary>
public static string? WithdrawCommand(Currency c, string amount) =>
long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) && n > 0 ? $"/bank withdraw {c.Token} {n}" : null;
/// <summary>"/bank transfer &lt;token&gt; &lt;n&gt; "name"", or null when the amount or name isn't usable.</summary>
public static string? TransferCommand(Currency c, string amount, string target)
{
target = (target ?? "").Trim().Replace("\"", "");
if (target.Length == 0 || !long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) || n <= 0 || n > c.Max) return null;
try { return $"/bank transfer {c.Token} {checked(n * c.Multiplier)} \"{target}\""; }
catch (OverflowException) { return null; }
}
// ── Levels and enlightenment (ConquestAC's levels 276-300, upstream's table) ──
private static readonly long[] Levels276To300 =
{
194665023377, 198152685223, 201689992550, 205277652043, 208916380445,
212606904701, 216349962105, 220146300445, 223996678153, 227901864460,
231862639544, 235879794689, 239954132442, 244086466776, 248277623248,
252528439169, 256839763767, 261212458359, 265647396522, 270145464270,
274707560226, 279334595807, 284027495403, 288787196561, 293614650176,
};
public const int MaxLevel = 300;
/// <summary>Total XP to reach a level 276-300 (0 otherwise).</summary>
public static long XpForLevel(int level) => level >= 276 && level <= 300 ? Levels276To300[level - 276] : 0;
private static double EnlMultiplier(int target) => target >= 75 ? 7.5 : target >= 50 ? 5.0 : target >= 25 ? 2.5 : 1.0;
public static long EnlCoinCost(int target) => (long)(target * 100 * EnlMultiplier(target));
public static long EnlLuminanceCost(int target) => (long)(target * 1_000_000L * EnlMultiplier(target));
/// <summary>Void DoT duration on ConquestAC: × (1 + Archmage's Endurance × 0.2 + Duration augs × 0.05).</summary>
public double VoidDurationMultiplier(int archmagesEndurance) => 1.0 + archmagesEndurance * 0.2 + DurationAugs * 0.05;
}

View file

@ -0,0 +1,73 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>The bundled lists (embedded CSVs) and a small RFC 4180 line parser.</summary>
internal static class Csv
{
/// <summary>Opens an embedded resource by its logical name (RynthOracle.&lt;file&gt;).</summary>
public static StreamReader OpenEmbedded(string fileName)
{
Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RynthOracle." + fileName)
?? throw new FileNotFoundException("Embedded resource not found: " + fileName);
return new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
}
/// <summary>Header names (lower case, trimmed) to column index.</summary>
public static Dictionary<string, int> MapColumns(string header)
{
var map = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
string[] names = ParseLine(header);
for (int i = 0; i < names.Length; i++)
{
string n = names[i].Trim().TrimStart('');
if (n.Length > 0 && !map.ContainsKey(n)) map[n] = i;
}
return map;
}
public static int Column(Dictionary<string, int> map, params string[] names)
{
foreach (string n in names)
if (map.TryGetValue(n, out int i)) return i;
return -1;
}
public static string Field(string[] fields, int index) =>
index >= 0 && index < fields.Length ? fields[index].Trim() : string.Empty;
/// <summary>Splits one CSV line: commas separate, double quotes enclose, "" is a quote.</summary>
public static string[] ParseLine(string line)
{
var fields = new List<string>();
var sb = new StringBuilder();
bool quoted = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (quoted)
{
if (c == '"')
{
if (i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; }
else quoted = false;
}
else sb.Append(c);
}
else if (c == '"') quoted = true;
else if (c == ',') { fields.Add(sb.ToString()); sb.Clear(); }
else sb.Append(c);
}
fields.Add(sb.ToString());
return fields.ToArray();
}
public static bool IsTrue(string s) =>
s.Equals("true", StringComparison.OrdinalIgnoreCase) || s.Equals("yes", StringComparison.OrdinalIgnoreCase)
|| s == "1" || s.Equals("verified", StringComparison.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,59 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// A server's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint). Each
/// row carries its server tag, so only the current server's rows show (today: ConquestAC's).
/// A repeatable counts as done only while on cooldown (upstream's rule).
/// </summary>
internal sealed class CustomQuest
{
public string Server = "", Name = "", Flag = "", Url = "", Hint = "";
public bool IsComplete(QuestFlagStore flags, DateTime utcNow)
{
if (!flags.TryGet(Flag, out QuestFlag q)) return false;
if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0;
return !q.Ready(utcNow);
}
public string Status(QuestFlagStore flags, DateTime utcNow)
{
if (!flags.TryGet(Flag, out QuestFlag q)) return "ready";
if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0 ? "completed" : "ready";
return q.NextAvailable(utcNow);
}
}
internal static class CustomQuestList
{
public static List<CustomQuest> All { get; } = Load();
public static IEnumerable<CustomQuest> For(ServerIdentity server)
{
foreach (CustomQuest q in All)
if (server.Is(q.Server)) yield return q;
}
private static List<CustomQuest> Load()
{
var list = new List<CustomQuest>();
using StreamReader r = Csv.OpenEmbedded("customquests.csv");
r.ReadLine(); // Server,Name,QuestFlag,Url,Hint
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
list.Add(new CustomQuest
{
Server = Csv.Field(f, 0), Name = Csv.Field(f, 1), Flag = Csv.Field(f, 2).ToLowerInvariant(),
Url = Csv.Field(f, 3), Hint = Csv.Field(f, 4),
});
}
return list;
}
}

View file

@ -0,0 +1,55 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// One of the 100 Dereth exploration markers (markers.csv). Each group of ten shares a quest
/// flag whose solve count is a bit field (explorationmarkersfoundingroupa..j, max 1023 on
/// Aelrynth's quest table); a marker is found when its bit is set (upstream's rule).
/// </summary>
internal sealed class Marker
{
public int Number;
public string Name = "";
public string Location = "";
public int BitMask;
public string Flag = "";
public string Hint = "";
public bool IsFound(QuestFlagStore flags) =>
flags.TryGet(Flag, out QuestFlag q) && (q.Solves & BitMask) == BitMask;
public string Url => "https://acportalstorm.com/wiki/Dereth_Exploration/Markers_by_Efficiency#" + Location.Replace(" ", "_");
}
internal static class MarkerList
{
/// <summary>The flag counting all markers found.</summary>
public const string CountFlag = "explorationmarkersfound";
public static List<Marker> All { get; } = Load();
private static List<Marker> Load()
{
var list = new List<Marker>();
using StreamReader r = Csv.OpenEmbedded("markers.csv");
r.ReadLine(); // Number,Name,Location,BitMask,QuestFlag,Hint
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
list.Add(new Marker
{
Number = int.TryParse(Csv.Field(f, 0), out int n) ? n : 0,
Name = Csv.Field(f, 1),
Location = Csv.Field(f, 2),
BitMask = int.TryParse(Csv.Field(f, 3), out int b) ? b : 0,
Flag = Csv.Field(f, 4).ToLowerInvariant(),
Hint = Csv.Field(f, 5),
});
}
return list;
}
}

View file

@ -0,0 +1,331 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>One quest: a base (retail) row, a server pack row, or a held flag no list knows.</summary>
internal sealed class Quest
{
public string Flag = "";
/// <summary>"" for a retail quest; the server tag for a row from that server's pack.</summary>
public string Server = "";
public string Name = "";
public string Url = "";
public string Info = "";
public string Hint = "";
/// <summary>The list's Repeatable column (known for every quest, earned or not).</summary>
public bool Repeatable;
/// <summary>A flag from /myquests that no list knows.</summary>
public bool IsNew;
/// <summary>From a server pack: the repeat timer in seconds (-1 unknown) and solve limit (null unknown).</summary>
public long MinDelta = -1;
public int? MaxSolves;
/// <summary>From a server pack: who sets the flag ("set by Monroe").</summary>
public string Source = "";
/// <summary>The row had a Repeatable value (a pack row without one doesn't override the base).</summary>
internal bool HasRepeatable;
/// <summary>Pack row: the base quest's flag can't be read on this server (hide it there).</summary>
internal bool NotOnServer;
/// <summary>The Name column: the curated name, else the one-line info, else "Unknown quest" (upstream's rule).</summary>
public string DisplayName => Name.Length > 0 ? Name : Info.Length > 0 ? Info : "Unknown quest";
/// <summary>The server is the source of truth where it has spoken (the flag's timer); else the lists.</summary>
public bool IsRepeatable(QuestFlagStore flags) =>
flags.TryGet(Flag, out QuestFlag q) ? q.RepeatTime != TimeSpan.Zero : Repeatable;
/// <summary>Holding the flag at all is the test: /myquests only reports flags the character earned.</summary>
public bool IsComplete(QuestFlagStore flags) => flags.Flags.ContainsKey(Flag);
/// <summary>"ready" (never earned or off cooldown), "completed" (one-time), "maxed" (solve limit) or the countdown.</summary>
public string Status(QuestFlagStore flags, DateTime utcNow)
{
if (!flags.TryGet(Flag, out QuestFlag q)) return "ready";
if (!IsRepeatable(flags)) return "completed";
if (q.AtSolveLimit) return "maxed";
return q.NextAvailable(utcNow);
}
public string SolvesText(QuestFlagStore flags) =>
flags.TryGet(Flag, out QuestFlag q) && IsRepeatable(flags) ? q.Solves.ToString() : "";
/// <summary>The info blurb, the walkthrough and (from a server pack) who sets it and its timer, as one line.</summary>
public string Details()
{
string d;
if (Info.Length == 0) d = Hint;
else if (Hint.Length == 0 || string.Equals(Info, Hint, StringComparison.OrdinalIgnoreCase)) d = Info;
else d = Info + " " + Hint;
var extra = new List<string>();
if (Source.Length > 0) extra.Add(Source);
if (MinDelta > 0) extra.Add("repeats after " + TimeText.Friendly(TimeSpan.FromSeconds(MinDelta)));
if (MaxSolves is int m && m > 0) extra.Add(m == 1 ? "once only" : $"at most {m} times");
if (extra.Count > 0) d = (d.Length > 0 ? d + " " : "") + "(" + string.Join("; ", extra) + ")";
return d;
}
}
/// <summary>
/// The quest catalog: the base list (every retail quest: Oracle of Dereth's curated master
/// list, or a newer download of it) plus the current server's quest pack.
///
/// Packs: Resources\quests.&lt;tag&gt;.csv embedded as "RynthOracle.quests.&lt;tag&gt;.csv" (Conquest and
/// Levistras: Advis's server-specific rows; Aelrynth: generated from the world database by
/// Tools\RynthOracle.QuestPackGen). A file %APPDATA%\RynthCore\RynthOracle\packs\quests.&lt;tag&gt;.csv
/// replaces the embedded pack, so a regenerated pack can be tried without a rebuild. A new
/// server only needs a tag (ServerTags) and a pack file.
///
/// Pack columns: the base list's (QuestFlag, Quest, Url, Info, Hint, Repeatable) plus optional
/// MinDelta, MaxSolves, Source and NotOnServer. Merge: a pack row for a flag the base list has
/// keeps the base row's text (Advis's) and only fills its empty fields, adding the timer and
/// source; other pack rows are added; NotOnServer=TRUE hides a base row on that server (its
/// flag can't be read there). A base list row with a Server value (a downloaded master list)
/// is treated as that server's pack row.
/// </summary>
internal sealed class QuestCatalog
{
private readonly List<Quest> _quests = new();
private readonly Dictionary<string, Quest> _byFlag = new(StringComparer.OrdinalIgnoreCase);
public IReadOnlyList<Quest> Quests => _quests;
public int RetailCount { get; private set; }
public int ServerCount { get; private set; }
public int HiddenCount { get; private set; }
public string PackServer { get; private set; } = "";
public string PackSource { get; private set; } = "";
public bool UsingBundled { get; private set; } = true;
public string Source => UsingBundled ? "bundled list" : "downloaded list";
public int KnownCount => RetailCount + ServerCount;
public int Revision { get; private set; }
public static string DownloadedPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "quests.csv");
public static string PackOverridePath(string tag) => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "packs",
$"quests.{tag.ToLowerInvariant()}.csv");
/// <summary>The servers with an embedded quest pack.</summary>
public static IEnumerable<string> EmbeddedPacks() =>
Assembly.GetExecutingAssembly().GetManifestResourceNames()
.Where(n => n.StartsWith("RynthOracle.quests.", StringComparison.Ordinal) && n.EndsWith(".csv", StringComparison.Ordinal)
&& n.Length > "RynthOracle.quests..csv".Length)
.Select(n => n["RynthOracle.quests.".Length..^4]);
/// <summary>Loads the base list (downloaded when valid, else bundled) and the pack for <paramref name="serverTag"/>.</summary>
public void Load(string serverTag, Action<string>? log)
{
List<Quest>? baseRows = null;
UsingBundled = true;
if (File.Exists(DownloadedPath))
{
try
{
using var reader = new StreamReader(DownloadedPath);
baseRows = ReadRows(reader, "", out string? why);
if (baseRows == null) log?.Invoke($"[RynthOracle] The downloaded quest list is unusable ({why}); using the bundled one.");
else UsingBundled = false;
}
catch (Exception ex)
{
log?.Invoke($"[RynthOracle] Couldn't read the downloaded quest list ({ex.Message}); using the bundled one.");
}
}
if (baseRows == null)
{
using StreamReader bundled = Csv.OpenEmbedded("quests.csv");
baseRows = ReadRows(bundled, "", out _) ?? new List<Quest>();
}
List<Quest>? packRows = null;
PackServer = "";
PackSource = "";
if (serverTag.Length > 0)
{
string over = PackOverridePath(serverTag);
try
{
if (File.Exists(over))
{
using var r = new StreamReader(over);
packRows = ReadRows(r, serverTag, out string? why);
if (packRows != null) PackSource = "file " + over;
else log?.Invoke($"[RynthOracle] {over} is unusable ({why}); using the bundled {serverTag} pack.");
}
}
catch (Exception ex)
{
log?.Invoke($"[RynthOracle] Couldn't read {over} ({ex.Message}).");
}
if (packRows == null && EmbeddedPacks().Any(t => t.Equals(serverTag, StringComparison.OrdinalIgnoreCase)))
{
using StreamReader r = Csv.OpenEmbedded($"quests.{serverTag.ToLowerInvariant()}.csv");
packRows = ReadRows(r, serverTag, out _);
if (packRows != null) PackSource = "bundled pack";
}
if (packRows != null) PackServer = serverTag;
}
Build(baseRows, packRows ?? new List<Quest>(), serverTag);
}
private void Build(List<Quest> baseRows, List<Quest> packRows, string serverTag)
{
_quests.Clear();
_byFlag.Clear();
int retail = 0, server = 0, hidden = 0;
// Base rows tied to a server (a downloaded master list) are that server's pack rows.
var pack = new List<Quest>();
foreach (Quest q in baseRows)
{
if (q.Server.Length == 0)
{
if (_byFlag.TryAdd(q.Flag, q)) { _quests.Add(q); retail++; }
}
else if (serverTag.Length > 0 && q.Server.Equals(serverTag, StringComparison.OrdinalIgnoreCase))
{
q.Server = serverTag;
pack.Add(q);
}
}
pack.AddRange(packRows);
var hide = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (Quest p in pack)
{
if (p.NotOnServer) { hide.Add(p.Flag); continue; }
if (_byFlag.TryGetValue(p.Flag, out Quest? b))
{
// Advis's text wins; the pack fills gaps and adds what only the server knows.
if (b.Name.Length == 0) b.Name = p.Name;
if (b.Url.Length == 0) b.Url = p.Url;
if (b.Info.Length == 0) b.Info = p.Info;
if (b.Hint.Length == 0) b.Hint = p.Hint;
if (p.MinDelta >= 0) b.MinDelta = p.MinDelta;
if (p.MaxSolves != null) b.MaxSolves = p.MaxSolves;
if (p.Source.Length > 0) b.Source = p.Source;
if (p.HasRepeatable) b.Repeatable = p.Repeatable;
}
else
{
p.Server = serverTag;
_byFlag[p.Flag] = p;
_quests.Add(p);
server++;
}
}
if (hide.Count > 0)
{
hidden = _quests.RemoveAll(q => q.Server.Length == 0 && hide.Contains(q.Flag));
foreach (string f in hide) if (_byFlag.TryGetValue(f, out Quest? q) && q.Server.Length == 0) _byFlag.Remove(f);
retail -= hidden;
}
RetailCount = retail;
ServerCount = server;
HiddenCount = hidden;
Revision++;
}
/// <summary>Checks a CSV is a usable master list (header with a flag column, enough rows).</summary>
public static bool Validate(string csv, out string why)
{
using var reader = new StringReader(csv);
string? header = reader.ReadLine();
if (header == null) { why = "empty"; return false; }
if (Csv.Column(Csv.MapColumns(header), "questflag", "flag") < 0) { why = "no quest flag column"; return false; }
int rows = 0;
while (reader.ReadLine() is string line)
if (!string.IsNullOrWhiteSpace(line)) rows++;
if (rows < 1000) { why = $"only {rows} rows"; return false; }
why = "";
return true;
}
/// <summary>Reads quest rows; <paramref name="packServer"/> "" for a base list. Null when unusable.</summary>
private static List<Quest>? ReadRows(TextReader reader, string packServer, out string? why)
{
string? header = reader.ReadLine();
if (header == null) { why = "empty"; return null; }
Dictionary<string, int> cols = Csv.MapColumns(header);
int flagCol = Csv.Column(cols, "questflag", "flag");
if (flagCol < 0) { why = "no quest flag column"; return null; }
int serverCol = Csv.Column(cols, "server", "world");
int nameCol = Csv.Column(cols, "quest", "questname", "name", "title");
int urlCol = Csv.Column(cols, "url", "link", "wiki");
int infoCol = Csv.Column(cols, "info", "notes", "description");
int hintCol = Csv.Column(cols, "hint", "hints", "directions", "walkthrough");
int repeatCol = Csv.Column(cols, "repeatable", "repeat");
int deltaCol = Csv.Column(cols, "mindelta");
int maxCol = Csv.Column(cols, "maxsolves");
int sourceCol = Csv.Column(cols, "source");
int notOnCol = Csv.Column(cols, "notonserver");
var rows = new List<Quest>();
while (reader.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
string flag = Csv.Field(f, flagCol).ToLowerInvariant();
if (flag.Length == 0) continue;
string rep = Csv.Field(f, repeatCol);
var q = new Quest
{
Flag = flag,
Server = packServer.Length > 0 ? packServer : Csv.Field(f, serverCol),
Name = Csv.Field(f, nameCol),
Url = Csv.Field(f, urlCol),
Info = Csv.Field(f, infoCol),
Hint = Csv.Field(f, hintCol),
Repeatable = Csv.IsTrue(rep),
HasRepeatable = rep.Length > 0,
Source = Csv.Field(f, sourceCol),
NotOnServer = Csv.IsTrue(Csv.Field(f, notOnCol)),
};
if (long.TryParse(Csv.Field(f, deltaCol), out long d) && d >= 0) q.MinDelta = d;
if (int.TryParse(Csv.Field(f, maxCol), out int m)) q.MaxSolves = m;
rows.Add(q);
}
if (rows.Count == 0) { why = "no rows"; return null; }
why = null;
return rows;
}
public bool TryGet(string flag, out Quest q) => _byFlag.TryGetValue(flag, out q!);
/// <summary>Adds rows for held flags no list knows, and drops such rows no longer held.</summary>
public void SyncDiscoveries(QuestFlagStore flags)
{
bool changed = false;
for (int i = _quests.Count - 1; i >= 0; i--)
{
Quest q = _quests[i];
if (q.IsNew && !flags.Flags.ContainsKey(q.Flag))
{
_quests.RemoveAt(i);
_byFlag.Remove(q.Flag);
changed = true;
}
}
foreach (QuestFlag f in flags.Flags.Values)
{
if (_byFlag.ContainsKey(f.Key)) continue;
var q = new Quest
{
Flag = f.Key,
Name = f.Description.Replace("\"", "").Replace("'", "").Trim(),
Repeatable = f.RepeatTime != TimeSpan.Zero,
IsNew = true,
};
_quests.Add(q);
_byFlag[q.Flag] = q;
changed = true;
}
if (changed) Revision++;
}
}

View file

@ -0,0 +1,104 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// Optional daily check for a newer master quest list at upstream's address (off by default).
/// The download runs on a pool thread and only writes a file; the pump picks the result up
/// (<see cref="TakeResult"/>) and reloads the catalog. <see cref="Shutdown"/> cancels and waits,
/// so nothing of the plugin is left running when it unloads.
/// </summary>
internal sealed class QuestCatalogUpdater
{
public const string Url = "https://raw.githubusercontent.com/advis61/OracleOfDereth/master/OracleOfDereth/Resources/quests.csv";
public static readonly TimeSpan Interval = TimeSpan.FromDays(1);
private CancellationTokenSource? _cts;
private Task? _task;
private volatile string? _result; // a message for the pump: what happened
private volatile bool _updated; // a new file was written
public bool Running => _task is { IsCompleted: false };
/// <summary>Starts a check unless one is running. Pump thread.</summary>
public void Start()
{
if (Running) return;
_cts?.Dispose();
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
_task = Task.Run(() => RunAsync(token));
}
/// <summary>Pump thread: the outcome of the last check, once. updated = reload the catalog.</summary>
public string? TakeResult(out bool updated)
{
string? r = _result;
updated = false;
if (r == null) return null;
_result = null;
updated = _updated;
_updated = false;
return r;
}
private async Task RunAsync(CancellationToken token)
{
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthOracle/0.1");
string csv = await http.GetStringAsync(Url, token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (!QuestCatalog.Validate(csv, out string why))
{
_result = $"The downloaded quest list was not usable ({why}); kept the current one.";
return;
}
string path = QuestCatalog.DownloadedPath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
if (File.Exists(path) && File.ReadAllText(path) == csv)
{
_result = "The quest list is up to date.";
return;
}
string tmp = path + ".tmp";
File.WriteAllText(tmp, csv);
File.Move(tmp, path, overwrite: true);
_updated = true;
_result = "Downloaded a newer quest list.";
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// Shutting down.
}
catch (Exception ex)
{
_result = $"Couldn't check for a newer quest list: {ex.GetType().Name}: {ex.Message}";
}
}
/// <summary>Cancels a running check and waits for it (at most 3 s). Pump thread.</summary>
public void Shutdown()
{
try
{
_cts?.Cancel();
_task?.Wait(TimeSpan.FromSeconds(3));
}
catch { }
finally
{
_cts?.Dispose();
_cts = null;
_task = null;
}
}
}

View file

@ -0,0 +1,185 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>One quest flag the character holds, as /myquests reports it.</summary>
internal sealed class QuestFlag
{
public string Key = "";
public string Description = "";
public int Solves;
/// <summary>-1 = no limit (ACE).</summary>
public int MaxSolves = -1;
public DateTime CompletedOnUtc = DateTime.MinValue;
public TimeSpan RepeatTime = TimeSpan.Zero;
public TimeSpan NextAvailableTime(DateTime utcNow) => CompletedOnUtc + RepeatTime - utcNow;
/// <summary>ACE: a quest with a solve limit that has reached it can never be solved again.</summary>
public bool AtSolveLimit => MaxSolves > -1 && Solves >= MaxSolves;
public bool Ready(DateTime utcNow) => NextAvailableTime(utcNow).TotalSeconds <= 0;
public string NextAvailable(DateTime utcNow)
{
TimeSpan d = NextAvailableTime(utcNow);
return d.TotalSeconds > 0 ? TimeText.Friendly(d) : "ready";
}
}
/// <summary>What one chat line is, as far as /myquests goes.</summary>
internal enum MyQuestsLine { None, Quest, Empty, Disabled }
/// <summary>
/// The character's quest flags, read from the server's /myquests reply (ACE: one Broadcast line
/// per flag, "name - N solves (unix)"message" maxSolves minDelta"). Every reply is the whole
/// list, so a burst of lines replaces the flags once it goes quiet, whoever asked: RynthOracle,
/// the player, or RynthAi's meta manager (which polls and hides its own replies).
///
/// Threads: everything runs on the plugin pump, except <see cref="NoteTypedCommand"/>, which the
/// chat bar calls on AC's thread (it only touches interlocked fields).
/// </summary>
internal sealed class QuestFlagStore
{
// Optional chat timestamp, then the flag line. Anchored so a pasted 'Bob says, "x - 1 solves (0)"'
// can't inject a flag (upstream's hardening). ACE puts no space between ")" and the quote.
private static readonly Regex LineRegex = new(
@"^\s*(?:(?:\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?\s+)|(?:\[[^\]]+\][\s:]*))*"
+ @"(?<key>\S+) - (?<solves>-?\d+) solves \((?<completed>\d{0,11})\)\s*""?(?:(?<desc>.*)"" (?<max>-?\d+) (?<delta>\d+))?\s*$",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
public const string EmptyText = "Quest list is empty.";
public const string DisabledText = "The command \"myquests\" is not currently enabled on this server.";
private const int QuietMs = 1500; // a reply is complete once no line came for this long
private const int RequestTimeoutMs = 10_000;
private const int MinRequestGapMs = 5_000;
public Dictionary<string, QuestFlag> Flags { get; private set; } = new(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, QuestFlag>? _pending;
private long _lastLineMs;
public DateTime LastReadUtc { get; private set; } = DateTime.MinValue;
public bool ServerDisabled { get; private set; }
/// <summary>Bumps whenever the flags change (views rebuild their caches on it).</summary>
public int Revision { get; private set; }
// Our own request: its reply may be hidden from chat.
public bool AwaitingOurs { get; private set; }
private long _requestedMs = long.MinValue / 2;
private int _selfSends; // our "/myquests" sends not yet seen by the chat bar
private int _typedByPlayer; // the player typed /myquests (AC's thread sets it)
public bool Loading => _pending != null || AwaitingOurs;
/// <summary>Sends /myquests unless one went out moments ago. Returns false if nothing was sent.</summary>
public bool Request(Func<string, bool> invokeChat, long nowMs)
{
if (nowMs - _requestedMs < MinRequestGapMs) return false;
_requestedMs = nowMs;
Interlocked.Increment(ref _selfSends);
if (!invokeChat("/myquests"))
{
Interlocked.Decrement(ref _selfSends);
return false;
}
AwaitingOurs = true;
return true;
}
/// <summary>AC's thread (chat bar): a "/myquests" went through it. Ours, or typed by the player?</summary>
public void NoteTypedCommand()
{
if (Interlocked.Decrement(ref _selfSends) >= 0) return;
Interlocked.Exchange(ref _selfSends, 0);
Interlocked.Exchange(ref _typedByPlayer, 1);
}
/// <summary>Classifies a chat line and takes in its flag.</summary>
public MyQuestsLine OnChatLine(string? text, long nowMs)
{
if (string.IsNullOrEmpty(text)) return MyQuestsLine.None;
string line = text.Trim();
if (line.EndsWith(EmptyText, StringComparison.Ordinal))
{
_pending = new Dictionary<string, QuestFlag>(StringComparer.OrdinalIgnoreCase);
_lastLineMs = nowMs - QuietMs; // nothing follows it
ServerDisabled = false;
return MyQuestsLine.Empty;
}
if (line.EndsWith(DisabledText, StringComparison.Ordinal))
{
ServerDisabled = true;
AwaitingOurs = false;
Revision++;
return MyQuestsLine.Disabled;
}
if (line.IndexOf(" solves (", StringComparison.Ordinal) < 0) return MyQuestsLine.None;
QuestFlag? flag = Parse(line);
if (flag == null) return MyQuestsLine.None;
_pending ??= new Dictionary<string, QuestFlag>(StringComparer.OrdinalIgnoreCase);
_pending[flag.Key] = flag;
_lastLineMs = nowMs;
ServerDisabled = false;
return MyQuestsLine.Quest;
}
/// <summary>Pump tick: completes a reply once it has gone quiet.</summary>
public void Tick(long nowMs)
{
if (Interlocked.Exchange(ref _typedByPlayer, 0) != 0)
AwaitingOurs = false; // the player asked too: their reply shows in chat
if (_pending != null && nowMs - _lastLineMs >= QuietMs)
{
Flags = _pending;
_pending = null;
LastReadUtc = DateTime.UtcNow;
AwaitingOurs = false;
Revision++;
}
else if (AwaitingOurs && _pending == null && nowMs - _requestedMs > RequestTimeoutMs)
{
AwaitingOurs = false; // no reply (not in world, server busy)
}
}
public void Clear()
{
Flags = new Dictionary<string, QuestFlag>(StringComparer.OrdinalIgnoreCase);
_pending = null;
AwaitingOurs = false;
LastReadUtc = DateTime.MinValue;
ServerDisabled = false;
Revision++;
}
public bool TryGet(string flag, out QuestFlag q) => Flags.TryGetValue(flag, out q!);
internal static QuestFlag? Parse(string line)
{
Match m = LineRegex.Match(line);
if (!m.Success) return null;
var q = new QuestFlag
{
Key = m.Groups["key"].Value.ToLowerInvariant(),
Description = m.Groups["desc"].Value.Trim().Trim('"').Trim(),
};
int.TryParse(m.Groups["solves"].Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out q.Solves);
if (m.Groups["max"].Success && int.TryParse(m.Groups["max"].Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int max))
q.MaxSolves = max;
if (long.TryParse(m.Groups["completed"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out long completed) && completed > 0)
q.CompletedOnUtc = DateTime.UnixEpoch.AddSeconds(completed);
if (m.Groups["delta"].Success && long.TryParse(m.Groups["delta"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out long delta))
q.RepeatTime = TimeSpan.FromSeconds(Math.Min(delta, (long)TimeSpan.MaxValue.TotalSeconds / 2));
return q;
}
}

View file

@ -0,0 +1,119 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>The servers RynthOracle has server-specific features or data packs for.</summary>
internal static class ServerTags
{
public const string Aelrynth = "Aelrynth";
public const string Conquest = "Conquest";
public const string Levistras = "Levistras";
/// <summary>Tags with a quest pack (Resources\quests.&lt;tag&gt;.csv) or features.</summary>
public static readonly string[] Known = { Aelrynth, Conquest, Levistras };
}
/// <summary>
/// Which server this client is on, decided once per login and re-checked each second until
/// known. Server-specific features and data packs carry a tag (<see cref="ServerTags"/>) and
/// only load or show where <see cref="Allows"/> says so; untagged (retail) ones work anywhere.
///
/// Sources, best first:
/// 1. Engine API v75 GetServerInfo: the engine's own verdict for Aelrynth (connect host,
/// announced world name, Bank mod properties) and the world name the server announced
/// at login. Never the launcher profile name.
/// 2. Older engines: the world name (GetWorldName; the server's own once logged in, though
/// it falls back to the launcher profile name before that) and, for Aelrynth, the Bank
/// mod's player properties 9101-9103, which only Aelrynth sends.
/// Aelrynth's live config still names the world "Aeshnidae" (its earlier name); both count.
/// ConquestAC and Levistras are matched on their world names, as upstream does
/// (Decal's CharacterFilter.Server).
/// </summary>
internal sealed class ServerIdentity
{
private const uint QuadRadianceEarned = 9101, QuadLuminanceBanked = 9102, QuadLuminanceDrawn = 9103;
/// <summary>A known tag, or "" (a server without its own features: retail features only).</summary>
public string Tag { get; private set; } = "";
public string WorldName { get; private set; } = "";
public string Source { get; private set; } = "not logged in";
public bool Known => WorldName.Length > 0 || Tag.Length > 0;
public int Revision { get; private set; }
public bool Is(string tag) => Tag.Length > 0 && string.Equals(Tag, tag, StringComparison.OrdinalIgnoreCase);
/// <summary>Untagged features always; tagged ones only on their own server.</summary>
public bool Allows(string? tag) => string.IsNullOrEmpty(tag) || Is(tag);
public void Reset()
{
Set("", "", "not logged in");
}
public void Refresh(RynthCoreHost host, uint playerId)
{
string tag, world, source;
if (host.TryGetServerInfo(out bool aelrynth, out bool staging, out string announced))
{
world = announced;
if (aelrynth)
{
tag = ServerTags.Aelrynth;
source = staging ? "engine: Aelrynth (staging)" : "engine: Aelrynth";
}
else
{
// The engine's Aelrynth verdict is the authority (it already weighs the world name,
// and /rc server other overrides it for testing): never Aelrynth from the name here.
tag = TagForWorld(world);
if (tag == ServerTags.Aelrynth) tag = "";
source = world.Length > 0 ? $"engine: the server calls itself \"{world}\"" : "engine: world name not announced yet";
}
}
else
{
world = host.TryGetWorldName(out string w) ? w.Trim() : "";
tag = TagForWorld(world);
source = world.Length > 0 ? $"world name \"{world}\" (older engine)" : "world name not known yet (older engine)";
if (tag.Length == 0 && playerId != 0 && HasBankProperties(host, playerId))
{
tag = ServerTags.Aelrynth;
source = "the Aelrynth Bank properties (older engine)";
}
}
Set(tag, world, source);
}
/// <summary>The tag for a world name; "" for servers without their own features.</summary>
public static string TagForWorld(string? world)
{
if (string.IsNullOrWhiteSpace(world)) return "";
string w = world.Trim();
if (w.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase) || w.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase))
return ServerTags.Aelrynth;
if (w.Equals(ServerTags.Conquest, StringComparison.OrdinalIgnoreCase) || w.Equals("ConquestAC", StringComparison.OrdinalIgnoreCase))
return ServerTags.Conquest;
if (w.Equals(ServerTags.Levistras, StringComparison.OrdinalIgnoreCase))
return ServerTags.Levistras;
return "";
}
private static bool HasBankProperties(RynthCoreHost host, uint playerId) =>
host.HasGetObjectQuadProperty
&& (host.TryGetObjectQuadProperty(playerId, QuadRadianceEarned, out _)
|| host.TryGetObjectQuadProperty(playerId, QuadLuminanceBanked, out _)
|| host.TryGetObjectQuadProperty(playerId, QuadLuminanceDrawn, out _));
private void Set(string tag, string world, string source)
{
if (tag == Tag && world == WorldName && source == Source) return;
Tag = tag;
WorldName = world;
Source = source;
Revision++;
}
/// <summary>For tests: a fixed identity.</summary>
internal void Force(string tag, string world) => Set(tag, world, "forced");
}

View file

@ -0,0 +1,150 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// Society membership and rank from the rank properties (PropertyInt 287 Celestial Hand,
/// 288 Eldrytch Web, 289 Radiant Blood: the ribbon count, sent at login), and the daily ribbon
/// count from the societyribbonsperday* flags. Upstream's thresholds and rules.
/// </summary>
internal readonly struct SocietyStanding
{
public readonly int Value;
public readonly string SocietyName;
public SocietyStanding(int celhan, int eldweb, int radblo)
{
if (celhan > 0) { Value = celhan; SocietyName = "Celestial Hand"; }
else if (eldweb > 0) { Value = eldweb; SocietyName = "Eldrytch Web"; }
else if (radblo > 0) { Value = radblo; SocietyName = "Radiant Blood"; }
else { Value = 0; SocietyName = "None"; }
}
public bool IsMember => Value > 0;
public string RankName =>
Value > 1000 ? "Master" : Value > 600 ? "Lord" : Value > 300 ? "Knight" : Value > 100 ? "Adept" : Value > 0 ? "Initiate" : "None";
public string NextRankName =>
Value > 994 ? "" : Value > 600 ? "Master" : Value > 300 ? "Lord" : Value > 100 ? "Knight" : Value > 0 ? "Adept" : "";
/// <summary>Ribbons per day by rank, up to Lord; a Master has no daily limit.</summary>
public int DailyLimit => Value > 1000 ? 0 : Value > 600 ? 200 : Value > 300 ? 150 : Value > 100 ? 100 : Value > 0 ? 50 : 0;
private int NextThreshold => Value > 994 ? 0 : Value > 600 ? 995 : Value > 300 ? 595 : Value > 100 ? 295 : Value > 0 ? 95 : 0;
/// <summary>At the floor of a rank (1, 101, 301, 601, 1001): the +1 came from the promotion.</summary>
public bool FreshlyPromoted => Value is 1 or 101 or 301 or 601 or 1001;
/// <summary>Ribbons turned in (the rank value without a promotion's +1).</summary>
public int Progress => FreshlyPromoted ? Value - 1 : Value;
public int RibbonsToNextRank => NextThreshold == 0 ? 0 : NextThreshold - Progress;
/// <summary>Displayed cap for the rank bar (ribbons go in five at a time: 95/295/595/995).</summary>
public int RankMax => Value > 1000 ? 1000 : Value > 600 ? 995 : Value > 300 ? 595 : Value > 100 ? 295 : Value > 0 ? 95 : 0;
public bool HasReachedRank(string rank) => rank switch
{
"Initiate" => Value > 0,
"Adept" => Value > 100,
"Knight" => Value > 300,
"Lord" => Value > 600,
"Master" => Value > 1000,
_ => false,
};
/// <summary>
/// Ribbons turned in today. The counter only resets on the next turn-in, so once the 20-hour
/// timer is ready it's stale and today's count is 0.
/// </summary>
public int RibbonsToday(QuestFlagStore flags, DateTime utcNow)
{
if (FreshlyPromoted) return 0;
if (!flags.TryGet("societyribbonsperdaytimer", out QuestFlag timer) || timer.Ready(utcNow)) return 0;
return flags.TryGet("societyribbonsperdaycounter", out QuestFlag counter) ? counter.Solves : 0;
}
}
/// <summary>A row of society.csv: a quest, a "Rank: ..." heading, or "Blank" (a gap).</summary>
internal sealed class SocietyQuest
{
public string Name = "";
public string Flag = "";
public string Area = "";
public string Url = "";
public string Hint = "";
public bool IsBlank => Name == "Blank";
public bool IsHeading => Name.StartsWith("Rank:", StringComparison.Ordinal);
public bool IsRankTest => Name is "Adept Test" or "Knight Test" or "Lord Test" or "Master Test";
private string RankTestTarget => Name switch
{
"Adept Test" => "Adept",
"Knight Test" => "Knight",
"Lord Test" => "Lord",
"Master Test" => "Master",
_ => "",
};
private static bool IsMembershipFlag(string flag) =>
flag is "celestialhandmember" or "eldrytchwebmember" or "radiantbloodmember";
/// <summary>A rank test once the rank is reached; membership by the rank property; one-time by a solve; repeatables while on cooldown.</summary>
public bool IsComplete(SocietyStanding s, QuestFlagStore flags, DateTime utcNow)
{
if (IsRankTest) return s.HasReachedRank(RankTestTarget);
if (IsMembershipFlag(Flag))
return s.IsMember && Name.StartsWith(s.SocietyName, StringComparison.Ordinal);
if (!flags.TryGet(Flag, out QuestFlag q)) return false;
if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0;
return !q.Ready(utcNow);
}
public string Status(SocietyStanding s, QuestFlagStore flags, DateTime utcNow)
{
if (IsRankTest || IsMembershipFlag(Flag)) return IsComplete(s, flags, utcNow) ? "completed" : "";
if (!flags.TryGet(Flag, out QuestFlag q)) return "ready";
if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0 ? "completed" : "ready";
return q.NextAvailable(utcNow);
}
}
internal static class SocietyQuestList
{
public static List<SocietyQuest> All { get; } = Load();
/// <summary>In a society, the precursor and the other societies' initiations are hidden (upstream's rule).</summary>
public static IEnumerable<SocietyQuest> Visible(SocietyStanding s)
{
if (!s.IsMember) return All;
return All.Where(q => q.Name != "Investigating the Societies"
&& (!q.Name.EndsWith(" Initiation", StringComparison.Ordinal) || q.Name.StartsWith(s.SocietyName, StringComparison.Ordinal)));
}
private static List<SocietyQuest> Load()
{
var list = new List<SocietyQuest>();
using StreamReader r = Csv.OpenEmbedded("society.csv");
r.ReadLine(); // Name,QuestFlag,Area,Url,Hint
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
list.Add(new SocietyQuest
{
Name = Csv.Field(f, 0),
Flag = Csv.Field(f, 1).ToLowerInvariant(),
Area = Csv.Field(f, 2),
Url = Csv.Field(f, 3),
Hint = Csv.Field(f, 4),
});
}
return list;
}
}

View file

@ -0,0 +1,47 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>The spell groups the status summary and the Void tracker look for (upstream's lists).</summary>
internal static class SpellIds
{
/// <summary>Prodigal (3679-3744 and later) and Spectral rare buffs.</summary>
public static readonly HashSet<uint> Rare = new()
{
3679, 3680, 3681, 3682, 3683, 3684, 3685, 3686, 3687, 3688, 3689, 3690, 3691, 3692, 3693, 3694,
3695, 3696, 3697, 3698, 3699, 3700, 3701, 3702, 3703, 3704, 3705, 3706, 3707, 3708, 3709, 3710,
3711, 3712, 3713, 3714, 3715, 3716, 3717, 3718, 3719, 3720, 3721, 3722, 3723, 3724, 3725, 3726,
3727, 3728, 3729, 3730, 3731, 3732, 3733, 3734, 3735, 3736, 3737, 3738, 3739, 3740, 3741, 3742,
3743, 3744, 5025, 5026, 5436, 5903, 5905, 5907, 5909, 5911,
4131, 4132, 4133, 4134, 4135, 4136, 4137, 4138, 4139, 4140, 4141, 4142, 4208, 4221, 5023, 5435,
5904, 5906, 5908, 5910, 5912,
};
/// <summary>House, mansion and other long "place" buffs (Dark Equilibrium, Ride the Lightning, ...).</summary>
public static readonly HashSet<uint> House = new()
{
3896, 3894, 3897, 3895, 6146, 4099, 4025, 3323, 3324, 3325, 3237, 3831, 3830, 2995, 2993, 2997,
3829, 3977, 3978, 3979,
};
/// <summary>Long enchantments that aren't buffs you refresh (Blazing Heart, meads, rare armor damage, ...).</summary>
public static readonly HashSet<uint> NotBuff = new() { 3204, 5127, 5131, 5132, 5978, 5192, 6170, 5966, 5122 };
/// <summary>Beers (Bobo's Quickening and friends).</summary>
public static readonly HashSet<uint> Beer = new() { 3531, 3533, 3862, 3864, 3530, 3863 };
/// <summary>Pages of Salt and Ash (Incantation of the Black Book).</summary>
public static readonly HashSet<uint> Pages = new() { 3869 };
// Aetheria surges
public const uint SurgeOfDestruction = 5204;
public const uint SurgeOfProtection = 5206;
public const uint SurgeOfRegeneration = 5208;
public const uint CloakedInSkill = 5753;
// Void damage-over-time spells
public static readonly HashSet<uint> Corrosion = new() { 5387, 5388, 5389, 5390, 5391, 5392, 5393, 5394 };
public static readonly HashSet<uint> Corruption = new() { 5395, 5396, 5397, 5398, 5399, 5400, 5401, 5402 };
public static readonly HashSet<uint> Curse = new() { 5339, 5340, 5341, 5342, 5343, 5344, 5337, 5338 };
}

View file

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace RynthCore.Plugin.RynthOracle.Data;
internal readonly record struct SpellInfo(string Name, double Duration, bool IsDebuff);
/// <summary>
/// Spell names and base durations from RynthAi's embedded spell table (SpellData.txt, linked
/// into this plugin): tab separated, id, name, category, family, words, duration (s, -1 none),
/// difficulty, then three flags, the second of which marks a debuff. Loaded on first use.
/// </summary>
internal static class SpellTable
{
private static Dictionary<uint, SpellInfo>? _spells;
public static bool TryGet(uint id, out SpellInfo info)
{
EnsureLoaded();
return _spells!.TryGetValue(id, out info);
}
public static string Name(uint id) => TryGet(id, out SpellInfo s) ? s.Name : $"Spell {id}";
public static int Count
{
get { EnsureLoaded(); return _spells!.Count; }
}
private static void EnsureLoaded()
{
if (_spells != null) return;
var map = new Dictionary<uint, SpellInfo>();
try
{
using Stream? s = Assembly.GetExecutingAssembly().GetManifestResourceStream("RynthOracle.SpellData.txt");
if (s != null)
{
using var reader = new StreamReader(s, detectEncodingFromByteOrderMarks: true);
while (reader.ReadLine() is string line)
{
string[] c = line.Split('\t');
if (c.Length < 2 || !uint.TryParse(c[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out uint id)) continue;
double duration = c.Length > 5 && double.TryParse(c[5].Trim(), NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out double d) ? d : -1;
bool debuff = c.Length > 8 && c[8].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
map[id] = new SpellInfo(c[1].Trim(), duration, debuff);
}
}
}
catch
{
// A missing table only costs names ("Spell 1234").
}
_spells = map;
}
}

View file

@ -0,0 +1,36 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Globalization;
namespace RynthCore.Plugin.RynthOracle.Data;
internal static class TimeText
{
/// <summary>
/// "2d 5h 0m", "12m 4s". Seconds only inside the last hour; once a unit shows, every smaller
/// one follows even at zero, so a column doesn't change shape as it counts down (upstream's rule).
/// </summary>
public static string Friendly(TimeSpan d)
{
if (d < TimeSpan.Zero) d = TimeSpan.Zero;
bool showSeconds = d.TotalHours < 1;
string o = "";
if (d.Days > 0) o += d.Days + "d ";
if (o.Length > 0 || d.Hours > 0) o += d.Hours + "h ";
if (o.Length > 0 || d.Minutes > 0) o += d.Minutes + "m ";
if (showSeconds && (o.Length > 0 || d.Seconds > 0)) o += d.Seconds + "s ";
return o.Length == 0 ? "0s" : o.Trim();
}
/// <summary>"1:02:03" (hours unbounded), for buff timers.</summary>
public static string Clock(double seconds)
{
if (!double.IsFinite(seconds) || seconds < 0) seconds = 0;
var t = TimeSpan.FromSeconds(seconds);
return t.TotalHours >= 1
? $"{(int)t.TotalHours}:{t.Minutes:D2}:{t.Seconds:D2}"
: $"{t.Minutes}:{t.Seconds:D2}";
}
public static string Number(long n) => n.ToString("N0", CultureInfo.InvariantCulture);
}

View file

@ -0,0 +1,64 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>A row of titles.csv: a character title and how to earn it.</summary>
internal sealed class Title
{
public int Number;
public string Name = "";
public int TitleId;
public string Type = "";
public string Category = "";
public int Level;
public string Url = "";
public string Hint = "";
public bool Unavailable => Category == "Unavailable";
public string Group => Type.Length > 0 ? Type : Category;
}
/// <summary>
/// The title list. Which titles the character holds comes from the server's title events
/// (GameEvent 0x0029 at login, 0x002B for each new title), which upstream reads with Decal's
/// network filter and RynthCore's engine serves through API v75 GetCharacterTitles
/// (OracleContext.EarnedTitles).
/// </summary>
internal static class TitleList
{
public static List<Title> All { get; } = Load();
private static List<Title> Load()
{
var list = new List<Title>();
using StreamReader r = Csv.OpenEmbedded("titles.csv");
r.ReadLine(); // Number,Name,Id,Type,Category,Level,Url,Hint
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
list.Add(new Title
{
Number = int.TryParse(Csv.Field(f, 0), out int n) ? n : 0,
Name = Csv.Field(f, 1),
TitleId = int.TryParse(Csv.Field(f, 2), out int id) ? id : 0,
Type = Csv.Field(f, 3),
Category = Csv.Field(f, 4),
Level = int.TryParse(Csv.Field(f, 5), out int lv) ? lv : 0,
Url = Csv.Field(f, 6),
Hint = Csv.Field(f, 7),
});
}
list.Sort((a, b) =>
{
int c = string.Compare(a.Group, b.Group, StringComparison.OrdinalIgnoreCase);
if (c != 0) return c;
c = a.Level.CompareTo(b.Level);
return c != 0 ? c : a.Number.CompareTo(b.Number);
});
return list;
}
}

View file

@ -0,0 +1,156 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
internal enum VoidFamily { Corrosion, Corruption, Curse }
/// <summary>One of your Void damage-over-time spells on a target.</summary>
internal sealed class VoidDot
{
public uint TargetId;
public string TargetName = "";
public uint SpellId;
public string SpellName = "";
public VoidFamily Family;
public long StartedMs;
public long TickedMs; // 0 until the first "periodic nether damage" line
/// <summary>Cast while Surge of Destruction was up (shown highlighted).</summary>
public bool Destruction;
/// <summary>ConquestAC scales void DoT duration by the caster's augs (1.0 elsewhere).</summary>
public double DurationScale = 1.0;
/// <summary>Corrosion 15 s, Corruption and Destructive Curse 30 s (upstream's retail values), times the server's scale.</summary>
public int Duration => (int)((Family == VoidFamily.Corrosion ? 15 : 30) * DurationScale);
/// <summary>
/// Seconds left. Before the first tick: from the cast, plus 2 s for the first tick's delay;
/// after it: from the first tick (upstream's timing).
/// </summary>
public int SecondsRemaining(long nowMs) => TickedMs == 0
? Duration - (int)((nowMs - StartedMs) / 1000) + 2
: Duration - (int)((nowMs - TickedMs) / 1000);
}
/// <summary>
/// Tracks your own Corrosion, Corruption and Destructive Curse on each target from the chat
/// lines the server sends you ("You cast X on Y", "You scar Y for N points of periodic nether
/// damage"). Upstream also uses Decal's SpellCast event for the target's id; RynthCore has no
/// spell-cast event for plugins, so the id is the selected target when its name matches, else
/// unknown (the spell then matches targets by name). Only your own spells; Corruption's splash
/// isn't tracked.
/// </summary>
internal sealed class VoidTracker
{
private static readonly Regex YouCast = new(@"^You cast (.+?) on (.+?)(?:,.*)?$", RegexOptions.CultureInvariant);
private static readonly Regex PeriodicNether = new(@"^You scar (.+?) for (\d+) points of periodic nether damage", RegexOptions.CultureInvariant);
private readonly List<VoidDot> _dots = new();
private Dictionary<string, (uint Id, VoidFamily Family)>? _byName;
public IReadOnlyList<VoidDot> Dots => _dots;
public int Revision { get; private set; }
/// <summary>
/// A chat line. <paramref name="resolveTarget"/> finds a target's id by name;
/// <paramref name="destructionUp"/> says whether Surge of Destruction is on you now.
/// </summary>
public bool OnChatLine(string text, long nowMs, Func<string, uint> resolveTarget, Func<bool> destructionUp, double durationScale = 1.0)
{
if (text.StartsWith("You cast ", StringComparison.Ordinal))
{
Match m = YouCast.Match(text);
if (!m.Success) return false;
if (!SpellsByName().TryGetValue(m.Groups[1].Value.Trim(), out var spell)) return false;
string target = m.Groups[2].Value.Trim();
uint targetId = resolveTarget(target);
VoidDot? existing = Find(targetId, target, spell.Family, nowMs);
bool destruction = destructionUp();
bool keepDestruction = existing != null && existing.Destruction;
if (existing != null) _dots.Remove(existing);
_dots.Insert(0, new VoidDot
{
TargetId = targetId,
TargetName = target,
SpellId = spell.Id,
SpellName = m.Groups[1].Value.Trim(),
Family = spell.Family,
StartedMs = nowMs,
DurationScale = durationScale > 0 ? durationScale : 1.0,
Destruction = keepDestruction || (destruction && existing == null),
});
Revision++;
return true;
}
if (text.StartsWith("You scar ", StringComparison.Ordinal))
{
Match m = PeriodicNether.Match(text);
if (!m.Success) return false;
string target = m.Groups[1].Value.Trim();
foreach (VoidDot d in _dots)
if (d.TickedMs == 0 && d.TargetName == target) d.TickedMs = nowMs;
Revision++;
return true;
}
return false;
}
private VoidDot? Find(uint targetId, string targetName, VoidFamily family, long nowMs)
{
foreach (VoidDot d in _dots)
if (d.Family == family && d.SecondsRemaining(nowMs) > 0
&& (targetId != 0 ? d.TargetId == targetId : d.TargetName == targetName))
return d;
return null;
}
/// <summary>
/// Seconds left on a family's spell on a target, or -1; destruction = cast with the surge up.
/// A spell whose target id wasn't known at the cast matches by name.
/// </summary>
public int Remaining(uint targetId, string targetName, VoidFamily family, long nowMs, out bool destruction)
{
destruction = false;
foreach (VoidDot d in _dots)
{
if (d.Family != family) continue;
if (d.TargetId != 0 ? d.TargetId != targetId : d.TargetName != targetName) continue;
int s = d.SecondsRemaining(nowMs);
if (s <= 0) continue;
destruction = d.Destruction;
return s;
}
return -1;
}
public void RemoveExpired(long nowMs)
{
if (_dots.RemoveAll(d => d.SecondsRemaining(nowMs) <= 0) > 0) Revision++;
}
public void Clear()
{
_dots.Clear();
Revision++;
}
private Dictionary<string, (uint Id, VoidFamily Family)> SpellsByName()
{
if (_byName != null) return _byName;
var map = new Dictionary<string, (uint, VoidFamily)>(StringComparer.OrdinalIgnoreCase);
void Add(HashSet<uint> ids, VoidFamily f)
{
foreach (uint id in ids)
if (SpellTable.TryGet(id, out SpellInfo s) && !string.IsNullOrEmpty(s.Name)) map[s.Name] = (id, f);
}
Add(SpellIds.Corrosion, VoidFamily.Corrosion);
Add(SpellIds.Corruption, VoidFamily.Corruption);
Add(SpellIds.Curse, VoidFamily.Curse);
return _byName = map;
}
}