dotmax 0.1.9

High-performance terminal braille rendering for images, animations, and graphics
Documentation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Animation benchmarks for Stories 6.1, 6.2, and 6.5
//!
//! Validates performance requirements:
//! - Buffer swap time: <1ms (target: <1μs actual)
//! - Buffer creation: baseline measurement
//! - Frame timing overhead: <1ms
//! - FPS calculation: baseline measurement
//! - Differential rendering: 60-80% I/O reduction

// Allow certain clippy warnings that are acceptable in benchmarks
#![allow(clippy::cast_precision_loss)]

use criterion::{criterion_group, criterion_main, Criterion};
use dotmax::animation::{DifferentialRenderer, FrameBuffer, FrameTimer};
use dotmax::BrailleGrid;
use std::hint::black_box;

/// Benchmark: `FrameBuffer` creation (80x24 standard terminal)
///
/// Measures allocation time for two `BrailleGrid` buffers.
fn bench_frame_buffer_creation_80x24(c: &mut Criterion) {
    c.bench_function("frame_buffer_creation_80x24", |b| {
        b.iter(|| black_box(FrameBuffer::new(80, 24)));
    });
}

/// Benchmark: `FrameBuffer` creation (200x50 large buffer)
///
/// Measures allocation time for larger animation buffers.
fn bench_frame_buffer_creation_200x50(c: &mut Criterion) {
    c.bench_function("frame_buffer_creation_200x50", |b| {
        b.iter(|| black_box(FrameBuffer::new(200, 50)));
    });
}

/// Benchmark: `swap_buffers()` operation (80x24)
///
/// **AC #7 Target: <1ms (95th percentile)**
///
/// This should be an O(1) pointer swap, so actual time should be <1μs.
fn bench_swap_buffers_80x24(c: &mut Criterion) {
    c.bench_function("swap_buffers_80x24", |b| {
        let mut buffer = FrameBuffer::new(80, 24);

        // Pre-populate with some data for realistic measurement
        for y in 0..24 {
            for x in 0..80 {
                let _ = buffer.get_back_buffer().set_dot(x * 2, y * 4);
            }
        }

        b.iter(|| {
            buffer.swap_buffers();
            black_box(&buffer);
        });
    });
}

/// Benchmark: `swap_buffers()` operation (200x50 large buffer)
///
/// Verifies O(1) scaling - large buffers should swap as fast as small ones.
fn bench_swap_buffers_200x50(c: &mut Criterion) {
    c.bench_function("swap_buffers_200x50", |b| {
        let mut buffer = FrameBuffer::new(200, 50);

        // Pre-populate with some data
        for y in 0..50 {
            for x in 0..200 {
                let _ = buffer.get_back_buffer().set_dot(x * 2, y * 4);
            }
        }

        b.iter(|| {
            buffer.swap_buffers();
            black_box(&buffer);
        });
    });
}

/// Benchmark: `get_back_buffer()` access time
///
/// Measures the overhead of acquiring mutable reference to back buffer.
fn bench_get_back_buffer(c: &mut Criterion) {
    c.bench_function("get_back_buffer", |b| {
        let mut buffer = FrameBuffer::new(80, 24);

        b.iter(|| {
            black_box(buffer.get_back_buffer());
        });
    });
}

/// Benchmark: Full frame preparation cycle
///
/// Measures: clear + draw pattern + swap (typical animation frame)
fn bench_full_frame_cycle(c: &mut Criterion) {
    c.bench_function("full_frame_cycle_80x24", |b| {
        let mut buffer = FrameBuffer::new(80, 24);

        b.iter(|| {
            // Clear back buffer
            buffer.get_back_buffer().clear();

            // Draw something (simulated ball at position)
            let _ = buffer.get_back_buffer().set_dot(40, 48);
            let _ = buffer.get_back_buffer().set_dot(41, 48);
            let _ = buffer.get_back_buffer().set_dot(40, 49);
            let _ = buffer.get_back_buffer().set_dot(41, 49);

            // Swap buffers
            buffer.swap_buffers();

            black_box(&buffer);
        });
    });
}

// ============================================================================
// Story 6.2: FrameTimer Benchmarks
// ============================================================================

/// Benchmark: `FrameTimer` creation
///
/// Measures initialization overhead including `VecDeque` allocation.
fn bench_frame_timer_creation(c: &mut Criterion) {
    c.bench_function("frame_timer_creation", |b| {
        b.iter(|| black_box(FrameTimer::new(60)));
    });
}

/// Benchmark: `FrameTimer::actual_fps()` calculation
///
/// Measures the overhead of calculating rolling average FPS.
/// Should be negligible (<100μs).
fn bench_frame_timer_actual_fps(c: &mut Criterion) {
    c.bench_function("frame_timer_actual_fps", |b| {
        // Pre-populate with frame data for realistic measurement
        let mut timer = FrameTimer::new(60);

        // Simulate 60 frames worth of data by calling wait_for_next_frame
        // with artificial short sleeps
        for _ in 0..60 {
            // Record a synthetic frame time
            timer.wait_for_next_frame();
        }

        b.iter(|| {
            black_box(timer.actual_fps());
        });
    });
}

/// Benchmark: `FrameTimer::frame_time()` retrieval
///
/// Measures the overhead of getting the last frame duration.
fn bench_frame_timer_frame_time(c: &mut Criterion) {
    c.bench_function("frame_timer_frame_time", |b| {
        let mut timer = FrameTimer::new(60);
        timer.wait_for_next_frame(); // Record at least one frame

        b.iter(|| {
            black_box(timer.frame_time());
        });
    });
}

/// Benchmark: `FrameTimer::reset()` operation
///
/// Measures the overhead of resetting timer state.
fn bench_frame_timer_reset(c: &mut Criterion) {
    c.bench_function("frame_timer_reset", |b| {
        let mut timer = FrameTimer::new(60);

        // Pre-populate with frame data
        for _ in 0..60 {
            timer.wait_for_next_frame();
        }

        b.iter(|| {
            timer.reset();
            black_box(&timer);
        });
    });
}

/// Benchmark: Full frame timing cycle overhead
///
/// Measures the computational overhead of `wait_for_next_frame()`
/// excluding the actual sleep time. This uses a high FPS to minimize
/// sleep and measure pure overhead.
fn bench_frame_timer_overhead(c: &mut Criterion) {
    c.bench_function("frame_timer_wait_overhead", |b| {
        // Use 240 FPS to minimize sleep time
        let mut timer = FrameTimer::new(240);

        b.iter(|| {
            // Measure just the calculation overhead
            // Note: This will include minimal sleep but focuses on computational work
            timer.wait_for_next_frame();
            black_box(&timer);
        });
    });
}

// ============================================================================
// Story 6.5: Differential Rendering Benchmarks
// ============================================================================

/// Benchmark: Create `DifferentialRenderer`
fn bench_differential_renderer_creation(c: &mut Criterion) {
    c.bench_function("differential_renderer_creation", |b| {
        b.iter(|| black_box(DifferentialRenderer::new()));
    });
}

/// Benchmark: Count changed cells (comparison logic overhead)
///
/// Measures the overhead of comparing two frames.
fn bench_differential_count_changes(c: &mut Criterion) {
    c.bench_function("differential_count_changes_80x24", |b| {
        let renderer = DifferentialRenderer::new();
        let frame1 = BrailleGrid::new(80, 24).unwrap();
        let mut frame2 = BrailleGrid::new(80, 24).unwrap();
        // Set 5% of cells as changed (typical animation scenario)
        for i in 0..96 {
            let x = (i * 7) % 160; // Spread changes across grid
            let y = (i * 13) % 96;
            let _ = frame2.set_dot(x, y);
        }

        b.iter(|| black_box(renderer.count_changed_cells(&frame2, &frame1)));
    });
}

/// Benchmark: Identical frames comparison (best case)
///
/// Measures comparison overhead when no changes detected.
fn bench_differential_no_changes(c: &mut Criterion) {
    c.bench_function("differential_no_changes_80x24", |b| {
        let renderer = DifferentialRenderer::new();
        let frame1 = BrailleGrid::new(80, 24).unwrap();
        let frame2 = BrailleGrid::new(80, 24).unwrap();

        b.iter(|| black_box(renderer.count_changed_cells(&frame2, &frame1)));
    });
}

/// Benchmark: Full frame comparison (worst case)
///
/// Measures comparison overhead when all cells differ.
fn bench_differential_all_changes(c: &mut Criterion) {
    c.bench_function("differential_all_changes_80x24", |b| {
        let renderer = DifferentialRenderer::new();
        let frame1 = BrailleGrid::new(80, 24).unwrap();
        let mut frame2 = BrailleGrid::new(80, 24).unwrap();
        // Set all cells as different
        for y in 0..96 {
            for x in 0..160 {
                let _ = frame2.set_dot(x, y);
            }
        }

        b.iter(|| black_box(renderer.count_changed_cells(&frame2, &frame1)));
    });
}

/// Benchmark: Moving object simulation
///
/// Simulates typical animation: static background with small moving object.
/// Verifies 60-80% I/O reduction target.
fn bench_differential_moving_object(c: &mut Criterion) {
    c.bench_function("differential_moving_object_80x24", |b| {
        let renderer = DifferentialRenderer::new();

        // Static background frame (border)
        let mut frame1 = BrailleGrid::new(80, 24).unwrap();
        // Draw border (static content)
        for x in 0..160 {
            let _ = frame1.set_dot(x, 0);
            let _ = frame1.set_dot(x, 95);
        }
        for y in 0..96 {
            let _ = frame1.set_dot(0, y);
            let _ = frame1.set_dot(159, y);
        }

        // Frame with border + moved ball (only ~1-2% changed)
        let mut frame2 = frame1.clone();
        // New ball at (22, 22) - different position from frame1 (which has no ball)
        for dy in 0..8 {
            for dx in 0..4 {
                let _ = frame2.set_dot(44 + dx, 44 + dy);
            }
        }

        b.iter(|| {
            let changed = renderer.count_changed_cells(&frame2, &frame1);
            black_box(changed);
        });
    });
}

/// Verify I/O reduction calculation
///
/// This benchmark verifies that typical animations achieve 60-80%+ I/O reduction.
fn bench_differential_io_reduction_verification(c: &mut Criterion) {
    c.bench_function("differential_io_reduction_verify", |b| {
        let renderer = DifferentialRenderer::new();

        // Static background (80x24 = 1920 cells)
        let frame1 = BrailleGrid::new(80, 24).unwrap();

        // Frame with 5% changed cells (96 cells)
        let mut frame2 = BrailleGrid::new(80, 24).unwrap();
        for i in 0..96 {
            let x = (i * 17) % 160;
            let y = (i * 23) % 96;
            let _ = frame2.set_dot(x, y);
        }

        b.iter(|| {
            let total_cells = 80 * 24; // 1920
            let changed = renderer.count_changed_cells(&frame2, &frame1);
            let reduction = ((total_cells - changed) as f64 / total_cells as f64) * 100.0;
            black_box(reduction);
            // Verify: reduction should be >60% (target: 60-80%)
            assert!(
                reduction > 60.0,
                "I/O reduction should be >60%, got {reduction:.1}%"
            );
        });
    });
}

// ============================================================================
// Story 7.2: 60fps Sustained Benchmarks (AC3, AC6)
// ============================================================================

/// Benchmark: 60fps sustained over 100+ frames
///
/// **AC6 Target: Frame timing < 16.67ms per frame for 60fps**
///
/// This benchmark validates that we can sustain 60fps by measuring:
/// 1. Frame preparation time (clear + draw + convert)
/// 2. Buffer swap time
/// 3. Total frame cycle time
///
/// The benchmark simulates a realistic animation with:
/// - Double-buffered rendering
/// - Frame preparation (clear, draw shape, convert to unicode)
/// - Buffer swap
fn bench_60fps_sustained_100_frames(c: &mut Criterion) {
    use std::time::Duration;

    let mut group = c.benchmark_group("60fps_sustained");
    group.measurement_time(Duration::from_secs(15));

    // Simulate 100 frames of animation at 60fps
    // Each frame: clear back buffer, draw moving object, convert to unicode, swap
    group.bench_function("100_frames_80x24", |b| {
        let mut buffer = FrameBuffer::new(80, 24);

        b.iter(|| {
            for frame in 0..100_u32 {
                // Clear back buffer
                buffer.get_back_buffer().clear();

                // Draw animated object (bouncing ball simulation)
                let ball_x = ((frame * 2) % 156) as usize + 2; // 2-158 range
                let ball_y = ((frame * 3) % 92) as usize + 2; // 2-94 range

                // Draw 4x4 ball
                for dy in 0..4 {
                    for dx in 0..4 {
                        let _ = buffer.get_back_buffer().set_dot(ball_x + dx, ball_y + dy);
                    }
                }

                // Convert to unicode (rendering step)
                let chars = buffer.get_back_buffer().to_unicode_grid();
                black_box(&chars);

                // Swap buffers (present frame)
                buffer.swap_buffers();
            }
            black_box(&buffer);
        });
    });

    // Larger terminal size
    group.bench_function("100_frames_200x50", |b| {
        let mut buffer = FrameBuffer::new(200, 50);

        b.iter(|| {
            for frame in 0..100_u32 {
                buffer.get_back_buffer().clear();

                let ball_x = ((frame * 2) % 396) as usize + 2;
                let ball_y = ((frame * 3) % 196) as usize + 2;

                for dy in 0..8 {
                    for dx in 0..8 {
                        let _ = buffer.get_back_buffer().set_dot(ball_x + dx, ball_y + dy);
                    }
                }

                let chars = buffer.get_back_buffer().to_unicode_grid();
                black_box(&chars);

                buffer.swap_buffers();
            }
            black_box(&buffer);
        });
    });

    group.finish();
}

/// Benchmark: Single frame preparation time
///
/// Validates that a single frame can be prepared in < 16.67ms
fn bench_frame_preparation_time(c: &mut Criterion) {
    let mut group = c.benchmark_group("frame_preparation");

    // 80x24 standard terminal
    group.bench_function("single_frame_80x24", |b| {
        let mut buffer = FrameBuffer::new(80, 24);

        b.iter(|| {
            // Clear
            buffer.get_back_buffer().clear();

            // Draw complex scene (multiple shapes)
            for i in 0..10 {
                let x = (i * 15) % 156;
                let y = (i * 9) % 92;
                for dy in 0..4 {
                    for dx in 0..4 {
                        let _ = buffer.get_back_buffer().set_dot(x + dx, y + dy);
                    }
                }
            }

            // Convert to unicode
            let chars = buffer.get_back_buffer().to_unicode_grid();
            black_box(&chars);

            // Swap
            buffer.swap_buffers();
            black_box(&buffer);
        });
    });

    // 200x50 large terminal
    group.bench_function("single_frame_200x50", |b| {
        let mut buffer = FrameBuffer::new(200, 50);

        b.iter(|| {
            buffer.get_back_buffer().clear();

            for i in 0..20 {
                let x = (i * 19) % 396;
                let y = (i * 9) % 196;
                for dy in 0..8 {
                    for dx in 0..8 {
                        let _ = buffer.get_back_buffer().set_dot(x + dx, y + dy);
                    }
                }
            }

            let chars = buffer.get_back_buffer().to_unicode_grid();
            black_box(&chars);

            buffer.swap_buffers();
            black_box(&buffer);
        });
    });

    group.finish();
}

/// Benchmark: Verify 60fps is achievable (computational overhead only)
///
/// This measures pure computational time excluding any sleep/sync.
/// Target: Total time for 100 frames should be < 1667ms (16.67ms * 100)
fn bench_60fps_computational_budget(c: &mut Criterion) {
    use std::time::Duration;

    let mut group = c.benchmark_group("60fps_budget");
    group.measurement_time(Duration::from_secs(10));

    group.bench_function("100_frames_compute_only_80x24", |b| {
        let mut buffer = FrameBuffer::new(80, 24);
        let renderer = DifferentialRenderer::new();
        let mut prev_grid = BrailleGrid::new(80, 24).unwrap();

        b.iter(|| {
            for frame in 0..100_u32 {
                // Clear and draw
                buffer.get_back_buffer().clear();
                let ball_x = ((frame * 2) % 156) as usize + 2;
                let ball_y = ((frame * 3) % 92) as usize + 2;
                for dy in 0..4 {
                    for dx in 0..4 {
                        let _ = buffer.get_back_buffer().set_dot(ball_x + dx, ball_y + dy);
                    }
                }

                // Differential check (simulating optimized rendering)
                let changed = renderer.count_changed_cells(buffer.get_back_buffer(), &prev_grid);
                black_box(changed);

                // Convert only changed regions (optimization benefit)
                let chars = buffer.get_back_buffer().to_unicode_grid();
                black_box(&chars);

                // Update previous frame reference
                prev_grid = buffer.get_back_buffer().clone();

                // Swap
                buffer.swap_buffers();
            }
        });
    });

    group.finish();
}

criterion_group!(
    benches,
    bench_frame_buffer_creation_80x24,
    bench_frame_buffer_creation_200x50,
    bench_swap_buffers_80x24,
    bench_swap_buffers_200x50,
    bench_get_back_buffer,
    bench_full_frame_cycle,
    // Story 6.2 benchmarks
    bench_frame_timer_creation,
    bench_frame_timer_actual_fps,
    bench_frame_timer_frame_time,
    bench_frame_timer_reset,
    bench_frame_timer_overhead,
    // Story 6.5 benchmarks
    bench_differential_renderer_creation,
    bench_differential_count_changes,
    bench_differential_no_changes,
    bench_differential_all_changes,
    bench_differential_moving_object,
    bench_differential_io_reduction_verification,
    // Story 7.2 benchmarks (AC3, AC6)
    bench_60fps_sustained_100_frames,
    bench_frame_preparation_time,
    bench_60fps_computational_budget
);
criterion_main!(benches);