Snapshot for release 2026.10.15.2 (internal 2d4b0af)

This commit is contained in:
Tom Bohar 2026-10-15 20:32:35 -04:00
commit d5e0b50de7
224 changed files with 17914 additions and 1182 deletions

View file

@ -0,0 +1,143 @@
// DataInterface.cs - RynthILT's side of the "RynthILT.Data" interface (Plugins/Shared/RynthIltDataApi.cs):
// the charms list and the bank balances (every character RynthILT has seen on this server) the
// Mini Remote's Charms and Banking tabs show, for other plugins to draw, with the charm Toggle and
// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs.
//
// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never
// unloaded); after Release() it reports Version 0 and every function answers 0. Before login there
// is no controller: the JSON getters answer 0 (nothing to report) and the actions are refused.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT;
internal static unsafe class DataInterface
{
/// <summary>Longest bank / breeding verb line taken (a transfer with a long character name fits easily).</summary>
private const int MaxVerbBytes = 256;
private static RynthIltDataApiV1* _table;
private static volatile bool _released;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthIltDataApiV1.InterfaceName || version < 1 || version > RynthIltDataApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthIltDataApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltDataApiV1));
t->StructSize = (uint)sizeof(RynthIltDataApiV1);
t->GetCharmsJson = &GetCharmsJson;
t->GetBankJson = &GetBankJson;
t->ToggleCharm = &ToggleCharm;
t->BankCommand = &BankCommand;
t->GetPetBreedingJson = &GetPetBreedingJson;
t->PetBreedingCommand = &PetBreedingCommand;
t->Version = RynthIltDataApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Plugin shutdown: readers see Version 0 and re-query; every function answers 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
}
private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCharmsJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.CharmsJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBankJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.BankJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ToggleCharm(uint objectId)
{
try
{
IltHubController? hub = Hub;
if (hub == null || objectId == 0) return 0;
hub.RequestCharmToggle(objectId);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int BankCommand(byte* utf8)
{
try
{
IltHubController? hub = Hub;
if (hub == null) return 0;
string? line = ReadVerb(utf8);
if (line == null) return 0;
hub.RequestBankVerb(line);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPetBreedingJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.PetBreedingJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int PetBreedingCommand(byte* utf8)
{
try
{
IltHubController? hub = Hub;
if (hub == null) return 0;
string? line = ReadVerb(utf8);
if (line == null) return 0;
hub.RequestBreedingVerb(line);
return 1;
}
catch { return 0; }
}
/// <summary>A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command).</summary>
private static string? ReadVerb(byte* utf8)
{
if (utf8 == null) return null;
int len = 0;
while (len < MaxVerbBytes && utf8[len] != 0) len++;
if (len == 0 || len >= MaxVerbBytes) return null;
string line = System.Text.Encoding.UTF8.GetString(utf8, len);
foreach (char c in line)
if (c < 0x20 || c > 0x7E) return null;
return line;
}
}

View file

@ -1,50 +1,69 @@
// IltBankCommands.cs — The /bank commands the Banking tab sends, and the reply lines it collects.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 2026-10-11):
// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 976606695):
// /b d [code] deposit everything (no code) or one kind; "Deposited N <kind>",
// "No <kind> found to deposit", "Deposited all <kind>!".
// /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x <token>"
// a kind, "Ending Banked Lum"; "No luminance tokens found to deposit".
// /b w <code> <amount> withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...".
// /b w n <denom> [n] trade notes by denomination (i v x l c d m md mm mmd).
// /b t <code> <n> <who> transfer (IltBanking); Prestige Coins can't be transferred.
// Deposit, withdraw and transfer share one server throttle (bank_command_limit); a plain
// /bank balance doesn't touch it. Pure: no host calls, so the host tests cover it.
// /b t <code> <n> <who> transfer; "Transferred {N0} {Currency} to {Name}[ (offline)]".
// /b t n <denom> <n> <who> trade notes' pyreal value, then "(Equivalent to Nx DENOM notes)".
// The recipient is one argument: a name with a space has to be in "quotes".
// Prestige Coins are bound to the character: "[BANK] Prestige Coins are bound to you and
// cannot be transferred." Pyreal peas and luminance tokens are deposit only.
// Items is the one table of what the server allows; the deposit, withdraw and transfer lists
// are built from it. Deposit, withdraw and transfer share one server throttle
// (bank_command_limit); a plain /bank balance doesn't touch it. Pure: no host calls, so the
// host tests cover it.
using System;
using System.Linq;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltBankCommands
{
/// <summary>
/// One bank item: label, server code, and what the server allows for it. For trade notes
/// ("n") a withdrawal or transfer is by denomination and note count.
/// </summary>
internal sealed record BankItem(string Label, string Code, bool Deposit, bool Withdraw, bool Transfer);
/// <summary>The trade-notes code: withdrawn and transferred by denomination.</summary>
public const string NotesCode = "n";
/// <summary>The luminance-tokens deposit: its own command, "/b lum".</summary>
public const string LuminanceTokensCode = "lum";
/// <summary>Everything the bank holds, in the server's order, with what it allows.</summary>
public static readonly BankItem[] Items =
{
new("Pyreals", "p", Deposit: true, Withdraw: true, Transfer: true),
new("Pyreal peas", "ps", Deposit: true, Withdraw: false, Transfer: false),
new("Luminance", "l", Deposit: true, Withdraw: true, Transfer: true),
new("Luminance tokens", LuminanceTokensCode, Deposit: true, Withdraw: false, Transfer: false),
new("Legendary keys", "k", Deposit: true, Withdraw: true, Transfer: true),
new("Mythical keys", "mk", Deposit: true, Withdraw: true, Transfer: true),
new("Enlightened coins", "e", Deposit: true, Withdraw: true, Transfer: true),
new("Weakly enlightened coins", "we", Deposit: true, Withdraw: true, Transfer: true),
new("Prestige coins", "pc", Deposit: true, Withdraw: true, Transfer: false),
new("Trade notes", NotesCode, Deposit: true, Withdraw: true, Transfer: true),
};
/// <summary>A deposit choice: label, and the command's argument after "/b d" ("" = all).</summary>
public static readonly (string Label, string Args)[] Deposits =
{
("Everything", ""),
("Pyreals", "p"),
("Pyreal peas", "ps"),
("Luminance", "l"),
("Luminance tokens", "lum"),
("Legendary keys", "k"),
("Mythical keys", "mk"),
("Enlightened coins", "e"),
("Weakly enlightened coins", "we"),
("Prestige coins", "pc"),
("Trade notes", "n"),
};
new[] { ("Everything", string.Empty) }
.Concat(Items.Where(i => i.Deposit).Select(i => (i.Label, i.Code)))
.ToArray();
/// <summary>A withdraw choice: label and the server code; "n" is trade notes (by denomination).</summary>
public static readonly (string Label, string Code)[] Withdrawals =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary keys", "k"),
("Mythical keys", "mk"),
("Enlightened coins", "e"),
("Weakly enlightened coins", "we"),
("Prestige coins", "pc"),
("Trade notes", "n"),
};
Items.Where(i => i.Withdraw).Select(i => (i.Label, i.Code)).ToArray();
/// <summary>A transfer choice: label and the server code; "n" moves trade notes' pyreal value.</summary>
public static readonly (string Label, string Code)[] Transfers =
Items.Where(i => i.Transfer).Select(i => (i.Label, i.Code)).ToArray();
/// <summary>Trade note denominations: label and code, in the server's order.</summary>
public static readonly (string Label, string Code, long Value)[] NoteDenominations =
@ -54,7 +73,7 @@ internal static class IltBankCommands
("MD (150K)", "md", 150_000), ("MM (200K)", "mm", 200_000), ("MMD (250K)", "mmd", 250_000),
};
/// <summary>The server refuses a trade-note withdrawal of more than this many notes.</summary>
/// <summary>The server refuses a trade-note withdrawal of more than this many notes; transfers use the same cap.</summary>
public const int MaxNoteCount = 50_000;
/// <summary>"/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index.</summary>
@ -63,7 +82,7 @@ internal static class IltBankCommands
if (index < 0 || index >= Deposits.Length) return string.Empty;
string args = Deposits[index].Args;
if (args.Length == 0) return "/b d";
return args == "lum" ? "/b lum" : "/b d " + args;
return args == LuminanceTokensCode ? "/b lum" : "/b d " + args;
}
/// <summary>
@ -76,10 +95,47 @@ internal static class IltBankCommands
if (index < 0 || index >= Withdrawals.Length) { error = "Pick what to withdraw."; return string.Empty; }
if (amount <= 0) { error = "Amount must be positive."; return string.Empty; }
string code = Withdrawals[index].Code;
if (code != "n") return $"/b w {code} {amount}";
if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return string.Empty; }
if (amount > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return string.Empty; }
return $"/b w n {NoteDenominations[denomination].Code} {amount}";
if (code != NotesCode) return $"/b w {code} {amount}";
if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty;
return $"/b w n {denom} {amount}";
}
/// <summary>
/// "/bank t p 250000 Bob", "/bank t n mmd 4 \"Some Name\"" for trade notes (<paramref name="amount"/>
/// is then the note count). <paramref name="target"/> must already be a checked character name
/// (IltParse.CharacterName); a name with a space is quoted, as the server reads one argument.
/// Empty (with <paramref name="error"/>) when the input can't be sent.
/// </summary>
public static string Transfer(int index, long amount, int denomination, string target, out string error)
{
error = string.Empty;
if (index < 0 || index >= Transfers.Length) { error = "Pick a currency."; return string.Empty; }
if (amount <= 0) { error = "Amount must be positive."; return string.Empty; }
target = (target ?? string.Empty).Trim();
if (target.Length == 0) { error = "Enter a recipient."; return string.Empty; }
if (target.IndexOf('"') >= 0) { error = "Recipient must be a character name."; return string.Empty; }
string who = target.IndexOf(' ') >= 0 ? "\"" + target + "\"" : target;
string code = Transfers[index].Code;
if (code != NotesCode) return $"/bank t {code} {amount} {who}";
if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty;
return $"/bank t n {denom} {amount} {who}";
}
/// <summary>True when <paramref name="index"/> is the trade-notes transfer (denomination and count).</summary>
public static bool IsNoteTransfer(int index) => index >= 0 && index < Transfers.Length && Transfers[index].Code == NotesCode;
/// <summary>The pyreal value of <paramref name="count"/> notes of <paramref name="denomination"/> (0 if unknown).</summary>
public static long NoteValue(int denomination, long count) =>
denomination >= 0 && denomination < NoteDenominations.Length && count > 0 ? NoteDenominations[denomination].Value * count : 0;
private static bool TryNote(int denomination, long count, out string code, out string error)
{
code = string.Empty;
error = string.Empty;
if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return false; }
if (count > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return false; }
code = NoteDenominations[denomination].Code;
return true;
}
/// <summary>
@ -110,4 +166,23 @@ internal static class IltBankCommands
|| line.StartsWith("Count cannot exceed", StringComparison.Ordinal)
|| line.StartsWith("You are not permitted to use bank commands", StringComparison.Ordinal);
}
/// <summary>
/// True for a line the server sends in reply to a transfer: the result, the trade-note
/// equivalent, the throttle, or a refusal (unknown player, bound prestige coins, bad input).
/// </summary>
public static bool IsTransferReply(string line)
{
if (string.IsNullOrEmpty(line)) return false;
return line.StartsWith("Transferred ", StringComparison.Ordinal)
|| line.StartsWith("(Equivalent to ", StringComparison.Ordinal)
|| line.StartsWith("Character '", StringComparison.Ordinal)
|| line.StartsWith("You cannot transfer", StringComparison.Ordinal)
|| line.StartsWith("You don't have enough", StringComparison.Ordinal)
|| line.StartsWith("[Transfer]", StringComparison.Ordinal)
|| line.StartsWith("[BANK] Too many parameters", StringComparison.Ordinal)
|| line.StartsWith("[BANK] Prestige Coins are bound", StringComparison.Ordinal)
|| line.StartsWith("Invalid count", StringComparison.Ordinal)
|| line.StartsWith("Invalid denomination", StringComparison.Ordinal);
}
}

View file

@ -0,0 +1,151 @@
// IltBankExport.cs - The bank JSON of "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the
// Banking tab's balances, form choices and log for another plugin's view (every character here).
//
// Every character RynthILT has run on this server keeps its balances in its own hub.json
// (<RynthILT folder>\<world>\<character>\hub.json, IltHubStore); the export lists them all, the
// logged-in character from its live state and the rest from their saved files (read on the pump
// at most every SiblingReadMs, so a reader polling every couple of seconds costs one directory
// listing now and then). Plus the form choices (IltBankCommands), the last action's reply and
// the recent transfers. Build is pure: the tests feed it rows.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltBankExport
{
/// <summary>How many recent transfers the JSON carries (newest first).</summary>
public const int MaxTransactions = 50;
/// <summary>One character's balances as exported.</summary>
internal sealed record Row(string Name, bool Current, IltBankState Bank);
/// <summary>
/// The bank JSON. <paramref name="enabled"/>: 1 the server has /bank, 0 not, -1 not known yet.
/// Rows are listed current character first, then by name. Plain ASCII.
/// </summary>
public static string Build(bool available, int enabled, string world, string character, IReadOnlyList<Row> rows,
string result, IReadOnlyList<IltBankTransaction> transactions)
{
var sb = new StringBuilder(4096);
sb.Append("{\"available\":").Append(available ? "true" : "false");
sb.Append(",\"enabled\":").Append(Math.Clamp(enabled, -1, 1).ToString(CultureInfo.InvariantCulture));
sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(world ?? string.Empty)).Append('"');
sb.Append(",\"character\":\"").Append(IltStyle.JsonEscape(character ?? string.Empty)).Append('"');
var ordered = new List<Row>(rows);
ordered.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
sb.Append(",\"characters\":[");
for (int i = 0; i < ordered.Count; i++)
{
Row r = ordered[i];
IltBankState b = r.Bank;
if (i > 0) sb.Append(',');
sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Name)).Append('"');
sb.Append(",\"current\":").Append(r.Current ? "true" : "false");
Num(sb, "pyreals", b.Pyreals);
Num(sb, "luminance", b.Luminance);
Num(sb, "legendaryKeys", b.LegendaryKeys);
Num(sb, "mythicalKeys", b.MythicalKeys);
Num(sb, "enlightenedCoins", b.EnlightenedCoins);
Num(sb, "weaklyEnlightenedCoins", b.WeaklyEnlightenedCoins);
Num(sb, "prestigeCoins", b.PrestigeCoins);
sb.Append(",\"updated\":\"").Append(Utc(b.LastUpdated)).Append("\"}");
}
sb.Append(']');
sb.Append(",\"deposits\":[");
for (int i = 0; i < IltBankCommands.Deposits.Length; i++)
{
if (i > 0) sb.Append(',');
sb.Append('"').Append(IltStyle.JsonEscape(IltBankCommands.Deposits[i].Label)).Append('"');
}
sb.Append(']');
Choices(sb, "withdrawals", IltBankCommands.Withdrawals, w => w.Code == IltBankCommands.NotesCode);
Choices(sb, "transfers", IltBankCommands.Transfers, t => t.Code == IltBankCommands.NotesCode);
sb.Append(",\"notes\":[");
for (int i = 0; i < IltBankCommands.NoteDenominations.Length; i++)
{
var n = IltBankCommands.NoteDenominations[i];
if (i > 0) sb.Append(',');
sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(n.Label)).Append('"');
Num(sb, "value", n.Value);
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"result\":\"").Append(IltStyle.JsonEscape(result ?? string.Empty)).Append('"');
sb.Append(",\"transactions\":[");
int written = 0;
for (int i = transactions.Count - 1; i >= 0 && written < MaxTransactions; i--, written++)
{
IltBankTransaction t = transactions[i];
if (written > 0) sb.Append(',');
sb.Append("{\"when\":\"").Append(t.Timestamp == default ? "" : t.Timestamp.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append('"');
sb.Append(",\"type\":\"").Append(IltStyle.JsonEscape(t.Type)).Append('"');
Num(sb, "amount", t.Amount);
sb.Append(",\"currency\":\"").Append(IltStyle.JsonEscape(t.Currency)).Append('"');
sb.Append(",\"player\":\"").Append(IltStyle.JsonEscape(t.OtherPlayer)).Append("\"}");
}
sb.Append("]}");
return sb.ToString();
}
private static void Num(StringBuilder sb, string name, long value)
=> sb.Append(",\"").Append(name).Append("\":").Append(value.ToString(CultureInfo.InvariantCulture));
private static void Choices(StringBuilder sb, string name, (string Label, string Code)[] items, Func<(string Label, string Code), bool> notes)
{
sb.Append(",\"").Append(name).Append("\":[");
for (int i = 0; i < items.Length; i++)
{
if (i > 0) sb.Append(',');
sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(items[i].Label)).Append("\",\"notes\":")
.Append(notes(items[i]) ? "true" : "false").Append('}');
}
sb.Append(']');
}
/// <summary>A local DateTime as ISO UTC ("" = never).</summary>
private static string Utc(DateTime local) => local == DateTime.MinValue || local == default
? ""
: local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
/// <summary>
/// The other characters' saved balances: every <c>&lt;world folder&gt;\*\hub.json</c> except
/// <paramref name="currentFolder"/>. A file that can't be read is skipped (its character just
/// isn't listed). Characters never banked (no LastUpdated) are left out.
/// </summary>
public static List<Row> ReadSiblings(string currentFolder)
{
var rows = new List<Row>();
if (string.IsNullOrEmpty(currentFolder)) return rows;
string? worldDir = Path.GetDirectoryName(currentFolder.TrimEnd('\\', '/'));
if (string.IsNullOrEmpty(worldDir) || !Directory.Exists(worldDir)) return rows;
string self = Path.GetFullPath(currentFolder).TrimEnd('\\', '/');
foreach (string dir in Directory.EnumerateDirectories(worldDir))
{
if (string.Equals(Path.GetFullPath(dir).TrimEnd('\\', '/'), self, StringComparison.OrdinalIgnoreCase)) continue;
string file = Path.Combine(dir, IltHubStore.StateFile);
if (!File.Exists(file)) continue;
try
{
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
var state = JsonSerializer.Deserialize(fs, IltHubJsonContext.Default.IltHubState);
IltBankState? bank = state?.Bank;
if (bank == null || bank.LastUpdated == DateTime.MinValue) continue;
rows.Add(new Row(Path.GetFileName(dir), false, bank));
}
catch (Exception ex)
{
RynthLog.Trace(LogCat.IltBanking, $"bank export: skipped {file} ({ex.Message})");
}
}
return rows;
}
}

View file

@ -1,6 +1,7 @@
// IltBanking.cs — ILT Hub "Banking" tab: /bank balances, deposits, withdrawals, confirmed
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// transfers, transaction log.
// IltBanking.cs — ILT banking: /bank balances, deposits, withdrawals, confirmed transfers,
// transaction log. Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// Render is the Mini Remote's "Banking" tab. The balances and log are also exported to other
// plugins through "RynthILT.Data" (IltBankExport; their verbs come back through RunVerb).
//
// Server contract (ACECustom PlayerCommands bank handler, upstream 2026-10-11):
// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:",
@ -9,8 +10,9 @@
// /b d, /b lum, /b w → deposits and withdrawals (IltBankCommands has the commands and replies).
// /bank t <c> <n> <who> → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error;
// the recipient sees "Received {N0} {currency} from {Name}".
// Codes: p pyreals, l luminance, k legendary keys, mk mythical keys, e enl coins, we weak coins.
// Prestige Coins (pc) are bound: deposit and withdraw only.
// /bank t n <d> <n> <who> → trade notes' pyreal value, then "(Equivalent to ...)".
// What each item allows is IltBankCommands.Items (the server's table): Prestige Coins (pc)
// are bound (deposit and withdraw only); pyreal peas and luminance tokens deposit only.
// Deposit, withdraw and transfer share the server's bank_command_limit throttle; a balance
// refresh doesn't, so it has its own (client-side) spacing.
// Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN
@ -20,21 +22,14 @@ using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltBanking : IIltFeature
{
/// <summary>Transfer currency table: display name, /bank t code.</summary>
public static readonly (string Name, string Code)[] Currencies =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary Keys", "k"),
("Mythical Keys", "mk"),
("Enlightened Coins", "e"),
("Weakly Enlightened Coins", "we"),
};
/// <summary>Transfer currencies: display name, /bank t code (IltBankCommands.Transfers).</summary>
public static readonly (string Name, string Code)[] Currencies = IltBankCommands.Transfers;
private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray();
private static readonly string[] DepositNames = IltBankCommands.Deposits.Select(d => d.Label).ToArray();
private static readonly string[] WithdrawNames = IltBankCommands.Withdrawals.Select(w => w.Label).ToArray();
@ -69,6 +64,23 @@ internal sealed class IltBanking : IIltFeature
private string _txFilter = string.Empty;
private string _lastResult = string.Empty;
private volatile string _actionResult = string.Empty;
/// <summary>The newest action reply or error (deposit, withdrawal or transfer), for the bank export.</summary>
private volatile string _latestResult = string.Empty;
/// <summary>
/// Another plugin is showing the balances (a "RynthILT.Data" reader):
/// the periodic quiet refresh runs as it does while the Mini Remote is open. Pump thread.
/// </summary>
public bool ReaderWatching;
/// <summary>The newest action reply or error (any thread).</summary>
public string LatestResult => _latestResult;
/// <summary>The transaction log as last published (any thread; oldest first).</summary>
public IReadOnlyList<IltBankTransaction> Transactions => _txSnapshot;
/// <summary>The bank state (pump thread).</summary>
public IltBankState State => Bank;
/// <summary>Raised (pump thread) after a balance line updates the state; Character rates use the deltas.</summary>
public event Action<string, long, long>? BalanceChanged;
@ -128,40 +140,36 @@ internal sealed class IltBanking : IIltFeature
}
/// <summary>
/// Validates and (after the UI confirm) sends a transfer. Pump thread.
/// Validates and (after the UI confirm) sends a transfer. For trade notes
/// <paramref name="amount"/> is the note count of <paramref name="denomination"/>. Pump thread.
/// Returns an error message, or empty when the command was queued.
/// </summary>
public string SendTransfer(int currencyIndex, long amount, string target)
public string SendTransfer(int currencyIndex, long amount, string target, int denomination = -1)
{
RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, target='{target}')");
RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, denom={denomination}, target='{target}')");
if (!Enabled) return "Bank is not available on this server.";
if (currencyIndex < 0 || currencyIndex >= Currencies.Length) return "Pick a currency.";
if (amount <= 0) return "Amount must be positive.";
target = (target ?? string.Empty).Trim();
if (target.Length == 0) return "Enter a recipient.";
// The recipient is spliced into a chat command, so only character-name characters are
// allowed: no '/', control characters or line breaks that could start a second command.
if (!IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only).";
// allowed: no '/', quotes, control characters or line breaks that could start a second command.
if (target.Length > 0 && !IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only).";
if (target.Equals(_ctx.CharName, StringComparison.OrdinalIgnoreCase)) return "You cannot transfer to yourself.";
string cmd = IltBankCommands.Transfer(currencyIndex, amount, denomination, target, out string error);
if (cmd.Length == 0) return error;
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
string cmd = $"/bank t {Currencies[currencyIndex].Code} {amount} {target}";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = t => t.StartsWith("Transferred ", StringComparison.Ordinal)
|| t.StartsWith("Character '", StringComparison.Ordinal)
|| t.StartsWith("You cannot transfer", StringComparison.Ordinal)
|| t.StartsWith("You don't have enough", StringComparison.Ordinal)
|| t.StartsWith("[Transfer]", StringComparison.Ordinal),
IsResponseLine = IltBankCommands.IsTransferReply,
IdleEndMs = 500,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty);
_latestResult = _lastResult;
// Balances changed: read them again shortly.
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
@ -212,19 +220,51 @@ internal sealed class IltBanking : IIltFeature
{
_actionResult = r.Lines.Count > 0 ? string.Join("\n", r.Lines.TakeLast(6))
: r.TimedOut ? "No reply from the server." : string.Empty;
_latestResult = _actionResult;
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
});
return string.Empty;
}
/// <summary>
/// A bank verb line from "RynthILT.Data" BankCommand (Plugins/Shared/RynthIltDataApi.cs):
/// "refresh", "deposit i", "withdraw i amount note", "transfer i amount note name". The reader
/// has already confirmed a transfer with the player. Pump thread. Returns an error, or empty
/// when it was queued; either way the outcome shows in <see cref="LatestResult"/>.
/// </summary>
public string RunVerb(string line)
{
string[] p = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
string err;
if (p.Length == 0) err = "Empty bank command.";
else if (p[0] == "refresh" && p.Length == 1) { RequestRefresh(quiet: true); return string.Empty; }
else if (p[0] == "deposit" && p.Length == 2 && int.TryParse(p[1], out int d)) err = SendDeposit(d);
else if (p[0] == "withdraw" && p.Length == 4 && int.TryParse(p[1], out int w) && long.TryParse(p[2], out long wa)
&& int.TryParse(p[3], out int wn))
err = SendWithdraw(w, wa, wn);
else if (p[0] == "transfer" && p.Length >= 5 && int.TryParse(p[1], out int c) && long.TryParse(p[2], out long ta)
&& int.TryParse(p[3], out int tn))
{
// The name may hold spaces; SendTransfer checks it is a character name.
string who = string.Join(' ', p, 4, p.Length - 4);
err = SendTransfer(c, ta, who, IltBankCommands.IsNoteTransfer(c) ? tn : -1);
if (err.Length == 0) _latestResult = "Transfer sent...";
}
else err = "Unknown bank command.";
if (err.Length > 0) _latestResult = err;
RynthLog.Trace(LogCat.IltBanking, $"reader verb '{line}' -> {(err.Length > 0 ? err : "queued")}");
return err;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// Periodic quiet refresh only while the Hub is open and the server has /bank.
// Periodic quiet refresh only while the balances are on screen (the Hub, or a reader's
// Banking tab) and the server has /bank.
int every = Bank.AutoRefreshSeconds;
if (Enabled && _ctx.WindowOpen && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L
if (Enabled && (_ctx.WindowOpen || ReaderWatching) && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L
&& nowMs - _lastBalanceAt >= BalanceSpacingMs)
{
_lastAutoRefreshAt = nowMs;
@ -369,7 +409,7 @@ internal sealed class IltBanking : IIltFeature
{
if (!Enabled)
{
ImGui.TextColored(IltStyle.ColTextMute,
SafeImGui.TextColored(IltStyle.ColTextMute,
_ctx.Options.IsOff(IltFeature.Bank) ? "The server reports /bank is not available." : "Waiting for the server options check...");
return;
}
@ -381,7 +421,7 @@ internal sealed class IltBanking : IIltFeature
ImGui.SameLine();
if (ImGui.SmallButton("Copy##bank")) ImGui.SetClipboardText(BuildCopyLine());
ImGui.SameLine();
ImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g"));
SafeImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g"));
if (ImGui.BeginTable("##iltbal", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV))
{
@ -432,7 +472,7 @@ internal sealed class IltBanking : IIltFeature
_ctx.Post(() => { string err = SendDeposit(index); if (err.Length > 0) _actionResult = err; });
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens."
SafeImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens."
+ "\nThe server refuses while you are busy or moving.");
ImGui.TextColored(IltStyle.ColTeal, "Withdraw");
@ -463,12 +503,12 @@ internal sealed class IltBanking : IIltFeature
{
ImGui.SameLine();
if (!ok) ImGui.TextColored(IltStyle.ColHp, "invalid amount");
else if (notes) ImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals");
else ImGui.TextDisabled("= " + IltParse.N0(amount));
else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals");
else SafeImGui.TextDisabled("= " + IltParse.N0(amount));
}
string result = _actionResult;
if (result.Length > 0) ImGui.TextWrapped(result);
if (result.Length > 0) SafeImGui.TextWrapped(result);
}
private void RenderTransferForm()
@ -478,9 +518,18 @@ internal sealed class IltBanking : IIltFeature
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Currency##xfer", ref idx, CurrencyNames, CurrencyNames.Length))
Bank.TransferCurrencyIndex = idx;
bool notes = IltBankCommands.IsNoteTransfer(idx);
int denom = Math.Clamp(Bank.TransferNoteIndex, 0, NoteNames.Length - 1);
if (notes)
{
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Denomination##xfer", ref denom, NoteNames, NoteNames.Length)) Bank.TransferNoteIndex = denom;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("The server moves the notes' pyreal value from your bank (/b t n <denomination> <count> <name>).");
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("Amount##xfer", "e.g. 250000, 1.5m, 2b", ref _amountText, 32u);
ImGui.InputTextWithHint("Amount##xfer", notes ? "how many notes" : "e.g. 250000, 1.5m, 2b", ref _amountText, 32u);
string target = Bank.TransferTarget;
ImGui.SetNextItemWidth(200);
if (ImGui.InputTextWithHint("Recipient##xfer", "character name", ref target, 64u))
@ -490,33 +539,37 @@ internal sealed class IltBanking : IIltFeature
if (_amountText.Length > 0)
{
ImGui.SameLine();
if (amountOk) ImGui.TextDisabled("= " + IltParse.N0(amount));
else ImGui.TextColored(IltStyle.ColHp, "invalid amount");
if (!amountOk) ImGui.TextColored(IltStyle.ColHp, "invalid amount");
else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(IltBankCommands.NoteValue(denom, amount)) + " pyreals");
else SafeImGui.TextDisabled("= " + IltParse.N0(amount));
}
ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget));
if (ImGui.Button("Send transfer..."))
{
int cur = idx;
int cur = idx, note = notes ? denom : -1;
long amt = amount;
string who = Bank.TransferTarget.Trim();
string what = notes
? $"{IltParse.N0(amt)} {IltBankCommands.NoteDenominations[denom].Label} trade notes ({IltParse.N0(IltBankCommands.NoteValue(denom, amt))} pyreals)"
: $"{IltParse.N0(amt)} {Currencies[cur].Name}";
_ctx.Confirm("Confirm bank transfer",
$"Send {IltParse.N0(amt)} {Currencies[cur].Name} to {who}?\n\nThis cannot be undone.",
$"Send {what} to {who}?\n\nThis cannot be undone.",
() =>
{
string err = SendTransfer(cur, amt, who);
string err = SendTransfer(cur, amt, who, note);
_lastResult = err.Length > 0 ? err : "Transfer sent...";
},
"Send");
}
ImGui.EndDisabled();
if (_lastResult.Length > 0) ImGui.TextWrapped(_lastResult);
if (_lastResult.Length > 0) SafeImGui.TextWrapped(_lastResult);
}
private void RenderTransactionLog()
{
var snap = _txSnapshot;
ImGui.TextColored(IltStyle.ColTeal, $"Transactions ({snap.Length})");
SafeImGui.TextColored(IltStyle.ColTeal, $"Transactions ({snap.Length})");
ImGui.SameLine();
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##txfilter", "filter player / currency", ref _txFilter, 64u);
@ -543,7 +596,7 @@ internal sealed class IltBanking : IIltFeature
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Timestamp.ToString("g"));
ImGui.TableNextColumn();
ImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.ColGreen, t.Type);
SafeImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.ColGreen, t.Type);
ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(t.Amount));
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Currency);
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.OtherPlayer);

View file

@ -0,0 +1,316 @@
// IltBreedingEssence.cs - One carried combat pet essence, as the breeding tracker sees it.
//
// The facts come from the essence's appraisal (ACECustom [AssessmentProperty] qualities: bond 9053,
// male charges 9057, next breeding time float 9056, incense float 9058, neutered bool 9051, the
// male override 50053, juvenile 50054, Chromatic Catalyst 50055, the guardian's Offering 50056,
// maturity kills 9077, the mutation lines 9070..9075) and its LongDesc breeding block ("Sex: ...",
// "Growth: ...", "(shiny - cannot breed)"). Evaluate turns them into what the player needs to know:
// stud or dam, every breeding gate that fails, when it clears, growth, and the boosters applied.
// The gates are ACE PetDevice_Breeding's, with the thresholds from IltBreedingRules.
//
// Pure: no host calls (IltPetBreeding reads the host), so RynthILT.Tests checks it offline.
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>A gate's outcome for one essence.</summary>
internal enum BreedGate { Ready, Resting, NoCharges, Growing, Neutered, Shiny, LowBond, LowTier, NeedsId }
/// <summary>What was read for one essence (host values; pump thread fills it).</summary>
internal sealed class BreedEssenceFacts
{
public int Id;
public string Name = string.Empty;
public uint Wcid;
public bool HasId;
/// <summary>The essence's level requirement (a tier fallback for WCIDs outside the table).</summary>
public int UseLevel;
public int Bond;
/// <summary>The server's explicit sex (Tailoring Kit), or null to derive it from the object id.</summary>
public bool? MaleOverride;
public bool Neutered;
public bool JuvenileFlag;
/// <summary>PetMaturityKills: -1 when absent (the essence was never bred).</summary>
public int MaturityKills = -1;
/// <summary>PetMaleBreedingCharges: -1 when absent (a full stud).</summary>
public int MaleCharges = -1;
public double MaleRefreshUnix;
public double NextBreedUnix;
public double Incense;
public bool Catalyst;
public bool Offering;
public double MaturityXpMult;
public int MutDamage, MutDamageResist, MutCrit, MutVitality, MutPotency, MutationCount;
public int PotencyStored;
public bool Attuned;
public string LongDesc = string.Empty;
}
/// <summary>One essence evaluated for breeding. Immutable; the UI and the reader JSON read it.</summary>
internal sealed record BreedEssence(
int Id, string Name, uint Wcid, bool HasId, int Tier, int Bond, bool Male, BreedGate Gate, string Status,
IReadOnlyList<string> Problems, double ReadyAtUnix, int Charges, int ChargesMax, double RefillAtUnix,
bool Bred, bool Juvenile, int Stage, int Stages, string StageName, int Kills, int KillsRequired, int KillsToNext,
double Incense, bool Catalyst, bool Offering, bool Draught, IReadOnlyList<string> Boosters,
int MutD, int MutDR, int MutC, int MutV, int MutP, bool Shiny, bool Unbound, int Potency)
{
/// <summary>Every gate passes now.</summary>
public bool Ready => Gate == BreedGate.Ready;
/// <summary>The stat mutation lines (damage, damage resist, crit, vitality) summed.</summary>
public int StatMutations => MutD + MutDR + MutC + MutV;
/// <summary>"Stud" or "Dam".</summary>
public string Role => Male ? "Stud" : "Dam";
}
internal static class IltBreedingEssence
{
/// <summary>Essence tiers, in the order of each family row below (ACE PetDeviceWcids petLevelIndexes).</summary>
public static readonly int[] Tiers = { 50, 80, 100, 125, 150, 180, 200, 250, 300 };
// ACECustom PetDeviceWcids: one row per combat pet family, tiers 50 .. 300 in order. "a-b" is a
// run of consecutive WCIDs. Rows copied from Source/ACE.Server/Factories/Tables/Wcids/PetDeviceWcids.cs.
private static readonly string[] FamilyRows =
{
"48942,48944,48945,48946,48947,48948,48956,787801001,787801037",
"49213-49219,787801002,787801038",
"49220-49226,787801003,787801039",
"49227-49232,49212,787801004,787801040",
"48972,49234-49239,787801005,787801041",
"49240-49246,787801006,787801042",
"49247-49253,787801007,787801043",
"49254-49259,49233,787801008,787801044",
"49421-49427,787801009,787801045",
"49428-49434,787801010,787801046",
"49435-49441,787801011,787801047",
"49442-49448,787801012,787801048",
"48959,48961,48963,48965,48967,48969,48957,787801013,787801049",
"49261-49267,787801014,787801050",
"49268-49274,787801015,787801051",
"49275-49280,49260,787801016,787801052",
"49282-49287,49281,787801017,787801053",
"49289-49294,49288,787801018,787801054",
"49296-49301,49295,787801019,787801055",
"49303-49308,49302,787801020,787801056",
"49310-49316,787801021,787801057",
"49317-49323,787801022,787801058",
"49324-49330,787801023,787801059",
"49331-49336,49309,787801024,787801060",
"49338-49344,787801025,787801061",
"49345-49351,787801026,787801062",
"49352-49358,787801027,787801063",
"49359-49364,49337,787801028,787801064",
"49366-49372,787801029,787801065",
"49373-49379,787801030,787801066",
"49380-49386,787801031,787801067",
"49387-49392,49365,787801032,787801068",
"49524-49530,787801033,787801069",
"49531-49537,787801034,787801070",
"49538-49544,787801035,787801071",
"49545-49551,787801036,787801072",
};
/// <summary>Each family row expanded (tests check every row has one WCID per tier).</summary>
internal static readonly uint[][] Families = Array.ConvertAll(FamilyRows, ExpandRow);
private static readonly Dictionary<uint, int> TierByWcid = BuildTiers();
private static uint[] ExpandRow(string row)
{
var list = new List<uint>(9);
foreach (string token in row.Split(','))
{
int dash = token.IndexOf('-');
if (dash < 0) { list.Add(uint.Parse(token, CultureInfo.InvariantCulture)); continue; }
uint a = uint.Parse(token.AsSpan(0, dash), NumberStyles.Integer, CultureInfo.InvariantCulture);
uint b = uint.Parse(token.AsSpan(dash + 1), NumberStyles.Integer, CultureInfo.InvariantCulture);
for (uint w = a; w <= b; w++) list.Add(w);
}
return list.ToArray();
}
private static Dictionary<uint, int> BuildTiers()
{
var d = new Dictionary<uint, int>();
foreach (uint[] row in Families)
for (int i = 0; i < row.Length && i < Tiers.Length; i++)
d[row[i]] = Tiers[i];
return d;
}
/// <summary>True for a combat pet essence WCID (the only kind that breeds).</summary>
public static bool IsCombatEssence(uint wcid) => TierByWcid.ContainsKey(wcid);
/// <summary>The essence tier for a WCID, else the level requirement when it is a tier, else 0.</summary>
public static int TierOf(uint wcid, int useLevel = 0)
{
if (TierByWcid.TryGetValue(wcid, out int t)) return t;
return Array.IndexOf(Tiers, useLevel) >= 0 ? useLevel : 0;
}
/// <summary>ACE PetDevice.IsMale without an override: murmur3 fmix32 on the object id, even = male.</summary>
public static bool DeriveIsMale(int objectId)
{
uint h = unchecked((uint)objectId);
h ^= h >> 16;
h = unchecked(h * 0x7feb352d);
h ^= h >> 15;
h = unchecked(h * 0x846ca68b);
h ^= h >> 16;
return (h & 1) == 0;
}
/// <summary>"3h 05m", "42m", "20s" (0 or less = "now").</summary>
public static string Duration(double seconds)
{
if (seconds <= 0) return "now";
long s = (long)Math.Ceiling(seconds);
if (s >= 3600) return $"{s / 3600}h {s % 3600 / 60:00}m";
if (s >= 60) return $"{s / 60}m";
return $"{s}s";
}
/// <summary>
/// Evaluates one essence: role, every failing gate (the first is the headline), the ready time,
/// growth and boosters. <paramref name="nowUnix"/> is unix seconds.
/// </summary>
public static BreedEssence Evaluate(BreedEssenceFacts f, IltBreedingRules r, double nowUnix)
{
string desc = f.LongDesc ?? string.Empty;
bool male = f.MaleOverride ?? DeriveIsMale(f.Id);
int tier = TierOf(f.Wcid, f.UseLevel);
int bond = Math.Max(1, f.Bond);
bool shiny = desc.Contains("(shiny - cannot breed)", StringComparison.OrdinalIgnoreCase);
bool bred = f.MaturityKills >= 0;
bool juvenile = f.JuvenileFlag || desc.Contains("cannot breed yet", StringComparison.OrdinalIgnoreCase);
// Stud charges refill lazily on the server: full again once the refill time has passed.
int max = Math.Max(0, r.GetInt(IltBreedingRules.MaleCharges));
int charges = f.MaleCharges < 0 ? max : Math.Min(f.MaleCharges, max);
double refillAt = 0;
double refillH = r.Get(IltBreedingRules.MaleRefillHours);
if (male && f.MaleRefreshUnix > 0 && refillH > 0)
{
refillAt = f.MaleRefreshUnix + refillH * 3600.0;
if (nowUnix >= refillAt) { charges = max; refillAt = 0; }
}
if (male && charges >= max) refillAt = 0;
// Growth (bred essences only): stage from credited kills, as ACE PetDevice_Maturity.
int required = Math.Max(1, r.GetInt(IltBreedingRules.MaturityKills));
int stages = Math.Max(1, r.GetInt(IltBreedingRules.MaturityStages));
int kills = Math.Max(0, f.MaturityKills);
int perStage = Math.Max(1, (int)Math.Ceiling(required / (double)stages));
int stage = juvenile ? Math.Min(stages, kills / perStage + 1) : stages + 1;
int toNext = juvenile ? Math.Max(0, Math.Min(required, stage * perStage) - kills) : 0;
string stageName = juvenile ? r.StageName(stage) : bred ? "Adult" : string.Empty;
if (juvenile && IltBreedingRules.TryParseGrowth(desc, out string seenName, out int seenStage, out _, out int seenNext, out _, out int seenAdult))
{
// The appraisal line is the server's own math: prefer it when it is there.
stage = seenStage;
stageName = seenName;
toNext = seenNext;
kills = Math.Max(kills, required - seenAdult);
}
// Every failing gate, in the order the server checks them.
var problems = new List<string>();
BreedGate gate = BreedGate.Ready;
void Fail(BreedGate g, string text)
{
if (gate == BreedGate.Ready) gate = g;
problems.Add(text);
}
double readyAt = 0;
if (!f.HasId) Fail(BreedGate.NeedsId, "not appraised yet");
if (f.Neutered) Fail(BreedGate.Neutered, "neutered (permanent)");
if (shiny) Fail(BreedGate.Shiny, "shiny essences can't breed");
if (juvenile) Fail(BreedGate.Growing, $"still growing: {stageName} ({Math.Max(0, required - kills)} kills to Adult)");
int minTier = r.GetInt(IltBreedingRules.MinTier);
if (tier > 0 && tier < minTier) Fail(BreedGate.LowTier, $"tier {tier} (needs {minTier}+)");
int minBond = r.GetInt(IltBreedingRules.MinBond);
if (f.HasId && bond < minBond) Fail(BreedGate.LowBond, $"bond {bond}/{minBond}");
if (male && charges <= 0)
{
Fail(BreedGate.NoCharges, refillAt > 0 ? $"no charges (refill in {Duration(refillAt - nowUnix)})" : "no charges left");
readyAt = Math.Max(readyAt, refillAt);
}
if (!male && f.NextBreedUnix > nowUnix)
{
Fail(BreedGate.Resting, $"resting ({Duration(f.NextBreedUnix - nowUnix)})");
readyAt = Math.Max(readyAt, f.NextBreedUnix);
}
string status = gate switch
{
BreedGate.Ready => male ? $"Ready ({charges}/{max})" : "Ready",
BreedGate.Resting => "Rest " + Duration(f.NextBreedUnix - nowUnix),
BreedGate.NoCharges => refillAt > 0 ? "0/" + max + " refill " + Duration(refillAt - nowUnix) : "0/" + max,
BreedGate.Growing => $"{stageName} {Math.Min(stage, stages)}/{stages}",
BreedGate.Neutered => "Neutered",
BreedGate.Shiny => "Shiny",
BreedGate.LowBond => $"Bond {bond}/{minBond}",
BreedGate.LowTier => $"Tier {tier}",
_ => "ID needed",
};
bool draught = f.MaturityXpMult > 1.0001;
var boosters = new List<string>(4);
if (f.Incense > 0) boosters.Add(IltBreedingSupplies.IncenseName(f.Incense));
if (f.Catalyst) boosters.Add("Chromatic Catalyst");
if (f.Offering) boosters.Add("Offering of Subjugation");
if (draught) boosters.Add("Nurturing Draught x" + f.MaturityXpMult.ToString("0.#", CultureInfo.InvariantCulture));
return new BreedEssence(
f.Id, f.Name, f.Wcid, f.HasId, tier, bond, male, gate, status, problems, readyAt,
male ? charges : 0, male ? max : 0, male ? refillAt : 0,
bred, juvenile, juvenile ? stage : 0, stages, stageName, kills, required, toNext,
Math.Max(0, f.Incense), f.Catalyst, f.Offering, draught, boosters,
Math.Max(0, f.MutDamage), Math.Max(0, f.MutDamageResist), Math.Max(0, f.MutCrit), Math.Max(0, f.MutVitality),
Math.Max(0, f.MutPotency), shiny, bred && !f.Attuned && desc.Contains("Bond: Unbound", StringComparison.OrdinalIgnoreCase),
Math.Max(0, f.PotencyStored));
}
}
/// <summary>What a stud + dam pairing would do: the gates both must pass, and the baby's odds.</summary>
internal sealed record BreedPairPlan(bool CanBreed, IReadOnlyList<string> Blockers, double Incense, double ChanceBest, double ChanceWorst,
double PotencyChance, int InheritMin, int InheritMax, IReadOnlyList<string> Notes);
internal static class IltBreedingPlanner
{
/// <summary>
/// Plans one pairing. Each stat line comes from one parent, so the baby inherits between the
/// sum of the lower lines and the sum of the higher lines; more inherited mutations lower the
/// stat mutation chance (the decay), so the best case is the fewest.
/// </summary>
public static BreedPairPlan Plan(BreedEssence stud, BreedEssence dam, IltBreedingRules r)
{
var blockers = new List<string>();
if (!stud.Male) blockers.Add($"{stud.Name} is female: the stud must be male.");
if (dam.Male) blockers.Add($"{dam.Name} is male: the dam must be female.");
if (stud.Id == dam.Id) blockers.Add("Pick two different essences.");
foreach (string p in stud.Problems) blockers.Add($"{stud.Name}: {p}");
foreach (string p in dam.Problems) blockers.Add($"{dam.Name}: {p}");
int lo = Math.Min(stud.MutD, dam.MutD) + Math.Min(stud.MutDR, dam.MutDR) + Math.Min(stud.MutC, dam.MutC) + Math.Min(stud.MutV, dam.MutV);
int hi = Math.Max(stud.MutD, dam.MutD) + Math.Max(stud.MutDR, dam.MutDR) + Math.Max(stud.MutC, dam.MutC) + Math.Max(stud.MutV, dam.MutV);
double incense = r.CombinedIncense(stud.Incense, dam.Incense);
var notes = new List<string>
{
"The baby goes to the dam's owner: they need a free main-pack slot and burden room.",
$"Both pets in the same room of the breeding area ({r.RoomText()}); both owners *dance* within {r.Get(IltBreedingRules.DanceWindow):0.#}s.",
};
if (stud.Catalyst || dam.Catalyst) notes.Add("Chromatic Catalyst: the baby rolls a fresh colour.");
if (r.Get(IltBreedingRules.GuardianEnabled) >= 0.5)
notes.Add(stud.Offering || dam.Offering
? "Offering of Subjugation applied: the mating guardian comes weakened."
: $"A mating guardian rises: kill it within {r.Get(IltBreedingRules.GuardianSeconds):0}s for an Awakened Blessing mutation.");
if (incense > 0) notes.Add($"Incense +{incense * 100:0.#}% is used up by this breed.");
return new BreedPairPlan(blockers.Count == 0, blockers, incense,
r.StatMutationChance(lo, incense), r.StatMutationChance(hi, incense),
Math.Clamp(r.Get(IltBreedingRules.PotencyMutation), 0, 1), lo, hi, notes);
}
}

View file

@ -0,0 +1,445 @@
// IltBreedingRules.cs - Infinite Leaftide's pet breeding rules as RynthILT knows them.
//
// ACECustom's breeding (Source/ACE.Server/WorldObjects/PetDevice_Breeding.cs, docs/PET_BREEDING_*.md)
// is driven by ServerConfig values the client is never sent. Each rule here therefore has three
// possible sources, best last:
// * ACE default - the ServerConfig default in ACECustom;
// * ILT profile - what Infinite Leaftide runs (deploy/PROD_DEPLOY_PLAN.md: decay 0.1, the
// mating guardian on, pet bond on, the Seedy Motel room);
// * seen on server - read back from this server's own text: the appraisal breeding block
// ("Sex: Male (9/10 breeding charges today) - refills in 3h 10m", "Growth: ..."),
// "@breed-debug" ("Allowed Target: whole landblock 0x106, Variant=2"), and
// breeding chat ("spent a breeding charge: 9/10 left today", "They have 90s ...").
// A value seen on the server is saved with the character (IltPetState.Breeding) and wins from then on.
//
// Pure: no host calls, so RynthILT.Tests checks every parser offline.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Where a breeding rule's value came from (later = more trusted).</summary>
internal enum BreedRuleSource { AceDefault = 0, IltProfile = 1, Server = 2 }
/// <summary>One rule: stable key, label, unit, the ACE default and the ILT profile value (null = same as ACE).</summary>
internal sealed record BreedRuleDef(string Key, string Label, string Unit, double AceDefault, double? IltProfile, string Help);
/// <summary>A rule's effective value and where it came from.</summary>
internal readonly record struct BreedRuleValue(BreedRuleDef Def, double Value, BreedRuleSource Source, DateTime SeenUtc);
/// <summary>A value this server showed, saved with the character.</summary>
public sealed class IltLearnedRule
{
public string Key = string.Empty;
public double Value;
public DateTime SeenUtc;
}
/// <summary>One breeding event from chat (ritual, birth, growth, ...), newest last.</summary>
public sealed class IltBreedingEvent
{
public DateTime Utc;
/// <summary>ritual, charge, birth, mutation, guardian, growth, adult, imprint, dance, debug.</summary>
public string Kind = string.Empty;
public string Text = string.Empty;
}
/// <summary>The breeding tracker's saved part (IltPetState.Breeding).</summary>
public sealed class IltBreedingState
{
/// <summary>Rules read back from this server (see IltBreedingRules).</summary>
public List<IltLearnedRule> Rules = new();
/// <summary>Growth stage names this server uses, by stage (index 0 = stage 1); "" = not seen yet.</summary>
public List<string> StageNames = new();
/// <summary>Recent breeding events (capped at IltBreedingRules.MaxEvents).</summary>
public List<IltBreedingEvent> Log = new();
/// <summary>The last "@breed-debug" reply's lines and when it came.</summary>
public List<string> LastDebug = new();
public DateTime LastDebugUtc;
}
/// <summary>What one "@breed-debug" reply said.</summary>
internal sealed record BreedDebugInfo(bool? Enabled, string Location, uint AllowedLandblock, int AllowedVariant, string AllowedKind,
bool? LocationOk, string ActivePet, string PetSex, int Partners);
internal sealed class IltBreedingRules
{
// ── Rule keys ───────────────────────────────────────────────────────────
public const string Landblock = "landblock";
public const string Variant = "variant";
public const string DanceWindow = "dance_window_s";
public const string MinTier = "min_tier";
public const string MinBond = "min_bond";
public const string MaleCharges = "male_charges";
public const string MaleRefillHours = "male_refill_h";
public const string FemaleRestHours = "female_rest_h";
public const string BaseMutation = "base_mutation";
public const string MutationDecay = "mutation_decay";
public const string MutationFloor = "mutation_floor";
public const string PotencyMutation = "potency_mutation";
public const string IncenseCap = "incense_cap";
public const string Inheritance = "inheritance";
public const string GuardianEnabled = "guardian_enabled";
public const string GuardianSeconds = "guardian_s";
public const string MaturityKills = "maturity_kills";
public const string MaturityStages = "maturity_stages";
public const string MaturityShare = "maturity_share";
/// <summary>Breeding events kept with the character.</summary>
public const int MaxEvents = 60;
/// <summary>ACECustom's default growth stage names (pet_maturity_stage_names).</summary>
public static readonly string[] DefaultStageNames = { "Newborn", "Whelp", "Juvenile", "Adolescent", "Young Adult" };
/// <summary>Every rule shown, in display order. Values copied from ACECustom ServerConfig and the ILT deploy plan.</summary>
public static readonly BreedRuleDef[] Defs =
{
new(Landblock, "Breeding room landblock", "hex", 0x0106, null,
"pet_breeding_allowed_landblock: the Seedy Motel (Ruggan's Annex, portal by Prof. Ruggan in Lin 54.7S 73.5E)."),
new(Variant, "Breeding room variant", "", 2, null, "pet_breeding_allowed_variant: the landblock variant the room is in."),
new(DanceWindow, "Dance window", "s", 5, null, "Both owners must *dance* (or @dance) within this many seconds."),
new(MinTier, "Minimum essence tier", "", 100, null, "Both parents must be at least this tier (50, 80, 100, ... 300)."),
new(MinBond, "Minimum bond", "", 100, null, "Both parents need this bond level (bond grows from kills; pet_bond must be on)."),
new(MaleCharges, "Stud charges", "", 10, null, "pet_breeding_male_max_charges: breeds a male can sire per refill."),
new(MaleRefillHours, "Stud refill", "h", 24, null, "pet_breeding_male_charge_reset_hours: charges refill this long after the last refill."),
new(FemaleRestHours, "Dam rest", "h", 4, null, "A female rests this long after each breed before she can breed again."),
new(BaseMutation, "Stat mutation chance", "%", 0.05, null, "pet_breeding_mutation_chance: the base chance of a stat mutation."),
new(MutationDecay, "Mutation decay", "", 0.0, 0.1,
"pet_breeding_mutation_decay: each stat mutation the baby inherits divides the chance by (1 + decay x mutations)."),
new(MutationFloor, "Mutation floor", "%", 0.02, null, "The stat mutation chance never drops below this."),
new(PotencyMutation, "Potency mutation chance", "%", 0.03, null, "An independent roll for a potency mutation."),
new(IncenseCap, "Incense cap", "%", 0.50, null, "Both parents' incense together adds at most this much."),
new(Inheritance, "Dominant line weight", "%", 0.55, null, "Each stat line comes from one parent, 55 / 45."),
new(GuardianEnabled, "Mating guardian", "on/off", 0, 1,
"pet_breeding_guardian_enabled: a spirit rises after the ritual; killing it in time grants an Awakened Blessing mutation."),
new(GuardianSeconds, "Guardian timer", "s", 90, null, "How long the two parents have to kill the guardian."),
new(MaturityKills, "Kills to adulthood", "", 300, null, "pet_maturity_kills_required: a bred baby grows up with this many credited kills."),
new(MaturityStages, "Growth stages", "", 5, null, "pet_maturity_stages: the growth stages before Adult."),
new(MaturityShare, "Kill credit share", "%", 0.10, null,
"A kill counts when the pet dealt this share of the victim's health and the victim's level is at least the essence tier."),
};
private static readonly Dictionary<string, BreedRuleDef> DefByKey = BuildIndex();
private static Dictionary<string, BreedRuleDef> BuildIndex()
{
var d = new Dictionary<string, BreedRuleDef>(StringComparer.Ordinal);
foreach (BreedRuleDef def in Defs) d[def.Key] = def;
return d;
}
private readonly IltBreedingState _state;
/// <param name="state">The saved breeding state; learned values are read from and written to it.</param>
public IltBreedingRules(IltBreedingState state) => _state = state;
/// <summary>The saved state these rules read and update.</summary>
public IltBreedingState State => _state;
/// <summary>A copy that never changes (the render thread reads it while the pump learns).</summary>
public IltBreedingRules Frozen()
{
var copy = new IltBreedingState { StageNames = new List<string>(_state.StageNames) };
foreach (IltLearnedRule l in _state.Rules)
copy.Rules.Add(new IltLearnedRule { Key = l.Key, Value = l.Value, SeenUtc = l.SeenUtc });
return new IltBreedingRules(copy);
}
/// <summary>The effective value of rule <paramref name="key"/> (0 for an unknown key).</summary>
public double Get(string key) => Value(key).Value;
/// <summary>A whole-number rule (charges, kills, tiers).</summary>
public int GetInt(string key) => (int)Math.Round(Get(key));
/// <summary>The effective value and its source.</summary>
public BreedRuleValue Value(string key)
{
if (!DefByKey.TryGetValue(key, out BreedRuleDef? def))
return new BreedRuleValue(new BreedRuleDef(key, key, "", 0, null, ""), 0, BreedRuleSource.AceDefault, default);
foreach (IltLearnedRule l in _state.Rules)
if (l.Key == key) return new BreedRuleValue(def, l.Value, BreedRuleSource.Server, l.SeenUtc);
return def.IltProfile.HasValue
? new BreedRuleValue(def, def.IltProfile.Value, BreedRuleSource.IltProfile, default)
: new BreedRuleValue(def, def.AceDefault, BreedRuleSource.AceDefault, default);
}
/// <summary>Every rule's effective value, in display order.</summary>
public List<BreedRuleValue> All()
{
var list = new List<BreedRuleValue>(Defs.Length);
foreach (BreedRuleDef d in Defs) list.Add(Value(d.Key));
return list;
}
/// <summary>Records a value the server showed. True when it changed what RynthILT knew.</summary>
public bool Learn(string key, double value, DateTime utc)
{
if (!DefByKey.ContainsKey(key) || double.IsNaN(value) || double.IsInfinity(value)) return false;
foreach (IltLearnedRule l in _state.Rules)
{
if (l.Key != key) continue;
bool changed = Math.Abs(l.Value - value) > 1e-9;
l.Value = value;
l.SeenUtc = utc;
return changed;
}
_state.Rules.Add(new IltLearnedRule { Key = key, Value = value, SeenUtc = utc });
return true;
}
/// <summary>Applies every (key, value) an observer returned. True when anything changed.</summary>
public bool LearnAll(IEnumerable<(string Key, double Value)> seen, DateTime utc)
{
bool changed = false;
foreach ((string k, double v) in seen) changed |= Learn(k, v, utc);
return changed;
}
/// <summary>Records a growth stage's name (1-based) as the server spelled it.</summary>
public bool LearnStageName(int stage, string name)
{
name = (name ?? string.Empty).Trim();
if (stage < 1 || stage > 50 || name.Length == 0 || name.Length > 40) return false;
while (_state.StageNames.Count < stage) _state.StageNames.Add(string.Empty);
if (_state.StageNames[stage - 1] == name) return false;
_state.StageNames[stage - 1] = name;
return true;
}
/// <summary>The name of growth stage <paramref name="stage"/> (1-based): seen on the server, else ACE's default, else "Stage N".</summary>
public string StageName(int stage)
{
if (stage >= 1 && stage <= _state.StageNames.Count && _state.StageNames[stage - 1].Length > 0)
return _state.StageNames[stage - 1];
if (stage >= 1 && stage <= DefaultStageNames.Length && GetInt(MaturityStages) == DefaultStageNames.Length)
return DefaultStageNames[stage - 1];
return "Stage " + stage.ToString(CultureInfo.InvariantCulture);
}
/// <summary>Appends an event, dropping the oldest past <see cref="MaxEvents"/>.</summary>
public void AddEvent(string kind, string text, DateTime utc)
{
_state.Log.Add(new IltBreedingEvent { Utc = utc, Kind = kind, Text = text });
if (_state.Log.Count > MaxEvents) _state.Log.RemoveRange(0, _state.Log.Count - MaxEvents);
}
// ── Mutation odds (ACE PetDevice_Breeding) ──────────────────────────────
/// <summary>
/// The chance of a stat mutation for a baby that inherits <paramref name="babyStatMutations"/>
/// stat mutations, with <paramref name="incense"/> from both parents (already capped):
/// clamp(max(floor, (base + incense) / (1 + decay x mutations)), 0, 1).
/// </summary>
public double StatMutationChance(int babyStatMutations, double incense)
{
double decay = Math.Max(0, Get(MutationDecay));
double raw = (Get(BaseMutation) + Math.Max(0, incense)) / (1.0 + decay * Math.Max(0, babyStatMutations));
return Math.Clamp(Math.Max(Get(MutationFloor), raw), 0.0, 1.0);
}
/// <summary>Both parents' incense together, capped at the incense cap.</summary>
public double CombinedIncense(double a, double b) => Math.Clamp(Math.Max(0, a) + Math.Max(0, b), 0.0, Math.Max(0, Get(IncenseCap)));
// ── Observers: what the server's own text says about its rules ──────────
private const RegexOptions Rx = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;
private static readonly Regex MaleLine = new(@"Sex:\s*Male\s*\((\d+)\s*/\s*(\d+) breeding charges today\)(?:\s*-\s*refills in (?:(\d+)h\s*)?(?:(\d+)m)?)?", Rx);
private static readonly Regex GrowthLine = new(@"Growth:\s*(.+?)\s+(\d+)\s*/\s*(\d+)\s*-\s*(\d+) kills to (.+?)(?:,\s*(\d+) to Adult)?\s*$", Rx | RegexOptions.Multiline);
private static readonly Regex ChargeSpent = new(@"spent a breeding charge:\s*(\d+)\s*/\s*(\d+) left today", Rx);
private static readonly Regex GuardianRise = new(@"They have (\d+)s to bring it down together", Rx);
private static readonly Regex GrownInto = new(@"has grown into an? (.+?)!.*\((\d+)\s*/\s*(\d+)\)", Rx);
private static readonly Regex DanceWindowLine = new(@"\*dance\* within (\d+(?:\.\d+)?) seconds", Rx);
private static readonly Regex DebugEnabled = new(@"Breeding System Enabled:\s*(True|False)", Rx);
private static readonly Regex DebugLocation = new(@"Your Location:\s*(.+)$", Rx);
private static readonly Regex DebugAllowed = new(@"Allowed Target:\s*(anywhere|whole landblock|exact cell)\s*0x([0-9A-F]+),\s*Variant=(-?\d+)\s*=>\s*Location Match:\s*(VALID|INVALID)", Rx);
private static readonly Regex DebugPet = new(@"Your Active Pet:\s*(.+)$", Rx);
private static readonly Regex DebugSex = new(@"^\s*Sex:\s*(.+)$", Rx);
private static readonly Regex DebugPartners = new(@"(?:Eligible breeding partners nearby|Valid Partner Candidates within 30m):\s*(\d+)", Rx);
/// <summary>
/// What an essence's appraisal text says: the stud's charge max and refill window (from the
/// "refills in" countdown against the essence's last refill time), and the growth stage count.
/// </summary>
/// <param name="longDesc">The appraisal LongDesc (string 16).</param>
/// <param name="maleRefreshUnix">The essence's PetMaleChargesRefreshTime (0 = not sent).</param>
/// <param name="nowUnix">Now, unix seconds.</param>
public static List<(string Key, double Value)> FromAppraisal(string longDesc, double maleRefreshUnix, double nowUnix)
{
var seen = new List<(string, double)>();
if (string.IsNullOrEmpty(longDesc)) return seen;
Match m = MaleLine.Match(longDesc);
if (m.Success)
{
if (int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000)
seen.Add((MaleCharges, max));
if ((m.Groups[3].Success || m.Groups[4].Success) && maleRefreshUnix > 0)
{
int h = m.Groups[3].Success ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) : 0;
int min = m.Groups[4].Success ? int.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture) : 0;
double refillAt = nowUnix + h * 3600.0 + min * 60.0;
double hours = Math.Round((refillAt - maleRefreshUnix) / 3600.0);
// The countdown is minute-rounded; only a whole-hour window that makes sense is taken.
if (hours >= 1 && hours <= 24 * 14) seen.Add((MaleRefillHours, hours));
}
}
Match g = GrowthLine.Match(longDesc);
if (g.Success && int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50)
seen.Add((MaturityStages, stages));
return seen;
}
/// <summary>
/// The growth line of an appraisal: current stage name, stage, stages, kills to the next stage
/// and to adulthood (-1 when the line has no "to Adult" part, i.e. the last stage).
/// </summary>
public static bool TryParseGrowth(string longDesc, out string stageName, out int stage, out int stages, out int toNext, out string nextName, out int toAdult)
{
stageName = nextName = string.Empty;
stage = stages = toNext = toAdult = 0;
if (string.IsNullOrEmpty(longDesc)) return false;
Match g = GrowthLine.Match(longDesc);
if (!g.Success) return false;
stageName = g.Groups[1].Value.Trim();
int.TryParse(g.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage);
int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stages);
int.TryParse(g.Groups[4].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toNext);
nextName = g.Groups[5].Value.Trim();
if (g.Groups[6].Success) int.TryParse(g.Groups[6].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toAdult);
else { toAdult = toNext; nextName = "Adult"; }
return true;
}
/// <summary>What one chat line says about the rules (a line can say nothing).</summary>
public static List<(string Key, double Value)> FromChat(string line)
{
var seen = new List<(string, double)>();
if (string.IsNullOrEmpty(line)) return seen;
Match m = ChargeSpent.Match(line);
if (m.Success && int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000)
seen.Add((MaleCharges, max));
m = GuardianRise.Match(line);
if (m.Success)
{
seen.Add((GuardianEnabled, 1));
if (int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int s) && s > 0 && s < 3600)
seen.Add((GuardianSeconds, s));
}
else if (line.Contains("The union stirs something", StringComparison.OrdinalIgnoreCase))
seen.Add((GuardianEnabled, 1));
m = GrownInto.Match(line);
if (m.Success && int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50)
seen.Add((MaturityStages, stages));
m = DanceWindowLine.Match(line);
if (m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double w) && w > 0 && w < 600)
seen.Add((DanceWindow, w));
foreach (string part in line.Split('\n'))
{
m = DebugAllowed.Match(part);
if (!m.Success) continue;
if (uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb))
seen.Add((Landblock, lb));
if (int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v))
seen.Add((Variant, v));
}
return seen;
}
/// <summary>The stage name a "has grown into a Whelp! ... (2/5)" line gives, with its stage number; false for any other line.</summary>
public static bool TryParseGrownInto(string line, out int stage, out string name)
{
stage = 0;
name = string.Empty;
Match m = GrownInto.Match(line ?? string.Empty);
if (!m.Success || !int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage)) return false;
name = m.Groups[1].Value.Trim();
return name.Length > 0;
}
/// <summary>True for any line of an "@breed-debug" reply (one multi-line message, or its lines one by one).</summary>
public static bool IsDebugLine(string text)
{
if (string.IsNullOrEmpty(text)) return false;
return text.Contains("PET BREEDING DIAGNOSTICS", StringComparison.OrdinalIgnoreCase)
|| DebugEnabled.IsMatch(text) || DebugLocation.IsMatch(text) || DebugAllowed.IsMatch(text)
|| DebugPet.IsMatch(text) || DebugPartners.IsMatch(text)
|| text.TrimStart().StartsWith("Sex:", StringComparison.OrdinalIgnoreCase)
|| text.Contains("Ensure your partner has their pet summoned", StringComparison.OrdinalIgnoreCase)
|| IsDebugEnd(text);
}
/// <summary>The reply's closing rule of '=' (alone, or ending the whole message).</summary>
public static bool IsDebugEnd(string text)
=> !string.IsNullOrEmpty(text) && text.TrimEnd().EndsWith("================================", StringComparison.Ordinal);
/// <summary>Parses an "@breed-debug" reply (any mix of whole messages and single lines).</summary>
public static BreedDebugInfo ParseDebug(IEnumerable<string> lines)
{
bool? enabled = null, ok = null;
string location = string.Empty, kind = string.Empty, pet = string.Empty, sex = string.Empty;
uint lb = 0;
int variant = -1, partners = -1;
foreach (string text in lines)
{
foreach (string raw in (text ?? string.Empty).Split('\n'))
{
string l = raw.TrimEnd('\r');
Match m;
if ((m = DebugEnabled.Match(l)).Success) enabled = m.Groups[1].Value.Equals("True", StringComparison.OrdinalIgnoreCase);
else if ((m = DebugAllowed.Match(l)).Success)
{
kind = m.Groups[1].Value.ToLowerInvariant();
uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb);
int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out variant);
ok = m.Groups[4].Value.Equals("VALID", StringComparison.OrdinalIgnoreCase);
}
else if ((m = DebugLocation.Match(l)).Success) location = m.Groups[1].Value.Trim();
else if ((m = DebugPet.Match(l)).Success) pet = m.Groups[1].Value.Trim();
else if ((m = DebugPartners.Match(l)).Success) int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out partners);
else if ((m = DebugSex.Match(l)).Success) sex = m.Groups[1].Value.Trim();
}
}
return new BreedDebugInfo(enabled, location, lb, variant, kind, ok, pet, sex, partners);
}
/// <summary>"0x0106 variant 2" (or "anywhere") for the rules list.</summary>
public string RoomText()
{
uint lb = (uint)Math.Max(0, Get(Landblock));
int variant = GetInt(Variant);
if (lb == 0) return "anywhere";
string place = lb > 0xFFFF ? "cell 0x" + lb.ToString("X8", CultureInfo.InvariantCulture) : "landblock 0x" + lb.ToString("X4", CultureInfo.InvariantCulture);
return variant >= 0 ? place + " variant " + variant.ToString(CultureInfo.InvariantCulture) : place;
}
/// <summary>A rule value for display: "5%", "24h", "0x0106", "on", "10".</summary>
public static string Format(BreedRuleValue v)
{
switch (v.Def.Unit)
{
case "%": return (v.Value * 100.0).ToString("0.##", CultureInfo.InvariantCulture) + "%";
case "h": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "h";
case "s": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "s";
case "hex": return "0x" + ((uint)Math.Max(0, v.Value)).ToString("X4", CultureInfo.InvariantCulture);
case "on/off": return v.Value >= 0.5 ? "on" : "off";
default: return v.Value.ToString("0.##", CultureInfo.InvariantCulture);
}
}
/// <summary>"ACE default", "ILT profile" or "seen on server".</summary>
public static string SourceText(BreedRuleSource s) => s switch
{
BreedRuleSource.Server => "seen on server",
BreedRuleSource.IltProfile => "ILT profile",
_ => "ACE default",
};
}

View file

@ -0,0 +1,112 @@
// IltBreedingSupplies.cs - Ivo's breeding supplies (ACECustom, Seedy Motel vendor) and when each can
// be used on an essence.
//
// WCIDs, prices and refusals copied from ACECustom (Player_Use.cs HandleActionUseOnTarget, the
// PetDevice.BreedingMath incense constants, docs/PET_BREEDING_PLAYER_GUIDE.md). RynthILT applies
// only the breeding boosters (incense, Nurturing Draught, Chromatic Catalyst, Offering of
// Subjugation), and only after the player confirms; the Neutering Kit is permanent and the kits,
// serum and tinctures are cosmetic, so those are counted, never used from here.
//
// Pure: RynthILT.Tests checks the refusals offline.
using System;
using System.Globalization;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One supply: key, WCID, name, what it does, Ivo's price, and whether the tracker can apply it.</summary>
internal sealed record BreedSupplyDef(string Key, uint Wcid, string Name, string Effect, long Price, bool Apply);
internal static class IltBreedingSupplies
{
public const string LesserIncense = "incense1";
public const string RefinedIncense = "incense2";
public const string ExquisiteIncense = "incense3";
public const string Draught = "draught";
public const string Catalyst = "catalyst";
public const string Offering = "offering";
public const string NeuteringKit = "neuter";
public const string TailoringKit = "tailor";
public const string FilledTailoringKit = "tailor_filled";
public const string Serum = "serum";
public const string Solidifying = "solidify";
public const string Fading = "fade";
/// <summary>Every supply, boosters first.</summary>
public static readonly BreedSupplyDef[] All =
{
new(LesserIncense, 78780250, "Lesser Courtship Incense", "+2.5% stat mutation chance on the next breed.", 1_250_000, true),
new(RefinedIncense, 78780251, "Refined Courtship Incense", "+5% stat mutation chance on the next breed.", 2_500_000, true),
new(ExquisiteIncense, 78780252, "Exquisite Courtship Incense", "+10% stat mutation chance on the next breed.", 5_000_000, true),
new(Draught, 78780253, "Nurturing Draught", "A juvenile earns 2x maturity kill credit until adulthood.", 2_500_000, true),
new(Catalyst, 78780254, "Chromatic Catalyst", "The next baby rolls a fresh colour.", 2_500_000, true),
new(Offering, 78780255, "Offering of Subjugation", "The next mating guardian comes weakened.", 2_500_000, true),
new(NeuteringKit, 78780258, "Neutering Kit", "Permanently stops an essence from breeding.", 2_500_000, false),
new(TailoringKit, 78780259, "Tailoring Kit", "Extracts an essence's appearance.", 125_000_000, false),
new(FilledTailoringKit, 78780260, "Filled Tailoring Kit", "Applies an extracted appearance.", 0, false),
new(Serum, 78780257, "Mutagenic Serum", "Re-rolls an essence's colour.", 25_000_000, false),
new(Solidifying, 78780262, "Solidifying Tincture", "Makes the summoned pet less translucent.", 12_500_000, false),
new(Fading, 78780263, "Fading Tincture", "Makes the summoned pet more translucent.", 12_500_000, false),
};
/// <summary>The supply with this key, or null.</summary>
public static BreedSupplyDef? Find(string key) => Array.Find(All, s => s.Key == key);
/// <summary>The incense bonus a supply gives (0 for anything else).</summary>
public static double IncenseBonus(string key) => key switch
{
LesserIncense => 0.025,
RefinedIncense => 0.05,
ExquisiteIncense => 0.10,
_ => 0,
};
/// <summary>"Refined incense +5%" for an applied bonus.</summary>
public static string IncenseName(double bonus)
{
string grade = bonus >= 0.0999 ? "Exquisite" : bonus >= 0.0499 ? "Refined" : "Lesser";
return $"{grade} incense +{(bonus * 100).ToString("0.#", CultureInfo.InvariantCulture)}%";
}
/// <summary>
/// Why the server would refuse <paramref name="s"/> on <paramref name="e"/> (the server's own
/// checks, so nothing is spent on a refusal), or null when it would take it.
/// </summary>
public static string? RefuseReason(BreedSupplyDef s, BreedEssence e, IltBreedingRules r)
{
if (!s.Apply) return "Not applied from here.";
double incense = IncenseBonus(s.Key);
if (incense > 0)
{
if (e.Gate == BreedGate.Neutered) return "A neutered essence can't take incense.";
if (e.Incense >= incense - 1e-6) return $"Already primed with equal or stronger incense (+{e.Incense * 100:0.#}%).";
return null;
}
return s.Key switch
{
Draught when !e.Juvenile => "Only a juvenile (still growing) can take a Nurturing Draught.",
Draught when e.Draught => "Already under a Nurturing Draught.",
Catalyst when e.Catalyst => "Already infused with a Chromatic Catalyst.",
Offering when r.Get(IltBreedingRules.GuardianEnabled) < 0.5 => "Mating guardians are off on this server.",
Offering when e.Offering => "Already under an Offering of Subjugation.",
_ => null,
};
}
/// <summary>A warning to show in the confirmation (a weaker incense being replaced), or "".</summary>
public static string Warning(BreedSupplyDef s, BreedEssence e)
{
double incense = IncenseBonus(s.Key);
if (incense > 0 && e.Incense > 0 && e.Incense < incense)
return $" It replaces the +{e.Incense * 100:0.#}% incense already on it (that one is lost).";
return string.Empty;
}
/// <summary>"1.25M", "125M", "-" for a price.</summary>
public static string PriceText(long price)
{
if (price <= 0) return "-";
if (price >= 1_000_000) return (price / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M";
if (price >= 1_000) return (price / 1_000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k";
return price.ToString(CultureInfo.InvariantCulture);
}
}

View file

@ -15,6 +15,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -214,9 +215,9 @@ internal sealed class IltBuffKeepers : IIltFeature
int cd = G.DispelCooldownSeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Cooldown (s)##disp", ref cd)) G.DispelCooldownSeconds = Math.Max(2, cd);
ImGui.TextDisabled("Status: " + _dispelStatus);
SafeImGui.TextDisabled("Status: " + _dispelStatus);
var harm = _harmfulNow;
if (harm.Length > 0) ImGui.TextColored(IltStyle.ColAmber, "Harmful now: " + string.Join(", ", harm));
if (harm.Length > 0) SafeImGui.TextColored(IltStyle.ColAmber, "Harmful now: " + string.Join(", ", harm));
if (ImGui.TreeNode("Always / never dispel lists"))
{
EditList("Always dispel (name contains)", G.DispelInclusions, ref _newInclude, "inc");
@ -228,7 +229,7 @@ internal sealed class IltBuffKeepers : IIltFeature
ImGui.TextColored(IltStyle.ColTeal, "Surging Strength");
bool ss = G.SurgingStrength;
if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss;
ImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus));
SafeImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus));
}
private void EditList(string label, List<string> list, ref string buffer, string id)
@ -237,7 +238,7 @@ internal sealed class IltBuffKeepers : IIltFeature
var snap = list.ToArray();
for (int i = 0; i < snap.Length; i++)
{
ImGui.BulletText(snap[i]);
SafeImGui.BulletText(snap[i]);
ImGui.SameLine();
string victim = snap[i];
if (ImGui.SmallButton($"x##{id}{i}")) _ctx.Post(() => list.Remove(victim));

View file

@ -132,7 +132,9 @@ internal sealed class IltCharmTracker
sb.Append(",\"server\":\"").Append(TriText(r.Server)).Append('"');
sb.Append(",\"lastSeen\":\"")
.Append(r.LastSeenUtc == default ? string.Empty : r.LastSeenUtc.ToString("yyyy-MM-dd"))
.Append("\"}");
.Append('"');
// The carried copy a reader's Toggle uses ("RynthILT.Data" ToggleCharm); 0 = none carried.
sb.Append(",\"toggleId\":").Append(unchecked((uint)r.ToggleId)).Append('}');
}
sb.Append("]}");
return sb.ToString();

View file

@ -1,4 +1,6 @@
// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm in one table.
// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm and the
// Guardian Hand, with their toggles. Other plugins read the same list and toggle through
// "RynthILT.Data" (BuildReaderJson / ToggleFromReader).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Per charm (IltCharmTracker): acquired ("carried" now, "stored" = carried before and remembered
@ -14,6 +16,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -68,6 +71,52 @@ internal sealed class IltCharms : IIltFeature
_lastScan = 0; // re-read the status soon (the appraisal refresh is throttled per item)
}
/// <summary>
/// A Toggle from another plugin ("RynthILT.Data" ToggleCharm). Only
/// a registry charm or Guardian Hand the player carries is used, so a reader can't make the
/// client use anything else. Pump thread. True when it was used.
/// </summary>
public bool ToggleFromReader(uint id)
{
if (id == 0 || id > int.MaxValue) return false;
var inv = _ctx.Inventory;
foreach (var wo in inv.Items())
{
if (wo.Id != (int)id) continue;
if (inv.CharmDefFor(wo) == null && !IsGuardianHand(wo)) return false;
Toggle(wo.Id);
return true;
}
return false;
}
/// <summary>
/// The "RynthILT.Data" charms JSON: the registry charms
/// (IltCharmTracker.BuildJson) plus a "hands" array, every Guardian Hand carried now with its
/// object id (the Toggle's id), status and the server's switch. Pump thread.
/// </summary>
public string BuildReaderJson()
{
string json = _tracker.BuildJson();
if (!_ctx.Options.IsIltLikeWorld || !json.EndsWith("]}", StringComparison.Ordinal)) return json;
var inv = _ctx.Inventory;
string server = _ctx.Options.Get(IltFeature.Charm("Guardian Hand")) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
var sb = new System.Text.StringBuilder(json, 0, json.Length - 1, json.Length + 256);
sb.Append(",\"hands\":[");
bool first = true;
foreach (var wo in inv.Items().Where(IsGuardianHand))
{
if (!first) sb.Append(',');
first = false;
string active = inv.CharmStatus(wo) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
sb.Append("{\"id\":").Append(unchecked((uint)wo.Id));
sb.Append(",\"name\":\"").Append(IltStyle.JsonEscape(wo.Name)).Append('"');
sb.Append(",\"active\":\"").Append(active).Append('"');
sb.Append(",\"server\":\"").Append(server).Append("\"}");
}
return sb.Append("]}").ToString();
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
@ -93,13 +142,13 @@ internal sealed class IltCharms : IIltFeature
var rows = _rows;
if (rows.Length == 0)
{
ImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms.");
SafeImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms.");
RenderGuardianHand();
return;
}
int acquired = rows.Count(r => r.Acquired != "no"), active = rows.Count(r => r.Active == IltTri.On);
ImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active");
SafeImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##charms")) _ctx.Post(() => { _lastScan = 0; });
@ -133,16 +182,16 @@ internal sealed class IltCharms : IIltFeature
ImGui.TableNextColumn();
bool carried = r.Acquired == "carried";
if (carried) ImGui.TextUnformatted(r.Def.Name);
else ImGui.TextColored(IltStyle.ColTextMute, r.Def.Name);
if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) ImGui.SetTooltip(r.Def.Effect);
else SafeImGui.TextColored(IltStyle.ColTextMute, r.Def.Name);
if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) SafeImGui.SetTooltip(r.Def.Effect);
ImGui.TableNextColumn();
if (carried) ImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
if (carried) SafeImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
else if (r.Acquired == "seen")
{
ImGui.TextColored(IltStyle.ColAmber, "Stored");
if (ImGui.IsItemHovered() && r.LastSeenUtc != default)
ImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd"));
SafeImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd"));
}
else ImGui.TextDisabled("No");
@ -188,12 +237,12 @@ internal sealed class IltCharms : IIltFeature
foreach (var h in hands)
{
ImGui.PushID(h.Id);
if (h.ServerDisabled) ImGui.TextDisabled($"{h.Name} - disabled on this server");
if (h.ServerDisabled) SafeImGui.TextDisabled($"{h.Name} - disabled on this server");
else
{
var col = h.Status == IltTri.On ? IltStyle.ColGreen
: h.Status == IltTri.Off ? IltStyle.ColTextMute : IltStyle.ColAmber;
ImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? ");
SafeImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? ");
ImGui.SameLine();
ImGui.TextUnformatted(h.Name);
ImGui.SameLine();

View file

@ -2,7 +2,7 @@
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb,
// /ilt features, the login probe, ...) goes through this one queue so that:
// the login probe, /myquests, ...) goes through this one queue so that:
// * only one capture is in flight at a time (replies can't be attributed to the wrong
// request),
// * reply lines can be eaten so a Hub refresh doesn't spam the chat window,
@ -21,6 +21,12 @@ internal sealed class IltChatRequest
public string Command = string.Empty;
/// <summary>True for lines that belong to this reply (captured, refresh the idle timer).</summary>
public Func<string, bool> IsResponseLine = _ => false;
/// <summary>
/// Optional: only these response lines arm / refresh the idle timer. Header / banner lines
/// still capture, but idle completion waits until a progress line arrives (UB's /aug fetch:
/// dashes and "Advanced Augmentation Levels:" must not start the 2s idle before Creature:).
/// </summary>
public Func<string, bool>? ArmsIdle;
/// <summary>Optional: a line that ends the reply immediately (it is captured too).</summary>
public Func<string, bool>? IsTerminator;
/// <summary>The reply is complete after this long with no new response line.</summary>
@ -55,6 +61,8 @@ internal sealed class IltChatCapture
private IltChatResult? _activeResult;
private long _sentAt;
private long _lastLineAt;
/// <summary>True once a response line that arms idle has arrived (always true when <see cref="IltChatRequest.ArmsIdle"/> is null).</summary>
private bool _idleArmed;
/// <summary>Minimum spacing between two sends so the server's own command throttles aren't tripped.</summary>
private const long SendSpacingMs = 400;
@ -102,9 +110,11 @@ internal sealed class IltChatCapture
if (_active != null && _activeResult != null)
{
bool gotAny = _activeResult.Lines.Count > 0;
if (gotAny && now - _lastLineAt >= _active.IdleEndMs)
// Idle completion only after a progress line when ArmsIdle is set (header alone is not enough).
bool idleReady = _active.ArmsIdle == null || _idleArmed;
if (gotAny && idleReady && now - _lastLineAt >= _active.IdleEndMs)
Finish();
else if (!gotAny && now - _sentAt >= _active.FirstLineTimeoutMs)
else if ((!gotAny || !idleReady) && now - _sentAt >= _active.FirstLineTimeoutMs)
{
_activeResult.TimedOut = true;
Finish();
@ -147,7 +157,12 @@ internal sealed class IltChatCapture
if (!_active.IsResponseLine(text)) return false;
_activeResult.Lines.Add(text);
_lastLineAt = NowMs;
// Header-only replies (e.g. /aug dashes + banner) must not start the idle clock.
if (_active.ArmsIdle == null || _active.ArmsIdle(text))
{
_idleArmed = true;
_lastLineAt = NowMs;
}
RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}");
return _active.Eat;
}
@ -179,6 +194,7 @@ internal sealed class IltChatCapture
_activeResult = result;
_sentAt = now;
_lastLineAt = now;
_idleArmed = req.ArmsIdle == null; // no progress gate → idle can finish after any response line
_lastSendAt = now;
RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})");
_host.InvokeChatParser(req.Command);
@ -190,6 +206,7 @@ internal sealed class IltChatCapture
var res = _activeResult;
_active = null;
_activeResult = null;
_idleArmed = false;
if (req == null || res == null) return;
RynthLog.Trace(LogCat.IltChat,
$"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " +

View file

@ -1,13 +1,17 @@
// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Chunk: uses a Lugian (Aetheria) Hammer on eligible items, one at a time:
// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time:
// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), and
// max level (int 319) under the configured cap (Coalesced always qualifies).
// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), no kept
// C / CD / CDR rating (gear ints 372 / 374 / 375; on by default), and max level
// (int 319, up to 10 on ILT) under the configured cap (Coalesced always qualifies).
// Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179),
// not equipped, not never-chunk, cleave (292) <= 1.
// Peace mode only unless ChunkInCombat; waits for the result line (10 s max).
// The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...)
// are loot and chunk nothing: the server answers with no result line, so every item timed out
// into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15).
// Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. Needs the
// AutoCraftingEnabled stamp; 30 min ± 2 min interval, first attempt ~1 min after enable.
using System;
@ -15,6 +19,7 @@ using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -60,10 +65,14 @@ internal sealed class IltChunkClap : IIltFeature
// ── Chunk ───────────────────────────────────────────────────────────────
/// <summary>Infinite Leaftide's chunking tool.</summary>
internal const string HammerName = "Lugian Aetheria Hammer";
/// <summary>True for the chunking tool only, never a Lugian Hammer weapon. Pure: the tests drive it.</summary>
internal static bool IsChunkHammer(string name) => name.Equals(HammerName, StringComparison.OrdinalIgnoreCase);
private WorldObject? FindHammer()
=> _ctx.Inventory.FindByName(n => n.Equals("Lugian Aetheria Hammer", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Lugian Hammer", StringComparison.OrdinalIgnoreCase)
|| n.EndsWith(" Lugian Hammer", StringComparison.OrdinalIgnoreCase));
=> _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo));
/// <summary>True/false when decidable; null when appraisal is still needed.</summary>
private bool? IsChunkableAetheria(WorldObject wo)
@ -77,9 +86,24 @@ internal sealed class IltChunkClap : IIltFeature
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false;
return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < Math.Max(1, G.ChunkAetheriaUnderLevel);
if (KeptForRatings(G, inv.Int(wo, IltInventory.IntGearCrit), inv.Int(wo, IltInventory.IntGearCritDamage),
inv.Int(wo, IltInventory.IntGearCritDamageResist)))
return false;
return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < ClampUnderLevel(G.ChunkAetheriaUnderLevel);
}
/// <summary>The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level).</summary>
internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1);
/// <summary>
/// True when an aetheria's C / CD / CDR rating is one the settings keep (any rating above 0 with
/// its keep switch on). Pure: the tests drive it.
/// </summary>
internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist)
=> (g.KeepAetheriaWithCrit && crit > 0)
|| (g.KeepAetheriaWithCritDamage && critDamage > 0)
|| (g.KeepAetheriaWithCritDamageResist && critDamageResist > 0);
private bool? IsChunkableCorrupted(WorldObject wo)
{
if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false;
@ -109,6 +133,7 @@ internal sealed class IltChunkClap : IIltFeature
RynthLog.Trace(LogCat.IltGear, $"ChunkNow()");
_manualPass = true;
_lastChunkAt = 0;
_skip.Clear(); // a manual pass gives the items that got no answer another try
_chunkStatus = "manual pass started";
}
@ -120,6 +145,7 @@ internal sealed class IltChunkClap : IIltFeature
{
if (now - _waitStartedAt < ChunkResultWaitMs) return;
_skip.Add(_waitingOn); // no result line — don't hammer the same item forever
RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)_waitingOn:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass");
_waitingOn = 0;
}
if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return;
@ -129,11 +155,12 @@ internal sealed class IltChunkClap : IIltFeature
if (_ctx.Inventory.IsBusy) return;
var hammer = FindHammer();
if (hammer == null) { _chunkStatus = "no Lugian Hammer carried"; _manualPass = false; return; }
if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; }
var target = NextChunkTarget();
if (target == null)
{
_chunkStatus = _chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible";
_chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible")
+ (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : "");
_manualPass = false;
return;
}
@ -216,23 +243,43 @@ internal sealed class IltChunkClap : IIltFeature
TickClap(nowMs);
}
internal enum ChunkResult { None, Busy, Done, Refused }
/// <summary>
/// What a chat line says about the chunk in flight. ILT names the item and the tool ("You
/// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted
/// item with the hammer, powder or shatter is a result too (combat's "You smash Foo for 147"
/// names neither). Pure: the tests drive it.
/// </summary>
internal static ChunkResult ClassifyChat(string text)
{
if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
return ChunkResult.Busy;
if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Refused;
if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Done;
if (text.Contains("corrupted", StringComparison.OrdinalIgnoreCase)
&& (text.Contains("hammer", StringComparison.OrdinalIgnoreCase) || text.Contains("powder", StringComparison.OrdinalIgnoreCase)
|| text.Contains("shatter", StringComparison.OrdinalIgnoreCase)))
return ChunkResult.Done;
return ChunkResult.None;
}
public bool OnChat(string text)
{
if (_waitingOn == 0) return false;
if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
switch (ClassifyChat(text))
{
_waitingOn = 0; // retry the same item next interval
return false;
}
if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_chunked++;
_waitingOn = 0;
}
else if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_skip.Add(_waitingOn);
_waitingOn = 0;
case ChunkResult.Busy:
_waitingOn = 0; // retry the same item next interval
break;
case ChunkResult.Done:
_chunked++;
_waitingOn = 0;
break;
case ChunkResult.Refused:
_skip.Add(_waitingOn);
_waitingOn = 0;
break;
}
return false;
}
@ -249,7 +296,7 @@ internal sealed class IltChunkClap : IIltFeature
public void Render()
{
ImGui.TextColored(IltStyle.ColTeal, "Chunking (Lugian Hammer)");
SafeImGui.TextColored(IltStyle.ColTeal, $"Chunking ({HammerName})");
bool a = G.AutoChunkAetheria, c = G.AutoChunkCorrupted, comb = G.ChunkInCombat;
if (ImGui.Checkbox("Auto-chunk low aetheria", ref a)) G.AutoChunkAetheria = a;
ImGui.SameLine();
@ -257,11 +304,24 @@ internal sealed class IltChunkClap : IIltFeature
if (ImGui.Checkbox("Allow while in combat mode", ref comb)) G.ChunkInCombat = comb;
int under = G.ChunkAetheriaUnderLevel;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = Math.Clamp(under, 1, 6);
if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = ClampUnderLevel(under);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.");
bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist;
ImGui.TextUnformatted("Never chunk aetheria with:");
ImGui.SameLine();
if (ImGui.Checkbox("C##keepc", ref kc)) G.KeepAetheriaWithCrit = kc;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit rating (GearCrit).");
ImGui.SameLine();
if (ImGui.Checkbox("CD##keepcd", ref kcd)) G.KeepAetheriaWithCritDamage = kcd;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage rating (GearCritDamage).");
ImGui.SameLine();
if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist).");
if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items",
"Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.",
ChunkNow, "Chunk");
ImGui.TextDisabled("Status: " + _chunkStatus);
SafeImGui.TextDisabled("Status: " + _chunkStatus);
ImGui.Separator();
ImGui.TextColored(IltStyle.ColTeal, "Clap (/clap all)");
@ -277,6 +337,6 @@ internal sealed class IltChunkClap : IIltFeature
if (ImGui.InputInt("Interval (min)", ref mins)) G.ClapIntervalMinutes = Math.Max(5, mins);
if (ImGui.SmallButton("Clap now")) _ctx.Post(() => ClapNow(manual: true));
ImGui.SameLine();
ImGui.TextDisabled(_clapStatus);
SafeImGui.TextDisabled(_clapStatus);
}
}

View file

@ -18,6 +18,7 @@ using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Install;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -238,7 +239,7 @@ internal sealed class IltEquipSuits : IIltFeature
var profiles = _profiles;
if (profiles.Length == 0)
{
ImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's EquipProfiles or UtilityBelt equip folders).");
SafeImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's EquipProfiles or UtilityBelt equip folders).");
}
else
{
@ -258,7 +259,7 @@ internal sealed class IltEquipSuits : IIltFeature
if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player"));
}
}
ImGui.TextDisabled("Status: " + _status);
foreach (string l in _preview) ImGui.BulletText(l);
SafeImGui.TextDisabled("Status: " + _status);
foreach (string l in _preview) SafeImGui.BulletText(l);
}
}

View file

@ -0,0 +1,273 @@
// IltFeatureCatalog.cs — Every Infinite Leaftide feature RynthILT supports, in one list.
//
// Each entry says what the feature is, where it lives in the Rynth tools, and how its state is
// known. Detection is client-side only: the server type comes from the login (the world name,
// RynthCore's "ilt" verdict), and the ILT profile below is the known set of what Infinite
// Leaftide runs, taken from ACECustom (its ServerConfig defaults and deploy/PROD_DEPLOY_PLAN.md,
// e.g. pet bond and potency on in prod, pet strain off since launch). The server is never asked
// for a list; what it returns on its own (probe replies, chat) refines the profile:
// * Profile (IltKnown.Profile): on in ILT (T11, split arrows, pet breeding, ...). On with the
// ILT world; a server refusal seen in chat turns it off.
// * Profile off (IltKnown.ProfileOff): an ACECustom option ILT runs with off (pet strain,
// defense scaling, the pyreal refill). Off with the ILT world; a chat line only the feature
// sends (e.g. a pyreal refill) turns it on.
// * Checked (IltKnown.Checked): the login probe answers it (/bank, /aug, /xp, /pets, ...).
// "checking" until the reply arrives, then on or off.
// * No server bit at all (the Temple guardians, Paragon gear): content, on with the ILT world.
// Off an ILT world nothing is claimed: every state is unknown.
// The list feeds the ILT settings window ("/ilt settings", IltSettingsView/) and "/ra hub features".
// Server facts copied from ACECustom: Fellowship.MaxFellows = 29 (Source/ACE.Server/Entity/
// Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One Leaftide feature: id, display text, where it lives, and the server bit that says whether it's on.</summary>
/// <param name="Key">Stable id.</param>
/// <param name="Label">Display name.</param>
/// <param name="Group">Character, Items, Fellowship or Activities (the list's sections).</param>
/// <param name="Where">Where the Rynth tools handle it.</param>
/// <param name="Description">One line on what the server does.</param>
/// <param name="ServerBit">The IltServerOptions key probes and chat refusals set; null = content built into ACECustom (on with the world).</param>
/// <param name="Known">How the state is known while the bit hasn't been set (see <see cref="IltKnown"/>).</param>
internal sealed record IltFeatureInfo(string Key, string Label, string Group, string Where, string Description, string? ServerBit,
IltKnown Known = IltKnown.Profile);
/// <summary>How a feature's state is known on an ILT world before (or without) a server answer.</summary>
internal enum IltKnown
{
/// <summary>On in ILT: on with the ILT world unless chat shows it off.</summary>
Profile,
/// <summary>The login probe answers it: "checking" until the reply arrives.</summary>
Checked,
/// <summary>Off in ILT: off with the ILT world unless chat shows it on.</summary>
ProfileOff,
}
internal static class IltFeatureCatalog
{
public const string GroupCharacter = "Character";
public const string GroupItems = "Items";
public const string GroupPets = "Pets";
public const string GroupFellowship = "Fellowship";
public const string GroupCombat = "Combat";
public const string GroupActivities = "Activities";
/// <summary>The section order of the list (ACECustom's "/ilt features" uses the same).</summary>
public static readonly string[] Groups = { GroupCharacter, GroupItems, GroupPets, GroupFellowship, GroupCombat, GroupActivities };
/// <summary>ACECustom's fellowship member limit (Fellowship.MaxFellows); retail is 9.</summary>
public const int IltFellowshipMax = 29;
/// <summary>A retail fellowship's member limit.</summary>
public const int RetailFellowshipMax = 9;
/// <summary>Every Leaftide feature RynthILT supports, in display order.</summary>
public static readonly IltFeatureInfo[] All =
{
// Character progression and money.
new("bank", "Banking", GroupCharacter, "Mini Remote > Banking tab; Remote tab bank line",
"Bank pyreals, luminance, keys and coins; deposit, withdraw and transfer (/bank).", IltFeature.Bank, IltKnown.Checked),
new("bank_notes", "Trade note banking", GroupCharacter, "Mini Remote > Banking tab (trade notes)",
"Deposit trade notes as pyreals, withdraw any note from I to MMD, transfer note value (/bank d n).", "bank_notes"),
new("guardian", "Guardian (infinite base attributes)", GroupCharacter, "Guardian panel (/rc guardian)",
"Temple of Enlightenment guardians raise base attributes past the retail cap.", null),
new("attributes", "Infinite raised attributes", GroupCharacter, "Skills > Progression > Attributes",
"Spend unassigned XP on attributes past the retail max (/xp, /attr).", IltFeature.Xp, IltKnown.Checked),
new("augmentations", "Infinite augmentations", GroupCharacter, "Skills > Progression > Augmentations",
"Luminance augmentations far past retail: Creature 6000, Item / Life / War / Void 4000 (/aug).", IltFeature.Aug, IltKnown.Checked),
new("aug_charms", "Augmentation counter charms", GroupCharacter, "Skills > Progression > Augmentations",
"Triune Weave and the school charms add to your aug counts past the purchase cap (/aug).", "aug_charms"),
new("enlightenment", "Enlightenment", GroupCharacter, "Skills > Progression > Enlightenment",
"Enlightenment tiers past retail, with medallions, sigils and crests (/enl).", IltFeature.Enl, IltKnown.Checked),
new("ilt_skills", "Spend XP and train skills in one go", GroupCharacter, "Chat: /ilt xp, /ilt train",
"Spends all unspent XP into trained skills, or trains every affordable skill, in priority order.", "ilt_skills"),
new("leaderboards", "Leaderboards", GroupCharacter, "Chat: /top",
"Server leaderboards: quest bonus, level, enlightenment, augs, bank, pets and more (/top).", "leaderboards"),
// Items, loot and crafting.
new("paragon_armor", "Paragon armor", GroupItems, "Item info (RynthAi): Paragon sets and levels",
"Paragon armor progression; the 50th Armor Paragon gates enlightenment past 300.", null),
new("paragon_weapons", "Paragon weapons", GroupItems, "Item info (RynthAi): Paragon sets and levels",
"Paragon weapon progression (Paragon Missile, Caster and Melee sets).", null),
new("paragon_jewelry", "Paragon jewelry", GroupItems, "Item info (RynthAi): Paragon sets and levels",
"Paragon jewelry progression; the 50th Paragon gates enlightenment past 150.", null),
new("t11", "T11 items", GroupItems, "Item info and loot rules (RynthAi, RynthCore Loot Editor)",
"Tier 11 to 25 gear (Zone Control tiers): tiers, gear grades, property slots and modifiers.", "t11"),
new("t11_scaling", "T11+ weapon scaling", GroupItems, "Item info (RynthAi)",
"T11+ weapons scale with your augs and have aug wield floors; from T16, charm counts too.", "t11_scaling"),
new("t11_craft_gate", "T11+ crafting rules (crafting uniqueness)", GroupItems, "Mini Remote > Gear tab",
"On T11+ items the server refuses an imbue or tink that would replace a better value, and limits materials per item type.",
"t11_craft_gate"),
new("split_arrows", "Split arrows", GroupItems, "Mini Remote > Gear > Split arrows",
"Missile weapons carry split arrows, added with White Quartz salvage.", "split_arrows"),
new("charms", "Charms", GroupItems, "Mini Remote > Charms tab",
"Registry charms and the Guardian Hand, with their toggles; each charm is listed in the Charms section.", "charms"),
new("clap", "Chunk clap (auto craft)", GroupItems, "Mini Remote > Gear tab",
"Turns aetheria, chunks and trinkets into banked enlightened coins (/clap all).", IltFeature.Clap, IltKnown.Checked),
// Pets.
new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked),
new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked),
new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab",
"Siphon lenses capture a creature's look into a pet essence (lens drops from kills are a separate server switch).", "monster_capture"),
new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding",
"Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"),
new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding",
"Bred pets start small and weak and grow up with kills.", "pet_maturity"),
new("pet_bond", "Pet bond", GroupPets, "Mini Remote > Pets tab",
"Pets gain bond XP from kills, which scales their stats (/top bonds). On in ILT (breeding needs bond 100).", IltFeature.PetBond),
new("pet_potency", "Pet potency", GroupPets, "Mini Remote > Pets tab",
"Savage Echo residue raises a pet's potency (/echo-notify). On in ILT.", IltFeature.PetPotency),
new("pet_strain", "Pet strain", GroupPets, "Mini Remote > Pets tab",
"High pet potency lowers the owner's damage rating. Off in ILT since launch.", "pet_strain", IltKnown.ProfileOff),
new("pet_refill", "Summon essence refill", GroupPets, "Mini Remote > Pets tab",
"Pays pyreals to refill an empty essence when you summon (needs its charm). Off by default; a refill message in chat shows it on.", IltFeature.PetRefill, IltKnown.ProfileOff),
new("universal_mastery", "Universal summoning mastery", GroupPets, "Mini Remote > Pets tab",
"Use pet essences of any summoning mastery (needs its charm).", IltFeature.UniversalMastery),
new("pet_naming", "Pet names", GroupPets, "Chat: /pet-name",
"Ask for a name for your pet; staff approve it (/pet-name).", "pet_naming"),
// Fellowship.
new("fellowship_large", "Large fellowships (up to 29)", GroupFellowship, "The game's fellowship panel",
"Fellowships hold up to 29 members instead of retail's 9.", "fellowship_size"),
new("fship", "Fellowship commands", GroupFellowship, "ILT fellowship window (/ilt fellow)",
"Create, invite, invite your landblock, list nearby, leave and disband from chat (/fship).", "fship"),
new("zone_share", "Zone Share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)",
"XP and luminance shared with everyone in a Zone Share area, capped at a fellowship's size.", "zone_share"),
new("fellowship_luminance", "Fellowship luminance share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)",
"Luminance splits among fellows the way XP does.", "fellowship_luminance"),
new("fellowship_blackjack", "Fellowship Blackjack", GroupFellowship, "Mini Remote > Games tab",
"Blackjack played as a fellowship (/fblackjack).", IltFeature.FBlackjack, IltKnown.Checked),
// Combat.
new("smart_ring", "Smart ring spells", GroupCombat, "Chat: /ilt smartring",
"Ring spells hit everything in their radius, with double and triple procs (/ilt smartring on|off).", "smart_ring"),
new("dmgformat", "Damage number format", GroupCombat, "Chat: /ilt dmgformat",
"Damage shown plain, with commas, or short (K/M/B) (/ilt dmgformat).", "dmgformat"),
new("overkill", "Overkill on kill messages", GroupCombat, "Chat: /ilt showoverkill",
"Kill and death messages show the overkill amount (/ilt showoverkill).", "overkill"),
new("missile_power", "Missile power bar damage", GroupCombat, "Combat",
"The missile accuracy bar scales damage from 1x to 2.5x.", "missile_power"),
new("t11_hit_gate", "T11+ hit gate", GroupCombat, "Combat",
"Attacks on v11+ monsters miss unless your aug counts meet that tier's requirement.", "t11_hit_gate"),
new("v11_endgame", "v11+ endgame scaling", GroupCombat, "Combat",
"Percent-of-max-HP damage, compressed vulnerabilities and tougher v11+ monsters.", "v11_endgame"),
new("defense_scaling", "Defense scaling", GroupCombat, "Combat",
"Curbs extreme evasion at very high defense skill. Off by default in ACECustom.", "defense_scaling", IltKnown.ProfileOff),
// Activities.
new("quests", "Quest tracker", GroupActivities, "Mini Remote > Quests tab",
"Your quest timers from the server (/myquests).", IltFeature.Quests, IltKnown.Checked),
new("quest_bonus", "Quest bonus", GroupActivities, "Mini Remote > Quests tab (quest bonus)",
"Each quest completed adds to your XP bonus; the list (/qb).", IltFeature.Qb, IltKnown.Checked),
new("bounties", "Bounties", GroupActivities, "Bounties window (/rc bounties)", "ACECustom bounties and your progress.", "bounties"),
new("rifts", "Greater Rifts", GroupActivities, "Chat: /rift", "Private, timed dungeon runs that scale by tier (/rift).", "rifts"),
new("room_assign", "Room Assign dungeons", GroupActivities, "Portals and recalls",
"One-player rooms with their own spawns.", "room_assign"),
new("portal_requirements", "Aug / ENL / QB portals", GroupActivities, "Portals",
"Portals that need augmentations, an enlightenment level or a quest bonus.", "portal_requirements"),
new("powerball", "Powerball", GroupActivities, "Mini Remote > Games tab", "The Powerball lottery (/pb).", IltFeature.Powerball, IltKnown.Checked),
new("blackjack", "Blackjack", GroupActivities, "Mini Remote > Games tab", "Blackjack against the house (/blackjack).", IltFeature.Blackjack, IltKnown.Checked),
new("unstuck", "Unstuck", GroupActivities, "Chat: /unstuck", "Gets you out of a stuck portal or spot (/unstuck).", "unstuck"),
};
/// <summary>The entry with <paramref name="key"/>, or null.</summary>
public static IltFeatureInfo? Find(string key)
{
foreach (IltFeatureInfo f in All)
if (f.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return f;
return null;
}
/// <summary>
/// A feature's state on an ILT world: what the server returned (a probe reply or a refusal in
/// chat) when it did; else the ILT profile: On for content and <see cref="IltKnown.Profile"/>,
/// Off for <see cref="IltKnown.ProfileOff"/>, Unknown ("checking") for probed features.
/// Off ILT nothing is claimed: Unknown.
/// </summary>
public static IltTri StateOf(IltFeatureInfo f, bool iltWorld, Func<string, IltTri> bit)
{
if (!iltWorld) return IltTri.Unknown;
if (f.ServerBit == null) return IltTri.On;
IltTri reported = bit(f.ServerBit);
if (reported != IltTri.Unknown) return reported;
return f.Known switch
{
IltKnown.Profile => IltTri.On,
IltKnown.ProfileOff => IltTri.Off,
_ => IltTri.Unknown,
};
}
/// <summary>
/// A charm's state: charms are part of the ILT profile, so on with the ILT world unless the
/// server refused one in chat (e.g. "Auto-Rebuff Charm is currently disabled globally").
/// </summary>
public static IltTri CharmStateOf(bool iltWorld, IltTri reported)
=> !iltWorld ? IltTri.Unknown : reported != IltTri.Unknown ? reported : IltTri.On;
/// <summary>Prefix of a charm's server key (IltFeature.Charm): "charm:manabarrier".</summary>
public const string CharmKeyPrefix = "charm:";
/// <summary>
/// Display text for a key the settings view lists: a catalog feature (its label, group and
/// description with where it lives and how its state is known), a charm ("charm:..." under
/// Charms, named from the charm registry), or any other server bit as itself under "Other".
/// </summary>
public static (string Label, string Group, string Tooltip) Describe(string key)
{
IltFeatureInfo? f = Find(key);
if (f != null) return (f.Label, f.Group, f.Description + "\nWhere: " + f.Where + "\n" + HowKnown(f));
if (key.StartsWith(CharmKeyPrefix, StringComparison.OrdinalIgnoreCase))
{
const string charmNote = "Part of ILT: on unless the server refuses it in chat.";
foreach (IltCharmDef def in IltInventory.Charms)
if (IltFeature.Charm(def.Name).Equals(key, StringComparison.OrdinalIgnoreCase))
return (def.Name, GroupCharms, (def.Effect.Length > 0 ? def.Effect + "\n" : string.Empty)
+ "Where: Mini Remote > Charms tab\n" + charmNote);
return (key.Substring(CharmKeyPrefix.Length), GroupCharms, charmNote);
}
return (key, GroupOther, "A server switch RynthILT reads from chat.");
}
/// <summary>One line on where a feature's state comes from (tooltips).</summary>
private static string HowKnown(IltFeatureInfo f) => f.ServerBit == null
? "Built into ILT: on with the world."
: f.Known switch
{
IltKnown.Checked => "Checked at login: the server's reply decides.",
IltKnown.ProfileOff => "Off in ILT: on only if the server shows it in chat.",
_ => "Part of ILT: on unless the server refuses it in chat.",
};
/// <summary>The settings view's extra sections after <see cref="Groups"/>.</summary>
public const string GroupCharms = "Charms";
public const string GroupOther = "Other";
/// <summary>Short state text for the list and chat: "on", "off" or "checking".</summary>
public static string StateText(IltTri state) => state switch
{
IltTri.On => "on",
IltTri.Off => "off",
_ => "checking",
};
/// <summary>The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere.</summary>
public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax;
/// <summary>The chat listing for "/ra hub features": one line per feature, ASCII only.</summary>
public static List<string> BuildChatLines(bool iltWorld, Func<string, IltTri> bit)
{
var lines = new List<string>(All.Length + Groups.Length);
foreach (string g in Groups)
{
var parts = new List<string>();
foreach (IltFeatureInfo f in All)
if (f.Group == g) parts.Add($"{f.Label} [{StateText(StateOf(f, iltWorld, bit))}]");
lines.Add($"{g}: {string.Join(", ", parts)}");
}
return lines;
}
}

View file

@ -12,6 +12,7 @@ using System.Collections.Generic;
using System.Numerics;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -179,7 +180,7 @@ internal sealed class IltGames : IIltFeature
ImGui.InputTextWithHint($"Bet (luminance)##{id}", "e.g. 1m, 500k", ref betText, 24u);
bool ok = IltParse.TryParseAmount(betText, out long bet) && (!fellowship || bet <= FBlackjackMaxBet);
ImGui.SameLine();
ImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid");
SafeImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid");
ImGui.BeginDisabled(!ok || _handActive);
if (ImGui.Button($"Deal...##{id}"))
@ -192,7 +193,7 @@ internal sealed class IltGames : IIltFeature
ImGui.EndDisabled();
if (_handActive && _fellowshipHand == fellowship) RenderHandButtons(id);
if (_lastResult.Length > 0 && _fellowshipHand == fellowship) ImGui.TextWrapped(_lastResult);
if (_lastResult.Length > 0 && _fellowshipHand == fellowship) SafeImGui.TextWrapped(_lastResult);
}
private void RenderHandButtons(string id)
@ -221,7 +222,7 @@ internal sealed class IltGames : IIltFeature
if (!_ctx.Options.IsOn(IltFeature.Powerball))
{
ImGui.TextDisabled("Ticket purchases unlock once the server confirms /pb (press Refresh).");
if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus);
if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus);
return;
}
int qty = S.PowerballQuantity;
@ -234,7 +235,7 @@ internal sealed class IltGames : IIltFeature
_ctx.Confirm("Powerball", $"Buy {q} Powerball ticket(s)?\n{(_pbPrice.Length > 0 ? _pbPrice : "Tickets cost banked luminance.")}",
() => Send($"/pb buy {q}"), "Buy");
}
if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus);
if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus);
}
/// <summary>Small HUD with the current hand; called every frame by the Hub UI.</summary>
@ -245,7 +246,7 @@ internal sealed class IltGames : IIltFeature
bool open = true;
if (ImGui.Begin("Blackjack HUD##iltbjhud", ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse))
{
ImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
SafeImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
RenderHandButtons("hud");
}
ImGui.End();

View file

@ -4,7 +4,8 @@
// The sections are separate modules (buff keepers, chunk/clap, split arrows, equipment suits)
// that this tab just lays out, plus RynthAi's VTank .usd importer (it edits RynthAi's own rules,
// so it stayed in RynthAi and is drawn here through RynthAi.Hub RenderSection). The charm strip (registry charms and the Guardian
// Hand, with their toggles) is the Charms tab now (IltCharms).
// Hand, with their toggles) is the Charms tab now (IltCharms). The Rings inscription chain
// (IltRingChainRunner) is SilentKelpie's RynthAi Crafting > Rings, moved here 2026-10-15.
using ImGuiNET;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -15,6 +16,7 @@ internal sealed class IltGear : IIltFeature
public IltChunkClap ChunkClap { get; }
public IltSplitArrows Split { get; }
public IltEquipSuits Suits { get; }
public IltRingChainRunner Rings { get; }
private readonly IltHubContext _ctx;
@ -24,6 +26,9 @@ internal sealed class IltGear : IIltFeature
ChunkClap = new IltChunkClap(ctx);
Split = new IltSplitArrows(ctx);
Suits = new IltEquipSuits(ctx);
// The two pack jobs that answer craft dialogs never run together.
Rings = new IltRingChainRunner(ctx, () => Split.Running);
Split.Blocked = () => Rings.Running;
_ctx = ctx;
}
@ -35,6 +40,7 @@ internal sealed class IltGear : IIltFeature
ChunkClap.Tick(nowMs);
Split.Tick(nowMs);
Suits.Tick(nowMs);
Rings.Tick(nowMs);
}
public bool OnChat(string text)
@ -43,6 +49,7 @@ internal sealed class IltGear : IIltFeature
eat |= ChunkClap.OnChat(text);
eat |= Split.OnChat(text);
eat |= Suits.OnChat(text);
eat |= Rings.OnChat(text);
return eat;
}
@ -52,6 +59,7 @@ internal sealed class IltGear : IIltFeature
ChunkClap.OnLogout();
Split.OnLogout();
Suits.OnLogout();
Rings.OnLogout();
}
// ── UI (render thread) ──────────────────────────────────────────────────
@ -62,6 +70,7 @@ internal sealed class IltGear : IIltFeature
if (ImGui.CollapsingHeader("Chunking / Clap")) ChunkClap.Render();
if (ImGui.CollapsingHeader("Split arrows")) Split.Render();
if (ImGui.CollapsingHeader("Equipment suits")) Suits.Render();
if (ImGui.CollapsingHeader("Rings (inscription chain)")) Rings.Render();
if (ImGui.CollapsingHeader("VirindiTank import") && !_ctx.Ai.RenderSection(RynthCore.Plugin.Shared.RynthAiHub.SectionVTankImport))
ImGui.TextDisabled("The VirindiTank .usd import fills RynthAi's rules: it comes with RynthAi, which isn't loaded.");
ImGui.TextDisabled("Charms and the Guardian Hand are on the Charms tab.");

View file

@ -465,16 +465,16 @@ internal sealed class IltGuardian : IIltFeature
ImGui.TextDisabled("Heard:");
ImGui.SameLine();
ImGui.PushTextWrapPos(0f);
ImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
SafeImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
ImGui.PopTextWrapPos();
}
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length > 0)
{
ImGui.TextColored(IltStyle.ColTeal, answer);
SafeImGui.TextColored(IltStyle.ColTeal, answer);
ImGui.SameLine();
ImGui.TextDisabled("-> " + npc);
SafeImGui.TextDisabled("-> " + npc);
if (HandInRunning)
{
if (ImGui.SmallButton("Stop##grdstop")) _ctx.Post(() => StopHandIn());
@ -485,7 +485,7 @@ internal sealed class IltGuardian : IIltFeature
}
}
else ImGui.TextDisabled("No guardian answer yet.");
ImGui.TextDisabled("Hand-in: " + _handInStatus);
SafeImGui.TextDisabled("Hand-in: " + _handInStatus);
ImGui.Spacing();
ImGui.InputTextMultiline("##grdinput", ref _input, 2048u, new Vector2(-1, 54));
@ -506,7 +506,7 @@ internal sealed class IltGuardian : IIltFeature
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-read /myquests and /qb list (the server allows each once a minute).");
ImGui.SameLine();
DateTime synced = Attributes.SyncedUtc;
ImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}");
SafeImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset counts##grdreset"))
_ctx.Confirm("Reset turn-in counts", "Forget the turn-in counts and cooldown estimates taken from /qb wait stamps? (/myquests counts are not affected.)",
@ -531,9 +531,9 @@ internal sealed class IltGuardian : IIltFeature
var col = r.Ready ? IltStyle.ColGreen
: r.Status == "Unknown" ? IltStyle.ColTextMute
: IltStyle.ColAmber;
ImGui.TextColored(col, r.Status);
SafeImGui.TextColored(col, r.Status);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates).");
SafeImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates).");
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Eta);
}
ImGui.EndTable();
@ -555,8 +555,8 @@ internal sealed class IltGuardian : IIltFeature
if (answer.Length == 0 || LastAnswerAge > AnswerShownFor) return;
ImGui.TextColored(IltStyle.ColTextMute, "Guardian:");
ImGui.SameLine();
ImGui.TextColored(IltStyle.ColTeal, answer);
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}");
SafeImGui.TextColored(IltStyle.ColTeal, answer);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}");
ImGui.SameLine();
if (HandInRunning)
{

View file

@ -35,12 +35,26 @@ internal sealed class IltHubController
private bool _availabilityAnnounced; // "open the Mini Remote" hint printed this session
private volatile int _forceRequest = -1; // SetForceIlt from another thread, applied on the next tick
// "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the charms and bank snapshots, rebuilt on
// the pump every DataRebuildMs only while a reader has asked within DataWatchMs.
private const long DataRebuildMs = 2000;
private const long DataWatchMs = 6000;
/// <summary>How often the other characters' saved balances are re-read for the bank export.</summary>
private const long SiblingReadMs = 15_000;
private long _charmsReadAt, _bankReadAt; // set by readers (any thread, Interlocked)
private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt;
private volatile string _charmsJson = string.Empty;
private volatile string _bankJson = string.Empty;
private List<IltBankExport.Row> _siblings = new();
public IltBanking Banking { get; }
public IltSessionRates Rates { get; }
/// <summary>The quest bonus list (/qb): the Quests tab's section and the Temple tracker's stamps.</summary>
public IltQuestBonus QuestBonus { get; }
/// <summary>The /pets and /shinies logs (the Pets tab's section).</summary>
public IltPetLogs PetLogs { get; }
/// <summary>The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON).</summary>
public IltPetBreeding Breeding { get; }
public IltProgression Progression { get; }
public IltGear Gear { get; }
public IltGames Games { get; }
@ -69,6 +83,7 @@ internal sealed class IltHubController
Banking = new IltBanking(_ctx);
PetLogs = new IltPetLogs(_ctx);
Breeding = new IltPetBreeding(_ctx);
Rates = new IltSessionRates(_ctx);
QuestBonus = new IltQuestBonus(_ctx);
Progression = new IltProgression(_ctx);
@ -77,7 +92,7 @@ internal sealed class IltHubController
Charms = new IltCharmTracker(_ctx);
CharmsTab = new IltCharms(_ctx, Charms);
Guardian = new IltGuardian(_ctx, QuestBonus);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian });
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian });
Banking.BalanceChanged += Rates.OnBankBalanceChanged;
Rates.MovingMoney = () => Banking.MovingMoney;
@ -86,6 +101,81 @@ internal sealed class IltHubController
_ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show");
}
/// <summary>
/// The charms JSON ("RynthILT.Data" GetCharmsJson). Reading it marks the charms as watched, so
/// the pump keeps the snapshot fresh while a reader is showing it; "" until the first rebuild
/// after that. Any thread.
/// </summary>
public string CharmsJson
{
get { System.Threading.Interlocked.Exchange(ref _charmsReadAt, IltHubContext.NowMs); return _charmsJson; }
}
/// <summary>The bank JSON ("RynthILT.Data" GetBankJson), as <see cref="CharmsJson"/>.</summary>
public string BankJson
{
get { System.Threading.Interlocked.Exchange(ref _bankReadAt, IltHubContext.NowMs); return _bankJson; }
}
/// <summary>A reader's charm Toggle, posted to the pump (IltCharms checks the id). Any thread.</summary>
public void RequestCharmToggle(uint objectId)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
if (!CharmsTab.ToggleFromReader(objectId))
RynthLog.Trace(LogCat.IltGear, $"reader toggle refused: 0x{objectId:X8} isn't a carried charm");
_charmsBuiltAt = 0; // show the new state on the next tick
});
/// <summary>
/// The pet breeding JSON ("RynthILT.Data" GetPetBreedingJson).
/// Reading it keeps the tracker scanning; "" off an ILT world or before its first scan. Any thread.
/// </summary>
public string PetBreedingJson => _ctx.Options.IsIltLikeWorld ? Breeding.ReaderJson : string.Empty;
/// <summary>A reader's breeding verb line, posted to the pump (IltPetBreeding.RunVerb). Any thread.</summary>
public void RequestBreedingVerb(string line)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
Breeding.RunVerb(line);
});
/// <summary>A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread.</summary>
public void RequestBankVerb(string line)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
Banking.RunVerb(line);
_bankBuiltAt = 0;
});
/// <summary>Pump: rebuilds the charms / bank snapshots a reader is watching.</summary>
private void RebuildReaderData(long now)
{
if (now - System.Threading.Interlocked.Read(ref _charmsReadAt) < DataWatchMs && now - _charmsBuiltAt >= DataRebuildMs)
{
_charmsBuiltAt = now;
_charmsJson = CharmsTab.BuildReaderJson();
}
bool bankWatched = now - System.Threading.Interlocked.Read(ref _bankReadAt) < DataWatchMs;
Banking.ReaderWatching = bankWatched;
if (!bankWatched || now - _bankBuiltAt < DataRebuildMs) return;
_bankBuiltAt = now;
if (_siblingsReadAt == 0 || now - _siblingsReadAt >= SiblingReadMs)
{
_siblingsReadAt = now;
_siblings = IltBankExport.ReadSiblings(_ctx.Store.CharFolder);
}
IltServerOptions o = _ctx.Options;
string me = _ctx.CharName.Length > 0 ? _ctx.CharName : System.IO.Path.GetFileName(_ctx.Store.CharFolder.TrimEnd('\\', '/'));
var rows = new List<IltBankExport.Row>(_siblings.Count + 1) { new(me, true, _ctx.State.Bank) };
rows.AddRange(_siblings);
int enabled = o.IsOn(IltFeature.Bank) ? 1 : o.IsOff(IltFeature.Bank) ? 0 : -1;
_bankJson = IltBankExport.Build(o.IsIltLikeWorld, enabled, o.WorldName, me, rows, Banking.LatestResult, Banking.Transactions);
}
public IltHubState State => _ctx.State;
public IltServerOptions Options => _ctx.Options;
internal IltHubContext Context => _ctx;
@ -94,8 +184,8 @@ internal sealed class IltHubController
public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
/// <summary>
/// Whether a section can be shown now. Character always can (it explains why the ILT tabs are
/// idle and holds the Force-ILT override); the rest need server features.
/// Whether a section can be shown now: the ILT tabs and the Guardian need server features.
/// Character (moved to RynthOracle) always answers true so its redirect is never refused.
/// </summary>
public bool SectionAvailable(IltSection section) => section switch
{
@ -107,7 +197,7 @@ internal sealed class IltHubController
/// <summary>
/// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT
/// override). The Character tab then always shows; the others follow <see cref="SectionAvailable"/>.
/// override from RynthCore Options > Diagnostics). The tabs then follow <see cref="SectionAvailable"/>.
/// </summary>
public bool OffersTabs => _ctx.Options.IsIltLikeWorld;
@ -117,6 +207,15 @@ internal sealed class IltHubController
/// <summary>Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar).</summary>
public void RenderTab(IltSection section) => _ui.RenderTab(section);
/// <summary>
/// Render thread: the ILT session extras (coins, pyreals, item conversions) in RynthCore's Mini
/// Remote "Session Stats" section, below RynthAi's session stats (surface "section:ilt-rates").
/// </summary>
public void RenderRatesSection() => _ui.RenderRatesSection();
/// <summary>Render thread: the /qb list in RynthILT's own Quests section (surface "section:ilt-questbonus").</summary>
public void RenderQuestBonusSection() => _ui.RenderQuestBonusSection();
/// <summary>Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian").</summary>
public void RenderGuardianPanel() => _ui.RenderGuardianPanel();
@ -180,6 +279,10 @@ internal sealed class IltHubController
_ctx.Options.Tick();
PollQuestOutcome();
// The charms / bank snapshots other plugins read (RynthILT.Data), only while watched.
try { RebuildReaderData(now); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildReaderData"); }
// "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans.
_ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible;
@ -237,7 +340,7 @@ internal sealed class IltHubController
private static LogCat CategoryOf(IIltFeature f) => f switch
{
IltBanking => LogCat.IltBanking,
IltPetLogs => LogCat.IltPets,
IltPetLogs or IltPetBreeding => LogCat.IltPets,
IltSessionRates => LogCat.IltRates,
IltQuestBonus => LogCat.IltQuests,
IltProgression => LogCat.IltProgression,
@ -353,24 +456,31 @@ internal sealed class IltHubController
{
// Quests and Pets are RynthAi's tabs: not ours to open.
if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false;
_ctx.Chat("[Mini Remote] Usage: /ra hub open character|quests|pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle]");
_ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)");
break;
}
OpenSection(section, args.Length > 2 ? args[2] : "toggle");
break;
case "tab":
// The engine's dashboard: it opens its Mini Remote window itself, so only switch tabs.
if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.IsTab(tab))
if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.MovedCommand(tab) is string moved)
OpenMoved(tab, moved);
else if (args.Length > 1 && IltSections.TryParse(args[1], out tab) && IltSections.IsTab(tab))
_ctx.Ai.MiniRemoteTab(IltSections.TabId(tab), "select");
else
return false; // the Remote tab or a RynthAi tab: RynthAi's
break;
case "refresh": _ctx.Options.Refresh(manual: true); break;
case "bank": Banking.RequestRefresh(quiet: false); break;
// "/ilt qb": reads the /qb list again (the Quests tab's quest bonus section).
case "qb": _ctx.Chat("[RynthILT] " + QuestBonus.RefreshQb()); break;
case "status": PrintStatus(); break;
case "features": PrintFeatures(); break;
case "force":
_ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
_ctx.Chat($"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server.");
_ctx.Chat(IltServerOptions.EngineDecides
? $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")} for this character (RynthCore counts it unless /rc server ilt off). Use /ra hub refresh to re-check the server."
: $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server.");
break;
case "servers": HandleServers(rest); break;
case "profile": HandleProfile(args.Skip(1).ToArray()); break;
@ -383,11 +493,11 @@ internal sealed class IltHubController
ClearPending();
break;
default:
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|force on|off|servers [list]|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open character|quests|pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs)");
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)");
_ctx.Chat("[Mini Remote] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (Skills panel > Progression)");
_ctx.Chat("[Mini Remote] /ra quests [refresh|check <regex>|window [show|hide]|favhud [show|hide]] /ra pets [show|hide]");
_ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)");
_ctx.Chat("[Mini Remote] /ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status] (window: ILT button > Guardian)");
_ctx.Chat("[Mini Remote] /ra bounty [show|hide|toggle] (RynthCore's ILT button > Bounties, /rc bounties)");
_ctx.Chat("[Mini Remote] The ILT verbs also work as /ilt hub ..., /ilt guardian ... (RynthILT).");
@ -396,6 +506,17 @@ internal sealed class IltHubController
return true;
}
/// <summary>"/ra hub features": every Leaftide feature RynthILT supports, with the server's state for each.</summary>
private void PrintFeatures()
{
IltServerOptions o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
_ctx.Chat($"[Mini Remote] Leaftide features on {world} ({(o.IsIltLikeWorld ? "ILT world" : "not an ILT world")}, "
+ $"fellowships up to {IltFeatureCatalog.FellowshipMax(o.IsIltLikeWorld)}):");
foreach (string line in IltFeatureCatalog.BuildChatLines(o.IsIltLikeWorld, o.Get))
_ctx.Chat("[Mini Remote] " + line);
}
/// <summary>"/ra hub servers [list | &lt;names, comma separated&gt; | default]": which world names count as Infinite Leaftide.</summary>
private void HandleServers(string rest)
{
@ -448,6 +569,12 @@ internal sealed class IltHubController
/// </summary>
private void OpenSection(IltSection section, string mode)
{
if (IltSections.MovedCommand(section) is string moved)
{
// Character left the Mini Remote: open its new home instead.
if (!mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) OpenMoved(section, moved);
return;
}
if (!IltSections.IsTab(section))
{
OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode);
@ -459,6 +586,19 @@ internal sealed class IltHubController
_ctx.Chat("[Mini Remote] " + reply);
}
/// <summary>
/// Opens the new home of a section that moved out of the Mini Remote (RynthOracle's Character
/// tab) by running its chat command, or says where it is when the command can't run (an older
/// RynthCore, or RynthOracle not loaded). Pump thread.
/// </summary>
public void OpenMoved(IltSection section, string command)
{
if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(command))
return;
_ctx.Chat($"[Mini Remote] {IltSections.Label(section)} moved to RynthOracle's Character tab ({command}); "
+ "the ILT session rates are in the Mini Remote's Session Stats.");
}
/// <summary>
/// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]")
/// through the engine's chat dispatcher. Pump thread.

View file

@ -53,7 +53,7 @@ public sealed class IltHubState
public sealed class IltServerOptionsSnapshot
{
public string WorldName = string.Empty;
/// <summary>"ilt-features" (structured dump), "probe" (command probing) or "" (never refreshed).</summary>
/// <summary>"probe" (the login probe) or "" (never refreshed).</summary>
public string Source = string.Empty;
public DateTime LastRefreshUtc = DateTime.MinValue;
/// <summary>Feature key → -1 unknown, 0 off, 1 on.</summary>
@ -77,6 +77,8 @@ public sealed class IltBankState
/// <summary>Last transfer recipient typed into the transfer form.</summary>
public string TransferTarget = string.Empty;
public int TransferCurrencyIndex;
/// <summary>Transfer form's trade-note denomination (IltBankCommands.NoteDenominations; 9 = MMD).</summary>
public int TransferNoteIndex = 9;
/// <summary>Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations).</summary>
public int DepositIndex;
@ -106,6 +108,8 @@ public sealed class IltPetState
/// <summary>Last captured /pets and /shinies rosters (display only; the Pets tab's logs).</summary>
public List<string> PetLog = new();
public List<string> ShinyLog = new();
/// <summary>The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding).</summary>
public IltBreedingState Breeding = new();
// The Pets tab's own settings (roster, healing / cosmetic pets, refill path) are RynthAi's
// (its miniremote.json); older ilt-hub.json files still carry them, and they are ignored here.
}
@ -199,8 +203,17 @@ public sealed class IltGearState
public bool AutoChunkCorrupted;
public bool ChunkInCombat;
public int ChunkIntervalMs = 2000;
/// <summary>Only chunk aetheria whose max level is below this (Coalesced always chunks).</summary>
/// <summary>
/// Only chunk aetheria whose max level is below this (Coalesced always chunks). Infinite Leaftide
/// aetheria goes up to level <see cref="IltInventory.AetheriaMaxLevel"/>, so the cap runs to one past it.
/// </summary>
public int ChunkAetheriaUnderLevel = 4;
/// <summary>Never chunk aetheria carrying a Crit rating (C, GearCrit 372; ILT tier-10 sigils of level 6+).</summary>
public bool KeepAetheriaWithCrit = true;
/// <summary>Never chunk aetheria carrying a Crit Damage rating (CD, GearCritDamage 374).</summary>
public bool KeepAetheriaWithCritDamage = true;
/// <summary>Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375).</summary>
public bool KeepAetheriaWithCritDamageResist = true;
// Auto-clap (/clap all)
public bool AutoClap;
@ -216,6 +229,14 @@ public sealed class IltGearState
// Equipment profiles (.utl suits). (The VTank .usd import path is RynthAi's: the importer stayed there.)
public string LastEquipProfile = string.Empty;
// Rings inscription chain (IltRingChainRunner; SilentKelpie's, moved from RynthAi's Crafting tab)
/// <summary>Recipe id (IltRingChain.Recipes) to how many times to craft it. Pump thread only.</summary>
public Dictionary<string, int> RingRuns = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Answer the server's craft dialog Yes for the queued combines (engine API v85).</summary>
public bool RingAnswerCraftDialog = true;
/// <summary>Craft and inscribe in combat mode too (servers with combat-mode crafting).</summary>
public bool RingAllowInCombat;
}
// ── Games ───────────────────────────────────────────────────────────────────

View file

@ -145,6 +145,16 @@ internal sealed class IltHubStore
s.Pet ??= new IltPetState();
s.Pet.PetLog ??= new();
s.Pet.ShinyLog ??= new();
s.Pet.Breeding ??= new();
s.Pet.Breeding.Rules ??= new();
s.Pet.Breeding.StageNames ??= new();
s.Pet.Breeding.Log ??= new();
s.Pet.Breeding.LastDebug ??= new();
s.Pet.Breeding.Rules.RemoveAll(r => r == null || string.IsNullOrEmpty(r.Key));
s.Pet.Breeding.Log.RemoveAll(e => e == null);
for (int i = 0; i < s.Pet.Breeding.StageNames.Count; i++) s.Pet.Breeding.StageNames[i] ??= string.Empty;
if (s.Pet.Breeding.Log.Count > IltBreedingRules.MaxEvents)
s.Pet.Breeding.Log.RemoveRange(0, s.Pet.Breeding.Log.Count - IltBreedingRules.MaxEvents);
s.Character ??= new IltCharacterState();
s.Character.ItemConversions ??= new();
s.Character.AugTargets = new Dictionary<string, int>(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase);
@ -157,6 +167,7 @@ internal sealed class IltHubStore
s.Gear ??= new IltGearState();
s.Gear.DispelInclusions ??= new();
s.Gear.DispelExclusions ??= new();
s.Gear.RingRuns = new Dictionary<string, int>(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase);
s.Games ??= new IltGamesState();
s.Guardian ??= new IltGuardianState();
s.Guardian.TurnInCounts = new Dictionary<string, int>(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase);
@ -286,6 +297,8 @@ internal sealed class IltHubStore
{
incoming.PetLog = current.PetLog;
incoming.ShinyLog = current.ShinyLog;
// The breeding tracker holds this object; it is the character's own (not a profile setting).
incoming.Breeding = current.Breeding;
return incoming;
}
@ -301,6 +314,7 @@ internal sealed class IltHubStore
s.Bank = new IltBankState { AutoRefreshSeconds = keepRefresh };
s.Pet.PetLog = new();
s.Pet.ShinyLog = new();
s.Pet.Breeding = new();
s.UbSidecarsImported = false;
s.WindowVisible = false;
}

View file

@ -4,12 +4,18 @@
// Infinite Leaftide items) that read the Hub's state.
//
// The ILT sections are tabs of RynthAi's Mini Remote (its MiniRemoteHud draws the tab bar and
// calls RenderTab through RynthILT.Hub): Character (world status, Force-ILT, server names,
// profiles, session rates), Banking, Gear, Charms and Games. A tab is offered only while the
// server reports its feature on. RenderSection draws the ILT pieces inside RynthAi's own
// surfaces (the Remote tab, the Quests and Pets tabs, the Mini Remote menu). The Guardian is a
// RynthCore ILT panel (the bar's ILT button, next to Bounties), drawn through
// RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation
// calls RenderTab through RynthILT.Hub): Banking, Gear, Charms and Games. A tab is offered only
// while the server reports its feature on. The Character tab left the Mini Remote on 2026-10-13:
// - the session rates are RynthCore's Mini Remote "Session Stats" section (RenderRatesSection,
// surface "section:ilt-rates"), below RynthAi's one session;
// - the character overview and session are RynthOracle's Character tab ("/ro character");
// - the "Treat this world as ILT" override and the ILT world names are RynthCore's
// Options > Diagnostics server selection only ("/ra hub force" and "/ra hub servers" remain).
// The /qb list (RynthAi's Quests tab before it moved to RynthOracle) is RynthILT's own "Quests"
// section on the rail (RenderQuestBonusSection, surface "section:ilt-questbonus").
// RenderSection draws the ILT pieces inside RynthAi's own surfaces (the Remote tab, the Pets tab,
// the Mini Remote menu). The Guardian is a RynthCore ILT panel (the bar's ILT button, next to
// Bounties), drawn through RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation
// modal. Augmentations / Enlightenment / XP planning live on the engine Skills panel. All AC
// actions go through IltHubContext.Post / Confirm so nothing here touches the game directly.
using System;
@ -24,15 +30,16 @@ internal sealed class IltHubUi
private const string ConfirmPopupId = "Confirm##iltconfirm";
private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f);
/// <summary>Where a server is forced now (the only place: RynthCore's Options window).</summary>
private const string ForceHint = "To force a server, use RynthCore Options > Diagnostics > server selection (/rc diagnostics).";
/// <summary>RynthCore's command that opens Options > Diagnostics (RynthCore 2026.10.5.54+).</summary>
private const string DiagnosticsCommand = "/rc diagnostics";
private readonly IltHubController _hub;
private readonly IltHubContext _ctx;
private IltConfirmRequest? _confirm;
private bool _confirmOpened;
private string _profileName = string.Empty;
private bool _profileShared;
private string[] _profileList = Array.Empty<string>();
private int _profileIdx;
private string? _serverNamesEdit;
// The last tab body drawn (for one shown log event per tab change); -1 = none yet.
private int _lastTabLogged = -1;
@ -59,14 +66,50 @@ internal sealed class IltHubUi
}
switch (section)
{
case IltSection.Character: RenderCharacterBody(); break;
case IltSection.Banking: _hub.Banking.Render(); break;
case IltSection.Gear: _hub.Gear.Render(); break;
case IltSection.Charms: _hub.CharmsTab.Render(); break;
case IltSection.Games: _hub.Games.Render(); break;
default:
// A saved tab id from before the move: say where the section lives now.
if (IltSections.MovedCommand(section) is string moved)
MovedLink(section, moved);
break;
}
}
/// <summary>
/// The ILT session extras in RynthCore's Mini Remote "Session Stats" section (surface
/// "section:ilt-rates", the Infinite Leaftide group): coins, pyreals and item conversions.
/// XP, luminance and kills are RynthAi's session stats, drawn above it in the same section.
/// </summary>
public void RenderRatesSection()
{
if (!_hub.Available)
{
RenderHeader();
RenderUnavailable();
return;
}
_hub.Rates.Render(extrasOnly: true);
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment: Skills panel > Progression.");
}
/// <summary>
/// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (surface
/// "section:ilt-questbonus"); it was a section of RynthAi's Quests tab, which moved to RynthOracle.
/// </summary>
public void RenderQuestBonusSection()
{
if (!_ctx.Options.IsIltLikeWorld)
{
RenderHeader();
RenderUnavailable();
return;
}
_hub.QuestBonus.RenderQb();
}
/// <summary>
/// One of the ILT pieces RynthAi draws in its own surfaces (RynthIltHub.Section*). False when
/// there is nothing to draw (unknown id, or not an ILT world).
@ -92,6 +135,10 @@ internal sealed class IltHubUi
if (!o.IsIltLikeWorld) return false;
_hub.PetLogs.RenderSection();
return true;
case RynthIltHub.SectionPetBreeding:
if (!o.IsIltLikeWorld) return false;
_hub.Breeding.RenderSection();
return true;
case RynthIltHub.SectionIltStatus:
return RenderIltStatus();
case RynthIltHub.SectionServerMenu:
@ -117,111 +164,28 @@ internal sealed class IltHubUi
_hub.Guardian.Render();
}
/// <summary>Character tab: world / options header, then session rates (or why the ILT tabs are idle).</summary>
private void RenderCharacterBody()
/// <summary>A button that opens a moved section's new home (posted: the command runs on the pump).</summary>
private void MovedLink(IltSection section, string command)
{
RenderHeader();
ImGui.Separator();
if (!_hub.Available) { RenderUnavailable(); return; }
if (ImGui.CollapsingHeader("Session rates", ImGuiTreeNodeFlags.DefaultOpen)) _hub.Rates.Render();
ImGui.Spacing();
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment are on the Skills panel's Progression tab");
ImGui.TextDisabled("(right-click the dashboard's Char button > Progression).");
const string home = "RynthOracle > Character";
SafeImGui.TextDisabled($"{IltSections.Label(section)} moved to {home}; the ILT session rates are in Session Stats.");
if (ImGui.SmallButton($"Open {home}##moved{(int)section}"))
_ctx.Post(() => _hub.OpenMoved(section, command));
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(command);
}
/// <summary>The world and when the server's ILT features were last read, with a Refresh.</summary>
private void RenderHeader()
{
var o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
ImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world);
SafeImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world);
ImGui.SameLine();
ImGui.TextDisabled(o.IsRefreshing ? "checking server options..."
SafeImGui.TextDisabled(o.IsRefreshing ? "checking server options..."
: o.LastRefreshUtc == DateTime.MinValue ? "server options not checked yet"
: $"options via {o.Source} @ {o.LastRefreshUtc.ToLocalTime():t}");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##opts")) _ctx.Post(() => o.Refresh(manual: true));
bool force = _ctx.State.ForceLeaftideFeatures;
if (ImGui.Checkbox("Treat this world as ILT", ref force)) _hub.ForceIltWorld = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: the Mini Remote asks the server which ILT features exist.\nIt never turns a feature on by itself.");
ImGui.SameLine();
if (ImGui.SmallButton("Servers...")) { _serverNamesEdit = null; ImGui.OpenPopup("##iltservers"); }
ImGui.SameLine();
if (ImGui.SmallButton("Profiles...")) { ImGui.OpenPopup("##iltprofiles"); _ctx.Post(() => _profileList = _ctx.Store.ListProfiles().ToArray()); }
RenderServersPopup();
RenderProfilesPopup();
}
/// <summary>
/// The world names that count as Infinite Leaftide (RynthAi's Settings > Misc "Server Features"
/// list before the move; one list for every character now).
/// </summary>
private void RenderServersPopup()
{
if (!ImGui.BeginPopup("##iltservers")) return;
ImGui.TextColored(IltStyle.ColTeal, "Infinite Leaftide world names");
ImGui.TextDisabled(ServerFeatureGate.Describe(_ctx.Options.WorldName, _ctx.Settings, _ctx.State.ForceLeaftideFeatures));
string text = _serverNamesEdit ?? ServerFeatureGate.FormatList(ServerFeatureGate.Patterns(_ctx.Settings));
ImGui.SetNextItemWidth(320);
bool enter = ImGui.InputTextWithHint("##iltservernames", "InfiniteLeaftide, *Leaftide*", ref text, 512, ImGuiInputTextFlags.EnterReturnsTrue);
_serverNamesEdit = text;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Comma-separated world names that turn on the ILT tabs, the Guardian, the Progression\n" +
"planners and the attribute raiser. * is a wildcard (*Leaftide* matches any\n" +
"name containing Leaftide). Case does not matter. Also: /ra hub servers <list>.");
ImGui.SameLine();
if (ImGui.SmallButton("Save") || enter)
{
var list = ServerFeatureGate.ParseList(_serverNamesEdit);
if (list.Count > 0)
_ctx.Post(() => { _ctx.Settings.ServerNames = list; _ctx.SaveSettings(); });
_serverNamesEdit = null;
}
ImGui.SameLine();
if (ImGui.SmallButton("Default"))
{
_ctx.Post(() => { _ctx.Settings.ServerNames = new(ServerFeatureGate.DefaultServerNames); _ctx.SaveSettings(); });
_serverNamesEdit = null;
}
ImGui.EndPopup();
}
private void RenderProfilesPopup()
{
if (!ImGui.BeginPopup("##iltprofiles")) return;
ImGui.TextColored(IltStyle.ColTeal, "ILT profiles (settings only; no balances)");
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##profname", "profile name", ref _profileName, 64u);
ImGui.SameLine();
ImGui.Checkbox("shared", ref _profileShared);
ImGui.SameLine();
if (ImGui.SmallButton("Save"))
{
string n = _profileName; bool sh = _profileShared;
_ctx.Post(() =>
{
_ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, n, sh, out string err) ? $"[Mini Remote] Saved profile '{n}'." : "[Mini Remote] Save failed: " + err);
_profileList = _ctx.Store.ListProfiles().ToArray();
});
}
var list = _profileList;
if (list.Length > 0)
{
_profileIdx = Math.Clamp(_profileIdx, 0, list.Length - 1);
ImGui.SetNextItemWidth(180);
ImGui.Combo("##proflist", ref _profileIdx, list, list.Length);
ImGui.SameLine();
if (ImGui.SmallButton("Load"))
{
string n = list[_profileIdx];
_ctx.Confirm("Load ILT profile", $"Replace the current ILT settings with profile '{n}'?",
() => _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, n, out string err) ? $"[Mini Remote] Loaded profile '{n}'." : "[Mini Remote] Load failed: " + err),
"Load");
}
}
else ImGui.TextDisabled("No saved profiles.");
ImGui.EndPopup();
}
private void RenderUnavailable()
@ -229,8 +193,7 @@ internal sealed class IltHubUi
var o = _ctx.Options;
if (!o.IsIltLikeWorld)
{
ImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tabs are idle. "
+ "If this shard runs ACECustom under another name, tick 'Treat this world as ILT' and press Refresh.");
SafeImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tools are idle. " + ForceHint);
}
else if (o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue)
{
@ -247,9 +210,19 @@ internal sealed class IltHubUi
private void RenderRemoteBank()
{
var b = _ctx.State.Bank;
if (b.LastUpdated == DateTime.MinValue) { ImGui.TextDisabled("Bank: not loaded (Options > Banking)"); return; }
if (b.LastUpdated == DateTime.MinValue)
{
// Nothing read yet this install: offer a quiet /bank (the Banking tab has the full view).
ImGui.TextDisabled("Bank: not loaded yet");
ImGui.SameLine();
if (ImGui.SmallButton("Load##mrbank")) _ctx.Post(() => _hub.Banking.RequestRefresh(quiet: true));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Reads your bank balances (/bank, reply hidden). The Banking tab has the details.");
BankLink();
return;
}
Stat("P:", Compact(b.Pyreals));
Stat("Lum:", Compact(b.Luminance));
BankLink();
if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return;
ImGui.TableNextColumn(); Stat("LK:", Compact(b.LegendaryKeys));
ImGui.TableNextColumn(); Stat("MK:", Compact(b.MythicalKeys));
@ -260,9 +233,20 @@ internal sealed class IltHubUi
ImGui.EndTable();
}
/// <summary>The Bank line's link to RynthILT's own Banking tab (Infinite Leaftide's bank stays RynthILT's).</summary>
private void BankLink()
{
if (!_hub.SectionAvailable(IltSection.Banking)) return;
ImGui.SameLine();
if (ImGui.SmallButton("Bank##mrbanklink"))
_ctx.Ai.MiniRemoteTab(IltSections.TabId(IltSection.Banking), "show");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("The Banking tab: deposits, withdrawals and transfers (/ra hub open banking).");
}
private static void Stat(string label, string value)
{
ImGui.TextColored(ColLabel, label);
SafeImGui.TextColored(ColLabel, label);
ImGui.SameLine();
ImGui.TextUnformatted(value);
}
@ -280,27 +264,28 @@ internal sealed class IltHubUi
// ── RynthAi's Mini Remote menu: the Infinite Leaftide section ──────────
/// <summary>
/// Under the Infinite Leaftide section while no ILT feature is on: why, this character's
/// "Treat this world as ILT" override and a server-features refresh. False when features are on.
/// Under the Infinite Leaftide section while no ILT feature is on: why, where a server is
/// forced (RynthCore Options > Diagnostics only) and a server-features refresh. False when
/// features are on.
/// </summary>
private bool RenderIltStatus()
{
if (_hub.Available) return false;
var o = _ctx.Options;
ImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
SafeImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
: o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..."
: "No ILT features reported.");
bool force = _hub.ForceIltWorld;
if (ImGui.Checkbox("Treat this world as ILT##mrforce", ref force)) _hub.ForceIltWorld = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: RynthILT asks the server which features exist.\nIt never turns a feature on by itself.");
if (!o.IsIltLikeWorld && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", DiagnosticsCommand))
_ctx.Post(() => { if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(DiagnosticsCommand); });
if (!o.IsIltLikeWorld && ImGui.IsItemHovered()) SafeImGui.SetTooltip(ForceHint);
if (ImGui.MenuItem("Refresh server features##mrrefresh")) _hub.RequestOptionsRefresh();
return true;
}
/// <summary>
/// RynthILT's own Infinite Leaftide entries, for when RynthCore sends no server list (older
/// RynthCore, or its ImGui layer off): the tabs, and the Guardian / Bounties panels.
/// RynthCore, or its ImGui layer off): the tabs, where Character went, and the Guardian /
/// Bounties panels.
/// </summary>
private bool RenderLocalMenu()
{
@ -312,6 +297,8 @@ internal sealed class IltHubUi
if (ImGui.MenuItem(IltSections.Label(section) + "##mrlocal", string.Empty, false, _hub.SectionAvailable(section)))
_ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show");
}
if (ImGui.MenuItem("Character##mrlocal", IltSections.OracleCharacterCommand))
_ctx.Post(() => _hub.OpenMoved(IltSection.Character, IltSections.OracleCharacterCommand));
if (ImGui.MenuItem("Guardian##mrlocal", "/rc guardian", false, _hub.SectionAvailable(IltSection.Guardian)))
_ctx.Post(() => _hub.OpenEnginePanel("guardian", "Guardian", "show"));
if (ImGui.MenuItem("Bounties##mrlocal", "/rc bounties"))
@ -340,9 +327,9 @@ internal sealed class IltHubUi
bool keepOpen = true;
if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize))
{
ImGui.TextColored(IltStyle.ColAmber, _confirm.Title);
SafeImGui.TextColored(IltStyle.ColAmber, _confirm.Title);
ImGui.Separator();
ImGui.TextWrapped(_confirm.Message);
SafeImGui.TextWrapped(_confirm.Message);
ImGui.Spacing();
if (ImGui.Button(_confirm.YesLabel + "##iltyes", new Vector2(120, 0)))
{

View file

@ -49,6 +49,12 @@ internal sealed class IltInventory
public const uint IntImbuedEffect = 179;
public const uint IntCleaving = 292;
public const uint IntItemMaxLevel = 319;
/// <summary>Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5).</summary>
public const int AetheriaMaxLevel = 10;
/// <summary>Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist).</summary>
public const uint IntGearCrit = 372;
public const uint IntGearCritDamage = 374;
public const uint IntGearCritDamageResist = 375;
public const uint IntSummoningMastery = 362;
public const uint IntEnlightenment = 390;
public const uint IntSplitArrowCount = 9031;

View file

@ -14,8 +14,11 @@ internal static class IltParse
{
private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
/// <summary>"/aug" level line: "Creature: 1,234".</summary>
public static readonly Regex AugLine = new(@"^(\w+):\s*([\d,]+)$", Opt);
/// <summary>
/// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2".
/// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys.
/// </summary>
public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*([\d,]+)", Opt);
/// <summary>"/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener".</summary>
public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt);

View file

@ -0,0 +1,790 @@
// IltPetBreeding.cs - The pet breeding tracker: the Breeding sub-tab of RynthAi's Mini Remote Pets tab,
// drawn here (RynthILT.Hub section "pets-breeding"; RynthAi only hosts it), and the same data as JSON
// for other plugins ("RynthILT.Data" v2 GetPetBreedingJson / PetBreedingCommand).
// Originally SilentKelpie's (2026-10-15, his RynthILT 0.2.7); ported into RynthILT 0.3.1 without his
// RynthOracle Pet Breeding tab: breeding is Leaftide's, so only this plugin draws it.
//
// What it does, on Infinite Leaftide only:
// * reads every carried combat essence (appraisal qualities + the LongDesc breeding block) and
// evaluates it with IltBreedingEssence: stud / dam, each gate that fails, when it clears, growth;
// * counts Ivo's supplies and applies a breeding booster to an essence after the player confirms;
// * runs "@breed-debug" (quietly) for the room check and "@dance" to start the ritual;
// * logs breeding chat (ritual, charge spent, birth, guardian, growth, adulthood, imprint);
// * learns this server's rules from its own text (IltBreedingRules) and reports what it sees to
// the Leaftide feature profile (the pet_breeding / pet_maturity bits).
// Essences are read only while someone is looking (the section drawn, or a reader asking for the
// JSON within WatchMs), so an unwatched tracker costs nothing.
// Threading: Tick / OnChat / actions on the pump; Render on the ImGui thread reads only the
// immutable snapshot and posts actions.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Everything the breeding UI and reader JSON show, rebuilt whole on the pump.</summary>
/// <remarks><see cref="RulesView"/> is a frozen copy of the rules: the render thread plans with it while the pump learns.</remarks>
internal sealed record BreedingSnapshot(
IReadOnlyList<BreedEssence> Essences, IReadOnlyList<(BreedSupplyDef Def, long Count)> Supplies,
IReadOnlyList<BreedRuleValue> Rules, IReadOnlyList<IltBreedingEvent> Events, BreedDebugInfo? Debug, DateTime DebugUtc,
IltTri Enabled, IltTri Maturity, IltTri Bond, string Room, int FreeSlots, string Message, double NowUnix, bool Built,
IltBreedingRules RulesView)
{
public static readonly BreedingSnapshot Empty = new(Array.Empty<BreedEssence>(), Array.Empty<(BreedSupplyDef, long)>(),
Array.Empty<BreedRuleValue>(), Array.Empty<IltBreedingEvent>(), null, default, IltTri.Unknown, IltTri.Unknown,
IltTri.Unknown, string.Empty, -1, string.Empty, 0, false, new IltBreedingRules(new IltBreedingState()));
}
internal sealed class IltPetBreeding : IIltFeature
{
/// <summary>Feature bits this tracker reports (IltFeatureCatalog's pet_breeding / pet_maturity rows).</summary>
public const string BitBreeding = RynthIltHub.FeaturePetBreeding;
public const string BitMaturity = "pet_maturity";
/// <summary>ACE commands: the diagnostics reply, and the courtship dance.</summary>
public const string DebugCommand = "@breed-debug";
public const string DanceCommand = "@dance";
// ACECustom pet device qualities (AssessmentProperty, sent with the appraisal).
private const uint StrLongDesc = 16;
private const uint IntUseRequiresLevel = 369;
private const uint IntUseLevelRequirement = 364;
private const uint IntBondLevel = 9053;
private const uint IntPotencyStored = 9056;
private const uint IntMaleCharges = 9057;
private const uint IntMutDamage = 9070, IntMutDamageResist = 9071, IntMutCrit = 9072, IntMutVitality = 9073, IntMutPotency = 9074;
private const uint IntMutationCount = 9075;
private const uint IntMaturityKills = 9077;
private const uint FloatNextBreeding = 9056;
private const uint FloatMaleRefresh = 9057;
private const uint FloatIncense = 9058;
private const uint FloatMaturityXpMult = 9059;
private const uint BoolBondAttuned = 9047;
private const uint BoolNeutered = 9051;
private const uint BoolMaleOverride = 50053;
private const uint BoolJuvenile = 50054;
private const uint BoolCatalyst = 50055;
private const uint BoolOffering = 50056;
/// <summary>The tracker reads essences while it was looked at within this long.</summary>
private const long WatchMs = 6000;
/// <summary>How often a watched tracker re-reads the essences.</summary>
private const long ScanMs = 2000;
/// <summary>Appraisal requests per scan for essences not yet appraised.</summary>
private const int AppraisePerScan = 2;
private readonly IltHubContext _ctx;
private readonly IltBreedingRules _rules;
private long _watchedAt; // Interlocked: render thread and readers mark it
private long _scannedAt;
private bool _refreshAll; // re-appraise every essence on the next scan (after an event)
private string _message = string.Empty;
private volatile BreedingSnapshot _snap = BreedingSnapshot.Empty;
private volatile string _readerJson = string.Empty;
// Render-thread selections (ids of carried essences; 0 = none).
private int _studId, _damId, _targetId;
public IltPetBreeding(IltHubContext ctx)
{
_ctx = ctx;
_rules = new IltBreedingRules(ctx.State.Pet.Breeding);
}
/// <summary>The rules (tests and the controller).</summary>
internal IltBreedingRules Rules => _rules;
/// <summary>The latest snapshot (any thread).</summary>
public BreedingSnapshot Snapshot => _snap;
/// <summary>Someone is looking: keep the essences fresh for a while (any thread).</summary>
public void MarkWatched() => System.Threading.Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs);
/// <summary>The reader JSON ("RynthILT.Data" GetPetBreedingJson); reading it marks the tracker watched. Any thread.</summary>
public string ReaderJson
{
get { MarkWatched(); return _readerJson; }
}
private static double UnixNow => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0;
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - System.Threading.Interlocked.Read(ref _watchedAt) > WatchMs) return;
if (_scannedAt != 0 && nowMs - _scannedAt < ScanMs) return;
_scannedAt = nowMs;
Scan();
}
public bool OnChat(string text)
{
if (string.IsNullOrEmpty(text)) return false;
DateTime utc = DateTime.UtcNow;
bool changed = _rules.LearnAll(IltBreedingRules.FromChat(text), utc);
foreach (string raw in text.Split('\n'))
{
string line = raw.Trim();
string? kind = EventKind(line);
if (kind == null) continue;
_rules.AddEvent(kind, line, utc);
changed = true;
if (kind is "ritual" or "birth" or "charge") _ctx.Options.Set(BitBreeding, IltTri.On);
if (kind is "growth" or "adult")
{
_ctx.Options.Set(BitMaturity, IltTri.On);
if (IltBreedingRules.TryParseGrownInto(line, out int stage, out string name)) _rules.LearnStageName(stage, name);
}
// The essences changed on the server (charges, rest, a baby, growth): read them again soon.
if (kind is not "dance") { _refreshAll = true; _scannedAt = 0; }
}
if (changed) RynthLog.Trace(LogCat.IltPets, "breeding: chat updated rules / events");
return false;
}
public void OnLogout()
{
_snap = BreedingSnapshot.Empty;
_readerJson = string.Empty;
_scannedAt = 0;
_message = string.Empty;
}
/// <summary>The event kind of a breeding chat line, or null for any other line.</summary>
internal static string? EventKind(string line)
{
if (line.Length == 0) return null;
if (line.StartsWith("The mating ritual has begun between", StringComparison.OrdinalIgnoreCase)) return "ritual";
if (line.Contains("spent a breeding charge", StringComparison.OrdinalIgnoreCase)) return "charge";
if (line.Contains("A baby pet has been born", StringComparison.OrdinalIgnoreCase)) return "birth";
if (line.StartsWith("The union stirs something", StringComparison.OrdinalIgnoreCase)) return "guardian";
if (line.Contains("yields to its parents", StringComparison.OrdinalIgnoreCase)) return "guardian";
if (line.Contains("Awakened Blessing", StringComparison.OrdinalIgnoreCase)) return "mutation";
if (line.Contains("spectral guardian dissolves", StringComparison.OrdinalIgnoreCase)) return "guardian";
if (line.Contains("has grown into a", StringComparison.OrdinalIgnoreCase)) return "growth";
if (line.Contains("has reached adulthood", StringComparison.OrdinalIgnoreCase)) return "adult";
if (line.Contains("has imprinted on you", StringComparison.OrdinalIgnoreCase)) return "imprint";
if (line.StartsWith("[Breeding] Your pet performs the courtship dance", StringComparison.OrdinalIgnoreCase)) return "dance";
if (line.StartsWith("You administer the Nurturing Draught", StringComparison.OrdinalIgnoreCase)) return "supply";
if (line.StartsWith("You have permanently spayed/neutered", StringComparison.OrdinalIgnoreCase)) return "supply";
return null;
}
// ── Scan (pump) ─────────────────────────────────────────────────────────
/// <summary>Reads every carried combat essence and the supplies, then rebuilds the snapshot and reader JSON.</summary>
private void Scan()
{
IltInventory inv = _ctx.Inventory;
RynthCoreHost host = _ctx.Host;
double now = UnixNow;
DateTime utc = DateTime.UtcNow;
var essences = new List<BreedEssence>();
int appraised = 0;
bool sawBlock = false, sawGrowth = false;
foreach (WorldObject wo in inv.Items())
{
uint wcid = inv.Wcid(wo);
if (!IltBreedingEssence.IsCombatEssence(wcid) && !LooksLikeEssence(wo, inv)) continue;
BreedEssenceFacts f = ReadFacts(host, inv, wo, wcid);
if (f.LongDesc.Contains("Sex:", StringComparison.Ordinal)) sawBlock = true;
if (f.LongDesc.Contains("Growth:", StringComparison.Ordinal)) sawGrowth = true;
_rules.LearnAll(IltBreedingRules.FromAppraisal(f.LongDesc, f.MaleRefreshUnix, now), utc);
if (IltBreedingRules.TryParseGrowth(f.LongDesc, out string stageName, out int stage, out _, out _, out _, out _))
_rules.LearnStageName(stage, stageName);
essences.Add(IltBreedingEssence.Evaluate(f, _rules, now));
// Appraise what isn't loaded (a few per scan), or everything after a breeding event.
if ((_refreshAll || !f.HasId) && appraised < (_refreshAll ? 32 : AppraisePerScan) && inv.RequestAppraisal(wo))
appraised++;
}
_refreshAll = false;
// The server only writes the breeding block while breeding is on: seeing it is the server saying so.
if (sawBlock) _ctx.Options.Set(BitBreeding, IltTri.On);
if (sawGrowth) _ctx.Options.Set(BitMaturity, IltTri.On);
essences.Sort((a, b) =>
{
int c = b.Ready.CompareTo(a.Ready);
if (c != 0) return c;
c = b.Male.CompareTo(a.Male);
return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
});
var supplies = new List<(BreedSupplyDef, long)>(IltBreedingSupplies.All.Length);
foreach (BreedSupplyDef s in IltBreedingSupplies.All) supplies.Add((s, inv.CountByWcid(s.Wcid)));
IltBreedingState st = _rules.State;
BreedDebugInfo? debug = st.LastDebug.Count > 0 ? IltBreedingRules.ParseDebug(st.LastDebug) : null;
var events = st.Log.Select(e => new IltBreedingEvent { Utc = e.Utc, Kind = e.Kind, Text = e.Text }).ToArray();
var snap = new BreedingSnapshot(essences, supplies, _rules.All(), events, debug, st.LastDebugUtc,
EnabledState(), _ctx.Options.Get(BitMaturity), _ctx.Options.Get(IltFeature.PetBond),
_rules.RoomText(), inv.FreeMainPackSlots(), _message, now, true, _rules.Frozen());
_snap = snap;
_readerJson = BuildJson(snap, _rules, _ctx.Options.WorldName);
}
/// <summary>The pet_breeding state the Leaftide profile shows (reported, else the ILT profile's "on").</summary>
private IltTri EnabledState()
{
IltTri t = _ctx.Options.Get(BitBreeding);
return t != IltTri.Unknown ? t : _ctx.Options.IsIltLikeWorld ? IltTri.On : IltTri.Unknown;
}
/// <summary>An essence outside the WCID table (a new family) that the server gave a breeding block.</summary>
private static bool LooksLikeEssence(WorldObject wo, IltInventory inv)
=> wo.Name.EndsWith("Essence", StringComparison.OrdinalIgnoreCase)
&& inv.Str(wo, StrLongDesc).Contains("Sex:", StringComparison.Ordinal);
private static BreedEssenceFacts ReadFacts(RynthCoreHost host, IltInventory inv, WorldObject wo, uint wcid)
{
uint id = unchecked((uint)wo.Id);
var f = new BreedEssenceFacts
{
Id = wo.Id,
Name = wo.Name,
Wcid = wcid,
HasId = inv.HasAppraisal(wo),
Bond = inv.Int(wo, IntBondLevel),
PotencyStored = inv.Int(wo, IntPotencyStored),
MutDamage = inv.Int(wo, IntMutDamage),
MutDamageResist = inv.Int(wo, IntMutDamageResist),
MutCrit = inv.Int(wo, IntMutCrit),
MutVitality = inv.Int(wo, IntMutVitality),
MutPotency = inv.Int(wo, IntMutPotency),
MutationCount = inv.Int(wo, IntMutationCount),
Neutered = TryBool(host, id, BoolNeutered, out bool n) && n,
JuvenileFlag = TryBool(host, id, BoolJuvenile, out bool j) && j,
Catalyst = TryBool(host, id, BoolCatalyst, out bool c) && c,
Offering = TryBool(host, id, BoolOffering, out bool o) && o,
Attuned = TryBool(host, id, BoolBondAttuned, out bool a) && a,
NextBreedUnix = TryDouble(host, id, FloatNextBreeding),
MaleRefreshUnix = TryDouble(host, id, FloatMaleRefresh),
Incense = TryDouble(host, id, FloatIncense),
MaturityXpMult = TryDouble(host, id, FloatMaturityXpMult),
LongDesc = inv.Str(wo, StrLongDesc),
};
f.UseLevel = inv.Int(wo, IntUseRequiresLevel);
if (f.UseLevel <= 0) f.UseLevel = inv.Int(wo, IntUseLevelRequirement);
if (TryBool(host, id, BoolMaleOverride, out bool male)) f.MaleOverride = male;
// Absent and 0 differ for these two: absent = never bred / a full stud.
f.MaturityKills = TryInt(host, id, IntMaturityKills, out int kills) ? kills : -1;
f.MaleCharges = TryInt(host, id, IntMaleCharges, out int charges) ? charges : -1;
return f;
}
private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v)
{
v = false;
return host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(id, stype, out v);
}
private static bool TryInt(RynthCoreHost host, uint id, uint stype, out int v)
{
v = 0;
return host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out v);
}
private static double TryDouble(RynthCoreHost host, uint id, uint stype)
=> host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out double v) ? v : 0;
// ── Actions (pump) ──────────────────────────────────────────────────────
/// <summary>Re-appraises every essence and rescans.</summary>
public void RefreshAll()
{
_refreshAll = true;
_scannedAt = 0;
MarkWatched();
}
/// <summary>Runs "@breed-debug" quietly and keeps its reply (the room check, partners nearby).</summary>
public void RequestDebug()
{
if (_ctx.Capture.IsPending(DebugCommand)) return;
_message = "Asking the server for breeding diagnostics...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = DebugCommand,
IsResponseLine = IltBreedingRules.IsDebugLine,
IsTerminator = IltBreedingRules.IsDebugEnd,
IdleEndMs = 1500,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = ApplyDebug,
});
_scannedAt = 0;
}
private void ApplyDebug(IltChatResult r)
{
if (r.UnknownCommand) { _message = "This server has no @breed-debug (no pet breeding here)."; _ctx.Options.Set(BitBreeding, IltTri.Off); return; }
if (r.NotSent) { _message = "This RynthCore can't send chat commands."; return; }
if (r.Lines.Count == 0) { _message = "No reply to @breed-debug."; return; }
DateTime utc = DateTime.UtcNow;
IltBreedingState st = _rules.State;
st.LastDebug = new List<string>(r.Lines);
st.LastDebugUtc = utc;
foreach (string l in r.Lines) _rules.LearnAll(IltBreedingRules.FromChat(l), utc);
BreedDebugInfo d = IltBreedingRules.ParseDebug(r.Lines);
if (d.Enabled.HasValue) _ctx.Options.Set(BitBreeding, d.Enabled.Value ? IltTri.On : IltTri.Off);
_message = d.Enabled == false ? "The server says breeding is switched off."
: d.LocationOk == true ? $"You're in the breeding room. Partners nearby: {Math.Max(0, d.Partners)}."
: d.LocationOk == false ? $"Not in the breeding room ({_rules.RoomText()})."
: "Diagnostics read.";
_rules.AddEvent("debug", _message, utc);
_scannedAt = 0;
}
/// <summary>Starts the courtship dance ("@dance"); the breed happens when a partner dances in time.</summary>
public void Dance()
{
if (!_ctx.Host.HasInvokeChatParser) { _message = "This RynthCore can't send chat commands."; return; }
_ctx.Host.InvokeChatParser(DanceCommand);
_message = $"Danced. Your partner must *dance* within {_rules.Get(IltBreedingRules.DanceWindow):0.#}s with their pet in the same room.";
_scannedAt = 0;
}
/// <summary>
/// Uses a supply on a carried essence, re-checking both are still here and that the server would
/// take it. Returns a message for the UI. Called after the player confirmed.
/// </summary>
public string ApplySupply(string key, int essenceId)
{
BreedSupplyDef? def = IltBreedingSupplies.Find(key);
if (def == null || !def.Apply) return _message = "That supply isn't applied from here.";
IltInventory inv = _ctx.Inventory;
WorldObject? item = inv.FindByWcid(def.Wcid);
if (item == null) return _message = $"No {def.Name} in your pack.";
BreedEssence? e = _snap.Essences.FirstOrDefault(x => x.Id == essenceId);
if (e == null || !inv.Items().Any(wo => wo.Id == essenceId)) return _message = "That essence isn't in your pack any more.";
string? refuse = IltBreedingSupplies.RefuseReason(def, e, _rules);
if (refuse != null) return _message = refuse;
if (inv.IsBusy) return _message = "You're busy; try again in a moment.";
bool sent = inv.UseOn(item, unchecked((uint)essenceId));
_message = sent ? $"Used {def.Name} on {e.Name}." : $"Couldn't use {def.Name} (the engine refused).";
if (sent) _rules.AddEvent("supply", _message, DateTime.UtcNow);
RefreshAll();
return _message;
}
/// <summary>
/// A reader's verb line ("RynthILT.Data" PetBreedingCommand): refresh, debug, dance,
/// or "apply &lt;supplyKey&gt; &lt;essenceId&gt;" (the reader confirmed it with the player). Pump thread.
/// </summary>
public void RunVerb(string line)
{
string[] parts = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return;
switch (parts[0].ToLowerInvariant())
{
case "refresh": RefreshAll(); break;
case "debug": RequestDebug(); break;
case "dance": Dance(); break;
case "apply" when parts.Length == 3 && int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id):
ApplySupply(parts[1], id);
break;
default:
RynthLog.Trace(LogCat.IltPets, $"breeding: unknown reader verb '{line}'");
break;
}
}
// ── Reader JSON ─────────────────────────────────────────────────────────
/// <summary>The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape).</summary>
internal static string BuildJson(BreedingSnapshot s, IltBreedingRules r, string world)
{
var sb = new StringBuilder(4096);
sb.Append("{\"available\":true");
Str(sb, "world", world);
Str(sb, "enabled", TriText(s.Enabled));
Str(sb, "maturity", TriText(s.Maturity));
Str(sb, "bond", TriText(s.Bond));
Str(sb, "room", s.Room);
sb.Append(",\"freeSlots\":").Append(s.FreeSlots);
Str(sb, "message", s.Message);
sb.Append(",\"essences\":[");
for (int i = 0; i < s.Essences.Count; i++)
{
BreedEssence e = s.Essences[i];
if (i > 0) sb.Append(',');
sb.Append("{\"id\":").Append(e.Id);
Str(sb, "name", e.Name);
Str(sb, "sex", e.Male ? "M" : "F");
sb.Append(",\"tier\":").Append(e.Tier).Append(",\"bond\":").Append(e.Bond);
sb.Append(",\"ready\":").Append(e.Ready ? "true" : "false");
Str(sb, "status", e.Status);
double readyIn = e.ReadyAtUnix > s.NowUnix ? e.ReadyAtUnix - s.NowUnix : 0;
sb.Append(",\"readyIn\":").Append((long)Math.Ceiling(readyIn));
sb.Append(",\"charges\":").Append(e.Charges).Append(",\"chargesMax\":").Append(e.ChargesMax);
sb.Append(",\"juvenile\":").Append(e.Juvenile ? "true" : "false");
Str(sb, "stage", e.StageName);
sb.Append(",\"kills\":").Append(e.Kills).Append(",\"killsRequired\":").Append(e.KillsRequired);
sb.Append(",\"mutations\":").Append(e.StatMutations).Append(",\"potencyMutations\":").Append(e.MutP);
Arr(sb, "problems", e.Problems);
Arr(sb, "boosters", e.Boosters);
sb.Append('}');
}
sb.Append(']');
// Ready pairings, best odds first (the fewest inherited mutations keeps the decay low).
var studs = s.Essences.Where(e => e.Male && e.Ready).ToList();
var dams = s.Essences.Where(e => !e.Male && e.Ready).ToList();
var pairs = new List<(BreedEssence Stud, BreedEssence Dam, BreedPairPlan Plan)>();
foreach (BreedEssence st in studs)
foreach (BreedEssence d in dams)
pairs.Add((st, d, IltBreedingPlanner.Plan(st, d, r)));
pairs.Sort((a, b) => b.Plan.ChanceBest.CompareTo(a.Plan.ChanceBest));
sb.Append(",\"pairs\":[");
for (int i = 0; i < pairs.Count && i < 6; i++)
{
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "stud", pairs[i].Stud.Name, first: true);
Str(sb, "dam", pairs[i].Dam.Name);
sb.Append(",\"chanceBest\":").Append(pairs[i].Plan.ChanceBest.ToString("0.####", CultureInfo.InvariantCulture));
sb.Append(",\"chanceWorst\":").Append(pairs[i].Plan.ChanceWorst.ToString("0.####", CultureInfo.InvariantCulture));
sb.Append(",\"inheritMin\":").Append(pairs[i].Plan.InheritMin).Append(",\"inheritMax\":").Append(pairs[i].Plan.InheritMax);
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"supplies\":[");
for (int i = 0; i < s.Supplies.Count; i++)
{
(BreedSupplyDef def, long count) = s.Supplies[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", def.Key, first: true);
Str(sb, "name", def.Name);
Str(sb, "effect", def.Effect);
sb.Append(",\"count\":").Append(count).Append(",\"price\":").Append(def.Price);
sb.Append(",\"apply\":").Append(def.Apply ? "true" : "false");
// Essences the server would take this on now (the reader's Use buttons).
var targets = def.Apply && count > 0
? s.Essences.Where(e => IltBreedingSupplies.RefuseReason(def, e, r) == null).Select(e => e.Id).ToList()
: new List<int>();
sb.Append(",\"targets\":[").Append(string.Join(',', targets)).Append(']');
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"rules\":[");
for (int i = 0; i < s.Rules.Count; i++)
{
BreedRuleValue v = s.Rules[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "label", v.Def.Label, first: true);
Str(sb, "value", IltBreedingRules.Format(v));
Str(sb, "source", IltBreedingRules.SourceText(v.Source));
Str(sb, "help", v.Def.Help);
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"events\":[");
int start = Math.Max(0, s.Events.Count - 20);
for (int i = s.Events.Count - 1; i >= start; i--)
{
IltBreedingEvent e = s.Events[i];
if (i != s.Events.Count - 1) sb.Append(',');
sb.Append('{');
Str(sb, "when", e.Utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true);
Str(sb, "kind", e.Kind);
Str(sb, "text", e.Text);
sb.Append('}');
}
sb.Append(']');
if (s.Debug != null)
{
BreedDebugInfo d = s.Debug;
sb.Append(",\"debug\":{");
Str(sb, "when", s.DebugUtc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true);
Str(sb, "enabled", d.Enabled == null ? "unknown" : d.Enabled.Value ? "on" : "off");
Str(sb, "location", d.Location);
Str(sb, "match", d.LocationOk == null ? "" : d.LocationOk.Value ? "valid" : "invalid");
Str(sb, "pet", d.ActivePet);
Str(sb, "sex", d.PetSex);
sb.Append(",\"partners\":").Append(d.Partners);
sb.Append('}');
}
sb.Append('}');
return sb.ToString();
}
private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
private static void Str(StringBuilder sb, string name, string? value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"');
}
private static void Arr(StringBuilder sb, string name, IReadOnlyList<string> values)
{
sb.Append(",\"").Append(name).Append("\":[");
for (int i = 0; i < values.Count; i++)
{
if (i > 0) sb.Append(',');
sb.Append('"').Append(IltStyle.JsonEscape(values[i])).Append('"');
}
sb.Append(']');
}
// ── UI (render thread): Mini Remote > Pets > Breeding ───────────────────
/// <summary>The Breeding tab's body (RynthIltHub.SectionPetBreeding).</summary>
public void RenderSection()
{
MarkWatched();
BreedingSnapshot s = _snap;
RenderHeader(s);
if (!s.Built)
{
ImGui.TextDisabled("Reading your essences...");
return;
}
ImGui.Separator();
RenderEssences(s);
RenderPlanner(s);
RenderSupplies(s);
RenderRules(s);
RenderEvents(s);
RenderGuide(s);
}
private void RenderHeader(BreedingSnapshot s)
{
Vector4 col = s.Enabled == IltTri.Off ? IltStyle.ColHp : IltStyle.ColTeal;
SafeImGui.TextColored(col, s.Enabled switch
{
IltTri.Off => "Pet breeding is off on this server.",
IltTri.On => $"Pet breeding: on. Breeding room: {s.Room}.",
_ => "Pet breeding: not confirmed yet (run Diagnostics in the breeding room).",
});
if (s.Bond == IltTri.Off) SafeImGui.TextColored(IltStyle.ColAmber, "Pet bond is off here, so bond can't reach the breeding minimum.");
if (ImGui.SmallButton("Refresh##brrefresh")) _ctx.Post(RefreshAll);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-appraise every essence (charges, rest timers, bond, growth).");
ImGui.SameLine();
if (ImGui.SmallButton("Diagnostics##brdebug")) _ctx.Post(RequestDebug);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("@breed-debug: are you in the breeding room, your summoned pet, partners nearby (reply hidden, shown here).");
ImGui.SameLine();
if (ImGui.SmallButton("Dance##brdance"))
_ctx.Confirm("Courtship dance",
"Dance now? If your partner dances within the window with both pets summoned in the same room, the breed happens:" +
" the stud spends a charge, the dam rests, incense is used up and the baby goes to the dam's owner.",
Dance, "Dance");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("@dance (the same as typing *dance*). Both owners must dance within the window.");
if (s.Message.Length > 0) SafeImGui.TextDisabled(s.Message);
if (s.FreeSlots == 0) SafeImGui.TextColored(IltStyle.ColAmber, "Your main pack is full: as the dam's owner you couldn't receive the baby.");
}
private void RenderEssences(BreedingSnapshot s)
{
int ready = s.Essences.Count(e => e.Ready);
if (!ImGui.CollapsingHeader($"Essences ({ready} ready of {s.Essences.Count})###bress", ImGuiTreeNodeFlags.DefaultOpen)) return;
if (s.Essences.Count == 0)
{
ImGui.TextDisabled("No combat pet essences in your pack.");
return;
}
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.ScrollY;
float h = Math.Min(260f, 26f + s.Essences.Count * ImGui.GetTextLineHeightWithSpacing());
if (!ImGui.BeginTable("##brtable", 6, flags, new Vector2(0, h))) return;
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("Essence", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Sex", ImGuiTableColumnFlags.WidthFixed, 34);
ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 34);
ImGui.TableSetupColumn("Bond", ImGuiTableColumnFlags.WidthFixed, 38);
ImGui.TableSetupColumn("Breeding", ImGuiTableColumnFlags.WidthFixed, 130);
ImGui.TableSetupColumn("Muts", ImGuiTableColumnFlags.WidthFixed, 40);
ImGui.TableHeadersRow();
for (int i = 0; i < s.Essences.Count; i++)
{
BreedEssence e = s.Essences[i];
ImGui.PushID(i);
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool picked = e.Id == _studId || e.Id == _damId;
if (ImGui.Selectable(SafeText(e.Name) + "##sel", picked, ImGuiSelectableFlags.SpanAllColumns))
{
if (e.Male) _studId = e.Id; else _damId = e.Id;
_targetId = e.Id;
}
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(e));
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.Male ? "M" : "F");
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?");
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.HasId ? e.Bond.ToString(CultureInfo.InvariantCulture) : "?");
ImGui.TableNextColumn();
Vector4 col = e.Ready ? IltStyle.ColGreen
: e.Gate is BreedGate.Resting or BreedGate.NoCharges or BreedGate.Growing or BreedGate.NeedsId ? IltStyle.ColAmber
: IltStyle.ColTextMute;
SafeImGui.TextColored(col, e.Status);
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.MutP > 0 ? $"{e.StatMutations}+{e.MutP}p" : e.StatMutations.ToString(CultureInfo.InvariantCulture));
ImGui.PopID();
}
ImGui.EndTable();
ImGui.TextDisabled("Click a male to pick the stud, a female for the dam (and the supply target). Hover for details.");
}
private static string Tooltip(BreedEssence e)
{
var sb = new StringBuilder();
sb.Append(e.Name).Append('\n').Append(e.Role).Append(", tier ").Append(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?")
.Append(", bond ").Append(e.Bond);
if (e.Male) sb.Append("\nCharges ").Append(e.Charges).Append('/').Append(e.ChargesMax);
if (e.Bred) sb.Append(e.Juvenile ? $"\nGrowing: {e.StageName}, {e.KillsToNext} kills to the next stage, {Math.Max(0, e.KillsRequired - e.Kills)} to Adult" : "\nBred: Adult");
if (e.Unbound) sb.Append("\nUnbound: imprints on the first character to summon it.");
sb.Append($"\nMutations: damage {e.MutD}, damage resist {e.MutDR}, crit {e.MutC}, vitality {e.MutV}, potency {e.MutP}");
if (e.Boosters.Count > 0) sb.Append("\nBoosters: ").Append(string.Join(", ", e.Boosters));
foreach (string p in e.Problems) sb.Append("\n- ").Append(p);
return sb.ToString();
}
private void RenderPlanner(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader("Pair planner###brplan")) return;
BreedEssence? stud = s.Essences.FirstOrDefault(e => e.Id == _studId && e.Male);
BreedEssence? dam = s.Essences.FirstOrDefault(e => e.Id == _damId && !e.Male);
PickCombo("Stud##brstud", s.Essences.Where(e => e.Male).ToList(), stud, id => _studId = id);
PickCombo("Dam##brdam", s.Essences.Where(e => !e.Male).ToList(), dam, id => _damId = id);
if (stud == null || dam == null)
{
ImGui.TextDisabled("Pick a stud and a dam (yours, or an alt's carried here) to see the odds.");
ImGui.TextDisabled("Breeding needs two owners: each dances with their own summoned pet.");
return;
}
BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, s.RulesView);
if (p.CanBreed) SafeImGui.TextColored(IltStyle.ColGreen, "Both are ready to breed.");
foreach (string b in p.Blockers) SafeImGui.TextColored(IltStyle.ColAmber, b);
SafeImGui.Text($"Stat mutation chance: {Pct(p.ChanceWorst)} to {Pct(p.ChanceBest)} (baby inherits {p.InheritMin}-{p.InheritMax} stat mutations)");
SafeImGui.Text($"Potency mutation chance: {Pct(p.PotencyChance)}" + (p.Incense > 0 ? $"; incense +{p.Incense * 100:0.#}%" : ""));
foreach (string n in p.Notes) SafeImGui.BulletText(n);
}
private static void PickCombo(string label, List<BreedEssence> list, BreedEssence? current, Action<int> set)
{
ImGui.SetNextItemWidth(260);
if (!ImGui.BeginCombo(label, current != null ? SafeText(current.Name) : "(none)")) return;
foreach (BreedEssence e in list)
{
if (ImGui.Selectable($"{SafeText(e.Name)} - {SafeText(e.Status)}##{e.Id}", current != null && current.Id == e.Id)) set(e.Id);
}
ImGui.EndCombo();
}
private void RenderSupplies(BreedingSnapshot s)
{
long carried = s.Supplies.Sum(x => x.Count);
if (!ImGui.CollapsingHeader($"Supplies ({carried} carried)###brsup")) return;
BreedEssence? target = s.Essences.FirstOrDefault(e => e.Id == _targetId);
PickCombo("Use on##brtarget", s.Essences.ToList(), target, id => _targetId = id);
ImGui.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed.");
for (int i = 0; i < s.Supplies.Count; i++)
{
(BreedSupplyDef def, long count) = s.Supplies[i];
ImGui.PushID("sup" + i);
Vector4 col = count > 0 ? IltStyle.ColGreen : IltStyle.ColTextMute;
SafeImGui.TextColored(col, $"{count,3} {def.Name}");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{def.Effect}\nIvo's price: {IltBreedingSupplies.PriceText(def.Price)} pyreals");
if (def.Apply && count > 0 && target != null)
{
ImGui.SameLine(300);
string? refuse = IltBreedingSupplies.RefuseReason(def, target, s.RulesView);
if (refuse != null)
{
ImGui.TextDisabled("can't");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(refuse);
}
else if (ImGui.SmallButton("Use"))
{
string key = def.Key;
int id = target.Id;
_ctx.Confirm("Use " + def.Name,
$"Use {def.Name} on {target.Name}? {def.Effect}{IltBreedingSupplies.Warning(def, target)}",
() => ApplySupply(key, id), "Use");
}
}
ImGui.PopID();
}
}
private void RenderRules(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader("Server rules###brrules")) return;
ImGui.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults.");
foreach (BreedRuleValue v in s.Rules)
{
SafeImGui.Text(v.Def.Label);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(v.Def.Help);
ImGui.SameLine(200);
SafeImGui.Text(IltBreedingRules.Format(v));
ImGui.SameLine(280);
SafeImGui.TextColored(v.Source == BreedRuleSource.Server ? IltStyle.ColGreen : IltStyle.ColTextMute,
IltBreedingRules.SourceText(v.Source));
}
if (s.Debug != null)
{
ImGui.Separator();
SafeImGui.TextDisabled($"Last diagnostics ({s.DebugUtc.ToLocalTime():g}):");
BreedDebugInfo d = s.Debug;
if (d.Location.Length > 0) SafeImGui.BulletText("You: " + d.Location);
if (d.LocationOk.HasValue) SafeImGui.BulletText(d.LocationOk.Value ? "In the breeding room" : "Not in the breeding room");
if (d.ActivePet.Length > 0) SafeImGui.BulletText("Pet: " + d.ActivePet + (d.PetSex.Length > 0 ? " (" + d.PetSex + ")" : ""));
if (d.Partners >= 0) SafeImGui.BulletText($"Partners nearby: {d.Partners}");
}
}
private static void RenderEvents(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader($"Recent events ({s.Events.Count})###brevents")) return;
if (s.Events.Count == 0) ImGui.TextDisabled("Nothing yet: rituals, births, growth and charges land here.");
for (int i = s.Events.Count - 1, shown = 0; i >= 0 && shown < 20; i--, shown++)
{
IltBreedingEvent e = s.Events[i];
SafeImGui.TextDisabled(e.Utc.ToLocalTime().ToString("MM-dd HH:mm", CultureInfo.InvariantCulture));
ImGui.SameLine(90);
SafeImGui.TextWrapped(e.Text);
}
}
private static void RenderGuide(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader("How to breed###brguide")) return;
SafeImGui.BulletText($"Go to the Seedy Motel (portal by Prof. Ruggan in Lin, 54.7S 73.5E); breeding room {s.Room}.");
SafeImGui.BulletText("Two owners: one summons a male (stud), the other a female (dam). Both pets in the same room.");
SafeImGui.BulletText("Both parents: tier 100+, bond 100+, adult, not shiny, not neutered. The stud needs a charge, the dam must have rested.");
SafeImGui.BulletText("Both owners *dance* (or @dance) within a few seconds. The baby goes to the dam's owner (free pack slot needed).");
SafeImGui.BulletText("A mating guardian may rise: both parents kill it in time for an Awakened Blessing mutation.");
SafeImGui.BulletText("The baby imprints on whoever summons it first, and grows up with kills (Nurturing Draught doubles the credit).");
}
private static string Pct(double v) => (v * 100).ToString("0.##", CultureInfo.InvariantCulture) + "%";
/// <summary>Item names go into ImGui labels, where "##" would start the hidden id.</summary>
private static string SafeText(string s) => (s ?? string.Empty).Replace("#", "");
}

View file

@ -7,6 +7,7 @@
using System;
using System.Collections.Generic;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -78,7 +79,7 @@ internal sealed class IltPetLogs : IIltFeature
if (ImGui.TreeNode($"{label} ({snap.Length})##{key}"))
{
if (ImGui.SmallButton($"Refresh##{key}")) _ctx.Post(() => RequestRoster(shinies));
foreach (string s in snap) ImGui.BulletText(s);
foreach (string s in snap) SafeImGui.BulletText(s);
ImGui.TreePop();
}
}

View file

@ -63,6 +63,10 @@ internal sealed class IltProgression : IIltFeature
private volatile string _augStatus = "not loaded";
// Opening the Progression tab pulls "/aug" once per login when nothing has loaded the levels yet.
private bool _augAutoTried;
/// <summary>Second Refresh current while /aug is already queued or in flight (UB coalesces the same way).</summary>
private bool _augRefreshAgain;
/// <summary>Passive /aug window: accept AugLine chat until this tick (like T11's report parser).</summary>
private long _augPassiveUntilMs;
// Cached player facts for the render thread (refreshed in Tick).
private volatile int _enl, _level, _freeSlots;
@ -104,38 +108,82 @@ internal sealed class IltProgression : IIltFeature
public void RequestAugs()
{
RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()");
if (_ctx.Options.IsOff(IltFeature.Aug) || _ctx.Capture.IsPending("/aug")) return;
if (_ctx.Options.IsOff(IltFeature.Aug))
{
_augStatus = "/aug is off for this world";
return;
}
// Coalesce: a click during an in-flight /aug runs again when that capture finishes (UB).
if (_ctx.Capture.IsPending("/aug"))
{
_augRefreshAgain = true;
_augStatus = "refresh queued (waiting for current /aug)...";
return;
}
_augStatus = "loading...";
_augPassiveUntilMs = IltHubContext.NowMs + 20_000; // also accept lines if capture finishes early
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/aug",
IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
// Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines.
ArmsIdle = t => IltParse.AugLine.IsMatch(t),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Aug, IltTri.Off); _augStatus = "/aug not available"; return; }
if (r.UnknownCommand)
{
_ctx.Options.Set(IltFeature.Aug, IltTri.Off);
_augStatus = "/aug not available";
_augRefreshAgain = false;
return;
}
ApplyAugLines(r.Lines);
if (r.TimedOut)
{
int have;
lock (_augLevels) have = _augLevels.Count;
if (have == 0)
_augStatus = "timed out waiting for /aug level lines";
}
if (_augRefreshAgain)
{
_augRefreshAgain = false;
RequestAugs();
}
},
});
}
/// <summary>Parses "/aug" output (also fed from the login probe).</summary>
/// <summary>Parses "/aug" output (also fed from the login probe and passive chat).</summary>
public void ApplyAugLines(List<string> lines)
{
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})");
int n = 0;
foreach (string l in lines)
{
var m = IltParse.AugLine.Match(l.Trim());
if (!m.Success) continue;
string key = m.Groups[1].Value.ToLowerInvariant();
if (key == "specialize") key = "specialization";
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
n++;
if (TryApplyAugLine(l)) n++;
}
_augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply";
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines done: {_augStatus} (raw lines={lines.Count})");
}
/// <summary>Applies one "/aug" Type: N line. Returns true when a known planner key was updated.</summary>
private bool TryApplyAugLine(string raw)
{
var m = IltParse.AugLine.Match((raw ?? string.Empty).Trim());
if (!m.Success) return false;
string key = m.Groups[1].Value.ToLowerInvariant();
if (key == "specialize") key = "specialization";
// Planner rows only; charm / Triune Weave lines are ignored here (T11 reads those).
bool known = false;
foreach (var (k, _) in IltAugCosts.Labels)
if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; }
if (!known) return false;
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
return true;
}
/// <summary>Sends "/enl" (server shows the confirmation dialog). Pump thread.</summary>
@ -172,6 +220,18 @@ internal sealed class IltProgression : IIltFeature
public bool OnChat(string text)
{
Attributes.OnChat(text);
// Passive /aug reader: updates Current even when the capture idle finished on the banner alone
// (chat-hold backlog) or the player typed /aug by hand. Window opens on the header.
string t = text;
if (t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase))
_augPassiveUntilMs = IltHubContext.NowMs + 8_000;
else if (IltHubContext.NowMs <= _augPassiveUntilMs && TryApplyAugLine(t))
{
_augPassiveUntilMs = IltHubContext.NowMs + 8_000;
int n;
lock (_augLevels) n = _augLevels.Count;
_augStatus = $"{n} aug types @ {DateTime.Now:t}";
}
if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase)
|| text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase))
{
@ -188,6 +248,8 @@ internal sealed class IltProgression : IIltFeature
Attributes.OnLogout();
lock (_augLevels) _augLevels.Clear();
_augAutoTried = false;
_augRefreshAgain = false;
_augPassiveUntilMs = 0;
_augStatus = "not loaded";
}

View file

@ -12,6 +12,7 @@ using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -178,7 +179,7 @@ internal sealed class IltQuestBonus : IIltFeature
if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQb()));
ImGui.SameLine();
long count = _qbCount;
ImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus);
SafeImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus);
string filter = _ctx.State.Character.QbFilter;
ImGui.SetNextItemWidth(220);
@ -195,7 +196,7 @@ internal sealed class IltQuestBonus : IIltFeature
if (ImGui.TreeNode($"{label} ({shown.Length})##qb{label}"))
{
if (ImGui.SmallButton($"Copy##qbc{label}")) ImGui.SetClipboardText(string.Join(Environment.NewLine, shown));
foreach (string s in shown) ImGui.TextColored(color, s);
foreach (string s in shown) SafeImGui.TextColored(color, s);
ImGui.TreePop();
}
}

View file

@ -0,0 +1,130 @@
// IltRingChain.cs - Infinite Leaftide's ring inscription chain (Gear tab > Rings), from UB-IT's
// ImbueSpellCraftDefinitions / SpellcraftInventoryPolicy. SilentKelpie's RynthAi Crafting > Rings
// (MiniRemote/Crafting/RingChain.cs), moved to RynthILT 2026-10-15: it is Leaftide-only.
//
// Step 1: Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction
// Step 2: Enlightened Quill used on Ink of Partition -> partition quill
// Step 3: partition quill used on a Glyph -> "Inscription of ..." scroll
// Then each scroll is used on a ring / jewelry / weapon.
//
// Pure: ingredient matching (case-insensitive substrings with alternates and one exclude), the
// craft queue order and the scroll-to-target pairing. IltRingChainRunner does the using.
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One ingredient: the first of <see cref="Names"/> found in an item's name, unless it also has <see cref="Exclude"/>.</summary>
internal sealed record IltRingIngredient(string Label, string[] Names, string Exclude = "");
/// <summary>One combine: <see cref="Tool"/> is used on <see cref="Target"/>.</summary>
/// <param name="Tier">1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first.</param>
/// <param name="ScrollMarkers">Step 3: the words the resulting inscription scroll's name carries.</param>
internal sealed record IltRingRecipe(string Id, int Tier, string Name, string Notes,
IltRingIngredient Tool, IltRingIngredient Target, string[] ScrollMarkers);
internal static class IltRingChain
{
/// <summary>Every inscription scroll's name has this.</summary>
public const string InscriptionMarker = "Inscription of";
/// <summary>Most runs of one recipe the tab queues.</summary>
public const int MaxRuns = 99;
private static readonly IltRingIngredient PartitionQuill = new("Enlightened Infliction Quill of Partition",
new[] { "Enlightened Infliction Quill of Partition", "Enlightened Quill of Infliction of Partition" });
private static IltRingRecipe Glyph(string id, string element, string scroll) => new(
id, 3, $"Step 3: {element} glyph - {scroll}",
$"Partition quill used on Glyph of {element} -> Inscription of {scroll} scroll.",
PartitionQuill,
// The full glyph name: a short one can match the wrong stack.
new IltRingIngredient($"Glyph of {element}", new[] { $"Glyph of {element}" }),
new[] { scroll, element });
/// <summary>The chain, in UB-IT's order.</summary>
public static readonly IltRingRecipe[] Recipes =
{
new("ring2_step1_quill_trophy", 1, "Step 1: Quill of Infliction + Trophy",
"Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction.",
new IltRingIngredient("Quill of Infliction", new[] { "Quill of Infliction", "Infliction Quill" }, Exclude: "Enlightened"),
// Not plain "Trophy": scrolls and kits carry that word too.
new IltRingIngredient("Trophy", new[] { "Royal Summons", "Empyrean Trophy", "Summoning Gem" }),
Array.Empty<string>()),
new("ring2_step2_ink", 2, "Step 2: Enlightened Quill + Ink of Partition",
"Enlightened Quill of Infliction (from Step 1) used on Ink of Partition -> partition quill.",
new IltRingIngredient("Enlightened Quill of Infliction",
new[] { "Enlightened Quill of Infliction", "Enlightened Infliction Quill", "Enlightened Infliction Quill of" }, Exclude: "Partition"),
new IltRingIngredient("Ink of Partition", new[] { "Ink of Partition", "Partition Ink" }),
Array.Empty<string>()),
Glyph("ring2_glyph_bludgeoning", "Bludgeoning", "Tectonic Rifts"),
Glyph("ring2_glyph_lightning", "Lightning", "Eye of the Storm"),
Glyph("ring2_glyph_piercing", "Piercing", "Nuhmudira's Spines"),
Glyph("ring2_glyph_nether", "Nether", "Clouded Soul"),
Glyph("ring2_glyph_corrosion", "Corrosion", "Searing Disc"),
Glyph("ring2_glyph_frost", "Frost", "Halo of Frost"),
Glyph("ring2_glyph_slashing", "Slashing", "Horizon's Blades"),
Glyph("ring2_glyph_flame", "Flame", "Cassius' Ring of Fire"),
};
/// <summary>True when an item's name is this ingredient.</summary>
public static bool Matches(string? name, IltRingIngredient ing)
{
if (string.IsNullOrEmpty(name)) return false;
if (ing.Exclude.Length > 0 && name.IndexOf(ing.Exclude, StringComparison.OrdinalIgnoreCase) >= 0) return false;
foreach (string n in ing.Names)
if (n.Length > 0 && name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
/// <summary>
/// The craft queue: every Step 1 run, then every Step 2 run, then the glyphs, each tier in
/// definition order (a later tier's ingredients come out of the earlier one).
/// </summary>
public static List<IltRingRecipe> Expand(Func<string, int> runs)
{
var queue = new List<IltRingRecipe>();
foreach (var r in Recipes.OrderBy(r => r.Tier))
{
int n = Math.Clamp(runs(r.Id), 0, MaxRuns);
for (int i = 0; i < n; i++) queue.Add(r);
}
return queue;
}
/// <summary>The glyph recipe a scroll came from (null when its name has no known marker).</summary>
public static IltRingRecipe? GlyphOf(string? scrollName)
{
if (string.IsNullOrEmpty(scrollName)) return null;
foreach (var r in Recipes)
foreach (string m in r.ScrollMarkers)
if (scrollName.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0) return r;
return null;
}
public static bool IsInscriptionScroll(string? name)
=> !string.IsNullOrEmpty(name) && name.IndexOf(InscriptionMarker, StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>The order scrolls are listed and used in: by glyph recipe id, unknown ones last by name.</summary>
public static string ScrollOrderKey(string? scrollName) => GlyphOf(scrollName)?.Id ?? "zzz_" + scrollName;
/// <summary>
/// Pairs scrolls with targets the way UB-IT does: scrolls by glyph recipe id (unknown ones
/// last, by name), targets by object id, one scroll per target.
/// </summary>
public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable<int> targets)
{
var ordered = scrolls
.OrderBy(s => ScrollOrderKey(s.Name), StringComparer.Ordinal)
.ThenBy(s => s.Id)
.ToList();
var pairs = new List<(int, int)>();
int i = 0;
foreach (int t in targets.Distinct().OrderBy(x => x))
{
if (i >= ordered.Count) break;
pairs.Add((ordered[i++].Id, t));
}
return pairs;
}
}

View file

@ -0,0 +1,557 @@
// IltRingChainRunner.cs - Crafts Infinite Leaftide's ring inscription chain and applies the scrolls
// (Gear tab > Rings). SilentKelpie's RynthAi RingChainRunner (MiniRemote/Crafting/), moved to
// RynthILT 2026-10-15 and run on the ILT Hub's context; its settings are the Gear state's
// (IltGearState.RingRuns, RingAnswerCraftDialog, RingAllowInCombat), saved with the Hub.
//
// Tick runs on the pump thread; Render on the render thread reads the volatile snapshots and
// posts the commands (IltHubContext.Post / Confirm).
// Crafting: the queue from IltRingChain.Expand, one combine at a time:
// 1. gates: peace mode (unless allowed in combat for servers with combat crafting), not busy,
// no other ILT pack job (the split-arrow imbuer);
// 2. find the tool and the target by name; a later step's ingredients come out of the earlier
// combine, so a missing one is looked for again for a while (inventory lag) before giving up;
// 3. arm the engine's confirmation answer (API v85; Yes: the player queued it) and use tool on
// target; without v85 (or with the answer off) the player clicks Yes in AC's dialog;
// 4. the combine is done when the tool or the target stack shrinks or the output shows up.
// No sign of it stops the job instead of retrying, so nothing is crafted twice.
// Scrolls: each "Inscription of ..." scroll is used on its target (the item selected in AC, or
// the carried jewelry paired the UB-IT way) and is done when it leaves the pack.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One line of the Rings scan: a recipe header (Found null) or an ingredient.</summary>
/// <param name="State">0 found, 1 comes from an earlier step, 2 missing.</param>
internal sealed record IltRingScanLine(string Text, string? Found, int State);
internal sealed class IltRingChainRunner : IIltFeature
{
private const uint ErrorYoureTooBusy = 0x1D;
private const long StepTimeoutMs = 15_000;
/// <summary>The player answers AC's own dialog: give them time.</summary>
private const long ManualTimeoutMs = 60_000;
private const long StepGapMs = 700;
private const long RetryDelayMs = 1_500;
private const int MaxBusyRetries = 3;
/// <summary>A missing ingredient is looked for this often and this many times (~10 s).</summary>
private const long LookAgainMs = 250;
private const int LookTries = 40;
private const long RunsViewMs = 1000;
private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private enum Mode { Idle, Craft, Apply }
private readonly IltHubContext _ctx;
/// <summary>True while another ILT job (the split-arrow imbuer) is using the pack.</summary>
private readonly Func<bool> _blocked;
// Job (pump thread)
private Mode _mode;
private List<IltRingRecipe> _queue = new();
private List<(int Scroll, int Target)> _pairs = new();
private int _index, _crafted, _lookTries, _busyRetries, _confSeq, _errSeq;
private bool _waiting, _manual;
private long _stepAt, _nextAt, _runsViewAt;
// Counts before the current combine (craft) / the scroll's stack (apply).
private long _toolBefore, _targetBefore, _outputBefore;
private int _scrollStackBefore;
// Render snapshots
private volatile string _status = "idle";
private volatile IltRingScanLine[] _scan = Array.Empty<IltRingScanLine>();
private volatile (int Id, string Name)[] _scrolls = Array.Empty<(int, string)>();
private volatile (int Id, string Name)[] _jewelry = Array.Empty<(int, string)>();
// Runs per recipe (IltRingChain.Recipes order), copied from the Gear state on the pump.
private volatile int[] _runsView = new int[IltRingChain.Recipes.Length];
private volatile bool _running;
public IltRingChainRunner(IltHubContext ctx, Func<bool> blocked)
{
_ctx = ctx;
_blocked = blocked;
}
public bool Running => _running;
public string Status => _status;
public IltRingScanLine[] ScanLines => _scan;
/// <summary>The inscription scrolls the last scan found.</summary>
public (int Id, string Name)[] Scrolls => _scrolls;
private RynthCoreHost Host => _ctx.Host;
private IltInventory Inv => _ctx.Inventory;
private IltGearState G => _ctx.State.Gear;
/// <summary>Pump thread: the saved run count for a recipe.</summary>
private int Runs(string id) => G.RingRuns.TryGetValue(id, out int n) ? n : 0;
/// <summary>Pump thread: sets a recipe's run count (0 removes it) and the render copy.</summary>
public void SetRuns(string id, int runs)
{
runs = Math.Clamp(runs, 0, IltRingChain.MaxRuns);
if (runs == 0) G.RingRuns.Remove(id);
else G.RingRuns[id] = runs;
PublishRuns();
}
private void PublishRuns()
{
var view = new int[IltRingChain.Recipes.Length];
for (int i = 0; i < view.Length; i++) view[i] = Runs(IltRingChain.Recipes[i].Id);
_runsView = view;
}
// ── Inventory ───────────────────────────────────────────────────────────
private IEnumerable<WorldObject> Carried() => Inv.Items().Where(w => !Inv.IsEquipped(w));
private WorldObject? Find(IltRingIngredient ing) => Carried().FirstOrDefault(w => IltRingChain.Matches(w.Name, ing));
private long Count(IltRingIngredient ing) => Carried().Where(w => IltRingChain.Matches(w.Name, ing)).Sum(w => (long)Inv.StackSize(w));
private long ScrollCount() => Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)).Sum(w => (long)Inv.StackSize(w));
/// <summary>What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll.</summary>
private long OutputCount(IltRingRecipe r) => r.Tier switch
{
1 => Count(IltRingChain.Recipes[1].Tool),
2 => Count(IltRingChain.Recipes[2].Tool),
_ => ScrollCount(),
};
// ── Scan ────────────────────────────────────────────────────────────────
/// <summary>
/// Lists every queued recipe's ingredients, marking the ones a later step only gets from an
/// earlier combine (UB-IT's "(after Step 1)"), the carried inscription scrolls and the carried
/// jewelry they can go on. Pump thread.
/// </summary>
public void Scan()
{
var lines = new List<IltRingScanLine>();
bool Stocked(int tier) => IltRingChain.Recipes
.Where(r => r.Tier == tier && Runs(r.Id) > 0)
.All(r => Find(r.Tool) != null && Find(r.Target) != null);
bool tier1 = Stocked(1), tier2 = Stocked(2);
bool any = false, blocking = false;
foreach (var r in IltRingChain.Recipes)
{
int runs = Runs(r.Id);
if (runs <= 0) continue;
any = true;
lines.Add(new IltRingScanLine($"{r.Name} x{runs}", null, 0));
foreach (var ing in new[] { r.Tool, r.Target })
{
var found = Find(ing);
if (found != null) { lines.Add(new IltRingScanLine(ing.Label, $"{found.Name} ({Count(ing)})", 0)); continue; }
string? later = r.Tier == 2 && !tier1 ? "(after Step 1)"
: r.Tier == 3 && !tier1 ? "(after Step 1)"
: r.Tier == 3 && !tier2 ? "(after Step 2)"
: null;
if (later == null) blocking = true;
lines.Add(new IltRingScanLine(ing.Label, later ?? "(not found)", later == null ? 2 : 1));
}
}
_scan = lines.ToArray();
RefreshScrolls();
_status = !any ? "set how many times to craft at least one recipe"
: blocking ? "missing ingredients are marked (not found)"
: "ready: Create runs every Step 1, then Step 2, then Step 3";
}
private void RefreshScrolls()
{
_scrolls = Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name))
.Select(w => (w.Id, w.Name ?? string.Empty))
.OrderBy(s => IltRingChain.ScrollOrderKey(s.Item2), StringComparer.Ordinal)
.ToArray();
_jewelry = Carried().Where(w => w.ObjectClass == AcObjectClass.Jewelry)
.Select(w => (w.Id, w.Name ?? string.Empty))
.OrderBy(j => j.Id)
.ToArray();
}
// ── Job control (pump thread) ───────────────────────────────────────────
/// <summary>Crafts the queued recipes (after the tab's confirm).</summary>
public void Create()
{
if (_running) return;
if (_blocked()) { _status = "the split-arrow imbuer is running"; return; }
var queue = IltRingChain.Expand(Runs);
if (queue.Count == 0) { _status = "set how many times to craft at least one recipe"; return; }
Begin(Mode.Craft);
_queue = queue;
_status = $"crafting {queue.Count} combine(s)";
RynthLog.Write(LogCat.IltGear, $"[Rings] create, {queue.Count} combine(s)");
}
/// <summary>Uses one scroll on the item selected in AC.</summary>
public void ApplyToSelected(int scrollId)
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { _status = "select the ring or item in AC first"; return; }
if (unchecked((int)sel) == scrollId) { _status = "the scroll itself is selected: select the ring or item"; return; }
ApplyPairs(new List<(int, int)> { (scrollId, unchecked((int)sel)) });
}
/// <summary>Pairs the carried scrolls with these items (the carried jewelry) and uses them.</summary>
public void ApplyToItems(IReadOnlyList<int> targetIds)
{
RefreshScrolls();
if (_scrolls.Length == 0) { _status = "no inscription scroll in the pack (name has \"Inscription of\")"; return; }
if (targetIds.Count == 0) { _status = "no jewelry carried (worn items aren't inscribed)"; return; }
ApplyPairs(IltRingChain.PairScrolls(_scrolls, targetIds));
}
private void ApplyPairs(List<(int Scroll, int Target)> pairs)
{
if (_running) return;
if (_blocked()) { _status = "the split-arrow imbuer is running"; return; }
if (pairs.Count == 0) { _status = "nothing to apply"; return; }
Begin(Mode.Apply);
_pairs = pairs;
_status = $"applying {pairs.Count} inscription(s)";
RynthLog.Write(LogCat.IltGear, $"[Rings] apply {pairs.Count} inscription(s)");
}
private void Begin(Mode mode)
{
_mode = mode;
_index = 0;
_crafted = 0;
_lookTries = 0;
_busyRetries = 0;
_waiting = false;
_nextAt = 0;
_running = true;
}
public void Stop(string why)
{
if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
_mode = Mode.Idle;
_waiting = false;
_running = false;
_queue = new List<IltRingRecipe>();
_pairs = new List<(int, int)>();
_status = why;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void OnLogout()
{
Stop("idle");
_scan = Array.Empty<IltRingScanLine>();
_scrolls = Array.Empty<(int, string)>();
_jewelry = Array.Empty<(int, string)>();
}
public void Tick(long nowMs)
{
if (nowMs - _runsViewAt >= RunsViewMs)
{
// A profile load replaces the Gear state: follow it.
_runsViewAt = nowMs;
PublishRuns();
}
if (_mode == Mode.Idle) return;
if (_waiting) { Wait(nowMs); return; }
if (nowMs < _nextAt) return;
if (!G.RingAllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; }
if (Inv.IsBusy) return;
if (_mode == Mode.Craft) NextCombine(nowMs);
else NextScroll(nowMs);
}
private void NextCombine(long nowMs)
{
if (_index >= _queue.Count)
{
Stop($"done - {_crafted} combine(s)");
RefreshScrolls();
RynthLog.Write(LogCat.IltGear, $"[Rings] done, {_crafted} combine(s)");
return;
}
var r = _queue[_index];
var tool = Find(r.Tool);
var target = Find(r.Target);
if (tool == null || target == null)
{
string label = tool == null ? r.Tool.Label : r.Target.Label;
if (++_lookTries <= LookTries)
{
_nextAt = nowMs + LookAgainMs;
_status = $"{r.Name}: looking for {label}";
return;
}
Stop($"{r.Name}: no {label} in the pack");
return;
}
_lookTries = 0;
_toolBefore = Count(r.Tool);
_targetBefore = Count(r.Target);
_outputBefore = OutputCount(r);
if (!Use(tool, target, $"Rings: {r.Name} ({_index + 1}/{_queue.Count})"))
{
Stop($"{r.Name}: the use request didn't go out");
return;
}
string ask = _manual ? " - click Yes in AC's craft dialog" : "";
_status = $"{r.Name} ({_index + 1}/{_queue.Count}): {tool.Name} on {target.Name}{ask}";
}
private void NextScroll(long nowMs)
{
if (_index >= _pairs.Count)
{
Stop($"done - {_crafted} inscription(s) applied");
RefreshScrolls();
return;
}
var (scrollId, targetId) = _pairs[_index];
var scroll = Inv.Cache?[scrollId];
var target = Inv.Cache?[targetId];
if (scroll == null || target == null)
{
// UB-IT moves on past a pair whose scroll or item is gone.
_status = $"inscription {_index + 1}: the scroll or the item is gone - skipped";
_index++;
_nextAt = nowMs + StepGapMs;
return;
}
if (Inv.IsEquipped(target)) { Stop($"{target.Name} is equipped: take it off to inscribe it"); return; }
_scrollStackBefore = Inv.StackSize(scroll);
if (!Use(scroll, target, $"Rings: {scroll.Name} on {target.Name}"))
{
Stop("the use request didn't go out");
return;
}
string ask = _manual ? " - click Yes in AC's dialog" : "";
_status = $"inscription {_index + 1}/{_pairs.Count}: {scroll.Name} on {target.Name}{ask}";
}
/// <summary>Arms the dialog answer (Yes: the player asked for this) and uses source on target.</summary>
private bool Use(WorldObject source, WorldObject target, string why)
{
_manual = !(G.RingAnswerCraftDialog && Host.HasConfirmationAnswers
&& Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)StepTimeoutMs) == 1);
_confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0;
_errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0;
if (!Host.UseOnFor(unchecked((uint)source.Id), unchecked((uint)target.Id), "IltRings", why, UseKind.Asked))
{
if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
return false;
}
_waiting = true;
_stepAt = Environment.TickCount64;
return true;
}
private void Wait(long nowMs)
{
if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _)
&& seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction)
{
_confSeq = seq;
if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) { Stop("the craft dialog was answered No"); return; }
if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed)
{
_manual = true;
_status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})";
}
}
if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq)
{
_errSeq = es;
// Busy: the server did nothing, so the same combine can go again.
if (error == ErrorYoureTooBusy && ++_busyRetries <= MaxBusyRetries)
{
_waiting = false;
_nextAt = nowMs + RetryDelayMs;
_status = $"server says busy - trying again ({_busyRetries}/{MaxBusyRetries})";
return;
}
Stop($"the server refused it (error 0x{error:X})");
return;
}
if (Done()) { Next(nowMs); return; }
if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs))
Stop(_manual ? "no answer to AC's dialog - stopped" : "no result seen - stopped (check the pack before going on)");
}
/// <summary>The current combine or inscription went through.</summary>
private bool Done()
{
if (_mode == Mode.Craft)
{
var r = _queue[_index];
return Count(r.Tool) < _toolBefore || Count(r.Target) < _targetBefore || OutputCount(r) > _outputBefore;
}
var scroll = Inv.Cache?[_pairs[_index].Scroll];
return scroll == null || Inv.StackSize(scroll) < _scrollStackBefore;
}
private void Next(long nowMs)
{
_waiting = false;
_busyRetries = 0;
_crafted++;
_index++;
_nextAt = nowMs + StepGapMs;
}
/// <summary>"cannot be used on" ends the job: the names didn't match what the server expects. Never eaten.</summary>
public bool OnChat(string text)
{
if (!_waiting || string.IsNullOrEmpty(text)) return false;
if (CannotUse.IsMatch(text)) Stop(text);
return false;
}
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls.</summary>
public void Render()
{
ImGui.TextDisabled("Quill of Infliction -> Enlightened Quill -> partition quill -> glyph -> Inscription scroll -> ring.");
int[] runsView = _runsView;
if (ImGui.BeginTable("##ringrecipes", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Runs", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("Recipe");
for (int i = 0; i < IltRingChain.Recipes.Length; i++)
{
var r = IltRingChain.Recipes[i];
ImGui.PushID(r.Id);
ImGui.TableNextRow();
ImGui.TableNextColumn();
int n = i < runsView.Length ? runsView[i] : 0;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("##runs", ref n, 1))
{
string id = r.Id;
int runs = Math.Clamp(n, 0, IltRingChain.MaxRuns);
var shown = (int[])runsView.Clone();
shown[i] = runs;
_runsView = shown; // shown at once; the pump saves it and republishes
_ctx.Post(() => SetRuns(id, runs));
}
ImGui.TableNextColumn();
ImGui.TextUnformatted(r.Name);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Notes);
ImGui.PopID();
}
ImGui.EndTable();
}
bool answer = G.RingAnswerCraftDialog, combat = G.RingAllowInCombat;
if (ImGui.Checkbox("Answer the craft dialog##rings", ref answer)) G.RingAnswerCraftDialog = answer;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Answers AC's craft confirmation Yes for each combine you queued (needs RynthCore plugin API v85).\nOff, or on an older RynthCore: click Yes in AC's dialog yourself.");
ImGui.SameLine();
if (ImGui.Checkbox("Allow in combat mode##rings", ref combat)) G.RingAllowInCombat = combat;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only for servers that allow crafting in combat mode.");
bool running = Running;
bool blocked = _blocked();
ImGui.BeginDisabled(running);
if (ImGui.Button("Scan##rings")) _ctx.Post(Scan);
ImGui.SameLine();
ImGui.BeginDisabled(blocked);
if (ImGui.Button("Create##rings"))
{
int[] view = _runsView;
int total = IltRingChain.Expand(id =>
{
int k = Array.FindIndex(IltRingChain.Recipes, x => x.Id == id);
return k >= 0 && k < view.Length ? view[k] : 0;
}).Count;
_ctx.Confirm("Rings chain", $"Craft {total} combine(s)?\n\nEvery Step 1 run goes first, then Step 2, then Step 3.\nThe ingredients are used up.",
Create, "Create");
}
ImGui.EndDisabled();
ImGui.EndDisabled();
ImGui.SameLine();
ImGui.BeginDisabled(!running);
if (ImGui.Button("Stop##rings")) _ctx.Post(() => Stop("stopped by player"));
ImGui.EndDisabled();
ImGui.SameLine();
if (blocked && !running) ImGui.TextColored(IltStyle.ColAmber, "the split-arrow imbuer is running");
else SafeImGui.TextDisabled(Status);
var lines = ScanLines;
if (lines.Length > 0 && ImGui.BeginTable("##ringscan", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp))
{
foreach (var l in lines)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (l.Found == null) { SafeImGui.TextColored(IltStyle.ColTeal, l.Text); continue; }
ImGui.TextUnformatted(" " + l.Text);
ImGui.TableNextColumn();
if (l.State == 0) ImGui.TextUnformatted(l.Found);
else if (l.State == 1) SafeImGui.TextDisabled(l.Found);
else SafeImGui.TextColored(IltStyle.ColAmber, l.Found);
}
ImGui.EndTable();
}
ImGui.Separator();
RenderScrolls(running || blocked);
}
/// <summary>The carried inscription scrolls: one to the selected item, or all to the carried jewelry.</summary>
private void RenderScrolls(bool busy)
{
ImGui.TextColored(IltStyle.ColTeal, "Inscription scrolls");
var scrolls = Scrolls;
if (scrolls.Length == 0) { ImGui.TextDisabled("None carried (Scan to look again)."); return; }
ImGui.BeginDisabled(busy);
foreach (var (id, name) in scrolls)
{
ImGui.PushID(id);
if (ImGui.SmallButton("Apply to selected"))
{
int scrollId = id;
string scrollName = name;
_ctx.Confirm("Ring inscription", $"Use {scrollName} on the item selected in AC?",
() => ApplyToSelected(scrollId), "Apply");
}
ImGui.SameLine();
ImGui.TextUnformatted(name);
ImGui.PopID();
}
// UB-IT pairs the scrolls with a scan's items; here the carried (not worn) jewelry.
var jewelry = _jewelry;
var targets = jewelry.Select(j => j.Id).ToList();
ImGui.BeginDisabled(targets.Count == 0);
if (ImGui.Button($"Apply all to the carried jewelry ({targets.Count})"))
{
int pairs = Math.Min(targets.Count, scrolls.Length);
_ctx.Confirm("Ring inscriptions", $"Use {pairs} inscription scroll(s) on the carried jewelry, one each?",
() => ApplyToItems(targets), "Apply");
}
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
SafeImGui.SetTooltip("Scrolls in glyph order go on the jewelry in your pack (not worn) in id order (UB-IT's pairing).\n"
+ (jewelry.Length == 0 ? "No jewelry carried (Scan to look again)."
: string.Join("\n", jewelry.Select(j => j.Name))));
ImGui.EndDisabled();
}
}

View file

@ -0,0 +1,72 @@
// IltSalvage.cs - Infinite Leaftide's own tinkering salvage, for the Mini Remote's Crafting tab.
//
// Served through RynthILT's "RynthServer.Profile" JSON (ProfileInterface.cs, the "salvage" list),
// which RynthAi's Crafting tab shows under "Server tinkering" on ILT; RynthAi itself knows no
// server's recipes. Taken from UB-IT's LeaftideImbueHelper via SilentKelpie (his RynthAi Crafting
// tab, rynth/RynthSuite PR 12, moved here 2026-10-15): the weapon crit lines (Yellow Garnet,
// Turquoise, White Quartz, Abyssal-Touched Gems, Tourmaline, Wool), Tiger Eye on missile weapons,
// Leather as the post-cap tink, the jewelry rating salvages (Silver, Copper, Green Jade,
// Tourmaline, and Serpentine + Steel sharing a cap of 10) and the trinket tiers (Diamond, Ruby,
// Gromnie Hide, Pyreal, prepared on Ammunition). ILT's recipes live in its database, so their
// chances are the server's: the Crafting runner reads the confirmation's percent.
using RynthCore.Plugin.ServerPack;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltSalvage
{
// MaterialType (131) ids.
private const int Wool = 8, BlackGarnet = 15, Diamond = 20, GreenJade = 24, Ruby = 38, TigerEye = 42, Tourmaline = 43,
Turquoise = 44, WhiteQuartz = 46, YellowGarnet = 48, Leather = 52, GromnieHide = 54, Copper = 59, Pyreal = 62,
Silver = 63, Steel = 64, Serpentine = 71;
// ILT's flag ints on the item: 2 = that salvage is on.
public const int IntJewelCopper = 370, IntJewelGreenJade = 371, IntJewelSilver = 374, IntJewelTourmaline = 375;
public const int IntTrinketDiamond = 384, IntTrinketRuby = 385, IntTrinketGromnie = 386, IntTrinketPyreal = 387;
/// <summary>Steel and Serpentine stack on ILT jewelry, at most this many combined.</summary>
public const string JewelryStackGroup = "jewelry-stack";
public const int JewelryStackCap = 10;
private const string Once = "once", Tink = "tink";
private const string PostCap = "100% tink once the 10 ordinary tinks are on";
public static readonly ServerSalvage[] Rows =
{
new("melee", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70),
new("melee", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80),
new("melee", WhiteQuartz, "Cleaving (no tink slot)", Once, UsesTinkSlot: false, Order: 90),
new("melee", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100),
new("melee", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104),
new("melee", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108),
new("melee", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true),
new("missile", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70),
new("missile", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80),
new("missile", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100),
new("missile", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104),
new("missile", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108),
new("missile", TigerEye, "+missile defense bonus", Tink, Order: 230),
new("missile", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true),
new("caster", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70),
new("caster", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80),
new("caster", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true),
// ILT keeps these in their own ints (370-376) with their own cap, not the 10 tinker slots.
new("jewelry", Silver, "+1 critical damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelSilver, Order: 10),
new("jewelry", Copper, "+1 damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelCopper, Order: 20),
new("jewelry", GreenJade, "+1 damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelGreenJade, Order: 30),
new("jewelry", Tourmaline, "+1 critical damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelTourmaline, Order: 40),
new("jewelry", Serpentine, "+1 critical rating (stacks with Steel, 10 max)", Tink, UsesTinkSlot: false, Order: 50,
StackGroup: JewelryStackGroup, StackCap: JewelryStackCap),
new("jewelry", Steel, "Steel stack tier (stacks with Serpentine, 10 max)", Tink, UsesTinkSlot: false, Order: 60,
StackGroup: JewelryStackGroup, StackCap: JewelryStackCap),
// UB-IT's trinket imbues, in its order: Diamond, Ruby, Gromnie Hide, Pyreal.
new("trinkets", Diamond, "Trinket tier: Diamond", Once, UsesTinkSlot: false, AppliedInt: IntTrinketDiamond, Prepared: true, Order: 10),
new("trinkets", Ruby, "Trinket tier: Ruby", Once, UsesTinkSlot: false, AppliedInt: IntTrinketRuby, Prepared: true, Order: 20),
new("trinkets", GromnieHide, "Trinket tier: Gromnie Hide", Once, UsesTinkSlot: false, AppliedInt: IntTrinketGromnie, Prepared: true, Order: 30),
new("trinkets", Pyreal, "Trinket tier: Pyreal", Once, UsesTinkSlot: false, AppliedInt: IntTrinketPyreal, Prepared: true, Order: 40),
};
}

View file

@ -1,20 +1,30 @@
// IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel.
// Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Character, Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws
// the tab bar (after its Remote, Quests and Pets tabs) and asks RynthILT for each tab's body
// (RynthILT.Hub GetTabs / RenderTab); "/ra hub open <section>" picks one. Guardian is a RynthCore
// ILT panel instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this
// plugin through RynthPluginRenderEmbed("guardian"). The Quests and Pets tabs are RynthAi's
// (every server: /myquests and summoning essences aren't ILT's).
// Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar
// (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub
// GetTabs / RenderTab); "/ra hub open <section>" picks one, and with RynthCore's sections rail
// RynthAi lists them as "section:<tab>" views (Inventory). Guardian is a RynthCore ILT panel
// instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this plugin through
// RynthPluginRenderEmbed("guardian"). The Pets tab is RynthAi's (every server: summoning essences
// aren't ILT's); quests are RynthOracle's.
//
// Character was a Mini Remote tab until 2026-10-13. It moved out:
// the character overview and session -> RynthOracle's Character tab ("/ro character");
// the ILT session rates -> RynthCore's Mini Remote "Session Stats" section
// (RynthILT's own surface "section:ilt-rates");
// the force-server override -> RynthCore Options > Diagnostics only.
// Its names still parse, so old links and commands land on the new home (MovedCommand). Charms and
// Banking are Infinite Leaftide's own screens and stay RynthILT's tabs.
using System;
using System.Numerics;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>ILT sections: the Mini Remote's ILT tabs, then the Guardian panel.</summary>
/// <summary>ILT sections: the Mini Remote's ILT tabs, the one that moved out, then the Guardian panel.</summary>
internal enum IltSection
{
/// <summary>Moved out (2026-10-13): RynthOracle's Character tab and the Session Stats section.</summary>
Character,
Banking,
Gear,
@ -30,12 +40,15 @@ internal static class IltSections
/// <summary>The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs).</summary>
public static readonly IltSection[] Tabs =
{
IltSection.Character, IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games,
IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games,
};
/// <summary>The Mini Remote's own tab (the remote itself): its tab id.</summary>
public const string RemoteTab = "";
/// <summary>RynthOracle's Character tab: the character overview and this session.</summary>
public const string OracleCharacterCommand = "/ro character";
public static string Label(IltSection s) => s switch
{
IltSection.Character => "Character",
@ -62,10 +75,20 @@ internal static class IltSections
_ => s.ToString().ToLowerInvariant(),
};
/// <summary>True for the sections drawn as Mini Remote tabs (all but the Guardian panel).</summary>
public static bool IsTab(IltSection s) => s != IltSection.Guardian;
/// <summary>True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games).</summary>
public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games;
/// <summary>"quests" / "pets" (and their aliases): RynthAi's universal tabs, not ILT sections.</summary>
/// <summary>
/// Where a section that moved out of the Mini Remote lives now, as the chat command that opens
/// it; null for a section that is still RynthILT's (a tab or the Guardian panel).
/// </summary>
public static string? MovedCommand(IltSection s) => s switch
{
IltSection.Character => OracleCharacterCommand,
_ => null,
};
/// <summary>"quests" / "pets" (and their aliases): not ILT sections (RynthAi's Pets tab, RynthOracle's quests).</summary>
public static bool IsUniversalTabName(string text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch
{
"quests" or "quest" or "pets" or "pet" => true,
@ -83,7 +106,7 @@ internal static class IltSections
case "games": case "game": section = IltSection.Games; return true;
case "charms": case "charm": section = IltSection.Charms; return true;
case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true;
default: section = IltSection.Character; return false;
default: section = IltSection.Gear; return false;
}
}
@ -93,7 +116,6 @@ internal static class IltSections
/// </summary>
public static Vector2 TabSize(IltSection section) => section switch
{
IltSection.Character => new Vector2(520, 440),
IltSection.Banking => new Vector2(560, 520),
IltSection.Gear => new Vector2(560, 520),
IltSection.Charms => new Vector2(560, 520),

View file

@ -7,17 +7,20 @@
// * World identity: ServerFeatureGate (RynthILT's server list, or this character's
// override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never
// switches a feature on by itself.
// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once
// ACECustom ships it. Today the server prints "Coming Soon", so:
// * Fallback: a one-shot login probe of read-only commands (/bank, /aug, /qb, /pets,
// /shinies, /xp, /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten.
// * Everything is decided on the Rynth side: the server is never asked for a feature list
// (ACECustom has none; "/ilt features" prints "Coming Soon"). IltFeatureCatalog's ILT
// profile says what the server runs, and these bits only record what the server returned:
// * Login probe: one pass of read-only commands (/bank, /aug, /qb, /pets, /shinies, /xp,
// /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten.
// /enl is NEVER probed — it opens the enlightenment confirmation dialog.
// * Passive: explicit server refusals seen in chat at any time flip a bit to Off
// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...).
// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...),
// and lines only an enabled feature sends flip it On (a summon-time pyreal refill).
// Unknown bits are treated as OFF by anything that spends currency or runs automation.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT.IltSettingsView;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -103,11 +106,23 @@ internal sealed class IltServerOptions
}
}
/// <summary>RynthCore's id for Infinite Leaftide in its server verdicts.</summary>
public const string EngineServerId = "ilt";
/// <summary>
/// True when the world is (or is declared to be) an ACECustom/ILT shard: its name is in the
/// server list (IltSettings), or this character's override is on (ServerFeatureGate).
/// RynthCore (2026.10.5.47+) decides whether this is Infinite Leaftide: one world check for
/// the engine and every plugin, with its per-character override ("/rc server ilt on|off|auto").
/// True once its first verdict has arrived (IltEngineVerdict).
/// </summary>
public bool IsIltLikeWorld
public static bool EngineDecides => IltEngineVerdict.Active.HasValue;
/// <summary>
/// RynthILT's own verdict: the world name is in the server list (IltSettings), or this
/// character's "Treat this world as ILT" is on (ServerFeatureGate). This is what the status
/// export reports to the engine, which adds it to its own detection (never echo the engine's
/// verdict back, or it would latch on).
/// </summary>
public bool IsIltLikeWorldLocal
{
get
{
@ -118,7 +133,21 @@ internal sealed class IltServerOptions
}
}
/// <summary>True while a refresh (dump or probe) is running.</summary>
/// <summary>
/// True when the world is (or is declared to be) an ACECustom/ILT shard. With a RynthCore
/// that sends server verdicts, its verdict (which already includes ours, IsIltLikeWorldLocal,
/// unless this character's override is off); otherwise our own.
/// </summary>
public bool IsIltLikeWorld
{
get
{
bool? engine = IltEngineVerdict.Active;
return engine ?? IsIltLikeWorldLocal;
}
}
/// <summary>True while the login probe is running.</summary>
public bool IsRefreshing => _refreshInFlight;
public string Source => _state.ServerOptions.Source;
@ -179,8 +208,11 @@ internal sealed class IltServerOptions
return;
}
// World not reported yet: try again next tick rather than concluding "not ILT".
if (string.IsNullOrEmpty(WorldName) && sinceLogin < WorldNameWaitMs)
// World not reported yet: try again next tick rather than concluding "not ILT". RynthCore's
// verdict trails the world name by up to a second (its push), and before its first push
// there is none: keep checking for the same window rather than conclude early.
if ((string.IsNullOrEmpty(WorldName) || EngineDecides || !IltEngineVerdict.Pushed)
&& sinceLogin < WorldNameWaitMs)
return;
_loginRefreshDone = true;
@ -189,8 +221,8 @@ internal sealed class IltServerOptions
}
/// <summary>
/// Runs the dump-then-probe refresh. Manual refreshes report progress in chat; the
/// login refresh is silent.
/// Runs the probe refresh. Manual refreshes report progress in chat; the login refresh is
/// silent.
/// </summary>
public void Refresh(bool manual)
{
@ -201,7 +233,10 @@ internal sealed class IltServerOptions
}
if (!IsIltLikeWorld)
{
if (manual) _chat("[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override).");
if (manual)
_chat(EngineDecides
? "[Mini Remote] RynthCore doesn't treat this world as Infinite Leaftide (/rc server ilt on forces it for this character; /rc server names ilt add <name> adds the world)."
: "[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override).");
return;
}
@ -210,87 +245,8 @@ internal sealed class IltServerOptions
RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')");
if (manual) _chat("[Mini Remote] Refreshing server options...");
// Step 1: structured dump. Lines start with "=== ILT Custom Features ===".
_capture.Enqueue(new IltChatRequest
{
Command = "/ilt features",
IsResponseLine = t => t.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)
|| t.Contains("ILT Custom Features", StringComparison.OrdinalIgnoreCase)
|| t.Equals("Coming Soon", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1200,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r => OnFeatureDump(r, manual),
});
}
private void OnFeatureDump(IltChatResult r, bool manual)
{
var fromDump = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
if (!line.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)) continue;
foreach (var kv in ParseFeatureLine(line))
{
Set(kv.Key, kv.Value);
fromDump.Add(kv.Key);
}
}
_state.ServerOptions.Source = fromDump.Count > 0 ? "ilt-features" : "probe";
RynthLog.Trace(LogCat.IltOptions, $"feature dump: {fromDump.Count} key(s) (timedOut={r.TimedOut}, unknown={r.UnknownCommand}) → source={_state.ServerOptions.Source}");
RunProbes(fromDump, manual);
}
/// <summary>
/// Parses "ILTFEATURE bank=1 powerball=0 charms=infinitecasting:1,guardianhand:0".
/// ServerConfig-style names ("powerball_enabled") are mapped onto Hub keys.
/// </summary>
internal static IEnumerable<KeyValuePair<string, IltTri>> ParseFeatureLine(string line)
{
string body = line.Substring("ILTFEATURE".Length).Trim();
foreach (string token in body.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
int eq = token.IndexOf('=');
if (eq <= 0) continue;
string key = token.Substring(0, eq).Trim();
string val = token.Substring(eq + 1).Trim();
if (key.Equals("charms", StringComparison.OrdinalIgnoreCase))
{
foreach (string pair in val.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
int c = pair.IndexOf(':');
if (c <= 0) continue;
yield return new(IltFeature.Charm(pair.Substring(0, c)), ParseTri(pair.Substring(c + 1)));
}
continue;
}
yield return new(MapServerKey(key), ParseTri(val));
}
}
private static IltTri ParseTri(string v)
{
v = v.Trim().ToLowerInvariant();
return v is "1" or "on" or "true" or "yes" ? IltTri.On
: v is "0" or "off" or "false" or "no" ? IltTri.Off
: IltTri.Unknown;
}
private static string MapServerKey(string key)
{
string k = key.Trim().ToLowerInvariant();
return k switch
{
"powerball_enabled" => IltFeature.Powerball,
"quest_info_enabled" => IltFeature.Quests,
"pet_device_pyreal_auto_refill_enabled" => IltFeature.PetRefill,
"pet_charm_universal_summoning_mastery_enabled" => IltFeature.UniversalMastery,
"pet_bond_enabled" => IltFeature.PetBond,
"pet_potency_enabled" => IltFeature.PetPotency,
_ => k.EndsWith("_enabled", StringComparison.Ordinal) ? k.Substring(0, k.Length - "_enabled".Length) : k,
};
_state.ServerOptions.Source = "probe";
RunProbes(manual);
}
// ── Probe ───────────────────────────────────────────────────────────────
@ -325,15 +281,13 @@ internal sealed class IltServerOptions
|| t.Contains(keyword2, StringComparison.OrdinalIgnoreCase)
|| (t.Contains(keyword, StringComparison.OrdinalIgnoreCase) && !t.StartsWith("<Tell", StringComparison.OrdinalIgnoreCase));
private void RunProbes(HashSet<string> alreadyKnown, bool manual)
private void RunProbes(bool manual)
{
var todo = Probes.Where(p => !alreadyKnown.Contains(p.Key)).ToList();
var todo = Probes.ToList();
// /enl is never probed (it pops the enlightenment confirmation). On an ILT-like
// world the command is part of ACECustom, so it is assumed present unless the
// dump said otherwise.
if (!alreadyKnown.Contains(IltFeature.Enl))
Set(IltFeature.Enl, IltTri.On);
// world the command is part of ACECustom, so it is assumed present.
Set(IltFeature.Enl, IltTri.On);
_probesOutstanding = todo.Count;
if (_probesOutstanding == 0) { CompleteRefresh(manual); return; }
@ -345,6 +299,8 @@ internal sealed class IltServerOptions
{
Command = probe.Command,
IsResponseLine = probe.IsReply,
// /aug: banner alone must not end the probe before Creature:/Item: lines arrive.
ArmsIdle = probe.Key == IltFeature.Aug ? t => IltParse.AugLine.IsMatch(t) : null,
IdleEndMs = 1500,
FirstLineTimeoutMs = 8000,
Eat = true,
@ -379,8 +335,8 @@ internal sealed class IltServerOptions
// ── Passive refusals ────────────────────────────────────────────────────
/// <summary>
/// Watches every chat line for explicit server refusals and flips the matching bit Off.
/// Cheap substring checks; runs on the pump thread.
/// Watches every chat line for explicit server refusals (bit Off) and for lines only an
/// enabled feature sends (bit On). Cheap substring checks; runs on the pump thread.
/// </summary>
public void OnChatLine(string text)
{
@ -398,8 +354,19 @@ internal sealed class IltServerOptions
Set(IltFeature.Charm("Auto-Rebuff"), IltTri.Off);
else if (text.Contains("not permitted to use bank commands", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Bank, IltTri.Off);
else if (IsPyrealRefillLine(text))
Set(IltFeature.PetRefill, IltTri.On);
}
/// <summary>
/// ACECustom's summon-time refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon). The
/// server sends them only while pet_device_pyreal_auto_refill_enabled is on, so any of them
/// proves the refill is on even when the profile says it's off.
/// </summary>
internal static bool IsPyrealRefillLine(string text)
=> text.Contains("charge on your summoning essence", StringComparison.OrdinalIgnoreCase)
|| text.Contains("pyreals to auto-replenish your summoning essence", StringComparison.OrdinalIgnoreCase);
/// <summary>Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes).</summary>
public void NoteQuestTrackerOutcome(bool disabled, int recordCount)
{

View file

@ -1,4 +1,6 @@
// IltSessionRates.cs — Session earnings / per-hour rates for the ILT Hub Character tab.
// IltSessionRates.cs — Session earnings / per-hour rates for Infinite Leaftide: the coins, pyreals and
// item conversions RynthCore's Mini Remote "Session Stats" section shows under "Server: Infinite
// Leaftide" (surface "section:ilt-rates", 2026-10-13; it was the ILT Character tab before).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Sources (all passive — nothing is sent to the server except the optional bank refresh
@ -44,7 +46,9 @@ internal sealed class IltSessionRates : IIltFeature
// Render snapshot.
private volatile RateRow[] _rows = Array.Empty<RateRow>();
private sealed record RateRow(string Label, string Total, string PerHour);
// Shared = one of RynthAi's session stats rows (XP, luminance, kills), which the Session Stats
// section already shows above this table; the embedded view leaves those out.
private sealed record RateRow(string Label, string Total, string PerHour, bool Shared = false);
/// <summary>Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample).</summary>
public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour);
@ -157,13 +161,13 @@ internal sealed class IltSessionRates : IIltFeature
var rows = new List<RateRow>();
if (_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s))
{
rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour)));
rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour)));
rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour), Shared: true));
rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour), Shared: true));
// Per hour at the last five minutes' pace.
rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0)));
rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0), Shared: true));
if (s.PassUpTracked != 0)
rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour)));
rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0")));
rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour), Shared: true));
rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0"), Shared: true));
}
rows.Add(new RateRow("Enlightened Coins", IltParse.Compact(_coins), IltParse.Compact(_coins / hours)));
rows.Add(new RateRow("Pyreals", IltParse.Compact(_pyreals), IltParse.Compact(_pyreals / hours)));
@ -189,12 +193,16 @@ internal sealed class IltSessionRates : IIltFeature
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
/// <param name="extrasOnly">
/// True in the Mini Remote's Session Stats section: RynthAi's XP / luminance / kills rows are
/// drawn there already (one session), so only the ILT coins, pyreals and items are listed.
/// </param>
public void Render(bool extrasOnly = false)
{
// The session clock is RynthAi's session stats' (it and the coins reset together).
var start = _ctx.Ai.TryGetSessionStats(out SessionStatsV1 v) && v.SessionSeconds > 0 && v.StartUtcTicks > 0
? new DateTime(v.StartUtcTicks, DateTimeKind.Utc) : _start;
ImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}");
SafeImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset##rates")) _ctx.Post(ResetAll);
@ -206,11 +214,12 @@ internal sealed class IltSessionRates : IIltFeature
ImGui.TableHeadersRow();
foreach (var r in _rows)
{
if (extrasOnly && r.Shared) continue;
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label);
if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) ImGui.SetTooltip(PassUpTooltip);
if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) SafeImGui.SetTooltip(PassUpTooltip);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total);
ImGui.TableNextColumn(); ImGui.TextColored(IltStyle.ColTeal, r.PerHour);
ImGui.TableNextColumn(); SafeImGui.TextColored(IltStyle.ColTeal, r.PerHour);
}
ImGui.EndTable();
}

View file

@ -4,7 +4,8 @@
// The list was RynthAi's Settings > Misc "Server Features" (FeatureServerNames, saved with each
// RynthAi profile). RynthILT keeps one list for every character; the first time a character
// logs in with RynthILT, IltMigration folds that character's RynthAi list into this one.
// Edited from the Character tab and "/ilt servers <list>".
// Edited with "/ilt servers <list>" (the Character tab's editor went with the tab, 2026-10-13;
// RynthCore Options > Diagnostics lists the world names RynthCore uses).
using System;
using System.Collections.Generic;
using System.IO;

View file

@ -14,6 +14,7 @@ using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -50,6 +51,9 @@ internal sealed class IltSplitArrows : IIltFeature
private IltGearState G => _ctx.State.Gear;
public bool Running => _weaponId != 0;
/// <summary>True while another ILT pack job (the Rings chain) is running: no imbue starts then.</summary>
public Func<bool>? Blocked;
private int Needed(WorldObject w)
{
var inv = _ctx.Inventory;
@ -83,6 +87,7 @@ internal sealed class IltSplitArrows : IIltFeature
{
var w = _ctx.Inventory.Cache?[weaponId];
if (w == null) { _status = "weapon not found"; return; }
if (Blocked?.Invoke() == true) { _status = "the Rings chain is running"; return; }
if (_ctx.Inventory.IsEquipped(w)) { _status = "unequip the weapon first"; return; }
int need = Needed(w);
if (need <= 0) { _status = $"{w.Name} needs no more splits"; return; }
@ -179,7 +184,7 @@ internal sealed class IltSplitArrows : IIltFeature
ImGui.SameLine();
bool skip = G.SplitIgnoreImbued;
if (ImGui.Checkbox("Skip imbued weapons", ref skip)) G.SplitIgnoreImbued = skip;
ImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}");
SafeImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}");
foreach (var w in _weapons)
{
@ -200,6 +205,6 @@ internal sealed class IltSplitArrows : IIltFeature
}
if (_weapons.Length == 0) ImGui.TextDisabled("No missile weapons carried.");
if (Running && ImGui.SmallButton("Stop imbuing")) _ctx.Post(() => Stop("stopped by player"));
ImGui.TextDisabled("Status: " + _status);
SafeImGui.TextDisabled("Status: " + _status);
}
}

View file

@ -74,7 +74,7 @@ internal sealed unsafe class RynthAiClient
if (_host.HasGetPluginInterface)
{
var t = (RynthAiHubApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion);
if (t != null && t->Version >= 1 && t->StructSize >= (uint)sizeof(RynthAiHubApiV1)) _t = t;
if (t != null && t->Version >= 1 && t->StructSize >= RynthAiHubApiV1.BaseStructSize) _t = t;
}
System.Threading.Volatile.Write(ref _renderTable, (IntPtr)_t);
return _t;

View file

@ -4,9 +4,9 @@
// One gate for everything ILT-shaped: the Mini Remote's ILT tabs, the Guardian, the Skills
// panel's Progression planners and the attribute raiser. A world is "on" when:
// * its name matches one of the server patterns (IltSettings.ServerNames, '*' wildcard,
// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers" or the Character tab
// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers"
// edits them — they were RynthAi's Settings > Misc "Server Features" list), or
// * this character's override is on (the Character tab's "Treat this world as ILT",
// * this character's override is on ("Treat this world as ILT",
// "/ra hub force on"; also set by migration from RynthAi's "Force enable" profile flag).
// The gate only decides whether RynthILT ASKS the server; each feature still follows the
// server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off.
@ -67,7 +67,11 @@ internal static class ServerFeatureGate
return true;
}
/// <summary>The gate itself: the character's override, or the world name in the list.</summary>
/// <summary>
/// RynthILT's own gate: the character's override, or the world name in the list. RynthCore's
/// verdict, once it sends one, takes over in IltServerOptions.IsIltLikeWorld; this stays ours
/// (it is what the status export reports, IltServerOptions.IsIltLikeWorldLocal).
/// </summary>
public static bool IsEnabled(string world, IltSettings? settings, bool forceOn)
=> forceOn || NameMatches(world, Patterns(settings), out _);
@ -92,6 +96,14 @@ internal static class ServerFeatureGate
{
world = (world ?? string.Empty).Trim();
string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)";
var engine = IltSettingsView.IltEngineVerdict.Server;
if (engine != null)
{
string why = engine.Force == "on" ? "forced on for this character"
: engine.Force == "off" ? "forced off for this character"
: engine.Detected ? "RynthCore recognises the world" : "RynthCore doesn't recognise the world";
return $"This world {shown}: {(engine.Active ? "ON" : "OFF")} - {why}.";
}
if (NameMatches(world, Patterns(settings), out string matched))
return $"This world {shown}: ON - matches '{matched}'.";
if (forceOn)

View file

@ -0,0 +1,62 @@
// IltFellowshipCommands.cs - Infinite Leaftide's fellowship chat commands (ACECustom /fship).
//
// ACECustom (Source/ACE.Server/Command/Handlers/PlayerCommands.cs, "fship") adds these on top
// of retail's fellowship panel; its fellowships hold up to 29 (Fellowship.MaxFellows). The list
// is kept in the shared "servercommands" form (Plugins/Shared/ServerCommandShare.cs) and drawn by
// RynthILT's fellowship window (IltFellowshipUi, "/ilt fellow").
// A name with spaces is sent quoted; ACE's command parser joins "two words". Pure: no ImGui, no host.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltFellowship;
internal static class IltFellowshipCommands
{
/// <summary>The RynthCore section the commands belong to.</summary>
public const string Section = "fellowship";
/// <summary>RynthCore's server id for Infinite Leaftide.</summary>
public const string ServerId = "ilt";
/// <summary>The server's display name.</summary>
public const string ServerName = "Infinite Leaftide";
/// <summary>ACECustom's fellowship size (Fellowship.MaxFellows; retail is 9).</summary>
public const int MaxFellows = 29;
/// <summary>The /fship commands, in button order.</summary>
public static readonly IReadOnlyList<ServerCommand> Commands = new[]
{
new ServerCommand("Create", "/fship create", "A",
"Create a fellowship with the name in the box (you lead it). Up to " + MaxFellows + " members on ILT."),
new ServerCommand("Invite", "/fship add", "a",
"Invite the player named in the box, or your selected player when the box is empty."),
new ServerCommand("Dismiss", "/fship remove", "ac",
"Leader: remove the player named in the box, or your selected player when the box is empty."),
new ServerCommand("Invite landblock", "/fship landblock", "c",
"Invite every player in your landblock (not in the Marketplace). Over level 50, only level 50+ players are invited."),
new ServerCommand("List nearby", "/fship list", "",
"The fellowships in your area and their leaders (wider in VOD and T10). Once every 10 seconds."),
new ServerCommand("Leave", "/fship leave", "c",
"Leave your fellowship."),
new ServerCommand("Disband", "/fship disband", "c",
"Leader: disband your fellowship."),
new ServerCommand("Help", "/fship", "",
"The server's /fship help."),
};
/// <summary>The set while ILT is active; with no commands when it isn't (a receiver drops it).</summary>
public static ServerCommandSet Set(bool active) =>
new(Section, ServerId, ServerName, active ? Commands : Array.Empty<ServerCommand>());
/// <summary>The "servercommands" payload for <see cref="Set"/>.</summary>
public static string Payload(bool active) => ServerCommandShare.Build(Set(active));
/// <summary>
/// ILT is active: RynthCore's verdict once it has sent one (<paramref name="engineActive"/>),
/// else the world name has "Leaftide" in it (RynthCore's default ILT names).
/// </summary>
public static bool IsActive(bool? engineActive, string? worldName) =>
engineActive ?? (worldName ?? string.Empty).IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0;
}

View file

@ -0,0 +1,44 @@
// IltFellowshipUi.cs - The "ILT fellowship" view: Infinite Leaftide's /fship commands as buttons.
//
// Drawn in its own window ("/ilt fellow"). Clicks queue the chat command for the plugin tick.
// Render thread only.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltFellowship;
internal sealed class IltFellowshipUi
{
private const string WindowTitle = "ILT fellowship (RynthILT)##rynthilt_fellowship";
private static readonly ServerCommandSet Set = IltFellowshipCommands.Set(active: true);
private readonly ServerCommandPanel _panel = new("iltfship");
private readonly Func<string, bool> _send;
/// <summary>The standalone window is open ("/ilt fellow").</summary>
public bool WindowOpen;
/// <param name="send">Queues a chat command for the plugin tick; false when it can't.</param>
public IltFellowshipUi(Func<string, bool> send) => _send = send;
/// <summary>The standalone window, while open.</summary>
public void RenderWindow()
{
if (!WindowOpen) return;
ImGui.SetNextWindowSize(new Vector2(420, 170), ImGuiCond.FirstUseEver);
bool open = WindowOpen;
if (ImGui.Begin(WindowTitle, ref open)) RenderBody();
ImGui.End();
WindowOpen = open;
}
/// <summary>The view's content, into the current window.</summary>
public void RenderBody()
{
SafeImGui.TextDisabled("Infinite Leaftide /fship (up to " + IltFellowshipCommands.MaxFellows + " members)");
_panel.Render(Set, _send);
}
}

View file

@ -0,0 +1,32 @@
// IltEngineVerdict.cs - RynthCore's Infinite Leaftide verdict as RynthILT last heard it.
//
// RynthCore decides whether this world is ILT once, for itself and every plugin, with this
// character's Auto / On / Off override ("/rc server ilt"). RynthILT reads that verdict from the
// engine's server list (plugin API v86, GetServerStateJson; the plugin tick polls it into
// IltSettingsModel.Engine). The Hub's world check (IltServerOptions, ServerFeatureGate) follows it
// once one has arrived; before that, or on an engine older than v86, RynthILT's own server list
// and "Treat this world as ILT" decide.
//
// RynthILT's status export must keep reporting its own verdict, not this one: the engine adds
// RynthILT's verdict to its detection, and an echo would keep ILT on after "/rc ilt auto".
// Any thread: one volatile reference read.
using System.Threading;
namespace RynthCore.Plugin.RynthILT.IltSettingsView;
internal static class IltEngineVerdict
{
private static IltSettingsModel? _model;
/// <summary>The model the plugin feeds from RynthCore's server list (RynthILTPlugin's constructor).</summary>
public static void Attach(IltSettingsModel? model) => Volatile.Write(ref _model, model);
/// <summary>RynthCore has sent its server list at least once since login (it may list no ILT).</summary>
public static bool Pushed => Volatile.Read(ref _model)?.Engine != null;
/// <summary>RynthCore's ILT entry; null until a RynthCore with the server list (v86) has sent one.</summary>
public static IltServerView? Server => Volatile.Read(ref _model)?.Engine?.Server;
/// <summary>RynthCore's verdict for this world; null when it hasn't given one.</summary>
public static bool? Active => Server?.Active;
}

View file

@ -0,0 +1,114 @@
// IltSettingsModel.cs - RynthILT's copy of the Infinite Leaftide settings (the "ILT settings" view).
//
// Nothing here is decided by RynthILT; it shows and edits what others own:
// * RynthCore owns the world verdict, this character's Auto / On / Off override and the ILT
// world-name list. RynthILT reads the verdict from its server list (plugin API v86,
// GetServerStateJson, parsed by Plugins/Shared/EngineServerState.cs): the plugin tick polls
// it every 2 s and publishes the "ilt" entry here (ApplyServerState). The world names aren't
// in that list; "/rc server names ilt" prints them. Edits go back as RynthCore commands:
// "/rc server ilt auto|on|off" and "/rc server names ilt add|remove <pattern>".
// * RynthILT's own Hub reads which ILT features the server has on; the plugin tick publishes
// them (PublishFeatures).
// Each is one immutable snapshot published with a single reference write, so the render thread
// always reads a whole one. Pure (no host calls): RynthILT.Tests covers it.
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltSettingsView;
/// <summary>RynthCore's verdict for Infinite Leaftide.</summary>
internal sealed record IltServerView(string Name, bool Active, string Force, bool Detected, string Reason);
/// <summary>What RynthCore's server list says: the ILT verdict (null if it lists no "ilt").</summary>
internal sealed record IltEngineView(IltServerView? Server);
/// <summary>The Hub's server read: the world, its last check, and each feature (-1 unknown, 0 off, 1 on).</summary>
internal sealed record IltFeatureView(string World, string Source, string LastCheck, bool Checking, bool IltLike,
KeyValuePair<string, int>[] Features);
internal sealed class IltSettingsModel
{
/// <summary>RynthCore's id for Infinite Leaftide.</summary>
public const string ServerId = EngineServerState.IltId;
/// <summary>Longest pattern RynthCore keeps (EngineSettings.MaxIltServerNameLength).</summary>
public const int MaxPattern = 64;
/// <summary>The RynthCore command that prints the ILT world names (and hosts) in chat.</summary>
public const string NamesListCommand = "/rc server names " + ServerId;
private IltEngineView? _engine;
private IltFeatureView? _features;
/// <summary>The last server list from RynthCore (null until one arrives). Any thread.</summary>
public IltEngineView? Engine => Volatile.Read(ref _engine);
/// <summary>The last feature read (null until the Hub publishes one). Any thread.</summary>
public IltFeatureView? Features => Volatile.Read(ref _features);
/// <summary>RynthCore's server list (GetServerStateJson); null (no answer) keeps the last one. Any thread.</summary>
public void ApplyServerState(EngineServerState? state)
{
IltEngineView? view = FromServerState(state);
if (view != null) Volatile.Write(ref _engine, view);
}
/// <summary>The Hub's own feature read (plugin tick); null clears it. Any thread.</summary>
public void PublishFeatures(IltFeatureView? view) => Volatile.Write(ref _features, view);
/// <summary>Logout: the next character's world and features come fresh.</summary>
public void Clear()
{
Volatile.Write(ref _engine, null);
Volatile.Write(ref _features, null);
}
/// <summary>The ILT verdict from RynthCore's server list; null for no list.</summary>
public static IltEngineView? FromServerState(EngineServerState? state)
{
if (state == null) return null;
EngineServer? s = state.Find(ServerId);
return new IltEngineView(s == null ? null
: new IltServerView(s.Name.Length > 0 ? s.Name : "Infinite Leaftide", s.Active, NormalizeForce(s.Force), s.Detected, s.Reason));
}
/// <summary>"auto", "on" or "off" (anything else is shown as auto).</summary>
public static string NormalizeForce(string? force) => (force ?? string.Empty).Trim().ToLowerInvariant() switch
{
"on" => "on",
"off" => "off",
_ => "auto",
};
/// <summary>The RynthCore command that sets this character's override; "" for an unknown mode.</summary>
public static string ForceCommand(string mode) => mode switch
{
"auto" or "on" or "off" => "/rc server " + ServerId + " " + mode,
_ => string.Empty,
};
/// <summary>
/// The RynthCore command that adds or removes a world-name pattern, or "" (with
/// <paramref name="error"/>) when the pattern can't be sent: empty, longer than
/// <see cref="MaxPattern"/>, or with a control character or '/' (it is spliced into a command).
/// </summary>
public static string NamesCommand(bool add, string? pattern, out string error)
{
error = string.Empty;
string p = (pattern ?? string.Empty).Trim();
if (p.Length == 0) { error = "Enter a world name ('*' matches any text)."; return string.Empty; }
if (p.Length > MaxPattern) { error = $"At most {MaxPattern} characters."; return string.Empty; }
foreach (char c in p)
if (char.IsControl(c) || c == '/' || c >= 128)
{
error = "World names are plain text (no '/', line breaks or special characters).";
return string.Empty;
}
return "/rc server names " + ServerId + (add ? " add " : " remove ") + p;
}
/// <summary>A feature's state as text.</summary>
public static string StateText(int value) => value switch { 1 => "on", 0 => "off", _ => "unknown" };
}

View file

@ -0,0 +1,198 @@
// IltSettingsUi.cs - The "ILT settings" view: RynthILT's copy of the Infinite Leaftide settings.
//
// Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's
// Auto / On / Off override, the ILT world names (edited through RynthCore), and every ILT feature
// with the state RynthILT's Hub read from the server (IltSettingsModel has where each comes from).
// Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the
// result. Render thread only.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltSettingsView;
internal sealed class IltSettingsUi
{
private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f);
private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f);
private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f);
private const string WindowTitle = "ILT settings (RynthILT)##rynthilt_settings";
private readonly IltSettingsModel _model;
private readonly Action<string> _runCommand;
private readonly Func<bool> _refreshFeatures;
private string _newName = string.Empty;
private string _status = string.Empty;
/// <summary>The standalone window is open ("/ilt settings").</summary>
public bool WindowOpen;
/// <param name="runCommand">Queues a RynthCore command (run on the plugin tick).</param>
/// <param name="refreshFeatures">Asks the Hub to read the server's features again; false before it exists.</param>
public IltSettingsUi(IltSettingsModel model, Action<string> runCommand, Func<bool> refreshFeatures)
{
_model = model;
_runCommand = runCommand;
_refreshFeatures = refreshFeatures;
}
/// <summary>The standalone window, while open.</summary>
public void RenderWindow()
{
if (!WindowOpen) return;
ImGui.SetNextWindowSize(new Vector2(440, 480), ImGuiCond.FirstUseEver);
bool open = WindowOpen;
if (ImGui.Begin(WindowTitle, ref open)) RenderBody();
ImGui.End();
WindowOpen = open;
}
/// <summary>The view's content, into the current window.</summary>
public void RenderBody()
{
RenderVerdict();
ImGui.Separator();
RenderFeatures();
if (_status.Length > 0)
{
ImGui.Separator();
SafeImGui.TextWrapped(_status);
}
}
private void RenderVerdict()
{
IltEngineView? engine = _model.Engine;
if (engine == null)
{
ImGui.TextWrapped("Waiting for RynthCore's server list (it needs plugin API v86). Until then RynthILT's own "
+ "world list and this character's 'Treat this world as ILT' (/ra hub force on|off) decide.");
return;
}
IltServerView? s = engine.Server;
if (s == null)
{
ImGui.TextDisabled("RynthCore doesn't list Infinite Leaftide.");
}
else
{
SafeImGui.TextColored(s.Active ? Teal : Mute, s.Active ? s.Name + ": on for this world" : s.Name + ": not this world");
if (s.Reason.Length > 0)
{
ImGui.PushStyleColor(ImGuiCol.Text, Mute);
SafeImGui.TextWrapped(s.Reason);
ImGui.PopStyleColor();
}
// Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13).
string force = s.Force switch { "on" => "forced on", "off" => "forced off", _ => "auto (detected)" };
SafeImGui.TextDisabled("This character: " + force + " (change it in RynthCore Options > Diagnostics)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\nor /rc server ilt auto|on|off in chat.");
}
ImGui.Spacing();
ImGui.TextUnformatted("ILT world names");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Worlds whose name matches one of these count as Infinite Leaftide ('*' matches any text).\nThe launch host is checked too. Kept by RynthCore for every character.");
ImGui.SameLine();
if (ImGui.SmallButton("List in chat##iltnames"))
{
_runCommand(IltSettingsModel.NamesListCommand);
_status = "RynthCore lists the names in chat (" + IltSettingsModel.NamesListCommand + ").";
}
ImGui.SetNextItemWidth(220);
bool enter = ImGui.InputTextWithHint("##iltnewname", "world name, * = any text", ref _newName, (uint)IltSettingsModel.MaxPattern,
ImGuiInputTextFlags.EnterReturnsTrue);
ImGui.SameLine();
if (ImGui.Button("Add##iltname") || enter)
{
string cmd = IltSettingsModel.NamesCommand(true, _newName, out string err);
if (Send(cmd, err, "Adding '" + _newName.Trim() + "'...")) _newName = string.Empty;
}
ImGui.SameLine();
if (ImGui.Button("Remove##iltname"))
{
string cmd = IltSettingsModel.NamesCommand(false, _newName, out string err);
if (Send(cmd, err, "Removing '" + _newName.Trim() + "'...")) _newName = string.Empty;
}
}
/// <summary>
/// The server's ILT features, one collapsible section per group (Character, Items, Pets,
/// Fellowship, Combat, Activities, then the charms and any other bit chat or a probe set), with
/// how many are on and each feature's state; the tooltip says where the Rynth tools handle it.
/// </summary>
private void RenderFeatures()
{
IltFeatureView? f = _model.Features;
ImGui.TextUnformatted("Server features");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##iltfeatures"))
_status = _refreshFeatures() ? "Checking the server again..." : "Not ready yet (log in first).";
if (f == null)
{
ImGui.TextWrapped("RynthILT reads which ILT features the server has on once this character is logged in. Not read yet.");
return;
}
string when = f.Checking ? "checking the server..." : f.LastCheck.Length == 0 ? "not checked yet" : "checked " + f.LastCheck;
SafeImGui.TextDisabled((f.World.Length > 0 ? f.World : "unknown world") + " - " + when
+ (f.Source.Length > 0 ? " (" + f.Source + ")" : string.Empty));
if (!f.IltLike) ImGui.TextDisabled("This world isn't treated as Infinite Leaftide, so the server isn't asked.");
if (f.Features.Length == 0)
{
ImGui.TextDisabled("The server hasn't reported any ILT features yet.");
return;
}
var groups = new Dictionary<string, List<(string Label, string Tooltip, int State)>>(StringComparer.Ordinal);
foreach (var kv in f.Features)
{
var (label, group, tooltip) = IltFeatureCatalog.Describe(kv.Key);
if (!groups.TryGetValue(group, out var rows)) groups[group] = rows = new();
rows.Add((label, tooltip, kv.Value));
}
foreach (string group in FeatureGroups())
{
if (!groups.TryGetValue(group, out var rows)) continue;
int on = 0, off = 0;
foreach (var r in rows) { if (r.State == 1) on++; else if (r.State == 0) off++; }
if (!ImGui.CollapsingHeader($"{group} ({on} of {rows.Count} on)##iltfg_{group}")) continue;
for (int i = 0; i < rows.Count; i++)
{
var r = rows[i];
SafeImGui.TextColored(r.State == 1 ? Teal : r.State == 0 ? Warn : Mute, IltSettingsModel.StateText(r.State));
ImGui.SameLine(80);
SafeImGui.Text(r.Label);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Tooltip);
}
}
}
/// <summary>The feature sections in display order: the catalog's groups, then Charms and Other.</summary>
private static IEnumerable<string> FeatureGroups()
{
foreach (string g in IltFeatureCatalog.Groups) yield return g;
yield return IltFeatureCatalog.GroupCharms;
yield return IltFeatureCatalog.GroupOther;
}
/// <summary>Queues <paramref name="command"/>, or shows <paramref name="error"/> when it is empty.</summary>
private bool Send(string command, string error, string pending)
{
if (command.Length == 0)
{
_status = error;
return false;
}
_runCommand(command);
_status = pending;
return true;
}
}

View file

@ -11,8 +11,12 @@ public static unsafe class PluginExports
{
internal static readonly RynthPluginRuntime<RynthILTPlugin> Runtime = new();
// Typed interface for RynthAi (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT
// tabs and sections its Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.cs).
// Typed interfaces (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT tabs and
// sections RynthAi's Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.cs), and
// "RynthServer.Profile" v1, ILT's settings and tinkering salvage for any reader, as every server
// plugin serves its own (Plugins/Shared/RynthServerProfileApi.cs, ProfileInterface.cs), and
// "RynthILT.Data" v1, the charms list and bank balances with their actions
// (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs).
// Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
@ -20,7 +24,10 @@ public static unsafe class PluginExports
try
{
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
return HubInterface.Query(iface, version);
IntPtr table = HubInterface.Query(iface, version);
if (table != IntPtr.Zero) return table;
table = ProfileInterface.Query(iface, version);
return table != IntPtr.Zero ? table : DataInterface.Query(iface, version);
}
catch
{
@ -37,9 +44,12 @@ public static unsafe class PluginExports
// An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT.
try { Runtime.Shutdown(); } catch { }
try { HubInterface.Release(); } catch { }
try { ProfileInterface.Release(); } catch { }
try { DataInterface.Release(); } catch { }
foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero),
Interlocked.Exchange(ref _statusPtr, IntPtr.Zero) })
Interlocked.Exchange(ref _statusPtr, IntPtr.Zero), Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) })
if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p);
_sectionsJson = null;
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
@ -76,9 +86,13 @@ public static unsafe class PluginExports
/// <summary>
/// Engine panels drawn by RynthILT (render thread): "guardian" is the engine's Guardian ILT
/// panel (RynthCore's GuardianFace); ":popout" is added when it is popped out into a window of
/// its own, and RynthILT draws in the engine's current context either way. The panel is
/// user-sized: want echoes the size given. 1 = drawn, 0 = not ready / unknown surface.
/// panel (RynthCore's GuardianFace); "section:ilt-rates" (the ILT session extras, Session Stats),
/// "section:ilt-fellowship" (the /fship commands), "section:ilt-questbonus" (the /qb list,
/// RynthILT's Quests section) and "section:ilt-settings" (the ILT settings, for an engine that
/// still asks) are RynthCore's Mini Remote sections. ":popout" is added when one is popped out
/// into a window of its own, and RynthILT draws in the engine's current context either way. The
/// Guardian panel is user-sized (want echoes the size given); a section reports the height it
/// used. 1 = drawn, 0 = not ready / unknown surface.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
@ -88,16 +102,28 @@ public static unsafe class PluginExports
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length];
if (!name.SequenceEqual("guardian"u8)) return 0;
var plugin = Runtime.Plugin;
if (plugin == null || !plugin.RenderEmbeddedGuardian()) return 0;
if (plugin == null) return 0;
if (name.SequenceEqual("guardian"u8))
{
if (!plugin.RenderEmbeddedGuardian()) return 0;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = height;
return 1;
}
string? view = name.SequenceEqual("section:ilt-settings"u8) ? RynthILTPlugin.SettingsSurface
: name.SequenceEqual("section:ilt-fellowship"u8) ? RynthILTPlugin.FellowshipSurface
: name.SequenceEqual("section:ilt-rates"u8) ? RynthILTPlugin.RatesSurface
: name.SequenceEqual("section:ilt-questbonus"u8) ? RynthILTPlugin.QuestBonusSurface
: null;
if (view == null || !plugin.RenderEmbedded(view, out float wantH)) return 0;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = height;
if (wantHeight != null) *wantHeight = wantH;
return 1;
}
catch
{
return 0;
return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client
}
}
@ -191,11 +217,20 @@ public static unsafe class PluginExports
try
{
string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length > 32) return;
var plugin = Runtime.Plugin;
if (plugin == null) return;
if (RynthILTPlugin.IsParsedRemoteAction(action))
{
// RynthCore's "servermenu" push (a few KB): answered here, never queued as an ILT verb.
plugin.ApplyRemoteCommand(action, valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty);
return;
}
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length + value.Length > 512) return;
Runtime.Plugin?.EnqueueRemoteCommand(action, value);
if (action.Length + value.Length > 512) return;
plugin.EnqueueRemoteCommand(action, value);
}
catch { }
catch { /* never let a managed exception cross the native boundary */ }
}
private static IntPtr _statusPtr = IntPtr.Zero;
@ -203,8 +238,9 @@ public static unsafe class PluginExports
/// <summary>
/// What RynthILT knows about the world (UTF-8 JSON, previous reply valid until the next call):
/// {"loaded":true,"ilt":bool,"forced":bool,"available":bool,"world":"..."}. "ilt" is RynthILT's
/// own verdict (its server list or this character's "Treat this world as ILT"); the engine's
/// IltInfo adds it to its own detection. Engine pump thread.
/// own verdict (its server list or this character's "Treat this world as ILT"), never the
/// engine's verdict echoed back: the engine's IltInfo adds it to its own detection, and an
/// echo would keep ILT on after "/rc ilt auto". Engine pump thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTGetStatusJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetStatusJson()
@ -214,7 +250,7 @@ public static unsafe class PluginExports
var hub = Runtime.Plugin?.Hub;
string json = hub == null
? "{\"loaded\":true,\"ilt\":false,\"forced\":false,\"available\":false,\"world\":\"\"}"
: "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorld ? "true" : "false")
: "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorldLocal ? "true" : "false")
+ ",\"forced\":" + (hub.ForceIltWorld ? "true" : "false")
+ ",\"available\":" + (hub.Available ? "true" : "false")
+ ",\"world\":\"" + RynthCore.Plugin.RynthILT.Hub.IltStyle.JsonEscape(hub.Options.WorldName) + "\"}";
@ -223,6 +259,28 @@ public static unsafe class PluginExports
catch { return IntPtr.Zero; }
}
private static IntPtr _sectionsPtr = IntPtr.Zero;
private static string? _sectionsJson;
/// <summary>
/// RynthCore 2026.10.5.46+ (optional): what RynthILT adds to the Mini Remote's sections (UTF-8
/// JSON, schema 1; RynthILTPlugin.BuildSectionsJson). Null before login. An unchanged manifest
/// keeps the same buffer.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSectionsJson()
{
try
{
string? json = Runtime.Plugin?.BuildSectionsJson();
if (json == null) return IntPtr.Zero;
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
_sectionsJson = json;
return Utf8Swap(ref _sectionsPtr, json);
}
catch { return IntPtr.Zero; }
}
private static IntPtr Utf8Swap(ref IntPtr slot, string json)
{
IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json);

View file

@ -0,0 +1,102 @@
// ProfileInterface.cs - RynthILT's side of "RynthServer.Profile" (Plugins/Shared/RynthServerProfileApi.cs):
// Infinite Leaftide's settings as JSON for other plugins, the same interface and JSON writer the
// server plugins use (Plugins/Shared/ServerPack/ServerPackProfile.cs). RynthCore's GetServerStateJson
// names RynthILT as the owner of "ilt"; a reader (RynthAi's Crafting tab, ...) then asks it for this.
// The profile carries ILT's tinkering salvage (Hub/IltSalvage.cs).
//
// As ServerPackInterface: the table is allocated once per loaded copy of RynthILT and never freed;
// after Release() it reports Version 0 and GetProfileJson answers 0. Before the Hub is up the profile
// still describes the server (active false, no world).
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT;
internal static unsafe class ProfileInterface
{
private static RynthServerProfileApiV1* _table;
private static volatile bool _released;
/// <summary>What RynthILT knows about its server (identity from the csproj's manifest properties).</summary>
internal static readonly ServerPackInfo Info =
new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames)
{
Emulator = "ACE",
Salvage = IltSalvage.Rows,
Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)",
};
/// <summary>The last JSON handed out, and what it was built for (rebuilt only when that changes).</summary>
private sealed record Snapshot(bool Active, string World, string Json);
private static Snapshot? _last;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1));
t->StructSize = (uint)sizeof(RynthServerProfileApiV1);
t->GetProfileJson = &GetProfileJson;
t->Version = RynthServerProfileApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
}
/// <summary>
/// The JSON to hand out for RynthILT's verdict (<paramref name="active"/>) and the world name.
/// Any thread.
/// </summary>
internal static string CurrentJson(bool active, string? world)
{
world ??= string.Empty;
Snapshot? last = Volatile.Read(ref _last);
if (last != null && last.Active == active && last.World == world) return last.Json;
string json = ServerPackProfile.BuildJson(Info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world);
Volatile.Write(ref _last, new Snapshot(active, world, json));
return json;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetProfileJson(byte* buffer, int capacity)
{
try
{
if (_released) return 0;
IltHubController? hub = PluginExports.Runtime.Plugin?.Hub;
string json = CurrentJson(hub?.Options.IsIltLikeWorld == true, hub?.Options.WorldName);
return Write(json, buffer, capacity);
}
catch { return 0; }
}
/// <summary>
/// Copies <paramref name="json"/> as NUL-terminated UTF-8 into the caller's buffer when it fits,
/// and returns its byte length either way (length >= capacity: too small, nothing written).
/// </summary>
internal static int Write(string json, byte* buffer, int capacity)
{
int length = Encoding.UTF8.GetByteCount(json);
if (buffer == null || capacity <= length) return length;
fixed (char* src = json)
Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity);
buffer[length] = 0;
return length;
}
}

View file

@ -5,12 +5,16 @@
not in RynthAi or the engine core. The engine shows its panels (the bar's ILT button: Bounties,
Guardian; /rc bounties, /rc guardian; the Skills panel's Progression tab) only on ILT
(RynthCore Compatibility/IltInfo.cs, which also asks RynthILT).
Bounty/ the Bounties window's tracker (ported from SilentKelpie's rynth/RynthSuite PR #11).
Hub/ the ILT Hub (SilentKelpie's): the Mini Remote's ILT tabs (Character, Banking, Gear,
Charms, Games), the Guardian, the progression planners and the attribute raiser,
server feature detection. Moved out of RynthAi 2026-10-13: RynthAi's Mini Remote
hosts the tabs through RynthILT.Hub, and RynthILT borrows from RynthAi through
RynthAi.Hub (Plugins/Shared/RynthIltHubApi.cs, RynthAiHubApi.cs).
Bounty/ the Bounties window's tracker (ported from SilentKelpie's rynth/RynthSuite PR #11).
Hub/ the ILT Hub (SilentKelpie's): the Mini Remote's ILT tabs (Character, Banking, Gear,
Charms, Games), the Guardian, the progression planners and the attribute raiser,
server feature detection, the Rings inscription chain (Gear tab). Moved out of
RynthAi 2026-10-13: RynthAi's Mini Remote hosts the tabs through RynthILT.Hub, and
RynthILT borrows from RynthAi through RynthAi.Hub (Plugins/Shared/RynthIltHubApi.cs,
RynthAiHubApi.cs).
IltSettingsView/ a copy of the ILT settings (RynthCore's verdict, this character's override, the
ILT world names, the Hub's feature read) in its own window ("/ilt settings").
IltFellowship/ ILT's /fship commands as buttons ("/ilt fellow").
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
@ -29,10 +33,17 @@
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Nothing above the v66 baseline: every
newer call (plugin interfaces v68, live object ids v69, vendor trade v67, ...) is behind
its Has* check, as it was in RynthAi. -->
newer call (plugin interfaces v68, live object ids v69, vendor trade v67, confirmation
answers v85, the server list v86, ...) is behind its Has* check, as it was in RynthAi. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games), the Guardian, bounties, progression and the attribute raiser.</RynthPluginDescription>
<!-- RynthILT is ILT's server plugin: RynthCore loads it only for clients connecting to ILT, or late
when the world announces an ILT name (SilentKelpie's server plugins). Same lists as RynthCore's
IltDetect defaults. -->
<RynthPluginServerId>ilt</RynthPluginServerId>
<RynthPluginServerName>Infinite Leaftide</RynthPluginServerName>
<RynthPluginServerHosts>infiniteleaftide.online</RynthPluginServerHosts>
<RynthPluginServerWorldNames>InfiniteLeaftide|*Leaftide*</RynthPluginServerWorldNames>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games), the Guardian, bounties, progression, the attribute raiser, the ring inscription chain, the ILT settings and the /fship fellowship commands.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
@ -45,8 +56,19 @@
<!-- The two interfaces between RynthILT and RynthAi (linked into both plugins). -->
<Compile Include="..\Shared\RynthIltHubApi.cs" Link="Shared\RynthIltHubApi.cs" />
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<!-- "RynthILT.Data": the charms list and bank balances for other plugins (DataInterface.cs). -->
<Compile Include="..\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
<!-- RynthCore's server list (API v86): the ILT verdict the Hub follows (IltSettingsView/). -->
<Compile Include="..\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
<!-- "RynthServer.Profile": ILT's settings and tinkering salvage (Hub/IltSalvage.cs) for other
plugins (ProfileInterface.cs), with the server plugins' own record and JSON writer. -->
<Compile Include="..\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
<Compile Include="..\Shared\ServerPack\ServerPackInfo.cs" Link="ServerPack\ServerPackInfo.cs" />
<Compile Include="..\Shared\ServerPack\ServerPackProfile.cs" Link="ServerPack\ServerPackProfile.cs" />
<!-- ImGui.NET bound to the engine's cimgui (the tabs draw inside RynthAi's Mini Remote). -->
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<!-- ImGui text calls for non-literal text ('%' escaped; RynthAi links the same file). -->
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- Install-folder resolver (the ILT Hub files left in the RynthAi folder). -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- One logged, guarded way to use an object (the Guardian's vendor). -->
@ -56,6 +78,9 @@
<Compile Include="..\Shared\DataWriteGuard.cs" Link="Shared\DataWriteGuard.cs" />
<!-- AcObjectClass (the item classes the gear tools check). -->
<Compile Include="..\..\Shared\RynthCore.LootSdk\AcGameEnums.cs" Link="Shared\AcGameEnums.cs" />
<!-- ILT's /fship commands (IltFellowship/): the shared command list format and its button panel. -->
<Compile Include="..\Shared\ServerCommandShare.cs" Link="Shared\ServerCommandShare.cs" />
<Compile Include="..\Shared\ServerCommandPanel.cs" Link="Shared\ServerCommandPanel.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -5,17 +5,33 @@
// /rc bounties). Its reads run only while that window polls RynthILTGetBountiesJson, and the
// engine polls only on ILT.
// * The ILT Hub (Hub/, SilentKelpie's, moved here from RynthAi 2026-10-13): the Mini Remote's
// ILT tabs (Character, Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through
// RynthILT.Hub, HubInterface.cs), their sections in its Quests / Pets / Remote tabs, the
// Guardian panel (RynthPluginRenderEmbed "guardian"), the Skills panel's Progression data
// (RynthILTGetProgressionJson, "prog ..." through RynthILTCommand), server feature detection.
// Every feature stays dormant off an ILT-like world (IltServerOptions: no probes, no chat).
// ILT tabs (Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through
// RynthILT.Hub, HubInterface.cs, and lists them on RynthCore's sections rail; the Gear tab has
// the Rings inscription chain; the Character tab moved to RynthOracle's Character tab), its
// own Mini Remote sections (BuildSectionsJson: the ILT session extras in Session Stats, the
// /fship buttons in Fellowship, the /qb list in a Quests section), its sections in RynthAi's
// Pets / Remote tabs, the Guardian panel (RynthPluginRenderEmbed "guardian"),
// the Skills panel's Progression data (RynthILTGetProgressionJson, "prog ..." through
// RynthILTCommand), server feature detection, and the charms and bank balances for other
// plugins ("RynthILT.Data", DataInterface.cs). Every feature stays dormant off an ILT-like
// world (IltServerOptions: no probes, no chat).
//
// Second: a copy of the ILT settings (IltSettingsView/): RynthCore's verdict, this character's
// override (read only: it is set in RynthCore Options > Diagnostics), the ILT world names and
// every feature the Hub read from the server, in its own window ("/ilt settings"). The verdict
// comes from RynthCore's server list (plugin API v86, polled every 2 s), and the Hub follows it
// once one arrives (IltEngineVerdict).
//
// Third: ILT's fellowship commands (IltFellowship/, ACECustom /fship) as buttons in RynthCore's
// Fellowship section and their own window ("/ilt fellow"). While ILT is active the list is also
// sent to RynthAi ("servercommands"), whose Fellowship view draws them; an empty list clears it.
//
// Threads: OnTick, OnChatWindowText, OnKillNotification, login/logout and the engine's export calls
// run on the plugin pump. OnChatBarEnter runs on AC's main thread (the engine's dispatcher queues it
// there, our own InvokeChatParser too), and RynthAi forwards its "/ra hub ..." verbs from there too,
// so commands only queue and run on the next tick. OnRender / RenderEmbed and the RynthILT.Hub
// render functions run on the render thread and only read what the pump built.
// render functions run on the render thread and only read what the pump built; the settings and
// fellowship windows queue their chat commands for the tick.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -24,6 +40,8 @@ using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Plugin.RynthILT.Bounty;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.RynthILT.IltFellowship;
using RynthCore.Plugin.RynthILT.IltSettingsView;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
@ -32,7 +50,51 @@ namespace RynthCore.Plugin.RynthILT;
public sealed class RynthILTPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.0");
// Previous release: 0.3.1.
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.2");
/// <summary>
/// The settings view's surface. Not in the sections manifest (the force-server override lives
/// only in RynthCore Options > Diagnostics), but still drawn for an engine that asks.
/// </summary>
internal const string SettingsSurface = "section:ilt-settings";
/// <summary>The ILT session extras' surface in RynthCore's Mini Remote "Session Stats" section.</summary>
internal const string RatesSurface = "section:ilt-rates";
/// <summary>The fellowship commands' surface in RynthCore's Fellowship section.</summary>
internal const string FellowshipSurface = "section:ilt-fellowship";
/// <summary>
/// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (it was part of
/// RynthAi's Quests tab, which moved to RynthOracle; Infinite Leaftide's /qb stays RynthILT's).
/// </summary>
internal const string QuestBonusSurface = "section:ilt-questbonus";
/// <summary>RynthAi's name for the plugin-command broker (its Fellowship view draws our commands).</summary>
private const string RynthAiPlugin = "RynthAi";
private readonly IltSettingsModel _settingsModel = new();
private readonly IltSettingsUi _settingsUi;
private readonly IltFellowshipUi _fellowshipUi;
// Chat commands from the settings and fellowship windows (render thread), run on the next tick.
private readonly ConcurrentQueue<string> _chatCommands = new();
private const int MaxQueuedChatCommands = 32;
public RynthILTPlugin()
{
_settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures);
_fellowshipUi = new IltFellowshipUi(QueueChatCommand);
IltEngineVerdict.Attach(_settingsModel);
}
/// <summary>Render thread: queues a chat command for the tick; false when the engine can't run one.</summary>
private bool QueueChatCommand(string command)
{
if (!Host.HasInvokeChatParser || _chatCommands.Count >= MaxQueuedChatCommands) return false;
_chatCommands.Enqueue(command);
return true;
}
/// <summary>Wait this long after login for the character's name before tracking without a save file.</summary>
private const long NameWaitMs = 30_000;
@ -100,6 +162,7 @@ public sealed class RynthILTPlugin : RynthPluginBase
_nextNameTryMs = 0;
_nextHubTryMs = 0;
_ai?.Reset();
PollServerState(force: true);
TryStartBounties();
TryStartHub();
}
@ -111,16 +174,24 @@ public sealed class RynthILTPlugin : RynthPluginBase
StopHub();
_ai?.Reset();
_loginComplete = false;
ClearSharedFellowshipCommands();
while (_commands.TryDequeue(out _)) { }
while (_typedBounty.TryDequeue(out _)) { }
while (_engineCommands.TryDequeue(out _)) { }
while (_chatCommands.TryDequeue(out _)) { }
_settingsModel.Clear();
_serverStateJson = string.Empty;
}
// Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the next copy.
// Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the
// next copy. No broker call while the engine unloads us: RynthAi drops the fellowship commands
// once they stop arriving (ServerCommandModel.StaleMs).
public override void Shutdown()
{
SaveBounties();
StopHub();
HubInterface.Release();
IltEngineVerdict.Attach(null);
RynthLog.Shutdown();
}
@ -129,16 +200,264 @@ public sealed class RynthILTPlugin : RynthPluginBase
try { RynthLog.Pump(); } catch { }
if (!_loginComplete) return;
_ai?.Tick();
PollServerState(force: false);
if (_bounties == null) TryStartBounties();
if (_hub == null) TryStartHub();
DrainTypedBounty();
while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts);
while (_engineCommands.TryDequeue(out string? engineCommand)) RunEngineCommand(engineCommand);
DrainChatCommands();
_bounties?.Tick();
try { _hub?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); }
RetryPendingMigration();
PostDataWriteProblems();
try { PublishHubFeatures(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PublishHubFeatures"); }
try { ShareFellowshipCommands(); }
catch (Exception ex) { Host.Log($"[RynthILT] Fellowship commands to RynthAi failed: {ex.Message}"); }
}
// ── ILT fellowship commands for RynthAi's Fellowship view (IltFellowship/) ──
private const long FellowshipShareCheckMs = 2000;
private const long FellowshipShareResendMs = 10_000;
private long _fellowshipShareNextAt;
private long _fellowshipShareSentAt;
// The last payload RynthAi took; empty when nothing was delivered (or after a clear).
private string _fellowshipShareLast = string.Empty;
/// <summary>
/// Plugin tick: sends RynthAi ILT's fellowship commands while ILT is active (an empty list when
/// it isn't), when that changes and every <see cref="FellowshipShareResendMs"/> (RynthAi may load
/// later, and drops a list that stops arriving). Nothing on an engine without the broker.
/// </summary>
private void ShareFellowshipCommands()
{
if (!Host.HasSendPluginCommand) return;
long now = Environment.TickCount64;
if (now < _fellowshipShareNextAt) return;
_fellowshipShareNextAt = now + FellowshipShareCheckMs;
bool active = IltActive();
// Nothing to clear when RynthAi never got a list.
if (!active && _fellowshipShareLast.Length == 0) return;
string payload = IltFellowshipCommands.Payload(active);
if (payload == _fellowshipShareLast && now - _fellowshipShareSentAt < FellowshipShareResendMs) return;
_fellowshipShareSentAt = now;
// Not delivered (RynthAi not installed or not loaded yet): the resend timer tries again.
if (Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, payload))
_fellowshipShareLast = active ? payload : string.Empty;
}
/// <summary>Clears RynthAi's copy of the fellowship commands (logout) if it has one.</summary>
private void ClearSharedFellowshipCommands()
{
if (_fellowshipShareLast.Length == 0) return;
_fellowshipShareLast = string.Empty;
_fellowshipShareNextAt = 0;
try
{
if (Host.HasSendPluginCommand)
Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, IltFellowshipCommands.Payload(active: false));
}
catch { /* RynthAi drops a list that stops arriving */ }
}
/// <summary>
/// The Hub's world check (RynthCore's verdict once it has one, else RynthILT's server list and
/// "Treat this world as ILT"); before the Hub exists, the engine verdict or the world name
/// (IltFellowshipCommands.IsActive).
/// </summary>
private bool IltActive()
{
var hub = _hub;
if (hub != null) return hub.Options.IsIltLikeWorld;
bool? engine = IltEngineVerdict.Active;
string world = engine == null && Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w : string.Empty;
return IltFellowshipCommands.IsActive(engine, world);
}
// ── RynthCore's Mini Remote sections ─────────────────────────────────────
/// <summary>
/// The broker actions answered on arrival rather than queued for the tick: RynthCore's
/// "servermenu" push (2026.10.5.47+, every 10 s) and the older "iltfeatures" text.
/// </summary>
internal static bool IsParsedRemoteAction(string action) =>
action.Equals("servermenu", StringComparison.OrdinalIgnoreCase)
|| action.Equals("iltfeatures", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// RynthPluginApplyRemoteCommand "servermenu" / "iltfeatures". Any thread. Taken and dropped:
/// the same verdicts, overrides and world names reach the settings model from RynthCore's
/// server list (plugin API v86, PollServerState), which RynthILT reads itself, so the push is
/// only acknowledged (it must not fall through to the ILT verbs).
/// </summary>
internal void ApplyRemoteCommand(string action, string value) { }
/// <summary>
/// RynthPluginRenderEmbed: <see cref="RatesSurface"/> (Session Stats), <see cref="FellowshipSurface"/>
/// (Fellowship), <see cref="QuestBonusSurface"/> (RynthILT's Quests section) or
/// <see cref="SettingsSurface"/> in RynthCore's Mini Remote, drawn into the engine's current
/// window and context (popped-out windows have their own). <paramref name="wantHeight"/> is the
/// height it used. False until login or for another surface. Render thread.
/// </summary>
internal bool RenderEmbedded(string surface, out float wantHeight)
{
wantHeight = 0;
if (!_loginComplete) return false;
Action? body = surface switch
{
SettingsSurface => _settingsUi.RenderBody,
FellowshipSurface => _fellowshipUi.RenderBody,
RatesSurface => RenderRatesSurface,
QuestBonusSurface => RenderQuestBonusSurface,
_ => null,
};
if (body == null) return false;
IntPtr previous = ImGui.GetCurrentContext();
IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext;
if (context == IntPtr.Zero) return false;
ImGui.SetCurrentContext(context);
try
{
float startY = ImGui.GetCursorPosY();
body();
wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f);
return true;
}
catch (Exception ex)
{
Host.Log($"[RynthILT] View {surface} failed: {ex.Message}");
return false;
}
finally { ImGui.SetCurrentContext(previous); }
}
/// <summary>The ILT session extras (render thread), or a line saying they start with the Hub.</summary>
private void RenderRatesSurface()
{
IltHubController? hub = _hub;
if (hub == null) { ImGui.TextDisabled("ILT session rates start once RynthILT's Hub is ready."); return; }
hub.RenderRatesSection();
}
/// <summary>The /qb list (render thread), or a line saying it starts with the Hub.</summary>
private void RenderQuestBonusSurface()
{
IltHubController? hub = _hub;
if (hub == null) { ImGui.TextDisabled("The quest bonus list starts once RynthILT's Hub is ready."); return; }
hub.RenderQuestBonusSection();
}
/// <summary>
/// RynthPluginGetSectionsJson (schema 1, UI/Sections/SectionManifest.cs in RynthCore): the ILT
/// session extras in Session Stats ("char"), the fellowship commands in Fellowship and the /qb
/// list in a Quests section of RynthILT's own, all Infinite Leaftide areas (shown while RynthCore
/// treats this world as ILT). The Mini Remote ILT tabs (Banking, Gear, Charms, Games) are listed
/// by RynthAi, which hosts them. Null before login.
/// </summary>
internal string? BuildSectionsJson() => _loginComplete ? SectionsJson : null;
internal const string SectionsJson =
"{\"version\":1,\"sections\":[{\"id\":\"quests\",\"label\":\"Quests\",\"order\":1160}],\"contributions\":[" +
"{\"section\":\"char\",\"server\":\"ilt\"," +
"\"label\":\"ILT session rates (RynthILT)\",\"surface\":\"" + RatesSurface + "\",\"primary\":false," +
"\"height\":220,\"enabled\":true,\"tooltip\":\"Enlightened Coins, pyreals and item conversions this session, " +
"on the same clock as RynthAi's session stats (RynthILT).\",\"order\":120}," +
"{\"section\":\"fellowship\",\"server\":\"ilt\"," +
"\"label\":\"ILT fellowship (RynthILT)\",\"surface\":\"" + FellowshipSurface + "\",\"primary\":false," +
"\"height\":110,\"enabled\":true,\"tooltip\":\"Infinite Leaftide's /fship commands: create, invite, dismiss, " +
"invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).\",\"order\":120}," +
"{\"section\":\"quests\",\"server\":\"ilt\"," +
"\"label\":\"Quest bonus (/qb)\",\"surface\":\"" + QuestBonusSurface + "\",\"primary\":true," +
"\"width\":520,\"height\":440,\"enabled\":true,\"tooltip\":\"Infinite Leaftide's quest bonus list: completed and " +
"incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).\",\"order\":100}]}";
/// <summary>Plugin tick: runs the settings and fellowship views' chat commands through the engine.</summary>
private void DrainChatCommands()
{
while (_chatCommands.TryDequeue(out string? command))
{
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command))
ChatLine("[RynthILT] RynthCore didn't take: " + command);
}
}
private const long ServerStatePollMs = 2000;
private long _serverStateNextAt;
private string _serverStateJson = string.Empty;
/// <summary>
/// Plugin tick, every 2 s (and at login): RynthCore's server list (plugin API v86,
/// GetServerStateJson) into the settings model, whose "ilt" entry the Hub's world check follows
/// (IltEngineVerdict). Parsed only when the text changed. An older engine leaves it empty, and
/// RynthILT's own list decides.
/// </summary>
private void PollServerState(bool force)
{
long now = Environment.TickCount64;
if (!force && now < _serverStateNextAt) return;
_serverStateNextAt = now + ServerStatePollMs;
try
{
if (!Host.HasGetServerStateJson || !Host.TryGetServerStateJson(out string json) || json == _serverStateJson) return;
_serverStateJson = json;
_settingsModel.ApplyServerState(EngineServerState.Parse(json));
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PollServerState"); }
}
private const long FeaturePublishMs = 1000;
private long _featurePublishNextAt;
/// <summary>
/// Plugin tick, at most once a second: the Hub's server read (world, last check, feature bits)
/// for the ILT settings view (IltSettingsModel.PublishFeatures); cleared while there is no Hub.
/// </summary>
private void PublishHubFeatures()
{
long now = Environment.TickCount64;
if (now < _featurePublishNextAt) return;
_featurePublishNextAt = now + FeaturePublishMs;
var hub = _hub;
if (hub == null)
{
_settingsModel.PublishFeatures(null);
return;
}
var options = hub.Options;
DateTime last = options.LastRefreshUtc;
string when = last == default ? string.Empty : last.ToLocalTime().ToString("HH:mm:ss");
_settingsModel.PublishFeatures(new IltFeatureView(options.WorldName, options.Source ?? string.Empty, when,
options.IsRefreshing, options.IsIltLikeWorld, BuildFeatureRows(options)));
}
/// <summary>
/// The settings view's feature rows: every catalog feature with its state (IltFeatureCatalog),
/// then each ILT charm ("charm:...", on with the world unless refused in chat), then any other
/// bit chat or a probe set that the catalog doesn't show. Pump thread.
/// </summary>
private static KeyValuePair<string, int>[] BuildFeatureRows(IltServerOptions options)
{
bool ilt = options.IsIltLikeWorld;
var rows = new List<KeyValuePair<string, int>>(IltFeatureCatalog.All.Length + 32);
var shown = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (IltFeatureInfo f in IltFeatureCatalog.All)
{
rows.Add(new KeyValuePair<string, int>(f.Key, (int)IltFeatureCatalog.StateOf(f, ilt, options.Get)));
if (f.ServerBit != null) shown.Add(f.ServerBit);
}
foreach (IltCharmDef def in IltInventory.Charms)
{
string key = IltFeature.Charm(def.Name);
rows.Add(new KeyValuePair<string, int>(key, (int)IltFeatureCatalog.CharmStateOf(ilt, options.Get(key))));
shown.Add(key);
}
foreach (var bit in options.SnapshotBits())
if (shown.Add(bit.Key)) rows.Add(bit);
return rows.ToArray();
}
/// <summary>
@ -151,6 +470,16 @@ public sealed class RynthILTPlugin : RynthPluginBase
DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2));
}
// ── ILT settings ─────────────────────────────────────────────────────────
/// <summary>Asks the Hub to read the server's ILT features again (as "/ilt hub refresh", on the next tick). Render thread.</summary>
private bool RefreshFeatures()
{
if (!_loginComplete || _hub == null) return false;
_commands.Enqueue(new[] { "/ilt", "hub", "refresh" });
return true;
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (string.IsNullOrEmpty(text)) return;
@ -201,15 +530,26 @@ public sealed class RynthILTPlugin : RynthPluginBase
// ── Rendering (render thread) ────────────────────────────────────────────
/// <summary>The Hub's floating extras (Games HUD, confirmations) in the engine's ImGui frame.</summary>
/// <summary>
/// The Hub's floating extras (Games HUD, confirmations) and the standalone ILT settings and
/// fellowship windows ("/ilt settings", "/ilt fellow") in the engine's ImGui frame.
/// </summary>
public override void OnRender()
{
var hub = _hub;
if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return;
if (!_loginComplete || Host.ImGuiContext == IntPtr.Zero) return;
if (hub == null && !_settingsUi.WindowOpen && !_fellowshipUi.WindowOpen) return;
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(Host.ImGuiContext);
try { hub.Render(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); }
try
{
try { hub?.Render(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); }
try { _settingsUi.RenderWindow(); }
catch (Exception ex) { Host.Log($"[RynthILT] Settings window failed: {ex.Message}"); _settingsUi.WindowOpen = false; }
try { _fellowshipUi.RenderWindow(); }
catch (Exception ex) { Host.Log($"[RynthILT] Fellowship window failed: {ex.Message}"); _fellowshipUi.WindowOpen = false; }
}
finally { ImGui.SetCurrentContext(previous); }
}
@ -334,9 +674,28 @@ public sealed class RynthILTPlugin : RynthPluginBase
case "hub":
case "rates":
break;
case "settings":
case "options":
{
// "/ilt settings [show|hide|toggle]": the ILT settings window.
string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle";
_settingsUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_settingsUi.WindowOpen };
return;
}
case "fellow":
case "fellowship":
case "fship":
{
// "/ilt fellow [show|hide|toggle]": the ILT fellowship commands window.
string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle";
_fellowshipUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_fellowshipUi.WindowOpen };
return;
}
case "help":
ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list|<names>|default],");
ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),");
ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),");
ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),");
ChatLine("[RynthILT] /ilt trace <category|all|list> [on|off], /ilt debug [on|off].");
return;
default: