Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
3 changes: 2 additions & 1 deletion mods.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
]
}
2 changes: 2 additions & 0 deletions mods/waypoint-tools/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
global using static Program;
global using static Game;
41 changes: 41 additions & 0 deletions mods/waypoint-tools/README.md
Original file line number Diff line number Diff line change
@@ -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": <the Gateway's process id>, "actions": ["item_give"]}`. A file whose
`pid` is not a running Gateway was left by one that stopped.
- `data/waypoint-tools/requests/<id>.json`: a request, one JSON object. Write it as `<id>.tmp` and rename it, so the mod
never reads half of it. `<id>` is the caller's (a GUID).
`{"action": "item_give", "character": "<name>", "item": <the 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/<id>.json`: the answer, written before the request is removed.
`{"protocol": 1, "id": "<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 `<name> 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).
225 changes: 225 additions & 0 deletions mods/waypoint-tools/WaypointToolsMod.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The way Waypoint's tools reach the game without the client control bridge (README.md). Waypoint writes a request into
/// <c>data/waypoint-tools/requests/</c>; 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
/// <c>data/waypoint-tools/replies/</c>. Nothing listens on the network.
/// </summary>
public sealed class WaypointToolsMod : IMod, IDisposable
{
/// <summary>The version of the request and reply files; Waypoint reads it from <c>loaded.json</c>.</summary>
const int Protocol = 1;

/// <summary>How long a request waits for its character to be in game before it is answered "not in game".</summary>
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<string, Request> _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<string> _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<string, long> _ticked = new(StringComparer.OrdinalIgnoreCase);

/// <summary>How recently a character's connection must have ticked to count as in game (ticks are about 4 a second).</summary>
const long InGameMilliseconds = 2000;

/// <summary>The characters whose connections ticked within <see cref="InGameMilliseconds"/>.</summary>
List<string> InGame()
{
long now = Environment.TickCount64;
return [.. _ticked.Where(t => now - t.Value <= InGameMilliseconds).Select(t => t.Key)];
}
IModContext _mod = null!;
Timer? _scan;
bool _disposed;

/// <inheritdoc/>
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));
}

/// <inheritdoc/>
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) { }
}

/// <summary>Reads the new requests, refuses those it cannot read, and answers those that waited too long.</summary>
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}");
}
}
}

/// <summary>The request in a file, or null when it is refused (and answered) or not readable yet.</summary>
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;
}
}

/// <summary>On a connection's own tick: carries out the requests for its character.</summary>
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}");
}
}

/// <summary>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.</summary>
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<InventoryItem>();
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}");
}

/// <summary>One JSON object, or every element of a JSON array in order.</summary>
static List<string> Specs(string json)
{
using var document = JsonDocument.Parse(json);
return document.RootElement.ValueKind == JsonValueKind.Array
? [.. document.RootElement.EnumerateArray().Select(element => element.GetRawText())]
: [json];
}

/// <summary>Writes the reply, then removes the request: a request without a reply is still waiting.</summary>
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}");
}

/// <summary>A reader never sees half a file: it is written beside, then moved into place.</summary>
static void WriteAtomically(string path, JsonNode json)
{
string temporary = path + ".tmp";
File.WriteAllText(temporary, json.ToJsonString());
File.Move(temporary, path, overwrite: true);
}
}
Binary file added mods/waypoint-tools/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions mods/waypoint-tools/mod.json
Original file line number Diff line number Diff line change
@@ -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"]
}
9 changes: 9 additions & 0 deletions mods/waypoint-tools/waypoint-tools.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<!-- Waypoint Tools: the request folder Waypoint's tools write to (README.md). Everything else is in Directory.Build.props. -->

<ItemGroup>
<None Update="icon.png" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
Loading