Skip to main content

saturnus_core/machine/
lcd.rs

1//! The LCD: 131x64 on the 48-family models, rendered from the display
2//! bitmaps in memory (wiki: hardware/display); 131x16 on the 42S, rendered
3//! from the Lewis display RAM (wiki: hardware/lewis "Display"); 137x32 on
4//! the 28S, from the display RAM of its two Lewis chips (wiki:
5//! hardware/hp28s "Display").
6
7use crate::cpu::ADDR_MASK;
8use crate::io::{IoRegisters, LewisIo};
9
10/// LCD width in pixels of every model but the 28S.
11pub const LCD_WIDTH: usize = 131;
12/// LCD width in pixels of the 28S.
13pub const LCD_WIDTH_28S: usize = 137;
14/// LCD height in pixels of the 28S: four lines of 8 rows.
15pub const LCD_HEIGHT_28S: usize = 32;
16/// Columns of the 28S's left half, on the slave chip; the master chip
17/// shows the other 69 (wiki: hardware/hp28s "Display").
18const CLAMSHELL_LEFT_COLUMNS: usize = 68;
19/// The slave chip's first displayed column (#FF840).
20const CLAMSHELL_SLAVE_FIRST: usize = 0x40;
21/// LCD height in pixels of the 48-family models.
22pub const LCD_HEIGHT: usize = 64;
23/// LCD height in pixels of the 42S: two lines of 8 rows.
24pub const LCD_HEIGHT_42S: usize = 16;
25/// Columns the Lewis's left column driver serves (0-65); the right one
26/// serves 66-130 (wiki: hardware/lewis "Display").
27const LEWIS_LEFT_COLUMNS: usize = 66;
28/// First nibble of the seven Lewis annunciator words, eight nibbles apart
29/// (#40218-#4024C).
30const LEWIS_ANNUNCIATORS: usize = 0x218;
31/// The Lewis word that lights every annunciator (#40210).
32const LEWIS_ANNUNCIATOR_ALL: usize = 0x210;
33/// Nibbles per bitmap row without the line offset (131 pixels rounded up
34/// to whole bytes: 136 bits = 34 nibbles).
35const ROW_NIBBLES: i64 = 34;
36
37/// A snapshot of the LCD pixels.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct Lcd {
40    /// Rows of pixels, `true` = dark, each [`Lcd::width`] long: 131x64 on
41    /// the 48-family models, 131x16 on the Pioneers, 137x32 on the 28S
42    /// (see [`crate::Model::lcd_size`]).
43    pub pixels: Vec<Vec<bool>>,
44    /// Pixels per row.
45    width: usize,
46}
47
48impl Lcd {
49    /// A blank 131x64 display.
50    pub fn blank() -> Self {
51        Self::blank_rows(LCD_HEIGHT)
52    }
53
54    /// A blank display of `rows` rows of 131 pixels.
55    pub fn blank_rows(rows: usize) -> Self {
56        Self::blank_sized(LCD_WIDTH, rows)
57    }
58
59    /// A blank display of `width` x `rows` pixels.
60    pub fn blank_sized(width: usize, rows: usize) -> Self {
61        Self {
62            pixels: vec![vec![false; width]; rows],
63            width,
64        }
65    }
66
67    /// Width in pixels: 131, or 137 on the 28S.
68    pub fn width(&self) -> usize {
69        self.width
70    }
71
72    /// Height in pixels.
73    pub fn height(&self) -> usize {
74        self.pixels.len()
75    }
76
77    /// Render the 28S's 137x32 display from the display RAM of its two
78    /// Lewis chips.
79    ///
80    /// Each column is eight consecutive nibbles, 32 bits, least
81    /// significant bit the top row. The slave chip shows the left 68
82    /// columns from its offset #040 (#FF840), the master the right 69 from
83    /// offset 0 (#FFC00); within each half the address grows to the right
84    /// (wiki: hardware/hp28s "Display", from Gariepy's scroll routine and
85    /// the ROM's screens). Each half is blank while its chip's DON is
86    /// clear (inferred: each chip drives its own columns).
87    // `x` is both the RAM address and the column of every row: no iterator says that more plainly.
88    #[allow(clippy::needless_range_loop)]
89    pub(crate) fn render_clamshell(master: &LewisIo, slave: &LewisIo) -> Self {
90        let mut lcd = Self::blank_sized(LCD_WIDTH_28S, LCD_HEIGHT_28S);
91        for x in 0..LCD_WIDTH_28S {
92            let (chip, base) = if x < CLAMSHELL_LEFT_COLUMNS {
93                (slave, CLAMSHELL_SLAVE_FIRST + 8 * x)
94            } else {
95                (master, 8 * (x - CLAMSHELL_LEFT_COLUMNS))
96            };
97            if !chip.display_on() {
98                continue;
99            }
100            for n in 0..8 {
101                let nib = chip.ram_nibble(base + n);
102                for bit in 0..4 {
103                    lcd.pixels[4 * n + bit][x] = nib >> bit & 1 != 0;
104                }
105            }
106        }
107        lcd
108    }
109
110    /// Render the 42S's 131x16 display from the Lewis display RAM.
111    ///
112    /// Two column drivers share the RAM byte by byte: byte `4k` holds
113    /// column `k` of the upper line, `4k+1` column `k` of the lower line
114    /// (k = 0-65), `4k+2` and `4k+3` the same for column `66+k` (k =
115    /// 0-64); 524 nibbles from #40000. Bit 0 of a byte is the top row of
116    /// its line. Put the other way: column `c` is four consecutive
117    /// nibbles, top to bottom, least significant bit on top, at #40000 +
118    /// 8c for c < 66 and #40004 + 8(c-66) above (wiki:
119    /// hardware/lewis "Display", checked on the ROM's "Memory Clear"
120    /// screen). Blank while DON is clear.
121    // `x` picks the RAM bytes and is the column of every row, as above.
122    #[allow(clippy::needless_range_loop)]
123    pub(crate) fn render_lewis(lewis: &LewisIo) -> Self {
124        let mut lcd = Self::blank_rows(LCD_HEIGHT_42S);
125        if !lewis.display_on() {
126            return lcd;
127        }
128        for x in 0..LCD_WIDTH {
129            let (k, half) = if x < LEWIS_LEFT_COLUMNS {
130                (x, 0)
131            } else {
132                (x - LEWIS_LEFT_COLUMNS, 2)
133            };
134            for line in 0..2 {
135                let byte = 4 * k + half + line;
136                let bits = lewis.ram_nibble(2 * byte) | (lewis.ram_nibble(2 * byte + 1) << 4);
137                for row in 0..8 {
138                    lcd.pixels[8 * line + row][x] = bits >> row & 1 != 0;
139                }
140            }
141        }
142        lcd
143    }
144
145    /// Render from the display registers in `io`, reading bitmap nibbles
146    /// through `peek`.
147    ///
148    /// Rows `0..=line_count` come from the main bitmap at `display_start`,
149    /// shifted left by `bit_offset` pixels; a line count of 0 or 1 is
150    /// treated as 63 (inferred). After each main row the address advances
151    /// by 34 nibbles plus the line offset plus 2 when the bit offset spans a
152    /// nibble, aligned down to a byte. The remaining rows come from the menu
153    /// bitmap at `menu_start`, 34 nibbles per row (wiki: hardware/display).
154    pub(crate) fn render(io: &IoRegisters, peek: impl Fn(u32) -> u8) -> Self {
155        let mut lcd = Self::blank();
156        if !io.display_on() {
157            return lcd;
158        }
159        for (row, (addr, offset)) in lcd.pixels.iter_mut().zip(row_starts(io)) {
160            render_row(row, addr, offset, &peek);
161        }
162        lcd
163    }
164
165    /// The first and last nibble address each of the 64 rows reads, in
166    /// row order; [`Lcd::render`] reads exactly the nibbles from the first
167    /// to the last of every row, through the mapping.
168    pub(crate) fn row_spans(io: &IoRegisters) -> impl Iterator<Item = (u32, u32)> {
169        row_starts(io).map(|(addr, offset)| {
170            let last = ((LCD_WIDTH - 1 + offset) / 4) as u32;
171            (addr, addr.wrapping_add(last) & ADDR_MASK)
172        })
173    }
174
175    /// One line of [`Lcd::width`] characters per row (131 by 64, 131 by
176    /// 16 on the Pioneers, 137 by 32 on the 28S), `#` for a dark pixel
177    /// and `.` for a light one, each line ended by `\n`.
178    pub fn to_text(&self) -> String {
179        let mut s = String::with_capacity((self.width + 1) * self.pixels.len());
180        for row in &self.pixels {
181            s.extend(row.iter().map(|&on| if on { '#' } else { '.' }));
182            s.push('\n');
183        }
184        s
185    }
186}
187
188/// Start address and bit offset of each of the 64 rows: rows
189/// `0..=line_count` from the main bitmap, shifted left by the bit offset;
190/// a line count of 0 or 1 is treated as 63 (inferred). After each main row
191/// the address advances by 34 nibbles plus the line offset plus 2 when the
192/// bit offset spans a nibble, aligned down to a byte. The remaining rows
193/// come from the menu bitmap, 34 nibbles per row, no offset (wiki:
194/// hardware/display).
195fn row_starts(io: &IoRegisters) -> impl Iterator<Item = (u32, usize)> {
196    let last_main = match io.line_count() {
197        0 | 1 => LCD_HEIGHT - 1,
198        n => usize::from(n).min(LCD_HEIGHT - 1),
199    };
200    let offset = usize::from(io.bit_offset());
201    let main_stride = ROW_NIBBLES + i64::from(io.line_offset()) + 2 * (offset as i64 / 4);
202    let main = std::iter::successors(Some(io.display_start()), move |&a| {
203        Some((((i64::from(a) + main_stride) as u32) & ADDR_MASK) & !1)
204    })
205    .take(last_main + 1)
206    .map(move |a| (a, offset));
207    let menu = std::iter::successors(Some(io.menu_start()), |&a| {
208        Some((a.wrapping_add(ROW_NIBBLES as u32) & ADDR_MASK) & !1)
209    })
210    .take(LCD_HEIGHT - 1 - last_main)
211    .map(|a| (a, 0));
212    main.chain(menu)
213}
214
215/// Fill one row: pixel x is bit `(x+offset)%4` of the nibble at
216/// `addr + (x+offset)/4`, least significant bit leftmost.
217fn render_row(row: &mut [bool], addr: u32, offset: usize, peek: &impl Fn(u32) -> u8) {
218    for (x, px) in row.iter_mut().enumerate() {
219        let bit = x + offset;
220        let nib = peek(addr.wrapping_add((bit / 4) as u32) & ADDR_MASK);
221        *px = nib >> (bit % 4) & 1 != 0;
222    }
223}
224
225/// The annunciators above the pixel area: six on the 48-family models
226/// (wiki: hardware/display, bit names after Giesselink: #10B LA1-LA4, #10C
227/// LA5-LA6), seven on the 42S (wiki: hardware/lewis "Annunciators") and
228/// seven on the 28S (wiki: hardware/hp28s "Annunciators"). The Lewis
229/// models' shift, print and run (busy) annunciators are reported as
230/// `left_shift`, `transmitting` and `busy`; `updown`, `g` exist only on
231/// the 42S, `battery` and `rad` on the 42S and 28S, `suspended` on the
232/// 28S.
233#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
234pub struct Annunciators {
235    /// Left shift (#10B bit 0); the 42S's shift.
236    pub left_shift: bool,
237    /// Right shift (#10B bit 1).
238    pub right_shift: bool,
239    /// Alpha (#10B bit 2).
240    pub alpha: bool,
241    /// Alert, the bell (#10B bit 3).
242    pub alert: bool,
243    /// Busy (#10C bit 0); the 42S's run annunciator.
244    pub busy: bool,
245    /// Transmitting, the I/O arrow (#10C bit 1); the 42S's print
246    /// annunciator.
247    pub transmitting: bool,
248    /// 42S: more menu rows (▲▼).
249    pub updown: bool,
250    /// 42S: low battery.
251    pub battery: bool,
252    /// 42S: "G" (lit with RAD in GRAD mode).
253    pub g: bool,
254    /// 42S and 28S: "RAD" (the 28S draws 2π).
255    pub rad: bool,
256    /// 28S: a program is suspended (a small circle).
257    pub suspended: bool,
258}
259
260impl Annunciators {
261    /// The 28S's seven annunciators from the slave chip's display RAM:
262    /// 5-nibble words eight nibbles apart from #FF800, written #FFFFF (on)
263    /// or 0 (off): busy, alpha, battery, shift, RAD, suspended program,
264    /// printer (seen in the ROM's behaviour: busy while it computes,
265    /// alpha and shift with their keys, RAD with the RAD command, battery
266    /// from the low-battery bit, suspended after HALT, printer while it
267    /// sends to the IR LED; wiki: hardware/hp28s "Annunciators"). The
268    /// printer is reported as `transmitting`, as the 42S's. The 19BII uses
269    /// the same words: its appointment alarm ((•)) in the 28S's busy word
270    /// (reported as `busy`, as the Pioneers' alarm), alpha, shift and RAD
271    /// as on the 28S (seen in its ROM's behaviour: a due appointment,
272    /// TEXT, shift, MODES; wiki: hardware/hp19bii "Annunciators"). A word counts
273    /// as lit when its first nibble is not 0, and nothing is lit while the
274    /// slave's DON is clear (inferred, as on the 42S).
275    pub(crate) fn from_clamshell(slave: &LewisIo) -> Self {
276        if !slave.display_on() {
277            return Self::default();
278        }
279        let lit = |i: usize| slave.ram_nibble(8 * i) != 0;
280        Self {
281            busy: lit(0),
282            alpha: lit(1),
283            battery: lit(2),
284            left_shift: lit(3),
285            rad: lit(4),
286            suspended: lit(5),
287            transmitting: lit(6),
288            ..Self::default()
289        }
290    }
291
292    /// Decode the annunciator byte (#10B in bits 0-3, #10C in bits 4-7).
293    /// Nothing is lit unless AON (#10C bit 3) is set; AON is independent of
294    /// DON (wiki: hardware/display "Bit names").
295    pub(crate) fn from_bits(bits: u8) -> Self {
296        if bits & 0x80 == 0 {
297            return Self::default();
298        }
299        Self {
300            left_shift: bits & 0x01 != 0,
301            right_shift: bits & 0x02 != 0,
302            alpha: bits & 0x04 != 0,
303            alert: bits & 0x08 != 0,
304            busy: bits & 0x10 != 0,
305            transmitting: bits & 0x20 != 0,
306            ..Self::default()
307        }
308    }
309
310    /// The 42S's seven annunciators from the Lewis display RAM: 5-nibble
311    /// words, eight nibbles apart, at #40218 (▲▼), #40220 (shift), #40228
312    /// (print), #40230 (busy), #40238 (battery), #40240 (G) and #40248
313    /// (RAD); the ROM writes #FFFFF (on) or 0 (off). The word at #40210
314    /// lights all of them (the ROM's display test writes it). Shift, ▲▼,
315    /// battery,
316    /// G and RAD were also seen in the ROM's behaviour (wiki:
317    /// hardware/lewis "Annunciators"). A word counts as lit when its
318    /// first nibble is not 0 (inferred), and nothing is lit while DON is
319    /// clear (inferred: the words are display RAM).
320    pub(crate) fn from_lewis(lewis: &LewisIo) -> Self {
321        if !lewis.display_on() {
322            return Self::default();
323        }
324        let all = lewis.ram_nibble(LEWIS_ANNUNCIATOR_ALL) != 0;
325        let lit = |i: usize| all || lewis.ram_nibble(LEWIS_ANNUNCIATORS + 8 * i) != 0;
326        Self {
327            updown: lit(0),
328            left_shift: lit(1),
329            transmitting: lit(2),
330            busy: lit(3),
331            battery: lit(4),
332            g: lit(5),
333            rad: lit(6),
334            ..Self::default()
335        }
336    }
337
338    /// Names and states: the 48's six left to right as on its label
339    /// strip, then the Lewis-only ones.
340    pub fn list(&self) -> [(&'static str, bool); 11] {
341        [
342            ("leftshift", self.left_shift),
343            ("rightshift", self.right_shift),
344            ("alpha", self.alpha),
345            ("alert", self.alert),
346            ("busy", self.busy),
347            ("transmit", self.transmitting),
348            ("updown", self.updown),
349            ("battery", self.battery),
350            ("g", self.g),
351            ("rad", self.rad),
352            ("suspended", self.suspended),
353        ]
354    }
355
356    /// One line naming the lit annunciators separated by spaces, or `-`
357    /// when none is lit; no trailing newline.
358    pub fn to_line(&self) -> String {
359        let lit: Vec<&str> = self
360            .list()
361            .iter()
362            .filter(|(_, on)| *on)
363            .map(|(n, _)| *n)
364            .collect();
365        if lit.is_empty() {
366            "-".to_string()
367        } else {
368            lit.join(" ")
369        }
370    }
371}
372
373/// Everything the display shows: pixels, annunciators and contrast.
374#[derive(Clone, Debug, PartialEq, Eq)]
375pub struct Framebuffer {
376    /// The pixel area: 131x64, 131x16 on the Pioneers, 137x32 on the 28S.
377    pub pixels: Lcd,
378    /// The annunciator row.
379    pub annunciators: Annunciators,
380    /// 5-bit contrast, 0-31, higher is darker (#101 bits 0-3, #102 bit 0).
381    pub contrast: u8,
382}
383
384impl Framebuffer {
385    /// The pixel area as text, identical to [`Lcd::to_text`].
386    pub fn to_text(&self) -> String {
387        self.pixels.to_text()
388    }
389
390    /// The annunciators as one line, see [`Annunciators::to_line`].
391    pub fn annunciator_line(&self) -> String {
392        self.annunciators.to_line()
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399
400    #[test]
401    fn annunciators_need_aon() {
402        assert_eq!(Annunciators::from_bits(0x3F), Annunciators::default());
403        let a = Annunciators::from_bits(0x80 | 0x21);
404        assert!(a.left_shift && a.transmitting);
405        assert!(!a.right_shift && !a.alpha && !a.alert && !a.busy);
406        assert_eq!(a.to_line(), "leftshift transmit");
407        assert_eq!(Annunciators::default().to_line(), "-");
408        // XTRA (#10C bit 2) is not an annunciator.
409        assert_eq!(
410            Annunciators::from_bits(0x80 | 0x40),
411            Annunciators::default()
412        );
413    }
414}