Skip to content
Open
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
15 changes: 15 additions & 0 deletions app/Sprint.Desktop.Core/Features/SessionPlanning/PlanLimits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public static class PlanLimits
/// <summary>The most fuel per lap a plan may type, in litres.</summary>
public const double MaxFuelPerLapLiters = 100;

/// <summary>The largest tank limit a race may set, in litres: more than any car in the game holds.</summary>
public const double MaxTankLimitLiters = 300;

/// <summary>Why a race length is refused, or null when the race could be run.</summary>
public static string? RaceLengthError(RaceLengthFormat format, double value) => format switch
{
Expand All @@ -47,6 +50,18 @@ public static class PlanLimits
? null
: $"avgLapTimeSeconds must be from {MinLapTimeSeconds} to {MaxLapTimeSeconds} seconds";

/// <summary>Why a race's tank limit is refused, or null for a tank a car could hold.</summary>
public static string? TankLimitError(double liters) =>
liters > 0 && liters <= MaxTankLimitLiters
? null
: $"tankLimitLiters must be more than 0 and at most {MaxTankLimitLiters} litres";

/// <summary>Why a race's virtual energy share is refused, or null for a whole percentage from 1 to 100.</summary>
public static string? VirtualEnergyPercentError(double percent) =>
percent >= 1 && percent <= 100 && Math.Floor(percent) == percent
? null
: "virtualEnergyPercent must be a whole number from 1 to 100";

/// <summary>Why a typed fuel per lap is refused, or null when a car could burn it.</summary>
public static string? FuelPerLapError(double liters) =>
liters > 0 && liters <= MaxFuelPerLapLiters
Expand Down
154 changes: 154 additions & 0 deletions app/Sprint.Desktop.Core/Features/SessionPlanning/PlanPicker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
using Sprint.Games;

namespace Sprint.Desktop.Features.SessionPlanning;

/// <summary>One car the New plan dialog offers: its name (the lap-history key, <see cref="CarNames"/>), how it reads, and the driver's valid laps in it.</summary>
public sealed record PlanPickerCar(string Name, CarMarks Marks, int Laps);

/// <summary>
/// One track layout the New plan dialog offers: the track as the plan stores it, its circuit (the
/// tile, as drivers call it: "Spa-Francorchamps") and layout (picked after the circuit when it has
/// several), the country for its flag, and the driver's valid laps on it.
/// </summary>
public sealed record PlanPickerTrack(string Track, string CircuitId, string Circuit, string Layout, string? Country, int Laps);

/// <summary>A car and track driven together, newest first: one click in the dialog's Recent row.</summary>
public sealed record PlanPickerPair(string Car, string Track);

/// <summary>
/// What the New plan dialog picks the car and track from, as tiles rather than long lists: every
/// car and track the game offers (<see cref="GameCarCatalog"/>, <see cref="GameTrackCatalog"/>),
/// so a plan can be made for one not driven yet, joined with what the driver has recorded, with
/// their laps on each, and their last pairings.
/// <para>
/// A driven car or layout is offered under the name its laps are filed under, never a second
/// spelling of it: the corpus is keyed on exact strings, and a plan under another spelling would
/// never see those laps. Recorded cars and tracks the catalogs do not know are offered too, as
/// they were recorded.
/// </para>
/// </summary>
public sealed record PlanPicker(IReadOnlyList<PlanPickerCar> Cars, IReadOnlyList<PlanPickerTrack> Tracks, IReadOnlyList<PlanPickerPair> Recent)
{
/// <summary>How many pairings the Recent row offers.</summary>
public const int RecentCount = 3;

/// <summary>The game a picker is built for when the dialog knows none: the one game Sprint reads.</summary>
public const string DefaultGame = "LeMansUltimate";

public static PlanPicker Empty { get; } = new([], [], []);

/// <summary>
/// The picker for <paramref name="game"/> over the corpus <paramref name="sessions"/>, with the
/// <paramref name="live"/> car and track (the session about to be driven, or the last one) offered
/// even before it has a recorded lap. Cars with laps come first, most laps first; circuits by the
/// laps on all their layouts, which keep catalog order; the rest keep catalog order.
/// </summary>
public static PlanPicker For(string game, IReadOnlyList<LapHistorySession> sessions, PlanContext live)
{
ArgumentNullException.ThrowIfNull(game);
ArgumentNullException.ThrowIfNull(sessions);
ArgumentNullException.ThrowIfNull(live);

List<LapHistorySession> ofGame = sessions.Where(session => SameGame(session.Context.Game, game)).ToList();
return new PlanPicker(OfferedCars(game, ofGame, live), OfferedTracks(game, ofGame, live), RecentPairs(ofGame));
}

private static bool SameGame(string recorded, string game) =>
string.Equals(recorded, game, StringComparison.OrdinalIgnoreCase)
|| (GameNames.IsLeMansUltimate(recorded) && GameNames.IsLeMansUltimate(game));

private static int ValidLaps(LapHistorySession session) => session.Laps.Count(lap => lap.IsValid && lap.LapTimeSeconds > 0);

private static IReadOnlyList<PlanPickerCar> OfferedCars(string game, List<LapHistorySession> sessions, PlanContext live)
{
Dictionary<string, int> laps = sessions
.GroupBy(session => session.Context.CarModel, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.Sum(ValidLaps), StringComparer.Ordinal);

List<PlanPickerCar> cars = [];
HashSet<string> named = new(StringComparer.Ordinal);
foreach (GameCar car in GameCarCatalog.Cars(game))
{
if (CarNames.Name(car.CarClass, car.Championship, car.Model) is { } name && named.Add(name))
{
cars.Add(new PlanPickerCar(name, CarMarks.Of(game, "", name, car.CarClass, car.Model), laps.GetValueOrDefault(name)));
}
}

// Recorded cars the catalog does not name, as the recorder filed them.
foreach (LapHistorySession session in sessions)
{
LapHistoryContext context = session.Context;
if (!string.IsNullOrWhiteSpace(context.CarModel) && named.Add(context.CarModel))
{
cars.Add(new PlanPickerCar(
context.CarModel,
CarMarks.Of(game, "", context.CarModel, context.CarClass, context.CarType),
laps.GetValueOrDefault(context.CarModel)));
}
}

if (!string.IsNullOrWhiteSpace(live.Car) && named.Add(live.Car))
{
cars.Add(new PlanPickerCar(live.Car, CarMarks.Of(game, "", live.Car), 0));
}

// Stable: equal laps keep catalog order.
return [.. cars.OrderByDescending(car => car.Laps)];
}

private static IReadOnlyList<PlanPickerTrack> OfferedTracks(string game, List<LapHistorySession> sessions, PlanContext live)
{
// Each recorded spelling with its laps, most laps first, so a layout recorded under two
// spellings is offered under the one most of its laps carry.
List<(string Track, int Laps)> recorded = sessions
.Where(session => !string.IsNullOrWhiteSpace(session.Context.TrackCourse))
.GroupBy(session => session.Context.TrackCourse, StringComparer.Ordinal)
.Select(group => (group.Key, group.Sum(ValidLaps)))
.OrderByDescending(entry => entry.Item2)
.ToList();
if (!string.IsNullOrWhiteSpace(live.Track) && !recorded.Any(entry => entry.Track == live.Track))
{
recorded.Add((live.Track, 0));
}

List<PlanPickerTrack> tracks = [];
HashSet<string> used = new(StringComparer.Ordinal);
foreach (GameCircuit circuit in GameTrackCatalog.Offered(game))
{
string firstName = circuit.Layouts[0].TrackName;
string? country = GameTrackCatalog.Country(game, firstName);
string shown = GameTrackCatalog.ShortName(game, firstName) ?? circuit.Name;
foreach (GameTrackLayout layout in circuit.Layouts)
{
List<(string Track, int Laps)> driven = recorded
.Where(entry => GameTrackCatalog.CircuitId(game, entry.Track) == circuit.Id
&& GameTrackCatalog.LayoutLabel(game, entry.Track) == layout.Label)
.ToList();
string track = driven.Count > 0 ? driven[0].Track : layout.TrackName;
used.UnionWith(driven.Select(entry => entry.Track));
tracks.Add(new PlanPickerTrack(track, circuit.Id, shown, layout.Label, country, driven.Sum(entry => entry.Laps)));
}
}

// Recorded tracks the catalog does not know: each its own circuit, as recorded.
foreach ((string track, int laps) in recorded.Where(entry => !used.Contains(entry.Track)))
{
tracks.Add(new PlanPickerTrack(track, GameTrackCatalog.CircuitId(game, track), track.Trim(), track.Trim(), null, laps));
}

// A circuit's tile carries all its layouts' laps, so order circuits by that and keep layouts in catalog order.
Dictionary<string, int> circuitLaps = tracks.GroupBy(track => track.CircuitId).ToDictionary(group => group.Key, group => group.Sum(track => track.Laps));
return [.. tracks.OrderByDescending(track => circuitLaps[track.CircuitId])];
}

private static IReadOnlyList<PlanPickerPair> RecentPairs(List<LapHistorySession> sessions) =>
[
.. sessions
.Where(session => !string.IsNullOrWhiteSpace(session.Context.CarModel) && !string.IsNullOrWhiteSpace(session.Context.TrackCourse))
.OrderByDescending(session => session.StartedAt)
.Select(session => new PlanPickerPair(session.Context.CarModel, session.Context.TrackCourse))
.Distinct()
.Take(RecentCount),
];
}
Loading