diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapCalibration.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapCalibration.cs new file mode 100644 index 0000000..6058a3c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapCalibration.cs @@ -0,0 +1,243 @@ +// ============================================================================ +// RynthAi - AcMaps/AcMapCalibration.cs +// Where you are on an ACMAPS map: the dungeon position (the /loc x, y, z in +// the landblock) to a pixel on the image, set by the player once per map. +// +// ACMAPS maps carry no coordinates. GoArrow had the player drag the map until +// its arrow sat on the entrance, then moved the map 3 pixels per unit walked +// (DungeonHud.cs: dX = (old - new) * 3, north up). Here the player does the +// same once and it is saved: stand somewhere you can find on the map, press +// "Place me here" and click that spot. One spot per floor places the floor +// with the map's scale (GoArrow's 3 pixels per unit until it is measured); +// a second spot on a floor, some way from the first, measures the scale. +// ACMAPS draws each floor in its own part of the image, so every floor +// (spots within FloorTolerance of each other's height) gets its own spots. +// The maps are north up: x east is right, y north is up (the image's -y). +// +// Pure: tests drive it. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +/// A spot the player set: where they stood (landblock x, y, z) and the pixel on the map they clicked. +internal readonly record struct MapSpot(float X, float Y, float Z, float Px, float Py); + +/// What a Place did, for the window's status line. +internal enum PlaceResult +{ + /// The first spot on this floor: placed with the map's scale. + FloorPlaced, + /// A spot near the floor's only one: it moved there. + Moved, + /// The second spot on the floor: the scale was measured. + ScaleMeasured, + /// The two spots disagree with a north-up map (the map would be mirrored or the scale absurd): kept as the floor's only spot. + ScaleRefused, +} + +internal sealed class AcMapCalibration +{ + /// GoArrow's scale: map pixels per landblock unit walked. + public const float DefaultScale = 3f; + public const float MinScale = 0.2f, MaxScale = 50f; + /// Spots this close in height are one floor (AC dungeon floors are about 6 units apart). + public const float FloorTolerance = 3f; + /// Two spots must be this far apart (landblock units) to measure the scale. + public const float MinSpotDistance = 8f; + /// The most spots a map keeps (two a floor; a dungeon has a handful of floors). + public const int MaxSpots = 64; + + private readonly List _spots = new(); + + /// Map pixels per landblock unit, shared by every floor. + public float Scale { get; private set; } = DefaultScale; + /// The scale was measured from two spots (or set by hand), not GoArrow's default. + public bool ScaleMeasuredOrSet { get; private set; } + + public IReadOnlyList Spots => _spots; + public bool IsEmpty => _spots.Count == 0; + + public AcMapCalibration() { } + + /// A saved calibration (AcMapSettings); bad values fall back to the defaults. + public AcMapCalibration(float scale, bool scaleSet, IEnumerable spots) + { + if (float.IsFinite(scale) && scale >= MinScale && scale <= MaxScale) { Scale = scale; ScaleMeasuredOrSet = scaleSet; } + foreach (MapSpot s in spots) + { + if (_spots.Count >= MaxSpots) break; + if (float.IsFinite(s.X) && float.IsFinite(s.Y) && float.IsFinite(s.Z) && float.IsFinite(s.Px) && float.IsFinite(s.Py)) + _spots.Add(s); + } + } + + /// The spots on the floor at height , nearest in height first. + public List FloorSpots(float z) + { + var list = new List(); + foreach (MapSpot s in _spots) + if (MathF.Abs(s.Z - z) <= FloorTolerance) list.Add(s); + list.Sort((a, b) => MathF.Abs(a.Z - z).CompareTo(MathF.Abs(b.Z - z))); + return list; + } + + /// This floor has a spot: a position on it has a pixel. + public bool FloorPlaced(float z) => FloorSpots(z).Count > 0; + + /// + /// The pixel for a landblock position, through the floor's spots (one: that spot and the map's scale; two: + /// their mean). False when the floor has no spot. + /// + public bool TryToImage(float x, float y, float z, out Vector2 pixel) + { + pixel = default; + if (!TryFloorOrigin(z, out Vector2 origin)) return false; + pixel = new Vector2(origin.X + Scale * x, origin.Y - Scale * y); + return true; + } + + /// The landblock x, y for a pixel on the floor at (the inverse of TryToImage). + public bool TryToWorld(Vector2 pixel, float z, out float x, out float y) + { + x = y = 0; + if (!TryFloorOrigin(z, out Vector2 origin)) return false; + x = (pixel.X - origin.X) / Scale; + y = -(pixel.Y - origin.Y) / Scale; + return true; + } + + /// Where landblock (0, 0) falls on the image for this floor: each spot's pixel less its position, averaged. + private bool TryFloorOrigin(float z, out Vector2 origin) + { + origin = default; + List floor = FloorSpots(z); + if (floor.Count == 0) return false; + int n = Math.Min(floor.Count, 2); + for (int i = 0; i < n; i++) + origin += new Vector2(floor[i].Px - Scale * floor[i].X, floor[i].Py + Scale * floor[i].Y); + origin /= n; + return true; + } + + /// + /// "Place me here": the player stands at (x, y, z) and clicked pixel (px, py). The floor's first spot places it; + /// a second one at least away measures the map's scale; one closer than that + /// moves the nearer spot. A floor keeps two spots: a third replaces the nearer. + /// + public PlaceResult Place(float x, float y, float z, float px, float py) + { + var spot = new MapSpot(x, y, z, px, py); + List floor = FloorSpots(z); + if (floor.Count == 0) + { + if (_spots.Count >= MaxSpots) _spots.RemoveAt(0); + _spots.Add(spot); + return PlaceResult.FloorPlaced; + } + // The spot nearest the new one (in the dungeon) is the one replaced or kept beside it. + MapSpot nearer = floor[0]; + float nearD = Dist(floor[0], spot); + for (int i = 1; i < floor.Count; i++) + { + float d = Dist(floor[i], spot); + if (d < nearD) { nearD = d; nearer = floor[i]; } + } + if (nearD < MinSpotDistance) + { + // Too near to measure anything: it moves (a better click on the same place). + Replace(nearer, spot); + return PlaceResult.Moved; + } + // The other spot on this floor (the one kept): with the new one they measure the scale. + MapSpot other = nearer; + if (floor.Count >= 2) + { + // Two already: the nearer one goes, the farther one stays with the new. + MapSpot farther = floor[0].Equals(nearer) ? floor[1] : floor[0]; + _spots.Remove(nearer); + for (int i = 2; i < floor.Count; i++) _spots.Remove(floor[i]); + other = farther; + } + else + { + for (int i = 1; i < floor.Count; i++) _spots.Remove(floor[i]); + } + if (!TrySolveScale(other, spot, out float scale)) + { + // A mirrored or absurd answer: the click was off. The new spot alone places the floor. + _spots.Remove(other); + _spots.Add(spot); + return PlaceResult.ScaleRefused; + } + _spots.Add(spot); + Scale = scale; + ScaleMeasuredOrSet = true; + return PlaceResult.ScaleMeasured; + } + + /// + /// The scale two spots give on a north-up map: the least-squares fit of pixel steps to (dx, -dy) steps. + /// False when the spots are too close, or the fit is mirrored, out of range, or far from a plain scale + /// (the pixel steps and the walked steps point more than 30 degrees apart). + /// + internal static bool TrySolveScale(MapSpot a, MapSpot b, out float scale) + { + scale = 0; + float wx = b.X - a.X, wy = -(b.Y - a.Y); + float ix = b.Px - a.Px, iy = b.Py - a.Py; + float w2 = wx * wx + wy * wy; + if (w2 < MinSpotDistance * MinSpotDistance) return false; + float s = (ix * wx + iy * wy) / w2; + if (!float.IsFinite(s) || s < MinScale || s > MaxScale) return false; + float i2 = ix * ix + iy * iy; + if (i2 <= 0) return false; + float cos = (ix * wx + iy * wy) / MathF.Sqrt(i2 * w2); + if (cos < MathF.Cos(30f * MathF.PI / 180f)) return false; + scale = s; + return true; + } + + /// The scale nudged by hand (the window's - and +), kept in range. + public void NudgeScale(float factor) + { + if (!float.IsFinite(factor) || factor <= 0) return; + Scale = Math.Clamp(Scale * factor, MinScale, MaxScale); + ScaleMeasuredOrSet = true; + } + + /// The floor at forgets its spots. True when it had some. + public bool ClearFloor(float z) => _spots.RemoveAll(s => MathF.Abs(s.Z - z) <= FloorTolerance) > 0; + + /// Every spot and the scale back to the start. + public void ClearAll() + { + _spots.Clear(); + Scale = DefaultScale; + ScaleMeasuredOrSet = false; + } + + /// How many floors have a spot (spots grouped by height). + public int FloorCount() + { + var zs = new List(); + foreach (MapSpot s in _spots) + if (!zs.Exists(z => MathF.Abs(z - s.Z) <= FloorTolerance)) zs.Add(s.Z); + return zs.Count; + } + + private void Replace(MapSpot old, MapSpot now) + { + int i = _spots.IndexOf(old); + if (i >= 0) _spots[i] = now; + else _spots.Add(now); + } + + private static float Dist(MapSpot a, MapSpot b) + { + float dx = a.X - b.X, dy = a.Y - b.Y; + return MathF.Sqrt(dx * dx + dy * dy); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapIndex.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapIndex.cs new file mode 100644 index 0000000..0be62be --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapIndex.cs @@ -0,0 +1,377 @@ +// ============================================================================ +// RynthAi - AcMaps/AcMapIndex.cs +// The player's own ACMAPS dungeon map pack, indexed (2026-11-26, a player's +// request: show the ACMAPS maps in game, as GoArrow did). Nothing here ships +// a map: the player points RynthAi at the folder they already have. +// +// What a pack looks like (GoArrow's "Dungeon Map Cache" folder, read from +// GoArrow's MIT-licensed source, Huds/DungeonHud.cs): +// - one image per dungeon, named by the dungeon's four-hex landblock, the +// top half of the /loc cell id: "02CA.gif" (GoArrow fetched +// www.acmaps.com/maps/{0:X4}.gif). PNG and JPG are taken too, and names +// like "0x02CA.png", "02CA - Mosswart Maze.gif" or "02CA0100.gif"; +// - "dungeons.txt" (ACMAPS' dungeon_ids.csv): "02CA;Mosswart Maze", one +// dungeon a line, the landblock in hex then the name; +// - optionally a GoArrow locations database (data_cod.xml, GAlocations.xml): +// records whose Dungeon ones carry +// (the same landblock), , , and the +// entrance's / (north and west negative). +// An image whose name has no landblock is matched to a name from those files. +// +// Pure apart from Scan (the disk listing); tests feed Build file names and text. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +/// One map image: its dungeon's landblock (0 = not known), name and the file, relative to the folder. +internal sealed record AcMapEntry(ushort Landblock, string Name, string RelativePath, string Notes) +{ + /// "Mosswart Maze (02CA)", or the file name when nothing names it. + public string Label => Landblock != 0 + ? (Name.Length > 0 ? $"{Name} ({Landblock:X4})" : $"Dungeon {Landblock:X4}") + : (Name.Length > 0 ? Name : Path.GetFileName(RelativePath)); +} + +internal sealed class AcMapIndex +{ + /// The image types WIC decodes that map packs use. + internal static readonly string[] ImageExtensions = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }; + + /// The index files read (a dungeon list or a locations database). + internal static readonly string[] IndexExtensions = { ".txt", ".csv", ".xml" }; + + /// Scan limits: a pack is a few hundred images; a wrong folder (C:\) must not stall. + internal const int MaxFiles = 20000, MaxDepth = 4; + internal const long MaxIndexFileBytes = 16L * 1024 * 1024; + + public static readonly AcMapIndex Empty = new(string.Empty, new List(), new Dictionary(), + new List(), new List()); + + public string Folder { get; } + /// Every map, by label. + public IReadOnlyList Maps { get; } + /// Dungeon names by landblock, from the index files. + public IReadOnlyDictionary Names { get; } + /// The index files that named at least one dungeon (relative paths). + public IReadOnlyList IndexFiles { get; } + /// What went wrong reading the folder (shown in the window). + public IReadOnlyList Problems { get; } + + private readonly Dictionary> _byLandblock = new(); + + private AcMapIndex(string folder, List maps, Dictionary names, List indexFiles, List problems) + { + Folder = folder; + Maps = maps; + Names = names; + IndexFiles = indexFiles; + Problems = problems; + foreach (AcMapEntry e in maps) + { + if (e.Landblock == 0) continue; + if (!_byLandblock.TryGetValue(e.Landblock, out var list)) _byLandblock[e.Landblock] = list = new List(); + list.Add(e); + } + } + + /// The maps of a dungeon (most packs have one; a few have extra parts), first by file name. + public IReadOnlyList ForLandblock(ushort landblock) => + _byLandblock.TryGetValue(landblock, out var list) ? list : (IReadOnlyList)Array.Empty(); + + public bool Has(ushort landblock) => _byLandblock.ContainsKey(landblock); + + /// The dungeon's name from the index files, or "". + public string NameOf(ushort landblock) => Names.TryGetValue(landblock, out string? n) ? n : string.Empty; + + /// "123 maps, 456 dungeon names (dungeons.txt)". + public string Summary() + { + var sb = new StringBuilder(); + sb.Append(Maps.Count == 1 ? "1 map" : $"{Maps.Count} maps"); + sb.Append(", ").Append(Names.Count == 1 ? "1 dungeon name" : $"{Names.Count} dungeon names"); + if (IndexFiles.Count > 0) sb.Append(" (").Append(string.Join(", ", IndexFiles)).Append(')'); + return sb.ToString(); + } + + // ── Building ───────────────────────────────────────────────────────── + + /// + /// The index of from its files (, relative paths) + /// and (an index file's text by relative path, null when it can't be read). + /// + public static AcMapIndex Build(string folder, IEnumerable relativeFiles, Func readText) + { + var problems = new List(); + var names = new Dictionary(); + var notes = new Dictionary(); + var indexFiles = new List(); + var images = new List(); + foreach (string rel in relativeFiles) + { + string ext = Path.GetExtension(rel).ToLowerInvariant(); + if (ImageExtensions.Contains(ext)) images.Add(rel); + else if (IndexExtensions.Contains(ext)) + { + string? text = readText(rel); + if (text == null) { problems.Add($"Couldn't read {rel}."); continue; } + int n = ext == ".xml" || text.Contains(" 0) indexFiles.Add(rel); + } + } + + // Names without a landblock in their file name: matched by dungeon name. + var byName = new Dictionary(StringComparer.Ordinal); + foreach (var (lb, name) in names) + { + string key = NameKey(name); + if (key.Length > 0 && !byName.ContainsKey(key)) byName[key] = lb; + } + + var maps = new List(images.Count); + foreach (string rel in images.OrderBy(r => r, StringComparer.OrdinalIgnoreCase)) + { + string file = Path.GetFileNameWithoutExtension(rel); + ushort lb; + string name; + // A whole file name that is a listed dungeon wins ("Dead End.png" is a name, not landblock DEAD). + if (byName.TryGetValue(NameKey(file), out ushort named) && ParseLandblock(file) == 0) + { + lb = named; + name = names[named]; + } + else if (TryLandblockFromFileName(file, out lb, out string rest)) + name = names.TryGetValue(lb, out string? n) ? n : rest; + else + { + name = file.Trim(); + lb = byName.TryGetValue(NameKey(name), out ushort found) ? found : (ushort)0; + if (lb != 0 && names.TryGetValue(lb, out string? listed)) name = listed; + } + maps.Add(new AcMapEntry(lb, name, rel, lb != 0 && notes.TryGetValue(lb, out string? note) ? note : string.Empty)); + } + maps.Sort((a, b) => string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase)); + if (images.Count == 0) problems.Add("No map images (GIF, PNG or JPG) in this folder or the folders in it."); + else if (names.Count == 0) problems.Add("No dungeon list (dungeons.txt) found: maps are shown by their landblock."); + return new AcMapIndex(folder, maps, names, indexFiles, problems); + } + + /// + /// Lists (and the folders in it, deep, + /// files at most) and builds the index. Any thread; never throws. + /// + public static AcMapIndex Scan(string folder) + { + try + { + if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder)) + return new AcMapIndex(folder ?? string.Empty, new List(), new Dictionary(), + new List(), new List { "The folder isn't there." }); + string root = Path.GetFullPath(folder); + var files = new List(); + bool truncated = false; + Walk(root, root, 0, files, ref truncated); + AcMapIndex index = Build(root, files, rel => + { + try + { + string full = Path.Combine(root, rel); + if (new FileInfo(full).Length > MaxIndexFileBytes) return null; + return File.ReadAllText(full, Encoding.UTF8); + } + catch { return null; } + }); + if (truncated) ((List)index.Problems).Add($"Stopped after {MaxFiles} files: is this the map folder?"); + return index; + } + catch (Exception ex) + { + return new AcMapIndex(folder ?? string.Empty, new List(), new Dictionary(), + new List(), new List { "Couldn't read the folder: " + ex.Message }); + } + } + + private static void Walk(string root, string dir, int depth, List files, ref bool truncated) + { + IEnumerable here; + try { here = Directory.EnumerateFiles(dir); } + catch { return; } + foreach (string f in here) + { + if (files.Count >= MaxFiles) { truncated = true; return; } + string ext = Path.GetExtension(f).ToLowerInvariant(); + if (ImageExtensions.Contains(ext) || IndexExtensions.Contains(ext)) files.Add(Path.GetRelativePath(root, f)); + } + if (depth >= MaxDepth) return; + IEnumerable subs; + try { subs = Directory.EnumerateDirectories(dir); } + catch { return; } + foreach (string d in subs) + { + if (files.Count >= MaxFiles) { truncated = true; return; } + Walk(root, d, depth + 1, files, ref truncated); + } + } + + // ── Parsing ────────────────────────────────────────────────────────── + + private static readonly Regex FileNameRx = new(@"^(?:0x)?([0-9A-Fa-f]{4})(?:[0-9A-Fa-f]{4})?(?![0-9A-Za-z])(.*)$", + RegexOptions.CultureInvariant); + + /// + /// "02CA", "0x02CA", "02CA0100", "02CA - Mosswart Maze": the landblock and the rest as a name ("Mosswart Maze"). + /// False for a name that doesn't start with 4 (or 8) hex digits on their own ("Mosswart Maze", "02CAB"). + /// + internal static bool TryLandblockFromFileName(string fileName, out ushort landblock, out string rest) + { + landblock = 0; + rest = string.Empty; + Match m = FileNameRx.Match(fileName.Trim()); + if (!m.Success) return false; + landblock = ushort.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + if (landblock == 0) return false; + rest = m.Groups[2].Value.Trim().TrimStart('-', '_', '.', ' ', '(').TrimEnd(')').Trim(); + return true; + } + + /// A landblock written as "02CA", "0x02CA", "02CA0100" or "0x02CA0100"; 0 when it isn't one. + internal static ushort ParseLandblock(string text) + { + string t = text.Trim(); + if (t.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) t = t[2..]; + if ((t.Length != 4 && t.Length != 8) || !uint.TryParse(t, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) + return 0; + return (ushort)(t.Length == 8 ? v >> 16 : v); + } + + /// + /// A dungeon list: "02CA;Mosswart Maze" a line (GoArrow's dungeons.txt, ACMAPS' dungeon_ids.csv); a comma or a + /// tab works as the separator too, and "Mosswart Maze;02CA". Other lines are skipped. Returns the names added. + /// + internal static int ParseDungeonList(string text, Dictionary names) + { + int added = 0; + foreach (string raw in text.Split('\n')) + { + string line = raw.Trim().TrimStart('\uFEFF'); + if (line.Length == 0 || line[0] == '#') continue; + char sep = line.Contains(';') ? ';' : line.Contains('\t') ? '\t' : ','; + string[] parts = line.Split(sep); + if (parts.Length < 2) continue; + string a = Unquote(parts[0]), b = Unquote(parts[1]); + ushort lb = ParseLandblock(a); + string name = b; + if (lb == 0) { lb = ParseLandblock(b); name = a; } + if (lb == 0 || name.Length == 0 || ParseLandblock(name) != 0) continue; + if (!names.ContainsKey(lb)) added++; + names[lb] = name; + } + return added; + } + + private static readonly Regex LocationRx = new(@"]*>(.*?)", + RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.IgnoreCase); + + /// + /// A GoArrow locations database: each <location> with a <dungeon_id> (or <type>Dungeon + /// and an id) names its dungeon; its restrictions, entrance and description become the map's notes. A + /// name the dungeon list already gave is kept. Returns the dungeons added. + /// + internal static int ParseLocationsXml(string text, Dictionary names, Dictionary notes) + { + int added = 0; + foreach (Match m in LocationRx.Matches(text)) + { + string body = m.Groups[1].Value; + ushort lb = ParseLandblock(Tag(body, "dungeon_id")); + if (lb == 0) continue; + if (Tag(body, "retired").Equals("Y", StringComparison.OrdinalIgnoreCase)) continue; + string name = Tag(body, "name"); + if (name.Length > 0 && !names.ContainsKey(lb)) { names[lb] = name; added++; } + if (!notes.ContainsKey(lb)) + { + string note = LocationNote(body); + if (note.Length > 0) notes[lb] = note; + } + } + return added; + } + + /// "Entrance 25.2S, 19.4E. Level 40+. Quest(s): ...". + private static string LocationNote(string body) + { + var parts = new List(); + if (TryCoord(Tag(body, "latitude"), 'S', 'N', out string ns) && TryCoord(Tag(body, "longitude"), 'E', 'W', out string ew) + && !(ns.StartsWith("0.0") && ew.StartsWith("0.0"))) + parts.Add($"Entrance {ns}, {ew}."); + string restrictions = Tag(body, "restrictions"); + if (restrictions.Length > 0) parts.Add(restrictions.TrimEnd('.') + "."); + string description = Tag(body, "description"); + if (description.Length > 0) parts.Add(description); + return string.Join(" ", parts); + } + + /// GoArrow's coordinates: south and east positive ("22.200" is 22.2S), north and west negative. + internal static bool TryCoord(string text, char positive, char negative, out string coord) + { + coord = string.Empty; + if (!double.TryParse(text.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double v)) return false; + coord = Math.Abs(v).ToString("0.0", CultureInfo.InvariantCulture) + (v < 0 ? negative : positive); + return true; + } + + private static string Tag(string body, string tag) + { + Match m = Regex.Match(body, "<" + tag + @"\b[^>]*>(.*?)", + RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.IgnoreCase); + return m.Success ? Unescape(m.Groups[1].Value).Trim() : string.Empty; + } + + private static string Unescape(string s) + { + if (s.StartsWith("", StringComparison.Ordinal)) return s[9..^3]; + if (s.IndexOf('&') < 0) return s; + s = Regex.Replace(s, "&#(x?)([0-9A-Fa-f]+);", m => + { + bool hex = m.Groups[1].Value.Length > 0; + return int.TryParse(m.Groups[2].Value, hex ? NumberStyles.HexNumber : NumberStyles.Integer, CultureInfo.InvariantCulture, out int c) + && c > 0 && c < 0x110000 ? char.ConvertFromUtf32(c) : string.Empty; + }); + return s.Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("'", "'").Replace("&", "&"); + } + + private static string Unquote(string s) + { + s = s.Trim(); + if (s.Length >= 2 && s[0] == '"' && s[^1] == '"') s = s[1..^1].Replace("\"\"", "\""); + return s.Trim(); + } + + /// A name for matching: letters and digits, lower case ("The Mosswart Maze!" is "themosswartmaze"). + internal static string NameKey(string name) + { + var sb = new StringBuilder(name.Length); + foreach (char c in name) + if (char.IsLetterOrDigit(c)) sb.Append(char.ToLowerInvariant(c)); + return sb.ToString(); + } + + // ── Search ─────────────────────────────────────────────────────────── + + /// The maps whose label has every word (any order, any case); every map for no words. + public static List Search(IReadOnlyList maps, string words) + { + string[] w = words.Split(new[] { ' ', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries); + if (w.Length == 0) return maps.ToList(); + return maps.Where(m => w.All(x => m.Label.Contains(x, StringComparison.OrdinalIgnoreCase) + || m.RelativePath.Contains(x, StringComparison.OrdinalIgnoreCase))).ToList(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapSettings.cs new file mode 100644 index 0000000..dd88a5d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapSettings.cs @@ -0,0 +1,149 @@ +// ============================================================================ +// RynthAi - AcMaps/AcMapSettings.cs +// The ACMAPS maps' settings, for every character on this PC: +// \RynthAi\acmaps.json - the maps folder, the chat line when a +// dungeon has a map (off unless turned on), and each map's spots (keyed by +// the image's path in the folder, so two parts of one dungeon keep their own). +// Hand-written JSON (no reflection: RynthAi is NativeAOT). +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; +using RynthCore.Install; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +internal sealed class AcMapSettings +{ + public const string FileName = "acmaps.json"; + public const string DefaultFolderName = "ACMaps"; + + /// Where the maps are put when the player hasn't picked a folder: <RynthSuite>\RynthAi\ACMaps. + public static string DefaultFolder => Path.Combine(RynthInstallPaths.RynthAiDir, DefaultFolderName); + + /// The settings file: <RynthSuite>\RynthAi\acmaps.json. + public static string DefaultPath => Path.Combine(RynthInstallPaths.RynthAiDir, FileName); + + /// The maps folder; empty = . + public string Folder { get; set; } = string.Empty; + /// Say in chat when you enter a dungeon that has a map. Off by default. + public bool Announce { get; set; } + /// Each map's spots, by the image's path relative to the folder (case-insensitive). + public Dictionary Maps { get; } = new(StringComparer.OrdinalIgnoreCase); + + public string FolderOrDefault => string.IsNullOrWhiteSpace(Folder) ? DefaultFolder : Folder; + + /// The map's calibration, made empty the first time. + public AcMapCalibration For(string relativePath) + { + if (!Maps.TryGetValue(relativePath, out AcMapCalibration? c)) Maps[relativePath] = c = new AcMapCalibration(); + return c; + } + + // ── JSON ───────────────────────────────────────────────────────────── + + public string ToJson() + { + using var stream = new MemoryStream(); + using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + w.WriteNumber("version", 1); + w.WriteString("folder", Folder); + w.WriteBoolean("announce", Announce); + w.WriteStartObject("maps"); + foreach (var (path, cal) in Maps) + { + if (cal.IsEmpty && !cal.ScaleMeasuredOrSet) continue; + w.WriteStartObject(path); + w.WriteNumber("scale", Math.Round(cal.Scale, 4)); + w.WriteBoolean("scaleSet", cal.ScaleMeasuredOrSet); + w.WriteStartArray("spots"); + foreach (MapSpot s in cal.Spots) + { + w.WriteStartArray(); + w.WriteNumberValue(Math.Round(s.X, 2)); + w.WriteNumberValue(Math.Round(s.Y, 2)); + w.WriteNumberValue(Math.Round(s.Z, 2)); + w.WriteNumberValue(Math.Round(s.Px, 1)); + w.WriteNumberValue(Math.Round(s.Py, 1)); + w.WriteEndArray(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + w.WriteEndObject(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// The settings in ; anything unreadable is left at its default. + public static AcMapSettings FromJson(string json) + { + var s = new AcMapSettings(); + try + { + using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return s; + if (root.TryGetProperty("folder", out JsonElement f) && f.ValueKind == JsonValueKind.String) s.Folder = f.GetString() ?? string.Empty; + if (root.TryGetProperty("announce", out JsonElement a) && (a.ValueKind == JsonValueKind.True || a.ValueKind == JsonValueKind.False)) + s.Announce = a.GetBoolean(); + if (root.TryGetProperty("maps", out JsonElement maps) && maps.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty map in maps.EnumerateObject()) + { + if (map.Value.ValueKind != JsonValueKind.Object) continue; + float scale = map.Value.TryGetProperty("scale", out JsonElement sc) && sc.TryGetDouble(out double d) ? (float)d : AcMapCalibration.DefaultScale; + bool set = map.Value.TryGetProperty("scaleSet", out JsonElement ss) && ss.ValueKind == JsonValueKind.True; + var spots = new List(); + if (map.Value.TryGetProperty("spots", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in arr.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Array || e.GetArrayLength() < 5) continue; + var v = new float[5]; + bool ok = true; + for (int i = 0; i < 5 && ok; i++) + { + ok = e[i].ValueKind == JsonValueKind.Number && e[i].TryGetDouble(out double x); + if (ok) v[i] = (float)e[i].GetDouble(); + } + if (ok) spots.Add(new MapSpot(v[0], v[1], v[2], v[3], v[4])); + } + s.Maps[map.Name] = new AcMapCalibration(scale, set, spots); + } + } + } + catch (JsonException) { } + return s; + } + + /// The settings file, or defaults when it isn't there or can't be read. Any thread. + public static AcMapSettings Load(string path) + { + try { return File.Exists(path) ? FromJson(File.ReadAllText(path, Encoding.UTF8)) : new AcMapSettings(); } + catch { return new AcMapSettings(); } + } + + /// Writes the file (a temp file, then moved over). The error, or "" when saved. + public static string Save(string path, string json) + { + try + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, json, new UTF8Encoding(false)); + File.Move(tmp, path, overwrite: true); + return string.Empty; + } + catch (Exception ex) { return ex.Message; } + } + + /// "3.00" for the window. + public static string ScaleText(float scale) => scale.ToString("0.00", CultureInfo.InvariantCulture); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapTexture.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapTexture.cs new file mode 100644 index 0000000..a117d68 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapTexture.cs @@ -0,0 +1,164 @@ +// ============================================================================ +// RynthAi - AcMaps/AcMapTexture.cs +// A decoded map image as D3D9 textures for ImGui, in Tile x Tile pieces +// (power-of-two textures, so no device limit or non-power-of-two rule bites; +// the edge pieces use part of theirs). Managed pool: they survive a device +// reset. A few pieces are made a frame so a big map doesn't stall a frame. +// +// Render thread only (the D3D device isn't made for other threads). A new +// device means the old textures belong to a dead one: they are forgotten, +// not released, as HudIconCache does. Once every piece is made the decoded +// pixels are let go (the managed pool keeps its own copy; the client is +// 32-bit): a new device after that asks for the image again (NeedsReload). +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +internal sealed unsafe class AcMapTexture +{ + public const int Tile = 512; + private const int TilesPerFrame = 6; + + private const int VtRelease = 2, VtCreateTexture = 23, VtLockRect = 19, VtUnlockRect = 20; + private const uint D3DFMT_A8R8G8B8 = 21, D3DPOOL_MANAGED = 1; + + [StructLayout(LayoutKind.Sequential)] + private struct LockedRect { public int Pitch; public IntPtr Bits; } + + /// One piece: its texture (Zero until made, or when making it failed), where it sits and its UV corner. + internal struct Piece + { + public IntPtr Tex; + public int X, Y, W, H; + public Vector2 Uv1; + public bool Tried; + } + + private uint[]? _pixels; // until every piece is made + private readonly int _width; + private readonly Piece[] _pieces; + private IntPtr _device; + private int _made; + + public AcMapTexture(DecodedImage image) + { + _pixels = image.Pixels; + _width = image.Width; + SourceWidth = image.SourceWidth; + SourceHeight = image.SourceHeight; + Factor = image.Factor; + var list = new List(); + for (int y = 0; y < image.Height; y += Tile) + for (int x = 0; x < image.Width; x += Tile) + { + int w = Math.Min(Tile, image.Width - x), h = Math.Min(Tile, image.Height - y); + int tw = Pow2(w), th = Pow2(h); + list.Add(new Piece { X = x, Y = y, W = w, H = h, Uv1 = new Vector2(w / (float)tw, h / (float)th) }); + } + _pieces = list.ToArray(); + } + + /// The file's size in pixels (spots and the view are in these). + public int SourceWidth { get; } + public int SourceHeight { get; } + /// Decoded (piece) pixels per file pixel. + public float Factor { get; } + /// The device changed after the pixels were let go: decode the file again. + public bool NeedsReload { get; private set; } + public int PieceCount => _pieces.Length; + /// Every piece has been made (or tried). + public bool Complete => _made >= _pieces.Length; + public ReadOnlySpan Pieces => _pieces; + + /// Makes the next few pieces on . Render thread, once a frame while drawn. + public void Upload(IntPtr device) + { + if (device == IntPtr.Zero) return; + if (device != _device && _device != IntPtr.Zero && _pixels == null) + { + NeedsReload = true; + return; + } + if (device != _device) + { + for (int i = 0; i < _pieces.Length; i++) { _pieces[i].Tex = IntPtr.Zero; _pieces[i].Tried = false; } + _made = 0; + _device = device; + } + int budget = TilesPerFrame; + for (int i = 0; i < _pieces.Length && budget > 0; i++) + { + if (_pieces[i].Tried) continue; + _pieces[i].Tried = true; + _pieces[i].Tex = Make(device, ref _pieces[i]); + _made++; + budget--; + } + if (_made >= _pieces.Length) _pixels = null; + } + + /// Releases every texture. Render thread. + public void Release() + { + for (int i = 0; i < _pieces.Length; i++) + { + IntPtr t = _pieces[i].Tex; + _pieces[i].Tex = IntPtr.Zero; + _pieces[i].Tried = false; + if (t == IntPtr.Zero || _device == IntPtr.Zero) continue; + try { ((delegate* unmanaged[Stdcall])Slot(t, VtRelease))(t); } catch { } + } + _made = 0; + } + + private IntPtr Make(IntPtr device, ref Piece p) + { + try + { + int tw = Pow2(p.W), th = Pow2(p.H); + IntPtr tex; + int hr = ((delegate* unmanaged[Stdcall])Slot(device, VtCreateTexture))( + device, (uint)tw, (uint)th, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, IntPtr.Zero); + if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero; + LockedRect locked; + hr = ((delegate* unmanaged[Stdcall])Slot(tex, VtLockRect))(tex, 0, &locked, IntPtr.Zero, 0); + if (hr < 0) + { + ((delegate* unmanaged[Stdcall])Slot(tex, VtRelease))(tex); + return IntPtr.Zero; + } + uint[]? pixels = _pixels; + if (pixels == null) return IntPtr.Zero; + fixed (uint* src = pixels) + { + for (int row = 0; row < th; row++) + { + uint* dst = (uint*)((byte*)locked.Bits + (long)row * locked.Pitch); + if (row < p.H) + { + Buffer.MemoryCopy(src + (long)(p.Y + row) * _width + p.X, dst, (long)tw * 4, (long)p.W * 4); + for (int x = p.W; x < tw; x++) dst[x] = 0; + } + else + for (int x = 0; x < tw; x++) dst[x] = 0; + } + } + ((delegate* unmanaged[Stdcall])Slot(tex, VtUnlockRect))(tex, 0); + return tex; + } + catch { return IntPtr.Zero; } + } + + internal static int Pow2(int v) + { + int p = 1; + while (p < v) p <<= 1; + return p; + } + + private static void* Slot(IntPtr com, int index) => (*(void***)com)[index]; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapWindow.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapWindow.cs new file mode 100644 index 0000000..52ff9f0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapWindow.cs @@ -0,0 +1,706 @@ +// ============================================================================ +// RynthAi - AcMaps/AcMapWindow.cs +// The ACMAPS Maps window: the player's own ACMAPS map of the dungeon they're +// in, with zoom, pan and their position on it once they've placed it. +// RynthCore hosts it (the sections manifest's "acmaps" window, plugin API +// v89; no bar button) and calls Draw through RynthPluginRenderEmbed. +// +// Top row: the dungeon's name and landblock; This dungeon, Maps (every map in +// the folder, searchable), Folder (where the maps are, Browse..., Scan, the +// chat line setting). The map: drag to pan, the wheel zooms where the cursor +// is, Follow me keeps you in the middle. Bottom row: zoom - / + / Fit, +// Follow me, Place me here (then click where you stand: AcMapCalibration), +// Clear floor, the scale - / +. +// +// AC's render thread. Decoding is on a thread of its own (WicImage); the +// textures are made here (AcMapTexture). Looks: Shared/RynthUi. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; +using static RynthCore.Plugin.Shared.RynthUi.RynthUi; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +/// What the window needs from RynthAi (RynthAiPlugin.AcMaps.cs). +internal interface IAcMapsHost +{ + AcMapIndex Index { get; } + bool Scanning { get; } + /// The settings; lock it to change them (the window's spots, the command's folder). + AcMapSettings Settings { get; } + void SetFolder(string folder); + void Rescan(); + void SetAnnounce(bool on); + /// Writes the settings file soon (off this thread). + void SaveSettings(); + /// The player's cell and landblock position, compass heading (0 north, clockwise). + bool TryPose(out uint cell, out float x, out float y, out float z, out float heading); + IntPtr Device { get; } +} + +internal sealed class AcMapWindow +{ + private const float MinZoom = 0.05f, MaxZoom = 8f; + private const string ChooserTitle = "Choose the folder with your ACMAPS maps (the GIF or PNG files and dungeons.txt)"; + + internal const string HelpText = + "Your own ACMAPS dungeon maps, as GoArrow showed them. RynthSuite doesn't come with the maps: " + + "point Folder at the map pack you have (the images named by landblock, like 02CA.gif, and dungeons.txt).\n\n" + + "In a dungeon with a map, it shows here. Drag to move it, the mouse wheel zooms.\n\n" + + "Your position: the maps have no coordinates, so place each floor once. Stand somewhere you can find on the map " + + "(the portal you came in by, a corner), press Place me here and click that spot. A second spot on the same floor, " + + "some way off, measures the map's scale. Spots are saved for the map. Clear floor forgets this floor's spots.\n\n" + + "Maps also lists every map in the folder, to look at any dungeon.\n\n" + + "/ra acmaps opens this window; /ra acmaps folder , /ra acmaps scan, /ra acmaps announce on|off."; + + private readonly IAcMapsHost _host; + private float _k = 1f; + private float Px(float v) => v * _k; + + // What is shown. + private bool _followDungeon = true; // show the current dungeon's map (else _picked) + private AcMapEntry? _picked; + private int _part; // which of a dungeon's maps + private AcMapEntry? _shown; + private string _shownFolder = string.Empty; + private AcMapTexture? _tex; + private string _loadingPath = string.Empty; + private string _loadError = string.Empty; + private sealed record Loaded(string Path, DecodedImage? Image, string Error); + private Loaded? _loaded; // the decode thread's result (Interlocked) + + // View. + private float _zoom = 1f; + private Vector2 _center; // file pixel at the canvas centre + private bool _fitPending; // a map just loaded: fit it, then centre on you if placed + private bool _fitAll; // Fit: the whole map + private bool _followMe = true; + private bool _dragging; + private bool _placing; + private string _status = string.Empty; + private long _statusUntil; + + // Panels. + private bool _mapsOpen, _folderOpen; + private string _search = string.Empty; + private string _folderText = string.Empty; + private bool _folderTextSet; + private volatile string? _chosenFolder; + + public AcMapWindow(IAcMapsHost host) => _host = host; + + /// The window was drawn this long ago: its textures go (they're remade when it shows). + public void ReleaseTextures() + { + _tex?.Release(); + _tex = null; + _shown = null; + _loadingPath = string.Empty; + } + + /// Draws the window body into the current ImGui window and returns the size it would like. Render thread. + public Vector2 Draw() + { + _k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f); + Vector2 origin = ImGui.GetCursorScreenPos(); + Vector2 size = ImGui.GetContentRegionAvail(); + var want = new Vector2(Px(620), Px(560)); + if (size.X < 80 || size.Y < 80) return want; + + string? chosen = Interlocked.Exchange(ref _chosenFolder, null); + if (chosen != null) { _folderText = chosen; _host.SetFolder(chosen); Say("Folder set: scanning it."); } + + bool havePose = _host.TryPose(out uint cell, out float px, out float py, out float pz, out float heading); + ushort here = havePose && (cell & 0xFFFF) >= 0x100 ? (ushort)(cell >> 16) : (ushort)0; + AcMapIndex index = _host.Index; + AcMapEntry? want_ = Choose(index, here); + Track(index, want_); + + ImDrawListPtr frame = ImGui.GetWindowDrawList(); + frame.AddRectFilled(origin, origin + size, Background, 4); + using (PushFont(RynthUiFont.Ui11)) + { + float pad = Px(6), rowH = Px(22); + float w = size.X - pad * 2; + Vector2 p = origin + new Vector2(pad, pad); + DrawTop(index, here, p, w, rowH); + p.Y += rowH + Px(4); + DrawStatusLine(index, here, havePose, pz, p, w); + p.Y += Px(18); + float bottomH = rowH + Px(6); + float canvasH = Math.Max(Px(40), origin.Y + size.Y - pad - bottomH - p.Y - Px(8)); + var cmin = p; + var cmax = p + new Vector2(w, canvasH); + bool onThisMap = _shown != null && here != 0 && _shown.Landblock == here; + // The map takes the mouse only where no panel lies over it (ImGui gives a press to the first + // item under it, and the canvas is drawn first). + Vector2 inputMin = cmin; + if (_mapsOpen) inputMin.X = cmin.X + MapsPanelWidth(cmin, cmax) + Px(6); + if (_folderOpen) inputMin.Y = cmin.Y + FolderPanelHeight(cmin, cmax) + Px(6); + DrawCanvas(cmin, cmax, inputMin, onThisMap, havePose, px, py, pz, heading); + if (_mapsOpen) DrawMapsPanel(index, cmin, cmax); + if (_folderOpen) DrawFolderPanel(index, cmin, cmax); + DrawBottom(new Vector2(p.X, cmax.Y + Px(6)), w, rowH, onThisMap, havePose, pz); + } + frame.AddRect(origin, origin + size, Border, 4); + return want; + } + + // ── What to show ──────────────────────────────────────────────────── + + private AcMapEntry? Choose(AcMapIndex index, ushort here) + { + if (!_followDungeon) return _picked; + if (here == 0) return null; + IReadOnlyList maps = index.ForLandblock(here); + if (maps.Count == 0) return null; + return maps[Math.Clamp(_part, 0, maps.Count - 1)]; + } + + /// Starts loading the map to show, takes a finished decode, makes its textures. + private void Track(AcMapIndex index, AcMapEntry? entry) + { + Loaded? done = Interlocked.Exchange(ref _loaded, null); + string path = entry == null ? string.Empty : Path.Combine(index.Folder, entry.RelativePath); + if (done != null && done.Path == _loadingPath && done.Path == path) + { + _tex?.Release(); + _tex = done.Image != null ? new AcMapTexture(done.Image) : null; + _loadError = done.Error; + _loadingPath = string.Empty; + _fitPending = true; + } + bool same = _shown != null && entry != null && _shown.RelativePath == entry.RelativePath && _shownFolder == index.Folder; + if (!same) + { + _tex?.Release(); + _tex = null; + _shown = entry; + _shownFolder = index.Folder; + _loadError = string.Empty; + _placing = false; + _loadingPath = string.Empty; + if (entry != null) + { + _loadingPath = path; + string p = path; + // A decode for a map no longer wanted (the player moved on) is dropped, so it can't + // take the slot from the one that is. + WicImage.DecodeAsync(p, (img, err) => + { + if (p == Volatile.Read(ref _loadingPath)) Interlocked.Exchange(ref _loaded, new Loaded(p, img, err)); + }); + } + } + _tex?.Upload(_host.Device); + if (_tex is { NeedsReload: true }) + { + // A new D3D device after the pixels were let go: read the file again. + _tex = null; + _shown = null; + } + } + + // ── Top row ───────────────────────────────────────────────────────── + + private void DrawTop(AcMapIndex index, ushort here, Vector2 p, float w, float h) + { + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + const string thisLabel = "This dungeon", mapsLabel = "Maps", folderLabel = "Folder"; + float bw1 = ButtonWidth(thisLabel), bw2 = ButtonWidth(mapsLabel), bw3 = ButtonWidth(folderLabel), helpW = h; + float right = p.X + w; + float x3 = right - helpW - Px(4) - bw3, x2 = x3 - Px(4) - bw2, x1 = x2 - Px(4) - bw1; + + string title = _shown != null ? _shown.Label + : _followDungeon && here != 0 ? (index.NameOf(here) is { Length: > 0 } n ? $"{n} ({here:X4})" : $"Dungeon {here:X4}") + : _followDungeon ? "Not in a dungeon" : "No map picked"; + using (PushFont(RynthUiFont.Ui14)) + { + dl.PushClipRect(p, new Vector2(x1 - Px(6), p.Y + h), true); + float th = ImGui.GetFontSize(); + dl.AddText(new Vector2(p.X, p.Y + (h - th) * 0.5f), Text, title); + dl.PopClipRect(); + } + IReadOnlyList parts = _followDungeon && here != 0 ? index.ForLandblock(here) : Array.Empty(); + if (parts.Count > 1) + { + // A dungeon with more than one map: which part. + float pw = Px(70); + float tx = x1 - Px(8) - pw; + if (Button("##am_part", $"Map {Math.Clamp(_part, 0, parts.Count - 1) + 1} of {parts.Count}", new Vector2(tx, p.Y), new Vector2(pw, h), Text, ButtonFill)) + _part = (Math.Clamp(_part, 0, parts.Count - 1) + 1) % parts.Count; + SafeImGui.SetItemTooltip("This dungeon has " + parts.Count + " maps: show the next."); + } + if (Button("##am_here", thisLabel, new Vector2(x1, p.Y), new Vector2(bw1, h), Text, _followDungeon ? AccentFill : ButtonFill)) + { + _followDungeon = true; + _mapsOpen = false; + _followMe = true; + } + SafeImGui.SetItemTooltip("Show the map of the dungeon you're in (changes as you go)."); + if (Button("##am_maps", mapsLabel, new Vector2(x2, p.Y), new Vector2(bw2, h), Text, _mapsOpen ? AccentFill : ButtonFill)) + { + _mapsOpen = !_mapsOpen; + if (_mapsOpen) _folderOpen = false; + } + SafeImGui.SetItemTooltip("Every map in your folder: pick one to look at."); + if (Button("##am_folder", folderLabel, new Vector2(x3, p.Y), new Vector2(bw3, h), Text, _folderOpen ? AccentFill : ButtonFill)) + { + _folderOpen = !_folderOpen; + if (_folderOpen) _mapsOpen = false; + } + SafeImGui.SetItemTooltip("Where your ACMAPS maps are, and the chat line setting."); + IconButton("##am_help", RynthIcons.Info, new Vector2(right - helpW, p.Y), new Vector2(helpW, h), Mute, ButtonFill, font: RynthUiFont.Ui11); + SafeImGui.SetItemTooltip(HelpText); + } + + private void DrawStatusLine(AcMapIndex index, ushort here, bool havePose, float z, Vector2 p, float w) + { + long now = Environment.TickCount64; + string line; + uint color = Mute; + if (_status.Length > 0 && now < _statusUntil) { line = _status; color = Highlight; } + else if (_host.Scanning) line = "Reading the maps folder..."; + else if (index.Maps.Count == 0) + { + line = index.Folder.Length == 0 && index.Problems.Count == 0 + ? "No maps yet: press Folder and choose your ACMAPS map pack." + : (index.Problems.Count > 0 ? index.Problems[0] + " " : string.Empty) + "Press Folder to choose another."; + color = index.Problems.Count > 0 ? Red : Mute; + } + else if (_shown == null && _followDungeon) + line = here == 0 ? "You're not in a dungeon. Maps lists every map in your folder." + : $"No ACMAPS map for this dungeon ({here:X4}) in your folder."; + else if (_loadError.Length > 0) { line = _loadError; color = Red; } + else if (_loadingPath.Length > 0) line = "Loading the map..."; + else if (_placing) { line = "Click the spot on the map where you're standing (Esc: stop)."; color = Highlight; } + else if (_shown != null && here != 0 && _shown.Landblock == here) + { + AcMapCalibration cal = Calibration(_shown); + line = !havePose ? "Your position can't be read right now." + : cal.FloorPlaced(z) ? (cal.ScaleMeasuredOrSet || cal.FloorSpots(z).Count >= 2 + ? "You're the green arrow." + : "You're the green arrow. A second spot on this floor, some way off, makes it exact.") + : "This floor isn't placed: stand somewhere you can find on the map, press Place me here, click that spot."; + } + else line = _shown?.Notes is { Length: > 0 } notes ? notes : "Looking at another dungeon's map."; + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + dl.PushClipRect(p, p + new Vector2(w, Px(16)), true); + dl.AddText(p, color, line); + dl.PopClipRect(); + if (ImGui.IsMouseHoveringRect(p, p + new Vector2(w, Px(16))) && line.Length > 60) SafeImGui.SetTooltip(line); + } + + // ── The map ───────────────────────────────────────────────────────── + + private void DrawCanvas(Vector2 cmin, Vector2 cmax, Vector2 inputMin, bool onThisMap, bool havePose, float px, float py, float pz, float heading) + { + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + dl.AddRectFilled(cmin, cmax, Field, 3); + Vector2 csize = cmax - cmin; + Vector2 mid = cmin + csize * 0.5f; + bool hovered = false, active = false; + Vector2 inputSize = cmax - inputMin; + if (inputSize.X >= 4 && inputSize.Y >= 4) + { + ImGui.SetCursorScreenPos(inputMin); + ImGui.InvisibleButton("##am_canvas", inputSize); + hovered = ImGui.IsItemHovered(); + active = ImGui.IsItemActive(); + } + + AcMapTexture? tex = _tex; + if (tex == null) + { + dl.AddRect(cmin, cmax, Border, 3); + return; + } + float factor = tex.Factor; // decoded per file pixel + var fileSize = new Vector2(tex.SourceWidth, tex.SourceHeight); + if (_fitAll) + { + _fitAll = false; + Fit(fileSize, csize); + } + if (_fitPending) + { + _fitPending = false; + Fit(fileSize, csize); + if (onThisMap && havePose && Calibration(_shown!).TryToImage(px, py, pz, out Vector2 me)) + { + _center = me; + _zoom = Math.Max(_zoom, 1f); + } + } + + AcMapCalibration cal = Calibration(_shown!); + Vector2 mePx = default; + bool meKnown = onThisMap && havePose && cal.TryToImage(px, py, pz, out mePx); + + // Input: drag pans (Follow me off), the wheel zooms at the cursor, a click places when armed. + ImGuiIOPtr io = ImGui.GetIO(); + if (active && ImGui.IsMouseDragging(ImGuiMouseButton.Left, 3f)) + { + _dragging = true; + _followMe = false; + _center -= io.MouseDelta / _zoom; + } + if (hovered && io.MouseWheel != 0) + { + Vector2 before = ToFile(io.MousePos, mid); + _zoom = Math.Clamp(_zoom * MathF.Pow(1.2f, io.MouseWheel), MinZoom, MaxZoom); + if (!_followMe || !meKnown) _center += before - ToFile(io.MousePos, mid); + } + bool clicked = hovered && ImGui.IsMouseReleased(ImGuiMouseButton.Left) && !_dragging; + if (!ImGui.IsMouseDown(ImGuiMouseButton.Left)) _dragging = false; + if (_placing && ImGui.IsKeyPressed(ImGuiKey.Escape)) { _placing = false; Say("Stopped placing."); } + if (_placing && clicked) + { + Vector2 at = ToFile(io.MousePos, mid); + if (!onThisMap || !havePose) Say("Placing needs you in this map's dungeon."); + else if (at.X < 0 || at.Y < 0 || at.X > fileSize.X || at.Y > fileSize.Y) Say("That's off the map: click on the map."); + else + { + PlaceResult r; + lock (_host.Settings) r = cal.Place(px, py, pz, at.X, at.Y); + _host.SaveSettings(); + _placing = false; + _followMe = true; + Say(r switch + { + PlaceResult.FloorPlaced => "Floor placed. A second spot on this floor, some way off, measures the scale.", + PlaceResult.Moved => "Spot moved (it was near the last one).", + PlaceResult.ScaleMeasured => "Scale measured from two spots: " + AcMapSettings.ScaleText(cal.Scale) + " pixels a unit.", + _ => "Those two spots don't fit a north-up map: the new spot places the floor on its own.", + }); + meKnown = cal.TryToImage(px, py, pz, out mePx); + } + } + if (_followMe && meKnown && !_dragging) _center = mePx; + ClampCenter(fileSize); + + // The image, piece by piece, culled to the canvas. + dl.PushClipRect(cmin, cmax, true); + ReadOnlySpan pieces = tex.Pieces; + int missing = 0; + foreach (AcMapTexture.Piece piece in pieces) + { + if (piece.Tex == IntPtr.Zero) { if (!piece.Tried) missing++; continue; } + Vector2 a = ToScreen(new Vector2(piece.X, piece.Y) / factor, mid); + Vector2 b = ToScreen(new Vector2(piece.X + piece.W, piece.Y + piece.H) / factor, mid); + if (b.X < cmin.X || b.Y < cmin.Y || a.X > cmax.X || a.Y > cmax.Y) continue; + dl.AddImage(piece.Tex, a, b, Vector2.Zero, piece.Uv1); + } + + // The spots of this floor while placing (so a bad one can be clicked again). + if (_placing && onThisMap && havePose) + foreach (MapSpot s in cal.FloorSpots(pz)) + { + Vector2 sp = ToScreen(new Vector2(s.Px, s.Py), mid); + dl.AddCircle(sp, Px(6), Highlight, 12, 2f); + } + + // You: a green arrow pointing your way (north up). + if (meKnown) + { + Vector2 c = ToScreen(mePx, mid); + float rad = heading * MathF.PI / 180f; + var fwd = new Vector2(MathF.Sin(rad), -MathF.Cos(rad)); + var side = new Vector2(-fwd.Y, fwd.X); + float len = Px(11), half = Px(6); + Vector2 tip = c + fwd * len, l = c - fwd * Px(5) + side * half, r = c - fwd * Px(5) - side * half; + uint green = Green; + dl.AddTriangleFilled(tip, l, r, WithAlpha(green, 0xE6)); + dl.AddTriangle(tip, l, r, 0xFF000000, 1.5f); + dl.AddCircleFilled(c, Px(2.5f), 0xFF000000); + } + if (missing > 0) + dl.AddText(cmin + new Vector2(Px(6), Px(4)), Mute, "Drawing the map..."); + + // Under the cursor: the landblock position, when the floor is placed. + if (hovered && onThisMap && havePose && cal.FloorPlaced(pz) && cal.TryToWorld(ToFile(io.MousePos, mid), pz, out float wx, out float wy)) + { + string t = string.Format(CultureInfo.InvariantCulture, "{0:0.0}, {1:0.0}", wx, wy); + Vector2 ts = ImGui.CalcTextSize(t); + Vector2 tp = new(cmax.X - ts.X - Px(6), cmax.Y - ts.Y - Px(4)); + dl.AddRectFilled(tp - new Vector2(Px(3), Px(1)), tp + ts + new Vector2(Px(3), Px(1)), WithAlpha(Background, 0xC0), 2); + dl.AddText(tp, Mute, t); + } + dl.PopClipRect(); + dl.AddRect(cmin, cmax, _placing ? Highlight : Border, 3, ImDrawFlags.None, _placing ? 2f : 1f); + if (_placing && hovered) ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + } + + private Vector2 ToScreen(Vector2 file, Vector2 mid) => mid + (file - _center) * _zoom; + private Vector2 ToFile(Vector2 screen, Vector2 mid) => _center + (screen - mid) / _zoom; + + private void Fit(Vector2 fileSize, Vector2 canvas) + { + if (fileSize.X <= 0 || fileSize.Y <= 0) return; + _zoom = Math.Clamp(Math.Min(canvas.X / fileSize.X, canvas.Y / fileSize.Y), MinZoom, MaxZoom); + _center = fileSize * 0.5f; + } + + private void ClampCenter(Vector2 fileSize) + { + _center = Vector2.Clamp(_center, Vector2.Zero, fileSize); + if (!float.IsFinite(_center.X) || !float.IsFinite(_center.Y)) _center = fileSize * 0.5f; + } + + // ── Bottom row ────────────────────────────────────────────────────── + + private void DrawBottom(Vector2 p, float w, float h, bool onThisMap, bool havePose, float pz) + { + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + bool haveMap = _tex != null; + float x = p.X, sq = h, gap = Px(4); + if (Button("##am_zout", "-", new Vector2(x, p.Y), new Vector2(sq, h), Text, ButtonFill, haveMap)) Zoom(1f / 1.25f); + SafeImGui.SetItemTooltip("Zoom out (or the mouse wheel)."); + x += sq + gap; + string zt = Math.Round(_zoom * 100).ToString(CultureInfo.InvariantCulture) + "%"; + float zw = Px(44); + Vector2 zs = ImGui.CalcTextSize(zt); + dl.AddText(new Vector2(x + (zw - zs.X) * 0.5f, p.Y + (h - zs.Y) * 0.5f), haveMap ? Text : Faded(Text), zt); + x += zw + gap; + if (Button("##am_zin", "+", new Vector2(x, p.Y), new Vector2(sq, h), Text, ButtonFill, haveMap)) Zoom(1.25f); + SafeImGui.SetItemTooltip("Zoom in (or the mouse wheel)."); + x += sq + gap; + const string fitLabel = "Fit"; + float fw = ButtonWidth(fitLabel); + if (Button("##am_fit", fitLabel, new Vector2(x, p.Y), new Vector2(fw, h), Text, ButtonFill, haveMap)) + { + _followMe = false; + _fitAll = true; // fitted to the canvas as it is drawn + } + SafeImGui.SetItemTooltip("The whole map in the window."); + x += fw + gap * 2; + + AcMapCalibration? cal = _shown != null ? Calibration(_shown) : null; + bool canPlace = haveMap && onThisMap && havePose; + const string followLabel = "Follow me"; + float folw = ButtonWidth(followLabel); + bool meKnown = canPlace && cal!.FloorPlaced(pz); + if (Button("##am_follow", followLabel, new Vector2(x, p.Y), new Vector2(folw, h), Text, _followMe && meKnown ? AccentFill : ButtonFill, meKnown)) + _followMe = !_followMe; + SafeImGui.SetItemTooltip(meKnown ? "Keep you in the middle of the map (dragging the map turns it off)." + : "Needs this floor placed (Place me here)."); + x += folw + gap; + + const string placeLabel = "Place me here"; + float plw = ButtonWidth(placeLabel); + if (Button("##am_place", placeLabel, new Vector2(x, p.Y), new Vector2(plw, h), Text, _placing ? AccentFill : ButtonFill, canPlace)) + { + _placing = !_placing; + if (_placing) Say("Now click the spot on the map where you're standing."); + } + SafeImGui.SetItemTooltip(canPlace + ? "Stand somewhere you can find on the map (a portal, a corner), press this, then click that spot on the map.\n" + + "Once per floor; a second spot on a floor, some way off, measures the scale." + : "Needs you in this map's dungeon, with the map loaded."); + x += plw + gap; + + const string clearLabel = "Clear floor"; + float clw = ButtonWidth(clearLabel); + bool canClear = canPlace && cal!.FloorPlaced(pz); + if (Button("##am_clear", clearLabel, new Vector2(x, p.Y), new Vector2(clw, h), Text, ButtonFill, canClear)) + { + lock (_host.Settings) cal!.ClearFloor(pz); + _host.SaveSettings(); + Say("This floor's spots are cleared."); + } + SafeImGui.SetItemTooltip("Forget this floor's spots (to place it again)."); + x += clw + gap * 2; + + // Scale: - 3.00 + + float right = p.X + w; + float sw = Px(40); + float need = sq * 2 + sw + gap * 2; + if (x + need <= right && cal != null) + { + float sx = right - need; + bool canScale = haveMap; + if (Button("##am_sdn", "-", new Vector2(sx, p.Y), new Vector2(sq, h), Text, ButtonFill, canScale)) + { + lock (_host.Settings) cal.NudgeScale(1f / 1.02f); + _host.SaveSettings(); + } + SafeImGui.SetItemTooltip("The map's scale, a little smaller (when the arrow runs ahead of you)."); + string st = AcMapSettings.ScaleText(cal.Scale); + Vector2 ss = ImGui.CalcTextSize(st); + dl.AddText(new Vector2(sx + sq + gap + (sw - ss.X) * 0.5f, p.Y + (h - ss.Y) * 0.5f), cal.ScaleMeasuredOrSet ? Text : Mute, st); + if (ImGui.IsMouseHoveringRect(new Vector2(sx + sq + gap, p.Y), new Vector2(sx + sq + gap + sw, p.Y + h))) + SafeImGui.SetTooltip(cal.ScaleMeasuredOrSet ? "Map pixels for each unit you walk (measured or set)." + : "Map pixels for each unit you walk: GoArrow's 3 until a second spot measures it."); + if (Button("##am_sup", "+", new Vector2(sx + sq + gap * 2 + sw, p.Y), new Vector2(sq, h), Text, ButtonFill, canScale)) + { + lock (_host.Settings) cal.NudgeScale(1.02f); + _host.SaveSettings(); + } + SafeImGui.SetItemTooltip("The map's scale, a little bigger (when the arrow lags behind you)."); + } + } + + private void Zoom(float k) => _zoom = Math.Clamp(_zoom * k, MinZoom, MaxZoom); + + // ── Maps panel ────────────────────────────────────────────────────── + + private float MapsPanelWidth(Vector2 cmin, Vector2 cmax) => Math.Min(Px(280), (cmax.X - cmin.X) * 0.7f); + + private float FolderPanelHeight(Vector2 cmin, Vector2 cmax) => Math.Min(cmax.Y - cmin.Y - Px(8), Px(250)); + + private void DrawMapsPanel(AcMapIndex index, Vector2 cmin, Vector2 cmax) + { + float pw = MapsPanelWidth(cmin, cmax); + Vector2 a = cmin + new Vector2(Px(4), Px(4)), b = new(cmin.X + pw, cmax.Y - Px(4)); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + dl.AddRectFilled(a, b, WithAlpha(Background, 0xF0), 4); + dl.AddRect(a, b, Border, 4); + ImGui.SetCursorScreenPos(a + new Vector2(Px(6), Px(6))); + ImGui.PushItemWidth(pw - Px(16)); + ImGui.InputTextWithHint("##am_search", "Find a map: a name or landblock", ref _search, 64u); + ImGui.PopItemWidth(); + List hits = AcMapIndex.Search(index.Maps, _search); + Vector2 listPos = ImGui.GetCursorScreenPos(); + ImGui.SetCursorScreenPos(new Vector2(a.X + Px(6), listPos.Y + Px(2))); + ImGui.BeginChild("##am_list", new Vector2(pw - Px(12), Math.Max(Px(20), b.Y - listPos.Y - Px(8)))); + if (hits.Count == 0) Label(index.Maps.Count == 0 ? "No maps in the folder." : "No map matches.", Mute); + int i = 0; + foreach (AcMapEntry e in hits) + { + bool sel = _shown != null && _shown.RelativePath == e.RelativePath; + if (ImGui.Selectable(SafeLabel(e.Label) + "##am_e" + i, sel)) + { + _followDungeon = false; + _picked = e; + _followMe = false; + _mapsOpen = false; + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(e.RelativePath + (e.Notes.Length > 0 ? "\n" + e.Notes : string.Empty)); + i++; + } + ImGui.EndChild(); + } + + // ── Folder panel ──────────────────────────────────────────────────── + + private void DrawFolderPanel(AcMapIndex index, Vector2 cmin, Vector2 cmax) + { + AcMapSettings s = _host.Settings; + string current; + bool announce; + lock (s) { current = s.FolderOrDefault; announce = s.Announce; } + if (!_folderTextSet) { _folderText = current; _folderTextSet = true; } + float w = cmax.X - cmin.X - Px(8); + Vector2 a = cmin + new Vector2(Px(4), Px(4)); + float h = FolderPanelHeight(cmin, cmax); + Vector2 b = a + new Vector2(w, h); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + dl.AddRectFilled(a, b, WithAlpha(Background, 0xF4), 4); + dl.AddRect(a, b, Border, 4); + float pad = Px(8), rowH = Px(22); + Vector2 p = a + new Vector2(pad, pad); + float iw = w - pad * 2; + dl.AddText(p, Text, "Your ACMAPS maps folder"); + p.Y += Px(18); + + const string browse = "Browse...", useDefault = "Default", scan = "Scan"; + float bw = ButtonWidth(browse), dw = ButtonWidth(useDefault), sw = ButtonWidth(scan); + float boxW = iw - bw - dw - sw - Px(12); + ImGui.SetCursorScreenPos(p); + ImGui.PushItemWidth(Math.Max(Px(60), boxW)); + bool enter = ImGui.InputText("##am_folderbox", ref _folderText, 260u, ImGuiInputTextFlags.EnterReturnsTrue); + ImGui.PopItemWidth(); + SafeImGui.SetItemTooltip("Type or paste the folder, then Enter (or Scan)."); + float bx = p.X + boxW + Px(4); + bool picking = FolderPicker.IsOpen; + if (Button("##am_browse", picking ? "Open..." : browse, new Vector2(bx, p.Y), new Vector2(bw, rowH), Text, ButtonFill, !picking)) + { + string start = Directory.Exists(_folderText) ? _folderText : current; + if (!FolderPicker.Pick(ChooserTitle, start, f => { if (f != null) _chosenFolder = f; })) + Say("A folder chooser is already open."); + else Say("The folder chooser is open (in full screen it may be behind the game: Alt+Tab)."); + } + SafeImGui.SetItemTooltip("Choose the folder in Windows' folder chooser."); + bx += bw + Px(4); + if (Button("##am_default", useDefault, new Vector2(bx, p.Y), new Vector2(dw, rowH), Text, ButtonFill)) + { + _folderText = AcMapSettings.DefaultFolder; + enter = true; + } + SafeImGui.SetItemTooltip("RynthSuite's own maps folder: " + AcMapSettings.DefaultFolder + "\n(copy your map pack into it; it is made if it isn't there)."); + bx += dw + Px(4); + bool doScan = Button("##am_scan", scan, new Vector2(bx, p.Y), new Vector2(sw, rowH), Text, ButtonFill, !_host.Scanning); + SafeImGui.SetItemTooltip("Read the folder again (after adding maps)."); + if (enter || doScan) + { + string f = _folderText.Trim().Trim('"'); + if (f.Length == 0) f = AcMapSettings.DefaultFolder; + if (!string.Equals(f, current, StringComparison.OrdinalIgnoreCase)) { _host.SetFolder(f); Say("Folder set: scanning it."); } + else { _host.Rescan(); Say("Scanning the folder."); } + } + p.Y += rowH + Px(6); + + string summary = _host.Scanning ? "Reading the folder..." : index.Summary(); + dl.AddText(p, Mute, summary); + p.Y += Px(16); + foreach (string problem in index.Problems) + { + dl.PushClipRect(p, p + new Vector2(iw, Px(16)), true); + dl.AddText(p, Red, problem); + dl.PopClipRect(); + p.Y += Px(16); + if (p.Y > b.Y - Px(80)) break; + } + p.Y += Px(4); + ImGui.SetCursorScreenPos(p); + bool a2 = announce; + if (ImGui.Checkbox("Say in chat when a dungeon has an ACMAPS map##am_announce", ref a2)) _host.SetAnnounce(a2); + SafeImGui.SetItemTooltip("A line in chat as you enter a dungeon your folder has a map for (off unless you turn it on)."); + p.Y += rowH + Px(8); + ImGui.SetCursorScreenPos(p); + ImGui.PushTextWrapPos(a.X + w - pad); + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped("The maps are ACMAPS', made by its players and kept by the AC community; RynthSuite doesn't come with them. " + + "A pack is the images named by landblock (02CA.gif) and dungeons.txt. GoArrow's \"Dungeon Map Cache\" folder works as it is."); + ImGui.PopStyleColor(); + ImGui.PopTextWrapPos(); + } + + // ── Helpers ───────────────────────────────────────────────────────── + + private AcMapCalibration Calibration(AcMapEntry e) + { + lock (_host.Settings) return _host.Settings.For(e.RelativePath); + } + + private void Say(string text) + { + _status = text; + _statusUntil = Environment.TickCount64 + 6000; + } + + private static string SafeLabel(string s) => s.Replace("##", "# "); + + /// "/ra acmaps" with a map named: show it (not following the dungeon). + public void Show(AcMapEntry entry) + { + _followDungeon = false; + _picked = entry; + _followMe = false; + } + + /// Back to the dungeon you're in. + public void FollowDungeon() + { + _followDungeon = true; + _followMe = true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/FolderPicker.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/FolderPicker.cs new file mode 100644 index 0000000..e91dc61 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/FolderPicker.cs @@ -0,0 +1,118 @@ +// ============================================================================ +// RynthAi - AcMaps/FolderPicker.cs +// The ACMAPS window's "Browse..." button: Windows' folder chooser, on its own +// STA thread so the game keeps running while it is open (it isn't owned by the +// game window, so it never freezes it). In full-screen it may open behind the +// game: the folder box beside the button takes a typed or pasted path too. +// ============================================================================ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +internal static unsafe class FolderPicker +{ + private const uint BifReturnOnlyFsDirs = 0x0001, BifEditBox = 0x0010, BifNewDialogStyle = 0x0040; + private const uint BffmInitialized = 1, BffmSetSelectionW = 0x0400 + 103; + private const int MaxPath = 260; + + [StructLayout(LayoutKind.Sequential)] + private struct BrowseInfo + { + public IntPtr Owner; + public IntPtr Root; + public char* DisplayName; + public char* Title; + public uint Flags; + public IntPtr Callback; + public IntPtr Param; + public int Image; + } + + [DllImport("shell32.dll")] private static extern IntPtr SHBrowseForFolderW(BrowseInfo* info); + [DllImport("shell32.dll")] private static extern int SHGetPathFromIDListW(IntPtr pidl, char* path); + [DllImport("ole32.dll")] private static extern void CoTaskMemFree(IntPtr p); + [DllImport("ole32.dll")] private static extern int OleInitialize(IntPtr reserved); + [DllImport("ole32.dll")] private static extern void OleUninitialize(); + [DllImport("user32.dll")] private static extern IntPtr SendMessageW(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll")] private static extern int SetForegroundWindow(IntPtr hwnd); + + private static int _open; + + /// A chooser is open now (one at a time). + public static bool IsOpen => Volatile.Read(ref _open) != 0; + + /// + /// Opens the chooser starting at ; gets the folder chosen, or + /// null when cancelled, on the chooser's thread. False when one is already open. + /// + public static bool Pick(string title, string start, Action done) + { + if (Interlocked.Exchange(ref _open, 1) != 0) return false; + var t = new Thread(() => + { + string? chosen = null; + try { chosen = Run(title, start); } + catch { } + finally { Volatile.Write(ref _open, 0); } + try { done(chosen); } catch { } + }) + { IsBackground = true, Name = "RynthAi folder chooser" }; + try { t.SetApartmentState(ApartmentState.STA); } catch { } + t.Start(); + return true; + } + + private static string? Run(string title, string start) + { + int ole = OleInitialize(IntPtr.Zero); + IntPtr startText = Marshal.StringToHGlobalUni(start ?? string.Empty); + try + { + char* name = stackalloc char[MaxPath + 1]; + fixed (char* t = title) + { + var info = new BrowseInfo + { + DisplayName = name, + Title = t, + Flags = BifReturnOnlyFsDirs | BifNewDialogStyle | BifEditBox, + Callback = (IntPtr)(delegate* unmanaged[Stdcall])&OnEvent, + Param = startText, + }; + IntPtr pidl = SHBrowseForFolderW(&info); + if (pidl == IntPtr.Zero) return null; + try + { + char* path = stackalloc char[MaxPath + 1]; + if (SHGetPathFromIDListW(pidl, path) == 0) return null; + string s = new string(path); + return s.Length > 0 ? s : null; + } + finally { CoTaskMemFree(pidl); } + } + } + finally + { + Marshal.FreeHGlobal(startText); + if (ole >= 0) OleUninitialize(); + } + } + + /// BFFM_INITIALIZED: start in the current folder and come to the front. + [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })] + private static int OnEvent(IntPtr hwnd, uint msg, IntPtr lParam, IntPtr data) + { + try + { + if (msg == BffmInitialized) + { + if (data != IntPtr.Zero) SendMessageW(hwnd, BffmSetSelectionW, (IntPtr)1, data); + SetForegroundWindow(hwnd); + } + } + catch { } + return 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/AcMaps/WicImage.cs b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/WicImage.cs new file mode 100644 index 0000000..db91937 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/AcMaps/WicImage.cs @@ -0,0 +1,161 @@ +// ============================================================================ +// RynthAi - AcMaps/WicImage.cs +// Reads a map image (GIF, PNG, JPG, BMP) into 32-bit BGRA pixels with +// Windows' own decoder (WIC, windowscodecs.dll): no image library to ship, +// and no reflection (RynthAi is NativeAOT), so COM is called through its +// vtables. The first frame only (ACMAPS GIFs are single-frame). +// +// A map larger than MaxSide or MaxPixels is scaled down on the way in (the +// client is 32-bit; a 4096 x 4096 map is 64 MB of pixels): Width/Height are +// what was decoded, SourceWidth/SourceHeight the file's, so spots stay in the +// file's pixels. +// +// Runs on its own thread (Decode starts one): it joins COM as MTA there. +// ============================================================================ +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.RynthAi.AcMaps; + +/// A decoded image: BGRA pixels (one uint each, as D3DFMT_A8R8G8B8), top row first. +internal sealed class DecodedImage +{ + public int Width { get; init; } + public int Height { get; init; } + public int SourceWidth { get; init; } + public int SourceHeight { get; init; } + public uint[] Pixels { get; init; } = Array.Empty(); + /// Decoded pixels per file pixel (1 unless scaled down). + public float Factor => SourceWidth > 0 ? Width / (float)SourceWidth : 1f; +} + +internal static unsafe class WicImage +{ + public const int MaxSide = 4096; + public const long MaxPixels = 8L * 1024 * 1024; + + private static readonly Guid ClsidFactory = new("cacaf262-9370-4615-a13b-9f5539da4c0a"); + private static readonly Guid IidFactory = new("ec5ec8a9-c395-4314-9c77-54d7a935ff70"); + private static readonly Guid FormatBgra32 = new("6fddc324-4e03-4bfe-b185-3d77768dc90f"); + + private const uint ClsctxInprocServer = 1; + private const uint GenericRead = 0x80000000; + private const int CoinitMultithreaded = 0; + private const int RpcEChangedMode = unchecked((int)0x80010106); + + // vtable slots (wincodec.h order). + private const int FactoryCreateDecoderFromFilename = 3, FactoryCreateFormatConverter = 10, FactoryCreateBitmapScaler = 11; + private const int DecoderGetFrame = 13; + private const int SourceGetSize = 3, SourceCopyPixels = 7; + private const int ConverterInitialize = 8, ScalerInitialize = 8; + private const int Release = 2; + private const int DitherNone = 0, PaletteCustom = 0, InterpolationFant = 3; + + [DllImport("ole32.dll")] private static extern int CoInitializeEx(IntPtr reserved, int coInit); + [DllImport("ole32.dll")] private static extern void CoUninitialize(); + [DllImport("ole32.dll")] private static extern int CoCreateInstance(Guid* clsid, IntPtr outer, uint context, Guid* iid, IntPtr* ppv); + + /// + /// Decodes on a new background thread and hands the result (or null and why) to + /// on that thread. + /// + public static void DecodeAsync(string path, Action done) + { + var t = new System.Threading.Thread(() => + { + DecodedImage? image = null; + string error; + try { image = Load(path, out error); } + catch (Exception ex) { error = ex.Message; } + try { done(image, error); } catch { } + }) + { IsBackground = true, Name = "RynthAi ACMAPS decode" }; + t.Start(); + } + + /// The image at , or null and why. Joins COM on the calling thread for the call. + public static DecodedImage? Load(string path, out string error) + { + int init = CoInitializeEx(IntPtr.Zero, CoinitMultithreaded); + bool uninit = init >= 0; // S_OK or S_FALSE; RPC_E_CHANGED_MODE: the thread is STA already, still usable + if (init < 0 && init != RpcEChangedMode) { error = $"COM didn't start (0x{init:X8})."; return null; } + IntPtr factory = IntPtr.Zero, decoder = IntPtr.Zero, frame = IntPtr.Zero, scaler = IntPtr.Zero, converter = IntPtr.Zero; + try + { + Guid clsid = ClsidFactory, iid = IidFactory; + int hr = CoCreateInstance(&clsid, IntPtr.Zero, ClsctxInprocServer, &iid, &factory); + if (hr < 0) { error = $"Windows' image decoder isn't available (0x{hr:X8})."; return null; } + fixed (char* p = path) + { + hr = ((delegate* unmanaged[Stdcall])Slot(factory, FactoryCreateDecoderFromFilename))( + factory, p, null, GenericRead, 0, &decoder); + } + if (hr < 0) { error = $"Couldn't open the image (0x{hr:X8}): not a GIF, PNG or JPG Windows can read?"; return null; } + hr = ((delegate* unmanaged[Stdcall])Slot(decoder, DecoderGetFrame))(decoder, 0, &frame); + if (hr < 0) { error = $"The image has no picture in it (0x{hr:X8})."; return null; } + uint w, h; + hr = ((delegate* unmanaged[Stdcall])Slot(frame, SourceGetSize))(frame, &w, &h); + if (hr < 0 || w == 0 || h == 0) { error = "The image is empty."; return null; } + + (int ow, int oh) = FitSize((int)w, (int)h); + IntPtr source = frame; + if (ow != (int)w || oh != (int)h) + { + hr = ((delegate* unmanaged[Stdcall])Slot(factory, FactoryCreateBitmapScaler))(factory, &scaler); + if (hr >= 0) + hr = ((delegate* unmanaged[Stdcall])Slot(scaler, ScalerInitialize))( + scaler, frame, (uint)ow, (uint)oh, InterpolationFant); + if (hr < 0) { error = $"Couldn't scale the {w} x {h} image down (0x{hr:X8})."; return null; } + source = scaler; + } + + hr = ((delegate* unmanaged[Stdcall])Slot(factory, FactoryCreateFormatConverter))(factory, &converter); + if (hr < 0) { error = $"Couldn't convert the image (0x{hr:X8})."; return null; } + Guid fmt = FormatBgra32; + hr = ((delegate* unmanaged[Stdcall])Slot(converter, ConverterInitialize))( + converter, source, &fmt, DitherNone, IntPtr.Zero, 0.0, PaletteCustom); + if (hr < 0) { error = $"Couldn't convert the image to colour pixels (0x{hr:X8})."; return null; } + + var pixels = new uint[(long)ow * oh]; + uint stride = (uint)ow * 4; + fixed (uint* dst = pixels) + { + hr = ((delegate* unmanaged[Stdcall])Slot(converter, SourceCopyPixels))( + converter, IntPtr.Zero, stride, stride * (uint)oh, (byte*)dst); + } + if (hr < 0) { error = $"Couldn't read the image's pixels (0x{hr:X8})."; return null; } + error = string.Empty; + return new DecodedImage { Width = ow, Height = oh, SourceWidth = (int)w, SourceHeight = (int)h, Pixels = pixels }; + } + finally + { + ReleaseCom(converter); + ReleaseCom(scaler); + ReleaseCom(frame); + ReleaseCom(decoder); + ReleaseCom(factory); + if (uninit) CoUninitialize(); + } + } + + /// The size to decode a w x h image at: itself, or scaled down (aspect kept) to MaxSide and MaxPixels. + internal static (int W, int H) FitSize(int w, int h) + { + if (w <= 0 || h <= 0) return (0, 0); + double k = 1.0; + int side = Math.Max(w, h); + if (side > MaxSide) k = MaxSide / (double)side; + double px = (double)w * h * k * k; + if (px > MaxPixels) k *= Math.Sqrt(MaxPixels / px); + if (k >= 1.0) return (w, h); + return (Math.Max(1, (int)Math.Floor(w * k)), Math.Max(1, (int)Math.Floor(h * k))); + } + + private static void* Slot(IntPtr com, int index) => (*(void***)com)[index]; + + private static void ReleaseCom(IntPtr com) + { + if (com == IntPtr.Zero) return; + try { ((delegate* unmanaged[Stdcall])Slot(com, Release))(com); } catch { } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AmmoRecipes.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AmmoRecipes.cs index 7fe2574..2afa8de 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/AmmoRecipes.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AmmoRecipes.cs @@ -89,6 +89,19 @@ public static partial class AmmoRecipes return null; } + /// + /// About how much ammo one combine makes, for planning a top-off (Make ammo when low). The world + /// database's success amounts (read 2026-11-23): a plain "Bundle of" shaft makes 100 (Crystal + /// heads 250), a "Wrapped Bundle of" shaft 1000 (a few Greater Deadly and elemental wrapped + /// bundles 2500). The shaft decides, so this reads the shaft: 100 or 1000, never more than made. + /// + public static int EstimatedYield(AmmoRecipe recipe) => + recipe.ShaftName.StartsWith("Wrapped", StringComparison.OrdinalIgnoreCase) ? 1000 : 100; + + /// Infinite heads are not used up by a combine (only the shaft bundle is). + public static bool HeadIsInfinite(AmmoRecipe recipe) => + recipe.HeadName.StartsWith("Infinite", StringComparison.OrdinalIgnoreCase); + /// Rank of finished ammo on the recipes' scale (), or 1 /// for ammo no recipe makes (quest arrows and the like) so crafted ammo outranks it. public static int OutputRank(string name, WeaponCategory category) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 166bb62..de46226 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -395,6 +395,18 @@ public partial class BuffManager : IDisposable private DateTime _buffFightWaitSince = DateTime.MinValue; private DateTime _buffFightNeedCheckedAt = DateTime.MinValue; + // ── A fight that never ends (2026-11-25, R-20261125-130039-e3bc) ── + // Conquest, a spot that respawns constantly with Monster Range 10: never more than ~15 s without a + // monster in range, so the wait above never ended. Buffs waited 24,811 s (almost 7 hours), ran out, + // and the character died several times; Force Rebuff (cast in the fight) worked. Now once buffs + // have waited BuffFightWaitMaxSec through one unbroken fight, a full pass goes in it, the way a Force + // Rebuff does: never while health is under Heal At, and it stops once nothing is due. A short fight + // (the 11-20 Thread dispel case) is over long before that and still waits. + internal const int BuffFightWaitMaxSec = 120; + private bool _buffFightPass; // a pass let through a fight that doesn't end + private bool _buffFightPassNeed; // NeedsAnyBuff, asked at most once a second during a pass + private DateTime _buffFightPassCheckedAt = DateTime.MinValue; + /// True in a fight: no new buff cast. A Force Rebuff the player asked for waits only while health /// is under Heal At. Logs the start (when there are buffs to cast) and the end of each wait. public bool BuffsWaitForFight() @@ -402,12 +414,34 @@ public partial class BuffManager : IDisposable bool fight = InCombatNow(); bool hurt = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt; bool playersOwn = _isForceRebuffing && !_isAutoBatchRebuff; - bool wait = fight && (!playersOwn || hurt); DateTime now = RynthClock.Now; + if (_buffFightPass) + { + // The pass ends with the fight or once nothing is due. + if ((now - _buffFightPassCheckedAt).TotalMilliseconds >= 1000) + { + _buffFightPassCheckedAt = now; + _buffFightPassNeed = NeedsAnyBuff(); + } + if (!fight || !_buffFightPassNeed) + { + _buffFightPass = false; + _host.Log($"[Buff] the rebuff pass in the fight is done ({(fight ? "nothing left to cast" : "the fight is over")})."); + } + } + else if (fight && _buffFightWaitOn && (now - _buffFightWaitSince).TotalSeconds >= BuffFightWaitMaxSec) + { + _buffFightPass = true; + _buffFightPassNeed = true; + _buffFightPassCheckedAt = now; + _host.Log($"[Buff] buffs have waited {(now - _buffFightWaitSince).TotalSeconds:0} s for a fight that doesn't end (a monster always within range): " + + "a full rebuff pass goes now, in the fight, as Force Rebuff does (never under Heal At)."); + } + bool wait = fight && (!(playersOwn || _buffFightPass) || hurt); if (!wait) { if (_buffFightWaitOn) - _host.Log($"[Buff] buffs go on: {(fight ? $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for" : "the fight is over")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s)."); + _host.Log($"[Buff] buffs go on: {(!fight ? "the fight is over" : _buffFightPass ? "the fight doesn't end, so they go in it" : $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s)."); _buffFightWaitOn = false; return false; } @@ -1324,8 +1358,28 @@ public partial class BuffManager : IDisposable /// monster near or hitting must not lower the line. Top Off HP applies then (2026-11-22: Combat off, /// Heal At 0, a monster hitting; every hit made it "a fight", Heal At 0 healed nothing, and the /// character stood until it died). + /// Nor while Boost Loot Priority's looting has the tick over the fight (BoostLootHealsToTopOff): the + /// looter isn't fighting either, so Top Off HP applies and the heal goes before the next pickup. /// - private bool FightHealthLine(bool inCombat) => UseFightVitalLines(inCombat && _settings.EnableCombat); + private bool FightHealthLine(bool inCombat) + => UseFightVitalLines(inCombat && _settings.EnableCombat && !BoostLootTopsOffNow()); + + /// + /// Boost Loot Priority (2026-11-23, the owner: "for loot boost below health max it keeps looting. I + /// think it should interrupt looting and heal"). The looter puts corpses ahead of a close monster at + /// or over Heal At (RynthAiPlugin.BoostLootFirst.cs), and with a monster within Monster Range the + /// health line was Heal At: a looter hit to 70% with Heal At 60 (or 0) looted on and healed nothing. + /// While that looting would have the tick, health uses Top Off HP (the between-fights line): under + /// it the heal wins the arbiter (Buffing halts the loot and keeps the claim), then looting resumes. + /// Set by RynthAiPlugin; null (tests, no plugin) = never. + /// + internal Func? BoostLootHealsToTopOff { get; set; } + + private bool BoostLootTopsOffNow() + { + if (BoostLootHealsToTopOff == null) return false; + try { return BoostLootHealsToTopOff(); } catch { return false; } + } // ── What the activity display says while the arbiter's slot is "Buffing" ── // BotAction stays "Buffing" for every vitals job: it is a control string (CombatManager's diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.LosVerdicts.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.LosVerdicts.cs new file mode 100644 index 0000000..559ff27 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.LosVerdicts.cs @@ -0,0 +1,83 @@ +// ============================================================================ +// RynthCore.Plugin.RynthAi - Combat/CombatManager.LosVerdicts.cs +// Show Line of Sight (2026-11-26, a testing aid): the scan's own line-of-sight +// verdict for each monster it tested, kept for the overlay (LosLineOverlay.cs) +// so the line is drawn in the colour the targeting raycast gave, with no second +// raycast per frame. Filled only while ShowLosLine is on; cleared each scan. +// +// Why: 2026-11-26, a melee character outdoors in 0xB470, locked monsters +// 4.3-4.7 m off in the same outdoor cell behind a wall; the scan's raycast said +// clear, nothing landed, and the target was blacklisted after three no-damage +// attacks. The line shows in game what the raycast thinks. +// ============================================================================ + +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.Plugin.RynthAi; + +public partial class CombatManager +{ + /// One monster's line-of-sight verdict from the last scan. + internal struct LosVerdict + { + /// What the targeting raycast said: true = blocked. + public bool Blocked; + /// The raycast tested geometry (false: clear without a test: raycasting off or warming up, + /// no geometry near the path, too far, no position). + public bool Tested; + /// Where it is blocked, global metres (landblock * 192 + local; Z the height). + public bool HasHit; + public float HitX, HitY, HitZ; + /// Blocked, but melee within MeleeIgnoresLosWithin fights it anyway (the scan kept it). + public bool MeleeThrough; + /// 3D distance at the scan, metres. + public double Distance; + public TargetingFSM.AttackType Type; + public DateTime At; + } + + private readonly Dictionary _losVerdicts = new(); + + /// The last scan's verdicts by monster id (empty while Show Line of Sight is off). + internal IReadOnlyDictionary LosVerdicts => _losVerdicts; + + internal bool TryGetLosVerdict(int id, out LosVerdict verdict) => _losVerdicts.TryGetValue(id, out verdict); + + /// The monster the line goes to: the combat target, else the locked one. + internal int LosLineTargetId => _activeTargetId != 0 ? _activeTargetId : _lockedTargetId; + + /// Start of a scan: the cache holds this scan's verdicts only; on, the raycast reports hit points. + private bool BeginLosVerdicts() + { + bool on = _settings.ShowLosLine; + if (_losVerdicts.Count > 0) _losVerdicts.Clear(); + var fsm = _raycastSystem?.TargetingFSM; + if (fsm != null && fsm.ReportHitPoints != on) fsm.ReportHitPoints = on; + return on; + } + + private void NoteLosVerdict(int id, bool blocked, bool tested, in TargetingFSM.LosDetail detail, double dist, TargetingFSM.AttackType type) + { + var v = new LosVerdict + { + Blocked = blocked, + Tested = tested, + HasHit = blocked && detail.HasHit, + HitX = detail.Hit.X, HitY = detail.Hit.Y, HitZ = detail.Hit.Z, + Distance = dist, + Type = type, + At = RynthClock.Now, + }; + _losVerdicts[id] = v; + } + + private void NoteLosMeleeThrough(int id) + { + if (_losVerdicts.TryGetValue(id, out var v)) { v.MeleeThrough = true; _losVerdicts[id] = v; } + } + + /// Tests: a verdict as a scan would leave it. + internal void SetLosVerdictForTests(int id, LosVerdict verdict) => _losVerdicts[id] = verdict; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index cef5df1..ed95b89 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -1216,6 +1216,7 @@ public partial class CombatManager : IDisposable attackType = DetermineAttackTypeForLOS(); bool losDebug = _settings.LosDebugLog; if (losDebug) LogLosDebugWeapon(); + bool noteLos = BeginLosVerdicts(); // Show Line of Sight (CombatManager.LosVerdicts.cs) // The player's position once per scan: Distance(player, mob) re-read it for every // creature, two host reads per monster 20 times a second (2026-10-02 flood work). @@ -1361,15 +1362,22 @@ public partial class CombatManager : IDisposable } bool losBlocked = false; + bool losTested = false; + TargetingFSM.LosDetail losDetail = default; if (LosBlockedOverride != null) + { losBlocked = LosBlockedOverride(wo.Id); + losTested = true; + } else if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null) { RaycastCheckCount++; - losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out var losDetail); + losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out losDetail); + losTested = losDetail.Checked; if (losBlocked) RaycastBlockCount++; if (losDebug) LogLosDebug(wo, losBlocked, losDetail); } + if (noteLos) NoteLosVerdict(wo.Id, losBlocked, losTested, in losDetail, dist, attackType); // Melee reaches through walls, on both sides: a monster this close is a target when // melee is, or is about to be, the attack (the owner, 2026-11-06). It was left out while @@ -1390,6 +1398,7 @@ public partial class CombatManager : IDisposable if (notePassed) NotePassedOver(wo.Id, dist, PassedOverLos); continue; } + if (noteLos) NoteLosMeleeThrough(wo.Id); losBlocked = false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs index 8ce1e82..2855805 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using RynthCore.PluginSdk; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.MiniRemote.Crafting; using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; @@ -17,9 +18,81 @@ namespace RynthCore.Plugin.RynthAi; /// /// Crafting is chat-driven: issues UseObjectOn (ApplyItem), waits for "You make" chat, /// then advances to the next combine or equips. Retries every 2s if no response. +/// +/// Make ammo when low (a players' request, 2026-11-23; MakeAmmoWhenLow, off by default): a top-off +/// between fights, so the empty-slot path above is rarely needed. The plugin (RynthAiPlugin.Ammo.cs) +/// decides when, on the Make kits when low rules (, a KitAuto of its own): fewer +/// than MakeAmmoBelow arrows, quarrels or darts for the launcher in hand (quiver and pack), nothing +/// else going, no monster near, no hit for 20 s, in peace mode. then makes +/// enough combines of the best recipe the pack and Fletching make reliably (the same choice as the +/// empty-slot path, never a risky one) to reach MakeAmmoUpTo, and wields ammo only if the slot is +/// empty. A fight, a launcher swap or leaving peace mode stops it at once (). /// public class MissileCraftingManager { + // ── Make ammo when low ────────────────────────────────────────────── + /// A plain bundle makes 100, so one combine always lifts you back over this. + public const int DefaultAmmoBelow = 100; + /// Five plain combines, or one wrapped bundle (1000). + public const int DefaultAmmoUpTo = 500; + public const int MaxAmmoBelow = 5000; + public const int MaxAmmoUpTo = 10000; + /// The most combines one top-off makes. + public const int MaxTopOffCombines = 10; + + /// When a top-off may start, and the waits after one (ticked by RynthAiPlugin.Ammo.cs). + internal KitAuto Auto { get; } = new KitAuto { Name = "Make ammo when low", Doing = "make ammo" }; + /// The chat line for the top-off's own lines (the plugin's ChatLine; null = the host's chat). + public Action? Say { get; set; } + + private bool _topOff, _topOffManual; + private int _topOffTarget, _topOffYield, _topOffFailed; + private WeaponCategory _topOffCategory; + private string _topOffOutput = string.Empty; + private KitStopKind? _topOffEndKind; + private string _topOffWhy = string.Empty; + private Func? _topOffEnded; + private volatile bool _makeNowAsked, _stopAsked; + + /// A top-off is under way (it holds the bot while it goes). + public bool TopOffRunning => _topOff && State != CraftState.Idle; + /// The top-off going was asked for (Make ammo now), not started by the low line. + public bool TopOffManual => _topOff && _topOffManual; + /// Combines made in the top-off going. + public int TopOffMade => _topOff ? _combinesCompleted : 0; + /// Combines the top-off going plans. + public int TopOffPlanned => _topOff ? _totalCombines : 0; + /// The last top-off's summary line ("" = none this session). + public string LastTopOffSummary { get; private set; } = string.Empty; + /// The last look at the launcher and the ammo (for the panels; null = none yet). + internal AmmoLook? LastLook { get; private set; } + /// Make ammo now: asked until this (plugin clock, ms; 0 = not asked). + internal long MakeNowUntilMs { get; set; } + + /// A panel's Make ammo now (any thread): the plugin takes it on its next tick. + public void RequestMakeNow() => _makeNowAsked = true; + /// A panel's Stop (any thread): the plugin takes it on its next tick. + public void RequestStop() => _stopAsked = true; + internal bool TakeMakeNowRequest() { if (!_makeNowAsked) return false; _makeNowAsked = false; return true; } + internal bool TakeStopRequest() { if (!_stopAsked) return false; _stopAsked = false; return true; } + + /// The launcher in hand and its ammo: what a top-off would make and why not. + internal sealed record AmmoLook(bool Launcher, WeaponCategory Category, int Carried, bool Wielded, + AmmoRecipe? Recipe, int Combines, string PackWhy) + { + public string CarriedText => AmmoText(Carried, Category); + } + + /// "1 arrow", "230 quarrels", "12 darts". + public static string AmmoText(int n, WeaponCategory c) => $"{n} {AmmoNoun(c, n)}"; + + public static string AmmoNoun(WeaponCategory c, int n = 2) => c switch + { + WeaponCategory.Crossbow => n == 1 ? "quarrel" : "quarrels", + WeaponCategory.Atlatl => n == 1 ? "dart" : "darts", + _ => n == 1 ? "arrow" : "arrows", + }; + private readonly RynthCoreHost _host; private readonly LegacyUiSettings _settings; private WorldObjectCache? _objectCache; @@ -105,6 +178,7 @@ public class MissileCraftingManager // crafting off mid-craft must let go too. if (!_settings.EnableMissileCrafting) { + if (_topOff) _topOffEndKind = KitStopKind.Other; if (State != CraftState.Idle) Reset("Missile crafting turned off"); return; } @@ -131,6 +205,191 @@ public class MissileCraftingManager } } + // ══════════════════════════════════════════════════════════════════ + // MAKE AMMO WHEN LOW (the top-off between fights) + // ══════════════════════════════════════════════════════════════════ + + /// + /// The launcher in hand, the ammo carried for it (quiver and pack, stacks summed), and what a + /// top-off would make: the best recipe the pack and Fletching make reliably (the empty-slot path's + /// own choice, AmmoRecipes.BestCraftable; never one under its 90% line) and how many combines the + /// bundles allow. false re-reads a scan under a second old. + /// + internal AmmoLook LookTopOff(bool forceRefresh = true) + { + var inv = GetInventory(forceRefresh); + AmmoLook look = LookTopOff(inv); + LastLook = look; + return look; + } + + private AmmoLook LookTopOff(List inv) + { + if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out _)) + return new AmmoLook(false, _lastWeaponCategory, 0, false, null, 0, "no bow, crossbow or atlatl in hand"); + _lastWeaponCategory = category; + int carried = CountAmmo(inv, category); + bool wielded = HasWieldedAmmo(inv, category); + + var fletching = _charSkills?[AcSkillType.Fletching]; + if (fletching != null && fletching.Training < 2) + return new AmmoLook(true, category, carried, wielded, null, 0, "Fletching is untrained"); + int skill = fletching?.Buffed ?? 250; + var best = AmmoRecipes.BestCraftable(inv.Select(i => i.Name), category, skill, out var tooHard); + if (best == null) + { + string why = tooHard != null + ? $"{tooHard.OutputName} is about {AmmoRecipes.SuccessChance(skill, tooHard.Difficulty):P0} with Fletching {skill}, under the 90% line (a failed combine destroys both bundles)" + : $"no heads and shafts for {AmmoNoun(category)} carried"; + return new AmmoLook(true, category, carried, wielded, null, 0, why); + } + int pairs = PairsCarried(best, inv); + return new AmmoLook(true, category, carried, wielded, best, pairs, + pairs > 0 ? string.Empty : $"no bundles for {best.OutputName}"); + } + + /// Loose ammo for the launcher: the stack in the quiver and every stack in the packs. + private int CountAmmo(List inv, WeaponCategory category) + { + int n = 0; + var seen = new HashSet(); + foreach (var item in WornCandidates(inv)) + { + if (!seen.Add(item.Id) || !IsLooseAmmo(item, category)) continue; + n += Math.Max(1, item.Values(LongValueKey.StackCount, 1)); + } + return n; + } + + /// Combines the first head and shaft stacks allow (an Infinite head is never used up). + private static int PairsCarried(AmmoRecipe recipe, List inv) + { + var head = inv.FirstOrDefault(i => recipe.IsHead(i.Name)); + var shaft = inv.FirstOrDefault(i => recipe.IsShaft(i.Name)); + if (head == null || shaft == null) return 0; + int heads = AmmoRecipes.HeadIsInfinite(recipe) ? int.MaxValue : Math.Max(1, head.Values(LongValueKey.StackCount, 1)); + int shafts = Math.Max(1, shaft.Values(LongValueKey.StackCount, 1)); + return Math.Min(heads, shafts); + } + + /// + /// Starts a top-off toward (the caller has checked it is safe: no fight, + /// no monster near, in peace mode). is the start line's reason ("under 100"). + /// hears how it ended and the combines made, and returns what the summary + /// adds (the next try). Returns "" or why not. + /// + internal string StartTopOff(int target, bool manual, string why, Func? ended) + { + if (!_settings.EnableMissileCrafting) return "Enable Missile Crafting is off"; + if (State != CraftState.Idle) return "ammo crafting is already under way"; + if (HoldWhile?.Invoke() == true) return "a launcher swap is under way"; + if (InFight()) return "a fight is on"; + var inv = GetInventory(forceRefresh: true); + AmmoLook look = LookTopOff(inv); + LastLook = look; + if (!look.Launcher || look.Recipe == null || look.Combines <= 0) return look.PackWhy; + if (look.Carried >= target) return $"{look.CarriedText} carried already (makes up to {target})"; + + var recipe = look.Recipe; + int yield = AmmoRecipes.EstimatedYield(recipe); + int combines = Math.Clamp((target - look.Carried + yield - 1) / yield, 1, Math.Min(MaxTopOffCombines, look.Combines)); + _topOffQuiet = true; + try { StartCrafting(recipe, inv, upgrade: false, pairs: combines); } + finally { _topOffQuiet = false; } + if (State != CraftState.Combining) return StatusMessage.Length > 0 ? StatusMessage : "the bundles couldn't be read"; + + _topOff = true; + _topOffManual = manual; + _topOffTarget = target; + _topOffYield = yield; + _topOffFailed = 0; + _topOffCategory = look.Category; + _topOffOutput = recipe.OutputName; + _topOffEndKind = null; + _topOffWhy = string.Empty; + _topOffEnded = ended; + string line = $"[RynthAi] Make ammo when low: {look.CarriedText} carried ({why}); making {Combines(combines)} of " + + $"{recipe.OutputName}, about {combines * yield}, toward {target}."; + SayLine(line); + RynthLog.Write(LogCat.Crafting, "[Ammo] start: " + line); + return string.Empty; + } + + /// Stops the top-off going (a monster, a hit, the player's Stop, ...): one summary line. + internal void StopTopOff(string why, KitStopKind kind) + { + if (!_topOff) return; + _topOffEndKind = kind; + _topOffWhy = why; + Reset(why); + } + + /// What stops a top-off from inside crafting ("" = go on): a fight, a launcher swap, leaving peace mode. + private string TopOffDanger() + { + if (InFight()) return "a fight"; + if (HoldWhile?.Invoke() == true) return "a launcher swap"; + try + { + if (_peaceSent && _host.HasGetCurrentCombatMode && _host.GetCurrentCombatMode() != CombatMode.NonCombat) + return "left peace mode"; + } + catch { } + return string.Empty; + } + + /// The top-off's summary line and the end callback (from , before it clears the craft). + private void FinishTopOff(string reason) + { + int made = _combinesCompleted, planned = _totalCombines, failed = _topOffFailed; + KitStopKind kind = _topOffEndKind ?? (made > 0 ? KitStopKind.Finished : KitStopKind.Refused); + string why = _topOffWhy.Length > 0 ? _topOffWhy : reason; + if (why.StartsWith("Done", StringComparison.Ordinal)) + why = made >= planned ? $"made the {Combines(planned)} planned" : "done"; + var ended = _topOffEnded; + string noun = AmmoNoun(_topOffCategory); + int yield = _topOffYield; + string output = _topOffOutput; + _topOff = false; + _topOffManual = false; + _topOffEnded = null; + _topOffEndKind = null; + _topOffWhy = string.Empty; + + string tail = string.Empty; + try { tail = ended?.Invoke(kind, made) ?? string.Empty; } + catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "Make ammo when low: the end of a top-off"); } + string madeText = made == 0 ? "made nothing" : $"made {Combines(made)} of {output} (about {made * yield} {noun})"; + string failText = failed == 0 ? "" : $", {Combines(failed)} failed (a failed combine destroys both bundles)"; + string line = $"[RynthAi] Make ammo when low: {madeText}{failText}. Stopped: {why}.{tail}"; + LastTopOffSummary = line; + SayLine(line); + RynthLog.Write(LogCat.Crafting, "[Ammo] " + line); + } + + private static string Combines(int n) => n == 1 ? "1 combine" : $"{n} combines"; + + /// All combines answered (or a timeout after some): wield only if the slot is empty, else done. + private bool TopOffSlotFilled() + { + var inv = GetInventory(forceRefresh: true); + return HasWieldedAmmo(inv, ResolveWeaponCategory(inv)); + } + + private void SayLine(string line) + { + try + { + if (Say != null) Say(line); + else if (_host.HasWriteToChat) _host.WriteToChat(line, 1); + } + catch { } + } + + // While a top-off starts or goes, crafting's own "[RynthAi Craft]" lines go to the log only: + // the top-off says one line when it starts and one when it stops. + private bool _topOffQuiet; + // ══════════════════════════════════════════════════════════════════ // CHAT HANDLER — called from RynthAiPlugin.OnChatWindowText // ══════════════════════════════════════════════════════════════════ @@ -139,10 +398,15 @@ public class MissileCraftingManager { if (State != CraftState.Combining) return; if (string.IsNullOrEmpty(text)) return; - if (text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) < 0) return; + bool made = text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) >= 0; + // A top-off counts a failed combine and goes on with the next (the empty-slot path never + // matched failures and retries until its timeout, as before). + bool failed = _topOff && !made && text.IndexOf("You fail to make", StringComparison.OrdinalIgnoreCase) >= 0; + if (!made && !failed) return; - _combinesCompleted++; - ChatLog($"Craft confirmed ({_combinesCompleted}/{_totalCombines})"); + if (made) _combinesCompleted++; else _topOffFailed++; + if (_topOff) _phaseStart = RynthClock.Now; // each combine of a top-off gets its own timeout + ChatLog(made ? $"Craft confirmed ({_combinesCompleted}/{_totalCombines})" : $"Combine failed ({_topOffFailed})"); if (_pendingBundlePairs.Count > 0) { @@ -254,7 +518,8 @@ public class MissileCraftingManager Reset("No ammo and no bundles available"); } - private void StartCrafting(AmmoRecipe recipe, List inv, bool upgrade = false) + /// Combines to queue (a top-off's count); 0 = the empty-slot path's up to 2. + private void StartCrafting(AmmoRecipe recipe, List inv, bool upgrade = false, int pairs = 0) { _craftIsUpgrade = upgrade; _currentRecipe = recipe; @@ -278,7 +543,7 @@ public class MissileCraftingManager // Check stack sizes to decide how many combines (1 or 2) int availableHeads = headItems[0].Values(LongValueKey.StackCount, 1); int availableShafts = shaftItems[0].Values(LongValueKey.StackCount, 1); - int pairCount = Math.Min(2, Math.Min(availableHeads, availableShafts)); + int pairCount = pairs > 0 ? pairs : Math.Min(2, Math.Min(availableHeads, availableShafts)); // Queue combines with same IDs — server decrements stacked bundles for (int i = 0; i < pairCount; i++) @@ -317,6 +582,14 @@ public class MissileCraftingManager private void ProcessCombining() { + // Make ammo when low: a top-off never holds the bot into a fight, a launcher swap or out of + // peace mode. It stops at once; the combine already sent finishes on the server. + if (_topOff) + { + string danger = TopOffDanger(); + if (danger.Length > 0) { StopTopOff(danger, KitStopKind.Danger); return; } + } + // In a fight, with ammo to shoot (carried before the craft, or a combine already made): // stop holding combat and wield the best ammo carried now. if (!_allCombinesDone && (_craftIsUpgrade || _combinesCompleted > 0) && InFight()) @@ -334,6 +607,8 @@ public class MissileCraftingManager if (_allCombinesDone) { + // A top-off wields only into an empty slot; the ammo in the quiver stays. + if (_topOff && TopOffSlotFilled()) { Reset("Done"); return; } StatusMessage = $"Equipping {_currentRecipe!.OutputName}..."; _equipTargetId = 0; SetState(CraftState.EquippingAmmo); @@ -342,7 +617,14 @@ public class MissileCraftingManager if ((RynthClock.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS) { - if (_combinesCompleted > 0) + if (_topOff && (_combinesCompleted > 0 || _topOffFailed > 0)) + { + _topOffWhy = $"no answer to the next combine after {Combines(_combinesCompleted + _topOffFailed)}"; + if (_combinesCompleted == 0 || TopOffSlotFilled()) { Reset("Craft timed out"); return; } + _equipTargetId = 0; + SetState(CraftState.EquippingAmmo); + } + else if (_combinesCompleted > 0) { ChatLog($"Timeout after {_combinesCompleted} combine(s). Equipping what we have."); _equipTargetId = 0; @@ -642,7 +924,9 @@ public class MissileCraftingManager private void Reset(string reason) { - if (State != CraftState.Idle || reason.IndexOf("bundle", StringComparison.OrdinalIgnoreCase) >= 0) + if (_topOff) + FinishTopOff(reason); // the top-off's own summary line (crafting's are quiet for it) + else if (State != CraftState.Idle || reason.IndexOf("bundle", StringComparison.OrdinalIgnoreCase) >= 0) ChatLog(reason); StatusMessage = reason; @@ -667,6 +951,11 @@ public class MissileCraftingManager private void ChatLog(string msg) { + if (_topOff || _topOffQuiet) + { + try { _host.Log($"[RynthAi] MissileCraft (Make ammo when low): {msg}"); } catch { } + return; + } try { _host.WriteToChat($"[RynthAi Craft] {msg}", 1); } catch { } } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 4724b0c..2b3b274 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -1584,11 +1584,21 @@ public class WorldObjectCache lock (_gate) return _homePack.TryGetValue(itemId, out int p) ? p : 0; } + /// + /// Free main-pack slots kept for loot when a weapon with no known home goes to the main pack + /// (loot goes only into the main pack). + /// + internal const int UnknownHomeMainPackMargin = 4; + /// /// As , for putting /// away: the pack they all came from when it still has - /// free slots (the main pack only with ), - /// else the usual choice. + /// free slots (the main pack only with ); + /// with no home known for any of them (wielded since login, never seen in a pack), the main pack + /// while it keeps slots more, as the game itself unwields; + /// else the usual choice. R-20261125-040855-4588: "If I manually swap out wands from my main pack the + /// one being disarmed goes into the main pack ... If the macro does this ... it puts the wand it is + /// removing into the 1st pack down". /// public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache, bool includeMainPack, int requireFree, IReadOnlyList forItems) @@ -1598,15 +1608,20 @@ public class WorldObjectCache if (playerId == 0) return 0; var inv = cache.GetDirectInventory(forceRefresh: true); int home = 0; + bool anyKnown = false; foreach (int id in forItems) { int h = id == 0 ? 0 : cache.HomePackOf(id); + if (h != 0) anyKnown = true; if (h == 0 || (home != 0 && h != home)) { home = 0; break; } home = h; } if (home != 0 && (home != playerId || includeMainPack) && FreeSlotsIn(inv, playerId, home, host) >= Math.Max(1, requireFree)) return home; + if (!anyKnown && forItems.Count > 0 && includeMainPack + && FreeSlotsIn(inv, playerId, playerId, host) >= Math.Max(1, requireFree) + UnknownHomeMainPackMargin) + return playerId; return FindPackFor(inv, playerId, includeMainPack, requireFree, host); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/CommandButtons/CommandButtons.cs b/Plugins/RynthCore.Plugin.RynthAi/CommandButtons/CommandButtons.cs new file mode 100644 index 0000000..53ea930 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CommandButtons/CommandButtons.cs @@ -0,0 +1,520 @@ +// ============================================================================ +// RynthAi - CommandButtons/CommandButtons.cs +// Command Buttons (2026-11-26, a player's ask: "a configurable window of blank +// buttons you can program with simple 1 line chat commands"): a grid of +// buttons, each a label and one chat line (/ra start, *snow angel*, @home, +// /lua start threads ...) sent as if typed in the chat box. +// +// Three lists, as the Timed Commands keep them: this character, every +// character on this server, and every character. The window shows all three +// (this character's first). Files beside the settings profiles, so switching +// a settings profile keeps them: +// SettingsProfiles\\\command_buttons.json (with the grid's +// layout: columns, button width and height), +// SettingsProfiles\\command_buttons.json and +// SettingsProfiles\command_buttons.json. +// "Copy from" takes another character's buttons (same server) into this +// character's list. +// +// Pure (no host, no ImGui): the host tests drive it. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthAi.CommandButtons; + +/// Which list a button is in. +internal enum ButtonScope { Character = 0, Server = 1, All = 2 } + +/// One button: what it says, the chat line it sends, its colour and whether it asks first. +internal sealed class CommandButton +{ + public const int MaxLabel = 32; + + public string Label = string.Empty; + public string Command = string.Empty; + /// The button's fill, ImGui ABGR with full alpha; 0 = the theme's button colour. + public uint Color; + /// Asks "Send ...?" before it sends (for a command that is hard to take back). + public bool Confirm; + + /// What the button shows: its label, else its command, else "(empty)". + public string Shown => Label.Length > 0 ? Label : Command.Length > 0 ? Command : "(empty)"; + + public CommandButton Clone() => new() { Label = Label, Command = Command, Color = Color, Confirm = Confirm }; + + /// A label: one line, no control characters, trimmed, at most characters. + public static string CleanLabel(string? text) + { + string t = CommandLine.OneLine(text); + return t.Length > MaxLabel ? t[..MaxLabel].TrimEnd() : t; + } + + // ── Colours: "#RRGGBB" in the file, ImGui ABGR in memory ─────────── + + /// "#RRGGBB" for an ABGR colour; "" for 0 (the theme's colour). + public static string ColorText(uint abgr) => abgr == 0 + ? string.Empty + : "#" + (abgr & 0xFF).ToString("X2", CultureInfo.InvariantCulture) + + ((abgr >> 8) & 0xFF).ToString("X2", CultureInfo.InvariantCulture) + + ((abgr >> 16) & 0xFF).ToString("X2", CultureInfo.InvariantCulture); + + /// "#RRGGBB" or "RRGGBB" to ABGR with full alpha. False (and 0) for anything else. + public static bool TryParseColor(string? text, out uint abgr) + { + abgr = 0; + string t = (text ?? string.Empty).Trim(); + if (t.StartsWith('#')) t = t[1..]; + if (t.Length != 6 || !uint.TryParse(t, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint rgb)) return false; + uint r = (rgb >> 16) & 0xFF, g = (rgb >> 8) & 0xFF, b = rgb & 0xFF; + abgr = 0xFF000000u | (b << 16) | (g << 8) | r; + return true; + } + + /// Text that reads on : near-black on a light fill, near-white on a dark one. + public static uint TextOn(uint fillAbgr) + { + double r = fillAbgr & 0xFF, g = (fillAbgr >> 8) & 0xFF, b = (fillAbgr >> 16) & 0xFF; + return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? 0xFF141414u : 0xFFF2F2F2u; + } +} + +/// The grid's shape (this character's file). +internal sealed class ButtonLayout +{ + /// Columns 0 = as many as fit the window's width. + public const int ColumnsMin = 0, ColumnsMax = 12, WidthMin = 40, WidthMax = 320, HeightMin = 18, HeightMax = 96; + public const int DefaultWidth = 110, DefaultHeight = 28; + + public int Columns; + public int Width = DefaultWidth; + public int Height = DefaultHeight; + + public void Clamp() + { + Columns = Math.Clamp(Columns, ColumnsMin, ColumnsMax); + Width = Math.Clamp(Width, WidthMin, WidthMax); + Height = Math.Clamp(Height, HeightMin, HeightMax); + } + + public ButtonLayout Clone() => new() { Columns = Columns, Width = Width, Height = Height }; + + /// + /// How many columns the grid draws: when set (1-12), else as many + /// -wide buttons with between them as fit + /// (at least one, at most 12). + /// + public static int ColumnsFor(int columns, float available, float buttonWidth, float gap) + { + if (columns > 0) return Math.Min(columns, ColumnsMax); + if (!(buttonWidth > 0) || !float.IsFinite(available)) return 1; + int fit = (int)Math.Floor((available + gap) / (buttonWidth + gap)); + return Math.Clamp(fit, 1, ColumnsMax); + } + + /// "Auto" or "4". + public static string ColumnsText(int columns) => columns > 0 ? columns.ToString(CultureInfo.InvariantCulture) : "Auto"; +} + +/// What a chat line is, as the chat box would send it. +internal enum CommandKind +{ + /// Nothing to send. + Empty, + /// A slash command: the game's own (/loc, /fillcomps), RynthCore's /rc, a plugin's (/ra, /lua, /rdef ...). + Slash, + /// An emote: *wave*, @e text, ; text. + Emote, + /// A server command: @home, @hp (the server runs it; nothing is said aloud). + Server, + /// Plain text: said aloud in local chat. + Say, +} + +/// A chat line checked: the line as it will be sent, what it is, and why it can't be sent (null: it can). +internal readonly record struct CommandCheck(string Line, CommandKind Kind, string? Problem) +{ + public bool CanSend => Problem == null && Kind != CommandKind.Empty; +} + +/// The rules for a button's chat line. +internal static class CommandLine +{ + /// As long as a chat line the engine sends (its sections manifest's command limit, a timed command's). + public const int MaxLength = 200; + + private static readonly string[] AtEmotes = { "@emotes", "@emote", "@em", "@e" }; + + /// One line: line breaks and tabs become spaces, other control characters go, trimmed. + public static string OneLine(string? text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var sb = new StringBuilder(text.Length); + foreach (char c in text) + { + if (c is '\r' or '\n' or '\t') sb.Append(' '); + else if (!char.IsControl(c)) sb.Append(c); + } + return sb.ToString().Trim(); + } + + /// A command as stored: one line, at most characters. + public static string Clean(string? text) + { + string t = OneLine(text); + return t.Length > MaxLength ? t[..MaxLength].TrimEnd() : t; + } + + /// What (cleaned) is, as RynthCore's chat dispatcher routes it. + public static CommandKind KindOf(string line) + { + if (line.Length == 0) return CommandKind.Empty; + char first = line[0]; + if (first == '/') return CommandKind.Slash; + if (first is ';' or ':') return line.Length > 1 ? CommandKind.Emote : CommandKind.Say; + if (first == '*') + return line.Length > 2 && line[^1] == '*' && line.AsSpan(1, line.Length - 2).Trim().Length > 0 ? CommandKind.Emote : CommandKind.Say; + if (first == '@') + { + foreach (string e in AtEmotes) + if (line.StartsWith(e, StringComparison.OrdinalIgnoreCase) && (line.Length == e.Length || char.IsWhiteSpace(line[e.Length]))) + return CommandKind.Emote; + return line.Length > 1 ? CommandKind.Server : CommandKind.Say; + } + return CommandKind.Say; + } + + /// + /// Checks a button's chat line. Refused: more than one line's worth (the cleaned line is what goes), + /// longer than , and a button that presses buttons ("/ra buttons press"), + /// which could press itself forever. Empty is no problem while editing; it just sends nothing. + /// + public static CommandCheck Check(string? text) + { + string raw = text ?? string.Empty; + string line = OneLine(raw); + CommandKind kind = KindOf(line); + if (kind == CommandKind.Empty) return new CommandCheck(line, kind, null); + if (line.Length > MaxLength) + return new CommandCheck(line[..MaxLength], kind, $"Too long: a chat line is at most {MaxLength} characters."); + if (raw.IndexOfAny(new[] { '\r', '\n' }) >= 0) + return new CommandCheck(line, kind, "One line only: each button sends one chat line."); + if (PressesButtons(line)) + return new CommandCheck(line, kind, "A button can't press buttons (it could press itself forever)."); + return new CommandCheck(line, kind, null); + } + + /// "/ra buttons press ..." (or run), in any case and spacing. + public static bool PressesButtons(string line) + { + string[] w = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (w.Length < 3 || !w[0].Equals("/ra", StringComparison.OrdinalIgnoreCase)) return false; + if (!(w[1].Equals("buttons", StringComparison.OrdinalIgnoreCase) || w[1].Equals("button", StringComparison.OrdinalIgnoreCase))) return false; + int at = 2; + if (w[at].ToLowerInvariant() is "server" or "all" or "char" or "character" or "me") at++; + return w.Length > at && w[at].ToLowerInvariant() is "press" or "run"; + } + + /// What pressing it does, in a few words (the edit row's tooltip). + public static string Describe(CommandKind kind) => kind switch + { + CommandKind.Slash => "A chat command, as if typed (the game's, RynthCore's /rc, or a plugin's: /ra, /lua, /rdef ...).", + CommandKind.Emote => "An emote.", + CommandKind.Server => "A server command (the server runs it; nothing is said aloud).", + CommandKind.Say => "Plain text: said aloud in local chat.", + _ => "No command yet: pressing it does nothing.", + }; +} + +/// The three lists, the layout and their files. +internal sealed class CommandButtonSet +{ + public const string FileName = "command_buttons.json"; + public const int MaxPerList = 60; + public const int FileVersion = 1; + + /// Locks every read and edit (the window is on the render thread, presses and saves on the tick). + public readonly object Sync = new(); + private readonly List[] _lists = { new(), new(), new() }; + private readonly string[] _paths = { string.Empty, string.Empty, string.Empty }; + private readonly bool[] _dirty = new bool[3]; + + /// The grid's shape, saved with this character's list. Lock . + public ButtonLayout Layout { get; private set; } = new(); + + public string Character { get; private set; } = string.Empty; + public string Server { get; private set; } = string.Empty; + public bool Loaded { get; private set; } + /// When the last edit was made (the tick saves a moment later). + public long ChangedAtMs { get; private set; } + + /// The list for ; lock around any use. + public List List(ButtonScope scope) => _lists[(int)scope]; + + public static string ScopeName(ButtonScope s) => s switch + { + ButtonScope.Character => "this character", + ButtonScope.Server => "this server", + _ => "all characters", + }; + + /// + /// Loads the three lists for the character whose settings folder is + /// (SettingsProfiles\<server>\<character>). A missing file is an empty list; one that can't be + /// read is reported in and left alone (it isn't saved over until edited). + /// + public void Load(string charFolder, List? problems = null) + { + string? serverFolder = Path.GetDirectoryName(charFolder); + string? baseFolder = serverFolder != null ? Path.GetDirectoryName(serverFolder) : null; + lock (Sync) + { + Character = Path.GetFileName(charFolder); + Server = serverFolder != null ? Path.GetFileName(serverFolder) : string.Empty; + _paths[(int)ButtonScope.Character] = Path.Combine(charFolder, FileName); + _paths[(int)ButtonScope.Server] = serverFolder != null ? Path.Combine(serverFolder, FileName) : string.Empty; + _paths[(int)ButtonScope.All] = baseFolder != null ? Path.Combine(baseFolder, FileName) : string.Empty; + Layout = new ButtonLayout(); + for (int i = 0; i < 3; i++) + { + _lists[i].Clear(); + _dirty[i] = false; + if (_paths[i].Length == 0 || !File.Exists(_paths[i])) continue; + try + { + _lists[i].AddRange(Parse(File.ReadAllText(_paths[i]), out ButtonLayout? layout)); + if (i == (int)ButtonScope.Character && layout != null) Layout = layout; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + problems?.Add($"{ScopeName((ButtonScope)i)} ({_paths[i]}): {ex.Message}"); + } + } + Loaded = true; + } + } + + /// Forgets the character (logout). + public void Unload() + { + lock (Sync) + { + for (int i = 0; i < 3; i++) { _lists[i].Clear(); _paths[i] = string.Empty; _dirty[i] = false; } + Layout = new ButtonLayout(); + Character = Server = string.Empty; + Loaded = false; + } + } + + /// A list (or, for this character, the layout) was edited. Call under . + public void MarkChanged(ButtonScope scope, long nowMs) + { + _dirty[(int)scope] = true; + ChangedAtMs = nowMs; + } + + public bool AnyDirty { get { lock (Sync) return _dirty[0] || _dirty[1] || _dirty[2]; } } + + /// Writes every edited list (temp file, then replace). Problems go to . + public void SaveDirty(List? problems = null) + { + lock (Sync) + { + for (int i = 0; i < 3; i++) + { + if (!_dirty[i] || _paths[i].Length == 0) continue; + _dirty[i] = false; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(_paths[i])!); + string tmp = _paths[i] + ".tmp"; + File.WriteAllText(tmp, Serialize(_lists[i], i == (int)ButtonScope.Character ? Layout : null)); + File.Move(tmp, _paths[i], overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + problems?.Add($"{ScopeName((ButtonScope)i)} ({_paths[i]}): {ex.Message}"); + } + } + } + } + + /// + /// Adds a button to 's list and marks it changed. Null when the list is full + /// (). Call under . + /// + public CommandButton? Add(ButtonScope scope, string? label, string? command, long nowMs) + { + List list = List(scope); + if (list.Count >= MaxPerList) return null; + var b = new CommandButton { Label = CommandButton.CleanLabel(label), Command = CommandLine.Clean(command) }; + list.Add(b); + MarkChanged(scope, nowMs); + return b; + } + + /// Moves button by places in its list. False when it can't. + public bool Move(ButtonScope scope, int index, int delta, long nowMs) + { + List list = List(scope); + int to = index + delta; + if (index < 0 || index >= list.Count || to < 0 || to >= list.Count || delta == 0) return false; + CommandButton b = list[index]; + list.RemoveAt(index); + list.Insert(to, b); + MarkChanged(scope, nowMs); + return true; + } + + // ── Copy from another character ───────────────────────────────────── + + /// + /// The other characters on this server with buttons of their own (their folder names, sorted), for + /// "Copy from". Empty before a load. + /// + public List OtherCharacters() + { + var names = new List(); + string own, serverFolder; + lock (Sync) + { + own = _paths[(int)ButtonScope.Character]; + serverFolder = own.Length > 0 ? Path.GetDirectoryName(Path.GetDirectoryName(own)) ?? string.Empty : string.Empty; + } + if (serverFolder.Length == 0 || !Directory.Exists(serverFolder)) return names; + try + { + foreach (string dir in Directory.GetDirectories(serverFolder)) + { + string name = Path.GetFileName(dir); + if (name.Equals(Character, StringComparison.OrdinalIgnoreCase)) continue; + if (File.Exists(Path.Combine(dir, FileName))) names.Add(name); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + names.Sort(StringComparer.OrdinalIgnoreCase); + return names; + } + + /// + /// Appends 's own buttons (same server) to this character's list, as many as + /// fit. Returns how many were added; -1 when that character's buttons can't be read (the reason in + /// ). + /// + public int CopyFrom(string character, long nowMs, out string problem) + { + problem = string.Empty; + string own; + lock (Sync) own = _paths[(int)ButtonScope.Character]; + string? serverFolder = own.Length > 0 ? Path.GetDirectoryName(Path.GetDirectoryName(own)) : null; + if (serverFolder == null || string.IsNullOrWhiteSpace(character) || character.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 + || character is "." or "..") + { + problem = "no such character"; + return -1; + } + string path = Path.Combine(serverFolder, character, FileName); + List theirs; + try { theirs = Parse(File.ReadAllText(path), out _); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + problem = ex is FileNotFoundException or DirectoryNotFoundException ? "they have no buttons" : ex.Message; + return -1; + } + int added = 0; + lock (Sync) + { + List list = List(ButtonScope.Character); + foreach (CommandButton b in theirs) + { + if (list.Count >= MaxPerList) break; + list.Add(b.Clone()); + added++; + } + if (added > 0) MarkChanged(ButtonScope.Character, nowMs); + } + return added; + } + + // ── File format ───────────────────────────────────────────────────── + // {"version":1,"layout":{"columns","width","height"},"buttons":[{"label","command","color":"#RRGGBB","confirm"}]} + // "layout" only in a character's file; "color" left out for the theme's colour. + + public static string Serialize(IReadOnlyList list, ButtonLayout? layout) + { + using var stream = new MemoryStream(); + using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + w.WriteNumber("version", FileVersion); + if (layout != null) + { + w.WriteStartObject("layout"); + w.WriteNumber("columns", layout.Columns); + w.WriteNumber("width", layout.Width); + w.WriteNumber("height", layout.Height); + w.WriteEndObject(); + } + w.WriteStartArray("buttons"); + foreach (CommandButton b in list) + { + w.WriteStartObject(); + w.WriteString("label", b.Label); + w.WriteString("command", b.Command); + if (b.Color != 0) w.WriteString("color", CommandButton.ColorText(b.Color)); + w.WriteBoolean("confirm", b.Confirm); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// The buttons in a file (cleaned, at most ), and its layout if it has one (clamped). + public static List Parse(string json, out ButtonLayout? layout) + { + layout = null; + var list = new List(); + using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return list; + if (root.TryGetProperty("layout", out JsonElement l) && l.ValueKind == JsonValueKind.Object) + { + layout = new ButtonLayout + { + Columns = Int(l, "columns", 0), + Width = Int(l, "width", ButtonLayout.DefaultWidth), + Height = Int(l, "height", ButtonLayout.DefaultHeight), + }; + layout.Clamp(); + } + if (!root.TryGetProperty("buttons", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return list; + foreach (JsonElement e in arr.EnumerateArray()) + { + if (list.Count >= MaxPerList) break; + if (e.ValueKind != JsonValueKind.Object) continue; + var b = new CommandButton + { + Label = CommandButton.CleanLabel(Str(e, "label")), + Command = CommandLine.Clean(Str(e, "command")), + Confirm = e.TryGetProperty("confirm", out JsonElement c) && c.ValueKind == JsonValueKind.True, + }; + if (CommandButton.TryParseColor(Str(e, "color"), out uint color)) b.Color = color; + list.Add(b); + } + return list; + } + + private static string? Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + + private static int Int(JsonElement e, string name, int fallback) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) && double.IsFinite(d) + ? (int)Math.Clamp(Math.Round(d), int.MinValue, int.MaxValue) + : fallback; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CommandButtons/CommandButtonsWindow.cs b/Plugins/RynthCore.Plugin.RynthAi/CommandButtons/CommandButtonsWindow.cs new file mode 100644 index 0000000..b64aaa7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CommandButtons/CommandButtonsWindow.cs @@ -0,0 +1,623 @@ +// ============================================================================ +// RynthAi - CommandButtons/CommandButtonsWindow.cs +// The Command Buttons window (2026-11-26): a grid of buttons, each sending one +// chat line, and an edit view to make them. RynthCore hosts the window (the +// sections manifest's "commandbuttons" window, plugin API v89: header, +// pop-out, resize, remembered place; no bar button: the dashboard's options +// menu, /ra buttons and Find a Feature open it) and calls Draw through +// RynthPluginRenderEmbed. +// +// Grid: this character's buttons, then this server's, then every character's, +// as many columns as set (Auto: as many as fit). A click sends the line (asks +// first for a button with "Ask" ticked); a right-click opens the edit view on +// that button's list. The pencil in the header opens the edit view. +// +// Edit view: the three lists as tabs; per button: move up / down, label, +// command (with a mark saying what it is, or why it can't be sent), colour, +// Ask, Send now and Remove; Add button; Copy from another character (this +// character's tab); the grid's columns and button size. +// +// AC's render thread. Edits go straight into the lists under the set's lock and +// mark them changed (the tick saves them a moment later); presses are queued +// for the tick. Looks: Shared/RynthUi (the player's theme). +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; +using static RynthCore.Plugin.Shared.RynthUi.RynthUi; + +namespace RynthCore.Plugin.RynthAi.CommandButtons; + +internal sealed class CommandButtonsWindow +{ + private readonly CommandButtonSet _set; + private readonly Action _press; // queued for the tick + private bool _edit; + private ButtonScope _scope = ButtonScope.Character; + private int _focusRow = -1; // a row just added: focus its label box + + // A button that asks first: which, and the line it will send. + private ButtonScope _confirmScope; + private int _confirmIndex = -1; + private string _confirmLine = string.Empty; + private bool _openConfirm; + + // Copy from another character (read when the edit view opens and when the list is opened). + private List _others = new(); + private int _copyPick; + + // The header's note: the last press, or a problem (set from the tick). + private volatile string _note = string.Empty; + private long _noteAtMs; + private const long NoteMs = 5000; + + private float _k = 1f; + private float Px(float v) => v * _k; + private const string ConfirmId = "##cb_confirm"; + + private const string HelpText = + "Buttons that each send one chat line, as if you typed it in the chat box: a command (/ra start, " + + "/lua start threads, /rdef weapons, /loc), an emote (*wave*, *snow angel*), a server command (@home) " + + "or plain text (said aloud).\n\n" + + "The pencil opens the edit view: a label and a command for each button, its colour, and Ask (it asks " + + "before it sends: for commands that are hard to take back). Columns and the button size are there too.\n\n" + + "Three lists: This character, This server (every character on this server) and All characters; the " + + "grid shows all three. Copy from takes another character's buttons.\n\n" + + "/ra buttons opens this window; /ra buttons list | add