From 1b6401ca0a6cee8b27a0410e33f04e7e5c1d722f Mon Sep 17 00:00:00 2001 From: Marco De Maio Date: Thu, 26 Nov 2026 10:25:27 +0100 Subject: [PATCH] Load the desktop demo level and spawn from JSON --- README.rst | 7 ++ src/RetroRaycaster.Core/LevelLoader.cs | 56 +++++++++++++ src/RetroRaycaster.Core/PlayerMovement.cs | 28 ++++++- src/RetroRaycaster.Desktop/DemoForm.cs | 29 ++----- src/RetroRaycaster.Desktop/Levels/demo.json | 14 ++++ src/RetroRaycaster.Desktop/Program.cs | 18 ++++- .../RetroRaycaster.Desktop.csproj | 1 + .../LevelLoaderTests.cs | 79 +++++++++++++++++++ 8 files changed, 204 insertions(+), 28 deletions(-) create mode 100644 src/RetroRaycaster.Core/LevelLoader.cs create mode 100644 src/RetroRaycaster.Desktop/Levels/demo.json create mode 100644 tests/RetroRaycaster.Core.Tests/LevelLoaderTests.cs diff --git a/README.rst b/README.rst index 0df4ee7f..06cfb10b 100644 --- a/README.rst +++ b/README.rst @@ -10,6 +10,13 @@ development workload. In Solution Explorer, right-click Use W/S to move forward and backward, A/D to strafe, the left and right arrow keys to turn, and Esc to close the demo. +Edit ``src/RetroRaycaster.Desktop/Levels/demo.json`` to change the level. +Build and publish copy it to ``Levels/demo.json`` beside the executable. +The ``rows`` array lists equal-length strings from top to bottom: +``.`` is empty, ``B`` is brick, and ``M`` is metal. The ``spawn`` object +sets ``x`` and ``y`` in grid units (right and down) and ``angleDegrees`` +clockwise from east. The player's circle must fit in free space. + Original source release ----------------------- diff --git a/src/RetroRaycaster.Core/LevelLoader.cs b/src/RetroRaycaster.Core/LevelLoader.cs new file mode 100644 index 00000000..7eb9ee55 --- /dev/null +++ b/src/RetroRaycaster.Core/LevelLoader.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RetroRaycaster.Core; + +public static class LevelLoader +{ + private sealed class LevelData + { + [JsonPropertyName("rows")] public required string?[]? Rows { get; init; } + [JsonPropertyName("spawn")] public required SpawnData? Spawn { get; init; } + } + + private sealed class SpawnData + { + [JsonPropertyName("x")] public required double X { get; init; } + [JsonPropertyName("y")] public required double Y { get; init; } + [JsonPropertyName("angleDegrees")] public required double AngleDegrees { get; init; } + } + + public static (GridMap Map, PlayerState Spawn) Load(Stream stream, WallTexture brick, WallTexture metal) + { + var level = JsonSerializer.Deserialize(stream); + if (level?.Rows is not { Length: > 0 } rows) + throw new JsonException("Expected a non-empty rows array."); + var spawn = level.Spawn ?? throw new JsonException("Expected a spawn object."); + int width = rows[0]?.Length ?? 0; + for (int y = 0; y < rows.Length; y++) + { + if (string.IsNullOrEmpty(rows[y])) + throw new JsonException($"Row {y + 1} must be a non-empty string."); + if (rows[y]!.Length != width) + throw new JsonException($"Row {y + 1} must contain {width} cells."); + } + + var cells = new int[rows.Length, width]; + for (int y = 0; y < rows.Length; y++) + for (int x = 0; x < width; x++) + cells[y, x] = rows[y]![x] switch + { + '.' => 0, + 'B' => 1, + 'M' => 2, + var symbol => throw new JsonException($"Unknown symbol '{symbol}' at row {y + 1}, column {x + 1}.") + }; + + var map = new GridMap(cells, [brick, metal]); + if (!PlayerMovement.CanStandAt(map, spawn.X, spawn.Y)) + throw new JsonException("The spawn circle must fit inside the map without overlapping a wall."); + if (!double.IsFinite(spawn.AngleDegrees)) + throw new JsonException("spawn.angleDegrees must be finite."); + return (map, new PlayerState(spawn.X, spawn.Y, spawn.AngleDegrees * (Math.PI / 180))); + } +} diff --git a/src/RetroRaycaster.Core/PlayerMovement.cs b/src/RetroRaycaster.Core/PlayerMovement.cs index e25bc543..393a0603 100644 --- a/src/RetroRaycaster.Core/PlayerMovement.cs +++ b/src/RetroRaycaster.Core/PlayerMovement.cs @@ -51,6 +51,30 @@ public static PlayerState Update(GridMap map, PlayerState player, MovementInput private static bool ValidAxis(double value) => value is >= -1 and <= 1; + internal static bool CanStandAt(GridMap map, double x, double y) + { + if (!double.IsFinite(x) || !double.IsFinite(y) || + x < Radius || x > map.Width - Radius || y < Radius || y > map.Height - Radius) + return false; + + for (int row = (int)(y - Radius); row <= Math.Min(map.Height - 1, (int)(y + Radius)); row++) + { + if (y <= row - Radius || y >= row + 1 + Radius) continue; + double reach = ReachAtRow(y, row); + for (int col = (int)(x - Radius); col <= Math.Min(map.Width - 1, (int)(x + Radius)); col++) + if (map.IsSolid(col, row) && x > col - reach && x < col + 1 + reach) + return false; + } + return true; + } + + // At a corner only this cross-section of the circle reaches the wall. + private static double ReachAtRow(double across, int row) + { + double gap = Math.Max(0, Math.Max(row - across, across - (row + 1))); + return Math.Sqrt(Math.Max(0, Radius * Radius - gap * gap)); + } + private static double MoveAxis(GridMap map, double position, double across, double delta, bool horizontal) { if (delta == 0) return position; @@ -64,9 +88,7 @@ private static double MoveAxis(GridMap map, double position, double across, doub for (int row = firstRow; row <= lastRow; row++) { if (across <= row - Radius || across >= row + 1 + Radius) continue; - double gap = Math.Max(0, Math.Max(row - across, across - (row + 1))); - // At a corner only this cross-section of the circle reaches the wall. - double reach = Math.Sqrt(Math.Max(0, Radius * Radius - gap * gap)); + double reach = ReachAtRow(across, row); for (int cell = first; cell <= last; cell++) { if (!(horizontal ? map.IsSolid(cell, row) : map.IsSolid(row, cell))) continue; diff --git a/src/RetroRaycaster.Desktop/DemoForm.cs b/src/RetroRaycaster.Desktop/DemoForm.cs index 14a8a208..12a47bce 100644 --- a/src/RetroRaycaster.Desktop/DemoForm.cs +++ b/src/RetroRaycaster.Desktop/DemoForm.cs @@ -15,8 +15,8 @@ internal sealed class DemoForm : Form private const int FrameWidth = 320; private const int FrameHeight = 200; private const double HorizontalFov = 70 * Math.PI / 180; - private readonly GridMap map = CreateMap(); - private PlayerState player = new(2.5, 3.5, 0); + private readonly GridMap map; + private PlayerState player; private readonly HashSet pressed = new(); private readonly Timer timer = new() { Interval = 16 }; private readonly Stopwatch clock = new(); @@ -25,8 +25,10 @@ internal sealed class DemoForm : Form private readonly uint[] pixels = GC.AllocateArray(FrameWidth * FrameHeight, pinned: true); private readonly Bitmap frame; - public DemoForm() + public DemoForm(GridMap map, PlayerState spawn) { + this.map = map; + player = spawn; frame = new Bitmap(FrameWidth, FrameHeight, FrameWidth * sizeof(uint), PixelFormat.Format32bppArgb, Marshal.UnsafeAddrOfPinnedArrayElement(pixels, 0)); Text = "RetroRaycaster"; @@ -96,25 +98,4 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } - - private static GridMap CreateMap() - { - string[] rows = - [ - "###############", - "#.............#", - "#.....MM......#", - "#.....MM......#", - "#.........###.#", - "###########.#.#", - "#...........#.#", - "#.............#", - "###############" - ]; - var walls = new int[rows.Length, rows[0].Length]; - for (int y = 0; y < rows.Length; y++) - for (int x = 0; x < rows[y].Length; x++) - walls[y, x] = rows[y][x] switch { '#' => 1, 'M' => 2, _ => 0 }; - return new GridMap(walls, [DemoTextures.Brick, DemoTextures.Metal]); - } } diff --git a/src/RetroRaycaster.Desktop/Levels/demo.json b/src/RetroRaycaster.Desktop/Levels/demo.json new file mode 100644 index 00000000..d976d153 --- /dev/null +++ b/src/RetroRaycaster.Desktop/Levels/demo.json @@ -0,0 +1,14 @@ +{ + "rows": [ + "BBBBBBBBBBBBBBB", + "B.............B", + "B.....MM......B", + "B.....MM......B", + "B.........BBB.B", + "BBBBBBBBBBB.B.B", + "B...........B.B", + "B.............B", + "BBBBBBBBBBBBBBB" + ], + "spawn": { "x": 2.5, "y": 3.5, "angleDegrees": 0 } +} diff --git a/src/RetroRaycaster.Desktop/Program.cs b/src/RetroRaycaster.Desktop/Program.cs index 8c09d586..aaa02e11 100644 --- a/src/RetroRaycaster.Desktop/Program.cs +++ b/src/RetroRaycaster.Desktop/Program.cs @@ -1,5 +1,8 @@ using System; +using System.IO; +using System.Text.Json; using System.Windows.Forms; +using RetroRaycaster.Core; namespace RetroRaycaster.Desktop; @@ -9,6 +12,19 @@ internal static class Program private static void Main() { ApplicationConfiguration.Initialize(); - Application.Run(new DemoForm()); + string path = Path.Combine(AppContext.BaseDirectory, "Levels", "demo.json"); + (GridMap Map, PlayerState Spawn) level; + try + { + using var file = File.OpenRead(path); + level = LevelLoader.Load(file, DemoTextures.Brick, DemoTextures.Metal); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + MessageBox.Show($"Could not load the level from {path}\n\n{ex.Message}", + "RetroRaycaster", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + Application.Run(new DemoForm(level.Map, level.Spawn)); } } diff --git a/src/RetroRaycaster.Desktop/RetroRaycaster.Desktop.csproj b/src/RetroRaycaster.Desktop/RetroRaycaster.Desktop.csproj index b47a6bf0..9c0e37ec 100644 --- a/src/RetroRaycaster.Desktop/RetroRaycaster.Desktop.csproj +++ b/src/RetroRaycaster.Desktop/RetroRaycaster.Desktop.csproj @@ -7,6 +7,7 @@ enable + diff --git a/tests/RetroRaycaster.Core.Tests/LevelLoaderTests.cs b/tests/RetroRaycaster.Core.Tests/LevelLoaderTests.cs new file mode 100644 index 00000000..229a0bd8 --- /dev/null +++ b/tests/RetroRaycaster.Core.Tests/LevelLoaderTests.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using System.Text; +using System.Text.Json; +using Xunit; + +namespace RetroRaycaster.Core.Tests; + +public class LevelLoaderTests +{ + private const uint Brick = 0xFFCC4422, Metal = 0xFF667788; + private const string Spawn = """{"x":0.5,"y":0.5,"angleDegrees":0}"""; + + private static (GridMap Map, PlayerState Spawn) Load(string json) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); + return LevelLoader.Load(stream, new WallTexture(new uint[,] { { Brick } }), + new WallTexture(new uint[,] { { Metal } })); + } + + [Fact] + public void LoadsRectangularMapWithBothTexturesAndConvertsHeading() + { + var (map, spawn) = Load("""{"rows":["..B","..M"],"spawn":{"x":1.5,"y":0.5,"angleDegrees":90}}"""); + Assert.Equal((3, 2), (map.Width, map.Height)); + Assert.Equal(new PlayerState(1.5, 0.5, Math.PI / 2), spawn); + var pixels = new uint[1]; + for (int row = 0; row < 2; row++) + { + SoftwareRenderer.Render(map, spawn.X, row + 0.5, 0, Math.PI / 2, 1, 1, pixels); + Assert.Equal(row == 0 ? Brick : Metal, pixels[0]); + } + } + + [Theory] + [InlineData("[]", "rows")] + [InlineData("""[""]""", "Row 1")] + [InlineData("""[".",null]""", "Row 2")] + [InlineData("""["..","."]""", "Row 2")] + [InlineData("""["..",".?"]""", "'?' at row 2, column 2")] + public void ReportsInvalidRows(string rows, string reason) + { + var error = Assert.Throws(() => Load($$"""{"rows":{{rows}},"spawn":{{Spawn}}}""")); + Assert.Contains(reason, error.Message); + } + + [Theory] + [InlineData("""{"rows":["."]}""", "spawn")] + [InlineData("""{"spawn":{}}""", "x")] + [InlineData("""{"spawn":{"x":0,"y":0,"angleDegrees":0}}""", "rows")] + [InlineData("""{"rows":["."],"spawn":{"x":0.5,"angleDegrees":0}}""", "y")] + [InlineData("""{"rows":["."],"spawn":{"x":0.5,"y":0.5}}""", "angleDegrees")] + [InlineData("""{"rows":["."],"spawn":{"x":0.5,"y":0.5,"angleDegrees":1e999}}""", "angleDegrees")] + public void ReportsMissingOrInvalidField(string json, string field) + { + Assert.Contains(field, Assert.Throws(() => Load(json)).Message); + } + + [Theory] + [InlineData(0.1, 0.5)] // Circle crosses the outer boundary. + [InlineData(1.5, 1.5)] // Center in the wall. + [InlineData(0.9, 1.5)] // Center in free space, overlap at a face. + [InlineData(0.9, 0.9)] // Only the corner intersects the circle. + public void RejectsSpawnOverlaps(double x, double y) + { + Assert.Throws(() => Load(CornerLevel(x, y))); + } + + [Theory] + [InlineData(0.85, 0.85)] // Bounding box overlaps the wall, but the circle clears it. + [InlineData(0.8, 1.5)] // Touching the wall is valid. + public void AcceptsSpawnClearOfWall(double x, double y) + { + Assert.Equal(new PlayerState(x, y, 0), Load(CornerLevel(x, y)).Spawn); + } + + private static string CornerLevel(double x, double y) => + JsonSerializer.Serialize(new { rows = new[] { "..", ".M" }, spawn = new { x, y, angleDegrees = 0 } }); +}