using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.Json; namespace RynthCore.Plugin.RynthNav; // The Atlas: RynthNav's location database (NavData\locations.json, made from the world // database by RynthCore's tools\navdata\gen_locations.py). Read-only; loaded once off the // tick thread and then shared. The idea of a typed, searchable atlas with an arrow is // GoArrow's (Digero 2006, Virindi 2011, MIT); the data is our own server's. // No host calls: the offline tests compile this file. internal sealed class AtlasLocation { public int Id; public string Name = "", Type = "", Desc = "", Cell = "", Place = "", Lb = ""; public uint Wcid; public bool OnMap; public double Ns, Ew; // A portal's destination. public bool HasDest, DestOnMap; public double DestNs, DestEw; public string DestName = "", DestPlace = "", DestCell = ""; public int MinLevel, MaxLevel; public bool Quest, Closed; } /// A spell that lands at a fixed spot (from locations.json "recalls"). internal sealed class AtlasRecall { public int SpellId; public string Name = "", In = ""; public bool OnMap; public double Ns, Ew; } internal sealed class Atlas { public static readonly Atlas Empty = new(new List(), new List(), "", ""); public IReadOnlyList Locations { get; } public IReadOnlyList Recalls { get; } public string Generated { get; } public string Path { get; } private readonly Dictionary _byId = new(); private Atlas(List locations, List recalls, string generated, string path) { Locations = locations; Recalls = recalls; Generated = generated; Path = path; foreach (var l in locations) _byId[l.Id] = l; } public static Atlas Load(string path) => Parse(File.ReadAllText(path), path); public static Atlas Parse(string json, string path = "") { var locs = new List(); var recalls = new List(); string generated = ""; using var doc = JsonDocument.Parse(json); JsonElement root = doc.RootElement; if (root.TryGetProperty("generated", out var g)) generated = g.GetString() ?? ""; if (root.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array) { foreach (JsonElement e in arr.EnumerateArray()) { var l = new AtlasLocation { Id = Int(e, "id"), Name = Str(e, "name"), Type = Str(e, "type"), Desc = Str(e, "desc"), Cell = Str(e, "cell"), Place = Str(e, "place"), Lb = Str(e, "lb"), Wcid = (uint)Int(e, "wcid"), MinLevel = Int(e, "minLevel"), MaxLevel = Int(e, "maxLevel"), Quest = Bool(e, "quest"), Closed = Bool(e, "closed"), }; l.OnMap = TryNum(e, "ns", out l.Ns) & TryNum(e, "ew", out l.Ew); if (e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object) { l.HasDest = true; l.DestOnMap = TryNum(d, "ns", out l.DestNs) & TryNum(d, "ew", out l.DestEw); l.DestName = Str(d, "name"); l.DestPlace = Str(d, "place"); l.DestCell = Str(d, "cell"); } locs.Add(l); } } if (root.TryGetProperty("recalls", out arr) && arr.ValueKind == JsonValueKind.Array) { foreach (JsonElement e in arr.EnumerateArray()) { var r = new AtlasRecall { SpellId = Int(e, "spell"), Name = Str(e, "name"), In = Str(e, "in") }; r.OnMap = TryNum(e, "ns", out r.Ns) & TryNum(e, "ew", out r.Ew); recalls.Add(r); } } return new Atlas(locs, recalls, generated, path); } public AtlasLocation? ById(int id) => _byId.TryGetValue(id, out var l) ? l : null; /// /// Landblocks that are dungeons: places (and portal destinations) the Atlas has in "dungeon" /// cells, less any landblock with places on the map. A dungeon's nav_XXXX.tile holds only that /// landblock's surface (a flat sheet; RynthNav.Baker leaves dungeon cells out), so it isn't /// a navmesh for walking inside the dungeon. /// public HashSet DungeonLandblocks() { var dungeon = new HashSet(); var map = new HashSet(); foreach (AtlasLocation l in Locations) { if (TryLandblock(l.Cell, out uint lb)) { if (l.OnMap) map.Add(lb); else if (l.Place.Equals("dungeon", StringComparison.Ordinal)) dungeon.Add(lb); } if (l.HasDest && !l.DestOnMap && l.DestPlace.Equals("dungeon", StringComparison.Ordinal) && TryLandblock(l.DestCell, out uint dlb)) dungeon.Add(dlb); } dungeon.ExceptWith(map); return dungeon; } private static bool TryLandblock(string cell, out uint lb) { lb = 0; return cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb); } // ── Search ─────────────────────────────────────────────────────────────── /// How well matches (lower case): 0 = not at all. public static int MatchScore(string name, string q) { if (q.Length == 0) return 1; if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100; int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase); if (at == 0) return 80; if (at > 0) { char before = name[at - 1]; return char.IsLetterOrDigit(before) ? 40 : 60; // starts a word / inside a word } // Every word of the query somewhere in the name ("mines despair"). string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (words.Length < 2) return 0; foreach (string w in words) if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0; return 30; } /// Type order when names match equally well: places before people. public static int TypeRank(string type) => type switch { "Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 4, "Portal" => 5, "Vendor" => 6, "NPC" => 7, _ => 8, }; /// /// The best atlas match for a name (/rnav arrow Holtburg): only places with a map /// position; best name match, then type (a town before its portal), then the /// nearest to the player when . /// public AtlasLocation? FindBest(string query, bool hasPos, double ns, double ew) { string q = query.Trim(); if (q.Length == 0) return null; AtlasLocation? best = null; int bestScore = 0, bestRank = int.MaxValue; double bestDist = double.MaxValue; foreach (var l in Locations) { if (!l.OnMap) continue; int s = MatchScore(l.Name, q); if (s == 0) continue; int rank = TypeRank(l.Type); double dist = hasPos ? NavCoords.Distance(ns, ew, l.Ns, l.Ew) : 0; bool better = s > bestScore || (s == bestScore && rank < bestRank) || (s == bestScore && rank == bestRank && dist < bestDist); if (!better) continue; best = l; bestScore = s; bestRank = rank; bestDist = dist; } return best; } /// /// Locations matching (empty = all) and, when /// isn't empty, of that type; best matches first. /// public List Search(string query, string? type, int max) { string q = query.Trim(); var hits = new List<(AtlasLocation L, int S)>(); foreach (var l in Locations) { if (!string.IsNullOrEmpty(type) && !l.Type.Equals(type, StringComparison.OrdinalIgnoreCase)) continue; int s = MatchScore(l.Name, q); if (s > 0) hits.Add((l, s)); } hits.Sort((a, b) => { int c = b.S.CompareTo(a.S); if (c != 0) return c; c = TypeRank(a.L.Type).CompareTo(TypeRank(b.L.Type)); return c != 0 ? c : string.Compare(a.L.Name, b.L.Name, StringComparison.OrdinalIgnoreCase); }); var result = new List(Math.Min(max, hits.Count)); for (int i = 0; i < hits.Count && result.Count < max; i++) result.Add(hits[i].L); return result; } /// The nearest on-map location of a type within , or null. public AtlasLocation? Nearest(string type, double ns, double ew, double maxUnits) { AtlasLocation? best = null; double bestD = maxUnits; foreach (var l in Locations) { if (!l.OnMap || !l.Type.Equals(type, StringComparison.Ordinal)) continue; double d = NavCoords.Distance(ns, ew, l.Ns, l.Ew); if (d <= bestD) { best = l; bestD = d; } } return best; } /// A portal by its weenie class, the one nearest the player when there are several. public AtlasLocation? PortalByWcid(uint wcid, double ns, double ew) { AtlasLocation? best = null; double bestD = double.MaxValue; foreach (var l in Locations) { if (l.Wcid != wcid || l.Type != "Portal") continue; double d = l.OnMap ? NavCoords.Distance(ns, ew, l.Ns, l.Ew) : double.MaxValue / 2; if (best == null || d < bestD) { best = l; bestD = d; } } return best; } // ── JSON helpers ───────────────────────────────────────────────────────── private static string Str(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; private static int Int(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0; private static bool Bool(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.True; private static bool TryNum(JsonElement e, string name, out double d) { d = 0; return e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d); } public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Locations.Count} locations, {Recalls.Count} recalls ({Generated})"); }