From 42fe25090874382ebd2e3a80faffd9208defc8d7 Mon Sep 17 00:00:00 2001 From: Marco De Maio Date: Fri, 27 Nov 2026 10:30:35 +0100 Subject: [PATCH] Render floor-standing world sprites with per-column wall depth --- README.rst | 4 + src/RetroRaycaster.Core/GridMap.cs | 5 +- src/RetroRaycaster.Core/LevelLoader.cs | 23 ++- src/RetroRaycaster.Core/SoftwareRenderer.cs | 74 ++++++++++ src/RetroRaycaster.Core/WorldSprite.cs | 25 ++++ src/RetroRaycaster.Desktop/DemoForm.cs | 3 +- src/RetroRaycaster.Desktop/Levels/demo.json | 5 +- .../WorldSpriteTests.cs | 132 ++++++++++++++++++ 8 files changed, 267 insertions(+), 4 deletions(-) create mode 100644 src/RetroRaycaster.Core/WorldSprite.cs create mode 100644 tests/RetroRaycaster.Core.Tests/WorldSpriteTests.cs diff --git a/README.rst b/README.rst index 0663ac6a..67643ad3 100644 --- a/README.rst +++ b/README.rst @@ -21,6 +21,10 @@ 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. +The optional ``objects`` array places decorations in floor cells using world +coordinates. You can walk through them. The demo places a signal lamp just +beyond the door with ``"objects": [{"type": "signalLamp", "x": 5.5, "y": 3.5}]``. + Original source release ----------------------- diff --git a/src/RetroRaycaster.Core/GridMap.cs b/src/RetroRaycaster.Core/GridMap.cs index 74cc791f..95a29c79 100644 --- a/src/RetroRaycaster.Core/GridMap.cs +++ b/src/RetroRaycaster.Core/GridMap.cs @@ -14,6 +14,8 @@ public sealed class GridMap private readonly WallTexture[] textures = []; // Door cells retain their material ID. A negative ID denotes an open door. private readonly int doorMaterial; + private readonly WorldSprite[] objects = []; + public ReadOnlySpan Objects => objects; public int Width => materials.GetLength(1); public int Height => materials.GetLength(0); @@ -37,7 +39,7 @@ public GridMap(bool[,] solidCells) /// Zero denotes empty space. Positive IDs select textures starting at one. public GridMap(int[,] materialIds, WallTexture[] textures) : this(materialIds, textures, 0) { } - internal GridMap(int[,] materialIds, WallTexture[] textures, int doorMaterial) + internal GridMap(int[,] materialIds, WallTexture[] textures, int doorMaterial, WorldSprite[]? objects = null) { ArgumentNullException.ThrowIfNull(materialIds); ArgumentNullException.ThrowIfNull(textures); @@ -45,6 +47,7 @@ internal GridMap(int[,] materialIds, WallTexture[] textures, int doorMaterial) throw new ArgumentException("The grid must contain at least one cell.", nameof(materialIds)); materials = (int[,])materialIds.Clone(); this.doorMaterial = doorMaterial; + this.objects = objects ?? []; this.textures = (WallTexture[])textures.Clone(); foreach (var texture in this.textures) ArgumentNullException.ThrowIfNull(texture); diff --git a/src/RetroRaycaster.Core/LevelLoader.cs b/src/RetroRaycaster.Core/LevelLoader.cs index b6c9321f..97d87851 100644 --- a/src/RetroRaycaster.Core/LevelLoader.cs +++ b/src/RetroRaycaster.Core/LevelLoader.cs @@ -11,6 +11,14 @@ private sealed class LevelData { [JsonPropertyName("rows")] public required string?[]? Rows { get; init; } [JsonPropertyName("spawn")] public required SpawnData? Spawn { get; init; } + [JsonPropertyName("objects")] public ObjectData?[]? Objects { get; init; } = []; + } + + private sealed class ObjectData + { + [JsonPropertyName("type")] public required string Type { get; init; } + [JsonPropertyName("x")] public required double X { get; init; } + [JsonPropertyName("y")] public required double Y { get; init; } } private sealed class SpawnData @@ -47,7 +55,20 @@ public static (GridMap Map, PlayerState Spawn) Load(Stream stream, WallTexture b var symbol => throw new JsonException($"Unknown symbol '{symbol}' at row {y + 1}, column {x + 1}.") }; - var map = new GridMap(cells, [brick, metal, DoorTexture], DoorMaterial); + var entries = level.Objects ?? throw new JsonException("Expected an objects array."); + var objects = new WorldSprite[entries.Length]; + for (int i = 0; i < entries.Length; i++) + { + var entry = entries[i] ?? throw new JsonException($"Expected an object at objects[{i}]."); + if (entry.Type != "signalLamp") + throw new JsonException($"Unknown type '{entry.Type}' at objects[{i}]."); + if (!double.IsFinite(entry.X) || !double.IsFinite(entry.Y) || + entry.X < 0 || entry.X >= width || entry.Y < 0 || entry.Y >= rows.Length || + cells[(int)entry.Y, (int)entry.X] != 0) + throw new JsonException($"objects[{i}] must have finite coordinates in a floor cell."); + objects[i] = WorldSprite.SignalLamp(entry.X, entry.Y); + } + var map = new GridMap(cells, [brick, metal, DoorTexture], DoorMaterial, objects); 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)) diff --git a/src/RetroRaycaster.Core/SoftwareRenderer.cs b/src/RetroRaycaster.Core/SoftwareRenderer.cs index 7ae1ef31..5cfabde9 100644 --- a/src/RetroRaycaster.Core/SoftwareRenderer.cs +++ b/src/RetroRaycaster.Core/SoftwareRenderer.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; namespace RetroRaycaster.Core; @@ -19,6 +20,21 @@ public static class SoftwareRenderer /// Rows run top to bottom, with pixel (x, y) at y * width + x. public static void Render(GridMap map, double cameraX, double cameraY, double angle, double horizontalFov, int width, int height, Span pixels) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + var depths = ArrayPool.Shared.Rent(width); + try + { + Render(map, cameraX, cameraY, angle, horizontalFov, width, height, pixels, depths); + } + finally + { + ArrayPool.Shared.Return(depths); + } + } + + public static void Render(GridMap map, double cameraX, double cameraY, double angle, + double horizontalFov, int width, int height, Span pixels, Span wallDepths) { ArgumentNullException.ThrowIfNull(map); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); @@ -29,6 +45,8 @@ public static void Render(GridMap map, double cameraX, double cameraY, double an throw new ArgumentOutOfRangeException(nameof(angle)); if ((long)width * height > pixels.Length) throw new ArgumentException("The buffer must hold the entire frame.", nameof(pixels)); + if (wallDepths.Length < width) + throw new ArgumentException("The depth buffer must hold one value per column.", nameof(wallDepths)); int floorStart = (height / 2) * width; pixels[..floorStart].Fill(SkyColor); @@ -47,6 +65,7 @@ public static void Render(GridMap map, double cameraX, double cameraY, double an double rayX = forwardX + offset * planeX; double rayY = forwardY + offset * planeY; var hit = map.CastRay(cameraX, cameraY, rayX, rayY); + wallDepths[x] = hit?.T ?? double.PositiveInfinity; if (hit is not RayHit wall) continue; @@ -82,5 +101,60 @@ public static void Render(GridMap map, double cameraX, double cameraY, double an pixels[y * width + x] = vertical ? color : (color & 0xFF000000u) | ((color & 0x00FEFEFEu) >> 1); } } + + if (!map.Objects.IsEmpty) + DrawSprites(map.Objects, cameraX, cameraY, forwardX, forwardY, focalLength, + width, height, pixels, wallDepths); + } + + private static void DrawSprites(ReadOnlySpan objects, double cameraX, double cameraY, + double forwardX, double forwardY, double focalLength, int width, int height, + Span pixels, ReadOnlySpan wallDepths) + { + var pool = ArrayPool<(double Depth, int Index)>.Shared; + var order = pool.Rent(objects.Length); + try + { + int count = 0; + for (int i = 0; i < objects.Length; i++) + { + double depth = (objects[i].X - cameraX) * forwardX + (objects[i].Y - cameraY) * forwardY; + // Cull at the camera plane before dividing, including a coincident lamp. + if (depth > 1e-8) order[count++] = (depth, i); + } + order.AsSpan(0, count).Sort(); + for (int i = count - 1; i >= 0; i--) + { + var (depth, index) = order[i]; + var sprite = objects[index]; + double right = (sprite.Y - cameraY) * forwardX - (sprite.X - cameraX) * forwardY; + double scale = focalLength / depth; + double spriteHeight = sprite.Height * scale; + double spriteWidth = spriteHeight * sprite.Texture.Width / sprite.Texture.Height; + double left = width * 0.5 + right * scale - spriteWidth * 0.5; + double top = height * 0.5 + (0.5 - sprite.Height) * scale; + int endX = ClipEdge(left + spriteWidth, width); + int startY = ClipEdge(top, height); + int endY = ClipEdge(top + spriteHeight, height); + for (int x = ClipEdge(left, width); x < endX; x++) + { + if (depth >= wallDepths[x]) continue; + int u = Math.Clamp((int)((x + 0.5 - left) / spriteWidth * sprite.Texture.Width), 0, sprite.Texture.Width - 1); + for (int y = startY; y < endY; y++) + { + int v = Math.Clamp((int)((y + 0.5 - top) / spriteHeight * sprite.Texture.Height), 0, sprite.Texture.Height - 1); + uint color = sprite.Texture[v, u]; + if ((color >> 24) != 0) pixels[y * width + x] = color; + } + } + } + } + finally + { + pool.Return(order); + } } + + private static int ClipEdge(double edge, int limit) => + (int)Math.Clamp(Math.Ceiling(edge - 0.5), 0, limit); } diff --git a/src/RetroRaycaster.Core/WorldSprite.cs b/src/RetroRaycaster.Core/WorldSprite.cs new file mode 100644 index 00000000..4e25fd43 --- /dev/null +++ b/src/RetroRaycaster.Core/WorldSprite.cs @@ -0,0 +1,25 @@ +namespace RetroRaycaster.Core; + +public readonly record struct WorldSprite(double X, double Y, double Height, WallTexture Texture) +{ + private static readonly WallTexture LampTexture = CreateLampTexture(); + + internal static WorldSprite SignalLamp(double x, double y) => new(x, y, 0.75, LampTexture); + + private static WallTexture CreateLampTexture() + { + var pixels = new uint[24, 16]; + for (int y = 0; y < 24; y++) + for (int x = 0; x < 16; x++) + pixels[y, x] = (x, y) switch + { + (>= 2 and <= 13, >= 21) => 0xFF394752, + (>= 4 and <= 11, 20) or (>= 6 and <= 9, >= 11 and < 20) => 0xFF7896A0, + (>= 3 and <= 12, 2 or 10) or (>= 5 and <= 10, 1) => 0xFF304854, + (>= 5 and <= 7, >= 4 and <= 6) => 0xFFCAFFF2, + (>= 4 and <= 11, >= 3 and <= 9) => 0xFF22DBB0, + _ => 0 + }; + return new WallTexture(pixels); + } +} diff --git a/src/RetroRaycaster.Desktop/DemoForm.cs b/src/RetroRaycaster.Desktop/DemoForm.cs index ee84a935..6affd498 100644 --- a/src/RetroRaycaster.Desktop/DemoForm.cs +++ b/src/RetroRaycaster.Desktop/DemoForm.cs @@ -24,6 +24,7 @@ internal sealed class DemoForm : Form // GDI+ reads the Core's packed ARGB pixels directly from this stable address. private readonly uint[] pixels = GC.AllocateArray(FrameWidth * FrameHeight, pinned: true); private readonly Bitmap frame; + private readonly double[] wallDepths = new double[FrameWidth]; public DemoForm(GridMap map, PlayerState spawn) { @@ -71,7 +72,7 @@ private int Axis(Keys positive, Keys negative) => private void RenderFrame() { SoftwareRenderer.Render(map, player.X, player.Y, player.Angle, HorizontalFov, - FrameWidth, FrameHeight, pixels); + FrameWidth, FrameHeight, pixels, wallDepths); Invalidate(); } diff --git a/src/RetroRaycaster.Desktop/Levels/demo.json b/src/RetroRaycaster.Desktop/Levels/demo.json index 167e728f..07c6641d 100644 --- a/src/RetroRaycaster.Desktop/Levels/demo.json +++ b/src/RetroRaycaster.Desktop/Levels/demo.json @@ -10,5 +10,8 @@ "B.............B", "BBBBBBBBBBBBBBB" ], - "spawn": { "x": 2.5, "y": 3.5, "angleDegrees": 0 } + "spawn": { "x": 2.5, "y": 3.5, "angleDegrees": 0 }, + "objects": [ + { "type": "signalLamp", "x": 5.5, "y": 3.5 } + ] } diff --git a/tests/RetroRaycaster.Core.Tests/WorldSpriteTests.cs b/tests/RetroRaycaster.Core.Tests/WorldSpriteTests.cs new file mode 100644 index 00000000..5b3fa84d --- /dev/null +++ b/tests/RetroRaycaster.Core.Tests/WorldSpriteTests.cs @@ -0,0 +1,132 @@ +using System; +using System.IO; +using System.Linq; +using System.Text.Json; +using Xunit; + +namespace RetroRaycaster.Core.Tests; + +public class WorldSpriteTests +{ + private const int Width = 128, Height = 96; + private const uint Brick = 0xFF993311; + private static readonly WallTexture Wall = new(new uint[,] { { Brick } }); + private static readonly string[] Room = ["....B", "....B", "....B", "....B"]; + + private static GridMap Load(string[] rows, params (double X, double Y)[] lamps) + { + var objects = lamps.Select(p => new { type = "signalLamp", x = p.X, y = p.Y }); + var json = JsonSerializer.SerializeToUtf8Bytes(new { rows, objects, spawn = new { x = 0.5, y = 1.5, angleDegrees = 0 } }); + using var stream = new MemoryStream(json); + return LevelLoader.Load(stream, Wall, Wall).Map; + } + + private static uint[] Frame(GridMap map, double cameraX = 0.5) + { + var pixels = new uint[Width * Height]; + SoftwareRenderer.Render(map, cameraX, 1.5, 0, Math.PI / 2, Width, Height, pixels); + return pixels; + } + + [Fact] + public void LegacyLevelHasNoObjects() + { + using var stream = new MemoryStream("""{"rows":["."],"spawn":{"x":0.5,"y":0.5,"angleDegrees":0}}"""u8.ToArray()); + Assert.True(LevelLoader.Load(stream, Wall, Wall).Map.Objects.IsEmpty); + } + + [Theory] + [InlineData("other", "1", "1")] + [InlineData("signalLamp", "1e999", "1")] + [InlineData("signalLamp", "1", "-0.1")] + [InlineData("signalLamp", "2", "0")] + [InlineData("signalLamp", "1", "0")] + [InlineData("signalLamp", "1", "1")] + public void RejectsUnknownTypeOrInvalidFloorPosition(string type, string x, string y) + { + var json = $$""" + {"rows":[".B",".D"],"spawn":{"x":0.5,"y":0.5,"angleDegrees":0}, + "objects":[{"type":"{{type}}","x":{{x}},"y":{{y}}}]} + """; + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); + Assert.Throws(() => LevelLoader.Load(stream, Wall, Wall)); + } + + [Fact] + public void WallEdgeHidesOnlyPartOfLamp() + { + string[] edge = ["....B", "....B", "..B.B", "....B"]; + var lamp = (3.5, 2.1); + var clear = Frame(Load(Room)); + var visible = Frame(Load(Room, lamp)); + var wall = Frame(Load(edge)); + var clipped = Frame(Load(edge, lamp)); + int hidden = 0, shown = 0; + for (int i = 0; i < clipped.Length; i++) + { + if (visible[i] == clear[i]) continue; + // The near wall's corner is (3, 2), at slope 0.2 from the camera. + if ((i % Width + 0.5 - Width / 2) / (Width / 2) > 0.2) + { + Assert.Equal(wall[i], clipped[i]); + hidden++; + } + else + { + Assert.Equal(visible[i], clipped[i]); + shown++; + } + } + Assert.True(hidden > 0 && shown > 0); + } + + [Fact] + public void NearLampOverlaysFarLampAndItsTransparentTexelsPreserveTheBackground() + { + var near = (2.5, 1.55); + var far = (3.5, 1.5); + var background = Frame(Load(Room)); + var front = Frame(Load(Room, near)); + var back = Frame(Load(Room, far)); + var both = Frame(Load(Room, near, far)); + bool overlap = false, throughTransparentPixel = false; + for (int i = 0; i < both.Length; i++) + { + bool opaque = front[i] != background[i]; + Assert.Equal(opaque ? front[i] : back[i], both[i]); + if (back[i] == background[i]) continue; + overlap |= opaque && front[i] != back[i]; + // Inside the nearer billboard's bounds, but outside its painted silhouette. + throughTransparentPixel |= !opaque && i % Width is >= 58 and < 74 && i / Width is >= 40 and < 64; + } + Assert.True(overlap && throughTransparentPixel); + } + + [Theory] + [InlineData(1.6)] + [InlineData(1.5)] + [InlineData(1.4999999999)] + public void LampBehindOrAtCameraPlaneIsCulled(double cameraX) + { + Assert.Equal(Frame(Load(Room), cameraX), Frame(Load(Room, (1.5, 1.5)), cameraX)); + } + + [Theory] + [InlineData("..D.B", 3.5)] + [InlineData("..D..", double.PositiveInfinity)] + public void OpeningDoorRefreshesSameDepthAndPixelBuffers(string row, double openDepth) + { + // Door is x=2, lamp x=3.5, and the last cell is either wall or a ray miss. + var map = Load([row, row, row], (3.5, 1.5)); + var pixels = new uint[Width * Height]; + var depths = new double[Width]; + void Render() => SoftwareRenderer.Render(map, 0.5, 1.5, 0, Math.PI / 2, Width, Height, pixels, depths); + Render(); + Assert.Equal(1.5, depths[Width / 2]); + Assert.DoesNotContain(0xFF22DBB0u, pixels); + Assert.True(map.TryToggleDoor(new PlayerState(0.5, 1.5, 0))); + Render(); + Assert.Equal(openDepth, depths[Width / 2]); + Assert.Contains(0xFF22DBB0u, pixels); + } +}