using System; using System.Collections.Generic; using System.IO; using RynthCore.Plugin.RynthAi.LegacyUi; namespace RynthCore.Plugin.RynthAi.Meta; /// /// An Embedded Nav Route carries its route inside the meta (2026-11-30: the route is embedded, /// so the meta still works with the .nav file deleted from the drive). /// /// It didn't: the Meta panel's route picker stores the name of a NavProfiles file, and the meta was /// saved with only the routes it already held in memory (those that came in a .met or a NAVDATA /// block), so a route picked from NavProfiles stayed a file the meta read at run time. Now: /// - picking a route (a new rule, or a rule whose route changed) copies that file in, replacing an /// older copy of the same name (); /// - every meta save copies in any route a rule names that the meta doesn't carry yet /// (), so an older meta becomes self-contained on its next save or load. /// Once a route is in the meta, the meta's copy is the one that runs; the file can go. /// "[None]", "Patrol" and "Camp" with no file behind them are not routes (MetaManager), and a file /// with no points is not copied (the parser drops an empty route and clears the rules naming it). /// internal static class MetaNavEmbedding { /// The route names the Embedded Nav Route actions of (and their DoAll steps) use. public static HashSet RouteNames(IEnumerable rules) { var names = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (MetaRule r in rules) Collect(r, names); return names; } /// The route names one rule's Embedded Nav Route actions use. public static HashSet RouteNames(MetaRule? rule) { var names = new HashSet(StringComparer.OrdinalIgnoreCase); if (rule != null) Collect(rule, names); return names; } /// /// Copies into every route name that it has no /// route for yet, from . Returns the names copied (empty: nothing to do). /// public static List EmbedMissing(IEnumerable rules, IDictionary> embedded, string navFolder, Action? log = null) { var done = new List(); foreach (string name in RouteNames(rules)) { if (FindKey(embedded, name) != null) continue; if (TryRead(navFolder, name, out List lines)) { embedded[name] = lines; done.Add(name); log?.Invoke($"[RynthAi] Meta: embedded route '{name}' from {Path.Combine(navFolder, name + ".nav")} ({PointCount(lines)} pts)"); } } return done; } /// /// A rule edit picked a route: each route names that /// didn't (a new rule: all of them) is copied in from its NavProfiles file, replacing the meta's older /// copy of that name. A route with no file keeps the meta's copy. Returns the names copied. /// public static List EmbedPicked(MetaRule after, MetaRule? before, IDictionary> embedded, string navFolder, Action? log = null, ISet? fromMemory = null) { var done = new List(); HashSet had = RouteNames(before); foreach (string name in RouteNames(after)) { if (had.Contains(name)) continue; if (fromMemory != null && fromMemory.Contains(name)) continue; // "Embed loaded" just copied it if (!TryRead(navFolder, name, out List lines)) continue; string? old = FindKey(embedded, name); if (old != null) embedded.Remove(old); embedded[name] = lines; done.Add(name); log?.Invoke($"[RynthAi] Meta: embedded route '{name}' from {Path.Combine(navFolder, name + ".nav")} ({PointCount(lines)} pts){(old != null ? ", replacing the meta's older copy" : "")}"); } return done; } // ── "Embed loaded" (the Meta panel's button, VTank's way) ─────────────────────────────────── // 2026-11-30: with a nav route loaded, a click on the Meta panel's button embeds that route. The snapshot tells the panel the loaded route's name (or why it // can't be embedded: DescribeLoaded); the button sets the action to that name with LoadedMarker // after it; the rule's save carries the marker here once (TakeLoadedMarkers), the route in memory // is copied in under that name (EmbedLoaded), and the rule keeps the plain name. /// After an Embedded Nav Route's name in a rule the panel sends: "copy the loaded route in under this name". public const string LoadedMarker = ";loaded"; /// /// The loaded route as "Embed loaded" would take it: its name (the meta's own name for a route from /// the meta, the file's name relative to for a .nav, a new "Route N" /// for one made in the nav editor or recorded), its point count, and a note that is empty when it /// can be embedded, else why not (no route; a route a feature built, ). /// public static (string Name, int Points, string Note) DescribeLoaded(NavRouteParser? route, string? navPath, string navFolder, IDictionary> embedded) { int points = route?.Points.Count ?? 0; bool follow = route != null && route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0; if (route == null || (points == 0 && !follow)) return (string.Empty, 0, "No nav route is loaded. Load or record one, then embed it."); if (route.MadeBy.Length > 0) return (string.Empty, points, $"The loaded route was made by {route.MadeBy}, not loaded or recorded, so it isn't embedded. Load or record a route."); string path = navPath ?? string.Empty; if (path.StartsWith("", StringComparison.Ordinal)) { string key = EmbedNavName.Clean(path.Substring(10, path.Length - 11)); if (key.Length > 0 && !EmbedNavName.IsNone(key)) return (key, points, string.Empty); return (UniqueName(navFolder, embedded), points, string.Empty); } if (path.StartsWith("<", StringComparison.Ordinal)) return (string.Empty, points, $"The loaded route isn't a nav route ({path}), so it isn't embedded."); if (path.Length > 0) { string name = FileRouteName(path, navFolder); if (name.Length > 0 && !EmbedNavName.IsNone(name)) return (name, points, string.Empty); } return (UniqueName(navFolder, embedded), points, string.Empty); } /// /// Strips from 's Embedded Nav Route actions (and its /// DoAll steps) and returns the names that carried it. /// public static List TakeLoadedMarkers(MetaRule rule) { var names = new List(); Take(rule, names); return names; static void Take(MetaRule r, List into) { if (r.Action == MetaActionType.EmbeddedNavRoute && r.ActionData != null && r.ActionData.EndsWith(LoadedMarker, StringComparison.OrdinalIgnoreCase)) { string name = EmbedNavName.Clean(r.ActionData.Substring(0, r.ActionData.Length - LoadedMarker.Length)); r.ActionData = name; if (name.Length > 0) into.Add(name); } if (r.ActionChildren != null) foreach (MetaRule c in r.ActionChildren) Take(c, into); } } /// /// Copies the loaded into as , /// replacing the meta's copy of that name. Null when it was copied, else why not (DescribeLoaded's note). /// public static string? EmbedLoaded(string name, NavRouteParser? route, string? navPath, string navFolder, IDictionary> embedded, Action? log = null) { var (_, points, note) = DescribeLoaded(route, navPath, navFolder, embedded); if (note.Length > 0) return note; if (string.IsNullOrWhiteSpace(name) || EmbedNavName.IsNone(name)) return "the route has no name to keep it under"; List lines = route!.ToLines(); if (lines.Count < 3) return "the loaded route didn't write out"; string? old = FindKey(embedded, name); if (old != null) embedded.Remove(old); embedded[name] = lines; log?.Invoke($"[RynthAi] Meta: embedded the loaded route as '{name}' ({points} pts{(string.IsNullOrEmpty(navPath) ? ", never saved to a file" : ", from " + navPath)}){(old != null ? ", replacing the meta's older copy" : "")}"); return null; } /// A .nav file's route name: relative to NavProfiles without ".nav" (as the nav list shows it), else the file name. internal static string FileRouteName(string path, string navFolder) { try { string full = Path.GetFullPath(path); string root = Path.GetFullPath(navFolder).TrimEnd('\\', '/') + Path.DirectorySeparatorChar; string rel = full.StartsWith(root, StringComparison.OrdinalIgnoreCase) ? full.Substring(root.Length) : Path.GetFileName(full); if (rel.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) rel = rel.Substring(0, rel.Length - 4); return EmbedNavName.Clean(rel); } catch { return string.Empty; } } /// "Route N", the first N with no route of that name in the meta or NavProfiles. internal static string UniqueName(string navFolder, IDictionary> embedded) { for (int n = 1; ; n++) { string name = "Route " + n.ToString(System.Globalization.CultureInfo.InvariantCulture); if (FindKey(embedded, name) != null) continue; try { if (!string.IsNullOrEmpty(navFolder) && File.Exists(Path.Combine(navFolder, name + ".nav"))) continue; } catch { } return name; } } /// The key files under (any case, stray brackets), or null. public static string? FindKey(IDictionary> embedded, string name) { if (embedded.ContainsKey(name)) { foreach (string k in embedded.Keys) if (string.Equals(k, name, StringComparison.OrdinalIgnoreCase)) return k; } foreach (string k in embedded.Keys) if (string.Equals(EmbedNavName.Clean(k), name, StringComparison.OrdinalIgnoreCase)) return k; return null; } /// /// NavProfiles\<name>.nav as the meta keeps it (canonical uTank2 lines), when the file is a route /// with points (or a Follow nav). A name that leaves the folder, "[None]" and an unreadable file give false. /// public static bool TryRead(string navFolder, string name, out List lines) { lines = new List(); if (string.IsNullOrWhiteSpace(navFolder) || string.IsNullOrWhiteSpace(name) || EmbedNavName.IsNone(name)) return false; string path; try { string root = Path.GetFullPath(navFolder).TrimEnd('\\', '/'); path = Path.GetFullPath(Path.Combine(root, name + ".nav")); if (!path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return false; } catch { return false; } if (!File.Exists(path)) return false; NavRouteParser route = NavRouteParser.Load(path); if (route.LoadWarning?.Length > 0) return false; bool follow = route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0; if (route.Points.Count == 0 && !follow) return false; lines = route.ToLines(); return lines.Count >= 3; } private static int PointCount(List lines) => NavRouteParser.LoadFromLines(lines).Points.Count; private static void Collect(MetaRule rule, HashSet names) { if (rule.Action == MetaActionType.EmbeddedNavRoute && !string.IsNullOrWhiteSpace(rule.ActionData)) { string name = EmbedNavName.Clean(rule.ActionData.Split(';')[0]); if (name.Length > 0) names.Add(name); } if (rule.ActionChildren != null) foreach (MetaRule c in rule.ActionChildren) Collect(c, names); if (rule.Children != null) // as AfFileWriter collects them foreach (MetaRule c in rule.Children) Collect(c, names); } }