|
| 1 | +namespace Chip8.UI.Blazor; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Blazor WebAssembly implementation of <see cref="IDisplay"/>. |
| 5 | +/// Maintains a pixel buffer; actual canvas rendering is driven externally via <see cref="GetPixelData"/>. |
| 6 | +/// </summary> |
| 7 | +internal sealed class BlazorDisplay : IDisplay |
| 8 | +{ |
| 9 | + private const int ScreenWidth = 64; |
| 10 | + private const int ScreenHeight = 32; |
| 11 | + |
| 12 | + private readonly bool[,] _pixelBuffer = new bool[ScreenWidth, ScreenHeight]; |
| 13 | + private readonly byte[] _pixelData = new byte[ScreenWidth * ScreenHeight]; |
| 14 | + private bool _dirty; |
| 15 | + |
| 16 | + public void Clear() |
| 17 | + { |
| 18 | + Array.Clear(_pixelBuffer); |
| 19 | + _dirty = true; |
| 20 | + } |
| 21 | + |
| 22 | + public void ClearPixel(byte x, byte y) |
| 23 | + { |
| 24 | + _pixelBuffer[x, y] = false; |
| 25 | + _dirty = true; |
| 26 | + } |
| 27 | + |
| 28 | + public bool GetPixel(byte x, byte y) => _pixelBuffer[x, y]; |
| 29 | + |
| 30 | + public void SetPixel(byte x, byte y) |
| 31 | + { |
| 32 | + _pixelBuffer[x, y] = true; |
| 33 | + _dirty = true; |
| 34 | + } |
| 35 | + |
| 36 | + public void RenderIfDirty() |
| 37 | + { |
| 38 | + // No - op in Blazor.Rendering is handled by the game loop via GetPixelData. |
| 39 | + } |
| 40 | + |
| 41 | + /// <summary> |
| 42 | + /// Returns a flat byte array (64×32, row-major, 1=on 0=off) if the display changed since the last call. |
| 43 | + /// Returns null if nothing changed. |
| 44 | + /// </summary> |
| 45 | + public byte[]? GetPixelData() |
| 46 | + { |
| 47 | + if (!_dirty) |
| 48 | + { |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + _dirty = false; |
| 53 | + |
| 54 | + for (int y = 0; y < ScreenHeight; y++) |
| 55 | + { |
| 56 | + for (int x = 0; x < ScreenWidth; x++) |
| 57 | + { |
| 58 | + _pixelData[y * ScreenWidth + x] = _pixelBuffer[x, y] ? (byte)1 : (byte)0; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return _pixelData; |
| 63 | + } |
| 64 | +} |
0 commit comments