Implement live game clock and simulation controls; enhance API with clock update functionality and improve world summary with clock data; update UI to display simulation controls and integrate clock features into the game experience.

This commit is contained in:
Leonid Pershin
2026-08-16 19:31:12 +03:00
parent b75844d11a
commit 3b7fca1495
22 changed files with 1290 additions and 14 deletions
@@ -0,0 +1,61 @@
using TheLivingWorld.Core.Simulation;
namespace TheLivingWorld.Tests;
public sealed class GameTimeTests
{
[Fact]
public void Advance_at_x1_adds_five_game_minutes_per_real_second()
{
var start = GameTime.DefaultStart;
var next = GameTime.Advance(start, TimeSpan.FromSeconds(1), timeScale: 1, paused: false);
Assert.Equal(start.AddMinutes(5), next);
}
[Fact]
public void Advance_scales_with_time_scale()
{
var start = GameTime.DefaultStart;
Assert.Equal(start.AddMinutes(10), GameTime.Advance(start, TimeSpan.FromSeconds(1), 2, false));
Assert.Equal(start.AddMinutes(20), GameTime.Advance(start, TimeSpan.FromSeconds(1), 4, false));
}
[Fact]
public void Advance_does_nothing_when_paused_or_non_positive()
{
var start = GameTime.DefaultStart;
Assert.Equal(start, GameTime.Advance(start, TimeSpan.FromSeconds(10), 4, paused: true));
Assert.Equal(start, GameTime.Advance(start, TimeSpan.Zero, 1, paused: false));
Assert.Equal(start, GameTime.Advance(start, TimeSpan.FromSeconds(-1), 1, paused: false));
}
[Fact]
public void Advance_handles_a_large_wall_clock_gap()
{
var start = GameTime.DefaultStart;
// One real hour at x1 → 5 * 3600 = 18_000 game minutes = 12.5 game days.
var next = GameTime.Advance(start, TimeSpan.FromHours(1), timeScale: 1, paused: false);
Assert.Equal(start.AddMinutes(5 * 3600), next);
Assert.Equal(new DateTime(2012, 4, 24, 18, 0, 0, DateTimeKind.Unspecified), next);
}
[Fact]
public void DefaultStart_is_morning_of_12_April_2012()
{
Assert.Equal(new DateTime(2012, 4, 12, 6, 0, 0, DateTimeKind.Unspecified), GameTime.DefaultStart);
}
[Theory]
[InlineData(1, true)]
[InlineData(4, true)]
[InlineData(0, false)]
[InlineData(5, false)]
public void IsValidTimeScale_accepts_1_through_4(int scale, bool expected)
{
Assert.Equal(expected, GameTime.IsValidTimeScale(scale));
}
}
@@ -2,6 +2,7 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using TheLivingWorld.Api.Generation;
using TheLivingWorld.Api.Simulation;
using TheLivingWorld.Api.Storage;
using TheLivingWorld.Core.Contracts;
using TheLivingWorld.Core.Export;
@@ -66,6 +67,7 @@ public sealed class WorldGenerationServiceTests : IDisposable
generator,
_store,
new ChunkExporter(),
new WorldSimulationHost(_store, NullLogger<WorldSimulationHost>.Instance),
Options.Create(new WorldStorageOptions
{
RootDirectory = _root,
@@ -0,0 +1,115 @@
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using TheLivingWorld.Api.Simulation;
using TheLivingWorld.Api.Storage;
using TheLivingWorld.Core.Contracts;
using TheLivingWorld.Core.Simulation;
namespace TheLivingWorld.Tests;
public sealed class WorldSimulationHostTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"tlw-sim-{Guid.NewGuid():n}");
private readonly WorldStore _store;
private readonly WorldSimulationHost _host;
public WorldSimulationHostTests()
{
_store = new WorldStore(
Options.Create(new WorldStorageOptions { RootDirectory = _root }),
NullLogger<WorldStore>.Instance);
_host = new WorldSimulationHost(_store, NullLogger<WorldSimulationHost>.Instance);
}
[Fact]
public async Task Attach_hydrates_legacy_worlds_without_catch_up_from_created_at()
{
var legacy = new WorldSummaryDto
{
Id = "legacy-11111111",
Name = "Legacy",
Latitude = 31.9,
Longitude = -100.5,
SizeMeters = 10_000,
Status = WorldStatus.Ready,
CreatedAt = DateTimeOffset.UtcNow - TimeSpan.FromDays(30),
};
await _store.SaveSummaryAsync(legacy);
// Mimic host startup hydration for worlds that lack a clock.
var seeded = legacy with
{
Clock = WorldSimulation.DefaultClock(),
LastTickedAt = DateTimeOffset.UtcNow,
};
await _store.SaveSummaryAsync(seeded);
_host.Attach(seeded with { LastTickedAt = null }); // Attach without prior tick → no catch-up
// Force attach path used for legacy: Create with catchUp false via AttachSeeded behaviour —
// Attach with LastTickedAt null means catchUp is false.
var clock = _host.TryGetClock(legacy.Id);
Assert.NotNull(clock);
Assert.Equal(GameTime.DefaultStart, clock.GameTime);
}
[Fact]
public async Task UpdateClock_changes_pause_and_Detach_stops_simulation()
{
var summary = new WorldSummaryDto
{
Id = "ready-22222222",
Name = "Ready",
Latitude = 31.9,
Longitude = -100.5,
SizeMeters = 10_000,
Status = WorldStatus.Ready,
CreatedAt = DateTimeOffset.UtcNow,
Clock = WorldSimulation.DefaultClock(),
LastTickedAt = DateTimeOffset.UtcNow,
};
await _store.SaveSummaryAsync(summary);
_host.Attach(summary);
var paused = _host.UpdateClock(summary.Id, new UpdateClockRequest { Paused = true });
Assert.True(paused.Paused);
var scaled = _host.UpdateClock(summary.Id, new UpdateClockRequest { TimeScale = 3 });
Assert.Equal(3, scaled.TimeScale);
Assert.True(scaled.Paused);
_host.Detach(summary.Id);
Assert.False(_host.IsAttached(summary.Id));
Assert.Null(_host.TryGetClock(summary.Id));
}
[Fact]
public void Overlay_strips_last_ticked_at_for_api()
{
var summary = new WorldSummaryDto
{
Id = "ready-33333333",
Name = "Ready",
Latitude = 31.9,
Longitude = -100.5,
SizeMeters = 10_000,
Status = WorldStatus.Ready,
CreatedAt = DateTimeOffset.UtcNow,
Clock = WorldSimulation.DefaultClock(),
LastTickedAt = DateTimeOffset.UtcNow,
};
_host.Attach(summary);
var overlaid = _host.Overlay(summary);
Assert.NotNull(overlaid.Clock);
Assert.Null(overlaid.LastTickedAt);
}
public void Dispose()
{
foreach (var id in new[] { "legacy-11111111", "ready-22222222", "ready-33333333" })
_host.Detach(id);
if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,105 @@
using TheLivingWorld.Api.Simulation;
using TheLivingWorld.Core.Contracts;
using TheLivingWorld.Core.Simulation;
namespace TheLivingWorld.Tests;
public sealed class WorldSimulationTests
{
[Fact]
public void Create_starts_at_default_morning_and_ticks_at_x1()
{
using var simulation = WorldSimulation.Create(ReadySummary(), catchUp: false);
var before = simulation.SnapshotClock();
Assert.Equal(GameTime.DefaultStart, before.GameTime);
Assert.Equal(1, before.TimeScale);
Assert.False(before.Paused);
simulation.Tick(TimeSpan.FromSeconds(2));
var after = simulation.SnapshotClock();
Assert.Equal(GameTime.DefaultStart.AddMinutes(10), after.GameTime);
Assert.True(simulation.IsDirty);
}
[Fact]
public void Tick_does_not_advance_while_paused()
{
var summary = ReadySummary() with
{
Clock = WorldSimulation.DefaultClock() with { Paused = true },
};
using var simulation = WorldSimulation.Create(summary, catchUp: false);
simulation.Tick(TimeSpan.FromSeconds(5));
Assert.Equal(GameTime.DefaultStart, simulation.SnapshotClock().GameTime);
Assert.False(simulation.IsDirty);
}
[Fact]
public void Update_bakes_elapsed_time_before_changing_scale()
{
using var simulation = WorldSimulation.Create(ReadySummary(), catchUp: false);
simulation.Tick(TimeSpan.FromSeconds(1));
var clock = simulation.Update(new UpdateClockRequest { TimeScale = 2 });
Assert.Equal(2, clock.TimeScale);
// Tick advanced 5 game minutes; Update may bake a few extra wall-clock milliseconds.
Assert.InRange(
clock.GameTime,
GameTime.DefaultStart.AddMinutes(5),
GameTime.DefaultStart.AddMinutes(5).AddSeconds(30));
Assert.True(simulation.IsDirty);
}
[Fact]
public void Update_rejects_invalid_time_scale()
{
using var simulation = WorldSimulation.Create(ReadySummary(), catchUp: false);
Assert.Throws<ArgumentOutOfRangeException>(() =>
simulation.Update(new UpdateClockRequest { TimeScale = 5 }));
}
[Fact]
public void Catch_up_advances_from_last_ticked_at()
{
var lastTickedAt = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(3);
var summary = ReadySummary() with { LastTickedAt = lastTickedAt };
using var simulation = WorldSimulation.Create(summary, catchUp: true);
// ~3 real seconds at x1 → ~15 game minutes (allow a little wall-clock drift).
var actual = simulation.SnapshotClock().GameTime;
Assert.InRange(
actual,
GameTime.DefaultStart.AddMinutes(14),
GameTime.DefaultStart.AddMinutes(17));
}
[Fact]
public void OverlayForApi_strips_last_ticked_at()
{
using var simulation = WorldSimulation.Create(ReadySummary(), catchUp: false);
var overlaid = simulation.OverlayForApi(ReadySummary());
Assert.NotNull(overlaid.Clock);
Assert.Null(overlaid.LastTickedAt);
}
private static WorldSummaryDto ReadySummary() => new()
{
Id = "town-aaaaaaaa",
Name = "Town",
Latitude = 31.9,
Longitude = -100.5,
SizeMeters = 10_000,
Status = WorldStatus.Ready,
CreatedAt = DateTimeOffset.UtcNow,
Clock = WorldSimulation.DefaultClock(),
LastTickedAt = DateTimeOffset.UtcNow,
};
}