// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! An Apple III: a 6502B at 2 MHz and up to half a megabyte of memory, seen //! through the addressing hardware that let a 16-bit processor have it. //! //! What the machine adds to a 6502 is around the processor rather than in it, //! and the SOS Reference Manual describes it from the software's side (Apple //! Computer, Inc., 1982a, chapter 2), the one place Apple wrote it down: //! //! - Memory is in banks of 32K. "One bank (called the 'SOS bank', or S-bank) //! is always present. This unswitched bank occupies locations $0000 through //! $1FFF and locations $A000 through $FFFF in the standard 6502 addressing //! space." "Locations $2000 through $9FFF are occupied by one of up to 15 //! switchable banks, numbered $0 through $E", chosen by "the bank register //! (memory location $FFEF)", of which "only the lower four bits ... contain //! the current bank number" (pp. 10–11, 29). //! - Zero page and the stack move. "The Apple III resolves this contention //! by allocating separate zero pages to the interpreter ($1A00 through //! $1AFF) and SOS ($1800 through $18FF)", and "separate stacks to the //! interpreter ($1B00 through $1BFF) and to SOS ($0100 through $01FF)" //! (p. 17). The page is the zero-page register at `$FFD0` (Apple //! Computer, Inc., n.d.-c, appendix D), and the stack is the page beside it //! unless the environment register forces "primary stack at 0100-01FF". //! - Enhanced indirect addressing. "Any 6502 instruction that supports //! indirect-X or indirect-Y addressing (ADC, AND, CMP, EOR, LDA, ORA, SBC, //! STA) can use enhanced indirect addressing": a pointer at `$nn` on zero //! page has "its extension byte, or X-byte" in the extension page, and //! "enhanced indirect addressing takes effect whenever you execute an //! indirect-mode instruction and bit 7 of the pointer's extension byte //! (X-byte) is 1; that is, whenever the extension byte is between $80 and //! $8F" (p. 31). The low four bits name a pair of adjacent banks, and the //! value $8F "pairs the S-bank with bank $0" in the standard arrangement //! (p. 14). The extension page is four below the zero page: "Page $16 is //! used as the extension page" for an interpreter on page $1A, and page //! $14 for SOS on $18 (pp. 18, 20). None of that is the processor's //! doing: the board watches the bus for the pointer being read and steers //! the data access that follows. //! - An environment register, at `$FFDF`, holding the processor speed, the //! I/O space, the screen, the reset key, write protection, which stack and //! whether the ROM shows (Apple Computer, Inc., n.d.-c, table 3-3). Its bit //! numbers are in SOS's own source: `ORA #$80` to "SET 1MHZ", `ORA #$40` //! to "SWITCH IN I/O BANK", `AND #$20` for "the state of the screen", //! `AND #$FF-$10` to "DISABLE NMI/RESET", `BITOFF3` to "WRITE ENABLE", //! `BITON2` to "FORCE PRIMARY STACK", `ORA #$03` to "ENABLE ROM/IO SPACE" //! (Apple Computer, Inc., 1982b). //! //! The three registers are the ports of two 6522s: the environment register //! is the D VIA's port A and the zero-page register its port B; the bank //! register is the E VIA's port A, whose bit 6 also decides whether the VIAs //! answer at `$FFD0` to `$FFEF` at all, and the E VIA's port B carries the //! six-bit sound DAC. The VIAs' other duties — the clock chip's interrupt, //! the keyboard's, the slots' — are wired here as far as the machine has //! anything on the end of them. //! //! The clock is nominally 2 MHz — "an interpreter runs at a nominal 2 MHz //! clock rate. In practice, execution speed is approximately 1.4 MHz if the //! Apple III's video display is on ... 1.8 MHz" with it off (Apple Computer, //! Inc., 1982a, p. 18) — and the environment register's top bit holds it to //! 1 MHz for "the statemachine I/O" of the disk. Cycles here are counted at //! 2 MHz, and the video's share of them is taken out in `spend`: with the //! display on the screen holds the other phase through each line's showing //! cycles, so an access there costs two and the rate settles near 1.4 MHz, //! and with the display off the processor keeps both phases and runs at the //! full 2 MHz. (The 1.8 MHz the manual names for the display-off case is the //! SOS interpreter's own throughput, which sits above this bare memory clock.) //! //! Where a detail below is not in the manuals — the VIA wiring, what the //! machine reads at reset, the rule for which zero-page reads arm the //! extension — it follows MAME's `apple3` driver, and says so, as a reading //! of the schematics that has been checked against the machine's software. const std = @import("std"); const bus_log = @import("bus.zig"); const Options = bus_log.Options; const disk2 = @import("../disk2.zig"); const disk35 = @import("../disk35.zig"); const font = @import("../font.zig"); const screen = @import("../screen.zig"); const serial = @import("../serial.zig"); const speaker = @import("../speaker.zig"); const via = @import("../via.zig"); const mm58167 = @import("../mm58167.zig"); const blockdevice = @import("../blockdevice.zig"); const profile = @import("../profile.zig"); const upic_module = @import("../upic.zig"); /// A bank: "banks of 32K bytes each". pub const bank_size: usize = 0x8000; /// The most memory the addressing can name: sixteen banks, of which the /// last is the S-bank, and the manual's 512K. pub const max_banks: u8 = 16; pub const max_memory: usize = max_banks * bank_size; /// What the machine was sold with, and the least a SOS system used. pub const default_memory: usize = 4 * bank_size; /// The boot ROM: "4K (4,096) eight-bit bytes initialization and diagnostics" /// (Apple Computer, Inc., 1981a, appendix E), at the top of the S-bank. pub const rom_size: usize = 0x1000; pub const rom_base: u16 = 0xf000; /// The three registers by the addresses the software knows them by. pub const zero_page_register: u16 = 0xffd0; pub const environment_register: u16 = 0xffdf; pub const bank_register: u16 = 0xffef; /// The environment register's bits, from SOS's source (Apple Computer, Inc., /// 1982b) and the Device Driver Writer's Guide's table of the driver /// environment (Apple Computer, Inc., n.d.-c, table 3-3). pub const Environment = struct { /// "SET 1MHZ": the processor held to 1 MHz, for the disk state machine. pub const slow: u8 = 0x80; /// "SWITCH IN I/O BANK": `$C000` to `$CFFF` is I/O rather than RAM. pub const io: u8 = 0x40; /// "The state of the screen": video enabled. pub const video: u8 = 0x20; /// "DISABLE NMI/RESET" clears it: the reset key and NMI reach the /// processor while it is set. pub const nmi: u8 = 0x10; /// "WRITE ENABLE" clears it: RAM in the S-bank's `$C000` to `$FFFF` is /// write protected while it is set. pub const write_protect: u8 = 0x08; /// "FORCE PRIMARY STACK": the stack at `$0100` whatever the zero-page /// register says. pub const primary_stack: u8 = 0x04; /// The ROM socket: this machine has one ROM, so the bit is set whenever /// the one below is. pub const primary_rom: u8 = 0x02; /// "ENABLE ROM": the ROM answers at `$F000` to `$FFFF`. pub const rom: u8 = 0x01; }; /// The modifier byte with nothing held: bits 2 to 6 high, which is control, /// alpha lock and the Apple keys released, and shift (bit 1) and the strobe /// (bit 0) low. pub const modifiers_idle: u8 = 0x7c; /// Bit 6 of the bank register — the E VIA's PA6 — is an input, not a switch: /// "The PA4-PA7 lines are configured as inputs. Slot 1 and 2 IRQs, the Solid /// Apple switch, and the IRQ line itself form the respective inputs" (Apple /// Computer, Inc., 1982c, p. 3.15). It reads high with the key up. Software /// writes the bit set out of habit, and MAME takes the written bit as what /// shows the VIAs at `$FFD0` to `$FFEF`; here the VIAs are always there, and /// the RAM beneath them is reached the way SOS reaches it, through enhanced /// indirect addressing, which goes round the I/O decode. pub const solid_apple: u8 = 0x40; /// The clock: "2 MHz peak" (Apple Computer, Inc., 1981a, appendix E). pub const clock_hz: u64 = 2_000_000; /// The frame, in the processor's cycles. The video is the Apple II's: 262 /// lines of 65 of the II's cycles, 192 of them showing a picture, from the /// same 14.318 MHz crystal (MAME Development Team, n.d., sets its screen to 910 dots by 262 lines at /// that rate); at twice the processor clock a line is 130 cycles. pub const cycles_per_line: u64 = 130; /// The part of a line that shows: forty of the II's 65 cycles, so eighty. pub const active_cycles_per_line: u64 = 80; pub const visible_cycles: u64 = 192 * cycles_per_line; pub const blanking_cycles: u64 = 70 * cycles_per_line; /// The beep: the speaker line changes at 2 kHz, two hundred times. pub const beep_half_period: u64 = clock_hz / 2000; pub const beep_edge_count: u16 = 200; /// Where the ProFile's interface card goes when nobody says otherwise: "This /// Interface Card is installed in slot #4 in your Apple III" (*Using the /// ProFile with the Apple ///*, n.d., p. 1), and every SOS.DRIVER file that /// came to hand configures its `.PROFILE` for slot 4. So its ports are at /// `$C0C0` and its control latch under `$C400`. /// /// It is a default rather than a fact about the machine, which is why the slot /// is a field rather than this constant. Slot assignment on an Apple III is /// software: the System Configuration Program's Peripheral Slot Assignment /// "enables you to tell each device driver the slot number into which you" /// put its card, "a number from 1 to 4", and a driver for something built in /// shows `n/a` instead (Apple Computer, Inc., 1981b, p. 17). So a SOS.DRIVER /// built with the ProFile assigned elsewhere expects the card elsewhere, and a /// model that had slot 4 compiled into it could not follow. pub const default_profile_slot: u3 = 4; /// The four slots, and what is in each. /// /// **These are the Apple III's own slots and not `slots.zig`'s.** That module /// is the Apple II's seven, and its cards are Apple II cards: a Videoterm or a /// Mockingboard in an Apple III would be a card the machine has no driver for /// and no business holding. The III has four slots, two cards that exist for /// it, and an I/O page laid out nothing like a II's — so what is shared with /// the II here is the `$c080 + s0` convention and nothing else, and one /// four-entry array is the whole of the apparatus. pub const SlotCard = enum { empty, /// The ProFile's interface card, whose state is the model's `profile`. profile, /// A Universal Parallel Interface Card, whose state is its `upic`. upic, }; /// The lowest and highest of the four. Slot 0 is not a slot. pub const first_slot: u3 = 1; pub const last_slot: u3 = 4; /// The video modes, as the four switches at `$C050` to `$C057` set them. Each /// switch is a pair of addresses, the even one clearing it and the odd one /// setting it: `VM0 EQU $C050`, `VM1 EQU $C052`, `VM2 EQU $C054`, `VM3 EQU /// $C056` in SOS's source. VM3 is text or graphics, VM1 and VM0 pick the mode /// within each, and VM2 chooses the page (MAME Development Team, n.d.). pub const VideoMode = packed struct(u4) { vm0: bool = false, vm1: bool = false, vm2: bool = false, vm3: bool = false, }; pub fn AppleIII(comptime options: Options) fn (type) type { return struct { fn model(comptime CPU: type) type { return struct { const Self = @This(); pub const Access = bus_log.Access; /// How fast the machine counts, for whoever paces or records it. pub const cycles_per_second: u64 = clock_hz; bus: bus_log.Log(options.bus_log) = .{}, /// Every bank the machine could have, of which `banks` are /// fitted. The S-bank is the highest one fitted. ram: [max_memory]u8 = undefined, banks: u8 = 4, rom: [rom_size]u8 = undefined, /// The D VIA, whose port A is the environment register and /// port B the zero-page register, and the E VIA, whose port /// A is the bank register and port B the sound DAC. vias: [2]via.Via = .{ .{}, .{} }, /// The enhanced-addressing latch: the X-byte the board /// picked up when a pointer was read off zero page, if its /// top bit was set, until the next opcode fetch. indirect: ?u8 = null, /// Whether the next read is an opcode fetch, which arms /// nothing. fetching: bool = false, video: VideoMode = .{}, smooth_scroll: bool = false, character_download: bool = false, /// The character generator, which is RAM: 128 shapes of eight /// rows, with nothing in it at power on. The ROM loads its /// font through the download cells before it prints, and SOS /// loads its own. A row's low seven bits are the dots, the /// leftmost in bit 0; its top bit marks a row that flashes /// when the character is inverse (MAME Development Team, /// n.d.). charset: [128][8]u8 = @splat(@splat(0)), /// What the keyboard encoder last put out: the key's code at /// `$C000` and the modifiers at `$C008`. The encoder does not /// apply shift itself to a letter — the code for the D key is /// `$44` shifted or not, and `$04` with control — and reports /// shift, control, alpha lock and the two Apple keys in the /// modifier byte, active low, with bit 1 shift the other way /// up and bit 7 marking a "special" key that the console /// driver passes through untransformed: space, return, /// escape, tab, the arrows. Apple's own table of "Keys and /// their Associated ASCII Codes" has it so — A alone `$C1`, /// with shift `$C1`, with control `$81`; 1 alone `$B1`, with /// shift `$A1` (Apple Computer, Inc., 1982c, p. 8.10) — and /// the console driver's handler reads the modifiers (1983a, /// p. 11). It is the driver's transform table that turns `$44` /// into `d` or `D`. keyboard: u8 = 0, modifiers: u8 = modifiers_idle, /// How many times the key latch has been read with nothing /// in it since a key was last pressed. Software that polls /// for its keys, as the Apple II emulation's II Plus ROM /// does, is given a key only once it is sitting in a read /// loop; see `takesKeysByInterrupt` for SOS, which is not. empty_polls: u16 = 0, strobe: bool = false, /// The speaker's one-bit line, toggled by an access to `$C030` /// — "one-bit square-wave generator", one of the "three /// different audio generators" (Apple Computer, Inc., 1981a, /// p. 154) — logged like a II's speaker, as is the beep. speaker: bool = false, /// The "fixed-frequency beep generator" (same page), which an /// access to `$C040` starts and which then rings on its own: /// "A reference to location 49216 (or the equivalent addresses /// -16336 or hexadecimal $C040) will cause a 0.1 second 1 KHz /// tone to be produced ... only 1 microsecond is required to /// start the BELL sound" (Apple Computer, Inc., 1982c, /// p. 10.3); SOS's `LDA $C040 ; SOUND BELL` is that one /// access. How many edges of the speaker line are still to /// come, and when the next is. beep_edges: u16 = 0, beep_edge: u64 = 0, speaker_log: speaker.Log(options.speaker_log) = .{}, /// The six-bit sound DAC, the last of the machine's "three /// different audio generators" (Apple Computer, Inc., 1981a, /// p. 154): "bits 0-5: 6-bit audio DAC output" of the E VIA's /// port B (MAME Development Team, n.d.), which the service /// manual calls the sound register (1982c, p. 3.15). A /// program drives it to a value between 0 and 63, and the /// waveform it plays is the succession of values; the log /// keeps them for a recording, the one cone summing the DAC /// and the one-bit speaker beside it. dac_log: speaker.LevelLog(options.speaker_log) = .{}, /// The built-in disk controller: the Disk II's state machine, /// whose PROM is byte for byte the Disk II's P6, with the /// internal drive on the first connector and the first /// external one on the second. It keeps time by `diskCycles`, /// the 1 MHz count it was built for, so its timing is the /// Disk II's own. disk: disk2.Controller = .{}, /// The built-in serial port, a 6551. acia: serial.Acia = .{ .cycles_per_second = cycles_per_second }, /// The clock chip, at `$C070` to `$C07F`, whose five address /// lines are the low bits of the zero-page register — "Port /// B: Zero page high 8 address bits, also MM58167 RTC /// register select" (MAME Development Team, n.d.) — so SOS /// moves its zero page to name a register: `LDX #CRESET; STX /// Z.REG; ... STA CLOCK` (Apple Computer, Inc., 1982b, /// p. 328). Not fitted unless asked for: Apple left the /// socket empty in most of the machines it sold, and SOS /// finds out by reading the status register, whose top bit /// an empty socket leaves to the floating bus. clock: mm58167.Mm58167 = .{ .cycles_per_second = clock_hz }, /// The two joystick ports' analog inputs and switches. The /// A/D converter is a ramp the software times: SOS's /// `AD.READ` selects an input with the three pairs of /// switches at `$C058`, `$C05E` and `$C05A`, charges the /// capacitor with `AD.CHRG` at `$C05C`, waits, starts the /// timeout with `AD.STRT` at `$C05D`, and measures how long /// `AD.FLAG` at `$C066` stays negative against the D VIA's /// second timer, loaded with 360 and counting at 2 MHz; the /// ROM's `ANALOG` at `$F4A8` returns the timer's high byte /// when the flag drops, and that is the eight-bit result /// (Apple Computer, Inc., 1982b, `SOS.UMGR.SRC`, JOYSTICK). /// So an input's value is the time its flag stays up. Null /// is nothing plugged in, whose capacitor discharges at once. analog: [8]?u8 = @splat(null), analog_select: u3 = 0, /// The cycle the flag drops, while a conversion is timing. conversion_ends: ?u64 = null, /// The four switches at `$C060` to `$C063`: port B's switch /// 1, port A's switch 0, port B's switch 0, port A's switch 1, /// in that order, each read in bit 7. switches: [4]bool = @splat(false), /// The ProFile on its interface card in slot 4, when /// `--hard-disk` puts one there; see `profile.zig` for the /// card and the drive, and `read8` for the pseudo-DMA that /// moves its blocks. profile: profile.Card = .{}, /// A Universal Parallel Interface Card, which is the other /// card this machine has anywhere to put. upic: upic_module.Card = .{}, /// Which of the four slots holds what, indexed by slot number. /// Index 0 is not a slot and is always empty. cards: [last_slot + 1]SlotCard = @splat(.empty), /// What was last on the data bus, which is what an address /// nothing decodes reads as: the operand byte just fetched, /// for a load from an absolute address. The boot block counts /// on it being something other than the zero it just stored. floating: u8 = 0, /// Whether the beam is in vertical blanking, and the cycle it /// next stops or starts being. The blanking goes to the E /// VIA's CB1 and CB2 lines, which is what the ROM waits on: /// "VWAIT BIT CB2INT ; WAIT FOR RETRACE" (Apple Computer, /// Inc., 1980, p. 16). The wiring is MAME's reading of the /// schematic; the ROM's own equates name the register. blanking: bool = false, blank_edge: u64 = visible_cycles, inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("memory", self)); } pub fn init(self: *Self, memory_size: ?usize) void { self.* = .{ .ram = @splat(0), .rom = @splat(0), }; if (memory_size) |bytes| self.fitMemory(bytes) catch {}; } /// Fits the machine's RAM: 128K, 256K or 512K, in whole /// banks. "The current Apple III hardware supports up to /// eight banks, or 256K bytes"; SOS "can support up to 16" /// (Apple Computer, Inc., 1982a, p. 10). pub fn fitMemory(self: *Self, bytes: usize) error{NotAConfiguration}!void { self.banks = switch (bytes) { 4 * bank_size => 4, 8 * bank_size => 8, 16 * bank_size => 16, else => return error.NotAConfiguration, }; } /// The reset line reaches the VIAs, and through them the /// machine's registers: a 6522 comes up with every line an /// input, and an input with nothing driving it reads high, so /// the environment register reads $FF — 1 MHz, I/O on, video /// on, the ROM in — which is how the ROM comes to be running /// at all, and the zero-page register reads $FF too until the /// ROM sets it (MAME Development Team, n.d., reads the same). /// The five-and-a-quarter drives, reached the same way on /// every machine that has any. A IIc puts an IWM in front of /// its pair and answers this from inside that; here the /// controller is the whole of the port, so this is simply it. pub inline fn drives(self: *Self) *disk2.Controller { return &self.disk; } /// No three-and-a-half inch drive: only a IIc Plus has one. /// Here so that a front end generic over every machine can ask. /// No intelligent drive here either; see `apple2e.zig`. pub inline fn unidisk(_: *Self) ?*@import("../unidisk.zig").Chain { return null; } pub inline fn disks35(_: *Self) ?*disk35.Controller { return null; } pub fn reset(self: *Self) void { const cycle = self.getCPU().clock.cycles; for (&self.vias) |*chip| chip.reset(cycle / 2); self.indirect = null; self.fetching = false; self.video = .{}; self.smooth_scroll = false; self.character_download = false; self.strobe = false; self.disk.reset(); self.acia.reset(); self.profile.resetCard(); self.blanking = false; self.blank_edge = cycle + visible_cycles; self.getCPU().irq = false; } /// Lays the 4K ROM at `$F000`. A longer image keeps its tail. pub fn loadROMAtEnd(self: *Self, image: []const u8) !void { if (image.len == 0) return error.Empty; const take = @min(image.len, rom_size); @memset(&self.rom, 0); @memcpy(self.rom[rom_size - take ..], image[image.len - take ..]); } pub fn loadProgram(self: *Self, location: u16, program: []const u8) !void { for (program, 0..) |byte, i| { const at = @as(usize, location) + i; if (at > 0xffff) return error.Overflow; self.poke(@intCast(at), byte); } } // ---------------------------------------------------------- // The registers, read off the VIAs' ports. /// What a VIA port's lines are at: what was written where the /// line is an output, and high where it is an input with /// nothing on it. fn portLines(self: *const Self, chip: u1, port: u1) u8 { return self.vias[chip].pins(port); } pub fn environment(self: *const Self) u8 { return self.portLines(0, 0); } pub fn zeroPage(self: *const Self) u8 { return self.portLines(0, 1); } pub fn bankRegister(self: *const Self) u8 { return self.portLines(1, 0); } /// The bank in the window: the register's low four bits. The /// S-bank is never one of them — "the X-byte can range from /// $80 (banks 0 and 1) to $8m (bank m), where m is the number /// of the highest bank: $2 for a 128K system; $6 for a 256K /// system; or $E for a 512K system" (Apple Computer, Inc., /// 1982a, p. 17) — and $F, the S-bank's own number, "pairs /// the S-bank with bank $0", so it is bank 0 that shows in the /// window. A number above the highest fitted selects RAM that /// is not there, and decodes nothing: null. SOS's boot block /// sizes the machine by writing to bank 14 and to bank 6 and /// reading back, and then counting down from bank 7 until a /// zero it stores comes back as a zero; a machine that /// answered for every bank number would be taken for 512K. fn currentBank(self: *const Self) ?u8 { const n = self.bankRegister() & 0x0f; if (n == 0x0f) return 0; if (n < self.banks - 1) return n; return null; } // ---------------------------------------------------------- // Where things are. /// The physical byte for an address in bank `bank`, taken as /// 32K of address space starting at `$2000`. fn inBank(self: *Self, bank: u8, offset: u16) *u8 { return &self.ram[@as(usize, bank % self.banks) * bank_size + offset]; } /// The S-bank's physical home: the last bank fitted. Its low /// 8K is `$0000` to `$1FFF` and the rest `$A000` to `$FFFF`. fn inSBank(self: *Self, address: u16) *u8 { const s: u8 = self.banks - 1; return if (address < 0x2000) self.inBank(s, address) else self.inBank(s, address - 0x8000); } /// The physical byte of a whole page, by page number, in the /// arrangement the zero-page register uses: pages below $20 /// are the S-bank's bottom, pages from $A0 its top, and the /// rest are the current bank. fn inPage(self: *Self, page: u8, low: u8) ?*u8 { const address = @as(u16, page) << 8 | low; if (page < 0x20 or page >= 0xa0) return self.inSBank(address); return self.inBank(self.currentBank() orelse return null, address - 0x2000); } /// The page the stack is on: the primary page one, or the /// page beside the zero page (MAME Development Team, n.d.: `Z ^ 1`). fn stackPage(self: *const Self) u8 { if (self.environment() & Environment.primary_stack != 0) return 0x01; return self.zeroPage() ^ 0x01; } /// The extension page, four below the zero page: $16 for $1A, /// $14 for $18 (MAME Development Team, n.d.: `Z ^ $0C`). fn extensionPage(self: *const Self) u8 { return self.zeroPage() ^ 0x0c; } /// Whether the address is I/O rather than RAM right now. /// With the I/O space switched in, `$C000` to `$C0FF` is the /// machine's own I/O, `$C100` to `$C4FF` the windows of the /// four slots' ROMs and `$C800` to `$CFFF` the expansion ROM /// of whichever card claimed it — and "Addresses C500 to /// C7FF are always Ram, regardless of the setting of the I/O /// enable bit" (Apple Computer, Inc., 1982c, p. 7.1). Apple's /// Apple II emulation /// counts on that: it keeps a Disk II boot routine at `$C600` /// for `PR#6` to find, where a II Plus has the card's PROM. fn isIO(self: *const Self, address: u16) bool { if (address < 0xc000 or address >= 0xd000) return false; if (address >= 0xc500 and address < 0xc800) return false; return self.environment() & Environment.io != 0; } /// Whether the address is one of the VIAs' sixteen. fn isVia(self: *const Self, address: u16) bool { _ = self; return address >= 0xffd0 and address <= 0xffef; } /// The RAM behind an address, for the plain map: no I/O, no /// ROM, no enhanced addressing. Null where there is none. fn plainRam(self: *Self, address: u16) ?*u8 { return switch (address) { 0x0000...0x00ff => self.inPage(self.zeroPage(), @truncate(address)), 0x0100...0x01ff => self.inPage(self.stackPage(), @truncate(address)), 0x0200...0x1fff => self.inSBank(address), 0x2000...0x9fff => self.inBank(self.currentBank() orelse return null, address - 0x2000), 0xa000...0xffff => self.inSBank(address), }; } /// Where an enhanced indirect access lands: the X-byte's bank /// pair, laid end to end so that an address above $7FFF is in /// the second bank of the pair — or, for $8F, the S-bank with /// bank 0 in the window (Apple Computer, Inc., 1982a, p. 14). /// A bank that is not fitted decodes nothing, and so does the /// S-bank's own number: "the highest bank pair is not really /// a pair: it ends at $8m:7FFF, and higher addresses will /// produce undefined results" (p. 17). fn inPair(self: *Self, xbyte: u8, address: u16) ?*u8 { const pair = xbyte & 0x0f; if (pair == 0x0f) { if (address < 0x2000 or address >= 0xa000) return self.inSBank(address); return self.inBank(0, address - 0x2000); } const bank = pair + @as(u8, if (address >= 0x8000) 1 else 0); if (bank >= self.banks - 1) return null; return self.inBank(bank, address & 0x7fff); } // ---------------------------------------------------------- // The processor's accesses. /// The SYNC line: an opcode is about to be fetched. Whatever /// the extension latch held was for the instruction just done. pub fn sync(self: *Self) void { self.indirect = null; self.fetching = true; } /// Puts a disk on the ProFile card's cable, or takes it off: /// the front end's `--hard-disk`, which on a III is a ProFile /// in slot 4. The card has one cable, so only drive 0 is one. pub fn insertVolume(self: *Self, which: u1, volume: ?*blockdevice.Volume) void { if (which != 0) return; self.profile.volume = volume; // A volume arriving means the card is in the machine, and // it goes where the ProFile's manual says unless somebody // has already put it somewhere else. Taking the volume // away takes the card out with it: an interface card with // no drive on the end of its cable is not what any of this // is for, and SOS finding one would be worse than SOS // finding nothing. if (volume == null) { if (self.slotOf(.profile)) |slot| self.cards[slot] = .empty; } else if (self.slotOf(.profile) == null) { self.cards[default_profile_slot] = .profile; } } /// The VIAs' idea of the time. Their clock pin "is the /// system PRE1M (PRE-1 MHZ) clock which operates at 1MHZ" /// (Apple Computer, Inc., 1982c, p. 3.1), so their timers /// count at half the processor's fast rate whatever the /// processor is doing, and SOS's arithmetic on them — the /// joystick's 360 counts, for one — is in those units. pub fn viaCycles(self: *Self) u64 { return self.getCPU().clock.cycles / 2; } /// The disk controller's idea of the time. Its state machine /// is the Disk II's and runs at the Disk II's 1 MHz — the /// environment register's top bit exists to hold the processor /// to that rate while it talks to it — so it is handed half /// the 2 MHz count, and every figure in `disk2` stays true. pub fn diskCycles(self: *Self) u64 { return self.getCPU().clock.cycles / 2; } /// Spends the access's time. Two cycles of the 2 MHz count in /// the slow state; otherwise one, unless the screen has the /// other one. "The display is memory mapped, the Screen /// timeshares the RAM on the opposite phase of the processor /// clock. Both the screen and the processor are running at a /// 1MHz rate, which means that the RAM is running at a 2MHz /// rate. One new feature of the Apple /// is that the /// processor is able to make use of the other phase while /// the screen is off. In other words, any time the screen is /// off, the processor may run at a full 2MHz rate" (Apple /// Computer, Inc., 1982c, p. 2.4). The screen is off for the /// fifty cycles of each line's horizontal blanking, and /// altogether when the environment register has switched the /// video off; it goes on fetching through the displayed part /// of the blanked lines as of the others, which is what makes /// the sum come to the "approximately 1.4 MHz" SOS promises /// with the display on (1982a, p. 18) — 1.385, against 1.55 if /// the vertical blanking were free too. The beam /// moves with the clock, and when it crosses into or out of /// the vertical blanking the VIA hears about it. fn spend(self: *Self) void { const slow = self.environment() & Environment.slow != 0; const clock = &self.getCPU().clock; clock.sleep(if (slow or self.screenFetching()) 2 else 1); while (clock.cycles >= self.blank_edge) self.crossBlankEdge(); while (self.beep_edges > 0 and clock.cycles >= self.beep_edge) { self.speaker = !self.speaker; self.speaker_log.record(self.beep_edge); self.beep_edge += beep_half_period; self.beep_edges -= 1; } } /// Whether the screen is taking its memory cycles now: the /// video is on and the beam is in the eighty of a line's 130 /// cycles that show, not the fifty of the horizontal blanking. fn screenFetching(self: *Self) bool { if (self.environment() & Environment.video == 0) return false; // `blank_edge` sits on a line boundary, so the cycles left // to it say where in the line the beam is. const to_blank = self.blank_edge - self.getCPU().clock.cycles; const remaining_in_line = to_blank % cycles_per_line; const position = (cycles_per_line - remaining_in_line) % cycles_per_line; return position < active_cycles_per_line; } /// The beam has reached the end of the picture or the top of /// the next one. fn crossBlankEdge(self: *Self) void { self.blanking = !self.blanking; self.blank_edge += if (self.blanking) blanking_cycles else visible_cycles; self.vias[1].setLine(.cb1, self.blanking); self.vias[1].setLine(.cb2, self.blanking); self.updateInterrupt(); // The download the console driver set up during the // picture is taken as the blanking ends (MAME Development // Team, n.d., does it at the end of VBL too). if (!self.blanking and self.character_download) self.downloadCharacters(); } /// The character download: eight "cells" in the screen holes /// of the two text pages, each holding one character's code /// and its eight rows. The layout is the console driver's /// `LOADCHR` (Apple Computer, Inc., 1983a, p. 40): for cell c /// and row y, the code is at page `$08 | (c >> 2) << 1 | /// (y >= 4)`, offset `DCPTRL[y] | (c & 3)` with `DCPTRL` = /// `$78 $7C $F8 $FC` repeated, and the image row at the same /// offset in that page `^ $0C` — the `$0400` page's holes. fn downloadCharacters(self: *Self) void { const dcptrl = [8]u8{ 0x78, 0x7c, 0xf8, 0xfc, 0x78, 0x7c, 0xf8, 0xfc }; for (0..8) |cell| { for (0..8) |row| { const page: u16 = 0x08 | @as(u16, @intCast(cell >> 2)) << 1 | @intFromBool(row >= 4); const low: u16 = dcptrl[row] | @as(u16, @intCast(cell & 3)); const code = self.inSBank(page << 8 | low).* & 0x7f; const image = self.inSBank((page ^ 0x0c) << 8 | low).*; self.charset[code][row] = image; } } } /// The dots of one row of a character on the screen: the /// shape from the downloaded set, inverted for a character /// whose top bit is clear — every row of it, or only its /// flashing rows in the flash clock's other phase (MAME /// Development Team, n.d.). pub fn glyphRow(self: *const Self, byte: u8, line: u3, flash: bool) u7 { const row = self.charset[byte & 0x7f][line]; const dots: u7 = @truncate(row); const inverse = byte & 0x80 == 0 and (row & 0x80 == 0 or flash); return if (inverse) ~dots else dots; } /// Whether anything is pulling the interrupt line: either /// VIA, or the serial port. Worked out from all of them, so /// that one letting go does not silence another. fn updateInterrupt(self: *Self) void { // The clock chip's interrupt output is the E VIA's CA1 // (MAME Development Team, n.d.; SOS's own table has "E.CA1 // -- CLOCK", Apple Computer, Inc., 1982b, p. 152). self.vias[1].setLine(.ca1, self.clock.fitted and self.clock.interrupting()); const irq = self.vias[0].interrupting() or self.vias[1].interrupting() or self.acia.interrupting(self.getCPU().clock.cycles); self.getCPU().irq = irq; // The line is also readable, on the top bit of the E // VIA's port A: "bit 7: IRQ status (in) (0 = IRQ, 1 = no // IRQ)" (MAME Development Team, n.d.). self.vias[1].setInputs(0, 0x80, if (irq) 0x00 else 0x80); } /// A data read of zero page arms the extension: the board /// picks up the byte at the same offset in the extension /// page, and if its top bit is set the accesses that follow, /// above the zero page and stack, go where it says. Only with /// the zero page at $18 to $1F, which is where SOS and an /// interpreter keep theirs (MAME Development Team, n.d., is the reading of the logic followed here). fn armExtension(self: *Self, low: u8) void { if (self.fetching) return; const z = self.zeroPage(); if (z < 0x18 or z > 0x1f) return; const xbyte = (self.inPage(self.extensionPage(), low) orelse return).* & 0x8f; self.indirect = if (xbyte & 0x80 != 0) xbyte else null; } fn ramFor(self: *Self, address: u16, writing: bool) ?*u8 { if (self.indirect) |xbyte| { if (address >= 0x100) return self.inPair(xbyte, address); } if (address < 0x100 and !writing) self.armExtension(@truncate(address)); return self.plainRam(address); } pub fn read(self: *Self, comptime T: type, address: u16) T { const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { self.spend(); const value = self.read8(address); self.fetching = false; self.floating = value; self.bus.record(address, value, .read); return value; }, 16 => { const low = self.read(u8, address); const high = self.read(u8, address +% 1); return @as(u16, high) << 8 | low; }, else => @compileError("must be a u8 or a u16"), } } fn read8(self: *Self, address: u16) u8 { if (self.indirect == null) { if (self.isIO(address)) return self.readIO(address); // The ProFile card's pseudo-DMA. SOS's driver holds the // processor to 1 MHz on a 2 MHz memory system and runs // it through the ROM's page of `SBC #1 / BEQ` at $F800, // and the card uses the memory slot each fetch leaves // free to move one byte between the drive and the // page the zero-page register names, at the offset // the processor is fetching. That is why the driver // sets Z_REG to the buffer's page and the bank register // to its bank before the call (Apple Computer, Inc., // 1983b, pp. 14, 19), and why it saves bytes 0 and $FE // of that page first: the taken branch out reads a // false address in the page, forward to $F900 or back // to $F7FE, and the card moves a byte for that too. if (address >= 0xf800 and address < 0xf900 and self.profile.transferring()) { if (self.inPage(self.zeroPage(), @truncate(address))) |cell| { if (self.profile.transferringOut()) cell.* = self.profile.readPort() else self.profile.writePort(cell.*); } } if (self.isVia(address)) { const chip: u1 = if (address < 0xffe0) 0 else 1; // D VIA at $FFD0, E VIA at $FFE0 return self.vias[chip].read(@enumFromInt(@as(u4, @truncate(address))), self.viaCycles()); } // The ROM, when it is switched in — except at $FFC0 to // $FFCF, which are always RAM, and the VIAs' sixteen // addresses, which are RAM when the VIAs are hidden // (MAME Development Team, n.d.). if (address >= rom_base and self.environment() & Environment.rom != 0 and !(address >= 0xffc0 and address <= 0xffef)) { return self.rom[address - rom_base]; } } // Nothing answers: the bus keeps what was last on it. return (self.ramFor(address, false) orelse return self.floating).*; } pub fn write(self: *Self, comptime T: type, address: u16, value: T) void { const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { self.spend(); self.fetching = false; self.floating = value; self.bus.record(address, value, .write); self.write8(address, value); }, 16 => { self.write(u8, address, @truncate(value)); self.write(u8, address +% 1, @truncate(value >> 8)); }, else => @compileError("must be a u8 or a u16"), } } fn write8(self: *Self, address: u16, value: u8) void { if (self.indirect == null) { if (self.isIO(address)) return self.writeIO(address, value); if (self.isVia(address)) { const chip: u1 = if (address < 0xffe0) 0 else 1; // D VIA at $FFD0, E VIA at $FFE0 self.vias[chip].write(@enumFromInt(@as(u4, @truncate(address))), value, self.viaCycles()); self.updateInterrupt(); // The E VIA's port B is the sound DAC; log where // it stands after a write that could have moved it. if (chip == 1) self.recordDac(); return; } // The ROM is never written, and with the S-bank's top // protected neither is the RAM under it. if (address >= 0xc000 and self.environment() & Environment.write_protect != 0) return; } const target = self.ramFor(address, true) orelse return; target.* = value; } // ---------------------------------------------------------- // The I/O page, `$C000` to `$C0FF`, from SOS's equates // (Apple Computer, Inc., 1982b) and the console driver. fn readIO(self: *Self, address: u16) u8 { // The slots' ROM windows and the expansion space. The // ProFile card's control latch is what reading its slot's // window does — the driver reads `$CN00` plus a code — // and no other card is fitted, so the rest is the bus. if (address >= 0xc100) { self.slotFirmware(address); return self.floating; } const which: u8 = @truncate(address); switch (which) { // The keyboard: the key with the strobe above it, and // the modifier keys with the strobe in the low bit. 0x00...0x07 => { if (!self.strobe) self.empty_polls +|= 1; return self.keyboard | @as(u8, if (self.strobe) 0x80 else 0); }, 0x08...0x0f => return self.modifiers | @as(u8, if (self.strobe) 0x01 else 0), 0x10...0x1f => { self.strobe = false; return self.keyboard; }, 0x30...0x3f => { self.toggleSpeaker(); return 0; }, 0x40...0x4d => { self.startBeep(); return 0; }, 0x50...0x57 => { self.setVideoMode(which); return 0; }, // The A/D converter's controls, read or written: // three select bits, the charge and the start. 0x58...0x5f => { self.analogControl(which); return 0; }, // The joystick switches, and the slot interrupt // lines, which read high for "no interrupt". 0x60...0x63, 0x68...0x6b => return if (self.switches[which & 3]) 0x80 else 0, 0x64, 0x65, 0x6c, 0x6d => return 0x80, // The A/D flag: up while the ramp is still timing. 0x66, 0x6e => return if (self.converting()) 0x80 else 0, // The clock chip's registers, one register behind all // sixteen addresses, the zero-page register saying // which. With no chip in the socket nothing answers // and the bus floats, which is how SOS tells: the // high byte of the address it just fetched has its // top bit set, and "DOES CLOCK EXIST? ... BMI" says // no. // on the machines Apple shipped after the first ones. 0x70...0x7f => { if (!self.clock.fitted) return self.floating; const value = self.clock.read(@enumFromInt(@as(u5, @truncate(self.zeroPage()))), self.getCPU().clock.cycles); self.updateInterrupt(); return value; }, 0xd8, 0xd9 => { self.smooth_scroll = which & 1 != 0; return 0; }, 0xda, 0xdb => { self.character_download = which & 1 != 0; return 0; }, // The four slots' sixteen device select addresses // each, at `$c080 + s0` the way an Apple II lays them // out: slot 1 at `$c090` through slot 4 at `$c0c0`. // An empty slot floats, because there is nothing in it // to drive the bus. 0x90...0xcf => return self.slotAccess(which, false, 0) orelse self.floating, 0xe0...0xef => return self.disk.access(@truncate(which), false, 0, self.diskCycles()), 0xf0...0xf3 => return self.acia.read(@enumFromInt(@as(u2, @truncate(which))), self.getCPU().clock.cycles), else => return 0, } } fn writeIO(self: *Self, address: u16, value: u8) void { if (address >= 0xc100) { self.slotFirmware(address); return; } const which: u8 = @truncate(address); switch (which) { 0x10...0x1f => self.strobe = false, 0x30...0x3f => self.toggleSpeaker(), 0x40...0x4d => self.startBeep(), 0x50...0x57 => self.setVideoMode(which), 0x58...0x5f => self.analogControl(which), 0xd8, 0xd9 => self.smooth_scroll = which & 1 != 0, 0xda, 0xdb => self.character_download = which & 1 != 0, 0x70...0x7f => if (self.clock.fitted) { self.clock.write(@enumFromInt(@as(u5, @truncate(self.zeroPage()))), value, self.getCPU().clock.cycles); self.updateInterrupt(); }, 0x90...0xcf => _ = self.slotAccess(which, true, value), 0xe0...0xef => _ = self.disk.access(@truncate(which), true, value, self.diskCycles()), 0xf0...0xf3 => self.acia.write(@enumFromInt(@as(u2, @truncate(which))), value, self.getCPU().clock.cycles), else => {}, } } /// One of the four slots' device select addresses, `$c090` /// to `$c0cf`. Null where nothing in the slot drove the bus. fn slotAccess(self: *Self, which: u8, is_write: bool, value: u8) ?u8 { const slot: u3 = @truncate((which -% 0x80) >> 4); const offset: u4 = @truncate(which); return switch (self.cards[slot]) { .empty => null, // The ProFile's interface card: two ports and a status // register, and the rest of its sixteen drive nothing. .profile => switch (offset) { 0x0 => taken: { if (is_write) self.profile.writePort(value); break :taken 0; }, 0x1 => if (is_write) 0 else self.profile.readPort(), 0x2 => if (is_write) 0 else self.profile.statusRegister(), 0x3 => taken: { self.profile.clearParity(); break :taken 0; }, else => 0, }, .upic => self.upic.access(offset, is_write, value), }; } /// A touch of a slot's firmware page, `$Cs00` to `$CsFF`. /// /// Neither of this machine's cards has a ROM this reads: what /// they have there is a side effect. The ProFile's card puts /// its control latch under the window -- the driver reads /// `$Cn00` plus a code -- and touching the UPIC's turns its /// autostrobe on. fn slotFirmware(self: *Self, address: u16) void { const slot: u3 = @truncate(address >> 8); if (slot < first_slot or slot > last_slot) return; switch (self.cards[slot]) { .empty => {}, .profile => self.profile.control(@truncate(address)), .upic => self.upic.touchFirmware(), } } /// Fits a Universal Parallel Interface Card and gives it /// somewhere to print, which is what `--parallel-out` does. /// /// Slot 1 by default, which is only a convention: this /// machine's slots are all alike and SOS is told which one the /// card is in. pub fn fitPrinter(self: *Self, slot: u3, out: ?*std.Io.Writer) void { self.fitCard(slot, .upic) catch return; self.upic = .{ .out = out }; } /// Puts a card in one of the four slots, or takes one out. /// /// A card can go in any of them, because on this machine which /// slot a card is in is something SOS is told rather than /// something the hardware decides -- see `default_profile_slot`. pub fn fitCard(self: *Self, slot: u3, card: SlotCard) error{NotASlot}!void { if (slot < first_slot or slot > last_slot) return error.NotASlot; self.cards[slot] = card; } /// Which slot holds a given kind of card, if any does. pub fn slotOf(self: *const Self, card: SlotCard) ?u3 { for (first_slot..last_slot + 1) |slot| { if (self.cards[slot] == card) return @intCast(slot); } return null; } /// `$C058` to `$C05F`: the even address clears and the odd /// sets, `$C058`/`$C059` select bit 0, `$C05A`/`$C05B` bit 2 /// and `$C05E`/`$C05F` bit 1 — `AD.SEL0 $C058`, `AD.SEL1 /// $C05E`, `AD.SEL2 $C05A` — while `$C05C` charges the /// capacitor and `$C05D` starts the timeout. fn analogControl(self: *Self, which: u8) void { const on = which & 1 != 0; switch (which & 0xfe) { 0x58 => self.analog_select = (self.analog_select & ~@as(u3, 1)) | @intFromBool(on), 0x5a => self.analog_select = (self.analog_select & ~@as(u3, 4)) | @as(u3, @intFromBool(on)) << 2, 0x5e => self.analog_select = (self.analog_select & ~@as(u3, 2)) | @as(u3, @intFromBool(on)) << 1, 0x5c => if (on) { self.conversion_ends = self.getCPU().clock.cycles + self.conversionCycles(); } else { self.conversion_ends = null; }, else => {}, } } fn converting(self: *Self) bool { const ends = self.conversion_ends orelse return false; return self.getCPU().clock.cycles < ends; } /// How long the flag stays up for the input selected: the /// time that makes SOS's arithmetic come out at the value. /// The D VIA's timer starts at 360 and counts at the VIAs' /// 1 MHz, and the result is its high byte when the flag /// drops, so a value V of two or more is a drop just short of /// 360 + 256 × (256 − V) microseconds, 1 is a drop inside the /// first 104, and 0 one between 104 and 360. Nothing plugged /// in drops at once. It is "a ramp type Analog to Digital /// converter (A/D)" whose values "must be interpreted by the /// program" (Apple Computer, Inc., 1982c, p. 7.5), and this /// is the interpretation SOS puts on it. fn conversionCycles(self: *const Self) u64 { const value = self.analog[self.analog_select] orelse return 4; const microseconds: u64 = switch (value) { 0 => 232, 1 => 50, else => 360 + 256 * (256 - @as(u64, value)) - 128, }; return microseconds * (clock_hz / 1_000_000); } /// Plugs a value into one of the eight analog inputs, or /// pulls it out: port B's X and Y are inputs 0 and 1, port /// A's 2 and 3, as SOS's JOYSTICK call reads them. pub fn setAnalog(self: *Self, input: u3, value: ?u8) void { self.analog[input] = value; } /// Presses or releases one of the four switches, in the /// order they sit at `$C060` to `$C063`. pub fn setButton(self: *Self, which: u2, down: bool) void { self.switches[which] = down; } /// The DAC's level now, from the low six bits the E VIA's port /// B drives, mapped to [0, 1]; a constant is filtered out in /// the rendering, so where the zero sits does not matter. fn recordDac(self: *Self) void { const value: u8 = self.vias[1].pins(1) & 0x3f; self.dac_log.record(self.getCPU().clock.cycles, @as(f32, @floatFromInt(value)) / 63.0); } fn toggleSpeaker(self: *Self) void { self.speaker = !self.speaker; self.speaker_log.record(self.getCPU().clock.cycles); } /// Starts the beep, or starts it over if it is ringing. fn startBeep(self: *Self) void { self.beep_edges = beep_edge_count; self.beep_edge = self.getCPU().clock.cycles; } fn setVideoMode(self: *Self, which: u8) void { const on = which & 1 != 0; switch ((which - 0x50) >> 1) { 0 => self.video.vm0 = on, 1 => self.video.vm1 = on, 2 => self.video.vm2 = on, 3 => self.video.vm3 = on, else => unreachable, } } // ---------------------------------------------------------- // Reading and writing without the processor. pub fn peek(self: *Self, address: u16) u8 { if (self.isIO(address)) return 0; if (address >= rom_base and self.environment() & Environment.rom != 0 and !(address >= 0xffc0 and address <= 0xffef)) { return self.rom[address - rom_base]; } return (self.plainRam(address) orelse return self.floating).*; } pub fn poke(self: *Self, address: u16, value: u8) void { if (self.isIO(address)) return; (self.plainRam(address) orelse return).* = value; } // ---------------------------------------------------------- // The keyboard. pub fn pressKey(self: *Self, character: u8) void { var code = character & 0x7f; var modifiers: u8 = modifiers_idle; switch (code) { 'a'...'z' => code -= 0x20, 'A'...'Z' => modifiers |= 0x02, // The symbols on the upper half of a key. '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '"', '<', '>', '?', '~' => modifiers |= 0x02, // Keys of their own rather than control and a letter. ' ', '\r', 0x1b, '\t', 0x08, 0x0a, 0x0b, 0x15, 0x7f => modifiers |= 0x80, 0x01...0x07, 0x0c, 0x0e...0x14, 0x16...0x1a => modifiers &= ~@as(u8, 0x04), else => {}, } self.keyboard = code; self.modifiers = modifiers; self.strobe = true; self.empty_polls = 0; // The keyboard's data-ready line is the E VIA's CA2, and // SOS reads a key on the interrupt it raises rather than // by polling: its console driver enables CA2 and its // handler reads the ports and clears the flag and strobe // (Apple Computer, Inc., 1983a, p. 11). The line pulses // for a key, so whichever edge is asked for arrives (MAME // Development Team, n.d., wires and pulses it the same). self.vias[1].setLine(.ca2, true); self.vias[1].setLine(.ca2, false); self.updateInterrupt(); } /// Whether the software running takes its keys on the /// interrupt the encoder raises rather than by polling: SOS's /// console driver enables the E VIA's CA2 and queues what /// arrives, so a key can be handed over the moment the strobe /// is clear, with no read loop to wait for. The Apple II /// emulation's ROM polls, and leaves the line disabled. pub fn takesKeysByInterrupt(self: *const Self) bool { return self.vias[1].ier & via.irq_ca2 != 0; } // ---------------------------------------------------------- // The display, as the screen-drawing code asks about it. /// Which of the seven modes the four switches make (MAME /// Development Team, n.d., is the reading of them followed /// here): text in forty columns, or eighty when VM1 is set; /// with VM3 set, graphics — 280 by 192, or 560 by 192 with /// VM1 — each in black and white or, with VM0, in colour, /// which `colourBurst` says. The colour text mode is forty /// columns with VM0, and `textColour` says what each /// character is coloured. pub fn mode(self: *const Self) screen.Mode { const v = self.video; if (!v.vm3) return if (v.vm1) .text_80 else .text; return if (v.vm1) .double_high_resolution else .high_resolution; } pub fn columns(self: *const Self) u16 { return if (self.video.vm1 and !self.video.vm3) 80 else 40; } /// The text page: `$0400`, or `$0800` with VM2 set, in the /// S-bank. pub fn displayPage(self: *const Self) u16 { return if (self.video.vm2) 0x0800 else 0x0400; } /// The graphics page: bank 0's `$2000`, or its `$4000` with /// VM2 set; the drawer is handed `$2000` and the pages are /// resolved in `videoByte`. pub fn hiresPage(self: *const Self) u16 { _ = self; return 0x2000; } /// What the video circuitry reads. Text comes from the S-bank; /// in eighty columns the left character of each pair is the /// `$0400` page's and the right the `$0800` page's (MAME Development Team, n.d.), so /// "auxiliary" here is the `$0400` page. Graphics come from /// bank 0, where the two 8K pages of the 560 and 140 modes are /// laid end to end, the drawer's "auxiliary" being the first. pub fn videoByte(self: *Self, auxiliary: bool, address: u16) u8 { const v = self.video; if (!v.vm3) { if (v.vm1) { const offset = address & 0x03ff; return self.inSBank((if (auxiliary) @as(u16, 0x0400) else 0x0800) + offset).*; } return self.inSBank(address).*; } const base: u16 = if (v.vm2) 0x4000 else 0x2000; const offset = address - 0x2000; const page: u16 = if (v.vm1 and !auxiliary) 0x2000 else 0; return self.inBank(0, base - 0x2000 + page + offset).*; } /// A III's screen byte is seven bits of ASCII with the top /// bit saying normal or, clear, inverse — the console driver /// "displays the inverse of the character" by clearing it — /// which is the coding a IIe calls its alternate set, without /// the II's flashing range (MAME Development Team, n.d., draws `ch & 0x7F` and inverts on the /// top bit). pub fn alternateCharacters(self: *const Self) bool { _ = self; return true; } pub fn flashing(self: *Self) bool { return font.flashing(self.getCPU().clock.cycles, cycles_per_second); } /// The machine's black-and-white output carries no colour /// burst; its colour output is a separate connector. /// Whether what goes out is a colour signal. Of the four /// graphics modes two are "black and white dots only" and two /// are "dots in any of 16 possible colors" (Apple Computer, /// Inc., 1981b, p. 74), and VM0 is the difference; text is /// white, or coloured by the byte beside it, see /// `textColour`. pub fn colourBurst(self: *const Self) bool { return self.video.vm3 and self.video.vm0; } /// The colours of one character in the colour text mode: forty /// columns with VM0 set, when the byte at the same place in /// the other text page gives "text fg/bg color byte" as the /// console driver's `TCOLOR` calls it (Apple Computer, Inc., /// 1983, p. 14), foreground in the high nibble, in the /// Lo-Res palette. Null in the other text modes, whose /// characters are white. (MAME gates the mode on the E VIA's /// PA6 as written; that line is the Solid Apple key, an /// input, so it is not followed here.) pub fn textColour(self: *Self, width: u16, base: u16, column: u16) ?struct { foreground: u4, background: u4 } { const v = self.video; if (v.vm3 or v.vm1 or !v.vm0 or width != 40) return null; const byte = self.inSBank((base ^ 0x0c00) + column).*; return .{ .foreground = @truncate(byte >> 4), .background = @truncate(byte) }; } pub fn delaysHires(self: *const Self) bool { _ = self; return false; } pub fn writeText(self: *Self, writer: *std.Io.Writer) std.Io.Writer.Error!void { return screen.write(self, writer); } }; } }.model; } const testing = std.testing; const TestCPU = @import("../cpu8.zig").CPU(@import("../clock.zig").FakeClock, AppleIII(.{})); /// Brings a machine up with the environment and zero-page registers set the /// way the ROM leaves them for SOS: all outputs, 2 MHz, I/O on, ROM in, the /// stack primary, zero page $18. fn setUp(cpu: *TestCPU) !void { try cpu.init(null, null); cpu.memory.reset(); cpu.memory.vias[0].direction = .{ 0xff, 0xff }; cpu.memory.vias[1].direction = .{ 0xff, 0xff }; cpu.memory.vias[0].port[0] = Environment.io | Environment.video | Environment.nmi | Environment.primary_stack | Environment.primary_rom | Environment.rom; cpu.memory.vias[0].port[1] = 0x18; cpu.memory.vias[1].port[0] = solid_apple | 0x02; } test "the registers read all ones at reset, which is what puts the ROM in and the processor at 1 MHz" { var cpu: TestCPU = undefined; try cpu.init(null, null); cpu.memory.reset(); try testing.expectEqual(@as(u8, 0xff), cpu.memory.environment()); try testing.expectEqual(@as(u8, 0xff), cpu.memory.zeroPage()); // The ROM shows, and a read in the slow state costs two cycles. cpu.memory.rom[0x0abc] = 0x5a; const before = cpu.clock.cycles; try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xfabc)); try testing.expectEqual(@as(u64, 2), cpu.clock.cycles - before); // And the VIAs answer, since the bank register's bit 6 reads high too. cpu.memory.write(u8, zero_page_register + 3, 0xff); // DDRA of the D VIA try testing.expectEqual(@as(u8, 0xff), cpu.memory.vias[0].direction[0]); } /// The effective processor rate over `accesses` memory reads, in hertz: the /// cycles they cost are the 2 MHz count, so the accesses done in that much /// real time is the rate the running program feels. fn measuredRate(cpu: *TestCPU, accesses: u64) u64 { const before = cpu.clock.cycles; var i: u64 = 0; while (i < accesses) : (i += 1) _ = cpu.memory.read(u8, 0x1000); return accesses * clock_hz / (cpu.clock.cycles - before); } test "the video steals a memory cycle, holding the processor near 1.4 MHz with the display on" { var cpu: TestCPU = undefined; try setUp(&cpu); const accesses = 200_000; // SOS's environment is 2 MHz with the video on, which is where the // stealing shows: the screen takes the other phase through the eighty // showing cycles of every one-hundred-and-thirty-cycle line and leaves the // fifty of horizontal blanking, so ninety accesses fit in a line and the // rate settles at 90/130 of 2 MHz, the "approximately 1.4 MHz" SOS names. const on = measuredRate(&cpu, accesses); try testing.expect(on > 1_360_000 and on < 1_410_000); // Video off, the processor keeps both phases: every access is one cycle, a // full 2 MHz. cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.video); try testing.expectEqual(@as(u64, 2_000_000), measuredRate(&cpu, accesses)); // The 1 MHz bit the disk sets holds it to 1 MHz whatever the video does. cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.slow); try testing.expectEqual(@as(u64, 1_000_000), measuredRate(&cpu, accesses)); } test "the S-bank is always there, and the window at $2000 is whichever bank the register names" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, bank_register, solid_apple | 0); cpu.memory.write(u8, 0x2000, 0x11); cpu.memory.write(u8, 0xa000, 0xaa); // S-bank cpu.memory.write(u8, 0x0300, 0x03); // S-bank cpu.memory.write(u8, bank_register, solid_apple | 1); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0x2000, 0x22); cpu.memory.write(u8, bank_register, solid_apple | 0); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); try testing.expectEqual(@as(u8, 0xaa), cpu.memory.read(u8, 0xa000)); try testing.expectEqual(@as(u8, 0x03), cpu.memory.read(u8, 0x0300)); // The S-bank is the highest bank fitted: bank 3 of a 128K machine. try testing.expectEqual(@as(u8, 0xaa), cpu.memory.ram[3 * bank_size + 0x2000]); try testing.expectEqual(@as(u8, 0x22), cpu.memory.ram[1 * bank_size]); // A 2 MHz read costs one cycle. // With the video off the processor has every cycle; see below for // what the screen takes. cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.video); const before = cpu.clock.cycles; _ = cpu.memory.read(u8, 0x2000); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles - before); } test "zero page and the stack are wherever the zero-page register puts them" { // "Separate zero pages to the interpreter ($1A00 through $1AFF) and SOS // ($1800 through $18FF)" and "separate stacks to the interpreter ($1B00 // through $1BFF) and to SOS ($0100 through $01FF)" (Apple Computer, Inc., // 1982a, p. 17). var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, 0x0057, 0x57); try testing.expectEqual(@as(u8, 0x57), cpu.memory.read(u8, 0x1857)); // SOS keeps the primary stack; the interpreter's is beside its zero page. cpu.memory.write(u8, 0x01fe, 0xfe); try testing.expectEqual(@as(u8, 0xfe), cpu.memory.read(u8, 0x01fe)); cpu.memory.write(u8, zero_page_register + 0, 0x1a); // ORB: page $1A cpu.memory.write(u8, environment_register + 0, cpu.memory.environment() & ~Environment.primary_stack); cpu.memory.write(u8, 0x0057, 0x75); try testing.expectEqual(@as(u8, 0x75), cpu.memory.read(u8, 0x1a57)); try testing.expectEqual(@as(u8, 0x57), cpu.memory.read(u8, 0x1857)); cpu.memory.write(u8, 0x01fe, 0xef); try testing.expectEqual(@as(u8, 0xef), cpu.memory.read(u8, 0x1bfe)); // And SOS's own stack is still where it was, once its stack is back. cpu.memory.write(u8, environment_register + 0, cpu.memory.environment() | Environment.primary_stack); try testing.expectEqual(@as(u8, 0xfe), cpu.memory.read(u8, 0x01fe)); } test "the environment register switches the I/O space, the ROM and the write protection" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.rom[0x0000] = 0xf0; try testing.expectEqual(@as(u8, 0xf0), cpu.memory.read(u8, 0xf000)); // Writes fall through to the RAM beneath, unless protected. cpu.memory.write(u8, 0xf000, 0x0f); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.rom); try testing.expectEqual(@as(u8, 0x0f), cpu.memory.read(u8, 0xf000)); cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.write_protect); cpu.memory.write(u8, 0xf000, 0x77); try testing.expectEqual(@as(u8, 0x0f), cpu.memory.read(u8, 0xf000)); // With I/O switched out, $C000 is RAM. cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.io & ~Environment.write_protect); cpu.memory.write(u8, 0xc000, 0xc0); try testing.expectEqual(@as(u8, 0xc0), cpu.memory.read(u8, 0xc000)); cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.io); cpu.memory.pressKey('A'); try testing.expectEqual(@as(u8, 'A' | 0x80), cpu.memory.read(u8, 0xc000)); // The VIAs stay at their sixteen addresses whatever is written to the // bank register's bit 6, which is the Solid Apple key coming in rather // than a switch: a VIA register still answers as a VIA with it clear. cpu.memory.write(u8, bank_register - 0x0f + 0x0e, 0x00); // E VIA IER, top bit clear cpu.memory.write(u8, bank_register, 0x02); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, bank_register - 0x0f + 0x0e)); // reads as an IER // The RAM beneath them is reached the way SOS keeps its pseudo-clock // at $8F:FFD0: through enhanced indirect addressing, which the I/O // decode does not see. cpu.memory.write(u8, zero_page_register, 0x1a); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.primary_stack); cpu.memory.ram[3 * bank_size + 0x7fd0] = 0xa5; cpu.memory.poke(0x1a57, 0xd0); cpu.memory.poke(0x1a58, 0xff); cpu.memory.poke(0x1658, 0x8f); cpu.memory.sync(); _ = cpu.memory.read(u8, 0xa700); _ = cpu.memory.read(u8, 0x0057); _ = cpu.memory.read(u8, 0x0058); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.read(u8, 0xffd0)); } test "a pointer read off zero page with its X-byte's top bit set sends the next access to another bank pair" { // The interpreter's arrangement: zero page $1A, extension page $16, and // "you store $lo in $nn, $hi in $nn+1, and $xx in location $16nn+1" // (Apple Computer, Inc., 1982a, p. 31). var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, zero_page_register, 0x1a); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.primary_stack); cpu.memory.write(u8, bank_register, solid_apple | 0x02); // Something to find: bank 1's $3289, which is $80:B289 — pair $80 lays // bank 0 then bank 1 end to end from $0000, so that "$8n:0000 to // $8n:00FF" has "the equivalent address in the next-lower bank pair: // that is, $8(n-1):8000 to $8(n-1):80FF" (Apple Computer, Inc., 1982a, // p. 15). cpu.memory.ram[1 * bank_size + 0x3289] = 0x42; // The pointer $B289 at $57, and its X-byte $80 at $1658. cpu.memory.poke(0x1a57, 0x89); cpu.memory.poke(0x1a58, 0xb2); cpu.memory.poke(0x1658, 0x80); // The instruction: an opcode fetch, then the pointer, then the data. cpu.memory.sync(); _ = cpu.memory.read(u8, 0xa700); // the opcode, from the S-bank const low = cpu.memory.read(u8, 0x0057); const high = cpu.memory.read(u8, 0x0058); try testing.expectEqual(@as(u16, 0xb289), @as(u16, high) << 8 | low); try testing.expectEqual(@as(?u8, 0x80), cpu.memory.indirect); try testing.expectEqual(@as(u8, 0x42), cpu.memory.read(u8, 0xb289)); // The next instruction reads $B289 in the S-bank, as usual. cpu.memory.sync(); _ = cpu.memory.read(u8, 0xa703); try testing.expectEqual(@as(?u8, null), cpu.memory.indirect); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xb289)); // An X-byte without its top bit arms nothing. cpu.memory.poke(0x1658, 0x00); cpu.memory.sync(); _ = cpu.memory.read(u8, 0xa700); _ = cpu.memory.read(u8, 0x0057); _ = cpu.memory.read(u8, 0x0058); try testing.expectEqual(@as(?u8, null), cpu.memory.indirect); // And $8F is the S-bank with bank 0 in the window. cpu.memory.ram[0x0100] = 0x8f; cpu.memory.poke(0x1658, 0x8f); cpu.memory.poke(0x1a57, 0x00); cpu.memory.poke(0x1a58, 0x21); cpu.memory.sync(); _ = cpu.memory.read(u8, 0xa700); _ = cpu.memory.read(u8, 0x0057); _ = cpu.memory.read(u8, 0x0058); try testing.expectEqual(@as(u8, 0x8f), cpu.memory.read(u8, 0x2100)); } test "the video switches make text and graphics modes, and the speaker is logged" { var cpu: TestCPU = undefined; try setUp(&cpu); try testing.expectEqual(screen.Mode.text, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc053); // VM1 on: eighty columns try testing.expectEqual(screen.Mode.text_80, cpu.memory.mode()); try testing.expectEqual(@as(u16, 80), cpu.memory.columns()); _ = cpu.memory.read(u8, 0xc057); // VM3 on: graphics, and with VM1 the 560-wide kind try testing.expectEqual(screen.Mode.double_high_resolution, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc052); // VM1 off try testing.expectEqual(screen.Mode.high_resolution, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc056); _ = cpu.memory.read(u8, 0xc055); // VM2: the second text page try testing.expectEqual(@as(u16, 0x0800), cpu.memory.displayPage()); try testing.expect(!cpu.memory.speaker); _ = cpu.memory.read(u8, 0xc030); try testing.expect(cpu.memory.speaker); } test "memory comes in 128K, 256K and 512K" { var cpu: TestCPU = undefined; try cpu.init(null, null); try cpu.memory.fitMemory(256 * 1024); try testing.expectEqual(@as(u8, 8), cpu.memory.banks); try cpu.memory.fitMemory(512 * 1024); try testing.expectEqual(@as(u8, 16), cpu.memory.banks); try testing.expectError(error.NotAConfiguration, cpu.memory.fitMemory(192 * 1024)); try testing.expectError(error.NotAConfiguration, cpu.memory.fitMemory(64 * 1024)); } test "the E VIA sees the vertical blanking on its CB lines, and the ROM's wait for it ends" { var cpu: TestCPU = undefined; try setUp(&cpu); // The ROM's own sequence: ask for the rising edge on CB2, clear its // flag, then wait for it. cpu.memory.write(u8, bank_register - 0x0f + 0x0c, 0x40); cpu.memory.write(u8, bank_register - 0x0f + 0x0d, via.irq_cb2); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, bank_register - 0x0f + 0x0d) & via.irq_cb2); // The picture takes 192 lines; the flag is up once the beam leaves it. var waited: u64 = 0; while (cpu.memory.read(u8, bank_register - 0x0f + 0x0d) & via.irq_cb2 == 0) { waited += 1; try testing.expect(waited < visible_cycles + blanking_cycles); } try testing.expect(cpu.memory.blanking); // And nothing asked for an interrupt, since none is enabled. try testing.expect(!cpu.irq); // The blanking is seventy lines, then the picture starts again. var frame: u64 = 0; while (cpu.memory.blanking) : (frame += 1) { cpu.memory.write(u8, bank_register - 0x0f + 0x0d, via.irq_cb2); try testing.expect(frame < blanking_cycles); } try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, bank_register - 0x0f + 0x0d) & via.irq_cb2); } test "a bank that is not fitted decodes nothing, which is how the boot block sizes the memory" { var cpu: TestCPU = undefined; try setUp(&cpu); // SOS's boot block, on a 128K machine: bank 14 is asked to hold $0E and // bank 6 to hold $06, and bank 14 is looked at again. Neither is there, // so what comes back is what was last on the bus — the high byte of the // address just fetched — and not the $0E a 512K machine would answer. cpu.memory.write(u8, bank_register, solid_apple | 0x0e); cpu.memory.write(u8, 0x2000, 0x0e); cpu.memory.write(u8, bank_register, solid_apple | 0x06); cpu.memory.write(u8, 0x2000, 0x06); cpu.memory.write(u8, bank_register, solid_apple | 0x0e); try testing.expect(cpu.memory.read(u8, 0x2000) != 0x0e); // Then it counts down from bank 7, storing a zero and reading it back, // until one comes back: bank 2, the highest fitted. var bank: u8 = 7; while (bank > 0) : (bank -= 1) { cpu.memory.write(u8, bank_register, solid_apple | bank); cpu.memory.write(u8, 0x2000, 0x00); cpu.memory.floating = 0x20; if (cpu.memory.read(u8, 0x2000) == 0) break; } try testing.expectEqual(@as(u8, 2), bank); // Bank 15 is the S-bank's own number, and puts bank 0 in the window. cpu.memory.write(u8, bank_register, solid_apple | 0x00); cpu.memory.write(u8, 0x2345, 0x45); cpu.memory.write(u8, bank_register, solid_apple | 0x0f); try testing.expectEqual(@as(u8, 0x45), cpu.memory.read(u8, 0x2345)); // And a 256K machine has banks up to 6. try cpu.memory.fitMemory(256 * 1024); cpu.memory.write(u8, bank_register, solid_apple | 0x06); cpu.memory.write(u8, 0x2000, 0x06); try testing.expectEqual(@as(u8, 0x06), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, bank_register, solid_apple | 0x07); cpu.memory.write(u8, 0x2000, 0x07); cpu.memory.floating = 0x20; try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(u8, 0x2000)); } test "the character set comes down through the screen holes as the blanking ends" { var cpu: TestCPU = undefined; try setUp(&cpu); // The console driver's LOADCHR, for cell 5 and the letter A: the code in // the $0800 page's holes, the image in the $0400 page's, eight rows. const dcptrl = [8]u8{ 0x78, 0x7c, 0xf8, 0xfc, 0x78, 0x7c, 0xf8, 0xfc }; const image = [8]u8{ 0x08, 0x14, 0x22, 0x22, 0x3e, 0x22, 0x22, 0x80 }; for (0..8) |row| { const page: u16 = 0x08 | (5 >> 2) << 1 | @as(u16, @intFromBool(row >= 4)); const low: u16 = dcptrl[row] | (5 & 3); cpu.memory.poke(page << 8 | low, 0x41); cpu.memory.poke((page ^ 0x0c) << 8 | low, image[row]); } // Nothing happens until the download is enabled and the blanking ends. cpu.memory.write(u8, 0xc0db, 0); try testing.expectEqual(@as(u8, 0), cpu.memory.charset[0x41][0]); while (!cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u8, 0), cpu.memory.charset[0x41][0]); while (cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); try testing.expectEqualSlices(u8, &image, &cpu.memory.charset[0x41]); // Normal A: the dots as stored, leftmost in bit 0. Inverse A: the // complement — except the last row, whose top bit makes it a flashing // row, inverted in one phase of the flash clock and not the other. try testing.expectEqual(@as(u7, 0x14), cpu.memory.glyphRow(0xc1, 1, false)); try testing.expectEqual(@as(u7, 0x14 ^ 0x7f), cpu.memory.glyphRow(0x41, 1, false)); try testing.expectEqual(@as(u7, 0x00), cpu.memory.glyphRow(0x41, 7, false)); try testing.expectEqual(@as(u7, 0x7f), cpu.memory.glyphRow(0x41, 7, true)); // With the download disabled the cells are left alone. cpu.memory.write(u8, 0xc0da, 0); cpu.memory.poke(0x0479 | 0, 0x00); while (!cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); while (cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u8, 0x08), cpu.memory.charset[0x41][0]); } test "two of the graphics modes are in colour, and the colour text mode colours each character from the other page" { var cpu: TestCPU = undefined; try setUp(&cpu); // Text, forty and eighty columns: white dots, no colour signal. try testing.expect(!cpu.memory.colourBurst()); try testing.expectEqual(@as(?@TypeOf(cpu.memory.textColour(40, 0x0400, 0).?), null), cpu.memory.textColour(40, 0x0400, 0)); // VM3 alone is 280 by 192 in black and white; with VM0, in colour; VM1 // makes them 560 in black and white and 140 in colour. cpu.memory.write(u8, 0xc057, 0); // VM3 on try testing.expect(!cpu.memory.colourBurst()); cpu.memory.write(u8, 0xc051, 0); // VM0 on try testing.expect(cpu.memory.colourBurst()); cpu.memory.write(u8, 0xc053, 0); // VM1 on try testing.expect(cpu.memory.colourBurst()); cpu.memory.write(u8, 0xc050, 0); // VM0 off try testing.expect(!cpu.memory.colourBurst()); // Colour text: VM0 with VM3 and VM1 off. The character at $0400 + 5 is // coloured by the byte at $0800 + 5: orange on dark blue. cpu.memory.write(u8, 0xc056, 0); // VM3 off cpu.memory.write(u8, 0xc052, 0); // VM1 off cpu.memory.write(u8, 0xc051, 0); // VM0 on cpu.memory.poke(0x0805, 0x92); const colour = cpu.memory.textColour(40, 0x0400, 5).?; try testing.expectEqual(@as(u4, 9), colour.foreground); try testing.expectEqual(@as(u4, 2), colour.background); // With the other page showing, the colours come from the first. cpu.memory.write(u8, 0xc055, 0); // VM2 on cpu.memory.poke(0x0405, 0xf0); try testing.expectEqual(@as(u4, 15), cpu.memory.textColour(40, 0x0800, 5).?.foreground); // Eighty columns has no room for a colour byte. cpu.memory.write(u8, 0xc053, 0); // VM1 on try testing.expectEqual(@as(?@TypeOf(colour), null), cpu.memory.textColour(80, 0x0400, 5)); } test "the keyboard puts out the key's code and the modifiers separately, and raises the E VIA's CA2 flag" { var cpu: TestCPU = undefined; try setUp(&cpu); // The console driver's setting: CA2 an independent negative edge, and // its interrupt wanted. cpu.memory.write(u8, bank_register - 0x0f + 0x0c, 0x02); cpu.memory.write(u8, bank_register - 0x0f + 0x0e, 0x81); try testing.expect(!cpu.irq); // A lowercase d is the D key with nothing held. cpu.memory.pressKey('d'); try testing.expectEqual(@as(u8, 0xc4), cpu.memory.read(u8, 0xc000)); try testing.expectEqual(@as(u8, 0x7d), cpu.memory.read(u8, 0xc008)); try testing.expect(cpu.irq); // The driver's handler: clear the flag and the strobe. cpu.memory.write(u8, bank_register - 0x0f + 0x0d, 0x01); _ = cpu.memory.read(u8, 0xc010); try testing.expect(!cpu.irq); try testing.expectEqual(@as(u8, 0x44), cpu.memory.read(u8, 0xc000)); // Uppercase is the same key with shift; control D is $04 with control. cpu.memory.pressKey('D'); try testing.expectEqual(@as(u8, 0xc4), cpu.memory.read(u8, 0xc000)); try testing.expectEqual(@as(u8, 0x7f), cpu.memory.read(u8, 0xc008)); cpu.memory.pressKey(0x04); try testing.expectEqual(@as(u8, 0x84), cpu.memory.read(u8, 0xc000)); try testing.expectEqual(@as(u8, 0x79), cpu.memory.read(u8, 0xc008)); // Return is a special key, and an exclamation mark is a shifted one. cpu.memory.pressKey('\r'); try testing.expectEqual(@as(u8, 0xfd), cpu.memory.read(u8, 0xc008)); cpu.memory.pressKey('!'); try testing.expectEqual(@as(u8, 0xa1), cpu.memory.read(u8, 0xc000)); try testing.expectEqual(@as(u8, 0x7f), cpu.memory.read(u8, 0xc008)); } test "the clock chip answers at $C070 by the register the zero-page register names, and an empty socket floats" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.io); // No chip: SOS's test reads the status register and looks at the top // bit, which the bus left floating gives it from the address just // fetched. cpu.memory.write(u8, zero_page_register, 0x14); cpu.memory.floating = 0xc0; try testing.expectEqual(@as(u8, 0xc0), cpu.memory.read(u8, 0xc070)); // A chip, set as the utilities would: the registers come up in BCD at // whichever of the sixteen addresses, selected by the zero page. cpu.memory.clock.fitted = true; cpu.memory.clock.set(.{ .year = 1983, .month = 11, .day = 17, .hour = 8, .minute = 30, .second = 0 }, cpu.clock.cycles); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc070)); // status: no rollover cpu.memory.write(u8, zero_page_register, 0x07); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0xc077)); // month cpu.memory.write(u8, zero_page_register, 0x06); try testing.expectEqual(@as(u8, 0x17), cpu.memory.read(u8, 0xc07f)); // day cpu.memory.write(u8, zero_page_register, 0x04); try testing.expectEqual(@as(u8, 0x08), cpu.memory.read(u8, 0xc070)); // hours // Writing goes the same way: SOS resets the counters with $FF at $12. cpu.memory.write(u8, zero_page_register, 0x12); cpu.memory.write(u8, 0xc070, 0xff); cpu.memory.write(u8, zero_page_register, 0x06); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc070)); // Its interrupt is the E VIA's CA1: enable the once-a-second rollover // and its flag, and a second later the line is up. cpu.memory.write(u8, zero_page_register, 0x11); cpu.memory.write(u8, 0xc070, mm58167.irq_second); cpu.memory.write(u8, bank_register - 0x0f + 0x0c, 0x01); // CA1 rising edge cpu.memory.write(u8, bank_register - 0x0f + 0x0e, 0x82); // CA1 enabled cpu.memory.write(u8, zero_page_register, 0x00); try testing.expect(!cpu.irq); var waited: u64 = 0; while (!cpu.irq and waited < 3_000_000) : (waited += 1) _ = cpu.memory.read(u8, 0xc070); try testing.expect(cpu.irq); cpu.memory.write(u8, zero_page_register, 0x10); _ = cpu.memory.read(u8, 0xc070); // the status read takes it down try testing.expect(cpu.memory.vias[1].lines.get(.ca1) == false); } test "$C500 to $C7FF is RAM whether the I/O space is in or out, and an empty slot window floats" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.io); cpu.memory.write(u8, 0xc600, 0xa2); cpu.memory.write(u8, 0xc100, 0x11); cpu.memory.write(u8, 0xc900, 0x99); cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.io); // The boot routine the emulation keeps at $C600 is still there. try testing.expectEqual(@as(u8, 0xa2), cpu.memory.read(u8, 0xc600)); // A slot with no card in it, and the expansion space, are the bus. cpu.memory.floating = 0xc1; try testing.expectEqual(@as(u8, 0xc1), cpu.memory.read(u8, 0xc100)); cpu.memory.floating = 0xc9; try testing.expectEqual(@as(u8, 0xc9), cpu.memory.read(u8, 0xc900)); // And writes there go nowhere; the RAM beneath keeps what it had. cpu.memory.write(u8, 0xc100, 0x22); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.io); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0xc100)); try testing.expectEqual(@as(u8, 0x99), cpu.memory.read(u8, 0xc900)); } test "one access to $C040 rings a beep a tenth of a second long, on its own" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.io); const started = cpu.clock.cycles; _ = cpu.memory.read(u8, 0xc040); // Nothing has changed yet; the generator runs by itself from here. try testing.expect(!cpu.memory.speaker); var flips: u32 = 0; var was = cpu.memory.speaker; while (cpu.clock.cycles < started + clock_hz / 5) { _ = cpu.memory.read(u8, 0x0300); if (cpu.memory.speaker != was) { flips += 1; was = cpu.memory.speaker; } } try testing.expectEqual(@as(u32, beep_edge_count), flips); try testing.expect(!cpu.memory.speaker); } test "the ProFile's card answers at slot 4, and its pseudo-DMA fills the page the zero-page register names" { var cpu: TestCPU = undefined; try setUp(&cpu); var image: [16 * blockdevice.block_size]u8 = @splat(0); for (image[2 * blockdevice.block_size ..][0..blockdevice.block_size], 0..) |*b, i| b.* = @truncate(0x1000 - i); var volume: blockdevice.Volume = .{ .image = &image }; // An empty slot: the ports and the window float. cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.io); cpu.memory.floating = 0xc0; try testing.expectEqual(@as(u8, 0xc0), cpu.memory.read(u8, 0xc0c2)); cpu.memory.insertVolume(0, &volume); // The driver's handshake through the machine: CMD up by reading $C404, // the response at $C0C1, the answer to $C0C0, CMD down at $C400. try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc0c2)); // BSY low, a drive there _ = cpu.memory.read(u8, 0xc404); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc0c2) & 0x80); // BSY up try testing.expectEqual(@as(u8, 0x01), cpu.memory.read(u8, 0xc0c1)); cpu.memory.write(u8, 0xc0c0, profile.accept); _ = cpu.memory.read(u8, 0xc400); for ([_]u8{ 0x00, 0x00, 0x00, 0x02, 0x0a, 0x03 }) |b| cpu.memory.write(u8, 0xc0c0, b); _ = cpu.memory.read(u8, 0xc404); try testing.expectEqual(@as(u8, 0x02), cpu.memory.read(u8, 0xc0c1)); cpu.memory.write(u8, 0xc0c0, profile.accept); _ = cpu.memory.read(u8, 0xc400); for (0..4) |_| try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0c1)); // Then the pseudo-DMA, as GO_DMA sets it up: the zero-page register at // the buffer's page, $20 in bank 1, and the processor fetching its way // through $F800 to $F8FF — here read by read, as the processor would. cpu.memory.write(u8, bank_register, solid_apple | 0x01); cpu.memory.write(u8, zero_page_register, 0x20); for (0..0x100) |i| _ = cpu.memory.read(u8, 0xf800 + @as(u16, @intCast(i))); cpu.memory.write(u8, zero_page_register, 0x21); for (0..0x100) |i| _ = cpu.memory.read(u8, 0xf800 + @as(u16, @intCast(i))); try testing.expect(!cpu.memory.profile.transferring()); cpu.memory.write(u8, zero_page_register, 0x18); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x2000)); try testing.expectEqual(@as(u8, 0xff), cpu.memory.read(u8, 0x2001)); try testing.expectEqual(@as(u8, 0x100 - 0xff), cpu.memory.read(u8, 0x20ff)); try testing.expectEqual(@as(u8, 0x01), cpu.memory.read(u8, 0x21ff)); // In bank 1, where the bank register put the window. try testing.expectEqual(@as(u8, 0xff), cpu.memory.ram[1 * bank_size + 0x0001]); // And with the transfer over, a read of $F800 moves nothing. _ = cpu.memory.read(u8, 0xf800); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x2000)); } test "an analog input is read the way SOS reads it: select, charge, start, and time the flag against 360 at 2 MHz" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, environment_register, cpu.memory.environment() | Environment.io); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.slow); // Port A's Y axis is input 3, selected as AD.READ does: bit 0 by $C059, // bit 1 by $C05F, bit 2 off by $C05A. cpu.memory.setAnalog(3, 200); _ = cpu.memory.read(u8, 0xc059); _ = cpu.memory.read(u8, 0xc05f); _ = cpu.memory.read(u8, 0xc05a); try testing.expectEqual(@as(u3, 3), cpu.memory.analog_select); // Charge, then start; the flag is up until the ramp reaches the value. _ = cpu.memory.read(u8, 0xc05c); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc066)); const started = cpu.clock.cycles; _ = cpu.memory.read(u8, 0xc05d); var polls: u64 = 0; while (cpu.memory.read(u8, 0xc066) & 0x80 != 0) polls += 1; const elapsed_us = (cpu.clock.cycles - started) / 2; // SOS's sum: the D VIA's timer, loaded with 360 and counting at 1 MHz, // has the value in its high byte at that moment. const timer: u16 = @truncate(360 -% elapsed_us); try testing.expectEqual(@as(u8, 200), @as(u8, @truncate(timer >> 8))); // Nothing plugged in drops the flag at once, and the switches read in // bit 7 at their four addresses. cpu.memory.setAnalog(3, null); _ = cpu.memory.read(u8, 0xc05c); _ = cpu.memory.read(u8, 0xc05d); _ = cpu.memory.read(u8, 0x0300); _ = cpu.memory.read(u8, 0x0300); _ = cpu.memory.read(u8, 0x0300); _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc066)); cpu.memory.setButton(1, true); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc061)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc060)); } test "the screen takes every other memory cycle while it is drawing, and none in the blanking or with the video off" { var cpu: TestCPU = undefined; try setUp(&cpu); cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.slow); // From the start of a line in the picture: forty accesses take the // eighty cycles the screen is fetching through, two each, and fifty more // take the fifty of the horizontal blanking, one each. try testing.expect(!cpu.memory.blanking); while ((cpu.memory.blank_edge - cpu.clock.cycles) % cycles_per_line != 0) _ = cpu.memory.read(u8, 0x0300); var before = cpu.clock.cycles; for (0..40) |_| _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u64, 80), cpu.clock.cycles - before); for (0..50) |_| _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u64, 130), cpu.clock.cycles - before); // The lines of the vertical blanking are no different: the screen // fetches through them, blanked, and the processor waits. while (!cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); while ((cpu.memory.blank_edge - cpu.clock.cycles) % cycles_per_line != 0) _ = cpu.memory.read(u8, 0x0300); before = cpu.clock.cycles; for (0..90) |_| _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u64, 130), cpu.clock.cycles - before); // Over a whole frame with the video on, the average is the 1.4 MHz SOS // quotes: ninety accesses a line, 23,580 in a frame's 34,060 cycles. while (cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); var accesses: u64 = 0; const frame_end = cpu.clock.cycles + visible_cycles + blanking_cycles; while (cpu.clock.cycles < frame_end) : (accesses += 1) _ = cpu.memory.read(u8, 0x0300); const hz = accesses * 2_000_000 / (visible_cycles + blanking_cycles); try testing.expect(hz > 1_350_000 and hz < 1_450_000); // And with the video switched off the processor has the whole 2 MHz. cpu.memory.write(u8, environment_register, cpu.memory.environment() & ~Environment.video); while (cpu.memory.blanking) _ = cpu.memory.read(u8, 0x0300); before = cpu.clock.cycles; for (0..100) |_| _ = cpu.memory.read(u8, 0x0300); try testing.expectEqual(@as(u64, 100), cpu.clock.cycles - before); } test "writing the E VIA's port B drives the sound DAC, and its levels are logged for a recording" { // A model with its logs switched on, which is what --audio asks for. const LoggedCPU = @import("../cpu8.zig").CPU(@import("../clock.zig").FakeClock, AppleIII(.{ .speaker_log = true })); var cpu: LoggedCPU = undefined; try cpu.init(null, null); cpu.memory.reset(); cpu.memory.vias[0].direction = .{ 0xff, 0xff }; cpu.memory.vias[1].direction = .{ 0xff, 0xff }; cpu.memory.vias[0].port[0] = Environment.io | Environment.video | Environment.nmi | Environment.primary_stack | Environment.primary_rom | Environment.rom; cpu.memory.vias[0].port[1] = 0x18; cpu.memory.vias[1].port[0] = solid_apple | 0x02; // The DAC is the low six bits of the E VIA's port B, all outputs, as // SOS sets them: E.DDRB := $3F. cpu.memory.write(u8, 0xffe2, 0x3f); try testing.expectEqual(@as(usize, 0), cpu.memory.dac_log.taken().len); // A rising ramp: eight steps, each a higher level than the last. var last: f32 = -1; for (0..8) |i| { cpu.memory.write(u8, 0xffe0, @intCast((i + 1) * 7)); const entries = cpu.memory.dac_log.taken(); try testing.expectEqual(@as(usize, i + 1), entries.len); try testing.expect(entries[i].level > last); last = entries[i].level; } // A write that does not change the low six bits logs nothing new: the // last value was 56, so 56 with a higher bit set is no change. cpu.memory.write(u8, 0xffe0, 56 | 0x40); // bit 6 is not the DAC try testing.expectEqual(@as(usize, 8), cpu.memory.dac_log.taken().len); // Full scale is 63, which is level 1. cpu.memory.write(u8, 0xffe0, 0x3f); const all = cpu.memory.dac_log.taken(); try testing.expectEqual(@as(f32, 1.0), all[all.len - 1].level); } test "a card goes in any of the four slots, and only the four" { var cpu: TestCPU = undefined; try setUp(&cpu); const m = &cpu.memory; // "The Peripheral Slot Assignment option... enables you to tell each // device driver the slot number into which you" put its card, "a number // from 1 to 4" (Apple Computer, Inc., 1981b, p. 17). So which slot a card // is in is software, and any of the four will do. try testing.expectError(error.NotASlot, m.fitCard(0, .upic)); try testing.expectError(error.NotASlot, m.fitCard(5, .upic)); try m.fitCard(2, .upic); try testing.expectEqual(@as(?u3, 2), m.slotOf(.upic)); try testing.expect(m.slotOf(.profile) == null); } test "an empty Apple III slot floats at its ports and its window" { var cpu: TestCPU = undefined; try setUp(&cpu); const m = &cpu.memory; // All four are empty to begin with, and an empty slot has nothing in it to // drive the bus. This used to be true of slot 4 and not of slots 1 to 3, // which fell through to a case that answered nought. m.floating = 0xa5; for ([_]u16{ 0xc090, 0xc0a0, 0xc0b0, 0xc0c0 }) |port| { try testing.expectEqual(@as(u8, 0xa5), m.read(u8, port)); } // And the four firmware windows, which no card here answers either. for ([_]u16{ 0xc100, 0xc200, 0xc300, 0xc400 }) |window| { try testing.expectEqual(@as(u8, 0xa5), m.read(u8, window)); } } test "a UPIC prints from whichever slot it is in" { var cpu: TestCPU = undefined; try setUp(&cpu); const m = &cpu.memory; var buffer: [8]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); // Slot 3, which is not where anything is by default: the card's eight // addresses are then at `$c080 + s0`, so `$c0b0` to `$c0b7`. m.fitPrinter(3, &writer); m.write(u8, 0xc0b0, 'A'); // PORTA m.write(u8, 0xc0b2, 0); // STROBE try testing.expectEqualStrings("A", writer.buffered()); // And it is not at any other slot's addresses. m.floating = 0x5a; try testing.expectEqual(@as(u8, 0x5a), m.read(u8, 0xc094)); // Its own status register, though, answers: the strobe was acknowledged. try testing.expectEqual(upic_module.status_ack, m.read(u8, 0xc0b4) & upic_module.status_ack); // Touching its firmware window turns autostrobe on, which is the one thing // that space does on this card, and then a write to PORTA is enough. _ = m.read(u8, 0xc300); m.write(u8, 0xc0b0, 'B'); try testing.expectEqualStrings("AB", writer.buffered()); } test "a ProFile and a UPIC share the bus without answering for each other" { var cpu: TestCPU = undefined; try setUp(&cpu); const m = &cpu.memory; var image: [4 * blockdevice.block_size]u8 = @splat(0); var volume: blockdevice.Volume = .{ .image = &image }; var buffer: [4]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); m.fitPrinter(1, &writer); m.insertVolume(0, &volume); // The ProFile went to slot 4 because that is what its manual says and what // every SOS.DRIVER expects, and the UPIC stayed in slot 1. try testing.expectEqual(@as(?u3, 4), m.slotOf(.profile)); try testing.expectEqual(@as(?u3, 1), m.slotOf(.upic)); // Each answers at its own sixteen and nowhere else. m.write(u8, 0xc090, 'x'); // the UPIC's PORTA, slot 1 m.write(u8, 0xc092, 0); // and its strobe try testing.expectEqualStrings("x", writer.buffered()); // Slot 4's status register is the ProFile's, not the UPIC's. _ = m.read(u8, 0xc0c2); try testing.expectEqualStrings("x", writer.buffered()); // Taking the volume away takes the card off the bus with it: an interface // card with no drive on the end is not what any of this is for. m.insertVolume(0, null); try testing.expect(m.slotOf(.profile) == null); m.floating = 0x33; try testing.expectEqual(@as(u8, 0x33), m.read(u8, 0xc0c2)); }