micronona/MemoryModel.cs
Hans-Jörg Meyer e0078538c3 Keyboard-Layout-Detection, SN76489-Sound, Text-Editor
- KeyboardLayoutDetector (KMAP-Befehl und --detect-keyboard-CLI)
  inkl. loadkeys-Integration und Persistenz im .micronona-Marker
- SN76489 PSG mit SDL-Audio-Anbindung
- Voll-Bildschirm-Texteditor (edit <file>) mit Undo, Cut/Paste,
  horizontalem Scrollen und Speicherbestätigung
- DiskManager-Erweiterungen: FindMicrononaMount, SaveKeyboardLayout,
  Dir-Listing
- ^-Glyph für die Editor-Statuszeile

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-13 22:09:57 +02:00

304 lines
No EOL
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/// <summary>
/// Memory model for Micronona.
///
/// Address space as seen by the 6809 CPU and all high-level layers (BASIC, host):
///
/// 0x0000 – 0xDEFF Fixed RAM (56,832 bytes, general purpose)
/// 0xDF00 – 0xDFFF Hardware registers (256 bytes, I/O)
/// 0xE000 – 0xFFFF Bank window (8KB, switchable via REG_BANK)
///
/// Extended RAM: 25 banks × 8KB = 200KB total.
/// The bank window at 0xE000 maps to one 8KB slice of extended RAM at a time.
/// Bank switching is done by writing the desired bank number to REG_BANK (0xDF01).
///
/// Bank layout conventions:
/// Bank 0 Text buffer (40×18×3 bytes: char, fg, bg) starts at offset 0,
/// or 320×180 RGB332 framebuffer when REG_MODE = 1 (graphics)
/// Bank 24 Font bitmaps (256 glyphs × 8×10 bytes) — FontBankIndex = BankCount-1
///
/// The CPU and all high-level layers use Read(address)/Write(address) exclusively.
/// Bank switching is transparent — callers set REG_BANK and then access 0xE000–0xFFFF.
///
/// The host (renderer, font loader, etc.) uses ReadFlat/WriteFlat to access extended
/// RAM directly by absolute byte offset, without affecting the bank register.
/// </summary>
public class MemoryModel
{
// -------------------------------------------------------------------------
// Layout constants
// -------------------------------------------------------------------------
public const int BankCount = 25;
public const int BankSize = 8192; // 8KB per bank
public const int FixedRamSize = 0xE000; // 56KB fixed RAM (0x0000–0xDFFF)
public const int IoBase = 0xDF00; // I/O register block start
public const int IoSize = 256; // 256 I/O registers
public const int BankWindowBase = 0xE000; // Bank window start address
// -------------------------------------------------------------------------
// I/O register offsets (relative to IoBase = 0xDF00)
// -------------------------------------------------------------------------
public const int REG_MODE = 0x00; // Display mode: 0 = text, 1 = graphics
public const int REG_BANK = 0x01; // Active bank in the 0xE000 window (0–255)
public const int REG_KEY_CHAR = 0x02; // Next keypress character (0 = none)
public const int REG_KEY_FLAGS = 0x03; // Modifier flags (Shift, Ctrl, …)
public const int REG_TIMER = 0x04; // Frame counter: incremented once per frame (60 Hz), saturates at 255, resets to 0 on read
public const int REG_VSYNC = 0x05; // VSync flag; set by host each frame
public const int REG_CURSOR_COL = 0x06; // Text cursor position horizontally
public const int REG_CURSOR_ROW = 0x07; // Text cursor position vertically
public const int REG_RANDOM = 0x08; // Read-only: returns a new random byte on every read
public const int REG_SOUND = 0x10; // Write-only: SN76489 PSG data port
// -------------------------------------------------------------------------
// Text mode layout (Bank 0, starting at offset 0)
// Each cell is 3 bytes: character code, foreground RGB332, background RGB332
// -------------------------------------------------------------------------
public const byte TextCols = 40;
public const int TextRows = 18;
public const int TextCellSize = 3;
public const int TextBankIndex = 0; // Text buffer lives in bank 0
public const int TextBufferSize = TextCols * TextRows * TextCellSize; // 2160 bytes
// -------------------------------------------------------------------------
// Font layout (Bank 255, starting at offset 0)
// 256 glyphs, each 8 pixels wide × 10 pixels tall, 1 bit per pixel packed
// into 2 bytes per row (only 8 bits used), so 10 bytes per glyph.
// -------------------------------------------------------------------------
public const int FontGlyphWidth = 8;
public const int FontGlyphHeight = 10;
public const int FontBankIndex = BankCount-1;
public const int FontSize = 256 * FontGlyphWidth * FontGlyphHeight; // 20480 bytes
// -------------------------------------------------------------------------
// Threading
// -------------------------------------------------------------------------
/// <summary>
/// Shared lock for all memory access. Callers may acquire this for bulk
/// operations (e.g. the renderer locks once per frame instead of once per
/// ReadFlat call). C# Monitor is re-entrant on the same thread, so nested
/// lock(Lock) blocks are safe.
/// </summary>
public readonly object Lock = new();
/// <summary>
/// Invoked whenever the CPU (or any writer) stores to REG_SOUND. The host
/// wires this to the SN76489 emulator. May be called from multiple threads.
/// </summary>
public Action<byte>? OnSoundWrite;
// VSync: semaphore signals each frame; _totalFrames counts them for elapsed measurement.
private readonly SemaphoreSlim _vsyncSem = new(0, 1);
private long _totalFrames = 0;
private long _lastVsyncFrame = 0;
// -------------------------------------------------------------------------
// Internal storage
// -------------------------------------------------------------------------
// Fixed RAM: 0x0000–0xDEFF (excludes I/O block)
private readonly byte[] _fixedRam = new byte[FixedRamSize];
// I/O registers: 0xDF00–0xDFFF
private readonly byte[] _io = new byte[IoSize];
// Extended RAM: 256 × 8KB = 2MB, bank-switched into 0xE000–0xFFFF
private readonly byte[] _extendedRam = new byte[BankCount * BankSize];
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
public MemoryModel(byte defaultFg, byte defaultBg)
{
// Bank 0 active by default
_io[REG_BANK] = TextBankIndex;
// Fill text buffer with spaces in default colors
int textBase = TextBankIndex * BankSize;
for (int i = 0; i < TextCols * TextRows; i++)
{
_extendedRam[textBase + i * TextCellSize + 0] = 0x20; // Space
_extendedRam[textBase + i * TextCellSize + 1] = defaultFg;
_extendedRam[textBase + i * TextCellSize + 2] = defaultBg;
}
}
// -------------------------------------------------------------------------
// CPU / high-level interface (Read/Write by 16-bit address)
// This is the only interface the CPU emulator, Lua, and TinyBasic use.
// -------------------------------------------------------------------------
/// <summary>
/// Read a single byte from the 16-bit address space.
/// </summary>
public byte Read(ushort address)
{
if (address >= IoBase && address < IoBase + IoSize)
return ReadIo(address - IoBase);
if (address >= BankWindowBase)
return ReadBank(address - BankWindowBase);
return _fixedRam[address];
}
/// <summary>
/// Write a single byte to the 16-bit address space.
/// </summary>
public void Write(ushort address, byte value)
{
if (address >= IoBase && address < IoBase + IoSize)
WriteIo(address - IoBase, value);
else if (address >= BankWindowBase)
WriteBank(address - BankWindowBase, value);
else
_fixedRam[address] = value;
}
/// <summary>
/// Write multiple bytes sequentially starting at address.
/// Convenient for loading font glyphs, tile data, strings, etc.
/// Example: mem.Write(0xE000, 0x48, 0x1C, 0x08);
/// </summary>
public void Write(ushort address, params byte[] data)
{
lock (Lock)
{
for (int i = 0; i < data.Length; i++)
WriteUnlocked((ushort)(address + i), data[i]);
}
}
private void WriteUnlocked(ushort address, byte value)
{
if (address >= IoBase && address < IoBase + IoSize)
WriteIo(address - IoBase, value);
else if (address >= BankWindowBase)
WriteBank(address - BankWindowBase, value);
else
_fixedRam[address] = value;
}
// -------------------------------------------------------------------------
// Host interface (flat access to extended RAM)
// Used by the renderer, font loader, and other host-side components.
// Does not affect the bank register; does not go through the bank window.
// Address is an absolute byte offset into the 2MB extended RAM (0–2097151).
// -------------------------------------------------------------------------
/// <summary>
/// Read a single byte from extended RAM by absolute offset.
/// </summary>
public byte ReadFlat(int address)
{
return _extendedRam[address];
}
/// <summary>
/// Write one or more bytes to extended RAM starting at absolute offset.
/// Example: mem.WriteFlat(255 * BankSize, 0x00, 0x18, 0x3C, 0x66, ...);
/// </summary>
public void WriteFlat(int address, params byte[] data)
{
lock (Lock)
{
for (int i = 0; i < data.Length; i++)
_extendedRam[address + i] = data[i];
}
}
public void FillFlat(int address, int length, byte value)
{
lock (Lock)
{
_extendedRam.AsSpan(address, length).Fill(value);
}
}
/// <summary>
/// Return a Span over one full bank in extended RAM.
/// Useful for bulk operations like SDL texture uploads.
/// </summary>
public Span<byte> GetBankSpan(int bank)
=> _extendedRam.AsSpan(bank * BankSize, BankSize);
// -------------------------------------------------------------------------
// Internal helpers
// -------------------------------------------------------------------------
/// <summary>
/// Called once per rendered frame by the host. Increments REG_TIMER, saturating at 255.
/// </summary>
public void TickFrame()
{
if (_io[REG_TIMER] < 255)
_io[REG_TIMER]++;
}
private byte ReadIo(int reg)
{
if (reg == REG_TIMER)
{
// Returns frames elapsed since last read, then resets to 0
byte val = _io[REG_TIMER];
_io[REG_TIMER] = 0;
return val;
}
if (reg == REG_RANDOM)
return (byte)Random.Shared.Next(256);
return _io[reg];
}
private void WriteIo(int reg, byte value)
{
if (reg == REG_VSYNC)
{
WaitVSync();
return;
}
if (reg == REG_SOUND)
{
_io[reg] = value;
OnSoundWrite?.Invoke(value);
return;
}
// All other register writes are simple stores.
_io[reg] = value;
}
private void WaitVSync()
{
_vsyncSem.Wait();
long now = Volatile.Read(ref _totalFrames);
int elapsed = (int)(now - _lastVsyncFrame);
_lastVsyncFrame = now;
_io[REG_TIMER] = (byte)Math.Min(elapsed, 255);
}
/// <summary>
/// Called by the SDL render loop after SDL_RenderPresent.
/// Increments the frame counter and unblocks any thread waiting on REG_VSYNC.
/// </summary>
public void SignalVSync()
{
Interlocked.Increment(ref _totalFrames);
if (_vsyncSem.CurrentCount == 0)
_vsyncSem.Release();
}
private byte ReadBank(int offset)
{
int bank = _io[REG_BANK];
return _extendedRam[bank * BankSize + offset];
}
private void WriteBank(int offset, byte value)
{
int bank = _io[REG_BANK];
_extendedRam[bank * BankSize + offset] = value;
}
}