diff --git a/docs/adaptive-game-compatibility.md b/docs/adaptive-game-compatibility.md index 00d43c04..e1226e37 100644 --- a/docs/adaptive-game-compatibility.md +++ b/docs/adaptive-game-compatibility.md @@ -28,9 +28,23 @@ Steam's secondary HUD table is linked to the already verified main HUD table thr Drift angle is calculated from Data Out. Custom targets and measured angle remain available when a Drift Zone scoring profile cannot be verified. The gauge then says `ANGLE ONLY` and withholds the bonus percentage and colored scoring guide. -Drift Zone bonus rules have a separate compatibility boundary. Successful adaptive HUD or Tune validation does not verify those rules. The scoring code and loaded curve values must be checked separately before a build receives a bonus profile; unchanged code alone cannot establish unchanged configuration. No new game-memory scans or reads have been added to the drift renderer. +Drift Zone bonus rules have a separate compatibility boundary. Successful adaptive HUD or Tune validation does not verify those rules. The loaded curve values must be checked before a build receives a bonus profile; unchanged code alone cannot establish unchanged configuration. The drift renderer itself reads no game memory: it asks `DriftZoneCurveCheck` for the profile on each frame and gets a stored answer. -Regression tests require the newest bundled Steam and Xbox builds to have drift guidance, in addition to checking the captured identities. This prevents a future bundled compatibility update from silently omitting drift again. Changed identities and unknown adaptive builds still receive no unverified bonus claims. Automatic discovery of future Drift Zone scoring profiles is not implemented. +Regression tests require the newest bundled Steam and Xbox builds to have drift guidance, in addition to checking the captured identities. This prevents a future bundled compatibility update from silently omitting drift again. Changed identities and unknown adaptive builds still receive no unverified bonus claims from the table. + +### Curve check for builds outside the table + +A build that is accepted but not in the scoring table gets the bonus guide only after Wisp has read the running game and found the curve. Until then the gauge says `ANGLE ONLY`. + +- `DriftZoneCurveCheck` starts the read the first time the gauge needs a profile in Drift Zone mode while the car is driving. One read runs at a time, on a thread at the lowest priority. +- `DriftZoneCurveScan` goes through the game's committed, private, writable memory with the read-only handle the HUD already holds. It looks for the float32 saturation angle and requires the minimum and maximum angles and both multipliers as float32 within 128 bytes, in one arrangement, at least eight times. It then waits one second and reads every entry again. Both checked builds hold 20 such entries. +- The read is paced: after each 4 MiB it waits three times as long as that chunk took. It stops after 90 seconds or 32 GiB and then reports no result. +- The result is kept per exact build identity in `drift-zone-checks.json` in Wisp's local data folder, so a build is read once per PC. A verified build is read again after 14 days. A build without the curve is tried again after 2 minutes, 10 minutes and then hourly. +- Builds in the table are read once as well. Their guidance does not depend on it; the result shows whether the check agrees with the table before the next game update needs it. +- Every result is reported once per run as a `drift` `check` observation: `success`, `unsupported` (curve not found), `unknown` (entries changed between the two reads), `timeout` or `failure`. +- The `drift-zone-check` feature control pauses the read. While it is paused, a build outside the table stays on `ANGLE ONLY`. + +Limits: the handle has only the limited query right, so the read cannot tell which pages are currently in memory and reads the others too. The check does not compare scoring code, and it cannot see a single zone whose curve differs while enough others still match. On October 6, bounded read-only checks of Steam 6.461.691.0 and Xbox 3.461.691.0 each found 20 stable typed scoring configurations. All observed instances matched the existing curve: 10-degree minimum, 110-degree maximum, float32 59.4-degree saturation, and multipliers 30 to 40. The checks completed in 4.77 and 4.56 seconds. Complete captured instruction ranges matched the retained scoring references on both platforms (19 Steam ranges and 21 Xbox ranges), with known scoring relationships checked separately. This qualifies the existing curve for these exact builds; it is not automatic admission of future profiles. diff --git a/src/Wisp.App/AppController.Drift.cs b/src/Wisp.App/AppController.Drift.cs index 1fecb201..914528ce 100644 --- a/src/Wisp.App/AppController.Drift.cs +++ b/src/Wisp.App/AppController.Drift.cs @@ -1,4 +1,6 @@ +using System.IO; using Wisp.App.Drift; +using Wisp.App.Supplementary; using Wisp.Core; namespace Wisp.App; @@ -11,12 +13,52 @@ public sealed partial class AppController public event EventHandler? DriftGaugeStatusChanged; public string DriftGaugeStatus { get; private set; } = "Off"; internal VehicleState? LatestDriftTelemetry => _receiver.Latest; - internal DriftZoneScoringProfile? CurrentDriftZoneProfile => DriftZoneProfileCatalog.ForBuild(_nativeHudProcessService.AttachedCompatibilityPack); + private DriftZoneCurveCheck? _driftZoneCheck; + + // Read by the drift renderer on every frame; DriftZoneCurveCheck.Resolve never waits. + internal DriftZoneScoringProfile? CurrentDriftZoneProfile + { + get + { + var pack = _nativeHudProcessService.AttachedCompatibilityPack; + var listed = DriftZoneProfileCatalog.ForBuild(pack); + return _driftZoneCheck is { } check + ? check.Resolve(pack is null ? null : DriftZoneGameKey.For(pack), listed, + _receiver.Latest is { IsRaceOn: true }, FeatureAllowed("drift-zone-check")) + : listed; + } + } + + private static DriftZoneCurveCheck CreateDriftZoneCheck() + { + var factory = new NativeHudProcessMemoryFactory(); + return new DriftZoneCurveCheck( + DriftZoneProfileCatalog.KnownCurve, + cancellation => + { + if (!factory.TryOpen(cancellation, out var opened, out _) || opened is null) + { + return null; + } + + if (opened is not NativeHudProcessMemory game) + { + opened.Dispose(); + return null; + } + + return new DriftZoneScanSession(DriftZoneGameKey.For(game.CompatibilityPack), new DriftZoneGameMemory(game), game); + }, + new DriftZoneCheckStore(Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Wisp", "drift-zone-checks.json")), + static (outcome, duration) => SupplementaryObservations.Record("feature", "drift", outcome, "check", duration)); + } private bool IsDriftGaugeWindowEnabled => HudFeatureAllowed("drift-hud") && Settings.DriftGaugeEnabled && DriftGaugeOverlay is { RendererFailed: false }; internal void InitializeDriftGaugeWindow() { if (_disposed || Settings.RequiresSetup || DriftGaugeOverlay is not null) return; + _driftZoneCheck ??= CreateDriftZoneCheck(); DriftGaugeOverlay = new DriftGaugeWindow(this); RestoreDriftGaugePlacement(); DriftGaugeOverlay.SetEditMode(!Settings.OverlayLocked); diff --git a/src/Wisp.App/AppController.cs b/src/Wisp.App/AppController.cs index cc97aa91..a35f84bf 100644 --- a/src/Wisp.App/AppController.cs +++ b/src/Wisp.App/AppController.cs @@ -2425,6 +2425,7 @@ public async ValueTask DisposeAsync() WindowZOrder.DetachFromGame(LapDeltaOverlay); WindowZOrder.DetachFromGame(LapMapOverlay); DriftGaugeOverlay?.Dispose(); + _driftZoneCheck?.Dispose(); LapDeltaOverlay?.Close(); LapMapOverlay?.Close(); _lapDelta.Dispose(); diff --git a/src/Wisp.App/Drift/DriftZoneCurveCheck.cs b/src/Wisp.App/Drift/DriftZoneCurveCheck.cs new file mode 100644 index 00000000..d74cf05d --- /dev/null +++ b/src/Wisp.App/Drift/DriftZoneCurveCheck.cs @@ -0,0 +1,327 @@ +using System.Collections.Immutable; +using System.IO; +using System.Text.Json; +using Wisp.Core; + +namespace Wisp.App.Drift; + +internal enum DriftZoneCheckOutcome +{ + Verified, + NotFound, + Unstable, + Incomplete, + Unavailable +} + +// The game memory for one check and the handle that keeps it open. +internal sealed record DriftZoneScanSession(string BuildKey, IDriftZoneScanMemory Memory, IDisposable Owner); + +internal sealed record DriftZoneCheckRecord(DriftZoneCheckOutcome Outcome, DateTimeOffset CheckedAt, int Entries); + +// Remembers the last result for each game build on this PC, so a build is read once and not on every start. +internal sealed class DriftZoneCheckStore +{ + private const int MaximumBuilds = 32; + private readonly string? _path; + private ImmutableDictionary _records; + + internal DriftZoneCheckStore(string? path) + { + _path = path; + _records = Load(path); + } + + internal DriftZoneCheckRecord? Find(string buildKey) => + Volatile.Read(ref _records).TryGetValue(buildKey, out var record) ? record : null; + + internal void Save(string buildKey, DriftZoneCheckRecord record) + { + var records = Volatile.Read(ref _records).SetItem(buildKey, record); + if (records.Count > MaximumBuilds) + { + records = records.OrderByDescending(static pair => pair.Value.CheckedAt).Take(MaximumBuilds) + .ToImmutableDictionary(StringComparer.Ordinal); + } + + Volatile.Write(ref _records, records); + if (_path is null) + { + return; + } + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(_path)!); + var temporary = _path + ".tmp"; + File.WriteAllText(temporary, JsonSerializer.Serialize(new Document(1, records.ToDictionary( + static pair => pair.Key, static pair => new Item(pair.Value.Outcome.ToString(), pair.Value.CheckedAt, pair.Value.Entries))))); + File.Move(temporary, _path, overwrite: true); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + // The result still holds for this run; the next start reads the build again. + } + } + + private static ImmutableDictionary Load(string? path) + { + var empty = ImmutableDictionary.Create(StringComparer.Ordinal); + if (path is null) + { + return empty; + } + + try + { + if (!File.Exists(path) || new FileInfo(path).Length > 64 * 1024) + { + return empty; + } + + var document = JsonSerializer.Deserialize(File.ReadAllText(path)); + if (document is not { Version: 1, Builds: { } builds }) + { + return empty; + } + + var records = empty.ToBuilder(); + foreach (var (key, item) in builds.Take(MaximumBuilds)) + { + if (key.Length is > 0 and <= 256 && item is not null && item.Entries is >= 0 and <= 100_000 && + Enum.TryParse(item.Outcome, out var outcome) && Enum.IsDefined(outcome)) + { + records[key] = new DriftZoneCheckRecord(outcome, item.CheckedAt, item.Entries); + } + } + + return records.ToImmutable(); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + return empty; + } + } + + private sealed record Document(int Version, Dictionary? Builds); + + private sealed record Item(string Outcome, DateTimeOffset CheckedAt, int Entries); +} + +// Decides whether Drift Zone guidance may use the known scoring curve on the attached game build. +// A build in the catalog has it at once. Any other accepted build gets it only after the running game +// was read and held the curve; until then the gauge shows the measured angle alone. The read runs once +// per build on a background thread, and its result is kept for later starts. +internal sealed class DriftZoneCurveCheck : IDisposable +{ + internal static readonly TimeSpan RevalidateAfter = TimeSpan.FromDays(14); + internal static readonly IReadOnlyList RetryDelays = + [TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(10), TimeSpan.FromHours(1)]; + + private readonly DriftZoneScoringProfile _curve; + private readonly Func _open; + private readonly DriftZoneCheckStore _store; + private readonly TimeProvider _time; + private readonly Action _report; + private readonly Func _scan; + private readonly Action _run; + private readonly CancellationTokenSource _cancellation = new(); + private readonly object _gate = new(); + private readonly Dictionary _attempts = new(StringComparer.Ordinal); + private readonly HashSet<(string BuildKey, string Outcome)> _reported = []; + private bool _running; + private bool _disposed; + + internal DriftZoneCurveCheck( + DriftZoneScoringProfile curve, + Func open, + DriftZoneCheckStore store, + Action report, + TimeProvider? time = null, + Func? scan = null, + Action? run = null) + { + _curve = curve ?? throw new ArgumentNullException(nameof(curve)); + _open = open ?? throw new ArgumentNullException(nameof(open)); + _store = store ?? throw new ArgumentNullException(nameof(store)); + _report = report ?? throw new ArgumentNullException(nameof(report)); + _time = time ?? TimeProvider.System; + _scan = scan ?? ((session, cancellation) => + DriftZoneCurveScan.Run(session.Memory, _curve, new DriftZoneCurveScanOptions(), cancellation)); + _run = run ?? StartBackground; + } + + // Called by the drift renderer on every frame in Drift Zone mode. It only looks at stored results and + // may start the background read; it never waits for it. + internal DriftZoneScoringProfile? Resolve(string? buildKey, DriftZoneScoringProfile? listed, bool driving, bool allowed) + { + if (buildKey is null) + { + return listed; + } + + var record = _store.Find(buildKey); + if (allowed && driving && IsDue(record)) + { + TryStart(buildKey); + } + + if (listed is not null) + { + return listed; + } + + return allowed && record is { Outcome: DriftZoneCheckOutcome.Verified } ? _curve : null; + } + + public void Dispose() + { + lock (_gate) + { + if (_disposed) + { + return; + } + + _disposed = true; + } + + _cancellation.Cancel(); + } + + private bool IsDue(DriftZoneCheckRecord? record) => record switch + { + null => true, + { Outcome: DriftZoneCheckOutcome.Verified } => _time.GetUtcNow() - record.CheckedAt >= RevalidateAfter, + _ => _time.GetUtcNow() - record.CheckedAt >= RetryDelays[0] + }; + + private void TryStart(string buildKey) + { + lock (_gate) + { + if (_disposed || _running || + (_attempts.TryGetValue(buildKey, out var attempt) && _time.GetUtcNow() < attempt.NextAllowed)) + { + return; + } + + _running = true; + } + + try + { + _run(() => Execute(buildKey)); + } + catch (Exception error) when (error is OutOfMemoryException or ThreadStartException or InvalidOperationException) + { + lock (_gate) + { + _running = false; + } + } + } + + private void Execute(string buildKey) + { + var outcome = DriftZoneCheckOutcome.Unavailable; + var entries = 0; + double? duration = null; + DriftZoneScanSession? session = null; + try + { + session = _open(_cancellation.Token); + if (session is not null && string.Equals(session.BuildKey, buildKey, StringComparison.Ordinal)) + { + var result = _scan(session, _cancellation.Token); + entries = result.Entries; + duration = result.Duration.TotalMilliseconds; + outcome = result.Verdict switch + { + DriftZoneCurveVerdict.Verified => DriftZoneCheckOutcome.Verified, + DriftZoneCurveVerdict.NotFound => DriftZoneCheckOutcome.NotFound, + DriftZoneCurveVerdict.Unstable => DriftZoneCheckOutcome.Unstable, + _ => DriftZoneCheckOutcome.Incomplete + }; + } + } + catch (OperationCanceledException) + { + outcome = DriftZoneCheckOutcome.Incomplete; + } + catch (Exception error) when (error is IOException or InvalidOperationException or UnauthorizedAccessException or + System.ComponentModel.Win32Exception or ArgumentException) + { + outcome = DriftZoneCheckOutcome.Unavailable; + } + finally + { + try + { + session?.Owner.Dispose(); + } + catch (Exception error) when (error is IOException or InvalidOperationException) + { + } + + Complete(buildKey, outcome, entries, duration); + } + } + + private void Complete(string buildKey, DriftZoneCheckOutcome outcome, int entries, double? duration) + { + var now = _time.GetUtcNow(); + var report = false; + lock (_gate) + { + _running = false; + if (_disposed) + { + return; + } + + if (outcome == DriftZoneCheckOutcome.Verified) + { + _attempts.Remove(buildKey); + } + else + { + var count = _attempts.TryGetValue(buildKey, out var attempt) ? attempt.Count : 0; + _attempts[buildKey] = (count + 1, now + RetryDelays[Math.Min(count, RetryDelays.Count - 1)]); + } + + report = _reported.Add((buildKey, Token(outcome))); + } + + // A read that did not finish says nothing about the build, so the stored result stays as it was. + if (outcome is DriftZoneCheckOutcome.Verified or DriftZoneCheckOutcome.NotFound or DriftZoneCheckOutcome.Unstable) + { + _store.Save(buildKey, new DriftZoneCheckRecord(outcome, now, entries)); + } + + if (report) + { + _report(Token(outcome), duration); + } + } + + internal static string Token(DriftZoneCheckOutcome outcome) => outcome switch + { + DriftZoneCheckOutcome.Verified => "success", + DriftZoneCheckOutcome.NotFound => "unsupported", + DriftZoneCheckOutcome.Unstable => "unknown", + DriftZoneCheckOutcome.Incomplete => "timeout", + _ => "failure" + }; + + private static void StartBackground(Action work) + { + var thread = new Thread(() => work()) + { + IsBackground = true, + Name = "Wisp drift zone curve check", + Priority = ThreadPriority.Lowest + }; + thread.Start(); + } +} diff --git a/src/Wisp.App/Drift/DriftZoneCurveScan.cs b/src/Wisp.App/Drift/DriftZoneCurveScan.cs new file mode 100644 index 00000000..9edffd01 --- /dev/null +++ b/src/Wisp.App/Drift/DriftZoneCurveScan.cs @@ -0,0 +1,249 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using Wisp.Core; + +namespace Wisp.App.Drift; + +internal readonly record struct DriftZoneScanRegion(ulong Base, ulong Size); + +// The game memory the curve check reads: its committed, private, writable regions. +internal interface IDriftZoneScanMemory +{ + IReadOnlyList Regions(); + + // Fills destination from address; bytes the layer cannot or will not read stay zero. + void ReadChunk(ulong address, Span destination); + + // An exact read of a short range; false when any byte could not be read. + bool Read(ulong address, Span destination); +} + +internal enum DriftZoneCurveVerdict +{ + Verified, + NotFound, + Unstable, + Incomplete +} + +internal sealed record DriftZoneCurveScanResult(DriftZoneCurveVerdict Verdict, int Entries, long BytesRead, TimeSpan Duration); + +internal sealed record DriftZoneCurveScanOptions +{ + internal int ChunkBytes { get; init; } = 4 * 1024 * 1024; + internal long MaximumBytes { get; init; } = 32L * 1024 * 1024 * 1024; + internal TimeSpan MaximumDuration { get; init; } = TimeSpan.FromSeconds(90); + internal TimeSpan SettleDelay { get; init; } = TimeSpan.FromSeconds(1); + + // The read yields between chunks for this multiple of the time each chunk took. + internal double PaceFactor { get; init; } = 3; + internal Action Wait { get; init; } = static delay => Thread.Sleep(delay); +} + +// Confirms that the running game holds the known Drift Zone scoring curve. The game keeps one scoring +// entry per drift zone, each with the minimum, maximum and saturation angles and the two multipliers +// close together. The check finds the saturation angle, requires the other four values beside it in one +// consistent arrangement, and reads every entry a second time. It never writes to the game. +internal static class DriftZoneCurveScan +{ + internal const int MinimumEntries = 8; + private const int Reach = 0x80; + private const int WindowBytes = Reach * 2 + 8; + private const int MaximumCandidates = 4096; + + private readonly record struct Entry(ulong Address, int Minimum, int Maximum, int Low, int High); + + internal static DriftZoneCurveScanResult Run( + IDriftZoneScanMemory memory, + DriftZoneScoringProfile curve, + DriftZoneCurveScanOptions options, + CancellationToken cancellation) + { + ArgumentNullException.ThrowIfNull(memory); + ArgumentNullException.ThrowIfNull(curve); + ArgumentNullException.ThrowIfNull(options); + var clock = Stopwatch.StartNew(); + var pattern = new byte[4]; + BinaryPrimitives.WriteSingleLittleEndian(pattern, (float)curve.SaturationAngleDegrees); + var companions = new[] + { + BitConverter.SingleToUInt32Bits((float)curve.MinimumAngleDegrees), + BitConverter.SingleToUInt32Bits((float)curve.MaximumAngleDegrees), + BitConverter.SingleToUInt32Bits((float)curve.MinimumAngleMultiplier), + BitConverter.SingleToUInt32Bits((float)curve.MaximumAngleMultiplier) + }; + var chunk = new byte[Math.Max(4096, options.ChunkBytes)]; + var window = new byte[WindowBytes]; + var candidates = new List(); + long bytes = 0; + var complete = true; + var work = new Stopwatch(); + + foreach (var region in memory.Regions()) + { + for (ulong offset = 0; offset < region.Size && complete; offset += (ulong)chunk.Length) + { + if (cancellation.IsCancellationRequested || bytes >= options.MaximumBytes || clock.Elapsed >= options.MaximumDuration) + { + complete = false; + break; + } + + work.Restart(); + var span = chunk.AsSpan(0, (int)Math.Min((ulong)chunk.Length, region.Size - offset)); + span.Clear(); + var address = region.Base + offset; + memory.ReadChunk(address, span); + bytes += span.Length; + Collect(memory, address, span, pattern, companions, window, candidates); + if (options.PaceFactor > 0) + { + options.Wait(TimeSpan.FromTicks((long)(work.Elapsed.Ticks * options.PaceFactor))); + } + } + + if (!complete) + { + break; + } + } + + if (!complete) + { + return new DriftZoneCurveScanResult(DriftZoneCurveVerdict.Incomplete, 0, bytes, clock.Elapsed); + } + + // Every entry of the real structure has the same arrangement; stray matches do not. + var entries = candidates + .GroupBy(static entry => (entry.Minimum, entry.Maximum, entry.Low, entry.High)) + .OrderByDescending(static group => group.Count()) + .Select(static group => group.ToList()) + .FirstOrDefault(); + if (entries is null || entries.Count < MinimumEntries) + { + return new DriftZoneCurveScanResult(DriftZoneCurveVerdict.NotFound, entries?.Count ?? 0, bytes, clock.Elapsed); + } + + options.Wait(options.SettleDelay); + foreach (var entry in entries) + { + if (cancellation.IsCancellationRequested) + { + return new DriftZoneCurveScanResult(DriftZoneCurveVerdict.Incomplete, 0, bytes, clock.Elapsed); + } + + if (!ReadWindow(memory, entry.Address, window) || + !pattern.AsSpan().SequenceEqual(window.AsSpan(Reach, 4)) || + Arrangement(entry.Address, window, companions) != entry) + { + return new DriftZoneCurveScanResult(DriftZoneCurveVerdict.Unstable, entries.Count, bytes, clock.Elapsed); + } + } + + return new DriftZoneCurveScanResult(DriftZoneCurveVerdict.Verified, entries.Count, bytes, clock.Elapsed); + } + + private static void Collect( + IDriftZoneScanMemory memory, + ulong address, + ReadOnlySpan data, + ReadOnlySpan pattern, + uint[] companions, + byte[] window, + List candidates) + { + var position = 0; + while (position + 4 <= data.Length && candidates.Count < MaximumCandidates) + { + var index = data[position..].IndexOf(pattern); + if (index < 0) + { + return; + } + + var at = position + index; + position = at + 1; + var hit = address + (ulong)at; + if ((hit & 3) != 0) + { + continue; + } + + if (at >= Reach && at + Reach + 8 <= data.Length) + { + data.Slice(at - Reach, WindowBytes).CopyTo(window); + } + else if (!ReadWindow(memory, hit, window)) + { + continue; + } + + if (Arrangement(hit, window, companions) is { } entry) + { + candidates.Add(entry); + } + } + } + + // The nearest float32 copy of each companion value within reach of the saturation angle. + private static Entry? Arrangement(ulong hit, ReadOnlySpan window, uint[] companions) + { + Span nearest = stackalloc int[4]; + for (var value = 0; value < companions.Length; value++) + { + var best = int.MinValue; + for (var offset = 0; offset + 4 <= window.Length; offset += 4) + { + if (offset == Reach || BinaryPrimitives.ReadUInt32LittleEndian(window[offset..]) != companions[value]) + { + continue; + } + + var delta = offset - Reach; + if (best == int.MinValue || Math.Abs(delta) < Math.Abs(best)) + { + best = delta; + } + } + + if (best == int.MinValue) + { + return null; + } + + nearest[value] = best; + } + + return new Entry(hit, nearest[0], nearest[1], nearest[2], nearest[3]); + } + + // Reads the bytes around a value page by page, so an entry at the edge of a memory block keeps its readable side. + private static bool ReadWindow(IDriftZoneScanMemory memory, ulong hit, Span window) + { + window.Clear(); + var start = hit - Reach; + if (memory.Read(start, window)) + { + return true; + } + + var any = false; + for (var offset = 0; offset < window.Length;) + { + var at = start + (ulong)offset; + var length = (int)Math.Min((ulong)(window.Length - offset), 0x1000 - (at & 0xFFF)); + if (memory.Read(at, window.Slice(offset, length))) + { + any = true; + } + else + { + window.Slice(offset, length).Clear(); + } + + offset += length; + } + + return any; + } +} diff --git a/src/Wisp.App/Drift/DriftZoneGameKey.cs b/src/Wisp.App/Drift/DriftZoneGameKey.cs new file mode 100644 index 00000000..f9623b30 --- /dev/null +++ b/src/Wisp.App/Drift/DriftZoneGameKey.cs @@ -0,0 +1,25 @@ +namespace Wisp.App.Drift; + +// Names one exact game build with the fields the scoring catalog matches on. +internal static class DriftZoneGameKey +{ + private sealed record Cached(NativeHudCompatibilityPack Pack, string Key); + + private static Cached? _last; + + // The drift renderer asks on every frame, so the key of the attached build is kept. + internal static string For(NativeHudCompatibilityPack pack) + { + ArgumentNullException.ThrowIfNull(pack); + if (Volatile.Read(ref _last) is { } last && ReferenceEquals(last.Pack, pack)) + { + return last.Key; + } + + var key = pack.StoreIdentity is { } store + ? FormattableString.Invariant($"store:{store.PackageFullName}:{pack.ImageSize}:{store.TimeDateStamp}") + : FormattableString.Invariant($"steam:{pack.GameVersion}:{pack.ExecutableLength}:{pack.ImageSize}:{pack.ExecutableSha256.ToUpperInvariant()}"); + Volatile.Write(ref _last, new Cached(pack, key)); + return key; + } +} diff --git a/src/Wisp.App/Drift/DriftZoneGameMemory.cs b/src/Wisp.App/Drift/DriftZoneGameMemory.cs new file mode 100644 index 00000000..176d7987 --- /dev/null +++ b/src/Wisp.App/Drift/DriftZoneGameMemory.cs @@ -0,0 +1,53 @@ +namespace Wisp.App.Drift; + +// The attached game's private writable memory, read through the read-only handle the HUD already holds. +internal sealed class DriftZoneGameMemory(NativeHudProcessMemory memory) : IDriftZoneScanMemory +{ + private const uint Committed = 0x1000; + private const uint PrivateMemory = 0x20000; + private const uint ReadWrite = 0x04; + private const int Piece = 64 * 1024; + + public IReadOnlyList Regions() + { + var regions = new List(); + ulong address = 0x10000; + while (address < NativeHudProcessMemory.UserAddressLimit && memory.TryQueryRegion(address, out var region)) + { + if (region.State == Committed && region.Type == PrivateMemory && region.Protect == ReadWrite) + { + regions.Add(new DriftZoneScanRegion(region.Base, region.Size)); + } + + var next = region.Base + region.Size; + if (next <= address) + { + break; + } + + address = next; + } + + return regions; + } + + public void ReadChunk(ulong address, Span destination) + { + if (memory.TryReadBytes(address, destination)) + { + return; + } + + // A region can change while it is read; keep the pieces that are still readable. + for (var offset = 0; offset < destination.Length; offset += Piece) + { + var part = destination.Slice(offset, Math.Min(Piece, destination.Length - offset)); + if (!memory.TryReadBytes(address + (ulong)offset, part)) + { + part.Clear(); + } + } + } + + public bool Read(ulong address, Span destination) => memory.TryReadBytes(address, destination); +} diff --git a/src/Wisp.App/Drift/DriftZoneProfileCatalog.cs b/src/Wisp.App/Drift/DriftZoneProfileCatalog.cs index f8f08fe0..977f4ab3 100644 --- a/src/Wisp.App/Drift/DriftZoneProfileCatalog.cs +++ b/src/Wisp.App/Drift/DriftZoneProfileCatalog.cs @@ -9,6 +9,10 @@ internal static class DriftZoneProfileCatalog private const string Steam483Hash = "63791D0B686186C23ADE10A1AE02EFD785045BD818CC89816F472CAD9A69FCB9"; private static readonly DriftZoneScoringProfile CurrentProfile = new(10, 110, (double)59.4f, 30, 40); + // The one scoring curve every checked build has used. DriftZoneCurveCheck grants it to a build + // outside this table only after reading it from the running game. + internal static DriftZoneScoringProfile KnownCurve => CurrentProfile; + // Scoring guidance is separate from HUD/Tune attachment. Adaptive validation // of those readers does not establish a game's loaded scoring parameters. // Unverified scoring retains the measured angle without claiming a bonus. diff --git a/src/Wisp.App/NativeHudProcessMemory.cs b/src/Wisp.App/NativeHudProcessMemory.cs index a9b1cae3..a0d7e37a 100644 --- a/src/Wisp.App/NativeHudProcessMemory.cs +++ b/src/Wisp.App/NativeHudProcessMemory.cs @@ -540,6 +540,22 @@ internal static bool IsValidReadSpan(ulong address, ulong length) => internal static SafeProcessHandle OpenReadOnly(int processId) => OpenProcess(RequiredProcessAccess, false, processId); + // Describes the memory region that holds address. A query only; it uses the same read-only handle. + internal bool TryQueryRegion(ulong address, out NativeMemoryRegion region) + { + region = default; + if (_handle.IsInvalid || _handle.IsClosed || + VirtualQueryEx(_handle, (nuint)address, out var information, (nuint)Marshal.SizeOf()) == 0 || + information.RegionSize == 0) + { + return false; + } + + region = new NativeMemoryRegion( + (ulong)information.BaseAddress, (ulong)information.RegionSize, information.State, information.Protect, information.Type); + return true; + } + internal static bool HandleMatchesIdentity( SafeProcessHandle handle, NativeHudProcessIdentity identity, bool allowStoreFileAlias = false) { @@ -567,6 +583,22 @@ private bool CanRead(ulong address, ulong length) => [DllImport("kernel32.dll", SetLastError = true)] private static extern SafeProcessHandle OpenProcess(uint desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, int processId); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern nuint VirtualQueryEx(SafeProcessHandle process, nuint address, out MemoryBasicInformation information, nuint length); + + [StructLayout(LayoutKind.Sequential)] + private struct MemoryBasicInformation + { + public nuint BaseAddress; + public nuint AllocationBase; + public uint AllocationProtect; + public ushort PartitionId; + public nuint RegionSize; + public uint State; + public uint Protect; + public uint Type; + } + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetProcessTimes(SafeProcessHandle process, out FILETIME creation, out FILETIME exit, out FILETIME kernel, out FILETIME user); @@ -597,6 +629,7 @@ private bool CanRead(ulong address, ulong length) => } internal readonly record struct NativeHudProcessIdentity(int ProcessId, long StartTimeUtcTicks, string ExecutablePath, ulong ModuleBase, uint ImageSize); +internal readonly record struct NativeMemoryRegion(ulong Base, ulong Size, uint State, uint Protect, uint Type); internal readonly record struct NativeHudFileMetadata(long Length, long CreationTimeUtcTicks, long LastWriteTimeUtcTicks, uint VolumeSerialNumber, ulong FileIndex, string Version); internal readonly record struct NativeHudExecutableFingerprint(NativeHudFileMetadata Metadata, string Sha256); diff --git a/src/Wisp.App/Supplementary/FeatureControlPolicy.cs b/src/Wisp.App/Supplementary/FeatureControlPolicy.cs index d996277d..67352855 100644 --- a/src/Wisp.App/Supplementary/FeatureControlPolicy.cs +++ b/src/Wisp.App/Supplementary/FeatureControlPolicy.cs @@ -12,7 +12,7 @@ internal static class ControlledFeatures "run-recording", "run-library", "lap-review", "tune-read", "tune-library", "clip-recording", "clip-playback", "clip-export", "clip-library", "shift-calibration", "tire-calibration", "shift-guidance", "traction-cue", "background-animation", - "hud-profiles", "appearance", "diagnostics", "news", "support", "updates", "gpu-priority"); + "hud-profiles", "appearance", "diagnostics", "news", "support", "updates", "gpu-priority", "drift-zone-check"); } internal sealed record FeatureControlRule(string Id, ImmutableArray Features, string Reason, diff --git a/tests/Wisp.App.Tests/DriftZoneCurveCheckTests.cs b/tests/Wisp.App.Tests/DriftZoneCurveCheckTests.cs new file mode 100644 index 00000000..5c97bde9 --- /dev/null +++ b/tests/Wisp.App.Tests/DriftZoneCurveCheckTests.cs @@ -0,0 +1,268 @@ +using System.IO; +using Wisp.App.Drift; +using Wisp.Core; +using Xunit; + +namespace Wisp.App.Tests; + +public sealed class DriftZoneCurveCheckTests : IDisposable +{ + private const string Build = "steam:6.999.1.0:1:2:ABC"; + private static readonly DriftZoneScoringProfile Curve = new(10, 110, (double)59.4f, 30, 40); + private readonly string _directory = Path.Combine(Path.GetTempPath(), "wisp-drift-check-" + Guid.NewGuid().ToString("N")); + private readonly FakeTime _time = new(); + private readonly List<(string Outcome, double? Duration)> _reports = []; + private readonly Queue _verdicts = new(); + private int _opens; + private int _scans; + private string? _sessionBuild = Build; + private bool _openFails; + + public void Dispose() + { + try { Directory.Delete(_directory, recursive: true); } + catch (IOException) { } + } + + private string StorePath => Path.Combine(_directory, "drift-zone-checks.json"); + + private DriftZoneCurveCheck Create(Action? run = null) => new( + Curve, + _ => + { + _opens++; + return _openFails || _sessionBuild is null ? null : new DriftZoneScanSession(_sessionBuild, new NoMemory(), new Owner()); + }, + new DriftZoneCheckStore(StorePath), + (outcome, duration) => _reports.Add((outcome, duration)), + _time, + (_, _) => + { + _scans++; + var verdict = _verdicts.Count > 0 ? _verdicts.Dequeue() : DriftZoneCurveVerdict.Verified; + return new DriftZoneCurveScanResult(verdict, verdict == DriftZoneCurveVerdict.Verified ? 20 : 0, 1024, TimeSpan.FromMilliseconds(1500)); + }, + run ?? (work => work())); + + [Fact] + public void AListedBuildHasTheCurveAtOnceAndIsReadOnceInTheBackground() + { + using var check = Create(); + + Assert.Same(Curve, check.Resolve(Build, Curve, driving: false, allowed: true)); + Assert.Equal(0, _scans); + Assert.Same(Curve, check.Resolve(Build, Curve, driving: true, allowed: true)); + Assert.Same(Curve, check.Resolve(Build, Curve, driving: true, allowed: true)); + + Assert.Equal(1, _scans); + Assert.Equal([("success", 1500d)], _reports); + } + + [Fact] + public void AnUnlistedBuildGetsTheCurveOnlyAfterTheGameWasReadAndHeldIt() + { + using var check = Create(); + + Assert.Null(check.Resolve(Build, null, driving: false, allowed: true)); + Assert.Equal(0, _scans); + // The read runs inline in this test, so the first driving frame already sees its result on the next call. + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Same(Curve, check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Same(Curve, check.Resolve(Build, null, driving: false, allowed: true)); + Assert.Equal(1, _scans); + } + + [Fact] + public void AVerifiedBuildIsRememberedAcrossStartsAndReadAgainAfterTwoWeeks() + { + using (var first = Create()) + { + first.Resolve(Build, null, driving: true, allowed: true); + } + + using var second = Create(); + Assert.Same(Curve, second.Resolve(Build, null, driving: true, allowed: true)); + Assert.Equal(1, _scans); + + _time.Advance(DriftZoneCurveCheck.RevalidateAfter); + _verdicts.Enqueue(DriftZoneCurveVerdict.NotFound); + // The stored result stands while the new read runs, then the new result replaces it. + Assert.Same(Curve, second.Resolve(Build, null, driving: true, allowed: true)); + Assert.Equal(2, _scans); + Assert.Null(second.Resolve(Build, null, driving: true, allowed: true)); + } + + [Fact] + public void ABuildWithoutTheCurveStaysAngleOnlyAndIsRetriedWithGrowingPauses() + { + foreach (var _ in Enumerable.Range(0, 5)) _verdicts.Enqueue(DriftZoneCurveVerdict.NotFound); + using var check = Create(); + + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Equal(1, _scans); + + _time.Advance(TimeSpan.FromMinutes(2)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Equal(2, _scans); + + _time.Advance(TimeSpan.FromMinutes(9)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Equal(2, _scans); + _time.Advance(TimeSpan.FromMinutes(1)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Equal(3, _scans); + + _time.Advance(TimeSpan.FromMinutes(59)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Equal(3, _scans); + _time.Advance(TimeSpan.FromMinutes(1)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Equal(4, _scans); + + // One report per result and build in a run, however often it repeats. + Assert.Equal([("unsupported", 1500d)], _reports); + } + + [Fact] + public void APausedCheckNeitherReadsTheGameNorGrantsTheCurveToAnUnlistedBuild() + { + using (var first = Create()) + { + first.Resolve(Build, null, driving: true, allowed: true); + } + + using var paused = Create(); + Assert.Null(paused.Resolve(Build, null, driving: true, allowed: false)); + Assert.Same(Curve, paused.Resolve(Build, Curve, driving: true, allowed: false)); + Assert.Null(paused.Resolve("store:other", null, driving: true, allowed: false)); + Assert.Equal(1, _scans); + } + + [Fact] + public void AReadThatCannotStartOrFinishKeepsTheStoredResultAndBacksOff() + { + using var check = Create(); + _openFails = true; + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Equal((1, 0), (_opens, _scans)); + Assert.Equal("failure", _reports[^1].Outcome); + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Equal(1, _opens); + + _openFails = false; + _verdicts.Enqueue(DriftZoneCurveVerdict.Incomplete); + _time.Advance(TimeSpan.FromMinutes(2)); + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Equal("timeout", _reports[^1].Outcome); + Assert.False(File.Exists(StorePath)); + + _time.Advance(TimeSpan.FromMinutes(10)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Same(Curve, check.Resolve(Build, null, driving: true, allowed: true)); + } + + [Fact] + public void AReadOfAnotherGameBuildDoesNotCountForThisOne() + { + using var check = Create(); + _sessionBuild = "steam:6.999.2.0:1:2:DEF"; + + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + Assert.Null(check.Resolve(Build, null, driving: true, allowed: true)); + + Assert.Equal((1, 0), (_opens, _scans)); + Assert.Equal("failure", _reports[^1].Outcome); + } + + [Fact] + public void OnlyOneReadRunsAtATimeAndNoneAfterDisposal() + { + var pending = new List(); + var check = Create(pending.Add); + + check.Resolve(Build, null, driving: true, allowed: true); + check.Resolve(Build, null, driving: true, allowed: true); + check.Resolve("store:other", null, driving: true, allowed: true); + Assert.Single(pending); + + check.Dispose(); + pending[0](); + Assert.Empty(_reports); + Assert.False(File.Exists(StorePath)); + check.Resolve(Build, null, driving: true, allowed: true); + Assert.Single(pending); + } + + [Fact] + public void WithoutAnAttachedGameTheCatalogAnswerStands() + { + using var check = Create(); + + Assert.Null(check.Resolve(null, null, driving: true, allowed: true)); + Assert.Same(Curve, check.Resolve(null, Curve, driving: true, allowed: true)); + Assert.Equal(0, _opens); + } + + [Theory] + [InlineData("")] + [InlineData("not json")] + [InlineData("{\"Version\":2,\"Builds\":{}}")] + [InlineData("{\"Version\":1,\"Builds\":{\"steam:6.999.1.0:1:2:ABC\":{\"Outcome\":\"Granted\",\"CheckedAt\":\"2026-11-20T00:00:00+00:00\",\"Entries\":20}}}")] + public void ADamagedOrUnknownResultFileIsTreatedAsEmpty(string content) + { + Directory.CreateDirectory(_directory); + File.WriteAllText(StorePath, content); + + Assert.Null(new DriftZoneCheckStore(StorePath).Find(Build)); + } + + [Fact] + public void ResultsRoundTripThroughTheFile() + { + var checkedAt = new DateTimeOffset(2026, 11, 20, 3, 0, 0, TimeSpan.Zero); + new DriftZoneCheckStore(StorePath).Save(Build, new DriftZoneCheckRecord(DriftZoneCheckOutcome.Verified, checkedAt, 20)); + + Assert.Equal(new DriftZoneCheckRecord(DriftZoneCheckOutcome.Verified, checkedAt, 20), new DriftZoneCheckStore(StorePath).Find(Build)); + Assert.Null(new DriftZoneCheckStore(null).Find(Build)); + } + + [Theory] + [InlineData("Verified", "success")] + [InlineData("NotFound", "unsupported")] + [InlineData("Unstable", "unknown")] + [InlineData("Incomplete", "timeout")] + [InlineData("Unavailable", "failure")] + public void EveryResultIsReportedWithAnOutcomeTheReportFormatKnows(string outcome, string expected) + { + Assert.Equal(expected, DriftZoneCurveCheck.Token(Enum.Parse(outcome))); + Assert.Equal(5, Enum.GetValues().Length); + } + + private sealed class FakeTime : TimeProvider + { + private DateTimeOffset _now = new(2026, 11, 20, 0, 0, 0, TimeSpan.Zero); + + public override DateTimeOffset GetUtcNow() => _now; + + internal void Advance(TimeSpan by) => _now += by; + } + + private sealed class Owner : IDisposable + { + public void Dispose() + { + } + } + + private sealed class NoMemory : IDriftZoneScanMemory + { + public IReadOnlyList Regions() => []; + + public void ReadChunk(ulong address, Span destination) + { + } + + public bool Read(ulong address, Span destination) => false; + } +} diff --git a/tests/Wisp.App.Tests/DriftZoneCurveScanTests.cs b/tests/Wisp.App.Tests/DriftZoneCurveScanTests.cs new file mode 100644 index 00000000..44dac4b6 --- /dev/null +++ b/tests/Wisp.App.Tests/DriftZoneCurveScanTests.cs @@ -0,0 +1,231 @@ +using System.Buffers.Binary; +using Wisp.App.Drift; +using Wisp.Core; +using Xunit; + +namespace Wisp.App.Tests; + +public sealed class DriftZoneCurveScanTests +{ + private static readonly DriftZoneScoringProfile Curve = new(10, 110, (double)59.4f, 30, 40); + private static readonly DriftZoneCurveScanOptions Fast = new() { PaceFactor = 0, SettleDelay = TimeSpan.Zero, Wait = static _ => { } }; + + [Fact] + public void TwentyEntriesInTheGameArrangementAreVerified() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 24 * 0xB00); + for (var i = 0; i < 20; i++) memory.WriteEntry(pool + (ulong)i * 0xB00 + 0x8D4); + + var result = DriftZoneCurveScan.Run(memory, Curve, Fast, CancellationToken.None); + + Assert.Equal(DriftZoneCurveVerdict.Verified, result.Verdict); + Assert.Equal(20, result.Entries); + Assert.Equal(24 * 0xB00, result.BytesRead); + } + + [Theory] + [InlineData(0)] + [InlineData(5)] + [InlineData(7)] + public void FewerEntriesThanTheMinimumAreNotAccepted(int count) + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 24 * 0xB00); + for (var i = 0; i < count; i++) memory.WriteEntry(pool + (ulong)i * 0xB00 + 0x8D4); + + var result = DriftZoneCurveScan.Run(memory, Curve, Fast, CancellationToken.None); + + Assert.Equal(DriftZoneCurveVerdict.NotFound, result.Verdict); + Assert.Equal(count, result.Entries); + } + + [Fact] + public void ADifferentSaturationAngleIsNotFound() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 24 * 0xB00); + for (var i = 0; i < 20; i++) memory.WriteEntry(pool + (ulong)i * 0xB00 + 0x8D4, saturation: 65f); + + Assert.Equal(DriftZoneCurveVerdict.NotFound, DriftZoneCurveScan.Run(memory, Curve, Fast, CancellationToken.None).Verdict); + } + + [Fact] + public void ADifferentMultiplierIsNotFound() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 24 * 0xB00); + for (var i = 0; i < 20; i++) memory.WriteEntry(pool + (ulong)i * 0xB00 + 0x8D4, high: 45f, extra: false); + + Assert.Equal(DriftZoneCurveVerdict.NotFound, DriftZoneCurveScan.Run(memory, Curve, Fast, CancellationToken.None).Verdict); + } + + [Fact] + public void StrayCopiesOfTheAngleDoNotCountAsEntries() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 0x10000); + for (var i = 0; i < 40; i++) memory.WriteSingle(pool + 0x100 + (ulong)i * 0x200, 59.4f); + // Seven complete entries in one arrangement and three in another are still too few of either. + for (var i = 0; i < 7; i++) memory.WriteEntry(pool + 0x8000 + (ulong)i * 0x400); + for (var i = 0; i < 3; i++) memory.WriteShuffledEntry(pool + 0xC000 + (ulong)i * 0x400); + + var result = DriftZoneCurveScan.Run(memory, Curve, Fast, CancellationToken.None); + + Assert.Equal(DriftZoneCurveVerdict.NotFound, result.Verdict); + Assert.Equal(7, result.Entries); + } + + [Fact] + public void EntriesThatChangeBeforeTheSecondReadAreUnstable() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 24 * 0xB00); + for (var i = 0; i < 20; i++) memory.WriteEntry(pool + (ulong)i * 0xB00 + 0x8D4); + var options = Fast with { Wait = _ => memory.WriteSingle(pool + 3 * 0xB00 + 0x8D4, 12f) }; + + var result = DriftZoneCurveScan.Run(memory, Curve, options, CancellationToken.None); + + Assert.Equal(DriftZoneCurveVerdict.Unstable, result.Verdict); + } + + [Fact] + public void EntriesAcrossChunkBordersAndAtBlockEdgesAreFound() + { + var memory = new FakeMemory(); + var first = memory.Add(0x1E0_0000_0000, 0x3000); + var second = memory.Add(0x1F0_0000_0000, 0x3000); + // One at the very start of a block, one at its very end, and four whose fields straddle a 4 KiB chunk border. + memory.WriteEntry(first + 8); + memory.WriteEntry(first + 0x3000 - 0x24); + memory.WriteEntry(first + 0xFFC); + memory.WriteEntry(first + 0x2004); + memory.WriteEntry(second + 0x1000); + memory.WriteEntry(second + 0x1FF8); + for (var i = 0; i < 4; i++) memory.WriteEntry(second + 0x2100 + (ulong)i * 0x400); + var options = Fast with { ChunkBytes = 4096 }; + + var result = DriftZoneCurveScan.Run(memory, Curve, options, CancellationToken.None); + + Assert.Equal(10, result.Entries); + Assert.Equal(DriftZoneCurveVerdict.Verified, result.Verdict); + } + + [Fact] + public void PagesTheMemoryLayerLeavesOutAreNotReadAnotherWay() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 0x20000); + for (var i = 0; i < 20; i++) memory.WriteEntry(pool + 0x10000 + (ulong)i * 0x400); + memory.LeaveOut(pool, 0x10000); + + var result = DriftZoneCurveScan.Run(memory, Curve, Fast, CancellationToken.None); + + Assert.Equal(DriftZoneCurveVerdict.Verified, result.Verdict); + Assert.Equal(0, memory.LeftOutBytesRead); + } + + [Fact] + public void ALimitOrACancellationLeavesTheResultIncomplete() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 0x40000); + for (var i = 0; i < 20; i++) memory.WriteEntry(pool + 0x30000 + (ulong)i * 0x400); + var small = Fast with { ChunkBytes = 4096, MaximumBytes = 0x8000 }; + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + + Assert.Equal(DriftZoneCurveVerdict.Incomplete, DriftZoneCurveScan.Run(memory, Curve, small, CancellationToken.None).Verdict); + Assert.Equal(DriftZoneCurveVerdict.Incomplete, DriftZoneCurveScan.Run(memory, Curve, Fast, cancelled.Token).Verdict); + Assert.Equal(DriftZoneCurveVerdict.Incomplete, DriftZoneCurveScan.Run(memory, Curve, Fast with { MaximumDuration = TimeSpan.Zero }, CancellationToken.None).Verdict); + } + + [Fact] + public void TheReadPausesBetweenChunksAndBeforeTheSecondRead() + { + var memory = new FakeMemory(); + var pool = memory.Add(0x1E0_0000_0000, 0x4000); + for (var i = 0; i < 8; i++) memory.WriteEntry(pool + 0x100 + (ulong)i * 0x400); + var waits = new List(); + var options = new DriftZoneCurveScanOptions { ChunkBytes = 4096, SettleDelay = TimeSpan.FromSeconds(1), Wait = waits.Add }; + + var result = DriftZoneCurveScan.Run(memory, Curve, options, CancellationToken.None); + + Assert.Equal(DriftZoneCurveVerdict.Verified, result.Verdict); + Assert.Equal(5, waits.Count); + Assert.Equal(TimeSpan.FromSeconds(1), waits[^1]); + } + + private sealed class FakeMemory : IDriftZoneScanMemory + { + private readonly List<(ulong Base, byte[] Data)> _blocks = []; + private readonly List<(ulong Start, ulong End)> _leftOut = []; + + internal long LeftOutBytesRead { get; private set; } + + internal ulong Add(ulong address, int size) + { + _blocks.Add((address, new byte[size])); + return address; + } + + internal void LeaveOut(ulong start, ulong length) => _leftOut.Add((start, start + length)); + + internal void WriteSingle(ulong address, float value) => BinaryPrimitives.WriteSingleLittleEndian(At(address, 4), value); + + // The arrangement both game builds use: minimum, maximum, saturation, four other values, then the multipliers. + internal void WriteEntry(ulong saturationAddress, float saturation = 59.4f, float high = 40f, bool extra = true) + { + float[] values = extra + ? [10f, 110f, saturation, 54f, 10f, 50f, 0.1f, 30f, high, 45f, 50f] + : [10f, 110f, saturation, 54f, 11f, 50f, 0.1f, 30f, high, 45f, 50f]; + for (var i = 0; i < values.Length; i++) WriteSingle(saturationAddress - 8 + (ulong)i * 4, values[i]); + } + + internal void WriteShuffledEntry(ulong saturationAddress) + { + float[] values = [30f, 40f, 59.4f, 10f, 110f]; + for (var i = 0; i < values.Length; i++) WriteSingle(saturationAddress - 8 + (ulong)i * 4, values[i]); + } + + public IReadOnlyList Regions() => _blocks.Select(block => new DriftZoneScanRegion(block.Base, (ulong)block.Data.Length)).ToList(); + + public void ReadChunk(ulong address, Span destination) + { + if (!Read(address, destination)) return; + foreach (var (start, end) in _leftOut) + { + var from = Math.Max(start, address); + var to = Math.Min(end, address + (ulong)destination.Length); + if (to > from) destination.Slice((int)(from - address), (int)(to - from)).Clear(); + } + } + + public bool Read(ulong address, Span destination) + { + foreach (var (blockBase, data) in _blocks) + { + if (address < blockBase || address + (ulong)destination.Length > blockBase + (ulong)data.Length) continue; + data.AsSpan((int)(address - blockBase), destination.Length).CopyTo(destination); + foreach (var (start, end) in _leftOut) + { + if (address < end && address + (ulong)destination.Length > start && destination.Length <= 0x200) LeftOutBytesRead += destination.Length; + } + + return true; + } + + return false; + } + + private Span At(ulong address, int length) + { + foreach (var (blockBase, data) in _blocks) + { + if (address >= blockBase && address + (ulong)length <= blockBase + (ulong)data.Length) return data.AsSpan((int)(address - blockBase), length); + } + + throw new ArgumentOutOfRangeException(nameof(address)); + } + } +} diff --git a/tests/Wisp.App.Tests/DriftZoneGameKeyTests.cs b/tests/Wisp.App.Tests/DriftZoneGameKeyTests.cs new file mode 100644 index 00000000..bd0e94f6 --- /dev/null +++ b/tests/Wisp.App.Tests/DriftZoneGameKeyTests.cs @@ -0,0 +1,52 @@ +using System.Text.Json.Nodes; +using Wisp.App.Drift; +using Xunit; + +namespace Wisp.App.Tests; + +public sealed class DriftZoneGameKeyTests +{ + [Fact] + public void SteamAndStoreBuildsAreNamedByTheFieldsTheScoringTableMatches() + { + var steam = NativeHudBuildContract.UpdatedSteamBuiltIn; + var store = NativeHudBuildContract.UpdatedStoreBuiltIn; + + Assert.Equal( + $"steam:{steam.GameVersion}:{steam.ExecutableLength}:{steam.ImageSize}:{steam.ExecutableSha256.ToUpperInvariant()}", + DriftZoneGameKey.For(steam)); + Assert.Equal( + $"store:{store.StoreIdentity!.PackageFullName}:{store.ImageSize}:{store.StoreIdentity.TimeDateStamp}", + DriftZoneGameKey.For(store)); + Assert.NotEqual(DriftZoneGameKey.For(steam), DriftZoneGameKey.For(NativeHudBuildContract.BuiltIn)); + Assert.NotEqual(DriftZoneGameKey.For(store), DriftZoneGameKey.For(NativeHudBuildContract.StoreBuiltIn)); + } + + [Theory] + [InlineData("gameVersion")] + [InlineData("executableLength")] + [InlineData("executableSha256")] + [InlineData("imageSize")] + public void AnyChangedIdentityFieldNamesAnotherBuild(string field) + { + using var stream = typeof(NativeHudBuildContract).Assembly.GetManifestResourceStream("Wisp.NativeCompatibility.UpdatedSteam.json")!; + var document = JsonNode.Parse(stream)!.AsObject(); + var original = DriftZoneGameKey.For(NativeHudCompatibilityPack.FromRuntimeValidation(JsonNode.Parse(document.ToJsonString())!.AsObject())); + document[field] = field switch + { + "gameVersion" => JsonValue.Create("6.999.1.0"), + "executableLength" => JsonValue.Create(document[field]!.GetValue() + 1), + "executableSha256" => JsonValue.Create(new string('A', 64)), + _ => JsonValue.Create(document[field]!.GetValue() + 4096) + }; + + Assert.NotEqual(original, DriftZoneGameKey.For(NativeHudCompatibilityPack.FromRuntimeValidation(document))); + } + + [Fact] + public void TheKnownCurveIsTheOneTheScoringTableGrants() + { + Assert.Equal(DriftZoneProfileCatalog.ForBuild(NativeHudBuildContract.BuiltIn), DriftZoneProfileCatalog.KnownCurve); + Assert.Contains("drift-zone-check", Wisp.App.Supplementary.ControlledFeatures.All); + } +} diff --git a/tests/Wisp.App.Tests/Fixtures/FeatureControls/service-schema-1.json b/tests/Wisp.App.Tests/Fixtures/FeatureControls/service-schema-1.json index e93c72cc..11368b10 100644 --- a/tests/Wisp.App.Tests/Fixtures/FeatureControls/service-schema-1.json +++ b/tests/Wisp.App.Tests/Fixtures/FeatureControls/service-schema-1.json @@ -36,7 +36,8 @@ "news", "support", "updates", - "gpu-priority" + "gpu-priority", + "drift-zone-check" ], "paused": { "keyId": "test-key",