From fad0411d52a0dc6fc7896429d5d800206a59ceb4 Mon Sep 17 00:00:00 2001 From: Marco De Maio Date: Thu, 26 Nov 2026 12:47:54 +0100 Subject: [PATCH] Add interactive doors to the raycaster demo --- README.rst | 8 +- src/RetroRaycaster.Core/GridMap.cs | 35 ++++++++- src/RetroRaycaster.Core/LevelLoader.cs | 26 ++++++- src/RetroRaycaster.Core/PlayerMovement.cs | 11 ++- src/RetroRaycaster.Desktop/DemoForm.cs | 3 +- src/RetroRaycaster.Desktop/Levels/demo.json | 2 +- tests/RetroRaycaster.Core.Tests/DoorTests.cs | 77 ++++++++++++++++++++ 7 files changed, 150 insertions(+), 12 deletions(-) create mode 100644 tests/RetroRaycaster.Core.Tests/DoorTests.cs diff --git a/README.rst b/README.rst index 06cfb10b..0663ac6a 100644 --- a/README.rst +++ b/README.rst @@ -8,12 +8,16 @@ Open ``RetroRaycaster.sln`` in Visual Studio 2022 with the .NET 8 desktop development workload. In Solution Explorer, right-click ``RetroRaycaster.Desktop``, choose **Set as Startup Project**, and press F5. 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. +arrow keys to turn, and Esc to close the demo. From the starting position, +press E to open the wooden door straight ahead. Walk through with W, clear +the threshold, turn around and press E again to close it. 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 +``.`` is empty, ``B`` is brick, ``M`` is metal and ``D`` is an initially +closed door. E toggles the first door in sight within 1.5 grid units. +An occupied doorway stays open. 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. diff --git a/src/RetroRaycaster.Core/GridMap.cs b/src/RetroRaycaster.Core/GridMap.cs index a3bc5160..74cc791f 100644 --- a/src/RetroRaycaster.Core/GridMap.cs +++ b/src/RetroRaycaster.Core/GridMap.cs @@ -12,10 +12,12 @@ public sealed class GridMap { private readonly int[,] materials; private readonly WallTexture[] textures = []; + // Door cells retain their material ID. A negative ID denotes an open door. + private readonly int doorMaterial; public int Width => materials.GetLength(1); public int Height => materials.GetLength(0); - internal bool IsSolid(int x, int y) => materials[y, x] != 0; + internal bool IsSolid(int x, int y) => materials[y, x] > 0; internal WallTexture? TextureAtWall(int x, int y) => textures.Length == 0 ? null : textures[materials[y, x] - 1]; @@ -33,13 +35,16 @@ public GridMap(bool[,] solidCells) } /// Zero denotes empty space. Positive IDs select textures starting at one. - public GridMap(int[,] materialIds, WallTexture[] textures) + public GridMap(int[,] materialIds, WallTexture[] textures) : this(materialIds, textures, 0) { } + + internal GridMap(int[,] materialIds, WallTexture[] textures, int doorMaterial) { ArgumentNullException.ThrowIfNull(materialIds); ArgumentNullException.ThrowIfNull(textures); if (materialIds.Length == 0) throw new ArgumentException("The grid must contain at least one cell.", nameof(materialIds)); materials = (int[,])materialIds.Clone(); + this.doorMaterial = doorMaterial; this.textures = (WallTexture[])textures.Clone(); foreach (var texture in this.textures) ArgumentNullException.ThrowIfNull(texture); @@ -54,7 +59,26 @@ public GridMap(int[,] materialIds, WallTexture[] textures) /// The origin belongs to cell (floor(x), floor(y)) and must be empty if inside. /// At a corner the ray enters only the diagonal cell and reports its vertical side. /// - public RayHit? CastRay(double originX, double originY, double directionX, double directionY) + public RayHit? CastRay(double originX, double originY, double directionX, double directionY) => + Trace(originX, originY, directionX, directionY, double.PositiveInfinity, includeOpenDoors: false); + + /// Toggles the first visible door within 1.5 grid units of the player. + public bool TryToggleDoor(PlayerState player) + { + if (doorMaterial == 0) return false; + var (dy, dx) = Math.SinCos(player.Angle); + var hit = Trace(player.X, player.Y, dx, dy, 1.5, includeOpenDoors: true); + if (hit is not RayHit cell) return false; + int id = materials[cell.CellY, cell.CellX]; + if (Math.Abs(id) != doorMaterial) return false; + if (id < 0 && PlayerMovement.OverlapsCell(player.X, player.Y, cell.CellX, cell.CellY)) + return false; + materials[cell.CellY, cell.CellX] = -id; + return true; + } + + private RayHit? Trace(double originX, double originY, double directionX, double directionY, + double maxDistance, bool includeOpenDoors) { if (!double.IsFinite(originX) || !double.IsFinite(originY) || !double.IsFinite(directionX) || !double.IsFinite(directionY)) @@ -68,6 +92,8 @@ public GridMap(int[,] materialIds, WallTexture[] textures) int y = (int)originY; if (IsSolid(x, y)) throw new ArgumentException("A moving ray must start in an empty cell."); + // The occupied doorway is the first door and cannot be closed. + if (includeOpenDoors && materials[y, x] < 0) return null; int stepX = Math.Sign(directionX); int stepY = Math.Sign(directionY); @@ -79,12 +105,13 @@ public GridMap(int[,] materialIds, WallTexture[] textures) bool crossX = stepX != 0 && (stepY == 0 || nextX <= nextY); bool crossY = stepY != 0 && (stepX == 0 || nextY <= nextX); double t = crossX ? nextX : nextY; + if (t > maxDistance) return null; if (crossX) x += stepX; if (crossY) y += stepY; if (x < 0 || x >= Width || y < 0 || y >= Height) return null; - if (IsSolid(x, y)) + if (IsSolid(x, y) || (includeOpenDoors && materials[y, x] < 0)) return new RayHit(x, y, crossX ? WallSide.Vertical : WallSide.Horizontal, t); // Compute from the original ray to avoid accumulating rounding at corners. diff --git a/src/RetroRaycaster.Core/LevelLoader.cs b/src/RetroRaycaster.Core/LevelLoader.cs index 7eb9ee55..b6c9321f 100644 --- a/src/RetroRaycaster.Core/LevelLoader.cs +++ b/src/RetroRaycaster.Core/LevelLoader.cs @@ -43,14 +43,38 @@ public static (GridMap Map, PlayerState Spawn) Load(Stream stream, WallTexture b '.' => 0, 'B' => 1, 'M' => 2, + 'D' => DoorMaterial, var symbol => throw new JsonException($"Unknown symbol '{symbol}' at row {y + 1}, column {x + 1}.") }; - var map = new GridMap(cells, [brick, metal]); + var map = new GridMap(cells, [brick, metal, DoorTexture], DoorMaterial); 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))); } + + private const int DoorMaterial = 3; + private static readonly WallTexture DoorTexture = CreateDoorTexture(); + + private static WallTexture CreateDoorTexture() + { + var pixels = new uint[32, 32]; + for (int y = 0; y < 32; y++) + for (int x = 0; x < 32; x++) + { + // A timber door with a dark frame, cross braces and a brass latch. + pixels[y, x] = (x, y) switch + { + (< 2 or >= 30, _) or (_, < 2 or >= 30) => 0xFF41352D, + (>= 23 and <= 27, >= 15 and <= 17) => 0xFFFFCC52, + (_, 6 or 7 or 24 or 25) => 0xFF564337, + _ when x % 6 == 2 => 0xFF774827, + _ when (x / 6) % 2 == 0 => 0xFFC28345, + _ => 0xFFAD703D + }; + } + return new WallTexture(pixels); + } } diff --git a/src/RetroRaycaster.Core/PlayerMovement.cs b/src/RetroRaycaster.Core/PlayerMovement.cs index 393a0603..0162d44d 100644 --- a/src/RetroRaycaster.Core/PlayerMovement.cs +++ b/src/RetroRaycaster.Core/PlayerMovement.cs @@ -59,15 +59,20 @@ internal static bool CanStandAt(GridMap map, double x, double y) 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) + if (map.IsSolid(col, row) && OverlapsCell(x, y, col, row)) return false; } return true; } + internal static bool OverlapsCell(double x, double y, int col, int row) + { + if (y <= row - Radius || y >= row + 1 + Radius) return false; + double reach = ReachAtRow(y, row); + return x > col - reach && x < col + 1 + reach; + } + // At a corner only this cross-section of the circle reaches the wall. private static double ReachAtRow(double across, int row) { diff --git a/src/RetroRaycaster.Desktop/DemoForm.cs b/src/RetroRaycaster.Desktop/DemoForm.cs index 12a47bce..ee84a935 100644 --- a/src/RetroRaycaster.Desktop/DemoForm.cs +++ b/src/RetroRaycaster.Desktop/DemoForm.cs @@ -40,7 +40,8 @@ public DemoForm(GridMap map, PlayerState spawn) KeyDown += (_, e) => { if (e.KeyCode == Keys.Escape) Close(); - else pressed.Add(e.KeyCode); + else if (pressed.Add(e.KeyCode) && e.KeyCode == Keys.E) + map.TryToggleDoor(player); }; KeyUp += (_, e) => pressed.Remove(e.KeyCode); Deactivate += (_, _) => pressed.Clear(); diff --git a/src/RetroRaycaster.Desktop/Levels/demo.json b/src/RetroRaycaster.Desktop/Levels/demo.json index d976d153..167e728f 100644 --- a/src/RetroRaycaster.Desktop/Levels/demo.json +++ b/src/RetroRaycaster.Desktop/Levels/demo.json @@ -3,7 +3,7 @@ "BBBBBBBBBBBBBBB", "B.............B", "B.....MM......B", - "B.....MM......B", + "B...D.MM......B", "B.........BBB.B", "BBBBBBBBBBB.B.B", "B...........B.B", diff --git a/tests/RetroRaycaster.Core.Tests/DoorTests.cs b/tests/RetroRaycaster.Core.Tests/DoorTests.cs new file mode 100644 index 00000000..51cf5d74 --- /dev/null +++ b/tests/RetroRaycaster.Core.Tests/DoorTests.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using System.Text.Json; +using Xunit; + +namespace RetroRaycaster.Core.Tests; + +public class DoorTests +{ + private static readonly WallTexture Wall = new(new uint[,] { { 0xFF808080 } }); + private static readonly MovementInput Forward = new(1, 0, 0); + + private static (GridMap Map, PlayerState Spawn) Load(params string[] rows) + { + var json = JsonSerializer.SerializeToUtf8Bytes(new { rows, spawn = new { x = 0.5, y = 0.5, angleDegrees = 0 } }); + using var stream = new MemoryStream(json); + return LevelLoader.Load(stream, Wall, Wall); + } + + [Fact] + public void DoorBlocksUntilOpenedAndCanBeClosedFromOtherSide() + { + var (map, spawn) = Load("..D..B"); + Assert.Equal(2, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX); + var blocked = PlayerMovement.Update(map, spawn, Forward, 1); + Assert.Equal(2 - PlayerMovement.Radius, blocked.X, 10); + + Assert.True(map.TryToggleDoor(spawn)); // Exactly 1.5 units to the near face. + Assert.Equal(5, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX); + var across = PlayerMovement.Update(map, spawn, Forward, 1) with { Angle = Math.PI }; + Assert.Equal(3.5, across.X, 10); + + Assert.True(map.TryToggleDoor(across)); + Assert.Equal(2, map.CastRay(across.X, across.Y, -1, 0)?.CellX); + Assert.Equal(3 + PlayerMovement.Radius, PlayerMovement.Update(map, across, Forward, 1).X, 10); + } + + [Theory] + [InlineData("...D.")] // Beyond reach. + [InlineData(".BD.")] // A brick wall hides a door within reach. + public void UnreachableDoorRemainsClosed(string row) + { + var (map, spawn) = Load(row); + Assert.False(map.TryToggleDoor(spawn)); + Assert.Equal(row.IndexOf('D'), map.CastRay(row.Length - 0.5, 0.5, -1, 0)?.CellX); + } + + [Fact] + public void RangeIsMeasuredAlongTheViewRay() + { + var (map, spawn) = Load("....", "..D."); + Assert.False(map.TryToggleDoor(spawn with { Angle = Math.PI / 6 })); + Assert.Equal(2, map.CastRay(spawn.X, spawn.Y, Math.Cos(Math.PI / 6), 0.5)?.CellX); + } + + [Theory] + [InlineData(1.5, 1.5, 0)] // Center in the doorway. + [InlineData(0.9, 1.5, 0)] // Circle straddles the near face. + [InlineData(0.9, 0.9, 45)] // Circle overlaps only a corner. + public void OccupiedDoorCannotClose(double x, double y, double degrees) + { + var (map, _) = Load("...", ".D."); + Assert.True(map.TryToggleDoor(new PlayerState(0.5, 1.5, 0))); + Assert.False(map.TryToggleDoor(new PlayerState(x, y, degrees * Math.PI / 180))); + Assert.Null(map.CastRay(0.5, 1.5, 1, 0)); + } + + [Fact] + public void OpenDoorTakesPrecedenceOverClosedDoorBehindIt() + { + var (map, spawn) = Load(".DD."); + Assert.True(map.TryToggleDoor(spawn)); + Assert.Equal(2, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX); + Assert.True(map.TryToggleDoor(spawn)); + Assert.Equal(1, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX); + } +}