Skip to content
Draft
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
45 changes: 45 additions & 0 deletions src/AzimuthRPC.Core/State/RaceLoadingGracePeriod.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
namespace AzimuthRPC;

/// <summary>
/// Avoid reporting "Loading Race" during a brief loss of the telemetry-active bit
/// while an event context is still confirmed. A real loading UI always wins.
/// This is a bounded display-only grace period, not a new game-state detector.
/// </summary>
internal sealed class RaceLoadingGracePeriod
{
private static readonly TimeSpan MaxTelemetryGap = TimeSpan.FromSeconds(2);
private DateTime? _lastConfirmedRaceUtc;

internal GameSnapshot Apply(GameSnapshot snapshot, DateTime nowUtc)
{
// Do not carry a previous race into a different activity, game process,
// missing hook, or an explicitly detected loading screen.
if (!snapshot.Attached || !snapshot.Hooks.Installed ||
snapshot.Hooks.EventContext != 1 || snapshot.UiMode == UiMode.Loading)
{
Reset();
return snapshot;
}

if (snapshot.Activity == GameActivity.Event && snapshot.Hooks.Active)
{
_lastConfirmedRaceUtc = nowUtc;
return snapshot;
}

// UiMode.Unknown is not proof of a loading screen. A single inactive
// hook sample should not replace a recently observed racing presence.
if (snapshot.UiMode == UiMode.Unknown &&
snapshot.Activity == GameActivity.RaceLoading &&
!snapshot.Hooks.Active &&
_lastConfirmedRaceUtc is DateTime last &&
nowUtc >= last && nowUtc - last <= MaxTelemetryGap)
{
return snapshot with { Activity = GameActivity.Event };
}

return snapshot;
}

internal void Reset() => _lastConfirmedRaceUtc = null;
}
9 changes: 5 additions & 4 deletions src/AzimuthRPC.Debug/DebugRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ internal sealed class DebugRuntime : IAsyncDisposable
private static readonly TimeSpan PresenceMinInterval = TimeSpan.FromSeconds(4);
private AppConfig _options;
private readonly CancellationTokenSource _stop = new();
private readonly RaceLoadingGracePeriod _raceLoadingGrace = new();
private Task? _loop;
private Process? _process;
private ExternalProcessMemoryReader? _memory;
Expand Down Expand Up @@ -46,15 +47,15 @@ private async Task RunAsync()
{
try { await TickAsync(_stop.Token); }
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { break; }
catch (Exception e) { _memorySnapshot = GameSnapshot.Unavailable(e.Message); Log?.Invoke(e.Message); Publish(_memorySnapshot); }
catch (Exception e) { _raceLoadingGrace.Reset(); _memorySnapshot = GameSnapshot.Unavailable(e.Message); Log?.Invoke(e.Message); Publish(_memorySnapshot); }
} while (await timer.WaitForNextTickAsync(_stop.Token));
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { }
}
private async Task TickAsync(CancellationToken token)
{
var options = Volatile.Read(ref _options); var now = DateTime.UtcNow;
if (options.Offline) { Publish(GameSnapshot.Unavailable("Offline debug mode; memory, hooks and Discord disabled")); return; }
if (options.Offline) { _raceLoadingGrace.Reset(); Publish(GameSnapshot.Unavailable("Offline debug mode; memory, hooks and Discord disabled")); return; }
if (_process is not null && Exited(_process)) await DetachAsync();
if (_process is null && now >= _nextAttach)
{
Expand Down Expand Up @@ -85,7 +86,7 @@ private async Task TickAsync(CancellationToken token)
else { candidate.Dispose(); Log?.Invoke(installed.Status); }
}
var telemetry = _hooks?.Read() ?? Fh2TelemetrySample.Unavailable("Telemetry hooks unavailable");
var snapshot = GameStateInterpreter.Apply(_memorySnapshot, telemetry, _hooks?.Installed == true);
var snapshot = _raceLoadingGrace.Apply(GameStateInterpreter.Apply(_memorySnapshot, telemetry, _hooks?.Installed == true), now);
var presence = DiscordPresenceBuilder.Build(snapshot, options, _started == default ? now : _started);
if (_discord is not null && (!_discord.IsConnected || _discordApplicationId != options.ApplicationId)) await DisconnectAsync();
if (_process is not null && !string.IsNullOrWhiteSpace(options.ApplicationId) && _discord is null && now >= _nextDiscord)
Expand Down Expand Up @@ -115,7 +116,7 @@ private void Publish(GameSnapshot snapshot, DiscordPresence? presence = null)
var next = new DebugStatus(snapshot, _process is null ? "Waiting for Azimuth" : $"azimuth · PID {_process.Id}", snapshot.Attached ? $"0x{snapshot.GameBase:X} ({(_pe.PreferredImageBase == snapshot.GameBase ? "preferred" : "relocated")})" : snapshot.Error ?? "Not attached", _discordStatus, presence ?? DiscordPresenceBuilder.Build(snapshot, Volatile.Read(ref _options), _started), _process?.Id, _started);
Volatile.Write(ref _status, next); Changed?.Invoke(next);
}
private void ResetHooks() { _hooks?.Dispose(); _hooks = null; _nextHook = DateTime.MinValue; }
private void ResetHooks() { _raceLoadingGrace.Reset(); _hooks?.Dispose(); _hooks = null; _nextHook = DateTime.MinValue; }
private void ResetMapping() { ResetHooks(); _base = 0; _reader = _memory is null ? null : new(_memory, Fh2MainlandLocationResolver.Instance); _memorySnapshot = GameSnapshot.Unavailable("Mapping invalidated"); }
private async Task DetachAsync()
{
Expand Down
31 changes: 31 additions & 0 deletions tests/AzimuthRPC.Core.Tests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,37 @@ var s when s.StartsWith("worldmap_") => UiMode.WorldMap,
Check(game.Activity == expected); Check(game.Hooks.NormalizedRev == .13f); Check(game.WorldPresence == WorldPresence.InWorld);
}
});
Test("Brief inactive telemetry does not flicker into Loading Race", () =>
{
var grace = new RaceLoadingGracePeriod();
var time = DateTime.UnixEpoch;
GameSnapshot Observed(int eventContext, bool active, UiMode ui = UiMode.Unknown) =>
GameStateInterpreter.Apply(
new GameSnapshot { Attached = true, UiMode = ui },
new Fh2TelemetrySample(true, active, null, null, false, false, eventContext, true, "Synthetic"),
true);

Check(grace.Apply(Observed(1, true), time).Activity == GameActivity.Event);
var brieflyInactive = grace.Apply(Observed(1, false), time.AddMilliseconds(700));
Check(brieflyInactive.Activity == GameActivity.Event, "Brief telemetry gap should retain racing");
Check(DiscordPresenceBuilder.Build(brieflyInactive, new PresenceOptions(), time).Details == "Racing");
Check(grace.Apply(Observed(1, false), time.AddSeconds(3)).Activity == GameActivity.RaceLoading,
"Grace period must expire; do not invent permanent racing");
Check(grace.Apply(Observed(1, true), time.AddSeconds(4)).Activity == GameActivity.Event);
Check(grace.Apply(Observed(1, false, UiMode.Loading), time.AddSeconds(4.1)).Activity == GameActivity.RaceLoading,
"An explicit loading UI must never be masked");
Check(grace.Apply(Observed(1, false), time.AddSeconds(4.2)).Activity == GameActivity.RaceLoading,
"Confirmed loading must reset the grace timer");

Check(grace.Apply(Observed(1, true), time.AddSeconds(5)).Activity == GameActivity.Event);
Check(grace.Apply(Observed(2, false), time.AddSeconds(5.1)).Activity == GameActivity.FreeRoam);
Check(grace.Apply(Observed(1, false), time.AddSeconds(5.2)).Activity == GameActivity.RaceLoading,
"Free Roam must cancel previous race activity");
Check(grace.Apply(Observed(1, true), time.AddSeconds(6)).Activity == GameActivity.Event);
Check(!grace.Apply(GameSnapshot.Unavailable("Game closed"), time.AddSeconds(6.1)).Attached);
Check(grace.Apply(Observed(1, false), time.AddSeconds(6.2)).Activity == GameActivity.RaceLoading,
"Detach must not leak previous game's race");
});
Test("Unavailable memory clears live telemetry and activity", () =>
{
var game = GameStateInterpreter.Apply(GameSnapshot.Unavailable("Read failed"), new(true, true, .5f, .2f, true, true, 1, true, "Old"), true);
Expand Down
Loading