std_console/
std_console.rs

1use std::{
2    io::{stdout, Write},
3    mem,
4    thread::sleep,
5    time::{Duration, Instant},
6};
7
8use toroid::Donut;
9
10fn main() {
11    const WIDTH: u8 = 80;
12    const HEIGHT: u8 = 22;
13    const SIZE: usize = (WIDTH as usize) * (HEIGHT as usize);
14
15    // Create the donut instance and pre allocate buffers
16    let mut donut = Donut::<WIDTH, HEIGHT>::new();
17    let mut output = [' '; SIZE];
18    let mut zbuf = [0.0_f32; SIZE];
19
20    // Clear the terminal
21    print!("\x1B[2J");
22    let stdout = stdout();
23    let mut handle = stdout.lock();
24
25    loop {
26        // Start timing this frame
27        let start = Instant::now();
28
29        // Render the donut into output and depth buffers
30        donut.render_frame_in_place(&mut output, &mut zbuf);
31
32        // Reset cursor to top left
33        write!(handle, "\x1B[H").unwrap();
34
35        // Write output buffer
36        for line in output.chunks(WIDTH as usize) {
37            for &ch in line {
38                handle.write_all(&[ch as u8]).unwrap();
39            }
40
41            handle.write_all(b"\n").unwrap();
42        }
43
44        // Write the status line with FPS and memory usage.
45        writeln!(
46            handle,
47            "\nFPS: {:>5.1} | Approx Mem: {}",
48            1.0 / start.elapsed().as_secs_f32().max(0.0001),
49            {
50                let u =
51                    mem::size_of_val(&output) + mem::size_of_val(&zbuf) + mem::size_of_val(&donut);
52
53                if u < 1024 {
54                    format!("{} bytes", u)
55                } else if u < 1024 * 1024 {
56                    format!("{:.1} KB", u as f32 / 1024.0)
57                } else {
58                    format!("{:.1} MB", u as f32 / (1024.0 * 1024.0))
59                }
60            }
61        )
62        .unwrap();
63
64        handle.flush().unwrap();
65
66        // Rotate for the next frame and sleep briefly.
67        donut.rotate(0.07, 0.03);
68        sleep(Duration::from_millis(20));
69    }
70}