feat(pathfinding): first-boot prompt to pre-bake the .swb map cache (#2475)

## What

On **first boot** (right after map selection), offer to pre-bake the pathfinding `.swb` cache for the selected maps. This removes first-pathfind-after-boot latency and is now cheap — ~18 MB/facet after the v8 format work (the old ~565 MB is gone). The answer persists in `modernuo.json` as **`pathfinding.prebakeMaps`** (default **false**): asked exactly once, and skipped on headless/CI boots (redirected input) where operators can set the flag directly.

## How — a generic startup phase, not pathfinding hardcoded in the engine

The clean-console (pre-Serilog) prompt window is inside the engine startup, but UOContent isn't loaded until after `ServerConfiguration.Load`. So rather than coupling the engine to pathfinding, this adds a generic lifecycle phase:

- **`Main.cs`**: new `AssemblyHandler.Invoke("ConfigurePrompts")` — runs **after** `LoadAssemblies` (so content can participate) but **before** the first `logger.Information` (so console prompts aren't interleaved with the async console sink). The first log line moves below it. Any class can hook in with `public static void ConfigurePrompts()` and self-gate on first-boot state. No `ServerConfiguration` or pathfinding coupling added to the engine.
- **`PathCacheCommands.ConfigurePrompts()`**: the first-boot prompt (interactive-only, flag-absent-only); persists the answer.
- **`PathCacheCommands.Initialize()`** (`Invoke("Initialize")` phase, after the tile matrix loads — which the bake walks): when the flag is set, bakes any map whose `.swb` is **missing or stale** (tile-data fingerprint mismatch, via `StepCache.ComputeLiveFingerprint` / `TryReadFingerprintFromFile`). A fresh cache is a no-op, so only the first boot — or a post-client-update boot — pays the several-minute cost.

## Docs

Fixed the now-stale "~565 MB / ~1.5–2 GB / do not bake by default" section in `dev-docs/pathfinding.md` (it's 17.9 MB for Trammel, tens of MB for all six facets after v8), added a "First-boot pre-bake prompt" section, and added the `pathfinding.prebakeMaps` lever row.

## Verified

- `dotnet build UOContent -c Release` → 0 errors (rebased on #2474).
- Pathfinding/StepCache tests: **90/90 pass**.
- Bootstrap streamlining of the startup phases is intentionally left as a follow-up.
This commit is contained in:
Kamron Batman 2026-06-07 16:30:33 -07:00 committed by GitHub
parent 30fec7da26
commit 2e93201e51
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 243 additions and 9 deletions

View file

@ -413,8 +413,6 @@ public static class Core
ServerConfiguration.Load();
logger.Information("Running on {Framework}", RuntimeInformation.FrameworkDescription);
var assemblyPath = Path.Join(BaseDirectory, AssembliesConfiguration);
// Load UOContent.dll
@ -431,6 +429,14 @@ public static class Core
AssemblyHandler.LoadAssemblies(assemblyFiles);
// First-boot interactive setup. Runs after assemblies are loaded (so content can
// register prompts) but before any Serilog output, so console prompts are not
// interleaved with the async console sink. Handlers self-gate on first-boot state
// (e.g. "is my setting already present?").
AssemblyHandler.Invoke("ConfigurePrompts");
logger.Information("Running on {Framework}", RuntimeInformation.FrameworkDescription);
VerifySerialization();
_now = DateTime.UtcNow;

View file

@ -1,6 +1,8 @@
using System;
using System.Diagnostics;
using System.IO;
using Server.Engines.Pathing.Cache;
using Server.Logging;
namespace Server.Engines.Pathing;
@ -19,6 +21,12 @@ namespace Server.Engines.Pathing;
/// </summary>
public static class PathCacheCommands
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(PathCacheCommands));
// modernuo.json flag: when true, Initialize() bakes any missing/stale .swb at startup.
// The first-boot ConfigurePrompts() prompt writes it.
private const string PrebakeSetting = "pathfinding.prebakeMaps";
private static string PathFor(int mapId) =>
Path.Combine(Core.BaseDirectory, "Data", "Pathfinding", $"{mapId}.swb");
@ -43,6 +51,81 @@ public static class PathCacheCommands
AutoLoadAtStartup();
}
/// <summary>
/// First-boot prompt, auto-invoked by <c>AssemblyHandler.Invoke("ConfigurePrompts")</c> in
/// the startup sequence — after assemblies load (so content can prompt) but before Serilog
/// starts, so the console prompt isn't interleaved with async log output. Offers to pre-bake
/// the pathfinding <c>.swb</c> cache for the selected maps; the answer persists in
/// modernuo.json (<see cref="PrebakeSetting"/>), so it's asked exactly once. Skipped when the
/// setting already exists or when input is redirected (headless/CI) — operators can set the
/// flag directly. The bake itself happens later in <see cref="Initialize"/>.
/// </summary>
public static void ConfigurePrompts()
{
if (ServerConfiguration.GetSetting(PrebakeSetting, (string)null) != null || Console.IsInputRedirected)
{
return;
}
Console.WriteLine();
Console.WriteLine("Pre-bake the pathfinding cache for your selected maps now?");
Console.WriteLine(" Bakes each map's .swb so there is zero first-pathfind-after-boot latency.");
Console.WriteLine(" Takes several minutes and ~tens of MB of disk per facet. You can also do");
Console.WriteLine(" this later at runtime with [PathBake.");
Console.Write("Pre-bake now? [y/N] ");
var answer = Console.ReadLine()?.Trim();
var prebake = answer?.StartsWith("y", StringComparison.OrdinalIgnoreCase) == true;
ServerConfiguration.SetSetting(PrebakeSetting, prebake);
}
/// <summary>
/// Auto-invoked by <c>AssemblyHandler.Invoke("Initialize")</c> after the tile matrix and
/// world are loaded. When <see cref="PrebakeSetting"/> is set, bakes any map whose
/// <c>.swb</c> is missing or stale (its tile-data fingerprint no longer matches), so the
/// first pathfind on each region is already warm. A fresh cache makes this a no-op, so only
/// first boot — or a client/map update that changes the fingerprint — pays the cost.
/// </summary>
public static void Initialize()
{
if (!ServerConfiguration.GetSetting(PrebakeSetting, false))
{
return;
}
var baked = 0;
for (var i = 0; i < Map.Maps.Length; i++)
{
var map = Map.Maps[i];
if (map == null || map == Map.Internal)
{
continue;
}
var path = PathFor(map.MapID);
var live = StepCache.ComputeLiveFingerprint(map.MapID);
if (StepCache.TryReadFingerprintFromFile(path, out var onDisk) && onDisk == live)
{
continue; // .swb already matches the current tile data
}
logger.Information(
"PathBake: pre-baking map {MapId} (pathfinding.prebakeMaps) — this can take several minutes...",
map.MapID
);
StepCache.Instance.BakeMap(map.MapID, path);
StepCache.Instance.ClearResidentChunks();
baked++;
}
if (baked > 0)
{
logger.Information("PathBake: pre-bake complete ({Count} map(s) written).", baked);
AutoLoadAtStartup(); // (re)open the freshly written files as lazy backing stores
}
}
/// <summary>
/// Open Data/Pathfinding/&lt;mapId&gt;.swb as a lazy backing store for every map.
/// Reads only the header + chunk-offset index up front (~16 bytes per chunk);