crates/tui/benches/render.rs 11.8 KiB raw
1
//! Render benchmark for core TUI widgets and layout.
2
//!
3
//! Builds a deterministic scene and computes a checksum to catch rendering
4
//! regressions across benchmark runs.
5
use std::hint::black_box;
6
use std::time::{Duration, Instant};
7
8
use rustik_tui as tui;
9
use rustik_tui_widgets::{List, ScrollView, ScrollbarStyle, Selection, Viewport};
10
11
use tui::{
12
    Border, Buffer, Cell, Color, Constraint, Fill, HStack, Label, Length, Line, Rect, Style, Table,
13
    TableOptions, VStack, Widget,
14
};
15
16
const WORKLOAD: &str = "render";
17
const AREA: Rect = Rect::new(0, 0, 640, 480);
18
const DEFAULT_FRAMES: usize = 500;
19
const LIST_ROWS: usize = 2_048;
20
const TABLE_ROWS: usize = 320;
21
const LOG_ROWS: usize = 4_096;
22
23
const ACTIVE_BORDER: Color = Color::Blue;
24
const INACTIVE_BORDER: Color = Color::Fixed(239);
25
const TABLE_BORDER: Color = Color::Fixed(236);
26
const DIM_TEXT: Color = Color::Fixed(244);
27
const HOT_TEXT: Color = Color::Yellow;
28
const OK_TEXT: Color = Color::Green;
29
const WARN_TEXT: Color = Color::Red;
30
const SELECTED_ACTIVE: Style = Style::new(Color::Unset).bg(Color::Blue);
31
const SELECTED_INACTIVE: Style = Style::new(Color::Unset).bg(Color::Fixed(238));
32
const DIVIDER_STYLE: Style = Style::new(Color::Fixed(239));
33
const FILL_STYLE: Style = Style::new(Color::Fixed(236));
34
35
fn main() {
36
    let args = Args::parse();
37
    let (elapsed, checksum) = run_headless(args.frames);
38
39
    black_box(checksum);
40
    report(args.frames, elapsed, checksum);
41
    if let Some(expected) = args.check {
42
        assert_eq!(
43
            checksum, expected,
44
            "deterministic render checksum changed for {WORKLOAD}"
45
        );
46
    }
47
}
48
49
fn run_headless(frames: usize) -> (Duration, usize) {
50
    let mut bench = Bench::new();
51
    let mut buffer = Buffer::empty(AREA);
52
53
    let start = Instant::now();
54
    let mut checksum = 0usize;
55
    for frame in 0..frames {
56
        buffer.clear();
57
        checksum ^= bench.frame(frame, AREA, &mut buffer);
58
        buffer.reset_dirty();
59
    }
60
    (start.elapsed(), checksum)
61
}
62
63
struct Args {
64
    frames: usize,
65
    check: Option<usize>,
66
}
67
68
impl Args {
69
    fn parse() -> Self {
70
        Self::parse_from(std::env::args().skip(1))
71
    }
72
73
    fn parse_from(args: impl IntoIterator<Item = String>) -> Self {
74
        let mut frames = DEFAULT_FRAMES;
75
        let mut check = None;
76
        let mut args = args.into_iter();
77
78
        while let Some(arg) = args.next() {
79
            match arg.as_str() {
80
                "--frames" => {
81
                    if let Some(value) = args.next().and_then(|value| value.parse().ok()) {
82
                        frames = value;
83
                    }
84
                }
85
                "--check" => {
86
                    if let Some(value) = args.next() {
87
                        check = parse_hex(&value);
88
                    }
89
                }
90
                "--help" | "-h" => {
91
                    println!(
92
                        "usage: cargo bench -p rustik-tui --bench render -- [--frames N] [--check HEX]"
93
                    );
94
                    std::process::exit(0);
95
                }
96
                value => {
97
                    if let Ok(value) = value.parse() {
98
                        frames = value;
99
                    }
100
                }
101
            }
102
        }
103
        Self { frames, check }
104
    }
105
}
106
107
fn parse_hex(value: &str) -> Option<usize> {
108
    usize::from_str_radix(value.trim_start_matches("0x"), 16).ok()
109
}
110
111
struct Bench {
112
    files: Vec<Line>,
113
    logs: Vec<String>,
114
    selection: Selection,
115
    viewport: Viewport,
116
}
117
118
impl Bench {
119
    fn new() -> Self {
120
        Self {
121
            files: files(),
122
            logs: logs(),
123
            selection: Selection::new(),
124
            viewport: Viewport::new(),
125
        }
126
    }
127
128
    fn frame(&mut self, frame: usize, area: Rect, buffer: &mut Buffer) -> usize {
129
        self.selection.select(frame % LIST_ROWS, LIST_ROWS);
130
        self.viewport
131
            .set_offset(frame * 3 % (LOG_ROWS - area.rows), LOG_ROWS, area.rows);
132
133
        render_dashboard(
134
            frame,
135
            self.selection.selected,
136
            self.viewport.view(LOG_ROWS, area.rows).offset,
137
            &self.files,
138
            &self.logs,
139
            area,
140
            buffer,
141
        );
142
        sample_buffer(buffer, frame)
143
    }
144
}
145
146
fn render_dashboard(
147
    frame: usize,
148
    selected: usize,
149
    log_offset: usize,
150
    files: &[Line],
151
    logs: &[String],
152
    area: Rect,
153
    buffer: &mut Buffer,
154
) {
155
    let active = !frame.is_multiple_of(3);
156
    let list = List::new(files.iter().cloned())
157
        .selected(selected)
158
        .active(active)
159
        .selected_styles(SELECTED_ACTIVE, SELECTED_INACTIVE)
160
        .scrollbar(scrollbar_style(DIM_TEXT, HOT_TEXT));
161
    let table = stats_table(frame, selected);
162
    let preview = preview_lines(frame, selected);
163
    let scroll = ScrollView::new(area, log_offset, |cols| log_lines(logs, cols))
164
        .scrollbar(scrollbar_style(DIM_TEXT, OK_TEXT));
165
    let summary = HStack::default()
166
        .child(Label::new("frame").fg(DIM_TEXT))
167
        .child(Label::from(format!("{frame:08}")).fg(HOT_TEXT))
168
        .spacer()
169
        .child(Label::new("selected").fg(DIM_TEXT))
170
        .child(Label::from(format!("{selected:04}")).fg(OK_TEXT));
171
172
    let left = VStack::default()
173
        .border(Some(Border::new(if active {
174
            ACTIVE_BORDER
175
        } else {
176
            INACTIVE_BORDER
177
        })))
178
        .child(summary)
179
        .divider_cell(Cell::new('─', DIVIDER_STYLE))
180
        .fill(list);
181
    let middle = VStack::default()
182
        .border(Some(Border::new(TABLE_BORDER)))
183
        .child(Label::new("render metrics").fg(HOT_TEXT))
184
        .divider()
185
        .child_with_height(table, Length::Fixed(24))
186
        .divider_cell(Cell::new('┄', DIVIDER_STYLE))
187
        .child_with_height(preview, Length::Fixed(18))
188
        .fill(Fill::new('·', FILL_STYLE));
189
    let right = VStack::default()
190
        .border(Some(Border::new(INACTIVE_BORDER)))
191
        .child(Label::new("scrolling log").fg(DIM_TEXT))
192
        .divider()
193
        .fill(scroll);
194
195
    HStack::default()
196
        .child(left)
197
        .child(middle)
198
        .child(right)
199
        .render(area, buffer);
200
}
201
202
fn scrollbar_style(track: Color, thumb: Color) -> ScrollbarStyle {
203
    ScrollbarStyle::new(
204
        Cell::new('┆', Style::new(track).bg(Color::Fixed(235))),
205
        Cell::new('█', Style::new(thumb).bg(Color::Fixed(235))),
206
    )
207
}
208
209
fn stats_table(frame: usize, selected: usize) -> Table<5, Label> {
210
    let mut table = Table::new(TableOptions::bordered());
211
212
    table.header(labels(["name", "value", "delta", "state", "note"]));
213
    table.divider();
214
    for row in 0..TABLE_ROWS {
215
        let value = frame.wrapping_mul(row + 17) % 1_000_003;
216
        let delta = value as isize - selected as isize;
217
        let state = match row % 4 {
218
            0 => Label::new("hot").fg(WARN_TEXT),
219
            1 => Label::new("warm").fg(HOT_TEXT),
220
            2 => Label::new("ok").fg(OK_TEXT),
221
            _ => Label::new("idle").fg(DIM_TEXT),
222
        };
223
        table.push([
224
            Label::from(format!("counter-{row:03}")),
225
            Label::from(format!("{value:08}")),
226
            Label::from(format!("{delta:+07}")),
227
            state,
228
            Label::from(format!("bucket {}", (row + selected) % 97)),
229
        ]);
230
        if row % 40 == 39 {
231
            table.divider_with_sigil('┄');
232
        }
233
    }
234
    table
235
}
236
237
fn labels<const N: usize>(items: [&str; N]) -> [Label; N] {
238
    items.map(Label::new)
239
}
240
241
fn preview_lines(frame: usize, selected: usize) -> Vec<Line> {
242
    (0..128)
243
        .map(|row| {
244
            let width = 24 + (row + selected + frame) % 96;
245
            Line::spaced([
246
                Label::from(format!("{row:03}")).fg(DIM_TEXT),
247
                Label::from_char('│').fg(INACTIVE_BORDER),
248
                Label::from("▸".repeat(row % 5 + 1)).fg(HOT_TEXT),
249
                Label::from("x".repeat(width)),
250
            ])
251
        })
252
        .collect()
253
}
254
255
fn log_lines(logs: &[String], cols: usize) -> Vec<Line> {
256
    logs.iter()
257
        .enumerate()
258
        .map(|(index, line)| {
259
            let tag = match index % 5 {
260
                0 => Label::new("TRACE").fg(DIM_TEXT),
261
                1 => Label::new("INFO ").fg(OK_TEXT),
262
                2 => Label::new("WARN ").fg(HOT_TEXT),
263
                3 => Label::new("ERROR").fg(WARN_TEXT),
264
                _ => Label::new("DEBUG").fg(DIM_TEXT),
265
            };
266
            Line::spaced([
267
                tag,
268
                Label::from(format!("{index:04}")).fg(DIM_TEXT),
269
                Label::from(line.clone()).bg(if cols.is_multiple_of(2) {
270
                    Color::Unset
271
                } else {
272
                    Color::Fixed(235)
273
                }),
274
            ])
275
        })
276
        .collect()
277
}
278
279
fn files() -> Vec<Line> {
280
    (0..LIST_ROWS)
281
        .map(|row| {
282
            let color = match row % 6 {
283
                0 => OK_TEXT,
284
                1 => HOT_TEXT,
285
                2 => WARN_TEXT,
286
                _ => DIM_TEXT,
287
            };
288
            Line::spaced([
289
                Label::from(format!("{row:04}")).fg(DIM_TEXT),
290
                Label::new("src").fg(INACTIVE_BORDER),
291
                Label::from(format!("module_{:02}/component_{row:04}.rs", row % 41)).fg(color),
292
                Label::from(format!("{} cols", 40 + row % 180)).fg(DIM_TEXT),
293
            ])
294
        })
295
        .collect()
296
}
297
298
fn logs() -> Vec<String> {
299
    (0..LOG_ROWS)
300
        .map(|row| {
301
            format!(
302
                "render pass {row:04}: table rows={TABLE_ROWS}, list rows={LIST_ROWS}, unicode=╭─╮ λ ❤️ {}",
303
                "payload ".repeat(row % 11 + 1)
304
            )
305
        })
306
        .collect()
307
}
308
309
fn sample_buffer(buffer: &Buffer, frame: usize) -> usize {
310
    let area = buffer.area();
311
    let mut checksum = frame;
312
    for row in (0..area.rows).step_by(7) {
313
        for col in (0..area.cols).step_by(11) {
314
            if let Some(cell) = buffer.get(area.x + col, area.y + row) {
315
                checksum = checksum.wrapping_mul(16_777_619) ^ cell.glyph().len();
316
                checksum ^= color_id(cell.style().fg_color());
317
                checksum ^= color_id(cell.style().bg_color()).rotate_left(7);
318
            }
319
        }
320
    }
321
    checksum
322
}
323
324
fn color_id(color: Color) -> usize {
325
    match color {
326
        Color::Unset => 0,
327
        Color::Black => 1,
328
        Color::Red => 2,
329
        Color::Green => 3,
330
        Color::Yellow => 4,
331
        Color::Blue => 5,
332
        Color::Magenta => 6,
333
        Color::Cyan => 7,
334
        Color::White => 8,
335
        Color::Fixed(value) => 0x100 + usize::from(value),
336
        Color::RGB(r, g, b) => {
337
            0x1_0000 + (usize::from(r) << 16) + (usize::from(g) << 8) + usize::from(b)
338
        }
339
    }
340
}
341
342
/// Prints the benchmark result as a styled terminal widget.
343
fn report(frames: usize, elapsed: Duration, checksum: usize) {
344
    let seconds = elapsed.as_secs_f64();
345
    let fps = frames as f64 / seconds;
346
    let cells = AREA.cols * AREA.rows * frames;
347
    let mcells = cells as f64 / seconds / 1_000_000.0;
348
349
    let mut table = Table::new(TableOptions {
350
        spacing: 3,
351
        ..TableOptions::default()
352
    });
353
    table.push([
354
        Label::new(WORKLOAD).style(Style::default().bold()),
355
        Label::from(format!("{fps:.1} frames/s")).fg(Color::White),
356
    ]);
357
    table.push([
358
        Label::new("frames").style(Style::default().bold()),
359
        Label::from(format!("{frames}")).fg(Color::White),
360
    ]);
361
    table.push([
362
        Label::new("area").style(Style::default().bold()),
363
        Label::from(format!("{}x{}", AREA.cols, AREA.rows)).fg(Color::White),
364
    ]);
365
    table.push([
366
        Label::new("elapsed").style(Style::default().bold()),
367
        Label::from(format!("{seconds:.3}s")).fg(Color::White),
368
    ]);
369
    table.push([
370
        Label::new("buffer").style(Style::default().bold()),
371
        Label::from(format!("{mcells:.1} Mcells/s")).fg(Color::White),
372
    ]);
373
    table.push([
374
        Label::new("checksum").style(Style::default().bold()),
375
        Label::from(format!("{checksum:#x}")).fg(DIM_TEXT),
376
    ]);
377
378
    for line in table.lines(Constraint::UNBOUNDED) {
379
        println!("{}", line.styled());
380
    }
381
}