Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! A Videx UltraTerm: the card Videx sold after the Videoterm, and a bigger//! machine than it in every direction.//!//! The Videoterm gave an Apple II eighty columns out of two kilobytes of its//! own memory, a 6845 and a character generator, and it drew on a monitor of//! its own beside the Apple's. This does all of that and then goes further://! four kilobytes of screen memory rather than two, nine display formats//! rather than one, two dot clocks to reach them with, a per-character//! attribute for intensity and inverse, and a switch that decides which of the//! two pictures reaches the one monitor rather than leaving the choice to//! whoever is looking.//!//! What it kept is the shape of the thing. The card answers sixteen device//! select addresses, its firmware sits in the shared `$C800` window, and its//! screen memory is seen five hundred and twelve bytes at a time at `$CC00` —//! all as the Videoterm did, which is why software written for one mostly ran//! on the other. `videx.zig` is the earlier card and reading it first is the//! shorter way into this one.//!//! ## The sixteen addresses//!//! Reading and writing are different operations here, which they were not on//! the Videoterm: the manual's table gives each address a meaning for each//! direction, and "it is the reading of a particular address that will set a//! specific operating mode" (Videx, 1983, § 8.d.3).//!//! | address | written | read |//! | --- | --- | --- |//! | `$C0n0` | the 6845's register number | selects screen memory page 0 |//! | `$C0n1` | that register's value | — |//! | `$C0n2` | the mode control port | — |//! | `$C0n3` | the attribute register | — |//! | `$C0n4` | — | selects page 1 |//! | `$C0n8` | — | selects page 2 |//! | `$C0nC` | — | selects page 3 |//!//! ## The mode control port//!//! Eight bits, and the low four of them are an address rather than a setting://!//! - **Bit 7, the bank.** The firmware calls it `HPBANK`, "read screen / ROM//! page two": it decides whether the window at `$CC00` shows the screen//! memory or another page of the firmware.//! - **Bit 6, the video signal.** Which picture goes to the monitor. The//! Videoterm had a monitor of its own and no opinion; this card has "an//! electronic switch that will automatically select the proper video//! signal when you change display modes", and a machine coming out of//! reset sends the Apple's forty columns until `PR#n` says otherwise.//! - **Bit 5, the clock.** Set for 28.7595 MHz and clear for 17.430 MHz,//! which is the Videoterm's own crystal. The wide formats need the fast//! one; eighty columns is drawn with either.//! - **Bit 4, how the processor addresses the memory.** Clear for the//! Videoterm's arrangement of four 512-byte blocks chosen by reads, set//! for sixteen 256-byte pages chosen by the four bits below.//! - **Bits 3 to 0**, address bits 11 to 8 of the screen memory in that//! second arrangement, which is how four kilobytes are reached through a//! window that shows a quarter of a kilobyte.//!//! ## Attributes//!//! Every character carries one bit of attribute and the card carries the rest.//! The high bit of a byte in screen memory picks one of two attribute sets,//! and the attribute register holds both: "the high nibble sets the attributes//! for characters with the high bit set. The lower nibble sets the attributes//! for characters with the high bit clear" (Videx, 1983, § 8.d.3). Three bits//! of each nibble mean anything, and they are the same three either way — the//! character set, whether the video is inverted, and whether the dots are//! bright or dim.//!//! Two brightnesses is the part with no equivalent on the earlier card, and it//! is why a scan line here is levels rather than dots: a lowlight character is//! not a dimmer idea of a character, it is the same dots driven less hard.
const std = @import("std");const testing = std.testing;
/// Four kilobytes of screen memory, which is twice the Videoterm's.pub const ram_size = 4096;
/// The window the processor sees it through, and the two ways of choosing/// which part of the memory is under it. `DISP0 EQU $CC00` and `DISP1 EQU/// $CD00` in the firmware's own equates: the window is 512 bytes and the/// firmware names its halves separately, the second being "the secondary/// screen page for block mode".pub const window_size = 512;pub const block_size = 512;pub const page_size = 256;
/// The character generator: 256 glyphs of sixteen rows, eight dots wide, and/// the part Videx shipped holds "a standard character set and a high-quality/// character set" between them — the lower half of it is the taller of the two/// and the upper half the compressed one.pub const charset_size = 4096;pub const charset_rows = 16;pub const glyph_dots = 8;
/// The cell those eight dots sit in is nine wide, the ninth being the gap to/// the next character, exactly as seven sit in nine on the Videoterm.////// The manual does not put a number on it, and the firmware does: it asks for/// 123 character times to a line and 262 scan lines to a frame at 17.43 MHz,/// and 123 x 262 x 9 comes to 60.1 Hz where 123 x 262 x 8 would come to 67.6./// A card built to drive an ordinary monitor is doing the first of those.pub const cell_dots = 9;
/// The firmware. Four kilobytes, and not four kilobytes of program: the first/// page is a copyright notice, the seven after it are one `$Cn00` page per/// slot — identical but for the card addresses baked into each — and the two/// kilobytes above them are the code.pub const firmware_size = 4096;pub const slot_page_size = 256;pub const first_slot_page = 1;pub const code_at = 2048;
/// Where a slot's `$Cn00` page is in that.pub fn slotPageAt(slot: u3) usize { return @as(usize, slot) * slot_page_size;}
/// The largest picture this will describe, as `videx.zig` bounds its own: the/// 6845's registers allow more than the card can fill, and a surface has to be/// allocated before anything is drawn.pub const max_columns = 160;pub const max_rows = 48;pub const max_cell_dots = 16;
/// What the mode control port's bits mean.pub const mode_bank = 0x80;pub const mode_video = 0x40;pub const mode_fast_clock = 0x20;pub const mode_paged = 0x10;pub const mode_address = 0x0f;
/// The two dot clocks, in hertz. The slow one is the Videoterm's crystal,/// which is what a card drawing eighty columns the older way runs at.pub const slow_clock = 17_430_000;pub const fast_clock = 28_759_500;
/// What one of the two attribute sets says about a character.pub const Attributes = packed struct(u3) { /// Bit 0: bright dots or dim ones. highlight: bool = false, /// Bit 1: the video inverted. inverse: bool = false, /// Bit 2: the other character set. alternate: bool = false,
pub fn from(nibble: u4) Attributes { return @bitCast(@as(u3, @truncate(nibble))); }};
/// How brightly a dot is drawn, which on this card is three answers rather/// than two.pub const Level = enum(u2) { off, low, high };
/// The 6845, which is the same part the Videoterm carries and is driven the/// same way: a register number to one address and its value to the next.pub const Crtc = struct { address: u5 = 0, register: [18]u8 = @splat(0),
fn readable(at: u5) bool { return at >= 14 and at <= 17; }
pub fn write(self: *Crtc, value: u8) void { if (self.address < self.register.len) self.register[self.address] = value; }
pub fn read(self: *const Crtc) u8 { if (self.address >= self.register.len) return 0; return if (readable(self.address)) self.register[self.address] else 0; }
pub fn startAddress(self: *const Crtc) u16 { return (@as(u16, self.register[12] & 0x3f) << 8) | self.register[13]; }
pub fn cursorAddress(self: *const Crtc) u16 { return (@as(u16, self.register[14] & 0x3f) << 8) | self.register[15]; }
pub fn cursorLines(self: *const Crtc) struct { first: u5, last: u5 } { return .{ .first = @truncate(self.register[10] & 0x1f), .last = @truncate(self.register[11] & 0x1f), }; }
pub const Blink = enum { steady, hidden, fast, slow };
pub fn blink(self: *const Crtc) Blink { return switch (@as(u2, @truncate(self.register[10] >> 5))) { 0b00 => .steady, 0b01 => .hidden, 0b10 => .fast, 0b11 => .slow, }; }};
pub const Card = struct { fitted: bool = false,
/// Which slot it is in, which decides which of the firmware's seven pages /// answers at `$Cn00`. The card knows because it is plugged in there. slot: u3 = 3,
ram: [ram_size]u8 = @splat(' '),
/// Which 512-byte block the window shows, when the window is blocks. block: u2 = 0,
crtc: Crtc = .{},
/// The mode control port, kept whole because four of its bits are an /// address and the rest are switches. mode: u8 = 0,
/// The attribute register: the high nibble for characters whose high bit /// is set, the low nibble for the rest. attributes: u8 = 0,
/// Whether a *read* of the window at `$CC00` gives back screen memory. /// /// This is a question about reading and not about the window, and the /// difference is the whole of how the card fits two kilobytes of firmware /// into a space that is also its screen. The manual is exact: "the upper /// 1K bytes of this space is used by the video refresh memory. For this /// reason the firmware is split into two banks. These banks are selected /// with bit seven of the MCP. When the second bank of firmware is selected /// it overlays the Video Refresh Memory at addresses from $CC00 to $CFE0. /// The first bank of the firmware always occupies the region from $C800 to /// $CBFF" (Videx, 1983, § Y.2). /// /// *Overlays* is doing the work there. An EPROM whose outputs are gated /// onto the bus can only answer a read; the RAM beside it still takes a /// write, because a write strobe does not care what is driving the bus. /// So the bit chooses what comes back from `$CC00` and never where a /// character goes — and the firmware's own name for it says as much, /// `MPBANK` being commented "read screen / ROM page two". /// /// This is not a nicety. The firmware clears the screen with the second /// bank selected, writing `$20` into `$CC00,Y` with bit seven set, and /// then jumps to `$CC2C` — code in that same bank, at that same address. /// A model that let the bit decide writes as well as reads drops every /// character; one that lets it decide neither runs the screen as code. pub fn windowReadsScreen(self: *const Card) bool { return self.mode & mode_bank == 0; }
/// Whether the card's own picture is the one reaching the monitor. /// /// A machine coming out of reset says no, and `PR#n` is what says yes. /// The Videoterm never had to answer this: it had a monitor of its own. pub fn driving(self: *const Card) bool { return self.mode & mode_video != 0; }
/// The dot clock in use, in hertz. pub fn clock(self: *const Card) u32 { return if (self.mode & mode_fast_clock != 0) fast_clock else slow_clock; }
/// Where in the four kilobytes an offset into the window lands. /// /// Two arrangements, and the mode port says which. Clear is the /// Videoterm's: four blocks of five hundred and twelve bytes, chosen by /// reading one of four addresses, which reaches half the memory. Set is /// this card's own: a page of two hundred and fifty-six bytes anywhere in /// the four kilobytes, the page number being the low four bits of the mode /// port, which reaches all of it. pub fn windowAt(self: *const Card, offset: u9) u12 { if (self.mode & mode_paged != 0) { const page: u12 = @as(u12, self.mode & mode_address) << 8; return page | (offset & 0xff); } return (@as(u12, self.block) << 9) | offset; }
/// One of the sixteen device select addresses was touched. /// /// Reads and writes do different things, and an address that does nothing /// in one direction really does nothing: the manual says as much, and adds /// that using the others "may have unpredictable effects". pub fn access(self: *Card, offset: u4, writing: bool, value: u8) u8 { if (writing) { switch (offset) { 0x0 => self.crtc.address = @truncate(value & 0x1f), 0x1 => self.crtc.write(value), 0x2 => self.mode = value, 0x3 => self.attributes = value, else => {}, } return 0; } switch (offset) { 0x0 => self.block = 0, 0x4 => self.block = 1, 0x8 => self.block = 2, 0xc => self.block = 3, else => {}, } return 0; }
pub fn windowRead(self: *const Card, offset: u9) u8 { return self.ram[self.windowAt(offset)]; }
pub fn windowWrite(self: *Card, offset: u9, value: u8) void { self.ram[self.windowAt(offset)] = value; }
/// The shape of the picture, from the 6845, as on the earlier card. pub fn cellLines(self: *const Card) u8 { return @as(u8, self.crtc.register[9]) + 1; }
pub fn rowsShown(self: *const Card) u8 { return self.crtc.register[6]; }
pub fn columnsShown(self: *const Card) u8 { return self.crtc.register[1]; }
/// Where a place on the screen comes from, wrapping at four kilobytes /// rather than at two. Scrolling is the start address moving, as before. pub fn addressOf(self: *const Card, row: usize, column: usize) u12 { const wide: usize = @max(1, self.columnsShown()); return @truncate(self.crtc.startAddress() +% @as(u16, @intCast(row * wide + column))); }
pub fn characterAt(self: *const Card, row: usize, column: usize) u8 { return self.ram[self.addressOf(row, column)]; }
/// Which attribute set a byte in screen memory asks for, and what it says. pub fn attributesOf(self: *const Card, byte: u8) Attributes { const nibble: u4 = if (byte & 0x80 != 0) @truncate(self.attributes >> 4) else @truncate(self.attributes); return .from(nibble); }
pub fn cursorIn(self: *const Card, row: usize, column: usize) ?struct { first: u5, last: u5 } { if (self.crtc.blink() == .hidden) return null; if (self.addressOf(row, column) != @as(u12, @truncate(self.crtc.cursorAddress()))) return null; const lines = self.crtc.cursorLines(); return .{ .first = lines.first, .last = lines.last }; }};
/// How wide the picture is, in dots.pub fn pictureWidth(card: *const Card) u16 { const across = card.columnsShown(); if (across == 0) return 80 * cell_dots; return @as(u16, @min(max_columns, across)) * cell_dots;}
/// And how tall.pub fn pictureHeight(card: *const Card) u16 { const down = card.rowsShown(); if (down == 0) return 24 * 9; return @as(u16, @min(max_rows, down)) * @min(max_cell_dots, @as(u16, card.cellLines()));}
/// One scan line, as a brightness for each dot.pub const Line = struct { levels: [max_columns * cell_dots]Level = @splat(.off),};
/// Draws one line of the card's display.////// The character generator is a part in a socket, as the Videoterm's is, and/// the standard and alternate sets are the two halves of it — which is why one/// four kilobyte part holds both where the earlier card wanted two of two/// kilobytes each.pub fn scanLine( card: *const Card, set: *const [charset_size]u8, y: u16, blinked: bool, into: *Line,) void { into.* = .{}; if (y >= pictureHeight(card)) return; const tall: u16 = @max(1, card.cellLines()); const row = y / tall; const line = y % tall; if (row >= card.rowsShown()) return; const across: usize = @min(max_columns, card.columnsShown());
for (0..across) |column| { const byte = card.characterAt(row, column); const attrs = card.attributesOf(byte); const glyph: usize = (@as(usize, @intFromBool(attrs.alternate)) << 7) | (byte & 0x7f); const dots: u8 = if (line < charset_rows) set[glyph * charset_rows + line] else 0;
const cursor = on: { if (!blinked) break :on false; const where = card.cursorIn(row, column) orelse break :on false; const at: u5 = @intCast(@min(line, 31)); break :on if (where.first <= where.last) at >= where.first and at <= where.last else at >= where.first or at <= where.last; }; // Inverse and the cursor are the same operation and cancel each other, // which is what a cursor sitting on an inverse character looks like. const flip = attrs.inverse != cursor; const bright: Level = if (attrs.highlight) .high else .low;
for (0..cell_dots) |dot| { // Eight dots of glyph and then the gap, which only an inverted // cell or a cursor ever fills. const lit = dot < glyph_dots and dots & (@as(u8, 0x80) >> @intCast(dot)) != 0; into.levels[column * cell_dots + dot] = if (lit != flip) bright else .off; } }}
/// A card set up the way its firmware sets one up, for the tests that draw.fn configured() Card { var card: Card = .{ .fitted = true }; // Eighty by twenty-four in a nine-line cell, which is mode 1 of nine. const written = [_]u8{ 98, 80, 83, 10, 27, 6, 24, 25, 0, 8, 0xe0, 8, 0, 0, 0, 0 }; for (written, 0..) |value, register| { card.crtc.address = @intCast(register); card.crtc.write(value); } card.crtc.address = 0; return card;}
test "reading selects a block and writing reaches a register, and never the other way" { var card: Card = .{ .fitted = true };
// Writing $C0n0 and $C0n1 is the 6845, as on the Videoterm. _ = card.access(0x0, true, 6); _ = card.access(0x1, true, 24); try testing.expectEqual(@as(u8, 24), card.crtc.register[6]);
// But writing $C0n0 does *not* also move the window here: on this card the // block is chosen by reading, and only by reading. try testing.expectEqual(@as(u2, 0), card.block); _ = card.access(0x8, false, 0); try testing.expectEqual(@as(u2, 2), card.block); _ = card.access(0x0, true, 9); try testing.expectEqual(@as(u2, 2), card.block);
// The two registers the Videoterm had no equivalent of. _ = card.access(0x2, true, mode_video | mode_fast_clock); try testing.expect(card.driving()); try testing.expectEqual(fast_clock, card.clock()); _ = card.access(0x3, true, 0x35); try testing.expectEqual(@as(u8, 0x35), card.attributes);}
test "four kilobytes are reached two ways, and the mode port says which" { var card: Card = .{ .fitted = true }; card.ram = @splat(0);
// Blocks: four of five hundred and twelve bytes, chosen by reading, which // is the Videoterm's arrangement and reaches half the memory. _ = card.access(0xc, false, 0); card.windowWrite(0, 'A'); try testing.expectEqual(@as(u8, 'A'), card.ram[1536]);
// Pages: two hundred and fifty-six bytes anywhere in the four kilobytes, // the page being the low four bits of the mode port. Page fifteen is the // last quarter-kilobyte, which blocks cannot reach at all. _ = card.access(0x2, true, mode_paged | 0x0f); card.windowWrite(0, 'B'); try testing.expectEqual(@as(u8, 'B'), card.ram[0x0f00]); try testing.expectEqual(@as(u8, 'B'), card.windowRead(0));
// An offset past a page wraps within it rather than running into the next, // because only eight bits of it are an address in this arrangement. card.windowWrite(0x100, 'C'); try testing.expectEqual(@as(u8, 'C'), card.ram[0x0f00]);}
test "the high bit of a character picks an attribute set, and the register holds both" { var card: Card = .{ .fitted = true };
// The high nibble is for characters with the high bit set and the low // nibble for the rest. $71 is alternate, inverse and highlight for the // first, and standard, normal and highlight for the second. _ = card.access(0x3, true, 0x71); const high = card.attributesOf('A' | 0x80); try testing.expect(high.alternate and high.inverse and high.highlight); const low = card.attributesOf('A'); try testing.expect(!low.alternate and !low.inverse and low.highlight);
// Only three bits of each nibble mean anything. _ = card.access(0x3, true, 0x88); try testing.expectEqual(Attributes{}, card.attributesOf('A')); try testing.expectEqual(Attributes{}, card.attributesOf('A' | 0x80));}
test "a character is drawn at one of two brightnesses, which the Videoterm had no way to do" { var set: [charset_size]u8 = @splat(0); set[0x41 * charset_rows] = 0xff; // eight dots of glyph $41
var card = configured(); card.ram = @splat(' '); card.ram[0] = 'A';
var line: Line = .{};
// Lowlight, which is what the low nibble says by default. _ = card.access(0x3, true, 0x00); scanLine(&card, &set, 0, false, &line); try testing.expectEqual(Level.low, line.levels[0]);
// And highlight, which is one bit of one nibble. _ = card.access(0x3, true, 0x01); scanLine(&card, &set, 0, false, &line); try testing.expectEqual(Level.high, line.levels[0]);
// Inverse turns the cell inside out at whatever brightness it is. _ = card.access(0x3, true, 0x03); scanLine(&card, &set, 0, false, &line); try testing.expectEqual(Level.off, line.levels[0]); try testing.expectEqual(Level.high, line.levels[cell_dots]); // the space beside it}
test "the alternate set is the other half of one four kilobyte part" { var set: [charset_size]u8 = @splat(0); set[0x41 * charset_rows] = 0x0f; // standard glyph $41 set[(0x80 + 0x41) * charset_rows] = 0xf0; // alternate glyph $41
var card = configured(); card.ram = @splat(' '); card.ram[0] = 'A';
var line: Line = .{}; _ = card.access(0x3, true, 0x00); // standard scanLine(&card, &set, 0, false, &line); try testing.expectEqual(Level.off, line.levels[0]); try testing.expectEqual(Level.low, line.levels[4]);
_ = card.access(0x3, true, 0x04); // alternate scanLine(&card, &set, 0, false, &line); try testing.expectEqual(Level.low, line.levels[0]); try testing.expectEqual(Level.off, line.levels[4]);}
test "the bank bit decides what a read of the window gives back, and nothing else" { var card: Card = .{ .fitted = true }; // Out of reset the bit is clear and a read is the screen. try testing.expect(card.windowReadsScreen()); // Setting it overlays the second bank of firmware there. _ = card.access(0x2, true, mode_bank); try testing.expect(!card.windowReadsScreen());
// A write is unaffected either way, which is what lets the firmware clear // the screen with its own second bank selected — which is exactly what it // does, and then jump into that bank at $CC2C. card.windowWrite(0, 'A'); try testing.expectEqual(@as(u8, 'A'), card.ram[0]); _ = card.access(0x2, true, 0); card.windowWrite(1, 'B'); try testing.expectEqual(@as(u8, 'B'), card.ram[1]);}
test "a card coming out of reset is not the one driving the monitor" { // The difference from the Videoterm that matters most to whoever is // looking: there is one monitor and the card decides whether it is on it. var card: Card = .{ .fitted = true }; try testing.expect(!card.driving()); try testing.expectEqual(slow_clock, card.clock());
_ = card.access(0x2, true, mode_video); try testing.expect(card.driving());}
test "the seven slot pages are one apiece, and the code is above them" { try testing.expectEqual(@as(usize, 0x100), slotPageAt(1)); try testing.expectEqual(@as(usize, 0x300), slotPageAt(3)); try testing.expectEqual(@as(usize, 0x700), slotPageAt(7)); // Page zero is not a slot's: it is the copyright notice. try testing.expectEqual(@as(usize, 0), slotPageAt(0)); try testing.expect(code_at > slotPageAt(7));}