diff --git a/README.md b/README.md index 80212ff..fd2609b 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ works with. The maintainers publish the releases of the mods in this repository. | [fastcampaign](mods/fastcampaign/) | a faster campaign: 5× kill experience, +50% movement speed, `/fast` lists the commands that skip ahead | | [gm-commands](mods/gm-commands/) | the development and testing chat commands: teleport, items, monsters, experience, test hits, protocol probes | | [globalchat](mods/globalchat/) | talk to other LocalExile players through the LocalExile global chat server | +| [waypoint-tools](mods/waypoint-tools/) | lets Waypoint's tools reach the game without the client control bridge: the item crafter gives its items through it | | [itemquantity](mods/itemquantity/) | 10× as many item drops | | [itemrarity](mods/itemrarity/) | 10× the chance of magic, rare and unique equipment | diff --git a/mods.json b/mods.json index ff87ae8..633e3a0 100644 --- a/mods.json +++ b/mods.json @@ -6,6 +6,7 @@ { "id": "gm-commands", "name": "GM Commands", "description": "The development and testing chat commands: teleport, items, monsters, experience, quest flags, test hits and protocol probes.", "author": "LocalExile", "version": "1.1.1", "compatibleClientVersions": ["0.4.2-beta"], "kind": "feature", "type": "project", "path": "mods/gm-commands", "depends": ["Game"], "settings": false }, { "id": "itemquantity", "name": "Item Quantity", "description": "10 times as many item drops from every kill.", "author": "LocalExile", "version": "1.1.1", "compatibleClientVersions": ["0.4.2-beta"], "kind": "feature", "type": "project", "path": "mods/itemquantity", "depends": [], "settings": true }, { "id": "itemrarity", "name": "Item Rarity", "description": "10 times the chance of magic, rare and unique equipment.", "author": "LocalExile", "version": "1.1.1", "compatibleClientVersions": ["0.4.2-beta"], "kind": "feature", "type": "project", "path": "mods/itemrarity", "depends": [], "settings": true }, - { "id": "liveeconomy", "name": "Live Economy", "description": "Faustus's Currency Exchange as a live market: the official Path of Exile leagues' prices, a spread, depth, and orders that fill with time.", "author": "JetStream", "version": "1.1.1", "compatibleClientVersions": ["0.4.2-beta"], "kind": "feature", "type": "project", "path": "mods/liveeconomy", "depends": [], "settings": true } + { "id": "liveeconomy", "name": "Live Economy", "description": "Faustus's Currency Exchange as a live market: the official Path of Exile leagues' prices, a spread, depth, and orders that fill with time.", "author": "JetStream", "version": "1.1.1", "compatibleClientVersions": ["0.4.2-beta"], "kind": "feature", "type": "project", "path": "mods/liveeconomy", "depends": [], "settings": true }, + { "id": "waypoint-tools", "name": "Waypoint Tools", "description": "Lets Waypoint's tools reach the game without the client control bridge: the item crafter gives its items through it.", "author": "Waypoint", "version": "1.0.0", "compatibleClientVersions": ["0.4.2-beta"], "kind": "feature", "type": "project", "path": "mods/waypoint-tools", "depends": ["Game"], "settings": false } ] } diff --git a/mods/waypoint-tools/GlobalUsings.cs b/mods/waypoint-tools/GlobalUsings.cs new file mode 100644 index 0000000..7fd13db --- /dev/null +++ b/mods/waypoint-tools/GlobalUsings.cs @@ -0,0 +1,2 @@ +global using static Program; +global using static Game; diff --git a/mods/waypoint-tools/README.md b/mods/waypoint-tools/README.md new file mode 100644 index 0000000..f1f2dbb --- /dev/null +++ b/mods/waypoint-tools/README.md @@ -0,0 +1,41 @@ +# Waypoint Tools + +Lets [Waypoint](https://github.com/LocalExile/Waypoint)'s tools reach the game without the client control bridge, so they +work on a LocalExile release too. Waypoint's item crafter gives its items through it: no Frida, no Python, and no limit on +how long the item may be. + +It adds no chat command and changes nothing in the game by itself. It does only what Waypoint asks, for a character on +this server, and says so in that character's chat (`Waypoint: Added Dire Abyss Iron Ring`). + +## How Waypoint talks to it + +Through files in the LocalExile folder (the extracted release, or a checkout); nothing listens on the network. + +- `data/waypoint-tools/loaded.json`: written while the mod is loaded, removed when it unloads. + `{"protocol": 1, "version": "1.0.0", "pid": , "actions": ["item_give"]}`. A file whose + `pid` is not a running Gateway was left by one that stopped. +- `data/waypoint-tools/requests/.json`: a request, one JSON object. Write it as `.tmp` and rename it, so the mod + never reads half of it. `` is the caller's (a GUID). + `{"action": "item_give", "character": "", "item": }`. Without `character` (or with `""`) it goes to + the one character in game; with several in game it is answered `Several characters are in game (…): name one`. + `item` is an item in the format of LocalExile's + [item crafter hook](https://github.com/LocalExile/LocalExile/blob/main/Agents/docs/dev/item-crafter.md), which the + mod builds with the Gateway's own `ItemCrafter.Build`: one object, or an array whose items are given in order. +- `data/waypoint-tools/replies/.json`: the answer, written before the request is removed. + `{"protocol": 1, "id": "", "ok": true, "message": "Added Dire Abyss Iron Ring"}`. The caller reads and deletes it. + +A request is carried out on the next tick of that character's connection (about 4 a second while the character is in an +area and not paused), so it changes the inventory and sends to the client from the connection's own task, as a chat +command does. A character counts as in game while its connection ticked in the last 2 seconds. One that waits more than +30 seconds for its character is answered ` is not in game` (`No character is in game` when it names none); one that cannot be +read is answered with why. A request left when the mod unloads stays, and the next load reads it. + +## Settings + +None. + +## Works with + +LocalExile v0.4.2-beta. It needs no other mod: it uses the server and LocalExile's Game module directly, as a module +does, and lists `Game` (that module, not a mod) in `depends` so it reloads with it. So it needs v0.4.0-beta or later +(the first where mods reach what modules reach). diff --git a/mods/waypoint-tools/WaypointToolsMod.cs b/mods/waypoint-tools/WaypointToolsMod.cs new file mode 100644 index 0000000..357477b --- /dev/null +++ b/mods/waypoint-tools/WaypointToolsMod.cs @@ -0,0 +1,225 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.Json.Nodes; +using GameServer.Core; +using GameServer.Core.Protocol.Instance; +using GameServer.Core.World; +using GameServer.Modding; + +namespace LocalExile.Mods.WaypointTools; + +/// +/// The way Waypoint's tools reach the game without the client control bridge (README.md). Waypoint writes a request into +/// data/waypoint-tools/requests/; the mod carries it out on the next tick of that character's connection, so what it +/// changes and sends goes through the connection's own task, as a chat command would, and answers in +/// data/waypoint-tools/replies/. Nothing listens on the network. +/// +public sealed class WaypointToolsMod : IMod, IDisposable +{ + /// The version of the request and reply files; Waypoint reads it from loaded.json. + const int Protocol = 1; + + /// How long a request waits for its character to be in game before it is answered "not in game". + static readonly TimeSpan Wait = TimeSpan.FromSeconds(30); + + static readonly string Root = Path.Combine("data", "waypoint-tools"); + static readonly string Requests = Path.Combine(Root, "requests"); + static readonly string Replies = Path.Combine(Root, "replies"); + static readonly string Loaded = Path.Combine(Root, "loaded.json"); + + sealed record Request(string Id, string File, string Action, string Character, string Item, DateTime Written); + + // The requests read and not yet answered, by id. A tick claims one by removing it. + readonly ConcurrentDictionary _pending = new(StringComparer.OrdinalIgnoreCase); + // Every request this load took, answered or not: while a tick gives one, its file is still there until the answer, + // and reading it again would give the item twice. Under _scanning. + readonly HashSet _taken = new(StringComparer.OrdinalIgnoreCase); + readonly Lock _scanning = new(); + // When each character's connection last ticked (Environment.TickCount64): who is in game, for a request that names nobody. + readonly ConcurrentDictionary _ticked = new(StringComparer.OrdinalIgnoreCase); + + /// How recently a character's connection must have ticked to count as in game (ticks are about 4 a second). + const long InGameMilliseconds = 2000; + + /// The characters whose connections ticked within . + List InGame() + { + long now = Environment.TickCount64; + return [.. _ticked.Where(t => now - t.Value <= InGameMilliseconds).Select(t => t.Key)]; + } + IModContext _mod = null!; + Timer? _scan; + bool _disposed; + + /// + public void Load(IModContext mod) + { + _mod = mod; + Directory.CreateDirectory(Requests); + Directory.CreateDirectory(Replies); + WriteAtomically(Loaded, new JsonObject + { + ["protocol"] = Protocol, + ["version"] = mod.Manifest.Version, + ["pid"] = Environment.ProcessId, + ["actions"] = new JsonArray("item_give"), + }); + GameEvents.Tick.Add(mod.Manifest.Id, (conn, _) => Tick(conn)); + _scan = new Timer(_ => Scan(), null, TimeSpan.Zero, TimeSpan.FromMilliseconds(250)); + } + + /// + public void Dispose() + { + lock (_scanning) _disposed = true; + using (var stopped = new ManualResetEvent(false)) + if (_scan?.Dispose(stopped) == true) stopped.WaitOne(TimeSpan.FromSeconds(2)); + // What was not answered stays in requests/: the next load reads it again, with its own age. + try { File.Delete(Loaded); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + + /// Reads the new requests, refuses those it cannot read, and answers those that waited too long. + void Scan() + { + lock (_scanning) + { + if (_disposed) return; + try + { + foreach (string file in Directory.EnumerateFiles(Requests, "*.json")) + { + string id = Path.GetFileNameWithoutExtension(file); + if (_taken.Contains(id)) continue; + if (Read(id, file) is { } request && _taken.Add(id)) _pending[id] = request; + } + DateTime now = DateTime.UtcNow; + var inGame = InGame(); + foreach (var request in _pending.Values) + { + if (request.Character.Length == 0 && inGame.Count > 1 && _pending.TryRemove(request.Id, out _)) + Answer(request, false, $"Several characters are in game ({string.Join(", ", inGame)}): name one"); + else if (now - request.Written > Wait && _pending.TryRemove(request.Id, out _)) + Answer(request, false, request.Character.Length > 0 ? $"{request.Character} is not in game" : "No character is in game"); + } + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + _mod.Log($"reading {Requests} failed: {e.Message}"); + } + } + } + + /// The request in a file, or null when it is refused (and answered) or not readable yet. + Request? Read(string id, string file) + { + DateTime written; + string text; + try + { + written = File.GetLastWriteTimeUtc(file); + text = File.ReadAllText(file); + } + catch (IOException) { return null; } // still being written: the next scan reads it + var refused = new Request(id, file, "", "", "", written); + try + { + if (JsonNode.Parse(text) is not JsonObject json) { Answer(refused, false, "A request is one JSON object"); return null; } + string action = (string?)json["action"] ?? ""; + string character = (string?)json["character"] ?? ""; + if (action != "item_give") { Answer(refused, false, $"Unknown action \"{action}\""); return null; } + if (json["item"] is not { } item || item is not (JsonObject or JsonArray)) { Answer(refused, false, "Which item?"); return null; } + return new Request(id, file, action, character, item.ToJsonString(), written); + } + catch (JsonException e) + { + Answer(refused, false, $"Not JSON: {e.Message}"); + return null; + } + } + + /// On a connection's own tick: carries out the requests for its character. + async Task Tick(ClientState conn) + { + if (conn is not { PlayerSent: true, Character: { Length: > 0 } character }) return; + _ticked[character] = Environment.TickCount64; + if (_pending.IsEmpty) return; + foreach (var request in _pending.Values) + { + bool mine = request.Character.Length > 0 + ? string.Equals(request.Character, character, StringComparison.OrdinalIgnoreCase) + : InGame() is [var only] && string.Equals(only, character, StringComparison.OrdinalIgnoreCase); + if (!mine || !_pending.TryRemove(request.Id, out _)) continue; + var (ok, message) = await GiveItems(conn, request.Item); + Answer(request, ok, message); + await Send(conn.Wire.Remote, conn.Wire.Stream, conn.Wire.Ciphers, InstanceChat.ChatLine($"Waypoint: {message}"), + $"waypoint-tools: {message}"); + } + } + + /// Builds each item with the Gateway's own ItemCrafter.Build (the item format of LocalExile's + /// Agents/docs/dev/item-crafter.md) and puts it into the main inventory, one object or each item of a JSON array in + /// order, until one is refused or does not fit. Self-contained: no other mod is needed. + static async Task<(bool Ok, string Message)> GiveItems(ClientState conn, string json) + { + if (ItemsFor(conn).Error is { } error) return (false, error); + var items = ItemsOf(conn); + var added = new List(); + string? failure = null, singleName = null; + foreach (string spec in Specs(json)) + { + if (ItemCrafter.Build(ItemsFor(conn), RollsFor(conn), spec, conn.Pools.Level, Random.Shared, out string? why) is not { } created + || ItemsFor(conn).ByHash(created.TypeHash) is not { } type) + { failure = why ?? "Unknown item type"; break; } + if (items.FreeCell(PlayerInventories.MainInventory, type.Width, type.Height, ShapeOf) is not { } cell) + { failure = "No room in the inventory"; break; } + added.Add(items.Put(PlayerInventories.MainInventory, new InventoryItem(items.NewItemId(), cell.X, cell.Y, created))); + singleName = $"{(created.NameWords.Count > 0 ? RollsFor(conn).NameOf(created.NameWords) + " " : "")}{type.Name}"; + } + if (added.Count == 0) return (false, failure ?? "No room in the inventory"); + await Send(conn.Wire.Remote, conn.Wire.Stream, conn.Wire.Ciphers, + InstanceItems.InventoryChange(PlayerInventories.InventoryId(PlayerInventories.MainInventory), + items.NextRevision(PlayerInventories.MainInventory), [], added), + $"0x00bf inventory 1: waypoint-tools item_give × {added.Count}"); + return failure is null + ? (true, added.Count == 1 && singleName is not null ? $"Added {singleName}" : $"Added {added.Count} item(s)") + : (false, $"Added {added.Count} item(s), then stopped: {failure}"); + } + + /// One JSON object, or every element of a JSON array in order. + static List Specs(string json) + { + using var document = JsonDocument.Parse(json); + return document.RootElement.ValueKind == JsonValueKind.Array + ? [.. document.RootElement.EnumerateArray().Select(element => element.GetRawText())] + : [json]; + } + + /// Writes the reply, then removes the request: a request without a reply is still waiting. + void Answer(Request request, bool ok, string message) + { + try + { + WriteAtomically(Path.Combine(Replies, request.Id + ".json"), new JsonObject + { + ["protocol"] = Protocol, + ["id"] = request.Id, + ["ok"] = ok, + ["message"] = message, + }); + File.Delete(request.File); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + _mod.Log($"answering {request.Id} failed: {e.Message}"); + } + _mod.Log($"{request.Id} {(request.Character.Length > 0 ? request.Character + " " : "")}{(ok ? "done" : "refused")}: {message}"); + } + + /// A reader never sees half a file: it is written beside, then moved into place. + static void WriteAtomically(string path, JsonNode json) + { + string temporary = path + ".tmp"; + File.WriteAllText(temporary, json.ToJsonString()); + File.Move(temporary, path, overwrite: true); + } +} diff --git a/mods/waypoint-tools/icon.png b/mods/waypoint-tools/icon.png new file mode 100644 index 0000000..3a2175a Binary files /dev/null and b/mods/waypoint-tools/icon.png differ diff --git a/mods/waypoint-tools/mod.json b/mods/waypoint-tools/mod.json new file mode 100644 index 0000000..fb69067 --- /dev/null +++ b/mods/waypoint-tools/mod.json @@ -0,0 +1,10 @@ +{ + "id": "waypoint-tools", + "name": "Waypoint Tools", + "description": "Lets Waypoint's tools reach the game without the client control bridge: the item crafter gives its items through it.", + "author": "Waypoint", + "version": "1.0.0", + "compatibleClientVersions": ["0.4.2-beta"], + "kind": "feature", + "depends": ["Game"] +} diff --git a/mods/waypoint-tools/waypoint-tools.csproj b/mods/waypoint-tools/waypoint-tools.csproj new file mode 100644 index 0000000..627b4c7 --- /dev/null +++ b/mods/waypoint-tools/waypoint-tools.csproj @@ -0,0 +1,9 @@ + + + + + + + + +