termin-8 0.1.1

CHIP-8 emulator that runs in your terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
extern crate ansi_colours;
use ansi_colours::*;

extern crate ini;
use ini::Ini;

extern crate clap;
use clap::{crate_version, App, Arg};

//mod chip8;
//use chip8::Chip8;
//use chip8::Quirks;
extern crate deca;
use deca::Chip8;
use deca::Quirks;

//extern crate drawille;
//use drawille::Canvas;

extern crate dirs;
use dirs::{config_dir, home_dir};

use crossterm::{
    cursor,
    event::{poll, read, Event, KeyCode, KeyEvent, KeyModifiers},
    execute, queue, style, terminal,
    terminal::{
        disable_raw_mode, enable_raw_mode, size, Clear, ClearType, DisableLineWrap, EnableLineWrap,
        EnterAlternateScreen, LeaveAlternateScreen,
    },
    Result,
};
use std::io::{stdout, Write};
use std::time::Duration;
use std::u8;

fn main() {
    let matches = App::new("Termin-8")
        .version(crate_version!())
        .author("Tobias V. Langhoff <tobias@langhoff.no>")
        .about("Octo emulator")
        .arg(Arg::with_name("tickrate")
                .short("t")
                .long("tickrate")
                .takes_value(true)
                .value_name("TICKRATE")
                .help("Instructions to execute per 60Hz frame")
                .default_value("40")
        )
        .arg(Arg::with_name("config")
                .short("c")
                .long("config")
                .takes_value(true)
                .value_name("CONFIG_FILE")
                .help("Configuration file, compatible with C-Octo")
                .default_value("~/.octo.rc")
        )
        .arg(Arg::with_name("quirks")
                .short("q")
                .long("quirks")
                .takes_value(true)
                .value_name("COMPATIBILITY_PROFILE")
                .help("Force quirky behavior for platform compatibility.\n(For fine-tuned quirks configuration, you can toggle individual settings in a configuration file; see --config)\nPossible values: chip8, schip, octo")
                .default_value("octo")
        )
        .arg(
            Arg::with_name("ROM")
                .help("CHIP-8 ROM file")
                .required(true) // for the time being
                //.index(1),
        )
        .get_matches();

    let rom = std::fs::read(matches.value_of("ROM").unwrap()).expect("Couldn't load ROM");

    let quirks = match matches.value_of("quirks").unwrap() {
        "vip" => Quirks {
            shift: false,
            loadstore: false,
            jump0: false,
            logic: true,
            clip: true,
            vblank: true,
            resclear: false,
            delaywrap: false,
            multicollision: false,
            loresbigsprite: false,
            lorestallsprite: false,
            max_rom: 3216,
        },
        "schip" => Quirks {
            shift: true,
            loadstore: true,
            jump0: true,
            logic: false,
            clip: true,
            vblank: false,
            resclear: false,
            delaywrap: false,
            multicollision: false,
            loresbigsprite: false,
            lorestallsprite: false,
            max_rom: 3583,
        },
        _ => Quirks {
            shift: false,
            loadstore: false,
            jump0: false,
            logic: false,
            clip: false,
            vblank: false,
            resclear: false,
            delaywrap: false,
            multicollision: false,
            loresbigsprite: false,
            lorestallsprite: false,
            max_rom: 65024,
        },
    };

    let mut chip8 = Chip8::new(quirks);

    if rom.len() > chip8.quirks.max_rom as usize {
        println!("Warning: ROM size ({}) exceeds maximum available memory on target platform ({}) (will try to run anyway)", rom.len(), chip8.quirks.max_rom)
    }

    chip8.read_rom(&rom);

    let tickrate = match matches.value_of("num") {
        None => 400,
        Some(s) => s.parse::<u16>().unwrap_or(400),
    };

    let mut stdout = stdout();

    execute!(stdout, EnterAlternateScreen, Clear(ClearType::All)).unwrap();
    enable_raw_mode().unwrap();
    execute!(stdout, DisableLineWrap, cursor::Hide).unwrap();

    let conf = Ini::load_from_file("/home/tvl/.octo.rc").unwrap();
    let section = conf.section(None::<String>).unwrap();

    let bg_color = color_from_ini(section, "color.plane0");
    let fg_color = color_from_ini(section, "color.plane1");

    execute!(stdout, style::SetBackgroundColor(bg_color)).unwrap();
    execute!(stdout, style::SetForegroundColor(fg_color)).unwrap();

    let big_charset = vec!["  ", "██"];
    let thin_charset = vec![" ", ""];
    let small_charset = vec![" ", "", "", ""];
    let smallest_charset = vec![
        " ", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    ];
    let (width, height) = size().unwrap();
    let mut charset = if width >= chip8.display.width * 2 && height >= chip8.display.height {
        &big_charset
    } else {
        //if width >= chip8.display.width && height >= chip8.display.height {
        &thin_charset
        //    } else if width >= chip8.display.width / 2 && height >= chip8.display.height {
        //        &small_charset
        //    } else {
        //        &smallest_charset
    };

    let mut interrupt = true;
    let mut halted = false;

    loop {
        let mut halt_message = if !interrupt && !halted {
            match chip8.run(tickrate) {
                Err(error) => {
                    halted = true;
                    error
                }
                Ok(_) => "".to_string(),
            }
        } else {
            "".to_string()
        };

        // check for debug keypress
        // check for regular keypress?
        for key in chip8.keyboard.iter_mut() {
            *key = false;
        }
        loop {
            if poll(Duration::from_millis(1)).unwrap() {
                // It's guaranteed that the `read()` won't block when the `poll()`
                // function returns `true`
                match read().unwrap() {
                    Event::Key(keyevent) => match keyevent.code {
                        KeyCode::Esc => exit(),
                        KeyCode::Char('1') => chip8.keyboard[0x1] = true,
                        KeyCode::Char('2') => chip8.keyboard[0x2] = true,
                        KeyCode::Char('3') => chip8.keyboard[0x3] = true,
                        KeyCode::Char('4') => chip8.keyboard[0xC] = true,
                        KeyCode::Char('q') | KeyCode::Char(' ') => chip8.keyboard[0x4] = true,
                        KeyCode::Char('w') | KeyCode::Up => chip8.keyboard[0x5] = true,
                        KeyCode::Char('e') => chip8.keyboard[0x6] = true,
                        KeyCode::Char('r') => chip8.keyboard[0xD] = true,
                        KeyCode::Char('a') | KeyCode::Left => chip8.keyboard[0x7] = true,
                        KeyCode::Char('s') | KeyCode::Down => chip8.keyboard[0x8] = true,
                        KeyCode::Char('d') | KeyCode::Right => chip8.keyboard[0x9] = true,
                        KeyCode::Char('f') => chip8.keyboard[0xE] = true,
                        KeyCode::Char('z') => chip8.keyboard[0xA] = true,
                        KeyCode::Char('x') => chip8.keyboard[0x0] = true,
                        KeyCode::Char('c') => {
                            if keyevent.modifiers.contains(KeyModifiers::CONTROL) {
                                exit()
                            } else {
                                chip8.keyboard[0xB] = true
                            }
                        }
                        KeyCode::Char('v') => chip8.keyboard[0xF] = true,
                        KeyCode::Char('i') => interrupt = !interrupt,
                        KeyCode::Char('o') => {
                            if interrupt && !halted {
                                halt_message = match chip8.run(1) {
                                    Err(error) => {
                                        halted = true;
                                        error
                                    }
                                    Ok(_) => "".to_string(),
                                }
                            }
                        }
                        KeyCode::Char('m') => (),
                        _ => (),
                    },
                    Event::Resize(width, height) => {
                        execute!(stdout, Clear(ClearType::All)).unwrap();
                        execute!(stdout, cursor::Hide).unwrap();
                        chip8.display.dirty = true;
                        charset =
                            if width >= chip8.display.width * 2 && height >= chip8.display.height {
                                &big_charset
                            } else {
                                // if width >= chip8.display.width && height >= chip8.display.height {
                                &thin_charset
                                //} else if width >= chip8.display.width / 2 && height >= chip8.display.height {
                                //    &small_charset
                                //} else {
                                //    &smallest_charset
                            };
                    }
                    _ => (),
                }
            } else {
                break;
            }
        }

        if chip8.display.dirty {
            let (width, height) = size().unwrap();

            execute!(
                stdout,
                terminal::SetTitle(format!(
                    "{}x{} actual, {}x{} c8, {} colors",
                    width.to_string(),
                    height.to_string(),
                    chip8.display.width.to_string(),
                    chip8.display.height.to_string(),
                    style::available_color_count()
                ))
            )
            .unwrap();

            // draw to terminal
            queue!(stdout, cursor::MoveTo(0, 0)).unwrap();
            execute!(stdout, style::SetBackgroundColor(bg_color)).unwrap();
            execute!(stdout, style::SetForegroundColor(fg_color)).unwrap();

            if width >= chip8.display.width && height >= chip8.display.height {
                for y in 0..chip8.display.height {
                    for x in 0..chip8.display.width {
                        queue!(
                            stdout,
                            style::Print(
                                charset[chip8.display.display[y as usize][x as usize] as usize]
                                    .to_string()
                            )
                        )
                        .unwrap();
                    }
                    queue!(stdout, cursor::MoveToNextLine(0)).unwrap();
                }
            } else if width >= chip8.display.width && height >= chip8.display.height / 2 {
                for y in (0..chip8.display.height).step_by(2) {
                    for x in 0..chip8.display.width {
                        let pixels = (chip8.display.display[y as usize][x as usize] << 1)
                            | chip8.display.display[(y + 1) as usize][x as usize];
                        queue!(
                            stdout,
                            style::Print(small_charset[pixels as usize].to_string())
                        )
                        .unwrap();
                    }
                    queue!(stdout, cursor::MoveToNextLine(0)).unwrap();
                }
            } else {
                //let mut canvas =
                //    Canvas::new(chip8.display.width as u32, chip8.display.height as u32);
                //canvas.set(5, 4);
                //for y in (0..chip8.display.height) {
                //    for x in (0..chip8.display.width) {
                //        if chip8.display.display[y as usize][x as usize] == 1 {
                //            canvas.set(x as u32, y as u32);
                //        }
                //    }
                //}
                //execute!(stdout, style::Print(canvas.frame()));

                for y in (0..chip8.display.height).step_by(2) {
                    for x in (0..chip8.display.width).step_by(2) {
                        let pixels = (chip8.display.display[y as usize][x as usize] << 3)
                            | (chip8.display.display[y as usize][(x + 1) as usize] << 2)
                            | (chip8.display.display[(y + 1) as usize][x as usize] << 1)
                            | chip8.display.display[(y + 1) as usize][(x + 1) as usize];
                        queue!(
                            stdout,
                            //style::SetBackgroundColor(bg_color),
                            style::Print(smallest_charset[pixels as usize].to_string())
                        )
                        .unwrap();
                    }
                    queue!(stdout, cursor::MoveToNextLine(0)).unwrap();
                }
            };
            stdout.flush().unwrap();
        }
        if interrupt || halted {
            execute!(stdout, cursor::MoveTo(0, chip8.display.height + 1)).unwrap();
            execute!(stdout, style::ResetColor).unwrap();
            if halted {
                execute!(stdout, style::SetForegroundColor(style::Color::Red)).unwrap();
                execute!(stdout, style::Print(halt_message.to_string())).unwrap();
                execute!(stdout, cursor::MoveToNextLine(0)).unwrap();
                execute!(stdout, style::ResetColor).unwrap();
            };
            execute!(
                stdout,
                style::Print(format!(
                    "PC: {:#06X} ({:#04x}{:02x})",
                    chip8.pc,
                    chip8.memory[chip8.pc as usize],
                    chip8.memory[chip8.pc as usize + 1],
                ))
            )
            .unwrap();
            execute!(stdout, cursor::MoveToNextLine(0)).unwrap();
            execute!(stdout, style::Print(format!("I: {:#06X}", chip8.i))).unwrap();
            execute!(stdout, cursor::MoveToNextLine(0)).unwrap();
            for v in 0..16 {
                execute!(
                    stdout,
                    style::Print(format!("V{:X}: {:#04X}  ", v, chip8.v[v] as usize))
                )
                .unwrap();
            }
            execute!(stdout, cursor::MoveToNextLine(0)).unwrap();
            for v in 0..16 {
                execute!(
                    stdout,
                    style::Print(format!("K{:X}: {} ", v, chip8.keyboard[v]))
                )
                .unwrap();
            }
        } else {
            execute!(stdout, style::ResetColor).unwrap();
            execute!(
                stdout,
                cursor::MoveTo(0, chip8.display.height + 1),
                Clear(ClearType::FromCursorDown)
            )
            .unwrap();
        }
        // play sound if chip8.sound is greater than 0
    }
}

fn color_from_ini(section: &ini::Properties, attribute: &str) -> style::Color {
    let mut v = vec![];
    let mut cur = section.get(attribute).unwrap();
    while !cur.is_empty() {
        let (chunk, rest) = cur.split_at(std::cmp::min(2, cur.len()));
        v.push(chunk);
        cur = rest;
    }

    let rgb = (
        u8::from_str_radix(v[0], 16).unwrap(),
        u8::from_str_radix(v[1], 16).unwrap(),
        u8::from_str_radix(v[2], 16).unwrap(),
    );

    if style::available_color_count() > 256 {
        style::Color::Rgb {
            r: rgb.0,
            g: rgb.1,
            b: rgb.2,
        }
    } else {
        style::Color::AnsiValue(ansi256_from_rgb(rgb))
    }
}

fn exit() {
    disable_raw_mode().unwrap();
    execute!(stdout(), LeaveAlternateScreen, EnableLineWrap, cursor::Show).unwrap();
    std::process::exit(0);
}